Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bdb5991e8 | ||
|
|
89aaf8d79e | ||
|
|
0022429541 | ||
|
|
372f12dbca | ||
|
|
79a9011212 | ||
|
|
8bf70c98e8 | ||
|
|
e764078aaf | ||
|
|
7969859955 | ||
|
|
263e16b70d | ||
|
|
acf21c69c2 | ||
|
|
efd74c1693 | ||
|
|
e181aa09bd | ||
|
|
2eacbc2e33 | ||
|
|
8c535b1cc2 | ||
|
|
3fa456a063 | ||
|
|
1ddaff0690 | ||
|
|
fce6821f84 | ||
|
|
582b190698 | ||
|
|
289b5a5a1d | ||
|
|
0e48befbc7 | ||
|
|
ece1b654c7 | ||
|
|
1af625f5c3 | ||
|
|
14f59a3d28 | ||
|
|
ae961c1cd3 | ||
|
|
3d504da94c | ||
|
|
48e18ba67d | ||
|
|
66db14d0c5 | ||
|
|
e5b19956a2 | ||
|
|
4533b55da0 | ||
|
|
65fddfcfa2 | ||
|
|
422cde4708 | ||
|
|
0ac3321c41 | ||
|
|
45d4aa6eb2 | ||
|
|
529e80242f | ||
|
|
f5ab1e81be | ||
|
|
a244bee184 | ||
|
|
efbec1006f | ||
|
|
58880a4e07 | ||
|
|
604ac32028 | ||
|
|
c9d599a371 | ||
|
|
6d5420fab2 | ||
|
|
602aa522d6 | ||
|
|
3da49f4b24 | ||
|
|
ca3cd4db30 | ||
|
|
e54aaac181 | ||
|
|
967b464779 | ||
|
|
a8c55148af | ||
|
|
30918eefaa | ||
|
|
30e1fb31d8 | ||
|
|
bb5fd2bef9 | ||
|
|
44347e40eb | ||
|
|
c5a722bd1e | ||
|
|
1b5c8fc4a9 | ||
|
|
746f20158e | ||
|
|
d28524e8c0 | ||
|
|
e788e16898 | ||
|
|
f66d9c52ee | ||
|
|
99fe175ebf | ||
|
|
931b02c9e4 | ||
|
|
148b94959d | ||
|
|
da2ab9fb17 | ||
|
|
8b902350ad | ||
|
|
3764ea9c0b | ||
|
|
299b5f5224 | ||
|
|
af50e6c8ab | ||
|
|
810d3118b3 | ||
|
|
b832dd68b4 | ||
|
|
d3f722d077 | ||
|
|
71344a1f8d | ||
|
|
307268fbea |
@@ -32,3 +32,7 @@ Watchdog that restarted any container docker marked `unhealthy` (only `backend`
|
||||
and `python` define healthchecks). It mounts the docker socket, which is
|
||||
effectively root on the host. To bring it back, layer
|
||||
`docker-compose.autoheal.yml` the same way as above.
|
||||
|
||||
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
|
||||
labelled `autoheal=true` (nginx). This copy is the old `all` variant, kept for
|
||||
reference.
|
||||
|
||||
@@ -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
|
||||
+165
-25
@@ -9,24 +9,21 @@
|
||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||
# variables inside that container. nginx, backend, db, icecast2,
|
||||
# certbot and gitea all do this.
|
||||
# The `python` service deliberately does neither wholesale — it uses an
|
||||
# explicit `environment:` allow-list, so it never sees the database password
|
||||
# or any API key other than the two it uses (TFL_APP_KEY, CLAUDE_API_KEY).
|
||||
# The `python` and `jobs` services deliberately do neither wholesale — each
|
||||
# uses an explicit `environment:` allow-list, so neither sees the site's
|
||||
# database password, the JWT secret, or any key it does not use.
|
||||
#
|
||||
# HOW TO USE
|
||||
# cp .env.example .env then fill in every value.
|
||||
# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in
|
||||
# either direction — see that script's header before editing on both hosts).
|
||||
# On the Pi, keys and settings can also be changed from the admin panel's
|
||||
# Environment tab, which rewrites this file in place (previous version kept
|
||||
# as .env.bak) and restarts what reads the change. See "Editing from the
|
||||
# admin panel" in DEPLOYMENT.md.
|
||||
# On the host, edit .env in place. After changing a value, recreate the
|
||||
# services that read it:
|
||||
# docker compose up -d <service>.
|
||||
#
|
||||
# ADDING A VARIABLE
|
||||
# Add it to backend/services/env_registry.json as well. That file decides
|
||||
# whether the admin panel shows it, whether it is editable there, and which
|
||||
# services are restarted when it changes; a backend test fails if the two
|
||||
# lists differ.
|
||||
# Add it to .env.dev as well, with a dummy value, so the dev stack keeps
|
||||
# starting. If the python or jobs service reads it, add it to that service's
|
||||
# `environment:` list in docker-compose.yml too, or the container never
|
||||
# receives it.
|
||||
#
|
||||
# CAUTION: an unset variable does not fail loudly. envsubst renders it as an
|
||||
# empty string, which for a password field means "no password". After editing,
|
||||
@@ -37,15 +34,24 @@
|
||||
# =============================================================================
|
||||
|
||||
# --- Postgres ----------------------------------------------------------------
|
||||
# One instance, two databases: POSTGRES_DB for the Go backend, POSTGRES_GITEA_DB
|
||||
# for Gitea. Only POSTGRES_DB is auto-created on first init; the Gitea one must
|
||||
# be created by hand on a fresh volume.
|
||||
# One instance, four databases: POSTGRES_DB for the Go backend,
|
||||
# POSTGRES_GITEA_DB for Gitea, POSTGRES_JOBS_DB for the job tracker and
|
||||
# POSTGRES_TRACKER_DB for the activity tracker (each of the last two with its
|
||||
# own role). Only POSTGRES_DB is auto-created on first init; the others must
|
||||
# be created by hand on a fresh volume (the job-tracker and ccp READMEs have
|
||||
# the commands).
|
||||
# POSTGRES_HOST doubles as the db container's name.
|
||||
POSTGRES_USER=
|
||||
POSTGRES_PASSWORD=
|
||||
POSTGRES_DB=
|
||||
POSTGRES_PORT=5432
|
||||
POSTGRES_HOST=db
|
||||
POSTGRES_JOBS_DB=jobs
|
||||
POSTGRES_JOBS_USER=jobs
|
||||
POSTGRES_JOBS_PASSWORD=
|
||||
POSTGRES_TRACKER_DB=tracker
|
||||
POSTGRES_TRACKER_USER=tracker
|
||||
POSTGRES_TRACKER_PASSWORD=
|
||||
|
||||
# --- Gitea -------------------------------------------------------------------
|
||||
# GITEA_HOST is the container name AND the nginx upstream host.
|
||||
@@ -58,6 +64,10 @@ GITEA_INTERNAL_TOKEN=
|
||||
GITEA_LFS_JWT_SECRET=
|
||||
GITEA_OAUTH2_JWT_SECRET=
|
||||
POSTGRES_GITEA_DB=gitea
|
||||
# The host's Tailscale MagicDNS name (e.g. stpvm.tailf20278.ts.net), shown in
|
||||
# Gitea's SSH clone URLs. Not the public domain: 2222 is reachable only over
|
||||
# the tailnet. Becomes Gitea's SSH_DOMAIN and DOMAIN. Blank means localhost.
|
||||
GITEA_SSH_DOMAIN=
|
||||
|
||||
# --- Gitea Actions runner ----------------------------------------------------
|
||||
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
|
||||
@@ -68,7 +78,7 @@ GITEA_RUNNER_HOST=
|
||||
GITEA_RUNNER_NAME=pi-runner
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
|
||||
# --- Email ingest (backend) --------------------------------------------------
|
||||
# --- Email ingest (job tracker) -----------------------------------------------
|
||||
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
|
||||
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
|
||||
# so imap+app-password only works with non-Microsoft providers like Gmail).
|
||||
@@ -77,11 +87,12 @@ GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||
# (default tenant = "consumers"); add a delegated Mail.Read permission with
|
||||
# admin/user consent, and create a client secret. Redirect URI type "Web",
|
||||
# value must live behind the site's real HTTPS origin, e.g.
|
||||
# https://<YOUR_DOMAIN>/email/callback (callback route already exists in the
|
||||
# backend). Backend code exchanges a code there. TenantID must be "consumers"
|
||||
# for a personal outlook.com account.
|
||||
# The first sync prints an authorisation URL into the container log; visit it,
|
||||
# consent, and the refresh token is persisted to backend/token/msgraph_token.json.
|
||||
# https://<YOUR_DOMAIN>/jobs/api/email/callback (served by the job tracker,
|
||||
# which exchanges the code there). TenantID must be "consumers" for a personal
|
||||
# outlook.com account.
|
||||
# The tracker's Settings page (/jobs/settings) shows the authorisation link
|
||||
# until you sign in; the refresh token is persisted to
|
||||
# jobs-data/msgraph_token.json.
|
||||
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
|
||||
EMAIL_BACKEND=
|
||||
MSGRAPH_CLIENT_ID=
|
||||
@@ -97,6 +108,23 @@ IMAP_PASSWORD=
|
||||
EMAIL_SYNC_INTERVAL=
|
||||
EMAIL_SYNC_ENABLED=
|
||||
|
||||
# --- Job leads (job tracker) --------------------------------------------------
|
||||
# The lead fetcher polls the sources listed on /jobs/leads and files new
|
||||
# postings in the leads inbox. JOB_LEADS_ENABLED=true runs it on a timer;
|
||||
# "Check now" on that page works whether or not it is set. JOB_LEADS_INTERVAL
|
||||
# is a Go duration (default 6h). Scoring uses CLAUDE_API_KEY, above.
|
||||
# The board sources (Greenhouse, Lever, Ashby) need no key. The two search
|
||||
# sources do, both free:
|
||||
# Adzuna: https://developer.adzuna.com/ (an application id and a key)
|
||||
# Reed: https://www.reed.co.uk/developers/jobseeker
|
||||
# A search source whose key is blank reports that on the page; nothing else
|
||||
# is affected.
|
||||
JOB_LEADS_ENABLED=
|
||||
JOB_LEADS_INTERVAL=
|
||||
ADZUNA_APP_ID=
|
||||
ADZUNA_APP_KEY=
|
||||
REED_API_KEY=
|
||||
|
||||
# --- Services that nginx substitutes but no longer runs -----------------------
|
||||
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
|
||||
# compose service uses them today. Harmless if blank.
|
||||
@@ -163,11 +191,29 @@ LIQUIDSOAP_HARBOR_PORT=8001
|
||||
DOMAIN=
|
||||
EMAIL=
|
||||
|
||||
# --- Cloudflare Tunnel -------------------------------------------------------
|
||||
# Token of the remotely managed tunnel the `cloudflared` container runs
|
||||
# (Zero Trust -> Networks -> Tunnels -> your tunnel -> the `--token` value in
|
||||
# the install command). Hostnames and origin settings are configured in the
|
||||
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
|
||||
# the container restarting with an error and the site reachable directly.
|
||||
CLOUDFLARE_TUNNEL_TOKEN=
|
||||
# Cloudflare API token for certbot's DNS-01 challenge (My Profile -> API
|
||||
# Tokens -> Create Token -> "Edit zone DNS", limited to this zone). Set, the
|
||||
# certificate renews without any inbound port, so the router's 80/443
|
||||
# forwards can close. Blank falls back to HTTP-01 on port 80.
|
||||
CLOUDFLARE_DNS_API_TOKEN=
|
||||
|
||||
# --- Third-party API keys (backend) ------------------------------------------
|
||||
# CLAUDE_API_KEY is also passed to the python service, which makes the Claude
|
||||
# calls for the rowing photo reader and the job posting reader; the backend
|
||||
# uses it for the email pipeline.
|
||||
# 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
|
||||
# to apply a change.
|
||||
CLAUDE_MODEL=
|
||||
STEAM_API_KEY=
|
||||
STEAM_ID=
|
||||
|
||||
@@ -180,5 +226,99 @@ SEED_DB=
|
||||
PYTHON_HOST=python
|
||||
PYTHON_PORT=8000
|
||||
|
||||
# --- Job tracker (/jobs/) -----------------------------------------------------
|
||||
# An image built and published by the job-tracker repo's CI. Blank runs
|
||||
# :latest; set a commit sha to pin. Changing it needs
|
||||
# `docker compose pull jobs && docker compose up -d jobs`.
|
||||
JOBS_IMAGE_TAG=
|
||||
|
||||
# --- USACO site (/usaco/) ------------------------------------------------------
|
||||
# An image built and published by the usaco repo's CI. Blank runs :latest; set
|
||||
# a commit sha to pin. Changing it needs
|
||||
# `docker compose pull usaco && docker compose up -d usaco`.
|
||||
USACO_IMAGE_TAG=
|
||||
# The same for its code runner (usaco-runner), which the usaco repo's CI
|
||||
# publishes and rolls alongside it. It takes no other settings: it has no
|
||||
# secrets by design.
|
||||
USACO_RUNNER_IMAGE_TAG=
|
||||
# Gitea access token (repository: read and write on adamf/usaco). The site
|
||||
# clones with it and pushes the admin's edits back.
|
||||
USACO_GIT_TOKEN=
|
||||
# Shared secret of the usaco repo's push webhook in Gitea
|
||||
# (http://usaco:8080/usaco/api/hooks/gitea). Blank turns the hook off and
|
||||
# the site only pulls every 10 minutes. Generate with `openssl rand -hex 32`.
|
||||
USACO_WEBHOOK_SECRET=
|
||||
# Model for the problem explanations (the admin's Explain button), separate
|
||||
# from CLAUDE_MODEL because those are long, considered answers rather than
|
||||
# extraction. Blank means claude-opus-5-5. The key is CLAUDE_API_KEY above;
|
||||
# without it the button is off and the rest of the site works.
|
||||
USACO_CLAUDE_MODEL=
|
||||
# Monthly cap on the USACO site's estimated Claude spend, in dollars (e.g.
|
||||
# 20). Once a calendar month (UTC) reaches it, new Explain/review/concept/
|
||||
# evaluate jobs are refused until the 1st. Blank: no cap; the spend is still
|
||||
# shown on the site's stats page to the admin.
|
||||
USACO_CLAUDE_MONTHLY_BUDGET=
|
||||
# Recording reviews (the admin uploads themselves explaining a solution).
|
||||
# Claude cannot take audio, so this OpenAI key transcribes it (whisper-1,
|
||||
# about $0.006 a minute). Blank turns reviews off.
|
||||
USACO_OPENAI_API_KEY=
|
||||
# Optional: keep the recordings for playback in a PRIVATE Garage bucket,
|
||||
# never `uploads` (that one is served publicly at /uploads/). Its own key,
|
||||
# same shapes as S3_ACCESS_KEY_ID / S3_SECRET_ACCESS_KEY above. With the
|
||||
# key blank the recordings are thrown away once transcribed. One-off setup:
|
||||
# docker compose exec -T garage /garage bucket create usaco-audio
|
||||
# docker compose exec -T garage /garage key import -n usaco-site --yes "$USACO_S3_ACCESS_KEY_ID" "$USACO_S3_SECRET_ACCESS_KEY"
|
||||
# docker compose exec -T garage /garage bucket allow --read --write usaco-audio --key "$USACO_S3_ACCESS_KEY_ID"
|
||||
USACO_S3_ACCESS_KEY_ID=
|
||||
USACO_S3_SECRET_ACCESS_KEY=
|
||||
|
||||
# --- Activity tracker (/tracker/) --------------------------------------------
|
||||
# An image built and published by the ccp repo's CI. Blank runs :latest; set a
|
||||
# commit sha to pin. Changing it needs
|
||||
# `docker compose pull activity-tracker && docker compose up -d activity-tracker`.
|
||||
ACTIVITY_TRACKER_IMAGE_TAG=
|
||||
# IANA timezone that decides where a "day" starts in daily summaries. Blank is UTC.
|
||||
TRACKER_TZ=Europe/London
|
||||
|
||||
# --- Receipt printer (/receipt/) ---------------------------------------------
|
||||
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
|
||||
# which reaches the printer over the home LAN, and 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=
|
||||
|
||||
# --- Garage object store (public /uploads/) -----------------------------------
|
||||
# See garage/garage.toml and DEPLOYMENT.md ("Garage"). Everything here is
|
||||
# optional for the site to run: with S3_ENDPOINT blank the backend keeps
|
||||
# writing uploads to the `uploads` volume exactly as before.
|
||||
#
|
||||
# Garage's own secrets, passed to the garage and garage-webui containers.
|
||||
# Generate each with `openssl rand -hex 32`. The RPC secret must never change
|
||||
# once the node has data; the admin token unlocks garage-webui's whole API.
|
||||
GARAGE_RPC_SECRET=
|
||||
GARAGE_ADMIN_TOKEN=
|
||||
# The backend's S3 access, imported into Garage by garage/bootstrap.sh.
|
||||
# Garage only accepts this shape:
|
||||
# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12))
|
||||
# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32)
|
||||
S3_ACCESS_KEY_ID=
|
||||
S3_SECRET_ACCESS_KEY=
|
||||
# Blank keeps uploads on disk. Set to http://garage:3900 (after running
|
||||
# garage/bootstrap.sh) to store new public uploads in the bucket; recreate the
|
||||
# backend after changing it. If a write to Garage fails the backend logs it and
|
||||
# writes to disk instead, and nginx serves the file from there.
|
||||
S3_ENDPOINT=
|
||||
# Optional; these defaults match garage.toml and bootstrap.sh.
|
||||
S3_REGION=garage
|
||||
S3_BUCKET=uploads
|
||||
# Optional, bootstrap.sh only: the node's capacity in the layout. With one node
|
||||
# it only has to be non-zero; it is not a quota. Default 20G.
|
||||
GARAGE_CAPACITY=
|
||||
|
||||
@@ -1,31 +1,177 @@
|
||||
name: Deploy with Docker Compose
|
||||
# =============================================================================
|
||||
# deploy.yaml — test every push; deploy pushes to main that pass.
|
||||
#
|
||||
# TWO JOBS
|
||||
# test runs on every push, to any branch: `go vet` + `go test` for the
|
||||
# backend and pytest for the Python service. These are the same
|
||||
# checks as `make check-backend` and `make check-python`.
|
||||
# deploy runs only for refs/heads/main, and only if `test` passed
|
||||
# (`needs: test`). Before this gate existed every push to main went
|
||||
# straight to the live site.
|
||||
#
|
||||
# WHERE THIS RUNS, AND WHAT THAT RULES OUT
|
||||
# A self-hosted act_runner on the Pi itself, in HOST mode (see
|
||||
# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job
|
||||
# container. So:
|
||||
# - No host toolchains are assumed. The Pi is known to have git and docker
|
||||
# and nothing else; Go and Python run inside `docker run` containers
|
||||
# pinned to the same base images as backend/Dockerfile (golang:1.26) and
|
||||
# python/Dockerfile (python:3.12-slim). Bump them together.
|
||||
# - No `actions/checkout`. It is a JavaScript action and would need Node on
|
||||
# the host. The source is fetched with plain git instead, from the same
|
||||
# local Gitea SSH remote the deploy step has always used.
|
||||
#
|
||||
# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS
|
||||
# The site runs out of /home/adamf/deploy/web_server. The test job never
|
||||
# goes near it: it fetches into a separate bare cache repo and exports the
|
||||
# pushed commit to a scratch directory. Only the deploy job, after `test`
|
||||
# is green, does the `git reset --hard` there.
|
||||
#
|
||||
# NOT TESTED HERE: THE VUE BUILD
|
||||
# Deliberately skipped. `docker compose up --build` in the deploy job
|
||||
# already runs the full frontend build (npm ci + vite) while building the
|
||||
# vue image, and a failed image build aborts `up` BEFORE any container is
|
||||
# replaced, so the old site keeps serving. Building it a second time here
|
||||
# would cost the Pi several minutes per push to learn nothing new. The same
|
||||
# reasoning does not hold for Go and Python: their images build fine with
|
||||
# failing tests, which is exactly why those are gated here.
|
||||
#
|
||||
# NO pull_request TRIGGER
|
||||
# `push` with no branch filter already covers every branch, including the
|
||||
# head branch of any PR in this repo, so adding pull_request would run the
|
||||
# suite twice per push on a machine with little CPU to spare.
|
||||
# =============================================================================
|
||||
name: Test and deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: self-hosted
|
||||
env:
|
||||
# The commit and ref this push delivered. Passed through env rather
|
||||
# than interpolated into the scripts so a branch name can never be
|
||||
# parsed as shell.
|
||||
SHA: ${{ github.sha }}
|
||||
REF: ${{ github.ref }}
|
||||
REMOTE: ssh://git@localhost:2222/adamf/web_server.git
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
# Bare repo kept between runs so each fetch is incremental (the
|
||||
# history is ~140MB; a fresh clone per push would be slow on the
|
||||
# Pi's SD card). Lives outside the deploy directory on purpose.
|
||||
CACHE: /home/adamf/.cache/web_server-ci/repo.git
|
||||
# This run's source tree, exported from the cache and removed in
|
||||
# the last step. Keyed by commit so two runs cannot share a tree.
|
||||
SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }}
|
||||
steps:
|
||||
- name: Export the pushed commit to a scratch directory
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
mkdir -p "$(dirname "$CACHE")"
|
||||
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
|
||||
# Fetch the pushed ref, then export the exact pushed commit.
|
||||
# Using $SHA rather than FETCH_HEAD means that if the branch
|
||||
# has moved on since this run was queued we still test the
|
||||
# commit this run is about, not a newer one.
|
||||
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
|
||||
rm -rf "$SRC"
|
||||
mkdir -p "$SRC"
|
||||
# `git archive` gives a clean tree of tracked files only: no
|
||||
# .git, and nothing left over from an earlier run.
|
||||
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
||||
# Do not rely on the shell having pipefail: if the archive
|
||||
# half failed, make sure that is noticed here.
|
||||
test -f "$SRC/backend/go.mod"
|
||||
test -f "$SRC/python/requirements-dev.txt"
|
||||
echo "Exported $SHA ($REF) to $SRC"
|
||||
|
||||
# The whole repo is mounted read-only. Tests write only to
|
||||
# t.TempDir(), and a read-only mount means the container (root)
|
||||
# cannot leave root-owned files in $SRC that the clean-up step,
|
||||
# running as the runner user, could not delete.
|
||||
#
|
||||
# The two named volumes are the Go module cache and build cache.
|
||||
# Without them every run would re-download every dependency and
|
||||
# recompile gorm, gin and gqlgen from scratch — minutes on a Pi.
|
||||
# They survive `docker image prune` and the weekly maintenance
|
||||
# job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild`
|
||||
# resets them if they ever go bad.
|
||||
- name: Backend - go vet and go test
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/backend \
|
||||
-v web_server_ci_gomod:/go/pkg/mod \
|
||||
-v web_server_ci_gobuild:/root/.cache/go-build \
|
||||
golang:1.26 \
|
||||
sh -c 'go vet ./... && go test ./...'
|
||||
|
||||
# requirements-dev.txt pulls in requirements.txt plus pytest. The
|
||||
# install is repeated every run (the container is thrown away) but
|
||||
# the pip cache volume means it is unpacking cached wheels, not
|
||||
# downloading. Read-only source for the same reason as above, so
|
||||
# bytecode and the pytest cache are switched off rather than left
|
||||
# to fail noisily.
|
||||
- name: Python - pytest
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
docker run --rm \
|
||||
-v "$SRC":/src:ro \
|
||||
-w /src/python \
|
||||
-v web_server_ci_pip:/root/.cache/pip \
|
||||
-e PYTHONDONTWRITEBYTECODE=1 \
|
||||
python:3.12-slim \
|
||||
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
|
||||
|
||||
# always(): a failed test must not leave a source tree behind per
|
||||
# push. The cache repo is kept; only this run's export goes.
|
||||
- name: Remove the scratch directory
|
||||
if: always()
|
||||
shell: bash
|
||||
run: rm -rf "$SRC"
|
||||
|
||||
deploy:
|
||||
# Both conditions matter: `needs` makes a red test job skip this one,
|
||||
# and the `if` keeps pushes to other branches from deploying at all.
|
||||
needs: test
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: self-hosted
|
||||
steps:
|
||||
- name: Pull changes
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||
SHA: ${{ github.sha }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -eu
|
||||
git config --global --add safe.directory /home/adamf/deploy/web_server
|
||||
git fetch ssh://git@localhost:2222/adamf/web_server.git main
|
||||
# Deploy only the commit the test job just passed. If main
|
||||
# has moved on since this run started, FETCH_HEAD is a newer
|
||||
# commit that THIS run never tested — stop, and let that
|
||||
# commit's own run test and deploy it. Failing (rather than
|
||||
# resetting to $SHA anyway) also means re-running an old run
|
||||
# can never roll the site back to an old commit.
|
||||
if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then
|
||||
echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA."
|
||||
echo "Not deploying: the run for the newer commit will."
|
||||
exit 1
|
||||
fi
|
||||
git reset --hard FETCH_HEAD
|
||||
|
||||
- name: Run docker compose up
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
COMPOSE_BAKE: "false"
|
||||
# The lock is shared with env-apply/apply.py, so a deploy and a
|
||||
# .env change made from the admin panel cannot run compose at
|
||||
# the same time.
|
||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
||||
# The lock is shared with maintenance.yaml, so a deploy and the
|
||||
# weekly rebuild cannot run compose at the same time.
|
||||
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker resources
|
||||
run: docker image prune -f
|
||||
|
||||
@@ -2,7 +2,10 @@ name: Weekly Maintenance
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 1 * * 0"
|
||||
# 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and
|
||||
# every container, so it runs when nobody is likely to be mid-edit;
|
||||
# 01:00 kept catching late-night SilverBullet saves.
|
||||
- cron: "0 5 * * 0"
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
@@ -21,17 +24,22 @@ jobs:
|
||||
- name: Autoremove obsolete packages
|
||||
run: sudo apt-get -y autoremove --purge
|
||||
|
||||
# Both compose steps below take .compose.lock, the same flock
|
||||
# deploy.yaml holds while it runs compose. Without it this weekly
|
||||
# job could recreate containers while a deploy is mid-build, and
|
||||
# two `compose up`s racing over the same project can each recreate
|
||||
# a container the other just started. flock blocks until the other
|
||||
# holder finishes, so the job waits rather than fails. The lock is
|
||||
# taken per step, not across both: nothing needs pull and up to be
|
||||
# atomic, and holding it for less time keeps a deploy from waiting
|
||||
# behind a long pull.
|
||||
- name: Pull latest base images
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose pull
|
||||
run: flock .compose.lock docker compose pull
|
||||
|
||||
- name: Rebuild and restart containers
|
||||
working-directory: /home/adamf/deploy/web_server
|
||||
env:
|
||||
DOCKER_API_VERSION: "1.41"
|
||||
run: docker compose up -d --build --remove-orphans
|
||||
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||
|
||||
- name: Prune unused Docker images
|
||||
run: docker image prune -af
|
||||
|
||||
@@ -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
|
||||
+12
-9
@@ -1,14 +1,16 @@
|
||||
icecast2/fallback_music/*
|
||||
.claude/
|
||||
!icecast2/fallback_music/.gitkeep
|
||||
certbot/conf
|
||||
certbot/www
|
||||
backend/token/
|
||||
jobs-data/
|
||||
usaco-data/
|
||||
.env
|
||||
.env.bak
|
||||
|
||||
# Admin panel -> host hand-off (request and status files, holds secrets)
|
||||
env-apply/run/*
|
||||
!env-apply/run/.gitkeep
|
||||
# flock taken by the deploy and maintenance workflows around docker compose
|
||||
.compose.lock
|
||||
|
||||
gitea/data/*
|
||||
gitea/config/app.ini
|
||||
@@ -18,15 +20,13 @@ gitea-runner/.runner
|
||||
gitea-runner/act_runner
|
||||
gitea-runner/nohup.out
|
||||
|
||||
# Rust build artifacts
|
||||
**/target/
|
||||
|
||||
# Python bytecode
|
||||
__pycache__/
|
||||
*.pyc
|
||||
.pytest_cache/
|
||||
|
||||
# Generated WASM output
|
||||
vue/src/wasm/
|
||||
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
|
||||
/.venv/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
@@ -69,7 +69,6 @@ __screenshots__/
|
||||
|
||||
.deploy
|
||||
*.xcf
|
||||
sync-secrets.sh
|
||||
|
||||
# Local-only outstanding-work notes, deliberately not published
|
||||
TODO-NEXT.md
|
||||
@@ -77,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/
|
||||
|
||||
@@ -4,13 +4,22 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## Build & Run Commands
|
||||
|
||||
### Check everything
|
||||
|
||||
```
|
||||
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. 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)
|
||||
|
||||
@@ -24,7 +33,7 @@ docker compose up --build
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`.
|
||||
|
||||
### Frontend build
|
||||
|
||||
@@ -32,6 +41,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`
|
||||
cd vue && npm run build
|
||||
```
|
||||
|
||||
`npm run build` is a plain `vite build`.
|
||||
|
||||
### Regenerate GraphQL (after editing schema files)
|
||||
|
||||
```
|
||||
@@ -42,46 +53,54 @@ This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver
|
||||
|
||||
## Architecture
|
||||
|
||||
Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
||||
Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubuntu VM; formerly a Raspberry Pi).
|
||||
|
||||
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
|
||||
|
||||
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
|
||||
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. Two routes are internal — `/internal/rowing/read` (the Claude call behind `POST /api/rowing`) and `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`): the Go backend calls them directly over the Docker network and nginx 404s `/py/internal/`.
|
||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and nginx 404s `/py/internal/`. The model is one setting, shared with the job tracker, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
|
||||
|
||||
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min).
|
||||
**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. `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.
|
||||
|
||||
## Backend Structure
|
||||
|
||||
- `main.go` — entry point: wires up DB, services, router
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, EmailSync, etc. Passed to all handlers
|
||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, Notes, etc. Passed to all handlers
|
||||
- `handlers/handle_*.go` — REST handlers grouped by domain
|
||||
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
|
||||
- `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)
|
||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding
|
||||
- `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
|
||||
|
||||
## Frontend Structure
|
||||
|
||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData
|
||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
|
||||
- `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, 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`.
|
||||
|
||||
## Key Patterns
|
||||
|
||||
- **GraphQL models vs GORM models**: `gqlgen.yml` maps GraphQL types directly to GORM models in `backend/models`. The `graph/model/` package has only generated input/payload types.
|
||||
- **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. There is no token revocation — logout only clears cookies.
|
||||
- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`.
|
||||
- **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.
|
||||
- **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token because cookies do not travel from other origins. The token is generated on the admin panel and stored hashed in `backend/token/job_capture_token.json`; there is no env var for it. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`.
|
||||
- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it), with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`.
|
||||
- **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service or the job tracker reads must also be added to the `python` or `jobs` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
|
||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||
|
||||
## Further documentation
|
||||
|
||||
@@ -98,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.
|
||||
|
||||
+386
-138
@@ -4,15 +4,19 @@ How this site is put together and how to operate it. Application code is
|
||||
documented in `CLAUDE.md` and `README.md`; this file covers infrastructure only
|
||||
— compose, nginx, TLS, the runner, and the runbook.
|
||||
|
||||
Everything runs on a single Raspberry Pi, as Docker containers on one bridge
|
||||
Everything runs on a single host, `stpvm` (an x86-64 Ubuntu VM on Proxmox,
|
||||
reached over Tailscale as `stpvm.tailf20278.ts.net`; until 2026-10-15 it was
|
||||
the Raspberry Pi `stppi`), as Docker containers on one bridge
|
||||
network, behind one nginx.
|
||||
|
||||
---
|
||||
|
||||
## 1. Service topology
|
||||
|
||||
Only three things are reachable from outside the Pi: nginx on 80/443, Gitea on
|
||||
3000/2222, and the liquidsoap harbor port. Everything else is internal.
|
||||
Only three things are reachable from outside the host: nginx on 80/443, Gitea on
|
||||
3000/2222, and the liquidsoap harbor port. Everything else is internal. Web
|
||||
traffic can also come in through the Cloudflare tunnel (`cloudflared`), which
|
||||
dials out and publishes no port; see "Cloudflare Tunnel" in §3.
|
||||
|
||||
```
|
||||
internet
|
||||
@@ -47,19 +51,28 @@ backend icecast2 gitea sb sb-pub python | |
|
||||
|
||||
### Who listens where
|
||||
|
||||
| Service | Container name | Internal port | Public route | Published to host |
|
||||
|---|---|---|---|---|
|
||||
| nginx | `nginx` | 80, 443 | — | **80, 443** |
|
||||
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
|
||||
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
||||
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
|
||||
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
|
||||
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
||||
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
|
||||
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
|
||||
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
||||
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
||||
| certbot | `certbot` | — | — | no |
|
||||
| Service | Container name | Internal port | Public route | Published to host |
|
||||
| --------------------------------------------- | ----------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------- | -------------------- |
|
||||
| nginx | `nginx` | 80, 443 | — | **80, 443** |
|
||||
| backend (Go) | `${BACKEND_HOST}` | `${BACKEND_PORT}` (8080) | `${BACKEND_ENDPOINT}` = `/api/` | no |
|
||||
| db (Postgres 16) | `${POSTGRES_HOST}` | 5432 | none | no |
|
||||
| silverbullet (editor) | `${SILVERBULLET_HOST}` | `${SILVERBULLET_PORT}` | `/sb/` (admin-gated) | no |
|
||||
| silverbullet-public (notes site) | `${SILVERBULLET_PUBLIC_HOST}` | `${SILVERBULLET_PUBLIC_PORT}` | `/notes/` (**public**, read-only) | no |
|
||||
| silverbullet-git | n/a | n/a | none (timer loop) | no |
|
||||
| python (FastAPI) | `${PYTHON_HOST}` | `${PYTHON_PORT}` | `/py/`, docs at `/py/docs` | no |
|
||||
| jobs (job tracker, published image) | `jobs` | 8080 | `/jobs/` (admin-gated by nginx `auth_request`; capture API and userscript public, bearer-token) | no |
|
||||
| activity-tracker (published image, adamf/ccp) | `activity-tracker` | 8080 | `/tracker/`, prefix stripped (pages admin-gated by nginx `auth_request`; `/api/v1/` bearer/app-checked) | no |
|
||||
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
|
||||
| gitea | `${GITEA_HOST}` | 3000, 2222 | `/gitea/` | **3000, 2222** |
|
||||
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
|
||||
| certbot | `certbot` | — | — | no |
|
||||
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of nginx, via Cloudflare | no (outbound only) |
|
||||
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by nginx `auth_request`; reads the Docker socket) | no |
|
||||
| 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 |
|
||||
| garage-webui (Garage admin UI) | `garage-webui` | 3909 | `/garage/` (admin-gated by nginx `auth_request`) | no |
|
||||
|
||||
Container names come from `.env`, and nginx builds its upstreams from the same
|
||||
variables. **Renaming a `*_HOST` value renames the container and repoints nginx
|
||||
@@ -77,19 +90,33 @@ in one step — never change one without the other.**
|
||||
- **Per-request DNS.** Upstreams go through `set $upstream_* ...` variables with
|
||||
`resolver 127.0.0.11`, so names resolve per request. nginx boots fine with a
|
||||
backend down (502s until it appears) instead of refusing to start.
|
||||
- **Admin gate.** `/sb/`, `/radio/admin/` and `/uploads/private/` are protected by an `auth_request`
|
||||
subrequest to the backend's `/auth/validate-admin`; a failure redirects to the
|
||||
SPA login. None of these services has any auth of its own at that path.
|
||||
- **Admin gate.** `/sb/`, `/jobs/`, `/tracker/`, `/dozzle/`, `/garage/`, `/radio/admin/`, `/uploads/private/` and
|
||||
Gitea's history views and archives (`…/commit/`, `…/src/commit/`, `…/blame/commit/`, `…/archive/`, `…/compare/`; the
|
||||
branch views stay public) are
|
||||
protected by an `auth_request` subrequest to the backend's `/auth/validate-admin`; a failure
|
||||
redirects to the SPA login. Most of these services have no auth of their own at that path; the
|
||||
job and activity trackers also check the session themselves. Their carve-outs, which a session
|
||||
cookie never reaches, stay public at nginx and are guarded by bearer tokens in the apps:
|
||||
`/jobs/api/capture` and `/jobs/job-capture.user.js`, `/tracker/api/v1/` and `/tracker/tracker.user.js`.
|
||||
- **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
|
||||
file *list*; direct `/.fs/` fetches and server-rendered page URLs still serve
|
||||
file _list_; direct `/.fs/` fetches and server-rendered page URLs still serve
|
||||
them. Adding a folder to `SB_SPACE_IGNORE` on `silverbullet-public` without
|
||||
adding it to the deny regex in both nginx templates publishes it. See the
|
||||
comment above `location /notes/` in `nginx.conf.template`.
|
||||
- **Uploads served directly.** `/uploads/` is an alias onto the shared `uploads`
|
||||
volume with `nosniff`, `Content-Disposition: inline` and a deny-all CSP, so
|
||||
user-supplied files cannot execute anything on our origin.
|
||||
adding it to the deny regex in `nginx_routes.conf.template` publishes it. See the
|
||||
comment above `location /notes/` in `nginx_routes.conf.template`.
|
||||
- **Uploads: the bucket first, then disk.** `/uploads/<f>` is fetched from
|
||||
Garage's website endpoint and, if Garage has no such file or is down, from
|
||||
the shared `uploads` volume (`@uploads_disk`). Both paths add `nosniff`,
|
||||
`Content-Disposition: inline` and a deny-all CSP, so user-supplied files
|
||||
cannot execute anything on our origin. The bucket is the source of truth;
|
||||
a Garage outage only affects files that exist nowhere else. See "Garage"
|
||||
in §7.
|
||||
- **Rate limits** — see §6.
|
||||
|
||||
---
|
||||
@@ -104,32 +131,61 @@ docker compose up --build
|
||||
|
||||
1. `vue` builds the SPA into the `vue_dist` volume and **exits 0** (expected).
|
||||
2. `nginx` starts, runs `nginx/entrypoint.sh`, which:
|
||||
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
|
||||
- renders `nginx.conf.template` if the cert is there, else
|
||||
`nginx_setup.conf.template`;
|
||||
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
|
||||
nginx either way.
|
||||
- is not in `DEV_MODE`, so it looks for `/etc/letsencrypt/live/$DOMAIN/`;
|
||||
- renders `nginx.conf.template` if the cert is there, else
|
||||
`nginx_setup.conf.template`;
|
||||
- polls up to 120s for `index.html` to appear in `vue_dist`, then starts
|
||||
nginx either way.
|
||||
3. `certbot` obtains or confirms the certificate, then loops renewing.
|
||||
4. Everything else comes up in parallel; `depends_on` here is the plain list
|
||||
form, which waits only for *start*, not readiness.
|
||||
form, which waits only for _start_, not readiness.
|
||||
|
||||
On the Pi this is triggered automatically: `.gitea/workflows/deploy.yaml` runs on
|
||||
every push to `main`, fetches over `ssh://git@localhost:2222`, hard-resets the
|
||||
deploy checkout, and runs `docker compose up -d --build --remove-orphans`.
|
||||
On the host this is triggered automatically by `.gitea/workflows/deploy.yaml`,
|
||||
which has two jobs:
|
||||
|
||||
- **`test`** runs on every push to any branch. It exports the pushed commit
|
||||
(never the deploy checkout) and runs the backend's `go vet` + `go test` in
|
||||
`golang:1.26` and the Python tests in `python:3.12-slim`. The Vue build is
|
||||
not repeated here: the image build in the deploy step does it, and a failed
|
||||
build leaves the old containers running.
|
||||
- **`deploy`** runs only on `main`, only after `test` passes, and only if the
|
||||
tested commit is still the tip of `main` (so an older run cannot deploy a
|
||||
newer, untested commit). It fetches over `ssh://git@localhost:2222`,
|
||||
hard-resets the deploy checkout, and runs
|
||||
`docker compose up -d --build --remove-orphans` under the
|
||||
`.compose.lock` flock, shared with the weekly maintenance workflow.
|
||||
|
||||
The test job keeps state on the host outside the deploy checkout: a bare
|
||||
repository cache at `/home/adamf/.cache/web_server-ci/` and three named
|
||||
volumes (`web_server_ci_gomod`, `web_server_ci_gobuild`, `web_server_ci_pip`).
|
||||
The weekly maintenance workflow's `docker image prune -af` removes the two
|
||||
toolchain images, so the first run after it pulls them again; the volumes
|
||||
survive. Maintenance takes the same flock around its compose steps.
|
||||
|
||||
`make check` runs the same checks locally, plus the Vue build and compose
|
||||
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
|
||||
for hot reload, with anonymous-volume masks on `/app/node_modules` and
|
||||
`/app/src/wasm` so the image's installed deps and compiled WASM are not hidden
|
||||
by the bind mount. You need neither `node_modules` nor a Rust toolchain on the
|
||||
host.
|
||||
for hot reload, with an anonymous-volume mask on `/app/node_modules` so the
|
||||
image's installed deps are not hidden by the bind mount. You don't need
|
||||
`node_modules` on the host.
|
||||
- **nginx** — `DEV_MODE=true`, which makes the entrypoint self-sign a
|
||||
`CN=localhost` certificate (once, kept in `certbot/conf`) and render
|
||||
`nginx_dev.conf.template`: `/` proxies to the Vite dev server, both `:80` and
|
||||
@@ -144,7 +200,7 @@ Visit `http://localhost`.
|
||||
|
||||
**`SEED_DB`** makes the Go backend populate the database with test posts, users
|
||||
and messages at startup. It is set only in the dev override and must never be
|
||||
set on the Pi — it would inject fake content into the live site.
|
||||
set on the host — it would inject fake content into the live site.
|
||||
|
||||
Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
|
||||
`/api`, `/gitea` and `/radio` to locally running services.
|
||||
@@ -157,8 +213,7 @@ Frontend-only work can skip Docker: `cd vue && npm run dev`, which proxies
|
||||
|
||||
The production nginx config references
|
||||
`/etc/letsencrypt/live/$DOMAIN/fullchain.pem`, and nginx refuses to start if that
|
||||
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port
|
||||
80. On a brand-new host neither can go first.
|
||||
file is missing. Certbot's HTTP-01 challenge needs a working HTTP server on port 80. On a brand-new host neither can go first.
|
||||
|
||||
`nginx_setup.conf.template` breaks the loop: port 80 only, no TLS directives, no
|
||||
upstreams, nothing that can fail to load. It serves
|
||||
@@ -168,7 +223,7 @@ so a half-configured site is never partially exposed.
|
||||
**First run on a new domain:**
|
||||
|
||||
1. `docker compose up -d`. nginx logs `Certificates NOT found. Using setup nginx
|
||||
config.`
|
||||
config.`
|
||||
2. certbot runs `certbot certonly --webroot` and writes the certificate into
|
||||
`./certbot/conf` (bind-mounted into both containers — that sharing is what
|
||||
makes the whole thing work).
|
||||
@@ -183,6 +238,13 @@ until the cert is inside its 30-day window, so this is well within Let's Encrypt
|
||||
rate limits — it just means the window is checked twice a day. Certs are valid 90
|
||||
days, so renewal lands around day 60.
|
||||
|
||||
**Validation method.** With `CLOUDFLARE_DNS_API_TOKEN` set, certbot proves
|
||||
control of the domain by creating a `_acme-challenge` TXT record through the
|
||||
Cloudflare API (DNS-01), so renewal needs no inbound port at all. That is
|
||||
what lets the router's 80/443 forwards close behind the tunnel. Without the
|
||||
token it uses the webroot (HTTP-01) on port 80, as it always did. Switching
|
||||
either way takes effect at the next renewal; see `certbot/entrypoint.sh`.
|
||||
|
||||
**Caveat worth knowing:** there is no `--deploy-hook`, and the certbot container
|
||||
cannot signal nginx (no docker socket, no shared PID namespace). nginx reads the
|
||||
certificate at startup and holds it in memory, so **a renewed certificate is not
|
||||
@@ -190,6 +252,104 @@ served until nginx is reloaded or restarted.** In practice pushes to `main`
|
||||
recreate nginx often enough to hide this. If the site ever serves an expired
|
||||
cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
|
||||
|
||||
### Cloudflare Tunnel
|
||||
|
||||
The `cloudflared` container holds an outbound connection to Cloudflare and
|
||||
forwards requests for the site's hostnames down it to nginx. It is a
|
||||
_remotely managed_ tunnel: the only thing in this repo is the token
|
||||
(`CLOUDFLARE_TUNNEL_TOKEN` in `.env`); hostnames and
|
||||
origin settings live in the dashboard.
|
||||
|
||||
**Origin: `https://www.<DOMAIN>`, the site's own name.** Cloudflare
|
||||
terminates the visitor's TLS at its edge, and cloudflared opens a second TLS
|
||||
connection to nginx. That is deliberate. Pointed at `http://nginx:80`, the
|
||||
tunnel would hit the HTTP→HTTPS redirect and loop. Going to :443 keeps every
|
||||
redirect, security header and the `X-Forwarded-Proto: https` the backend's
|
||||
Secure cookies depend on, and needs no nginx change.
|
||||
|
||||
The origin is the public name, not `nginx`, because nginx carries `<DOMAIN>`
|
||||
and `www.<DOMAIN>` as network aliases on `app-network` (`docker-compose.yml`).
|
||||
Inside the network those names resolve to the nginx container, so the hop
|
||||
never leaves the host, and cloudflared verifies the Let's Encrypt certificate
|
||||
against a name it covers. `https://nginx` would fail that check and need No
|
||||
TLS Verify. The flip side: **an expired certificate now takes the tunnel down
|
||||
with a 502**, which is why renewal over DNS-01 (step 5) matters.
|
||||
|
||||
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.
|
||||
2. Zero Trust → Networks → Tunnels → Create a tunnel → Cloudflared. Copy the
|
||||
token from the install command (the long string after `--token`).
|
||||
3. Put it in `.env` as `CLOUDFLARE_TUNNEL_TOKEN`, then
|
||||
`docker compose up -d cloudflared`. The tunnel
|
||||
shows as Healthy in the dashboard.
|
||||
4. Add a public hostname per name, each with service `HTTPS` and its own
|
||||
name as the URL, and no other settings:
|
||||
- `www.<DOMAIN>` → `https://www.<DOMAIN>`: the site.
|
||||
- `<DOMAIN>` → `https://<DOMAIN>`: nginx redirects it to www, and it serves Gitea's registry
|
||||
at `/v2/`.
|
||||
Creating each hostname replaces the existing A record for that name with
|
||||
a CNAME to the tunnel. **That is the cutover**: until then the tunnel
|
||||
carries nothing.
|
||||
|
||||
5. Create a Cloudflare API token (My Profile → API Tokens → "Edit zone
|
||||
DNS", this zone only) and set it as `CLOUDFLARE_DNS_API_TOKEN`. certbot
|
||||
then renews over DNS-01 (see Renewal above) and needs no inbound port.
|
||||
6. On the host, point the apex at nginx locally (next section).
|
||||
7. Close the router's 80 and 443 forwards. Once 5 and 6 are done nothing
|
||||
depends on them.
|
||||
|
||||
#### What the tunnel does not carry, and where it goes instead
|
||||
|
||||
- **Certificate renewal.** Over DNS-01 with `CLOUDFLARE_DNS_API_TOKEN` set;
|
||||
without it certbot falls back to HTTP-01, which needs port 80 forwarded.
|
||||
The certificate matters behind the tunnel: cloudflared verifies it, as
|
||||
do the registry path below and any direct LAN access. A fresh machine with no
|
||||
certificate at all boots the setup config (§3), which serves nothing over
|
||||
443, so the tunnel carries nothing until the first issuance.
|
||||
- **Registry pushes and pulls on the host.** Cloudflare caps request bodies at
|
||||
100 MB on the free plan, so a push of a larger image layer through the
|
||||
tunnel fails. The runner on the host pushes to `<DOMAIN>/adamf/...` and the
|
||||
stack pulls from it, both through the host's Docker daemon, which resolves
|
||||
names through the host's `/etc/hosts`. Pin the apex there to the loopback:
|
||||
|
||||
```
|
||||
127.0.0.1 <DOMAIN>
|
||||
```
|
||||
|
||||
so registry traffic goes straight to nginx on :443, with the real
|
||||
certificate, and never leaves the host. (Without it the name resolves to
|
||||
Cloudflare once DNS moves there.) Only the apex: www stays on Cloudflare for anything on the host
|
||||
that wants the public site. Pushing from another machine still goes
|
||||
through Cloudflare and its cap; use the host's Tailscale name for that.
|
||||
- **Gitea SSH (2222).** Not HTTP, so not tunnelled. Already Tailscale-only:
|
||||
`GITEA_SSH_DOMAIN` in `.env` (Gitea's `SSH_DOMAIN`) is the host's MagicDNS name
|
||||
and 2222 has never been forwarded. Nothing changes.
|
||||
- **The radio harbor (8001).** Also a raw source protocol, so a DJ client
|
||||
pointed at `<DOMAIN>:8001` stops connecting once the domain resolves to
|
||||
Cloudflare. Point it at the host's Tailscale name
|
||||
(`stpvm.tailf20278.ts.net:8001`) and close the 8001 forward. A guest DJ
|
||||
off the tailnet would need either a Tailscale share of the host or a
|
||||
Cloudflare TCP route used with `cloudflared access tcp` on their side.
|
||||
|
||||
#### Other limits
|
||||
- Cloudflare returns a 524 if the origin sends no response bytes for 100
|
||||
seconds. Streaming endpoints are fine while they keep writing; a long
|
||||
silent request is not.
|
||||
- Dev never runs cloudflared (`disabled` profile in `docker-compose.dev.yml`),
|
||||
so a laptop cannot join the production tunnel.
|
||||
|
||||
---
|
||||
|
||||
## 4. What persists across restarts
|
||||
@@ -197,26 +357,28 @@ cert, `docker compose restart nginx` is the fix. See proposal 1 in §8.
|
||||
**Named volumes** — survive `docker compose down` and rebuilds; destroyed only by
|
||||
`docker compose down -v` or `docker volume rm`:
|
||||
|
||||
| Volume | Holds | Losing it means |
|
||||
|---|---|---|
|
||||
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
|
||||
| `uploads` | User-uploaded files (backend writes, nginx serves) | All uploaded images |
|
||||
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
|
||||
| Volume | Holds | Losing it means |
|
||||
| ---------- | ----------------------------------------------------- | -------------------------------------------------- |
|
||||
| `dbdata` | Postgres: the app database **and** the Gitea database | All posts, users, messages, and all Gitea metadata |
|
||||
| `uploads` | Uploads from before Garage, private attachments, and any upload Garage refused | Those files |
|
||||
| `garage_meta` | Garage's metadata: buckets, keys, object index, layout | Everything in the bucket (the bytes in `garage_data` are unreadable without it) |
|
||||
| `garage_data` | The bucket's object bytes | Every upload stored in Garage |
|
||||
| `vue_dist` | The built SPA | Nothing — rebuilt on next deploy |
|
||||
|
||||
**Bind mounts** — live in the repo checkout on the Pi, survive everything short
|
||||
**Bind mounts** — live in the repo checkout on the host, survive everything short
|
||||
of deleting the directory:
|
||||
|
||||
| Path | Holds | Notes |
|
||||
|---|---|---|
|
||||
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
|
||||
| `./certbot/www` | ACME challenge webroot | Transient by nature |
|
||||
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) and the **job capture token hash** (`job_capture_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild, and the capture userscript a new token from the admin panel. |
|
||||
| `./env-apply/run` | The admin panel's queued `.env` change (`request.json`) and the host's report on it (`status.json`) | Gitignored. Transient, but must be owned by the deploy user, not root — see §5. |
|
||||
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
|
||||
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
|
||||
| `./logs` | Backend logs | |
|
||||
| `./icecast2/fallback_music` | Radio fallback MP3s | Synced by `sync-secrets.sh`, not git |
|
||||
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
|
||||
| Path | Holds | Notes |
|
||||
| --------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `./certbot/conf` | TLS certificates and **private keys** | Gitignored. Never commit. |
|
||||
| `./certbot/www` | ACME challenge webroot | Transient by nature |
|
||||
| `./backend/token/` | **Spotify OAuth refresh token** (`spotify_token.json`) | Gitignored. Without this mount, Spotify would need re-authorising after every rebuild. |
|
||||
| `./jobs-data` | The job tracker's **capture token hash** and Graph OAuth session | Gitignored. Must be owned by uid 1000, the user the `jobs` image runs as. |
|
||||
| `./gitea/data` | Git repositories, LFS objects, avatars, sessions | The actual git data |
|
||||
| `./gitea/config` | Gitea's live `app.ini` | Gitignored; generated from the template on first boot and then owned by Gitea |
|
||||
| `./logs` | Backend logs (`go.log`); nginx's JSON request-body log in `logs/nginx/payloads.log` | The payload log grows without bound; rotate it on the host (§7, "Incoming request bodies") |
|
||||
| `./icecast2/fallback_music` | Radio fallback MP3s | Copied to the host by hand, not git |
|
||||
| `${OBSIDIAN_DIR}` | The Obsidian vault (a git clone of the notes repo) | Read-write to backend and silverbullet, **read-only** to silverbullet-public |
|
||||
|
||||
**Ephemeral:** anything else inside a container. Notably the Vue build, the
|
||||
rendered nginx/icecast configs, and the Gitea runner's downloaded binary
|
||||
@@ -239,48 +401,28 @@ Two distinct mechanisms read it, and services use both:
|
||||
`gitea` instead receives explicit `GITEA__section__KEY` variables (Gitea's own
|
||||
convention for overriding `app.ini` keys), and `python` receives an explicit
|
||||
allow-list, so it never sees the database password or any API key other than
|
||||
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY` for the rowing photo and
|
||||
job posting readers).
|
||||
the two it uses (`TFL_APP_KEY`, and `CLAUDE_API_KEY`, plus `CLAUDE_MODEL`,
|
||||
which picks the model). The Python service
|
||||
makes the site's one Claude call (the rowing photo reader); the `jobs` container
|
||||
(the job tracker, built from its own repo) makes its own, and gets a similar
|
||||
allow-list with its own database role. The backend receives `CLAUDE_API_KEY`
|
||||
through `env_file` but does not use it. A new variable for either service has
|
||||
to be added to its allow-list as well as
|
||||
`.env.example`.
|
||||
|
||||
**`.env` reaches the Pi via `./sync-secrets.sh`**, which syncs exactly two
|
||||
things between this checkout and `adamf@stppi.local:~/deploy/web_server`:
|
||||
`.env`, and `icecast2/fallback_music/*.mp3`. The sync is **bidirectional and
|
||||
resolved by modification time — newer wins, with no merge.** Editing `.env` on
|
||||
both machines silently loses one side's edits. Run it before and after editing.
|
||||
**`.env` is edited by hand on the host**, in
|
||||
`~/deploy/web_server`. Nothing syncs it from a laptop checkout, so a laptop's
|
||||
`.env` (often with dev values) never reaches production by accident.
|
||||
|
||||
An unset variable is not an error: `envsubst` renders it as an empty string,
|
||||
which for a password field means *no password*. After editing `.env`, confirm
|
||||
which for a password field means _no password_. After editing `.env`, confirm
|
||||
with `docker compose config`.
|
||||
|
||||
### Editing from the admin panel
|
||||
### Changing a value on the host
|
||||
|
||||
The **Environment** tab at `/admin` edits `.env` on the Pi without SSH. API
|
||||
keys, OAuth client settings, the email settings and the generated secrets are
|
||||
editable; anything that would rename a container, move a port or lock the
|
||||
backend out of Postgres is shown read-only.
|
||||
|
||||
The backend cannot write `.env` or reach Docker. It queues the change in
|
||||
`./env-apply/run/request.json`, and a systemd path unit on the host runs
|
||||
`env-apply/apply.py`, which:
|
||||
|
||||
1. rewrites `.env` atomically, keeping comments and order, with the previous
|
||||
version saved as **`.env.bak`**;
|
||||
2. runs `docker compose config -q` and restores the backup if compose rejects
|
||||
the file;
|
||||
3. recreates only the services that read the changed variables, plus the
|
||||
backend (`docker compose up -d --no-deps --force-recreate …`);
|
||||
4. writes the outcome to `status.json`, which the panel is polling.
|
||||
|
||||
Only those services are recreated because nginx, db, icecast2 and certbot load
|
||||
the whole file too; a plain `up -d` would restart Postgres for a Steam key.
|
||||
They pick the new file up at the next deploy, which is harmless.
|
||||
|
||||
**The watcher is installed once per host** — see the runbook. Without it the
|
||||
panel still queues the change and says nothing has picked it up.
|
||||
|
||||
A change made this way makes the Pi's `.env` the newer copy, so the next
|
||||
`./sync-secrets.sh` pulls it down to the laptop. The newer-wins caveat above
|
||||
still applies: do not also edit the local copy before syncing.
|
||||
Edit `.env` on the host, and recreate only the services that read the variable:
|
||||
`docker compose up -d <service>`. A plain `up -d` would also restart Postgres,
|
||||
since nginx, db, icecast2 and certbot load the whole file.
|
||||
|
||||
---
|
||||
|
||||
@@ -294,29 +436,32 @@ tuned value.
|
||||
`rate` is a **smoothed leaky bucket**, not a per-window counter: `5r/m` means one
|
||||
request every 12 seconds, not five at once. `burst=N` lets N requests queue ahead
|
||||
of that drip, and `nodelay` (used everywhere here) serves those N immediately.
|
||||
So the effective behaviour is *"N instant requests, then throttled to the drip
|
||||
rate"*. Anything beyond the burst gets an immediate **503**.
|
||||
So the effective behaviour is _"N instant requests, then throttled to the drip
|
||||
rate"_. Anything beyond the burst gets an immediate **503**.
|
||||
|
||||
| Zone | Rate | Burst | Applied to | Why |
|
||||
|---|---|---|---|---|
|
||||
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
|
||||
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
||||
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
|
||||
| `upload` | 5/min | 3 | `/api/messages/upload` | Uploads can be 50MB and hit disk; bounds how fast one IP fills the volume. |
|
||||
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
|
||||
| Zone | Rate | Burst | Applied to | Why |
|
||||
| -------------- | ------ | ----- | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `login` | 5/min | 3 | `/api/auth/login` | Brute-force defence. A human mistyping gets 3 tries then one per 12s; a credential-stuffing script gets nothing useful. |
|
||||
| `api` | 30/sec | 20 | `/api/`, `/py/` | Generous on purpose — one SPA page load fans out to several calls. An abuse ceiling, not a quota. |
|
||||
| `graphql` | 10/sec | 10 | `/api/graphql` | Tighter than REST because one query can be arbitrarily expensive. **Production config only**; dev folds GraphQL into `api`. |
|
||||
| `upload` | 30/min | 20 | `/api/uploads` | Bounds how fast one IP fills the bucket or the volume. Generous because uploaders must be signed in (accounts are admin-created) and a batch of pictures dropped on a canvas page uploads at once. |
|
||||
| `hotel_search` | 3/min | 2 | `/py/hotels/(search\|scan)` | Each request holds an upstream call for minutes and the Python side has one search slot — concurrency protection more than abuse protection. |
|
||||
|
||||
The WebSocket endpoint is deliberately unlimited: a socket is one long-lived
|
||||
request, and a limit there would drop reconnect storms rather than abuse.
|
||||
|
||||
These zones key on the direct client IP, which is correct because nginx is the
|
||||
sole edge. **If a CDN or proxy is ever put in front, they must switch to a
|
||||
trusted `X-Forwarded-For` or every visitor shares one bucket.**
|
||||
These zones key on `$remote_addr`. For tunnel traffic nginx rewrites that
|
||||
from Cloudflare's `CF-Connecting-IP` header (`set_real_ip_from` /
|
||||
`real_ip_header` in `nginx.conf.template`), trusting the header only from
|
||||
cloudflared's fixed address. **If that address changes in
|
||||
`docker-compose.yml` without the nginx line, every tunnel visitor shares
|
||||
cloudflared's one bucket**, and the login limit locks everyone out together.
|
||||
|
||||
---
|
||||
|
||||
## 7. Runbook
|
||||
|
||||
All commands run from the deploy checkout on the Pi
|
||||
All commands run from the deploy checkout on the host
|
||||
(`~/deploy/web_server`) unless stated.
|
||||
|
||||
**Deploy.** Normally automatic — push to `main` and the Gitea Actions runner does
|
||||
@@ -326,24 +471,6 @@ it. By hand:
|
||||
git pull && docker compose up -d --build --remove-orphans
|
||||
```
|
||||
|
||||
**Install the `.env` watcher** (once per host; lets the admin panel's
|
||||
Environment tab apply changes):
|
||||
|
||||
```
|
||||
./env-apply/install.sh # asks for sudo
|
||||
systemctl status web-server-env-apply.path # should be active (waiting)
|
||||
journalctl -u web-server-env-apply.service # one entry per applied change
|
||||
```
|
||||
|
||||
Run it as the user that owns the checkout. `env-apply/run` must belong to that
|
||||
user: if Docker created it first it is root-owned, and the script fixes that.
|
||||
To apply a queued change by hand, or undo one:
|
||||
|
||||
```
|
||||
python3 env-apply/apply.py # apply what the panel queued
|
||||
cp .env.bak .env && docker compose up -d # roll back the last change
|
||||
```
|
||||
|
||||
**Rebuild one service** (e.g. after changing only the backend):
|
||||
|
||||
```
|
||||
@@ -380,6 +507,40 @@ docker compose ps # note: `vue` Exited(0) is correct
|
||||
docker compose logs certbot # issuance / renewal outcomes
|
||||
```
|
||||
|
||||
Or browse every container's logs at `https://www.<DOMAIN>/dozzle/` (admin
|
||||
login required).
|
||||
|
||||
**Incoming request bodies.** nginx writes one JSON line per request, body
|
||||
included, to `logs/nginx/payloads.log` (`nginx/payload_log.conf`). The
|
||||
`traffic` container tails it, so in Dozzle pick **traffic** and each request
|
||||
renders as fields you can search. From a shell:
|
||||
|
||||
```
|
||||
tail -f logs/nginx/payloads.log | jq 'select(.method=="POST")'
|
||||
jq -r 'select(.uri=="/api/graphql") | .body | fromjson? | .operationName' logs/nginx/payloads.log
|
||||
```
|
||||
|
||||
Bodies mentioning `password`, `token` or `secret` are logged as `[redacted]`
|
||||
(that covers every login and the refresh call). Bodies over 64 KB, i.e.
|
||||
uploads, are logged with an empty `body`, and responses are never logged.
|
||||
|
||||
The file is never rotated by the stack. On the host, add
|
||||
`/etc/logrotate.d/web_server`:
|
||||
|
||||
```
|
||||
/home/adamf/deploy/web_server/logs/nginx/*.log {
|
||||
weekly
|
||||
rotate 4
|
||||
compress
|
||||
missingok
|
||||
notifempty
|
||||
copytruncate
|
||||
}
|
||||
```
|
||||
|
||||
`copytruncate` because nginx keeps the file open; `tail -F` in `traffic`
|
||||
follows the truncation.
|
||||
|
||||
**Reset the database** — destructive; wipes the app database **and Gitea's**:
|
||||
|
||||
```
|
||||
@@ -397,37 +558,120 @@ manually before Gitea will start:
|
||||
docker compose exec db createdb -U "$POSTGRES_USER" "$POSTGRES_GITEA_DB"
|
||||
```
|
||||
|
||||
**Sync secrets / fallback music** (from the laptop checkout, not the Pi):
|
||||
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket,
|
||||
with the `uploads` volume as a safety net. Nothing breaks while Garage is down
|
||||
or not set up:
|
||||
|
||||
- the backend writes to disk until `S3_ENDPOINT` is set, and falls back to
|
||||
disk (with a log line) whenever Garage refuses a write;
|
||||
- nginx serves `/uploads/` from Garage and falls back to the volume when
|
||||
Garage has no such file or is unreachable, and it boots without the
|
||||
`garage` container.
|
||||
|
||||
Turning it on:
|
||||
|
||||
1. Fill in `GARAGE_RPC_SECRET`, `GARAGE_ADMIN_TOKEN`, `S3_ACCESS_KEY_ID` and
|
||||
`S3_SECRET_ACCESS_KEY` in `.env` **before** the deploy that adds the
|
||||
containers (otherwise `garage` crash-loops on a blank secret until they
|
||||
are set; nothing else is affected). `.env.example` says how to generate
|
||||
each.
|
||||
2. Deploy, then `garage/bootstrap.sh` (idempotent; it creates the layout, the
|
||||
`uploads` bucket and the backend's key, and opens the bucket to the
|
||||
website endpoint).
|
||||
3. Set `S3_ENDPOINT=http://garage:3900` and `docker compose up -d backend`.
|
||||
The backend logs `[upload] storing uploads in bucket uploads ...` on start.
|
||||
4. Check: upload something through a canvas page or chat, then
|
||||
`docker compose exec garage /garage bucket info uploads` shows the object
|
||||
count going up, and the returned `/uploads/...` URL loads.
|
||||
|
||||
Moving the old files in (so they show in garage-webui, and so the bucket
|
||||
holds everything):
|
||||
|
||||
```
|
||||
./sync-secrets.sh
|
||||
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
|
||||
docker run --rm --network web_server_app-network \
|
||||
-v web_server_uploads:/data:ro \
|
||||
-e AWS_ACCESS_KEY_ID="$S3_ACCESS_KEY_ID" -e AWS_SECRET_ACCESS_KEY="$S3_SECRET_ACCESS_KEY" \
|
||||
-e AWS_DEFAULT_REGION=garage \
|
||||
amazon/aws-cli:2.38.0 s3 sync /data s3://uploads --exclude 'private/*' \
|
||||
--endpoint-url http://garage:3900
|
||||
```
|
||||
|
||||
**Set up the CI runner on a fresh Pi:**
|
||||
The copies left on the volume are then only a fallback for when Garage is
|
||||
down, and the rollback. One catch: a file deleted in garage-webui is still
|
||||
served from its disk copy, if it has one. Once the bucket has been trusted for
|
||||
a while, remove everything but `private/` from the volume.
|
||||
|
||||
**Rollback:** blank `S3_ENDPOINT` and `docker compose up -d backend`. Files
|
||||
written to the bucket in the meantime stay reachable as long as `garage` runs;
|
||||
to drop Garage entirely, first copy them back
|
||||
(`aws s3 sync s3://uploads /data` with the volume mounted read-write).
|
||||
|
||||
**Managing files:** garage-webui at `/garage/` (site admin login). Files
|
||||
uploaded there are public at `/uploads/<path>` and skip the backend's type
|
||||
checks; keep them under a prefix such as `media/`. Uploads through it are
|
||||
capped at 2G by nginx.
|
||||
|
||||
**Backups:** Garage here is one node on the same disk — it is not a backup.
|
||||
Back up `garage_meta` and `garage_data` together (meta without data, or the
|
||||
reverse, is useless); Garage also snapshots its metadata every 6h inside
|
||||
`garage_meta`.
|
||||
|
||||
**Set up the CI runner on a fresh host:**
|
||||
|
||||
```
|
||||
cd gitea-runner
|
||||
bash download.sh # pulls the arm64 binary
|
||||
bash download.sh # pulls the binary for this CPU
|
||||
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners
|
||||
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises
|
||||
```
|
||||
|
||||
The runner lives **outside** Docker on purpose: it runs `docker compose up`
|
||||
against this stack, so it cannot be a container in it. Registration is one-shot —
|
||||
`.runner` is the lasting credential; re-registering needs that file deleted *and*
|
||||
`.runner` is the lasting credential; re-registering needs that file deleted _and_
|
||||
a fresh token.
|
||||
|
||||
**Go live on the radio:** point a broadcasting client (e.g. butt) at the Pi on
|
||||
**Dependency updates (Renovate).** Dependabot is GitHub-only, so
|
||||
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
|
||||
at 04:00 UTC (or by hand from the Actions tab), configured by
|
||||
`renovate.json5`. It opens PRs from `renovate/*` branches, which get the
|
||||
normal `test` job; nothing automerges, because merging to `main` deploys. It
|
||||
needs a `RENOVATE_TOKEN` repo Actions secret: create a `renovate` Gitea user,
|
||||
add it to this repo as a collaborator with write access, and mint a token for
|
||||
it with `read:user`, `read:organization`, `write:repository` and
|
||||
`write:issue`. `RENOVATE_GITHUB_COM_TOKEN` (any github.com token, no scopes)
|
||||
is optional and lifts GitHub's rate limit on release-note lookups. The first
|
||||
run opens a "Dependency Dashboard" issue listing everything pending.
|
||||
|
||||
**Go live on the radio:** point a broadcasting client (e.g. butt) at the host's
|
||||
Tailscale name (not the domain, which resolves to Cloudflare) on
|
||||
`${LIQUIDSOAP_HARBOR_PORT}` with mount `${LIQUIDSOAP_HARBOR_MOUNT}` and the
|
||||
icecast source password. liquidsoap pre-empts the fallback playlist immediately
|
||||
(`track_sensitive=false`). Disconnect and it falls back to the playlist, then to
|
||||
silence. Adding MP3s to `icecast2/fallback_music/` is picked up live
|
||||
(`reload_mode="watch"`) with no restart.
|
||||
|
||||
**Unhealthy containers are not restarted automatically.** `backend` and `python`
|
||||
define healthchecks, but the `autoheal` watchdog that acted on them was retired
|
||||
(`.deprecated/autoheal`), so `unhealthy` is only visible in `docker ps`.
|
||||
`restart: always` still brings back a container whose process exits.
|
||||
**Only nginx is restarted when unhealthy.** Docker marks a container
|
||||
`unhealthy` but never acts on it; `restart: always` only brings back a process
|
||||
that exits. The `autoheal` container restarts anything labelled
|
||||
`autoheal=true`, which today is just nginx (its healthcheck fetches
|
||||
`/nginx-health` on :80 every 30s; three misses, about 90s, and it is
|
||||
restarted). `backend` and `python` also define healthchecks, but carry no
|
||||
label, so for them `unhealthy` is only visible in `docker ps`. Add the label to
|
||||
cover another service.
|
||||
|
||||
**Site down but every container `Up`.** That is what a stalled nginx worker
|
||||
looks like (2026-10-19: 4.6 hours, every tunnel request a `TLS handshake
|
||||
timeout` in `docker logs cloudflared`, and the Cloudflare dashboard still
|
||||
showing the tunnel healthy, since that only covers the tunnel's own link). The
|
||||
healthcheck should now catch it. If it recurs, capture the stuck worker before
|
||||
restarting, since a restart destroys the only evidence of why:
|
||||
|
||||
```
|
||||
docker inspect nginx --format '{{.State.Health.Status}}'
|
||||
docker top nginx -o pid,stat,wchan:30,etime,cmd # what each worker is waiting in
|
||||
docker compose restart nginx
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -445,8 +689,12 @@ Documented, not fixed — each would change deploy behaviour.
|
||||
mounted to the same in-container path as the real wrapper. It is currently
|
||||
shadowed by an explicit file mount — fragile. Deleting it would be safe but
|
||||
is a file removal.
|
||||
4. **The dev nginx template duplicates its `:80` and `:443` server blocks**
|
||||
almost verbatim (~190 lines), so a routing fix must be made twice.
|
||||
4. **The `/uploads/` location blocks (with `@uploads_disk`) are still written twice** — once in
|
||||
`nginx.conf.template` and once in `nginx_dev_common.conf.template` —
|
||||
because production adds security headers inside an auth-gated block. Every
|
||||
other proxied route lives once in `nginx_routes.conf.template`, which both
|
||||
configs include; the `auth_request` lines on `/uploads/private/` are the
|
||||
one thing that must be kept in step by hand.
|
||||
5. **`nginx.conf.template` has a `/img/stamps/mine.gif` CORS header allowing
|
||||
only our own origin**, which defeats the point of having the header at all.
|
||||
6. **`certbot/entrypoint.sh` uses unquoted `${EMAIL}` and `${DOMAIN}`.** Inert
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
# =============================================================================
|
||||
# Makefile — one place for the commands that verify and run this repo.
|
||||
#
|
||||
# WHY THIS FILE EXISTS
|
||||
# The stack is four toolchains (Go, Python, Node, Docker) and the command
|
||||
# that checks each one used to live only in a gitignored notes file. `make
|
||||
# check` is the single thing to run before pushing; .gitea/workflows/
|
||||
# deploy.yaml runs the same backend and Python checks (in containers, since
|
||||
# the Pi runner has no host toolchains) before it deploys.
|
||||
#
|
||||
# WHAT IT NEEDS ON THE HOST
|
||||
# check-backend / generate Go (the version in backend/go.mod)
|
||||
# check-python python3 with the venv module
|
||||
# check-vue Node + `npm install` done in vue/
|
||||
# check-compose / dev Docker with the compose plugin
|
||||
# Nothing here installs a toolchain; a missing one fails that target only.
|
||||
#
|
||||
# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in
|
||||
# its own shell, so the directory change cannot leak into the next line.
|
||||
# =============================================================================
|
||||
|
||||
# `make` with no arguments prints the target list rather than running checks.
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
# Overridable: `make check-python PYTHON=python3.12` to match the image.
|
||||
PYTHON ?= python3
|
||||
|
||||
# The virtualenv for the Python checks. At the repo root rather than inside
|
||||
# python/, because python/ is a docker build context and a venv there would be
|
||||
# sent to the daemon on every build. Gitignored (/.venv/).
|
||||
VENV := .venv
|
||||
|
||||
# Written after a successful install. Being a file target that depends on both
|
||||
# requirements files, it is what makes `check-python` re-install when either
|
||||
# changes and skip the install otherwise.
|
||||
VENV_STAMP := $(VENV)/.installed
|
||||
|
||||
.PHONY: help check check-backend check-python check-vue check-compose generate dev
|
||||
|
||||
help:
|
||||
@echo "Targets:"
|
||||
@echo " make check run every check below"
|
||||
@echo " make check-backend go vet + go test in backend/"
|
||||
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
|
||||
@echo " make check-vue vite build of vue/ into a throwaway directory"
|
||||
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
|
||||
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
|
||||
@echo " make dev build and run the dev stack (http://localhost)"
|
||||
|
||||
# Run with `make -k check` to keep going past the first failing area.
|
||||
check: check-backend check-python check-vue check-compose
|
||||
|
||||
check-backend:
|
||||
cd backend && go vet ./... && go test ./...
|
||||
|
||||
# requirements-dev.txt `-r`-includes requirements.txt, so one install covers
|
||||
# the app's dependencies and pytest. The venv is recreated from scratch
|
||||
# whenever a requirements file changes: upgrading in place would leave behind
|
||||
# packages that were removed from the files, and the check would keep passing
|
||||
# on a dependency the image no longer has.
|
||||
$(VENV_STAMP): python/requirements.txt python/requirements-dev.txt
|
||||
rm -rf $(VENV)
|
||||
$(PYTHON) -m venv $(VENV)
|
||||
$(VENV)/bin/python -m pip install --quiet --upgrade pip
|
||||
$(VENV)/bin/python -m pip install --quiet -r python/requirements-dev.txt
|
||||
touch $@
|
||||
|
||||
check-python: $(VENV_STAMP)
|
||||
cd python && ../$(VENV)/bin/python -m pytest tests -q
|
||||
|
||||
# A Vite build is enough to catch a broken import or template; there is no
|
||||
# test runner or linter for the frontend.
|
||||
#
|
||||
# The build goes to a temp directory that is removed afterwards (success or
|
||||
# failure), so the check never leaves a vue/dist behind or overwrites one.
|
||||
check-vue:
|
||||
@test -d vue/node_modules || { \
|
||||
echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \
|
||||
exit 1; }
|
||||
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
|
||||
cd vue && npx vite build --outDir "$$out" --emptyOutDir
|
||||
|
||||
# Validates the compose files: YAML, schema, and that every ${VAR} they
|
||||
# interpolate resolves to something usable.
|
||||
#
|
||||
# With a real .env present this is simply `docker compose config -q`.
|
||||
#
|
||||
# Without one (a CI checkout, a fresh clone) two things break, and
|
||||
# `--env-file .env.example` fixes neither:
|
||||
# - several services declare `env_file: ./.env`, and compose refuses to load
|
||||
# the project if that file does not exist;
|
||||
# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount
|
||||
# source, where an empty string is a hard "invalid spec" error.
|
||||
# So in that case the files are validated against a temporary PROJECT
|
||||
# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for
|
||||
# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist,
|
||||
# so the build contexts not being under the temp directory is fine. Nothing is
|
||||
# written to the repo, and a real .env is never created by accident.
|
||||
check-compose:
|
||||
@set -e; \
|
||||
if [ -f .env ]; then \
|
||||
pd="."; \
|
||||
else \
|
||||
echo "check-compose: no .env, validating against .env.example"; \
|
||||
pd=$$(mktemp -d); trap 'rm -rf "$$pd"' EXIT; \
|
||||
cp .env.example "$$pd/.env"; \
|
||||
echo "OBSIDIAN_DIR=/placeholder/obsidian" >> "$$pd/.env"; \
|
||||
fi; \
|
||||
echo "docker compose -f docker-compose.yml config -q"; \
|
||||
docker compose --project-directory "$$pd" -f docker-compose.yml config -q; \
|
||||
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
|
||||
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
|
||||
|
||||
# Rewrites backend/graph/generated.go and graph/model/models_gen.go from
|
||||
# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved.
|
||||
generate:
|
||||
cd backend && go run github.com/99designs/gqlgen generate
|
||||
|
||||
# Dev stack: HTTP only, seeded database, Vite hot reload behind nginx.
|
||||
dev:
|
||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||
@@ -1,3 +1,4 @@
|
||||
Gay bal;;s
|
||||
# My Web
|
||||
|
||||

|
||||
@@ -32,7 +33,7 @@ certbot ── SSL Certificate Management (disabled in dev)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
|
||||
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
|
||||
|
||||
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
|
||||
|
||||
@@ -147,7 +148,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
||||
**Protected (auth required)**
|
||||
| Method | Path | Description |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
|
||||
| POST | `/api/messages/upload` | Upload a file for a chat message or a canvas box (rate limited: 30/min, burst 20) |
|
||||
|
||||
**Admin (auth + admin required)**
|
||||
| Method | Path | Description |
|
||||
@@ -242,7 +243,7 @@ Create a `.env` file in the project root. All services read from this file.
|
||||
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
||||
| `DOMAIN` | Production domain name |
|
||||
| `EMAIL` | Email for Let's Encrypt registration |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key |
|
||||
| `CLAUDE_API_KEY` | Anthropic Claude API key (read by the Python service, which makes every Claude call) |
|
||||
| `STEAM_API_KEY` | Steam Web API key |
|
||||
| `STEAM_ID` | Steam user ID |
|
||||
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
|
||||
@@ -302,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
|
||||
```
|
||||
|
||||
@@ -321,7 +323,17 @@ Visit `http://localhost` to test.
|
||||
cd vue && npm run dev
|
||||
```
|
||||
|
||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
||||
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets default to `localhost:8080`, `:3000`, `:8000` and `:8000`; override them with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (see the comment in `vue/vite.config.js` — compose does not publish the backend, Python or Icecast ports to the host).
|
||||
|
||||
### Checks
|
||||
|
||||
```sh
|
||||
make check
|
||||
```
|
||||
|
||||
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build and `docker compose config` validation. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
|
||||
|
||||
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
|
||||
|
||||
## Untracked Files
|
||||
|
||||
@@ -339,7 +351,6 @@ These files are git-ignored and must be created manually:
|
||||
|
||||
## Future Ideas
|
||||
|
||||
- More Rust to WASM
|
||||
- ML for chatboards
|
||||
- Cache requests
|
||||
- Design more webpages
|
||||
|
||||
+179
-102
@@ -2,7 +2,8 @@
|
||||
|
||||
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
|
||||
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic).
|
||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
|
||||
that needs Claude is asked of the Python service, not called from here.
|
||||
|
||||
Nginx strips the `/api` prefix before proxying, so a browser request to
|
||||
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
|
||||
handle_*.go one file per domain
|
||||
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
||||
graph/ GraphQL layer
|
||||
schema/*.graphql source of truth for the schema
|
||||
schema/*.graphql source of truth for the schema, including who may call what
|
||||
*.resolvers.go resolver implementations, one per schema file
|
||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||
directives.go @admin / @signedIn: the authorisation checks, written once
|
||||
directives_test.go fails when a mutation is added without one
|
||||
context.go reading identity out of the resolver context
|
||||
middleware.go putting it in
|
||||
doc.go package overview — read this before touching resolvers
|
||||
@@ -41,9 +44,10 @@ graph/ GraphQL layer
|
||||
reached through the `admin` group can assume both.
|
||||
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
||||
*annotates* the request context with the Gin context and, if a valid access
|
||||
token is present, the JWT claims — and then lets everything through. Each
|
||||
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
|
||||
**A resolver that forgets to check is public.**
|
||||
token is present, the JWT claims — and then lets everything through. A
|
||||
field is guarded by a directive on it in the schema, `@admin` or
|
||||
`@signedIn`, which runs before the resolver. **A field with neither is
|
||||
public.** See [GraphQL authorisation](#graphql-authorisation).
|
||||
5. Handlers and resolvers both reach the database and the caches through the
|
||||
single `handlers.Store` built in `main`.
|
||||
|
||||
@@ -60,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
|
||||
@@ -70,6 +84,95 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
||||
both. They share `services.Auth` and the rate limiter, but each has its own
|
||||
cookie-writing helper — change one and you must change the other.
|
||||
|
||||
## GraphQL authorisation
|
||||
|
||||
Who may call a field is written in the schema, on the field:
|
||||
|
||||
```graphql
|
||||
extend type Query {
|
||||
bookmarks: [Bookmark!]! # public
|
||||
places: [Place!]! @signedIn # any signed-in user
|
||||
users: [User!]! @admin # admins only
|
||||
}
|
||||
```
|
||||
|
||||
| directive | passes when | error otherwise |
|
||||
| --- | --- | --- |
|
||||
| `@admin` | the access token's `admin` claim is true | `admin access required` |
|
||||
| `@signedIn` | there is a valid access token at all | `authentication required` |
|
||||
| *(none)* | always | — |
|
||||
|
||||
Both are declared in `graph/schema/schema.graphql`, implemented once in
|
||||
`graph/directives.go`, and handed to gqlgen in `main.go`
|
||||
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
|
||||
before the resolver; on an error the resolver never runs and the client gets
|
||||
that message for the field. The two strings are shown as-is by the front end,
|
||||
so they are part of the API. If the `Directives` line were ever dropped from
|
||||
`main.go` the guarded fields would all fail (`directive admin is not
|
||||
implemented`), not open.
|
||||
|
||||
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
|
||||
the top of every guarded resolver, where leaving it out was invisible. Now a
|
||||
guarded resolver has no check in it, and the absence of a guard is something a
|
||||
test can see.
|
||||
|
||||
**What is guarded.** Queries are public and mutations are `@admin`, except:
|
||||
|
||||
- `login`, `logout`, `refreshToken` — public; they are how a session starts
|
||||
and ends.
|
||||
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
|
||||
`@signedIn`. Places are a shared list with no per-user ownership.
|
||||
- `users`, `user` — queries, but `@admin`: private data.
|
||||
|
||||
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
|
||||
`UserIDFromCtx` from `graph/context.go`:
|
||||
|
||||
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
|
||||
post's author; `setUserAdmin` refuses to change the caller's own flag.
|
||||
- `me` has no directive: it returns its own `unauthorized` error.
|
||||
- `messages` has no directive: it filters private messages out for non-admins
|
||||
instead of refusing.
|
||||
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
|
||||
|
||||
**The safety net** is `graph/directives_test.go`, which walks the parsed
|
||||
schema:
|
||||
|
||||
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
|
||||
the `publicMutations` list in that file (the three above). A new mutation
|
||||
with no directive fails the build's tests until one or the other is done;
|
||||
- the `@signedIn` mutations and the guarded queries are pinned by name, so
|
||||
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
|
||||
has to be done in the test as well;
|
||||
- the directive functions are unit-tested, and a handful of operations are run
|
||||
through the real executable schema to pin the messages on the wire.
|
||||
|
||||
One caveat: the test reads the `.graphql` files, but enforcement is in
|
||||
`generated.go`. Adding a directive to an existing field does nothing until
|
||||
gqlgen is re-run.
|
||||
|
||||
## Adding an entity
|
||||
|
||||
1. **Model** — add the struct to `models/models.go` with `ID uint`
|
||||
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
|
||||
in `services/database.go`. There are no migration files.
|
||||
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
|
||||
and `extend type Query` / `extend type Mutation`. Put `@admin` or
|
||||
`@signedIn` on every mutation, and on any query that is not for the public.
|
||||
Use `#` comments, not `"""` descriptions.
|
||||
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
|
||||
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
|
||||
unrelated struct in `graph/model/`.
|
||||
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
|
||||
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
|
||||
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
|
||||
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
|
||||
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
|
||||
gqlgen rewrites what is above the signature. A delete should load the row
|
||||
first and return an error for a missing id, as the existing ones do.
|
||||
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
|
||||
mutation was left unguarded; if you added a guarded *query*, add it to the
|
||||
pinned list there.
|
||||
|
||||
## GraphQL vs REST
|
||||
|
||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||
@@ -78,84 +181,46 @@ for the things GraphQL cannot do:
|
||||
| REST endpoint | why it is not GraphQL |
|
||||
| --- | --- |
|
||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||
| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here |
|
||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||
| `/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 |
|
||||
| `/admin/env`, `/admin/logs`, `/admin/capture-token` | process environment and files on disk, not the data model |
|
||||
| `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead |
|
||||
|
||||
### Environment tab
|
||||
## Calling the Python service
|
||||
|
||||
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
|
||||
change `.env` on the Pi without SSH. The backend never reads or writes the
|
||||
file and has no Docker access: it validates an edit and leaves it for the
|
||||
host, which is the part trusted to act.
|
||||
Every Claude call the site makes lives in the Python service; this backend has
|
||||
no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
|
||||
`/jobs/` is a separate app with its own Claude calls.) It reaches the
|
||||
internal routes directly over the Docker network
|
||||
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
|
||||
nginx, which answers 404 for `/py/internal/`:
|
||||
|
||||
- **`services/env_registry.json`** lists every variable in `.env.example`
|
||||
with its group, kind, whether it is editable, and the compose services that
|
||||
read it. It is embedded in the binary and read from the checkout by the host
|
||||
script, so one file decides what the panel offers and what the host accepts.
|
||||
A test fails if it and `.env.example` disagree.
|
||||
- `GET /admin/env` — the registry plus state from this process's own
|
||||
environment. A secret's value is never sent, only "set" and, for values of
|
||||
12+ characters, the last four.
|
||||
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
|
||||
clears. The whole batch is validated first. Control characters are refused
|
||||
because `.env` is line oriented: a newline would let an edit to an allowed
|
||||
variable write a second, arbitrary one. Generated values (32 random bytes,
|
||||
hex) are returned once.
|
||||
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
|
||||
on the host), `0600` and chowned to that directory's owner so the
|
||||
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
|
||||
`.env`, recreates the affected services and writes `status.json`.
|
||||
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
|
||||
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
|
||||
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
|
||||
an unclaimed request.
|
||||
| route | caller | sends | gets back |
|
||||
| --- | --- | --- | --- |
|
||||
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
|
||||
Every route goes through one function, `services.CallPython[T]` in
|
||||
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
|
||||
It has the one HTTP client (two-minute timeout, above the Python side's own
|
||||
worst case of a retried Claude call) and the one rule for failures:
|
||||
|
||||
The backend is always among the recreated services, because the values the
|
||||
panel shows are the ones this process started with.
|
||||
- a **502 whose `detail` is a string** is a message the route wrote for a
|
||||
person ("failed to parse image data"). It comes back as a
|
||||
`*services.PythonError`, and the HTTP handler relays it to the browser;
|
||||
- **anything else** — connection refused, a 422 (its `detail` is a list), a
|
||||
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
|
||||
ordinary error. Callers log it and show something generic.
|
||||
|
||||
### Job capture
|
||||
|
||||
`handlers/handle_job_capture.go` is the server half of the browser userscript
|
||||
(`vue/public/job-capture.user.js`, installed from the tracker page) that adds
|
||||
the posting open in the browser to the job tracker.
|
||||
|
||||
- **Auth** is `Authorization: Bearer <token>`, checked by
|
||||
`CaptureTokenMiddleware`. The token opens these three routes and nothing
|
||||
else — it cannot read the tracker or reach GraphQL. **With no token
|
||||
generated the routes are off (503)**; that never means "no auth".
|
||||
- **The token is generated in the admin panel**, not set in `.env`
|
||||
(`services/capture_token.go`; `GET`/`POST`/`DELETE /admin/capture-token`,
|
||||
cookie-authenticated like the rest of the admin group). It is 32 random
|
||||
bytes, shown once; only its SHA-256 is kept, in
|
||||
`/backend/token/job_capture_token.json` beside the OAuth tokens, so it
|
||||
survives restarts and rebuilds. There is one token at a time: generating
|
||||
again replaces it, which is how a leaked one is rotated.
|
||||
- `GET /jobs/capture/status?url=` — is this posting already tracked, and at
|
||||
what status. Drives the script's badge.
|
||||
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
|
||||
notes}` out, read by Claude through the Python service
|
||||
(`/internal/jobs/extract`). Stores nothing.
|
||||
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
|
||||
URL (`canonicalJobURL` strips tracking parameters and folds LinkedIn's
|
||||
several URL shapes into one), then by `(company, job title)` the way the
|
||||
email pipeline matches. A repeat capture only ever adds: status moves
|
||||
forwards, empty fields are filled, nothing is overwritten.
|
||||
|
||||
The upsert is what keeps this and the email pipeline from making two rows for
|
||||
one application. It is not watertight: the pipeline still matches on the exact
|
||||
title, so a posting captured as "Senior Engineer" whose confirmation email
|
||||
says "Senior Engineer (Platform)" becomes a second row.
|
||||
It lives in `services` so that a background job there could use it as well
|
||||
as a handler. A new internal route needs only a
|
||||
request struct, a reply struct and a one-line call.
|
||||
|
||||
## Services
|
||||
|
||||
Everything is constructed in `main` from environment variables and handed to
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an
|
||||
unconfigured mailbox or an absent Steam key all just leave that feature
|
||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token or an
|
||||
absent Steam key all just leave that feature
|
||||
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
|
||||
- **database.go** — Postgres via GORM. There are no migration files:
|
||||
@@ -170,14 +235,21 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
||||
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
||||
(Steam).
|
||||
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
|
||||
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
|
||||
it, ask Claude to extract structured data, create or advance a
|
||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
||||
- **claude.go** — the Anthropic client, used by the email pipeline. (The
|
||||
rowing photo reader's and the job posting reader's Claude calls live in the
|
||||
Python service; `POST /rowing` and `POST /jobs/capture/extract` reach it
|
||||
directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/...`.)
|
||||
- **python_call.go** — `CallPython`, the one way to reach the Python service's
|
||||
internal routes. See [Calling the Python service](#calling-the-python-service).
|
||||
- **uploads.go** — every stored file. `Uploads.Save(ctx, fileHeader, private)`
|
||||
validates against `UploadTypes` (extension, stored Content-Type, content
|
||||
sniff) and `MaxUploadSize`, names the file randomly, stores it and returns
|
||||
its `/uploads/...` URL; an `*UploadError` is the uploader's fault and safe
|
||||
to show them. Public files go to the Garage bucket wrapped in
|
||||
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
|
||||
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
|
||||
(nginx cannot gate a bucket). nginx serves `/uploads/` from the bucket
|
||||
first and disk second, so either store's files work at the same URL. A new
|
||||
handler that takes a file calls `store.Uploads.Save`. `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
|
||||
@@ -205,16 +277,30 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||
generated struct rather than the model you expected.
|
||||
|
||||
One scalar-level binding in `gqlgen.yml` is worth knowing about: `ID` lists
|
||||
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas).
|
||||
|
||||
If you delete a field or stop needing a resolver, delete the resolver function
|
||||
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
|
||||
warning block at the end of the file.
|
||||
|
||||
## Gotchas
|
||||
|
||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
||||
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
- **Soft delete everywhere.** Every model has a `gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
||||
with deleted rows — a soft-deleted username cannot be reused.
|
||||
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
||||
there is no error to tell you why the field came back null.
|
||||
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
|
||||
has a hand-written `ID` resolver doing `int(obj.ID)`.
|
||||
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
|
||||
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
|
||||
served directly — there are no `ID` resolvers, and a new type does not need
|
||||
one. `IntID` is listed first, which is why resolver *arguments* are still
|
||||
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
|
||||
string or a number, so the wire format is the same either way. Other
|
||||
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
|
||||
`Rowing.time`, `Rowing.distance`.
|
||||
- **Deletes error on a missing id.** Every delete mutation loads the row
|
||||
first, so a wrong id is a `record not found` error.
|
||||
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
||||
out by the chat hub on connect, meaningless across restarts.
|
||||
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
||||
@@ -222,19 +308,10 @@ generated struct rather than the model you expected.
|
||||
- **Store's caches are unsynchronised** and shared by all requests. The races
|
||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||
there that would be unsafe to tear.
|
||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
||||
fence — `services.StripMarkdownFence` in `email_sync.go`, with a port of it
|
||||
in `python/app/rowing.py` for the rowing photo reader.
|
||||
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
|
||||
A failed email is recorded with action `"error"` and an attempt counter;
|
||||
while it has attempts left the next sync reprocesses it and updates the same
|
||||
row. Because the fetch window is anchored to *processing* time, which has
|
||||
already moved past the failure, the sync also rewinds the window to the
|
||||
oldest retryable row's `ReceivedAt` — otherwise the email could never be
|
||||
re-fetched. Once the cap is reached the row is terminal, so an email Claude
|
||||
can never parse stops costing API calls.
|
||||
- **Authenticating email after start-up does not start the scheduler**, which
|
||||
only checks readiness once — restart, or trigger syncs by hand.
|
||||
- **Claude's output is never parsed here.** Prompts, the markdown-fence
|
||||
stripping and the JSON parsing are all in the Python service; this side
|
||||
receives typed JSON or an error (see
|
||||
[Calling the Python service](#calling-the-python-service)).
|
||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
||||
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
||||
@@ -253,15 +330,15 @@ generated struct rather than the model you expected.
|
||||
| `SEED_DB` | seed dev test data (never in production) |
|
||||
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
||||
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
||||
| `CLAUDE_API_KEY` | Anthropic API (email pipeline; the python service reads it too) |
|
||||
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
|
||||
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
||||
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
||||
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
|
||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
||||
|
||||
Paths baked into the code, all inside mounted volumes so they survive a
|
||||
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
||||
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
|
||||
OAuth tokens).
|
||||
`/backend/fallback_music`, `/backend/token/` (the Spotify OAuth token).
|
||||
|
||||
`CLAUDE_API_KEY` is not in the table: the backend does not read it. The
|
||||
`python` and `jobs` containers, the two that use it, get it through their
|
||||
explicit `environment:` lists in `docker-compose.yml`. The email and job-lead variables still in `.env` belong to the job
|
||||
tracker (`jobs`), which has its own repo and README.
|
||||
|
||||
+12
-5
@@ -4,7 +4,9 @@ go 1.26
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.95
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -19,6 +21,15 @@ require (
|
||||
|
||||
require (
|
||||
github.com/agnivade/levenshtein v1.2.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
|
||||
github.com/aws/smithy-go v1.28.5 // indirect
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
@@ -49,10 +60,6 @@ require (
|
||||
github.com/quic-go/qpack v0.5.1 // indirect
|
||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||
github.com/sosodev/duration v1.4.0 // indirect
|
||||
github.com/tidwall/gjson v1.18.0 // indirect
|
||||
github.com/tidwall/match v1.1.1 // indirect
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||
go.uber.org/mock v0.5.0 // indirect
|
||||
|
||||
+24
-16
@@ -37,10 +37,32 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
|
||||
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys=
|
||||
github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
|
||||
github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
@@ -60,8 +82,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||
@@ -205,16 +225,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||
@@ -522,8 +532,6 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||
|
||||
+59
-12
@@ -16,9 +16,16 @@ resolver:
|
||||
filename_template: "{name}.resolvers.go"
|
||||
|
||||
models:
|
||||
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
|
||||
# picks where it has a free choice — resolver arguments stay `id int`.
|
||||
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
|
||||
# with no hand-written resolver converting it. Both write an id as a quoted
|
||||
# decimal string ("12") and read a string or a number, so which one a field
|
||||
# uses is invisible on the wire.
|
||||
ID:
|
||||
model:
|
||||
- github.com/99designs/gqlgen/graphql.IntID
|
||||
- github.com/99designs/gqlgen/graphql.UintID
|
||||
User:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.User
|
||||
@@ -27,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
|
||||
@@ -63,21 +74,57 @@ models:
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobApplication:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobApplication
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
JobAppReference:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.JobAppReference
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Place:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Place
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Box:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Box
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Page:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Page
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Background:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Background
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
Layout:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Layout
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
boxCount:
|
||||
resolver: true
|
||||
hasBackground:
|
||||
resolver: true
|
||||
Component:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.Component
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
uses:
|
||||
resolver: true
|
||||
CoverLetter:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.CoverLetter
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
CoverSnippet:
|
||||
model:
|
||||
- adam-french.co.uk/backend/models.CoverSnippet
|
||||
fields:
|
||||
deletedAt:
|
||||
resolver: false
|
||||
|
||||
@@ -7,24 +7,16 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateActivity is the resolver for the createActivity field.
|
||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Admin-only, but there is no check to see here: the field is marked
|
||||
// @admin in the schema and the directive (directives.go) has already
|
||||
// refused anyone else by the time this runs.
|
||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -41,8 +33,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
||||
}
|
||||
return ptrs(activities), nil
|
||||
}
|
||||
|
||||
// Activity returns ActivityResolver implementation.
|
||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
||||
|
||||
type activityResolver struct{ *Resolver }
|
||||
|
||||
@@ -121,6 +121,9 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
||||
|
||||
// Me is the resolver for the me field.
|
||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||
// Checked here rather than with @signedIn because the message differs:
|
||||
// this query has always answered "unauthorized", and the directive's is
|
||||
// "authentication required".
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// SetBackground is the resolver for the setBackground field.
|
||||
func (r *mutationResolver) SetBackground(ctx context.Context, page string, input model.BackgroundInput) (*models.Background, error) {
|
||||
// One row per page: replaced in place if there is one, so its id stays
|
||||
// stable for the store on the front end.
|
||||
bg, err := backgroundFrom(page, input)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var existing models.Background
|
||||
err = r.Store.DB.Where("page = ?", page).First(&existing).Error
|
||||
switch {
|
||||
case err == nil:
|
||||
bg.ID, bg.CreatedAt = existing.ID, existing.CreatedAt
|
||||
err = r.Store.DB.Save(&bg).Error
|
||||
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||
err = r.Store.DB.Create(&bg).Error
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &bg, nil
|
||||
}
|
||||
|
||||
// ClearBackground is the resolver for the clearBackground field.
|
||||
func (r *mutationResolver) ClearBackground(ctx context.Context, page string) (bool, error) {
|
||||
res := r.Store.DB.Where("page = ?", page).Delete(&models.Background{})
|
||||
return res.RowsAffected > 0, res.Error
|
||||
}
|
||||
|
||||
// Background is the resolver for the background field.
|
||||
func (r *queryResolver) Background(ctx context.Context, page string) (*models.Background, error) {
|
||||
// Null, not an error, when the page has none: that is the default look.
|
||||
// Hidden along with an adminOnly page, like its boxes.
|
||||
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
|
||||
if err != nil || hidden {
|
||||
return nil, err
|
||||
}
|
||||
var bg models.Background
|
||||
err = r.Store.DB.Where("page = ?", page).First(&bg).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &bg, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for background.resolvers.go, kept out of the resolver
|
||||
// file for the same reason as box_helpers.go.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// The SPA puts these values straight into a style binding, as
|
||||
// `background-color` and `url("<image>")`. Vue sets them through the CSSOM,
|
||||
// so nothing can escape into other properties, but a quote or bracket in the
|
||||
// image could still end the url() early — hence the narrow shapes.
|
||||
var (
|
||||
// A hex colour, a colour name, or one of the colour functions — named,
|
||||
// so that url() and friends don't pass as a "function".
|
||||
bgColorPattern = regexp.MustCompile(`^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+|(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z.,%/ -]*\))$`)
|
||||
// A site path (an upload, /img/...) or an http(s) URL, with no quotes,
|
||||
// brackets, backslashes or spaces.
|
||||
bgImagePattern = regexp.MustCompile(`^(/|https?://)[^\s"'()\\<>]*$`)
|
||||
)
|
||||
|
||||
const maxBgImageLen = 1000
|
||||
|
||||
var bgFits = map[string]bool{"cover": true, "contain": true, "tile": true}
|
||||
|
||||
// backgroundFrom validates input into a Background for page.
|
||||
func backgroundFrom(page string, input model.BackgroundInput) (models.Background, error) {
|
||||
bg := models.Background{
|
||||
Page: page,
|
||||
Color: strings.TrimSpace(input.Color),
|
||||
Image: strings.TrimSpace(input.Image),
|
||||
Fit: input.Fit,
|
||||
}
|
||||
if !validPageKey(page) {
|
||||
return bg, errors.New("a background needs a valid page")
|
||||
}
|
||||
if bg.Color != "" && (len(bg.Color) > 64 || !bgColorPattern.MatchString(bg.Color)) {
|
||||
return bg, errors.New(`colour must be a CSS colour such as #1b110e, black or rgb(0 0 0 / 50%)`)
|
||||
}
|
||||
if bg.Image != "" && (len(bg.Image) > maxBgImageLen || !bgImagePattern.MatchString(bg.Image)) {
|
||||
return bg, errors.New("image must be a path on this site (e.g. /uploads/...) or an http(s) URL, without spaces or quotes")
|
||||
}
|
||||
if !bgFits[bg.Fit] {
|
||||
return bg, errors.New(`fit must be "cover", "contain" or "tile"`)
|
||||
}
|
||||
return bg, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
)
|
||||
|
||||
func TestBackgroundFrom(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
page string
|
||||
input model.BackgroundInput
|
||||
ok bool
|
||||
}{
|
||||
{"index", model.BackgroundInput{Color: "#102030", Fit: "cover"}, true},
|
||||
{"shrines/gto", model.BackgroundInput{Image: "/uploads/abc.gif", Fit: "tile"}, true},
|
||||
{"stp", model.BackgroundInput{Color: "rgb(0 0 0 / 50%)", Image: "https://example.com/a.png", Fit: "contain"}, true},
|
||||
{"index", model.BackgroundInput{Color: "rebeccapurple", Fit: "cover"}, true},
|
||||
{"index", model.BackgroundInput{Fit: "cover"}, true}, // plain theme colour
|
||||
{"Index", model.BackgroundInput{Fit: "cover"}, false}, // bad page key
|
||||
{"index", model.BackgroundInput{Fit: "stretch"}, false}, // unknown fit
|
||||
{"index", model.BackgroundInput{Color: "red; color: blue", Fit: "cover"}, false},
|
||||
{"index", model.BackgroundInput{Color: "url(/x.png)", Fit: "cover"}, false}, // an image in disguise
|
||||
{"index", model.BackgroundInput{Image: `/x.png") , url("/y`, Fit: "cover"}, false},
|
||||
{"index", model.BackgroundInput{Image: "javascript:alert(1)", Fit: "cover"}, false},
|
||||
{"index", model.BackgroundInput{Image: "uploads/relative.png", Fit: "cover"}, false},
|
||||
} {
|
||||
_, err := backgroundFrom(c.page, c.input)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("backgroundFrom(%q, %+v) = %v, want ok=%v", c.page, c.input, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,22 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateBookmark is the resolver for the createBookmark field.
|
||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -32,9 +23,6 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
|
||||
|
||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Loaded first so the deleted record can be returned to the client, and
|
||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
||||
@@ -56,8 +44,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
||||
}
|
||||
return ptrs(bookmarks), nil
|
||||
}
|
||||
|
||||
// Bookmark returns BookmarkResolver implementation.
|
||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
||||
|
||||
type bookmarkResolver struct{ *Resolver }
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// CreateBox is the resolver for the createBox field.
|
||||
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
|
||||
// Framed defaults to true here rather than in the gorm tag — see the
|
||||
// comment on models.Box.Framed. Sizes not supplied fall back to the
|
||||
// same 300x200 the column defaults use.
|
||||
box := models.Box{
|
||||
Page: input.Page,
|
||||
Kind: input.Kind,
|
||||
Widget: input.Widget,
|
||||
HTML: input.HTML,
|
||||
Title: input.Title,
|
||||
W: 300,
|
||||
H: 200,
|
||||
Framed: true,
|
||||
}
|
||||
setInt(&box.X, input.X)
|
||||
setInt(&box.Y, input.Y)
|
||||
setInt(&box.W, input.W)
|
||||
setInt(&box.H, input.H)
|
||||
setInt(&box.Z, input.Z)
|
||||
if input.Framed != nil {
|
||||
box.Framed = *input.Framed
|
||||
}
|
||||
if input.Shadow != nil {
|
||||
box.Shadow = *input.Shadow
|
||||
}
|
||||
if input.HideOnMobile != nil {
|
||||
box.HideOnMobile = *input.HideOnMobile
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
box.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
// A linked box takes its html from the component, so its own is
|
||||
// dropped rather than stored as a copy that would quietly go stale.
|
||||
if input.ComponentID != nil {
|
||||
id := uint(*input.ComponentID)
|
||||
exists, err := componentExists(r.Store.DB, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, errors.New("there is no such component")
|
||||
}
|
||||
box.Kind = "html"
|
||||
box.Widget = nil
|
||||
box.HTML = nil
|
||||
box.ComponentID = &id
|
||||
}
|
||||
if err := validateBox(&box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Create(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
// UpdateBox is the resolver for the updateBox field.
|
||||
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
|
||||
// Partial update: nil fields are left alone. The canvas sends only the
|
||||
// geometry after a drag and only the html after an edit, so this is
|
||||
// what keeps the two from overwriting each other. Kind is not
|
||||
// updatable — switching a widget box to html is a delete and create.
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Widget != nil {
|
||||
box.Widget = input.Widget
|
||||
}
|
||||
if input.HTML != nil {
|
||||
// A linked box's html is the component's; changing it here would
|
||||
// only fork a copy. The editor sends it to updateComponent instead.
|
||||
if box.ComponentID != nil {
|
||||
return nil, errors.New("that box is linked to a component: edit the component, or detach the box first")
|
||||
}
|
||||
box.HTML = input.HTML
|
||||
}
|
||||
if input.Title != nil {
|
||||
box.Title = input.Title
|
||||
}
|
||||
setInt(&box.X, input.X)
|
||||
setInt(&box.Y, input.Y)
|
||||
setInt(&box.W, input.W)
|
||||
setInt(&box.H, input.H)
|
||||
setInt(&box.Z, input.Z)
|
||||
if input.Framed != nil {
|
||||
box.Framed = *input.Framed
|
||||
}
|
||||
if input.Shadow != nil {
|
||||
box.Shadow = *input.Shadow
|
||||
}
|
||||
if input.HideOnMobile != nil {
|
||||
box.HideOnMobile = *input.HideOnMobile
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
box.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
if err := validateBox(&box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Save(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
// DeleteBox is the resolver for the deleteBox field.
|
||||
func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box, error) {
|
||||
var box models.Box
|
||||
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.Store.DB.Delete(&box).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &box, nil
|
||||
}
|
||||
|
||||
// Boxes is the resolver for the boxes field.
|
||||
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
|
||||
// Public: this is the page layout every visitor loads. Ordered by z so
|
||||
// DOM order matches stacking order, which keeps tab order sensible.
|
||||
//
|
||||
// What is admin-only is filtered here rather than hidden in the browser,
|
||||
// so a private note never reaches anyone else: an adminOnly page answers
|
||||
// with no boxes at all, and adminOnly boxes are left out of the rest.
|
||||
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if hidden {
|
||||
return []*models.Box{}, nil
|
||||
}
|
||||
query := r.Store.DB.Where("page = ?", page)
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
query = query.Where("admin_only = ?", false)
|
||||
}
|
||||
var boxes []models.Box
|
||||
if err := query.Order("z ASC, id ASC").Find(&boxes).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := fillLinked(r.Store.DB, boxes); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(boxes), nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for box.resolvers.go. Kept out of that file because
|
||||
// gqlgen moves unknown code in a resolvers file to the end, under a warning
|
||||
// comment, on every regenerate.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// minBoxSize stops a box being resized to nothing, after which it could not
|
||||
// be grabbed again on the canvas.
|
||||
const minBoxSize = 40
|
||||
|
||||
// maxShadowLen bounds a box's shadow, which is a single CSS value: even a
|
||||
// stack of a few comma-separated shadows is well under it.
|
||||
const maxShadowLen = 200
|
||||
|
||||
func setInt(dst *int, src *int) {
|
||||
if src != nil {
|
||||
*dst = *src
|
||||
}
|
||||
}
|
||||
|
||||
// validateBox checks the fields a box needs to render and clamps geometry
|
||||
// rather than rejecting it, because a drag that overshoots the canvas edge
|
||||
// should land at the edge, not fail.
|
||||
func validateBox(box *models.Box) error {
|
||||
if !validPageKey(box.Page) {
|
||||
return errors.New("a box needs a valid page")
|
||||
}
|
||||
switch box.Kind {
|
||||
case "widget":
|
||||
if box.Widget == nil || *box.Widget == "" {
|
||||
return errors.New("a widget box needs a widget name")
|
||||
}
|
||||
case "html":
|
||||
// A linked box's html lives on its component (fillLinked).
|
||||
if box.HTML == nil && box.ComponentID == nil {
|
||||
return errors.New("an html box needs html")
|
||||
}
|
||||
default:
|
||||
return errors.New(`box kind must be "widget" or "html"`)
|
||||
}
|
||||
if box.ComponentID != nil && box.Kind != "html" {
|
||||
return errors.New("only an html box can be linked to a component")
|
||||
}
|
||||
if err := validateShadow(&box.Shadow); err != nil {
|
||||
return err
|
||||
}
|
||||
box.X = max(box.X, 0)
|
||||
box.Y = max(box.Y, 0)
|
||||
box.W = max(box.W, minBoxSize)
|
||||
box.H = max(box.H, minBoxSize)
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateShadow trims a box-shadow value and bounds its length. The value is
|
||||
// not parsed: the front end sets it through a style binding, so it can only
|
||||
// ever be the one property, and an invalid value just draws no shadow.
|
||||
func validateShadow(shadow *string) error {
|
||||
*shadow = strings.TrimSpace(*shadow)
|
||||
if len(*shadow) > maxShadowLen {
|
||||
return fmt.Errorf("a shadow is at most %d characters", maxShadowLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
func TestValidateBox(t *testing.T) {
|
||||
str := func(s string) *string { return &s }
|
||||
one := uint(1)
|
||||
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
box models.Box
|
||||
wantErr bool
|
||||
}{
|
||||
{"widget with a name", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat")}, false},
|
||||
{"widget without a name", models.Box{Page: "stp", Kind: "widget"}, true},
|
||||
{"widget with an empty name", models.Box{Page: "stp", Kind: "widget", Widget: str("")}, true},
|
||||
{"html with html", models.Box{Page: "stp", Kind: "html", HTML: str("<p>hi</p>")}, false},
|
||||
{"html with empty html", models.Box{Page: "stp", Kind: "html", HTML: str("")}, false},
|
||||
{"html without html", models.Box{Page: "stp", Kind: "html"}, true},
|
||||
{"linked html without html", models.Box{Page: "stp", Kind: "html", ComponentID: &one}, false},
|
||||
{"linked widget", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), ComponentID: &one}, true},
|
||||
{"no page", models.Box{Kind: "widget", Widget: str("Chat")}, true},
|
||||
{"bad page", models.Box{Page: "Shrines/GTO", Kind: "widget", Widget: str("Chat")}, true},
|
||||
{"unknown kind", models.Box{Page: "stp", Kind: "iframe", HTML: str("x")}, true},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
err := validateBox(&c.box)
|
||||
if (err != nil) != c.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Geometry is clamped, not rejected: a drag past the canvas edge lands
|
||||
// at the edge, and a box can never shrink below a grabbable size.
|
||||
box := models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), X: -30, Y: -1, W: 5, H: 0}
|
||||
if err := validateBox(&box); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if box.X != 0 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize {
|
||||
t.Fatalf("clamped to %d,%d %dx%d; want 0,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize)
|
||||
}
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,8 @@ const (
|
||||
|
||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
||||
// not an error here, because many queries are public.
|
||||
// not an error here, because many queries are public. Turning "anonymous"
|
||||
// into a refusal is the job of the schema directives, per field.
|
||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||
if !ok {
|
||||
@@ -38,6 +39,10 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||
|
||||
// UserIDFromCtx returns the authenticated user's id. The claim arrives as a
|
||||
// float64 because claims are decoded by encoding/json, hence the conversion.
|
||||
//
|
||||
// ok is also the test behind the @signedIn directive. A resolver calls this
|
||||
// itself when it needs the id for more than a gate: to record a post's
|
||||
// author, or to compare the caller with a row's owner.
|
||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
@@ -50,11 +55,12 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||
return uint(idF), true
|
||||
}
|
||||
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
||||
// the authorisation check for nearly every mutation — there is no middleware
|
||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
||||
// flag only bites once the access token expires.
|
||||
// IsAdminFromCtx reports whether the request carries an admin token. It is
|
||||
// what the @admin directive tests (directives.go), which is how nearly every
|
||||
// mutation is authorised; resolvers call it directly only for the softer
|
||||
// cases a directive cannot express, such as the messages query filtering
|
||||
// rather than refusing. Admin comes from the token, not the database, so a
|
||||
// revoked admin flag only bites once the access token expires.
|
||||
func IsAdminFromCtx(ctx context.Context) bool {
|
||||
claims := UserClaimsFromCtx(ctx)
|
||||
if claims == nil {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
)
|
||||
|
||||
// The schema's two authorisation directives. A field marked @admin or
|
||||
// @signedIn in graph/schema/*.graphql has the matching function here run
|
||||
// before its resolver; if it returns an error the resolver is never called
|
||||
// and the error is what the client receives for that field.
|
||||
//
|
||||
// This replaces a check that used to be copied into the top of every guarded
|
||||
// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx /
|
||||
// UserIDFromCtx test against the claims AuthContextMiddleware verified — but
|
||||
// it is now declared next to the field, where a missing one can be seen and
|
||||
// tested for (directives_test.go), instead of being a line someone has to
|
||||
// remember to paste.
|
||||
//
|
||||
// The two error strings are part of the contract with the front end, which
|
||||
// shows them as they are; the tracker page, for one, explains "admin access
|
||||
// required" as a lapsed session. Do not reword them.
|
||||
//
|
||||
// This file is hand-written and never touched by gqlgen.
|
||||
|
||||
const (
|
||||
errAdminRequired = "admin access required"
|
||||
errSignedInRequired = "authentication required"
|
||||
)
|
||||
|
||||
// Directives is the set gqlgen needs in graph.Config. It is a function so
|
||||
// that main and the tests wire exactly the same implementations.
|
||||
//
|
||||
// Leaving a directive nil in the Config does not open the fields that use it:
|
||||
// the generated code answers "directive admin is not implemented" for each.
|
||||
func Directives() DirectiveRoot {
|
||||
return DirectiveRoot{
|
||||
Admin: requireAdmin,
|
||||
SignedIn: requireSignedIn,
|
||||
}
|
||||
}
|
||||
|
||||
// requireAdmin implements @admin: the request must carry an access token
|
||||
// whose admin claim is true. Admin comes from the token, not the database, so
|
||||
// demoting a user only bites once their access token is replaced.
|
||||
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf(errAdminRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
|
||||
// requireSignedIn implements @signedIn: any verified access token will do,
|
||||
// admin or not. An admin is signed in, so this never needs pairing with
|
||||
// @admin.
|
||||
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf(errSignedInRequired)
|
||||
}
|
||||
return next(ctx)
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
package graph
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/99designs/gqlgen/graphql/handler"
|
||||
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/vektah/gqlparser/v2/ast"
|
||||
|
||||
"adam-french.co.uk/backend/handlers"
|
||||
)
|
||||
|
||||
// Authorisation is declared in the schema (@admin / @signedIn) and enforced
|
||||
// by directives.go. These tests cover both halves: that the two functions
|
||||
// decide correctly, and that the schema marks the fields it should — the
|
||||
// second being the one that matters day to day, since the way this goes
|
||||
// wrong is a new field added without a directive.
|
||||
//
|
||||
// Nothing here needs a database: a refused field never reaches its resolver,
|
||||
// and the tests only ever drive fields that are refused or that return before
|
||||
// touching the Store.
|
||||
|
||||
// withClaims builds the context AuthContextMiddleware would for a verified
|
||||
// token. Claims are decoded from JSON in production, hence float64 for the id.
|
||||
func withClaims(id float64, admin bool) context.Context {
|
||||
claims := jwt.MapClaims{"id": id, "admin": admin}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}
|
||||
|
||||
func TestDirectives(t *testing.T) {
|
||||
anonymous := context.Background()
|
||||
user := withClaims(2, false)
|
||||
admin := withClaims(1, true)
|
||||
// A token that verified but carries no id: not something GenerateJWT
|
||||
// mints, but it must not count as signed in.
|
||||
noID := func() context.Context {
|
||||
claims := jwt.MapClaims{"admin": false}
|
||||
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||
}()
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
directive func(context.Context, any, graphql.Resolver) (any, error)
|
||||
ctx context.Context
|
||||
wantErr string // "" means the resolver must run
|
||||
}{
|
||||
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
|
||||
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
|
||||
{"@admin admits an admin", requireAdmin, admin, ""},
|
||||
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
|
||||
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
|
||||
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
|
||||
{"@signedIn admits an admin", requireSignedIn, admin, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
called := false
|
||||
next := func(ctx context.Context) (any, error) {
|
||||
called = true
|
||||
return "resolved", nil
|
||||
}
|
||||
res, err := c.directive(c.ctx, nil, next)
|
||||
|
||||
if c.wantErr == "" {
|
||||
if err != nil || !called || res != "resolved" {
|
||||
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The exact strings are what the front end displays.
|
||||
if err == nil || err.Error() != c.wantErr {
|
||||
t.Fatalf("err = %v, want %q", err, c.wantErr)
|
||||
}
|
||||
if called {
|
||||
t.Fatal("the resolver ran for a refused request")
|
||||
}
|
||||
if res != nil {
|
||||
t.Fatalf("res = %v, want nil alongside the error", res)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Directives() must supply every directive the schema declares; a nil one
|
||||
// makes gqlgen fail each field that uses it.
|
||||
func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||
d := Directives()
|
||||
if d.Admin == nil || d.SignedIn == nil {
|
||||
t.Fatal("Directives() left a directive unimplemented")
|
||||
}
|
||||
}
|
||||
|
||||
// guardOf reports which authorisation directive a field carries: "admin",
|
||||
// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds
|
||||
// nothing to @admin) and fails the test rather than being quietly accepted.
|
||||
func guardOf(t *testing.T, field *ast.FieldDefinition) string {
|
||||
t.Helper()
|
||||
admin := field.Directives.ForName("admin") != nil
|
||||
signedIn := field.Directives.ForName("signedIn") != nil
|
||||
switch {
|
||||
case admin && signedIn:
|
||||
t.Errorf("%s carries both @admin and @signedIn", field.Name)
|
||||
return "admin"
|
||||
case admin:
|
||||
return "admin"
|
||||
case signedIn:
|
||||
return "signedIn"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func schemaUnderTest() *ast.Schema {
|
||||
return NewExecutableSchema(Config{}).Schema()
|
||||
}
|
||||
|
||||
// publicMutations is the complete list of mutations that anyone may call.
|
||||
// A mutation is public only by being named here, so adding one to the schema
|
||||
// without a directive fails TestEveryMutationIsGuarded until it is either
|
||||
// guarded or deliberately listed.
|
||||
//
|
||||
// All three are how a session is obtained or given up, so they cannot require
|
||||
// one: login checks a password, refreshToken checks the refresh cookie, and
|
||||
// logout is a no-op for a visitor who is not signed in.
|
||||
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||
|
||||
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
var seen []string
|
||||
for _, field := range schema.Mutation.Fields {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
seen = append(seen, field.Name)
|
||||
guard := guardOf(t, field)
|
||||
public := slices.Contains(publicMutations, field.Name)
|
||||
switch {
|
||||
case guard == "" && !public:
|
||||
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
|
||||
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
|
||||
case guard != "" && public:
|
||||
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
|
||||
}
|
||||
}
|
||||
// A renamed or removed mutation must not leave a stale exemption behind.
|
||||
for _, name := range publicMutations {
|
||||
if !slices.Contains(seen, name) {
|
||||
t.Errorf("publicMutations lists %s, which is not in the schema", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The mutations that need only a session rather than an admin. Pinned so that
|
||||
// loosening a mutation from @admin to @signedIn — which the test above would
|
||||
// accept — has to be done here too.
|
||||
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||
var got []string
|
||||
for _, field := range schemaUnderTest().Mutation.Fields {
|
||||
if guardOf(t, field) == "signedIn" {
|
||||
got = append(got, field.Name)
|
||||
}
|
||||
}
|
||||
sort.Strings(got)
|
||||
if !slices.Equal(got, want) {
|
||||
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// Queries are public by default — the home page is built from them — so the
|
||||
// rule cannot be "every field is guarded". Instead the guarded set is pinned
|
||||
// exactly: removing a directive from one of these, or adding a query that
|
||||
// exposes private data without one, has to be a visible change to this map.
|
||||
//
|
||||
// Three queries are sensitive to who is asking without being in it, because
|
||||
// they answer rather than refuse: `me` returns "unauthorized" itself,
|
||||
// `messages` filters out private rows for non-admins, and
|
||||
// `spotifyNeedsReauth` is false for non-admins.
|
||||
func TestGuardedQueriesArePinned(t *testing.T) {
|
||||
want := map[string]string{
|
||||
"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 {
|
||||
if strings.HasPrefix(field.Name, "__") {
|
||||
continue
|
||||
}
|
||||
if guard := guardOf(t, field); guard != "" {
|
||||
got[field.Name] = guard
|
||||
}
|
||||
}
|
||||
for name, guard := range want {
|
||||
if got[name] != guard {
|
||||
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
|
||||
}
|
||||
}
|
||||
for name, guard := range got {
|
||||
if _, ok := want[name]; !ok {
|
||||
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The directives are FIELD_DEFINITION only and are meant for the two root
|
||||
// types. One on an object's field would be enforced, but nothing above would
|
||||
// notice it being removed, so keep them where the tests look.
|
||||
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||
schema := schemaUnderTest()
|
||||
for name, def := range schema.Types {
|
||||
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
|
||||
continue
|
||||
}
|
||||
for _, field := range def.Fields {
|
||||
if guardOf(t, field) != "" {
|
||||
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// execute runs one operation through the real executable schema, wired the
|
||||
// way main wires it, and returns the response's error messages. The Store is
|
||||
// empty: every operation below is refused, or returns, before its resolver
|
||||
// would touch the database.
|
||||
func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string {
|
||||
t.Helper()
|
||||
srv := handler.New(NewExecutableSchema(Config{
|
||||
Resolvers: &Resolver{Store: &handlers.Store{}},
|
||||
Directives: Directives(),
|
||||
}))
|
||||
srv.AddTransport(transport.POST{})
|
||||
|
||||
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
srv.ServeHTTP(rec, req)
|
||||
|
||||
var resp struct {
|
||||
Errors []struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"errors"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decoding response %s: %v", rec.Body, err)
|
||||
}
|
||||
var messages []string
|
||||
for _, e := range resp.Errors {
|
||||
messages = append(messages, e.Message)
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
// End to end: the message a client receives for a refused field is the bare
|
||||
// string the resolvers used to return, with nothing wrapped around it.
|
||||
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
query string
|
||||
want string
|
||||
}{
|
||||
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
|
||||
{"non-admin admin query", withClaims(2, false), `{ users { id } }`, "admin access required"},
|
||||
{"anonymous admin mutation", context.Background(), `mutation { deleteBookmark(id: 1) { id } }`, "admin access required"},
|
||||
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
|
||||
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
|
||||
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
|
||||
// Not a directive, and a different message on purpose.
|
||||
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got := execute(t, c.ctx, c.query, nil)
|
||||
if !slices.Equal(got, []string{c.want}) {
|
||||
t.Fatalf("errors = %q, want exactly %q", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// IDs: the wire form must be what it was when every type had a hand-written
|
||||
// resolver returning int. Both marshallers write a quoted decimal string and
|
||||
// both read a string or a number.
|
||||
func TestUintIDWireFormatMatchesIntID(t *testing.T) {
|
||||
for _, id := range []uint{0, 1, 12, 4294967295} {
|
||||
var asUint, asInt bytes.Buffer
|
||||
graphql.MarshalUintID(id).MarshalGQL(&asUint)
|
||||
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
|
||||
if asUint.String() != asInt.String() {
|
||||
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
|
||||
}
|
||||
}
|
||||
if got := func() string {
|
||||
var b bytes.Buffer
|
||||
graphql.MarshalUintID(12).MarshalGQL(&b)
|
||||
return b.String()
|
||||
}(); got != `"12"` {
|
||||
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
|
||||
}
|
||||
}
|
||||
+28
-9
@@ -9,8 +9,11 @@
|
||||
// matching *.resolvers.go. Never edit those two generated files.
|
||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
||||
// structs in backend/models, so model/ holds only input and payload
|
||||
// types. That is also why almost every type has a hand-written ID
|
||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
||||
// types. A model's `ID uint` binds to `id: ID!` directly, because
|
||||
// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is
|
||||
// needed for it. A field resolver is only written where the Go type has
|
||||
// no binding (Message.authorId and Rowing's time/distance are unsigned in
|
||||
// Go and Int in the schema).
|
||||
// - Resolvers reach the database and the third-party caches through
|
||||
// Resolver.Store, the same handlers.Store the REST endpoints use.
|
||||
// - context.go and middleware.go carry the caller's identity from Gin into
|
||||
@@ -18,13 +21,29 @@
|
||||
//
|
||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
||||
// annotates the context and lets everything through, so each resolver checks
|
||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
||||
// check is fully public. The rule of thumb in this schema is that queries are
|
||||
// public and mutations are admin-only, with these exceptions: the job
|
||||
// application and job reference queries are admin-only (they are private
|
||||
// data), the places mutations need only a signed-in user, and the messages
|
||||
// query hides private messages from non-admins rather than refusing.
|
||||
// annotates the context and lets everything through. What guards a field is a
|
||||
// directive on it in the schema:
|
||||
//
|
||||
// createUser(input: CreateUserInput!): User! @admin
|
||||
// places: [Place!]! @signedIn
|
||||
//
|
||||
// @admin requires an admin's access token, @signedIn any valid one. Both are
|
||||
// implemented once, in directives.go, and run before the resolver, so a
|
||||
// guarded resolver contains no check of its own. A field with NEITHER
|
||||
// directive is fully public.
|
||||
//
|
||||
// The rule of thumb in this schema is that queries are public and mutations
|
||||
// are @admin, with these exceptions: login, logout and refreshToken are
|
||||
// public; the places mutations and query are @signedIn; and the users
|
||||
// queries are @admin (they are private data).
|
||||
// directives_test.go holds that list and fails when the schema departs from
|
||||
// it — in particular when a mutation is added with no directive.
|
||||
//
|
||||
// A directive is only a gate. Anything finer stays in the resolver and uses
|
||||
// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its
|
||||
// author, `me` answers for the caller (with its own "unauthorized" error),
|
||||
// the messages query hides private messages from non-admins rather than
|
||||
// refusing, and spotifyNeedsReauth is simply false for non-admins.
|
||||
//
|
||||
// The files ending in _helpers.go are hand-written and are not touched by
|
||||
// gqlgen; the *.resolvers.go files are partly generated, so anything added to
|
||||
|
||||
@@ -7,23 +7,13 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateFavorite is the resolver for the createFavorite field.
|
||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
||||
}
|
||||
return ptrs(favorites), nil
|
||||
}
|
||||
|
||||
// Favorite returns FavoriteResolver implementation.
|
||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
||||
|
||||
type favoriteResolver struct{ *Resolver }
|
||||
|
||||
+6292
-1418
File diff suppressed because it is too large
Load Diff
@@ -1,95 +0,0 @@
|
||||
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"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
ref := models.JobAppReference{
|
||||
Category: input.Category,
|
||||
Label: input.Label,
|
||||
Value: input.Value,
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Create(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var ref models.JobAppReference
|
||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.Category != nil {
|
||||
ref.Category = *input.Category
|
||||
}
|
||||
if input.Label != nil {
|
||||
ref.Label = *input.Label
|
||||
}
|
||||
if input.Value != nil {
|
||||
ref.Value = *input.Value
|
||||
}
|
||||
if input.SortOrder != nil {
|
||||
ref.SortOrder = *input.SortOrder
|
||||
}
|
||||
if err := r.Store.DB.Save(&ref).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &ref, nil
|
||||
}
|
||||
|
||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var refs []*models.JobAppReference
|
||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
||||
// default 0) keep a stable, insertion-ordered sequence.
|
||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return refs, nil
|
||||
}
|
||||
|
||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
||||
|
||||
type jobAppReferenceResolver struct{ *Resolver }
|
||||
@@ -1,148 +0,0 @@
|
||||
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"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// String! is non-null but not non-empty, and the columns are only
|
||||
// `not null`, so "" stores happily and then never matches the email
|
||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
||||
jobTitle := strings.TrimSpace(input.JobTitle)
|
||||
company := strings.TrimSpace(input.Company)
|
||||
if jobTitle == "" || company == "" {
|
||||
return nil, fmt.Errorf("jobTitle and company are required")
|
||||
}
|
||||
app := models.JobApplication{
|
||||
JobTitle: jobTitle,
|
||||
Company: company,
|
||||
Location: input.Location,
|
||||
URL: input.URL,
|
||||
Status: services.NormalizeStatus(input.Status),
|
||||
Notes: input.Notes,
|
||||
AppliedAt: input.AppliedAt,
|
||||
Description: input.Description,
|
||||
}
|
||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Partial update: every input field is a pointer so that "not supplied"
|
||||
// is distinguishable from "set to empty". A nil field is left untouched.
|
||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
||||
// empties a wrong URL or stale notes — but the same value on a required
|
||||
// column is rejected rather than blanking a live row.
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if input.JobTitle != nil {
|
||||
if strings.TrimSpace(*input.JobTitle) == "" {
|
||||
return nil, fmt.Errorf("jobTitle cannot be empty")
|
||||
}
|
||||
app.JobTitle = strings.TrimSpace(*input.JobTitle)
|
||||
}
|
||||
if input.Company != nil {
|
||||
if strings.TrimSpace(*input.Company) == "" {
|
||||
return nil, fmt.Errorf("company cannot be empty")
|
||||
}
|
||||
app.Company = strings.TrimSpace(*input.Company)
|
||||
}
|
||||
if input.Location != nil {
|
||||
app.Location = input.Location
|
||||
}
|
||||
if input.URL != nil {
|
||||
app.URL = input.URL
|
||||
}
|
||||
if input.Status != nil {
|
||||
app.Status = services.NormalizeStatus(*input.Status)
|
||||
}
|
||||
if input.Notes != nil {
|
||||
app.Notes = input.Notes
|
||||
}
|
||||
if input.AppliedAt != nil {
|
||||
app.AppliedAt = input.AppliedAt
|
||||
}
|
||||
if input.Description != nil {
|
||||
app.Description = input.Description
|
||||
}
|
||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Soft delete straight by id, without loading first — so deleting an id
|
||||
// that does not exist still returns true.
|
||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// JobApplications is the resolver for the jobApplications field.
|
||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
||||
// Admin-only even though it is a query: job applications are private.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
// Find can populate a slice of pointers directly, avoiding the
|
||||
// copy-to-pointers loop the other list resolvers need.
|
||||
var apps []*models.JobApplication
|
||||
// id is the tie-break: one sync loop inserts several rows inside the same
|
||||
// timestamp, and Postgres gives no stable order for equal sort keys, so
|
||||
// without it the list can reshuffle between two identical page loads.
|
||||
if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return apps, nil
|
||||
}
|
||||
|
||||
// JobApplication is the resolver for the jobApplication field.
|
||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var app models.JobApplication
|
||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &app, nil
|
||||
}
|
||||
|
||||
// JobApplication returns JobApplicationResolver implementation.
|
||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
||||
|
||||
type jobApplicationResolver struct{ *Resolver }
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
@@ -11,11 +11,6 @@ import (
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// AuthorID is the resolver for the authorId field.
|
||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
||||
// hub's per-connection counter, not a User id — see models.Message.
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
||||
// valid access token is present. Crucially it never rejects a request: a
|
||||
// missing, expired or forged token simply leaves the context anonymous, which
|
||||
// is what lets public queries work and pushes every authorisation decision
|
||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
||||
// errors are swallowed for exactly that reason.
|
||||
// is what lets public queries work and leaves every authorisation decision
|
||||
// to the field being resolved — the @admin / @signedIn directives on it (see
|
||||
// directives.go), or the resolver itself for anything finer. Both cookie and
|
||||
// verify errors are swallowed for exactly that reason.
|
||||
//
|
||||
// It takes the database because validating a token means loading the user to
|
||||
// compare token versions; see services.Auth.AuthenticateTokenWithClaims.
|
||||
|
||||
@@ -12,6 +12,12 @@ type AuthPayload struct {
|
||||
User *models.User `json:"user"`
|
||||
}
|
||||
|
||||
type BackgroundInput struct {
|
||||
Color string `json:"color"`
|
||||
Image string `json:"image"`
|
||||
Fit string `json:"fit"`
|
||||
}
|
||||
|
||||
type CreateActivityInput struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
@@ -24,28 +30,60 @@ type CreateBookmarkInput struct {
|
||||
Link string `json:"link"`
|
||||
}
|
||||
|
||||
type CreateBoxInput struct {
|
||||
Page string `json:"page"`
|
||||
Kind string `json:"kind"`
|
||||
Widget *string `json:"widget,omitempty"`
|
||||
HTML *string `json:"html,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
X *int `json:"x,omitempty"`
|
||||
Y *int `json:"y,omitempty"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Z *int `json:"z,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
Shadow *string `json:"shadow,omitempty"`
|
||||
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
ComponentID *int `json:"componentId,omitempty"`
|
||||
}
|
||||
|
||||
type CreateComponentInput struct {
|
||||
Name string `json:"name"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
HTML string `json:"html"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
Shadow *string `json:"shadow,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type CreateCoverLetterInput struct {
|
||||
Name string `json:"name"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
type CreateCoverSnippetInput struct {
|
||||
Text string `json:"text"`
|
||||
Section *string `json:"section,omitempty"`
|
||||
}
|
||||
|
||||
type CreateFavoriteInput struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Link *string `json:"link,omitempty"`
|
||||
}
|
||||
|
||||
type CreateJobAppReferenceInput struct {
|
||||
Category string `json:"category"`
|
||||
Label string `json:"label"`
|
||||
Value string `json:"value"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
type CreateLayoutInput struct {
|
||||
Name string `json:"name"`
|
||||
Page string `json:"page"`
|
||||
}
|
||||
|
||||
type CreateJobApplicationInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
type CreatePageInput struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type CreatePlaceInput struct {
|
||||
@@ -131,22 +169,50 @@ type SteamStatus struct {
|
||||
RecentGames []*SteamGame `json:"recentGames"`
|
||||
}
|
||||
|
||||
type UpdateJobAppReferenceInput struct {
|
||||
Category *string `json:"category,omitempty"`
|
||||
Label *string `json:"label,omitempty"`
|
||||
Value *string `json:"value,omitempty"`
|
||||
SortOrder *int `json:"sortOrder,omitempty"`
|
||||
type UpdateBoxInput struct {
|
||||
Widget *string `json:"widget,omitempty"`
|
||||
HTML *string `json:"html,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
X *int `json:"x,omitempty"`
|
||||
Y *int `json:"y,omitempty"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Z *int `json:"z,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
Shadow *string `json:"shadow,omitempty"`
|
||||
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateJobApplicationInput struct {
|
||||
JobTitle *string `json:"jobTitle,omitempty"`
|
||||
Company *string `json:"company,omitempty"`
|
||||
Location *string `json:"location,omitempty"`
|
||||
URL *string `json:"url,omitempty"`
|
||||
Status *string `json:"status,omitempty"`
|
||||
Notes *string `json:"notes,omitempty"`
|
||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
type UpdateComponentInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
HTML *string `json:"html,omitempty"`
|
||||
W *int `json:"w,omitempty"`
|
||||
H *int `json:"h,omitempty"`
|
||||
Framed *bool `json:"framed,omitempty"`
|
||||
Shadow *string `json:"shadow,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateCoverLetterInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Body *string `json:"body,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateCoverSnippetInput struct {
|
||||
Text *string `json:"text,omitempty"`
|
||||
Section *string `json:"section,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateLayoutInput struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePageInput struct {
|
||||
Slug *string `json:"slug,omitempty"`
|
||||
Title *string `json:"title,omitempty"`
|
||||
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||
}
|
||||
|
||||
type UpdatePlaceInput struct {
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package graph
|
||||
|
||||
// This file will be automatically regenerated based on the schema, any resolver
|
||||
// implementations
|
||||
// will be copied through when generating and any unknown code will be moved to the end.
|
||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CreatePage is the resolver for the createPage field.
|
||||
func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePageInput) (*models.Page, error) {
|
||||
page := models.Page{
|
||||
Slug: input.Slug,
|
||||
Title: strings.TrimSpace(input.Title),
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
page.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
if err := validateSlug(page.Slug); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if page.Title == "" {
|
||||
return nil, errors.New("a page needs a title")
|
||||
}
|
||||
taken, err := slugTaken(r.Store.DB, page.Slug, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if taken {
|
||||
return nil, errors.New("there is already a page at that address")
|
||||
}
|
||||
if err := r.Store.DB.Create(&page).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &page, nil
|
||||
}
|
||||
|
||||
// UpdatePage is the resolver for the updatePage field.
|
||||
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
|
||||
// Partial update, like updateBox. A new slug moves the page's boxes and
|
||||
// background with it in the same transaction, since both find their page
|
||||
// by slug.
|
||||
var page models.Page
|
||||
if err := r.Store.DB.First(&page, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
oldSlug := page.Slug
|
||||
if input.Slug != nil {
|
||||
page.Slug = *input.Slug
|
||||
}
|
||||
if input.Title != nil {
|
||||
page.Title = strings.TrimSpace(*input.Title)
|
||||
}
|
||||
if input.AdminOnly != nil {
|
||||
page.AdminOnly = *input.AdminOnly
|
||||
}
|
||||
if page.Title == "" {
|
||||
return nil, errors.New("a page needs a title")
|
||||
}
|
||||
if page.Slug != oldSlug {
|
||||
if err := validateSlug(page.Slug); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taken, err := slugTaken(r.Store.DB, page.Slug, page.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if taken {
|
||||
return nil, errors.New("there is already a page at that address")
|
||||
}
|
||||
}
|
||||
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if page.Slug != oldSlug {
|
||||
if err := tx.Model(&models.Box{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&models.Background{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Save(&page).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &page, nil
|
||||
}
|
||||
|
||||
// DeletePage is the resolver for the deletePage field.
|
||||
func (r *mutationResolver) DeletePage(ctx context.Context, id int) (*models.Page, error) {
|
||||
// The boxes and background go too: left behind, they would reappear on
|
||||
// any page later created at the same address.
|
||||
var page models.Page
|
||||
if err := r.Store.DB.First(&page, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("page = ?", page.Slug).Delete(&models.Box{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Where("page = ?", page.Slug).Delete(&models.Background{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&page).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &page, nil
|
||||
}
|
||||
|
||||
// Pages is the resolver for the pages field.
|
||||
func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
|
||||
// Public, for page indexes such as /shrines; adminOnly pages are only
|
||||
// listed for an admin.
|
||||
query := r.Store.DB.Order("slug ASC")
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
query = query.Where("admin_only = ?", false)
|
||||
}
|
||||
var pages []models.Page
|
||||
if err := query.Find(&pages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(pages), nil
|
||||
}
|
||||
|
||||
// Page is the resolver for the page field.
|
||||
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
|
||||
// Null, not an error, for a missing page: the SPA's catch-all route asks
|
||||
// this for every unknown path and shows its 404 on null. An adminOnly
|
||||
// page reads as missing to everyone else, so its existence isn't leaked.
|
||||
var page models.Page
|
||||
err := r.Store.DB.Where("slug = ?", slug).First(&page).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if page.AdminOnly && !IsAdminFromCtx(ctx) {
|
||||
return nil, nil
|
||||
}
|
||||
return &page, nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package graph
|
||||
|
||||
// Hand-written helpers for page.resolvers.go and box.resolvers.go, kept out
|
||||
// of the resolver files for the same reason as box_helpers.go.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// pageKeyPattern is the shape of a box's page key and of a page slug: lower
|
||||
// case words joined by hyphens, in one or more /-separated segments. It is
|
||||
// URL-safe as it stands, so the front end can use a slug as a path without
|
||||
// escaping it.
|
||||
var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`)
|
||||
|
||||
const maxSlugLen = 100
|
||||
|
||||
// reservedFirstSegments are paths a page could never be reached at, because
|
||||
// nginx or one of the SPA's own routes answers them first (see
|
||||
// nginx/nginx_routes.conf.template and vue/src/router/index.js), plus the
|
||||
// landing page's key "index", whose boxes a page of the same slug would
|
||||
// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine
|
||||
// pages under it and the home page /stp are all canvas pages.
|
||||
var reservedFirstSegments = map[string]bool{
|
||||
"stp2": true, "index": true, "admin": true, "cv": true,
|
||||
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
|
||||
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
|
||||
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
|
||||
"sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true,
|
||||
}
|
||||
|
||||
func validPageKey(key string) bool {
|
||||
return len(key) <= maxSlugLen && pageKeyPattern.MatchString(key)
|
||||
}
|
||||
|
||||
// validateSlug reports why slug can't be a page's address, or nil.
|
||||
func validateSlug(slug string) error {
|
||||
if !validPageKey(slug) {
|
||||
return errors.New("a page address is lower-case letters, digits and hyphens, in /-separated parts, e.g. shrines/evangelion")
|
||||
}
|
||||
first, _, _ := strings.Cut(slug, "/")
|
||||
if reservedFirstSegments[first] {
|
||||
return errors.New("that address is already used by the site")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageHiddenFrom reports whether the page with this key is an adminOnly page
|
||||
// and the caller is not an admin. A key with no Page row (the landing page,
|
||||
// or a page that doesn't exist) is not hidden.
|
||||
func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) {
|
||||
if IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
}
|
||||
var count int64
|
||||
err := db.Model(&models.Page{}).Where("slug = ? AND admin_only = ?", key, true).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
// slugTaken reports whether a live page other than exceptID has this slug.
|
||||
// Checked up front so the admin gets a sentence rather than a constraint
|
||||
// violation; the partial unique index still backs it up.
|
||||
func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) {
|
||||
var count int64
|
||||
err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package graph
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateSlug(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
slug string
|
||||
ok bool
|
||||
}{
|
||||
{"notes-to-self", true},
|
||||
{"shrines/evangelion", true},
|
||||
{"shrines/neon-genesis/rei2", true},
|
||||
{"", false},
|
||||
{"Shrines/GTO", false}, // upper case
|
||||
{"shrines/", false}, // empty segment
|
||||
{"/shrines/gto", false}, // leading slash
|
||||
{"shrines//gto", false}, // empty segment
|
||||
{"shrines/gto-", false}, // trailing hyphen
|
||||
{"shrines/../admin", false}, // dots
|
||||
{"shrines", true}, // the index is a canvas page too
|
||||
{"shrines/demoman", true}, // no longer an SPA route
|
||||
{"admin/pages", false}, // under an SPA route
|
||||
{"jobs/x", false}, // under an nginx route
|
||||
{"stp", true}, // the home page is a canvas page too
|
||||
{"stp2", false}, // an SPA route
|
||||
{"index", false}, // the landing canvas's key
|
||||
{"stp-fan-page", true}, // only whole segments are reserved
|
||||
} {
|
||||
err := validateSlug(c.slug)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("validateSlug(%q) = %v, want ok=%v", c.slug, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,6 @@ package graph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -16,11 +15,9 @@ import (
|
||||
// CreatePlace is the resolver for the createPlace field.
|
||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
||||
// Any signed-in user, not just an admin — places are the one shared,
|
||||
// collaboratively edited list on the site. There is no per-user
|
||||
// ownership, so any signed-in user can edit or delete any place.
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// collaboratively edited list on the site, so the schema marks these
|
||||
// fields @signedIn rather than @admin. There is no per-user ownership, so
|
||||
// any signed-in user can edit or delete any place.
|
||||
place := models.Place{
|
||||
Title: input.Title,
|
||||
Location: input.Location,
|
||||
@@ -43,9 +40,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
|
||||
|
||||
// UpdatePlace is the resolver for the updatePlace field.
|
||||
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
// Partial update, same pointer-means-supplied convention as job
|
||||
// applications: nil fields are left as they are.
|
||||
var place models.Place
|
||||
@@ -84,9 +78,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
||||
|
||||
// DeletePlace is the resolver for the deletePlace field.
|
||||
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var place models.Place
|
||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,24 +88,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
|
||||
return &place, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Places is the resolver for the places field.
|
||||
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||
return nil, fmt.Errorf("authentication required")
|
||||
}
|
||||
var places []models.Place
|
||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ptrs(places), nil
|
||||
}
|
||||
|
||||
// Place returns PlaceResolver implementation.
|
||||
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
|
||||
|
||||
type placeResolver struct{ *Resolver }
|
||||
|
||||
@@ -8,6 +8,7 @@ package graph
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/graph/model"
|
||||
"adam-french.co.uk/backend/models"
|
||||
@@ -15,15 +16,20 @@ import (
|
||||
|
||||
// CreatePost is the resolver for the createPost field.
|
||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// @admin has already established that there is a session; the id is read
|
||||
// here because the post needs an author, not as a second gate. The !ok
|
||||
// branch is only reachable with a token that has admin but no usable id.
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
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
|
||||
@@ -34,10 +40,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
|
||||
|
||||
// UpdatePost is the resolver for the updatePost field.
|
||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -48,8 +50,9 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
return nil, fmt.Errorf("post not found")
|
||||
}
|
||||
|
||||
// Admin alone is not enough: a post may only be edited by its author, so
|
||||
// one admin cannot rewrite another's posts.
|
||||
// Admin alone (the @admin on the field) is not enough: a post may only be
|
||||
// edited by its author, so one admin cannot rewrite another's posts. This
|
||||
// is the kind of rule a directive cannot express, so it stays here.
|
||||
if post.AuthorID != userID {
|
||||
return nil, fmt.Errorf("you can only update your own posts")
|
||||
}
|
||||
@@ -67,10 +70,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
||||
|
||||
// DeletePost is the resolver for the deletePost field.
|
||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
userID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -95,11 +94,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Posts is the resolver for the posts field.
|
||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||
// Preload issues a second query for the authors and fills in Post.Author.
|
||||
@@ -120,8 +114,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
|
||||
}
|
||||
return &post, nil
|
||||
}
|
||||
|
||||
// Post returns PostResolver implementation.
|
||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
||||
|
||||
type postResolver struct{ *Resolver }
|
||||
|
||||
@@ -12,10 +12,12 @@ import "adam-french.co.uk/backend/handlers"
|
||||
// same handlers.Store the REST handlers use, so GraphQL and REST share one
|
||||
// database handle and one set of third-party caches.
|
||||
//
|
||||
// The generated code embeds *Resolver in per-type resolver structs
|
||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
||||
// resolvers file.
|
||||
// The generated code embeds *Resolver in per-type resolver structs, which is
|
||||
// why one-line `struct{ *Resolver }` declarations appear at the bottom of some
|
||||
// resolvers files. A type only gets one when a field of it needs a resolver:
|
||||
// queryResolver and mutationResolver always, messageResolver and
|
||||
// rowingResolver for their unsigned-to-Int fields. Most object types bind
|
||||
// every field straight to the model and have none.
|
||||
type Resolver struct {
|
||||
Store *handlers.Store
|
||||
}
|
||||
|
||||
@@ -20,11 +20,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
||||
return ptrs(rows), nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||
return int(obj.ID), nil
|
||||
}
|
||||
|
||||
// Time is the resolver for the time field.
|
||||
// Time is the resolver for the time field: total session seconds, narrowed
|
||||
// from uint64 to GraphQL's Int.
|
||||
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createActivity(input: CreateActivityInput!): Activity!
|
||||
createActivity(input: CreateActivityInput!): Activity! @admin
|
||||
}
|
||||
|
||||
@@ -7,10 +7,14 @@ type AuthPayload {
|
||||
user: User!
|
||||
}
|
||||
|
||||
# `me` carries no directive although it needs a session: it answers
|
||||
# "unauthorized", not @signedIn's "authentication required", and the front end
|
||||
# relies on that query failing quietly for an anonymous visitor.
|
||||
extend type Query {
|
||||
me: User
|
||||
}
|
||||
|
||||
# Deliberately public: these are how a session is obtained and given up.
|
||||
extend type Mutation {
|
||||
login(input: LoginInput!): AuthPayload!
|
||||
logout: Boolean!
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# The background behind a canvas page, keyed by the same page key as its
|
||||
# boxes ("index" for the landing page, or a Page's slug), so the landing
|
||||
# page and every other canvas page are set the same way. Edited from the
|
||||
# canvas's "Background" button; see models.Background.
|
||||
#
|
||||
# Anyone may read it, as part of the page, except that an adminOnly page's
|
||||
# background is null to everyone but an admin.
|
||||
|
||||
type Background {
|
||||
id: ID!
|
||||
updatedAt: Time!
|
||||
page: String!
|
||||
# A CSS colour, or "" for the theme's page colour.
|
||||
color: String!
|
||||
# An image URL, or "" for none.
|
||||
image: String!
|
||||
# "cover", "contain" or "tile".
|
||||
fit: String!
|
||||
}
|
||||
|
||||
input BackgroundInput {
|
||||
color: String!
|
||||
image: String!
|
||||
fit: String!
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
# Null when the page has none, i.e. shows the theme's default.
|
||||
background(page: String!): Background
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
# Creates or replaces the page's background.
|
||||
setBackground(page: String!, input: BackgroundInput!): Background! @admin
|
||||
# Back to the theme's default. True if there was one to remove.
|
||||
clearBackground(page: String!): Boolean! @admin
|
||||
}
|
||||
@@ -18,6 +18,6 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
||||
deleteBookmark(id: ID!): Bookmark!
|
||||
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
|
||||
deleteBookmark(id: ID!): Bookmark! @admin
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# Boxes on a canvas page: the landing page (page "index") or an
|
||||
# admin-created Page (page = its slug; the home page /stp is the Page "stp").
|
||||
# Anyone may read a page's layout — it is the page — but only an admin may
|
||||
# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h
|
||||
# are px on a fixed 1400px-wide design canvas; see models.Box.
|
||||
#
|
||||
# kind is "widget" (a built-in Vue component named by `widget`) or "html"
|
||||
# (`html` rendered in a sandboxed iframe on the front end). An html box with a
|
||||
# componentId is linked to that Component: its html is the component's, and
|
||||
# updateBox refuses to change it (component.graphql).
|
||||
|
||||
type Box {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
page: String!
|
||||
kind: String!
|
||||
widget: String
|
||||
html: String
|
||||
title: String
|
||||
x: Int!
|
||||
y: Int!
|
||||
w: Int!
|
||||
h: Int!
|
||||
z: Int!
|
||||
framed: Boolean!
|
||||
# A CSS box-shadow value, or "" for none.
|
||||
shadow: String!
|
||||
hideOnMobile: Boolean!
|
||||
adminOnly: Boolean!
|
||||
componentId: ID
|
||||
}
|
||||
|
||||
input CreateBoxInput {
|
||||
page: String!
|
||||
kind: String!
|
||||
widget: String
|
||||
html: String
|
||||
title: String
|
||||
x: Int
|
||||
y: Int
|
||||
w: Int
|
||||
h: Int
|
||||
z: Int
|
||||
framed: Boolean
|
||||
shadow: String
|
||||
hideOnMobile: Boolean
|
||||
adminOnly: Boolean
|
||||
# Links the new box to this component; kind is then "html" and html is
|
||||
# ignored.
|
||||
componentId: ID
|
||||
}
|
||||
|
||||
input UpdateBoxInput {
|
||||
widget: String
|
||||
html: String
|
||||
title: String
|
||||
x: Int
|
||||
y: Int
|
||||
w: Int
|
||||
h: Int
|
||||
z: Int
|
||||
framed: Boolean
|
||||
shadow: String
|
||||
hideOnMobile: Boolean
|
||||
adminOnly: Boolean
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
boxes(page: String!): [Box!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createBox(input: CreateBoxInput!): Box! @admin
|
||||
updateBox(id: ID!, input: UpdateBoxInput!): Box! @admin
|
||||
deleteBox(id: ID!): Box! @admin
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -18,5 +18,5 @@ extend type Query {
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
||||
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
|
||||
}
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
type JobAppReference {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int!
|
||||
}
|
||||
|
||||
input CreateJobAppReferenceInput {
|
||||
category: String!
|
||||
label: String!
|
||||
value: String!
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
input UpdateJobAppReferenceInput {
|
||||
category: String
|
||||
label: String
|
||||
value: String
|
||||
sortOrder: Int
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobAppReferences: [JobAppReference!]!
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
||||
deleteJobAppReference(id: ID!): Boolean!
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
# Job application tracker. Rows come from these mutations, automatically from
|
||||
# the email sync pipeline (backend/services/email_sync.go), or from the browser
|
||||
# capture userscript (backend/handlers/handle_job_capture.go). These are
|
||||
# private data, so the queries here are admin-only as well as the mutations.
|
||||
#
|
||||
# status is a free-form String, but only the values ranked in
|
||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
||||
# saved, applied, screening, assessment, interviewing, offer, rejected,
|
||||
# withdrawn.
|
||||
#
|
||||
# description is the captured posting text. It can run to tens of kilobytes,
|
||||
# so the tracker's list query leaves it out and asks for it per row.
|
||||
|
||||
type JobApplication {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input CreateJobApplicationInput {
|
||||
jobTitle: String!
|
||||
company: String!
|
||||
location: String
|
||||
url: String
|
||||
status: String!
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
input UpdateJobApplicationInput {
|
||||
jobTitle: String
|
||||
company: String
|
||||
location: String
|
||||
url: String
|
||||
status: String
|
||||
notes: String
|
||||
appliedAt: Time
|
||||
description: String
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
jobApplications: [JobApplication!]!
|
||||
jobApplication(id: ID!): JobApplication
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
||||
deleteJobApplication(id: ID!): Boolean!
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
#
|
||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||
# User id, and private messages are silently filtered out for non-admins
|
||||
# rather than causing an error.
|
||||
# rather than causing an error — which is why the query has no @admin: the
|
||||
# resolver makes that decision per row.
|
||||
|
||||
type Message {
|
||||
id: ID!
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Admin-created canvas pages. A page is just a slug and a title; its content
|
||||
# is the boxes whose `page` is the slug (see box.graphql). The SPA serves it
|
||||
# at /<slug> through its catch-all route, so a slug may not start with a path
|
||||
# the site already uses — see validateSlug in page_helpers.go.
|
||||
#
|
||||
# adminOnly pages, and their boxes, are invisible to everyone but an admin:
|
||||
# `page` answers null and `pages` leaves them out.
|
||||
|
||||
type Page {
|
||||
id: ID!
|
||||
createdAt: Time!
|
||||
updatedAt: Time!
|
||||
slug: String!
|
||||
title: String!
|
||||
adminOnly: Boolean!
|
||||
}
|
||||
|
||||
input CreatePageInput {
|
||||
slug: String!
|
||||
title: String!
|
||||
adminOnly: Boolean
|
||||
}
|
||||
|
||||
input UpdatePageInput {
|
||||
slug: String
|
||||
title: String
|
||||
adminOnly: Boolean
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
pages: [Page!]!
|
||||
page(slug: String!): Page
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPage(input: CreatePageInput!): Page! @admin
|
||||
# Renaming a page moves its boxes with it.
|
||||
updatePage(id: ID!, input: UpdatePageInput!): Page! @admin
|
||||
# Deletes the page's boxes too.
|
||||
deletePage(id: ID!): Page! @admin
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
||||
# not an admin, and there is no per-user ownership: the list is shared.
|
||||
# Places to go. Unlike most mutations these require only a signed-in user
|
||||
# (@signedIn), not an admin, and there is no per-user ownership: the list is
|
||||
# shared. The query is guarded too — the list is not public.
|
||||
|
||||
type Place {
|
||||
id: ID!
|
||||
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
places: [Place!]!
|
||||
places: [Place!]! @signedIn
|
||||
}
|
||||
|
||||
extend type Mutation {
|
||||
createPlace(input: CreatePlaceInput!): Place!
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
|
||||
deletePlace(id: ID!): Place!
|
||||
createPlace(input: CreatePlaceInput!): Place! @signedIn
|
||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
|
||||
deletePlace(id: ID!): Place! @signedIn
|
||||
}
|
||||
|
||||
@@ -22,8 +22,10 @@ extend type Query {
|
||||
post(id: ID!): Post
|
||||
}
|
||||
|
||||
# @admin is only the first half of the rule for updatePost and deletePost:
|
||||
# the resolver also requires the caller to be the post's author.
|
||||
extend type Mutation {
|
||||
createPost(input: CreatePostInput!): Post!
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
||||
deletePost(id: ID!): Post!
|
||||
createPost(input: CreatePostInput!): Post! @admin
|
||||
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
|
||||
deletePost(id: ID!): Post! @admin
|
||||
}
|
||||
|
||||
@@ -16,5 +16,22 @@
|
||||
|
||||
scalar Time
|
||||
|
||||
# Authorisation. There is no middleware in front of /graphql, so a field is
|
||||
# PUBLIC unless it carries one of these. Each is implemented once, in
|
||||
# graph/directives.go, and runs before the field's resolver:
|
||||
#
|
||||
# @admin the request must carry an admin's access token
|
||||
# (error: "admin access required")
|
||||
# @signedIn any valid access token will do
|
||||
# (error: "authentication required")
|
||||
#
|
||||
# Every mutation needs one of them unless it is deliberately public (login,
|
||||
# logout, refreshToken); graph/directives_test.go fails otherwise, and pins
|
||||
# which queries are guarded. Rules that are not a plain gate stay in the
|
||||
# resolver: a post is only editable by its author, `me` answers for whoever is
|
||||
# signed in, and `messages` filters private rows rather than refusing.
|
||||
directive @admin on FIELD_DEFINITION
|
||||
directive @signedIn on FIELD_DEFINITION
|
||||
|
||||
type Query
|
||||
type Mutation
|
||||
|
||||
@@ -36,6 +36,7 @@ extend type Query {
|
||||
spotifyRecent: [SpotifyRecentItem!]
|
||||
# True only for an admin session while the backend lacks a Spotify client
|
||||
# (OAuth never completed or the token was revoked), used by the Listening
|
||||
# widget to offer a reconnect link. Everyone else gets false.
|
||||
# widget to offer a reconnect link. Everyone else gets false — a soft
|
||||
# check in the resolver, not @admin, so the home page query never errors.
|
||||
spotifyNeedsReauth: Boolean!
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
@@ -12,12 +23,17 @@ input CreateUserInput {
|
||||
}
|
||||
|
||||
extend type Query {
|
||||
users: [User!]!
|
||||
user(id: ID!): User
|
||||
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!
|
||||
deleteUser(id: ID!): User!
|
||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
||||
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
|
||||
}
|
||||
|
||||
@@ -61,6 +61,8 @@ func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// A soft check, deliberately not @admin: the directive would turn this
|
||||
// into an error on the public home page query.
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
@@ -8,20 +8,19 @@ 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"
|
||||
)
|
||||
|
||||
// CreateUser is the resolver for the createUser field.
|
||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
// Only an existing admin can create accounts — there is no public
|
||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
||||
// Only an existing admin can create accounts (@admin in the schema) —
|
||||
// there is no public sign-up. New users are created non-admin;
|
||||
// setUserAdmin promotes them.
|
||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -37,10 +36,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
||||
|
||||
// DeleteUser is the resolver for the deleteUser field.
|
||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
@@ -55,10 +50,6 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
|
||||
|
||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
|
||||
callerID, ok := UserIDFromCtx(ctx)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unauthorized")
|
||||
@@ -83,11 +74,43 @@ 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) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var users []models.User
|
||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
@@ -97,9 +120,6 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||
|
||||
// User is the resolver for the user field.
|
||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||
if !IsAdminFromCtx(ctx) {
|
||||
return nil, fmt.Errorf("admin access required")
|
||||
}
|
||||
var user models.User
|
||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||
return nil, fmt.Errorf("user not found")
|
||||
@@ -107,12 +127,8 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// ID is the resolver for the id field.
|
||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
||||
return int(obj.ID), 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
|
||||
}
|
||||
|
||||
// User returns UserResolver implementation.
|
||||
func (r *Resolver) User() UserResolver { return &userResolver{r} }
|
||||
|
||||
type userResolver struct{ *Resolver }
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin diagnostics panel's log tail. It is an admin-only
|
||||
// REST endpoint rather than GraphQL because it reads the filesystem — outside
|
||||
// the data model the GraphQL schema describes. The configuration report that
|
||||
// used to live here is now the Environment tab (handle_env.go).
|
||||
|
||||
// logTailBytes and logTailLines bound how much of the log file one request
|
||||
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
|
||||
// cheap even on the Pi.
|
||||
const (
|
||||
logTailBytes = 256 << 10
|
||||
logTailLines = 500
|
||||
)
|
||||
|
||||
// Logs backs GET /admin/logs. It returns the tail of the backend's own log
|
||||
// file (go.log — Gin traffic plus application log lines), which lives on the
|
||||
// bind-mounted ./logs volume.
|
||||
//
|
||||
// Why tail and not offer a range: the panel wants "what happened recently",
|
||||
// and the file can grow unboundedly between rotations, so anything else
|
||||
// invites reading the whole thing into memory.
|
||||
func (store *Store) Logs(ctx *gin.Context) {
|
||||
lines, size, err := tailLogFile(logPath)
|
||||
if err != nil {
|
||||
// The mount being absent is a deployment problem worth surfacing
|
||||
// distinctly from "log file empty".
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size})
|
||||
}
|
||||
|
||||
// logPath matches the file main.go opens for gin.DefaultWriter.
|
||||
const logPath = "/backend/logs/go.log"
|
||||
|
||||
// tailLogFile returns the last logTailLines lines of a file, reading at most
|
||||
// logTailBytes from the end. Split out from the handler so the offset and
|
||||
// partial-line rules are testable without a filesystem mount.
|
||||
func tailLogFile(path string) ([]string, int64, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
// Read from near the end rather than head-to-toe so the read stays
|
||||
// constant-size regardless of how old the file is.
|
||||
start := int64(0)
|
||||
if info.Size() > logTailBytes {
|
||||
start = info.Size() - logTailBytes
|
||||
}
|
||||
buf := make([]byte, info.Size()-start)
|
||||
if len(buf) > 0 {
|
||||
if _, err := f.ReadAt(buf, start); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
}
|
||||
|
||||
// Starting mid-file almost certainly lands mid-line; drop that fragment
|
||||
// so the panel never renders a truncated first entry.
|
||||
text := string(buf)
|
||||
if start > 0 {
|
||||
if i := strings.IndexByte(text, '\n'); i >= 0 {
|
||||
text = text[i+1:]
|
||||
}
|
||||
}
|
||||
|
||||
text = strings.TrimRight(text, "\n")
|
||||
if text == "" {
|
||||
return []string{}, info.Size(), nil
|
||||
}
|
||||
|
||||
lines := strings.Split(text, "\n")
|
||||
if len(lines) > logTailLines {
|
||||
lines = lines[len(lines)-logTailLines:]
|
||||
}
|
||||
return lines, info.Size(), nil
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// tailLogFile's rules that are easy to get wrong: the line cap, and dropping
|
||||
// the partial first line when the read started mid-file.
|
||||
|
||||
func writeLog(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "go.log")
|
||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
||||
t.Fatalf("writing fixture: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestTailLogFileCapsLines(t *testing.T) {
|
||||
var b strings.Builder
|
||||
for range logTailLines + 50 {
|
||||
b.WriteString("line\n")
|
||||
}
|
||||
lines, _, err := tailLogFile(writeLog(t, b.String()))
|
||||
if err != nil {
|
||||
t.Fatalf("tailLogFile: %v", err)
|
||||
}
|
||||
if len(lines) != logTailLines {
|
||||
t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTailLogFileDropsPartialFirstLine(t *testing.T) {
|
||||
// A file larger than the byte window: the read starts mid-file, so the
|
||||
// first line it sees is a fragment and must be discarded.
|
||||
filler := strings.Repeat("x", 100) + "\n"
|
||||
var b strings.Builder
|
||||
for b.Len() < logTailBytes+len(filler) {
|
||||
b.WriteString(filler)
|
||||
}
|
||||
b.WriteString("FINAL\n")
|
||||
|
||||
lines, _, err := tailLogFile(writeLog(t, b.String()))
|
||||
if err != nil {
|
||||
t.Fatalf("tailLogFile: %v", err)
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
t.Fatal("expected some lines")
|
||||
}
|
||||
if lines[len(lines)-1] != "FINAL" {
|
||||
t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1])
|
||||
}
|
||||
// Every surviving line must be whole, i.e. a full filler line.
|
||||
if got := lines[0]; got != strings.TrimSuffix(filler, "\n") {
|
||||
t.Fatalf("first line = %q, want a complete filler line", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTailLogFileEmpty(t *testing.T) {
|
||||
lines, size, err := tailLogFile(writeLog(t, ""))
|
||||
if err != nil {
|
||||
t.Fatalf("tailLogFile: %v", err)
|
||||
}
|
||||
if len(lines) != 0 || size != 0 {
|
||||
t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTailLogFileMissing(t *testing.T) {
|
||||
if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil {
|
||||
t.Fatal("expected an error for a missing log file")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// REST endpoints for the job-application email pipeline: a manual
|
||||
// admin-triggered sync, and the OAuth redirect target (which has to be REST
|
||||
// because Microsoft redirects a browser to it).
|
||||
|
||||
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
|
||||
// synchronously, so the response reflects the result. If the scheduler is
|
||||
// mid-sync the service refuses via TryLock and this returns 500.
|
||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
||||
// A nil HTTPClient is the service's readiness flag — see
|
||||
// services.EmailSyncService.
|
||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
||||
return
|
||||
}
|
||||
|
||||
err := store.EmailSync.SyncEmails(ctx.Request.Context())
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Manual sync error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
||||
}
|
||||
|
||||
// CompleteEmailAuth handles Microsoft's OAuth redirect to
|
||||
// GET /email/callback and stores the resulting token.
|
||||
//
|
||||
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
|
||||
// which is safe only because the code is worthless without the app's client
|
||||
// secret. Note that completing auth here does not start the scheduler, which
|
||||
// only checks readiness at start-up — a restart is needed for that.
|
||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
||||
if store.EmailSync == nil {
|
||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
||||
return
|
||||
}
|
||||
|
||||
code := ctx.Query("code")
|
||||
if code == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
|
||||
log.Printf("[EmailSync] Auth completion error: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// This file backs the admin panel's Environment tab: a report on every
|
||||
// variable in .env, and a way to change the ones that are safe to change.
|
||||
//
|
||||
// The handlers never read or write .env. State is this process's own
|
||||
// environment, and a change is a request left for the host to apply (see
|
||||
// services.EnvManager). REST rather than GraphQL for the same reason as the
|
||||
// rest of the admin endpoints: this is process and host state, not the data
|
||||
// model the schema describes.
|
||||
|
||||
// envSecretHintMinLen is the shortest secret that gets its last four
|
||||
// characters shown. Below it, four characters is too much of the value.
|
||||
const envSecretHintMinLen = 12
|
||||
|
||||
type envVarView struct {
|
||||
services.EnvVar
|
||||
Secret bool `json:"secret"`
|
||||
Set bool `json:"set"`
|
||||
// Value is sent only for non-secret variables; Hint (the last four
|
||||
// characters) is all a secret ever reveals.
|
||||
Value string `json:"value,omitempty"`
|
||||
Hint string `json:"hint,omitempty"`
|
||||
}
|
||||
|
||||
type envGroupView struct {
|
||||
Name string `json:"name"`
|
||||
Vars []envVarView `json:"vars"`
|
||||
}
|
||||
|
||||
// GetEnv backs GET /admin/env: every registry variable grouped for display,
|
||||
// plus the state of the latest change.
|
||||
//
|
||||
// Values are what this process was started with, not what .env holds now —
|
||||
// the two differ between a save and the recreate that follows it, which is
|
||||
// what the status's pending list is for.
|
||||
func (store *Store) GetEnv(ctx *gin.Context) {
|
||||
var groups []envGroupView
|
||||
index := map[string]int{}
|
||||
for _, v := range store.Env.Vars() {
|
||||
value := os.Getenv(v.Name)
|
||||
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
|
||||
switch {
|
||||
case !view.Set:
|
||||
case !view.Secret:
|
||||
view.Value = value
|
||||
case len(value) >= envSecretHintMinLen:
|
||||
view.Hint = value[len(value)-4:]
|
||||
}
|
||||
|
||||
i, seen := index[v.Group]
|
||||
if !seen {
|
||||
i = len(groups)
|
||||
index[v.Group] = i
|
||||
groups = append(groups, envGroupView{Name: v.Group})
|
||||
}
|
||||
groups[i].Vars = append(groups[i].Vars, view)
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
|
||||
}
|
||||
|
||||
type updateEnvRequest struct {
|
||||
// Set maps a variable to its new value; "" clears it.
|
||||
Set map[string]string `json:"set"`
|
||||
// Generate names "generated" variables to mint a random value for.
|
||||
Generate []string `json:"generate"`
|
||||
}
|
||||
|
||||
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
|
||||
// returns straight away; the panel follows progress on GET /admin/env/status,
|
||||
// through the backend's own restart.
|
||||
//
|
||||
// The response is the only time a generated value is sent anywhere.
|
||||
func (store *Store) UpdateEnv(ctx *gin.Context) {
|
||||
var body updateEnvRequest
|
||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
|
||||
if errors.Is(err, services.ErrEnvApplying) {
|
||||
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
// Validation messages name the variable, never the value.
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(body.Set)+len(body.Generate))
|
||||
for name := range body.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
names = append(names, body.Generate...)
|
||||
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
|
||||
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusAccepted, gin.H{
|
||||
"generated": generated,
|
||||
"services": recreates,
|
||||
"status": store.Env.Status(),
|
||||
})
|
||||
}
|
||||
|
||||
// GetEnvStatus backs GET /admin/env/status.
|
||||
func (store *Store) GetEnvStatus(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
|
||||
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
|
||||
// the host has picked up, so new secrets do not sit in the shared directory
|
||||
// waiting for a watcher that is not there.
|
||||
func (store *Store) CancelEnv(ctx *gin.Context) {
|
||||
if err := store.Env.Cancel(); err != nil {
|
||||
log.Println("Cancelling env request failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func envRouter(t *testing.T) (*gin.Engine, string) {
|
||||
t.Helper()
|
||||
gin.SetMode(gin.TestMode)
|
||||
dir := t.TempDir()
|
||||
env, err := services.NewEnvManager(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
store := &Store{Env: env}
|
||||
r := gin.New()
|
||||
r.GET("/admin/env", store.GetEnv)
|
||||
r.PUT("/admin/env", store.UpdateEnv)
|
||||
r.GET("/admin/env/status", store.GetEnvStatus)
|
||||
r.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
return r, dir
|
||||
}
|
||||
|
||||
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// The property the whole tab rests on: a secret's value never leaves the
|
||||
// server, while a non-secret's does so it can be edited in place.
|
||||
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
|
||||
r, _ := envRouter(t)
|
||||
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
|
||||
t.Setenv("POSTGRES_PASSWORD", "hunter2")
|
||||
t.Setenv("STEAM_ID", "76561198000000000")
|
||||
t.Setenv("TFL_APP_KEY", "")
|
||||
|
||||
rec := envDo(r, http.MethodGet, "/admin/env", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
body := rec.Body.String()
|
||||
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
|
||||
if strings.Contains(body, secret) {
|
||||
t.Fatalf("response contains the secret %q", secret)
|
||||
}
|
||||
}
|
||||
|
||||
var parsed struct {
|
||||
Groups []struct {
|
||||
Vars []envVarView `json:"vars"`
|
||||
} `json:"groups"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
byName := map[string]envVarView{}
|
||||
for _, g := range parsed.Groups {
|
||||
for _, v := range g.Vars {
|
||||
byName[v.Name] = v
|
||||
}
|
||||
}
|
||||
|
||||
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
|
||||
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
|
||||
}
|
||||
// Too short for four characters to be a safe hint.
|
||||
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
|
||||
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
|
||||
}
|
||||
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
|
||||
t.Errorf("STEAM_ID = %+v, want its value shown", v)
|
||||
}
|
||||
if v := byName["TFL_APP_KEY"]; v.Set {
|
||||
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateEnv(t *testing.T) {
|
||||
r, dir := envRouter(t)
|
||||
requestPath := filepath.Join(dir, "request.json")
|
||||
|
||||
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("a refused change left a request behind")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a malformed body is refused", func(t *testing.T) {
|
||||
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
|
||||
}
|
||||
var parsed struct {
|
||||
Generated map[string]string `json:"generated"`
|
||||
Status services.EnvApplyStatus `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
||||
t.Fatalf("parsing response: %v", err)
|
||||
}
|
||||
secret := parsed.Generated["BACKEND_SECRET"]
|
||||
if len(secret) != 64 {
|
||||
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
|
||||
}
|
||||
if parsed.Status.State != "pending" {
|
||||
t.Fatalf("status = %+v, want pending", parsed.Status)
|
||||
}
|
||||
|
||||
// Reading the state back must not repeat it.
|
||||
for _, path := range []string{"/admin/env", "/admin/env/status"} {
|
||||
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
|
||||
t.Fatalf("GET %s repeats the generated secret", path)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a pending change can be withdrawn", func(t *testing.T) {
|
||||
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
if _, err := os.Stat(requestPath); err == nil {
|
||||
t.Fatal("the request file survived the cancel")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Job capture: the three endpoints behind userscripts/job-capture.user.js,
|
||||
// which adds the posting open in the browser to the job tracker.
|
||||
//
|
||||
// These are REST, and token-authenticated, because the caller is a userscript
|
||||
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
|
||||
// are SameSite=Lax and never accompany such a request, so the GraphQL
|
||||
// mutations, which rely on them, are out of reach from there.
|
||||
//
|
||||
// The token is deliberately narrow: it opens these routes and nothing else,
|
||||
// so a token leaked from the browser can add rows to the tracker and spend
|
||||
// Claude calls, but cannot read the tracker, edit other data or log in.
|
||||
//
|
||||
// As with rowing, the Claude call lives in the Python service
|
||||
// (python/app/jobs.py) and everything touching the database stays here.
|
||||
|
||||
const (
|
||||
// jobExtractPath is internal in the same way as rowingReadPath: nginx
|
||||
// refuses /py/internal/ and the route refuses anything nginx forwarded.
|
||||
jobExtractPath = "/internal/jobs/extract"
|
||||
|
||||
// maxCaptureBody bounds a capture request. A long posting is tens of
|
||||
// kilobytes of text; the userscript trims the page to maxPageRunes before
|
||||
// sending, so anything near this limit is not a job page.
|
||||
maxCaptureBody = 512 << 10
|
||||
|
||||
// maxPageRunes caps both the text sent to Claude and the description
|
||||
// stored. It mirrors MAX_TEXT_CHARS in python/app/jobs.py, which rejects
|
||||
// anything longer, so the cut has to happen on this side.
|
||||
maxPageRunes = 40_000
|
||||
)
|
||||
|
||||
// jobExtractClient bounds the wait on the Python service; see
|
||||
// rowingReadClient for why two minutes.
|
||||
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// CaptureTokenMiddleware guards the capture routes with the token generated
|
||||
// in the admin panel (services.CaptureToken), presented as
|
||||
// "Authorization: Bearer <token>".
|
||||
//
|
||||
// Until a token has been generated the routes are off (503) rather than
|
||||
// open; "no token" must never be satisfied by a request that sends none.
|
||||
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
|
||||
if store.CaptureToken == nil {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
|
||||
return
|
||||
}
|
||||
if set, _ := store.CaptureToken.Status(); !set {
|
||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
|
||||
return
|
||||
}
|
||||
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
|
||||
if !ok || !store.CaptureToken.Verify(presented) {
|
||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
ctx.Next()
|
||||
}
|
||||
|
||||
// The three handlers below manage that token from the admin panel. They sit
|
||||
// in the cookie-authenticated admin group, not behind the token: the token
|
||||
// must not be able to replace itself.
|
||||
|
||||
func captureTokenStatus(token *services.CaptureToken) gin.H {
|
||||
set, createdAt := token.Status()
|
||||
if !set {
|
||||
return gin.H{"set": false}
|
||||
}
|
||||
return gin.H{"set": true, "createdAt": createdAt}
|
||||
}
|
||||
|
||||
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
|
||||
// when it was made. The token itself is not recoverable — only its hash is
|
||||
// stored.
|
||||
func (store *Store) GetCaptureToken(ctx *gin.Context) {
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
|
||||
// existing token, so the userscript must be reconfigured with the new one,
|
||||
// and its response is the only time the token is ever sent anywhere.
|
||||
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
|
||||
token, createdAt, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
log.Println("Generating capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
|
||||
return
|
||||
}
|
||||
// The response carries a credential; keep it out of any cache.
|
||||
ctx.Header("Cache-Control", "no-store")
|
||||
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
|
||||
}
|
||||
|
||||
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
|
||||
// routes off until a new token is generated.
|
||||
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
|
||||
if err := store.CaptureToken.Revoke(); err != nil {
|
||||
log.Println("Revoking capture token failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
||||
}
|
||||
|
||||
// trackingParams are query parameters that say how the visitor arrived, not
|
||||
// which posting this is. Anything not listed is kept: ATS boards identify the
|
||||
// job in the query string often enough (gh_jid, jk, jobId) that dropping
|
||||
// unknown parameters would merge different postings.
|
||||
var trackingParams = map[string]bool{
|
||||
"trk": true, "trackingid": true, "refid": true, "ebp": true,
|
||||
"gh_src": true, "lever-source": true, "lever-origin": true,
|
||||
"source": true, "src": true, "ref": true,
|
||||
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
|
||||
}
|
||||
|
||||
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
|
||||
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
|
||||
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
|
||||
|
||||
// canonicalJobURL reduces a posting URL to a form that is the same however
|
||||
// the page was reached, so it can serve as the key that decides whether a
|
||||
// posting is already tracked. ok is false for anything that is not an
|
||||
// absolute http(s) URL.
|
||||
//
|
||||
// LinkedIn gets its own rule because the same posting appears under several
|
||||
// paths (search results, collections, the recommended feed), all carrying the
|
||||
// id in ?currentJobId= rather than in the path.
|
||||
func canonicalJobURL(raw string) (canonical string, ok bool) {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return "", false
|
||||
}
|
||||
host := strings.ToLower(u.Host)
|
||||
query := u.Query()
|
||||
|
||||
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
|
||||
id := query.Get("currentJobId")
|
||||
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
|
||||
id = m[1]
|
||||
}
|
||||
if id != "" && strings.Trim(id, "0123456789") == "" {
|
||||
return "https://www.linkedin.com/jobs/view/" + id + "/", true
|
||||
}
|
||||
}
|
||||
|
||||
for key := range query {
|
||||
lowered := strings.ToLower(key)
|
||||
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
|
||||
query.Del(key)
|
||||
}
|
||||
}
|
||||
|
||||
out := url.URL{
|
||||
Scheme: u.Scheme,
|
||||
Host: host,
|
||||
// A trailing slash is not a different posting.
|
||||
Path: strings.TrimRight(u.Path, "/"),
|
||||
// Encode sorts by key, so parameter order does not matter either.
|
||||
RawQuery: query.Encode(),
|
||||
}
|
||||
return out.String(), true
|
||||
}
|
||||
|
||||
// capturedJob is the slice of an application the userscript needs back: enough
|
||||
// to show "already tracked as …" and no more. The token is not meant to be
|
||||
// able to read the tracker, so notes and the description stay out of it.
|
||||
type capturedJob struct {
|
||||
ID uint `json:"id"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func capturedJobOf(app *models.JobApplication) *capturedJob {
|
||||
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
|
||||
}
|
||||
|
||||
// findByURL returns the newest live application stored under this posting's
|
||||
// URL, or nil. The raw form is tried as well as the canonical one because rows
|
||||
// typed into the tracker by hand hold whatever was pasted.
|
||||
func (store *Store) findByURL(canonical, raw string) (*models.JobApplication, error) {
|
||||
return firstApplication(store.DB.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
|
||||
}
|
||||
|
||||
// firstApplication returns the newest row the query matches, or nil for none.
|
||||
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
|
||||
// badge lookup on an untracked posting), and First reports one as
|
||||
// ErrRecordNotFound, which GORM writes to the log as an error each time.
|
||||
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
|
||||
var apps []models.JobApplication
|
||||
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(apps) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
return &apps[0], nil
|
||||
}
|
||||
|
||||
// JobCaptureStatus backs GET /jobs/capture/status?url=. It is what lets the
|
||||
// userscript show a posting's tracked status instead of an "add" button.
|
||||
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
|
||||
raw := ctx.Query("url")
|
||||
canonical, ok := canonicalJobURL(raw)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
||||
return
|
||||
}
|
||||
app, err := store.findByURL(canonical, raw)
|
||||
if err != nil {
|
||||
log.Println("Job capture status lookup failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
if app == nil {
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": false})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
|
||||
}
|
||||
|
||||
// ExtractedJobPosting is the JSON contract for what Claude reads off a job
|
||||
// page: the body of the Python service's reply (JobPosting in
|
||||
// python/app/jobs.py). Empty strings and nulls mean "not found on the page".
|
||||
type ExtractedJobPosting struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location *string `json:"location"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// postingReadError is a failure the Python service reported in words that are
|
||||
// safe to show in the capture popup (its 502 detail); the job-capture
|
||||
// counterpart of displayReadError.
|
||||
type postingReadError struct{ detail string }
|
||||
|
||||
func (e *postingReadError) Error() string { return e.detail }
|
||||
|
||||
// extractJobPosting sends a page's text to the Python service and returns the
|
||||
// fields Claude picked out. It mirrors readRowingDisplay, including which
|
||||
// replies are relayed and which are only logged.
|
||||
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
|
||||
var posting ExtractedJobPosting
|
||||
|
||||
body, err := json.Marshal(struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}{pageURL, title, text})
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := jobExtractClient.Do(req)
|
||||
if err != nil {
|
||||
return posting, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return posting, &postingReadError{detail: failure.Detail}
|
||||
}
|
||||
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
|
||||
return posting, fmt.Errorf("decoding job extractor response: %w", err)
|
||||
}
|
||||
return posting, nil
|
||||
}
|
||||
|
||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
||||
// is still valid UTF-8 for Postgres and for JSON.
|
||||
func truncateRunes(s string, max int) string {
|
||||
runes := []rune(s)
|
||||
if len(runes) <= max {
|
||||
return s
|
||||
}
|
||||
return string(runes[:max])
|
||||
}
|
||||
|
||||
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
||||
// cannot.
|
||||
func bindCapture(ctx *gin.Context, into any) bool {
|
||||
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
|
||||
if err := ctx.ShouldBindJSON(into); err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// JobCaptureExtract backs POST /jobs/capture/extract: page text in, the
|
||||
// popup's pre-filled fields out. Nothing is stored; saving is a separate
|
||||
// request made once the fields have been checked by eye.
|
||||
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
||||
var input struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if !bindCapture(ctx, &input) {
|
||||
return
|
||||
}
|
||||
text := strings.TrimSpace(input.Text)
|
||||
if text == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
|
||||
return
|
||||
}
|
||||
|
||||
posting, err := store.extractJobPosting(ctx.Request.Context(),
|
||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
||||
if err != nil {
|
||||
log.Println("Job extract failed:", err)
|
||||
var readErr *postingReadError
|
||||
if errors.As(err, &readErr) {
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.detail})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusOK, posting)
|
||||
}
|
||||
|
||||
// captureInput is the body of POST /jobs/capture: the popup's fields.
|
||||
type captureInput struct {
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Company string `json:"company"`
|
||||
Location string `json:"location"`
|
||||
URL string `json:"url"`
|
||||
Status string `json:"status"`
|
||||
Notes string `json:"notes"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
|
||||
|
||||
// mergeCapture folds a repeat capture into the application it matched and
|
||||
// reports whether anything changed.
|
||||
//
|
||||
// It only ever adds: the status moves forwards or not at all (the same rule
|
||||
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
|
||||
// pull an interviewing application back), and a field already holding a value
|
||||
// is left alone, because the row may have been corrected by hand since. Title
|
||||
// and company are never touched — they are the key the email pipeline matches
|
||||
// on.
|
||||
func mergeCapture(app *models.JobApplication, in captureInput, now time.Time) bool {
|
||||
changed := false
|
||||
|
||||
if status := services.NormalizeStatus(in.Status); services.StatusAdvances(app.Status, status) {
|
||||
app.Status = status
|
||||
changed = true
|
||||
}
|
||||
// Saved-then-applied is the common path here, and the moment of the
|
||||
// second capture is the application date.
|
||||
if app.AppliedAt == nil && app.Status == "applied" {
|
||||
app.AppliedAt = &now
|
||||
changed = true
|
||||
}
|
||||
|
||||
fill := func(field **string, value string) {
|
||||
if value != "" && !nonEmpty(*field) {
|
||||
*field = &value
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
fill(&app.Location, in.Location)
|
||||
fill(&app.URL, in.URL)
|
||||
fill(&app.Description, in.Description)
|
||||
|
||||
// Notes accumulate, as they do when the pipeline updates a row, but a
|
||||
// repeat capture of the same page must not append the same line twice.
|
||||
if in.Notes != "" {
|
||||
switch {
|
||||
case !nonEmpty(app.Notes):
|
||||
app.Notes = &in.Notes
|
||||
changed = true
|
||||
case !strings.Contains(*app.Notes, in.Notes):
|
||||
combined := *app.Notes + "\n" + in.Notes
|
||||
app.Notes = &combined
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// JobCapture backs POST /jobs/capture, an upsert.
|
||||
//
|
||||
// A posting already in the tracker is updated in place rather than added
|
||||
// again. That matters beyond tidiness: the email pipeline identifies an
|
||||
// application by (company, job title), so two rows for one posting means the
|
||||
// confirmation email advances only one of them.
|
||||
//
|
||||
// Match order is the posting URL, then (company, job title) compared the way
|
||||
// the pipeline compares them. Only live rows match — unlike the pipeline's
|
||||
// lookup, which also sees deleted rows so that an email cannot resurrect one.
|
||||
// A capture is a deliberate act, so capturing a posting whose row was deleted
|
||||
// makes a new row.
|
||||
func (store *Store) JobCapture(ctx *gin.Context) {
|
||||
var input captureInput
|
||||
if !bindCapture(ctx, &input) {
|
||||
return
|
||||
}
|
||||
input.JobTitle = strings.TrimSpace(input.JobTitle)
|
||||
input.Company = strings.TrimSpace(input.Company)
|
||||
input.Location = strings.TrimSpace(input.Location)
|
||||
input.Notes = strings.TrimSpace(input.Notes)
|
||||
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
|
||||
if input.JobTitle == "" || input.Company == "" {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jobTitle and company are required"})
|
||||
return
|
||||
}
|
||||
|
||||
rawURL := input.URL
|
||||
if strings.TrimSpace(rawURL) != "" {
|
||||
canonical, ok := canonicalJobURL(rawURL)
|
||||
if !ok {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
||||
return
|
||||
}
|
||||
input.URL = canonical
|
||||
} else {
|
||||
input.URL = ""
|
||||
}
|
||||
|
||||
var existing *models.JobApplication
|
||||
var err error
|
||||
if input.URL != "" {
|
||||
existing, err = store.findByURL(input.URL, rawURL)
|
||||
}
|
||||
if err == nil && existing == nil {
|
||||
existing, err = firstApplication(store.DB.Where(
|
||||
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
|
||||
}
|
||||
if err != nil {
|
||||
log.Println("Job capture lookup failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
||||
return
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
if existing != nil {
|
||||
action := "unchanged"
|
||||
if mergeCapture(existing, input, now) {
|
||||
if err := store.DB.Save(existing).Error; err != nil {
|
||||
log.Println("Job capture update failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
||||
return
|
||||
}
|
||||
action = "updated"
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(existing)})
|
||||
return
|
||||
}
|
||||
|
||||
// A new row is the merge of the capture into an empty application, which
|
||||
// keeps the two paths agreeing on what an empty field and "applied" mean.
|
||||
// The empty status counts as unknown, so any status takes over from it.
|
||||
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
|
||||
mergeCapture(&app, input, now)
|
||||
if err := store.DB.Create(&app).Error; err != nil {
|
||||
log.Println("Job capture insert failed:", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
||||
return
|
||||
}
|
||||
ctx.JSON(http.StatusCreated, gin.H{"action": "created", "application": capturedJobOf(&app)})
|
||||
}
|
||||
@@ -1,379 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// The capture handlers themselves need a database, and the only driver in
|
||||
// go.mod is postgres, so what is covered here is everything around the
|
||||
// queries: the token gate, the URL key that decides whether a posting is
|
||||
// already tracked, the merge rule for a repeat capture, and the call to the
|
||||
// Python service.
|
||||
|
||||
func TestCaptureTokenMiddleware(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
serve := func(store *Store, header string) int {
|
||||
r := gin.New()
|
||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
||||
if header != "" {
|
||||
req.Header.Set("Authorization", header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec.Code
|
||||
}
|
||||
newToken := func() *services.CaptureToken {
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
// The case the middleware exists to get right: with no token generated,
|
||||
// a request presenting nothing (or an empty bearer) must not get in.
|
||||
t.Run("no token generated switches the routes off", func(t *testing.T) {
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
|
||||
if got := serve(store, header); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("header %q: status = %d, want 503", header, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("a store built without the token service is off too", func(t *testing.T) {
|
||||
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want 503", got)
|
||||
}
|
||||
})
|
||||
|
||||
store := &Store{CaptureToken: newToken()}
|
||||
token, _, err := store.CaptureToken.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
header string
|
||||
want int
|
||||
}{
|
||||
{"the generated token is let through", "Bearer " + token, http.StatusOK},
|
||||
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
|
||||
{"no header is refused", "", http.StatusUnauthorized},
|
||||
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := serve(store, c.header); got != c.want {
|
||||
t.Fatalf("status = %d, want %d", got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The admin endpoints, driven without the admin middleware (covered
|
||||
// elsewhere): generate shows the token once, status never does, and a second
|
||||
// generate or a revoke stops the first token working.
|
||||
func TestCaptureTokenAdminEndpoints(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
store := &Store{CaptureToken: tok}
|
||||
r := gin.New()
|
||||
r.GET("/t", store.GetCaptureToken)
|
||||
r.POST("/t", store.GenerateCaptureToken)
|
||||
r.DELETE("/t", store.RevokeCaptureToken)
|
||||
|
||||
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
|
||||
}
|
||||
var out map[string]any
|
||||
json.Unmarshal(rec.Body.Bytes(), &out)
|
||||
return out, rec
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodGet); out["set"] != false {
|
||||
t.Fatalf("fresh status = %v", out)
|
||||
}
|
||||
|
||||
out, rec := call(http.MethodPost)
|
||||
first, _ := out["token"].(string)
|
||||
if !tok.Verify(first) {
|
||||
t.Fatalf("generated token %q does not verify", first)
|
||||
}
|
||||
if rec.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("the response carrying the token must not be cacheable")
|
||||
}
|
||||
|
||||
out, _ = call(http.MethodGet)
|
||||
if out["set"] != true || out["createdAt"] == nil {
|
||||
t.Fatalf("status after generate = %v", out)
|
||||
}
|
||||
if _, leaked := out["token"]; leaked {
|
||||
t.Fatal("status must never return the token")
|
||||
}
|
||||
|
||||
call(http.MethodPost)
|
||||
if tok.Verify(first) {
|
||||
t.Fatal("regenerating must invalidate the previous token")
|
||||
}
|
||||
|
||||
if out, _ := call(http.MethodDelete); out["set"] != false {
|
||||
t.Fatalf("status after revoke = %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCanonicalJobURL(t *testing.T) {
|
||||
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string // "" means rejected
|
||||
}{
|
||||
// One LinkedIn posting, reached four ways, must be one key.
|
||||
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
|
||||
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
|
||||
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
|
||||
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
|
||||
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
|
||||
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
|
||||
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
|
||||
|
||||
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
|
||||
// gh_jid IS the posting on an embedded Greenhouse board.
|
||||
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
|
||||
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
|
||||
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
|
||||
|
||||
{"a relative path is rejected", "/jobs/view/1", ""},
|
||||
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
|
||||
{"empty is rejected", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
got, ok := canonicalJobURL(c.in)
|
||||
if ok != (c.want != "") || got != c.want {
|
||||
t.Fatalf("canonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func strPtr(s string) *string { return &s }
|
||||
|
||||
func TestMergeCapture(t *testing.T) {
|
||||
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
|
||||
earlier := now.Add(-48 * time.Hour)
|
||||
|
||||
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
|
||||
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
|
||||
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
|
||||
if !mergeCapture(&app, in, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
|
||||
t.Fatalf("fields not filled: %+v", app)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a saved posting has no applied date", func(t *testing.T) {
|
||||
app := models.JobApplication{}
|
||||
mergeCapture(&app, captureInput{Status: "saved"}, now)
|
||||
if app.Status != "saved" || app.AppliedAt != nil {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "saved"}
|
||||
if !mergeCapture(&app, captureInput{Status: "applied"}, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
|
||||
if mergeCapture(&app, captureInput{Status: "saved"}, now) {
|
||||
t.Fatal("expected no change")
|
||||
}
|
||||
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
|
||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
|
||||
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
|
||||
if !mergeCapture(&app, in, now) {
|
||||
t.Fatal("expected a change")
|
||||
}
|
||||
if *app.Location != "Remote" {
|
||||
t.Fatalf("location overwritten: %q", *app.Location)
|
||||
}
|
||||
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
|
||||
t.Fatalf("empty fields not filled: url=%q", *app.URL)
|
||||
}
|
||||
if !app.AppliedAt.Equal(earlier) {
|
||||
t.Fatal("an existing applied date must not be replaced")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("notes append once", func(t *testing.T) {
|
||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
|
||||
in := captureInput{Status: "applied", Notes: "Hybrid, £70k"}
|
||||
if !mergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
|
||||
t.Fatalf("notes = %q", *app.Notes)
|
||||
}
|
||||
if mergeCapture(&app, in, now) {
|
||||
t.Fatalf("the same note was appended twice: %q", *app.Notes)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestTruncateRunes(t *testing.T) {
|
||||
if got := truncateRunes("££££", 2); got != "££" {
|
||||
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
|
||||
}
|
||||
if got := truncateRunes("short", 10); got != "short" {
|
||||
t.Fatalf("got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func jobExtractor(t *testing.T, handler http.HandlerFunc) *Store {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(handler)
|
||||
t.Cleanup(srv.Close)
|
||||
return &Store{PythonURL: srv.URL}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingRequestAndReply(t *testing.T) {
|
||||
var got map[string]string
|
||||
var path string
|
||||
var forwarded bool
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
path = r.URL.Path
|
||||
// As with the rowing reader, either header makes the Python route
|
||||
// answer 404.
|
||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Errorf("decoding request: %v", err)
|
||||
}
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": null}`))
|
||||
})
|
||||
|
||||
posting, err := store.extractJobPosting(context.Background(), "https://x.com/1", "Engineer | Acme", "page text")
|
||||
if err != nil {
|
||||
t.Fatalf("extractJobPosting: %v", err)
|
||||
}
|
||||
if posting.JobTitle != "Engineer" || posting.Company != "Acme" || posting.Location == nil || *posting.Location != "London" || posting.Notes != nil {
|
||||
t.Fatalf("got %+v", posting)
|
||||
}
|
||||
if path != jobExtractPath {
|
||||
t.Fatalf("path = %q, want %q", path, jobExtractPath)
|
||||
}
|
||||
if forwarded {
|
||||
t.Fatal("request carried a proxy header the Python route rejects")
|
||||
}
|
||||
if got["url"] != "https://x.com/1" || got["title"] != "Engineer | Acme" || got["text"] != "page text" {
|
||||
t.Fatalf("request body = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExtractJobPostingErrors(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a postingReadError with this message
|
||||
}{
|
||||
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(c.status)
|
||||
w.Write([]byte(c.body))
|
||||
})
|
||||
_, err := store.extractJobPosting(context.Background(), "https://x.com/1", "t", "text")
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *postingReadError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The extract handler runs without a database, so it can be driven whole: the
|
||||
// page text must be cut to the limit the Python side enforces before it is
|
||||
// forwarded, or a long page would come back as an opaque 422.
|
||||
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
var forwardedLen int
|
||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
forwardedLen = len([]rune(body["text"]))
|
||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": null, "notes": null}`))
|
||||
})
|
||||
r := gin.New()
|
||||
r.POST("/extract", store.JobCaptureExtract)
|
||||
|
||||
post := func(body string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
|
||||
return rec
|
||||
}
|
||||
|
||||
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "t", "text": strings.Repeat("é", maxPageRunes+500)})
|
||||
rec := post(string(long))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
|
||||
}
|
||||
if forwardedLen != maxPageRunes {
|
||||
t.Fatalf("forwarded %d runes, want %d", forwardedLen, maxPageRunes)
|
||||
}
|
||||
var out ExtractedJobPosting
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Company != "Acme" {
|
||||
t.Fatalf("body = %s (%v)", rec.Body, err)
|
||||
}
|
||||
|
||||
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("blank text: status = %d", rec.Code)
|
||||
}
|
||||
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("bad body: status = %d", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -1,178 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat.
|
||||
//
|
||||
// Files land in one of two directories. /backend/uploads/ is served by nginx
|
||||
// at /uploads/ with no authentication, so anything written there is publicly
|
||||
// reachable by URL — which is why the extension and content checks below
|
||||
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
|
||||
// messages and is served at /uploads/private/ behind an nginx auth_request
|
||||
// gate; only an admin may upload there.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
||||
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
|
||||
".pdf": true, ".txt": true,
|
||||
}
|
||||
|
||||
// extensionToMIMEPrefix cross-checks the sniffed content type against the
|
||||
// claimed extension, to stop e.g. HTML being served from a .png URL.
|
||||
//
|
||||
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
|
||||
// http.DetectContentType's answers for them are unreliable enough to reject
|
||||
// legitimate files, so a missing entry means "extension allowed, content not
|
||||
// verified".
|
||||
var extensionToMIMEPrefix = map[string]string{
|
||||
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
|
||||
".mp4": "video/", ".webm": "video/",
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// publicUploadDir and privateUploadDir are the two destinations; the private
|
||||
// one is created on demand because nothing else guarantees it exists.
|
||||
const (
|
||||
publicUploadDir = "/backend/uploads/"
|
||||
privateUploadDir = "/backend/uploads/private/"
|
||||
)
|
||||
|
||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
||||
// the URL of the stored file, which the client then sends over the WebSocket
|
||||
// as a message's fileUrl.
|
||||
//
|
||||
// The multipart form takes an optional "private" field: "true" stores the file
|
||||
// under /uploads/private/ for use as a private message's attachment. That is
|
||||
// admin-only, because private messages themselves are — an attachment URL
|
||||
// leaking out is the same disclosure as the message leaking out.
|
||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
const maxSize = 10 << 20 // 10MB
|
||||
if file.Size > maxSize {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
|
||||
return
|
||||
}
|
||||
|
||||
ext := strings.ToLower(filepath.Ext(file.Filename))
|
||||
if !allowedExtensions[ext] {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate actual content type matches extension
|
||||
f, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
// 512 bytes is exactly what http.DetectContentType inspects; reading more
|
||||
// would be wasted. A single Read may return fewer bytes than asked for,
|
||||
// which is fine — sniffing works on a short prefix — so only a read that
|
||||
// produced nothing at all is an error.
|
||||
buf := make([]byte, 512)
|
||||
n, err := f.Read(buf)
|
||||
f.Close()
|
||||
if err != nil && n == 0 {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
|
||||
return
|
||||
}
|
||||
detectedType := http.DetectContentType(buf[:n])
|
||||
|
||||
expectedPrefix, ok := extensionToMIMEPrefix[ext]
|
||||
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
|
||||
return
|
||||
}
|
||||
|
||||
// The uploaded name is discarded entirely in favour of 16 random bytes
|
||||
// from crypto/rand. That kills path traversal and collisions in one go,
|
||||
// and makes the resulting URL unguessable. Only the extension is carried
|
||||
// over, and it has already been checked against the allow-list.
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
|
||||
return
|
||||
}
|
||||
filename := hex.EncodeToString(b) + ext
|
||||
|
||||
uploadDir := publicUploadDir
|
||||
urlPrefix := "/uploads/"
|
||||
if private {
|
||||
uploadDir = privateUploadDir
|
||||
urlPrefix = "/uploads/private/"
|
||||
// 0755 so nginx (a different user) can traverse the directory to
|
||||
// serve the files once its auth_request gate has approved.
|
||||
if err := os.MkdirAll(uploadDir, 0755); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
}
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
// sniffing, and multipart files may be backed by either memory or a temp
|
||||
// file, so a fresh reader is the simplest correct option.
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
||||
return
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, src); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
@@ -1,19 +1,16 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -39,68 +36,21 @@ type ExtractedRowingData struct {
|
||||
|
||||
// rowingReadPath is the Python route. It is internal: nginx refuses
|
||||
// /py/internal/ and the route itself refuses anything nginx forwarded, so the
|
||||
// only way in is this direct container-to-container call.
|
||||
// only way in is the direct container-to-container call services.CallPython
|
||||
// makes.
|
||||
const rowingReadPath = "/internal/rowing/read"
|
||||
|
||||
// rowingReadClient bounds the wait on the Python service. Two minutes sits
|
||||
// above that side's own worst case (a 30s Claude timeout, retried twice with
|
||||
// backoff), so a slow Claude surfaces as Python's error rather than as a
|
||||
// timeout here.
|
||||
var rowingReadClient = &http.Client{Timeout: 2 * time.Minute}
|
||||
|
||||
// displayReadError is a failure the Python service reported in words that are
|
||||
// safe and useful to show the admin (its 502 detail), as opposed to a
|
||||
// transport or decoding failure, which is only logged.
|
||||
type displayReadError struct{ detail string }
|
||||
|
||||
func (e *displayReadError) Error() string { return e.detail }
|
||||
|
||||
// readRowingDisplay sends the image to the Python service and returns what
|
||||
// Claude read off it. No plausibility checking happens on either side of this
|
||||
// call; that is CreateRowing's job.
|
||||
// call; that is CreateRowing's job. A failure the reader described in its own
|
||||
// words comes back as a *services.PythonError (see services.CallPython).
|
||||
func (store *Store) readRowingDisplay(ctx context.Context, mediaType string, image []byte) (ExtractedRowingData, error) {
|
||||
var extracted ExtractedRowingData
|
||||
|
||||
// encoding/json writes a []byte as standard base64, which is the form the
|
||||
// Anthropic API wants and so what the Python side passes straight through.
|
||||
body, err := json.Marshal(struct {
|
||||
// Data is a []byte so that it is sent as standard base64, the encoding
|
||||
// the Anthropic API expects.
|
||||
return services.CallPython[ExtractedRowingData](ctx, store.PythonURL, rowingReadPath, struct {
|
||||
MediaType string `json:"media_type"`
|
||||
Data []byte `json:"data"`
|
||||
}{mediaType, image})
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+rowingReadPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := rowingReadClient.Do(req)
|
||||
if err != nil {
|
||||
return extracted, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
// FastAPI errors are {"detail": ...}. Only a 502 carries one of the
|
||||
// reader's own fixed messages; a 422's detail is a list, which fails
|
||||
// to decode into the string and falls through to the generic error.
|
||||
var failure struct {
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
||||
return extracted, &displayReadError{detail: failure.Detail}
|
||||
}
|
||||
return extracted, fmt.Errorf("rowing reader returned %d: %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(&extracted); err != nil {
|
||||
return extracted, fmt.Errorf("decoding rowing reader response: %w", err)
|
||||
}
|
||||
return extracted, nil
|
||||
}
|
||||
|
||||
// GetRowing backs the public GET /rowing with every logged session, newest
|
||||
@@ -219,9 +169,9 @@ func (store *Store) CreateRowing(ctx *gin.Context) {
|
||||
// passed on; anything else is a plumbing failure the admin can do
|
||||
// nothing with.
|
||||
msg := "failed to process image"
|
||||
var readErr *displayReadError
|
||||
var readErr *services.PythonError
|
||||
if errors.As(err, &readErr) {
|
||||
msg = readErr.detail
|
||||
msg = readErr.Detail
|
||||
}
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": msg})
|
||||
return
|
||||
|
||||
@@ -7,6 +7,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
)
|
||||
|
||||
// readRowingDisplay is the Go half of the contract with the Python service's
|
||||
@@ -63,7 +65,7 @@ func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
wantDetail string // non-empty: a displayReadError with this message
|
||||
wantDetail string // non-empty: a services.PythonError with this message
|
||||
}{
|
||||
{"reader failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse image data"}`, "failed to parse image data"},
|
||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
||||
@@ -82,12 +84,12 @@ func TestReadRowingDisplayErrors(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
var readErr *displayReadError
|
||||
var readErr *services.PythonError
|
||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
||||
}
|
||||
if readErr != nil && readErr.detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
||||
if readErr != nil && readErr.Detail != c.wantDetail {
|
||||
t.Fatalf("detail = %q, want %q", readErr.Detail, c.wantDetail)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Upload backs POST /uploads (login required): the one endpoint the frontend
|
||||
// stores a file through (vue/src/uploads.js). Multipart form:
|
||||
//
|
||||
// file the file (required)
|
||||
// private "true" to store it as an admin-only chat attachment
|
||||
//
|
||||
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
|
||||
// the file was refused (wrong type, too large) and 500 when storing failed.
|
||||
// Validation, naming and storage are all services.Uploads.Save; this handler
|
||||
// only reads the form and decides who may use `private`.
|
||||
//
|
||||
// `private` is admin-only because private messages themselves are: an
|
||||
// attachment URL leaking out is the same disclosure as the message leaking.
|
||||
func (store *Store) Upload(ctx *gin.Context) {
|
||||
private := ctx.PostForm("private") == "true"
|
||||
if private && !requestIsAdmin(ctx) {
|
||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||
return
|
||||
}
|
||||
|
||||
file, err := ctx.FormFile("file")
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
||||
return
|
||||
}
|
||||
|
||||
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
|
||||
var rejected *services.UploadError
|
||||
switch {
|
||||
case errors.As(err, &rejected):
|
||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
|
||||
case err != nil:
|
||||
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
default:
|
||||
ctx.JSON(http.StatusOK, gin.H{"url": url})
|
||||
}
|
||||
}
|
||||
|
||||
// ListUploads backs GET /uploads (admin): every public upload, newest first,
|
||||
// for the upload picker on the canvas pages (vue/src/components/util/
|
||||
// UploadPicker.vue). It answers {"files": [{name, url, size, modified}]}.
|
||||
//
|
||||
// Admin-only because the listing is the one thing that turns unguessable
|
||||
// upload URLs into known ones; see services.Uploads.List.
|
||||
func (store *Store) ListUploads(ctx *gin.Context) {
|
||||
files, err := store.Uploads.List(ctx.Request.Context())
|
||||
if err != nil {
|
||||
log.Printf("[upload] listing failed: %v", err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list uploads"})
|
||||
return
|
||||
}
|
||||
if files == nil {
|
||||
files = []services.StoredFile{} // [] rather than null for the frontend
|
||||
}
|
||||
ctx.JSON(http.StatusOK, gin.H{"files": files})
|
||||
}
|
||||
|
||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
||||
//
|
||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
||||
// public attachments — so the admin check is made here from the same
|
||||
// "userClaims" value AdminMiddleware would have read.
|
||||
func requestIsAdmin(ctx *gin.Context) bool {
|
||||
claims, exists := ctx.Get("userClaims")
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
admin, ok := (*mapClaims)["admin"].(bool)
|
||||
|
||||
return ok && admin
|
||||
}
|
||||
@@ -14,23 +14,22 @@ import (
|
||||
|
||||
// What is deliberately NOT covered here, and why:
|
||||
//
|
||||
// - Every handler method (Login, UploadMessageFile, the radio file movers,
|
||||
// - Every handler method (Login, Upload, the radio file movers,
|
||||
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
|
||||
// multipart request, the container's /backend/... directories, or a paid
|
||||
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
|
||||
// CI.
|
||||
// - The radio/chat upload filename sanitisation itself. It is written inline
|
||||
// inside the handler bodies rather than in a helper, so testing it would
|
||||
// mean either driving a full multipart upload against the real upload
|
||||
// directories or refactoring production code. Neither was in scope, so the
|
||||
// part that *is* extractable — the extension allow-lists those handlers
|
||||
// gate on — is covered as a table contract below instead.
|
||||
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
|
||||
// reach the database on the refresh path.
|
||||
// - The radio upload's filename sanitisation. It is written inline in the
|
||||
// handler, so only the extension allow-list it gates on is covered, as a
|
||||
// table contract below. (The site's general uploads — validation, naming,
|
||||
// storage — are services.Uploads, tested in services/uploads_test.go.)
|
||||
// - Store.isAdminRequest, and the validate endpoints past their first
|
||||
// check: they authenticate against the database. The allow/deny rule the
|
||||
// permission gate applies is services.HasPermission, tested there.
|
||||
//
|
||||
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
|
||||
// three shared caches, the admin claim check on the upload trust boundary, and
|
||||
// the upload allow-list tables.
|
||||
// the radio allow-list.
|
||||
|
||||
// --- Spotify OAuth CSRF nonces -------------------------------------------
|
||||
|
||||
@@ -253,57 +252,40 @@ func TestRequestIsAdmin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The allow-list tables are the upload trust boundary's data. Testing them as
|
||||
// data catches the realistic failure: someone adding an executable or markup
|
||||
// extension, or adding an extension to the MIME map without allowing it (which
|
||||
// would be dead configuration).
|
||||
func TestUploadAllowLists(t *testing.T) {
|
||||
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
|
||||
// Served by nginx from a public directory with no auth, so anything
|
||||
// the browser will execute or render as markup must not be storable.
|
||||
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
|
||||
if allowedExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed chat upload extension", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
// --- Permission gate ------------------------------------------------------
|
||||
|
||||
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
|
||||
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
|
||||
// any other shape is unreachable.
|
||||
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
|
||||
for ext := range m {
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("malformed allow-list key %q", ext)
|
||||
}
|
||||
}
|
||||
// An unknown key must be refused before any session lookup (Store has no DB
|
||||
// or Auth here, so reaching one would panic): it is how a typo in 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())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
|
||||
for ext := range extensionToMIMEPrefix {
|
||||
if !allowedExtensions[ext] {
|
||||
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
|
||||
}
|
||||
// The radio allow-list is the radio upload's trust boundary. Testing it as
|
||||
// data catches the realistic failure: someone adding a non-audio or malformed
|
||||
// extension.
|
||||
func TestRadioAllowList(t *testing.T) {
|
||||
for ext := range allowedAudioExtensions {
|
||||
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
|
||||
// any other shape is unreachable.
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("malformed allow-list key %q", ext)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("audio extensions are content-unverified by design", func(t *testing.T) {
|
||||
// http.DetectContentType is unreliable for these, so a missing entry
|
||||
// means "extension allowed, content not verified". Adding one would
|
||||
// start rejecting legitimate uploads.
|
||||
for _, ext := range []string{".mp3", ".ogg"} {
|
||||
if _, ok := extensionToMIMEPrefix[ext]; ok {
|
||||
t.Errorf("%q should not be MIME-checked", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("radio allow-list is audio only", func(t *testing.T) {
|
||||
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
|
||||
if allowedAudioExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed radio upload extension", ext)
|
||||
}
|
||||
}
|
||||
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
|
||||
if allowedAudioExtensions[ext] {
|
||||
t.Errorf("%q must not be an allowed radio upload extension", ext)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,21 +32,15 @@ type Store struct {
|
||||
Auth *services.Auth
|
||||
Notes *services.Notes
|
||||
LoginLimiter *services.RateLimiter
|
||||
EmailSync *services.EmailSyncService
|
||||
|
||||
// Base URL of the Python service on the Docker network, no trailing
|
||||
// slash. Used for the calls that bypass nginx: reading a rowing display
|
||||
// photo (handle_rowing.go) and a job posting (handle_job_capture.go).
|
||||
// slash. Used for the calls that bypass nginx, all through
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go).
|
||||
PythonURL string
|
||||
|
||||
// Bearer token for the browser capture routes (handle_job_capture.go),
|
||||
// generated from the admin panel. Nil, or holding no token, means those
|
||||
// routes are switched off, not open.
|
||||
CaptureToken *services.CaptureToken
|
||||
|
||||
// Registry of .env variables and the request/status hand-off with the
|
||||
// host that applies changes to them (handle_env.go).
|
||||
Env *services.EnvManager
|
||||
// Stores uploaded files and says where they are served
|
||||
// (services.Uploads.Save). Used by the Upload handler.
|
||||
Uploads *services.Uploads
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
|
||||
+39
-89
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
@@ -27,8 +26,9 @@ import (
|
||||
// setting from the environment, builds the services, packs them into one
|
||||
// handlers.Store, and registers the routes. There are three route groups —
|
||||
// open, `protected` (valid access token) and `admin` (token with admin=true)
|
||||
// — plus the GraphQL endpoint, which does its own per-resolver authorisation
|
||||
// instead of using middleware. See backend/README.md for the wider picture.
|
||||
// — plus the GraphQL endpoint, which is authorised by the @admin / @signedIn
|
||||
// directives in its schema instead of by middleware. See backend/README.md
|
||||
// for the wider picture.
|
||||
func main() {
|
||||
// Logs go to both stdout (so `docker compose logs` works) and a file in a
|
||||
// mounted volume (so they survive the container).
|
||||
@@ -89,12 +89,10 @@ func main() {
|
||||
spotifyConfig := services.SpotifyConfig{RedirectURL: spotifyRedirectURL, ClientID: spotifyClientID, ClientSecret: spotifyClientSecret}
|
||||
spotifyAuth, spotifyClient := services.InitSpotifyAuth(&spotifyConfig)
|
||||
|
||||
// CLAUDE
|
||||
// Only the email pipeline uses this client now; the rowing photo reader's
|
||||
// Claude call moved to the Python service, which reads the same key.
|
||||
claudeAPIKey := os.Getenv("CLAUDE_API_KEY")
|
||||
claudeConfig := services.ClaudeConfig{APIKey: claudeAPIKey}
|
||||
claudeClient := services.InitClaude(&claudeConfig)
|
||||
// No Claude client here: the site's one Claude call, the rowing photo
|
||||
// reader, is made by the Python service, which is the only container of
|
||||
// the site's own that reads CLAUDE_API_KEY. The backend reaches it at
|
||||
// pythonURL, below. (The job tracker, a separate container, makes its own.)
|
||||
|
||||
authSecret := os.Getenv("BACKEND_SECRET")
|
||||
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
|
||||
@@ -117,9 +115,9 @@ func main() {
|
||||
steamID := os.Getenv("STEAM_ID")
|
||||
|
||||
// PYTHON SERVICE
|
||||
// Called directly over the Docker network, not through nginx, for the
|
||||
// rowing photo reader. The defaults mirror docker-compose.yml, where both
|
||||
// variables are optional.
|
||||
// Called directly over the Docker network, not through nginx, for its
|
||||
// /internal/ Claude route (services/python_call.go). The defaults
|
||||
// mirror docker-compose.yml, where both variables are optional.
|
||||
pythonHost := os.Getenv("PYTHON_HOST")
|
||||
if pythonHost == "" {
|
||||
pythonHost = "python"
|
||||
@@ -130,54 +128,27 @@ func main() {
|
||||
}
|
||||
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
|
||||
|
||||
// EMAIL SYNC
|
||||
// An unparseable EMAIL_SYNC_INTERVAL is silently ignored and the 30
|
||||
// minute default stands — a typo here fails quietly.
|
||||
emailSyncInterval := 30 * time.Minute
|
||||
if interval := os.Getenv("EMAIL_SYNC_INTERVAL"); interval != "" {
|
||||
if parsed, err := time.ParseDuration(interval); err == nil {
|
||||
emailSyncInterval = parsed
|
||||
}
|
||||
// UPLOADS
|
||||
// Public uploads go to the Garage bucket (and to the shared `uploads`
|
||||
// volume when Garage refuses a write, or when S3_ENDPOINT is unset);
|
||||
// private ones to the volume. See services/uploads.go. Region and bucket
|
||||
// default to what garage/garage.toml and garage/bootstrap.sh set up.
|
||||
s3Region := os.Getenv("S3_REGION")
|
||||
if s3Region == "" {
|
||||
s3Region = "garage"
|
||||
}
|
||||
emailSyncConfig := services.EmailSyncConfig{
|
||||
Backend: os.Getenv("EMAIL_BACKEND"),
|
||||
ClientID: os.Getenv("MSGRAPH_CLIENT_ID"),
|
||||
ClientSecret: os.Getenv("MSGRAPH_CLIENT_SECRET"),
|
||||
TenantID: os.Getenv("MSGRAPH_TENANT_ID"),
|
||||
RedirectURI: os.Getenv("MSGRAPH_REDIRECT_URI"),
|
||||
IMAP: &services.IMAPConfig{
|
||||
Host: os.Getenv("IMAP_HOST"),
|
||||
Port: os.Getenv("IMAP_PORT"),
|
||||
Email: os.Getenv("IMAP_EMAIL"),
|
||||
Password: os.Getenv("IMAP_PASSWORD"),
|
||||
},
|
||||
SyncInterval: emailSyncInterval,
|
||||
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
|
||||
s3Bucket := os.Getenv("S3_BUCKET")
|
||||
if s3Bucket == "" {
|
||||
s3Bucket = "uploads"
|
||||
}
|
||||
emailSync := services.InitEmailSync(&emailSyncConfig, db, claudeClient)
|
||||
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
|
||||
uploads := services.NewUploads(s3Config, "/backend/uploads/", "/backend/uploads/private/")
|
||||
|
||||
// 5 login attempts per IP per minute, applied by both the REST handler
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
// JOB CAPTURE
|
||||
// The userscript's bearer token is generated in the admin panel and kept
|
||||
// (hashed) beside the OAuth tokens. A damaged file is logged, not fatal:
|
||||
// capture stays off until a new token is generated.
|
||||
captureToken, err := services.InitCaptureToken(services.CAPTURE_TOKEN_JSON_PATH)
|
||||
if err != nil {
|
||||
log.Println("Job capture token not loaded:", err)
|
||||
}
|
||||
|
||||
// ENVIRONMENT
|
||||
// The registry is embedded, so the only way this fails is a malformed
|
||||
// env_registry.json — a build mistake worth stopping for.
|
||||
envManager, err := services.NewEnvManager(services.ENV_APPLY_DIR)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, EmailSync: emailSync, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, CaptureToken: captureToken, Env: envManager}
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Uploads: uploads}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
@@ -186,13 +157,6 @@ func main() {
|
||||
protected := r.Group("/", store.AuthMiddlewear)
|
||||
admin := r.Group("/", store.AuthMiddlewear, store.AdminMiddleware)
|
||||
|
||||
// JOB CAPTURE: called by the browser userscript from other origins, so
|
||||
// these authenticate with a bearer token instead of the session cookies.
|
||||
capture := r.Group("/jobs/capture", store.CaptureTokenMiddleware)
|
||||
capture.GET("/status", store.JobCaptureStatus)
|
||||
capture.POST("/extract", store.JobCaptureExtract)
|
||||
capture.POST("", store.JobCapture)
|
||||
|
||||
// ROWING
|
||||
r.GET("/rowing", store.GetRowing)
|
||||
admin.POST("/rowing", store.CreateRowing)
|
||||
@@ -203,10 +167,7 @@ func main() {
|
||||
r.GET("/auth/check", store.CheckToken)
|
||||
r.POST("/auth/logout", store.Logout)
|
||||
r.GET("/auth/validate-admin", store.ValidateAdmin)
|
||||
|
||||
// EMAIL SYNC
|
||||
r.GET("/email/callback", store.CompleteEmailAuth)
|
||||
admin.POST("/email/sync", store.TriggerEmailSync)
|
||||
r.GET("/auth/validate/:permission", store.ValidatePermission)
|
||||
|
||||
// SPOTIFY
|
||||
// The callback must be open — Spotify redirects a logged-out browser to
|
||||
@@ -229,33 +190,29 @@ func main() {
|
||||
// /ws is deliberately outside the protected group: chat is public, and
|
||||
// the handler checks the cookies itself to decide admin privileges.
|
||||
r.GET("/ws", store.ConnectWebSocket)
|
||||
protected.POST("/messages/upload", store.UploadMessageFile)
|
||||
protected.POST("/uploads", store.Upload)
|
||||
admin.GET("/uploads", store.ListUploads)
|
||||
|
||||
// NOTES
|
||||
admin.GET("/notes/*path", store.GetNoteFile)
|
||||
|
||||
// ADMIN DIAGNOSTICS: log tail for the admin panel.
|
||||
admin.GET("/admin/logs", store.Logs)
|
||||
// ENVIRONMENT: report on .env and queue changes for the host to apply.
|
||||
admin.GET("/admin/env", store.GetEnv)
|
||||
admin.PUT("/admin/env", store.UpdateEnv)
|
||||
admin.GET("/admin/env/status", store.GetEnvStatus)
|
||||
admin.DELETE("/admin/env/pending", store.CancelEnv)
|
||||
// The job capture token is managed with the session cookie, never with
|
||||
// the token itself.
|
||||
admin.GET("/admin/capture-token", store.GetCaptureToken)
|
||||
admin.POST("/admin/capture-token", store.GenerateCaptureToken)
|
||||
admin.DELETE("/admin/capture-token", store.RevokeCaptureToken)
|
||||
|
||||
// GRAPHQL
|
||||
// GraphQL is assembled by hand rather than with handler.NewDefaultServer
|
||||
// so the transports and extensions below are explicit.
|
||||
//
|
||||
// Note the whole API is one POST route with no middleware guard:
|
||||
// authorisation happens per resolver via IsAdminFromCtx / UserIDFromCtx,
|
||||
// so a new resolver is PUBLIC until it checks for itself.
|
||||
// Note the whole API is one POST route with no middleware guard.
|
||||
// Authorisation is declared in the schema instead: a field marked @admin
|
||||
// or @signedIn is refused by the matching function in graph.Directives()
|
||||
// before its resolver runs. A field with neither is PUBLIC, so a new
|
||||
// mutation needs one — graph/directives_test.go fails until it has one or
|
||||
// is added to the list of deliberately public fields there.
|
||||
//
|
||||
// Directives must stay wired here: gqlgen fails closed on a nil directive
|
||||
// (the field errors with "directive admin is not implemented"), so
|
||||
// dropping this line breaks every guarded field rather than opening it.
|
||||
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Resolvers: &graph.Resolver{Store: &store},
|
||||
Directives: graph.Directives(),
|
||||
}))
|
||||
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
|
||||
gqlSrv.AddTransport(transport.Options{})
|
||||
@@ -289,13 +246,6 @@ func main() {
|
||||
c.JSON(200, gin.H{"message": "Hello World"})
|
||||
})
|
||||
|
||||
// The scheduler runs until ctx is cancelled, which in practice only
|
||||
// happens if r.Run returns — there is no signal handling or graceful
|
||||
// shutdown, so the container is simply killed.
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go store.EmailSync.StartScheduler(ctx)
|
||||
|
||||
port := os.Getenv("BACKEND_PORT")
|
||||
// Blocks until the server stops. Any return is a failure — a port clash,
|
||||
// most often — so it must exit non-zero, or Docker sees a clean shutdown
|
||||
|
||||
+160
-79
@@ -20,8 +20,9 @@ import (
|
||||
// every subsequent query silently filters those rows out. Rows are never
|
||||
// actually removed, and a uniqueIndex still sees deleted rows, so a
|
||||
// soft-deleted username cannot be reused.
|
||||
// - IDs are uint in Go but Int in GraphQL, which is why nearly every type
|
||||
// has a hand-written ID resolver doing int(obj.ID).
|
||||
// - IDs are uint here and the ID scalar in GraphQL. gqlgen.yml binds the
|
||||
// two directly (graphql.UintID), so an `ID uint` field needs no resolver.
|
||||
// On the wire an id is a quoted decimal string, "12".
|
||||
|
||||
// User is an account. There is no public sign-up: users are created by an
|
||||
// existing admin through the createUser mutation, or by the dev seeder.
|
||||
@@ -38,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
|
||||
@@ -137,57 +146,6 @@ type Bookmark struct {
|
||||
Link string `gorm:"not null" json:"link"`
|
||||
}
|
||||
|
||||
// JobAppReference is a reusable snippet for filling in job application forms
|
||||
// (a stock answer, a profile link, and so on), grouped by Category and
|
||||
// ordered within it by SortOrder.
|
||||
type JobAppReference struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Category string `gorm:"not null" json:"category"`
|
||||
Label string `gorm:"not null" json:"label"`
|
||||
Value string `gorm:"not null" json:"value"`
|
||||
SortOrder int `gorm:"default:0" json:"sortOrder"`
|
||||
}
|
||||
|
||||
// ProcessedEmail records that the email pipeline has already looked at a
|
||||
// message, so it is never classified twice.
|
||||
//
|
||||
// Unlike every other model it has no DeletedAt and so is NOT soft deleted —
|
||||
// the dedup check must see every historical row. Its CreatedAt also drives
|
||||
// the next sync's time window, so the most recent row here is effectively the
|
||||
// pipeline's cursor. A row is written even when classification failed, with
|
||||
// Action "error", which means failures are never retried.
|
||||
type ProcessedEmail struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
// The provider's message id: Microsoft Graph's id on the Graph backend,
|
||||
// the RFC822 Message-ID header on IMAP. Unique, which is what makes the
|
||||
// dedup check safe against a concurrent sync.
|
||||
GraphMessageID string `gorm:"uniqueIndex;not null" json:"graphMessageId"`
|
||||
Subject string `gorm:"not null" json:"subject"`
|
||||
Action string `gorm:"not null" json:"action"`
|
||||
// The application this email created or updated, if any. A plain nullable
|
||||
// column, not a GORM association — nothing preloads it.
|
||||
JobAppID *uint `json:"jobAppId"`
|
||||
// Attempts counts how many times processing this email has been tried.
|
||||
// A row with Action "error" and Attempts below the cap is retryable: the
|
||||
// next sync re-processes it instead of skipping it. Once Attempts reaches
|
||||
// the cap the row becomes terminal, so a genuinely unprocessable email
|
||||
// (one Claude can never parse) eventually stops consuming API calls.
|
||||
// Rows written before this column existed default to 1 and so get their
|
||||
// remaining attempts.
|
||||
Attempts int `gorm:"not null;default:1" json:"attempts"`
|
||||
// ReceivedAt is the provider's own timestamp for the email, as distinct
|
||||
// from CreatedAt (when we processed it). It exists so a retryable failure
|
||||
// can pull the fetch window back far enough to actually re-fetch the
|
||||
// email: the window is otherwise anchored to processing time, which would
|
||||
// have already advanced past it. Zero for rows written before this
|
||||
// column existed, and for those the clamp is skipped.
|
||||
ReceivedAt time.Time `json:"receivedAt"`
|
||||
}
|
||||
|
||||
// Place is an entry on the places-to-go list. Creating or editing one needs
|
||||
// only a signed-in user, not an admin — the one exception to the
|
||||
// admin-writes-everything rule.
|
||||
@@ -206,30 +164,153 @@ type Place struct {
|
||||
Done bool `gorm:"default:false" json:"done"`
|
||||
}
|
||||
|
||||
// JobApplication is a tracked job application. Rows are created by hand
|
||||
// through GraphQL, automatically by the email pipeline, or from the browser
|
||||
// by the capture userscript (handlers/handle_job_capture.go).
|
||||
//
|
||||
// Status is a free-form string, but only the values ranked in
|
||||
// services.statusOrder ("saved", "applied", "screening", "assessment",
|
||||
// "interviewing", "offer", "rejected", "withdrawn") can be advanced
|
||||
// automatically; the pipeline matches an existing application on
|
||||
// (Company, JobTitle) compared case-insensitively.
|
||||
//
|
||||
// Description is the posting's text as captured from the page, kept because
|
||||
// postings are usually taken down long before the interview. It is large, so
|
||||
// list queries should not select it.
|
||||
type JobApplication struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
JobTitle string `gorm:"not null" json:"jobTitle"`
|
||||
Company string `gorm:"not null" json:"company"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
Status string `gorm:"not null" json:"status"`
|
||||
Notes *string `json:"notes"`
|
||||
AppliedAt *time.Time `json:"appliedAt"`
|
||||
Description *string `gorm:"type:text" json:"description"`
|
||||
// Box is one panel on a canvas page. Page names the canvas it belongs to:
|
||||
// "index" for the landing page, or a Page.Slug for an admin-created page
|
||||
// (the home page is the Page "stp") — it is a key, not a foreign key, so the
|
||||
// built-in landing canvas needs no Page row. Its position and size are in px on a
|
||||
// fixed 1400px-wide design canvas, which the page scales down on narrower
|
||||
// screens — so the stored numbers mean the same thing for every visitor. Kind "widget" renders a built-in Vue component named by Widget;
|
||||
// kind "html" renders HTML in a sandboxed iframe on the front end, which is
|
||||
// what makes storing admin-authored script here acceptable.
|
||||
type Box struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
// default:stp is what the boxes that predate pages are migrated to.
|
||||
Page string `gorm:"not null;default:stp;index" json:"page"`
|
||||
Kind string `gorm:"not null" json:"kind"`
|
||||
Widget *string `json:"widget"`
|
||||
HTML *string `json:"html"`
|
||||
Title *string `json:"title"`
|
||||
X int `gorm:"not null;default:0" json:"x"`
|
||||
Y int `gorm:"not null;default:0" json:"y"`
|
||||
W int `gorm:"not null;default:300" json:"w"`
|
||||
H int `gorm:"not null;default:200" json:"h"`
|
||||
Z int `gorm:"not null;default:0" json:"z"`
|
||||
// No gorm default on Framed: GORM omits zero values for defaulted columns
|
||||
// on insert, so default:true would turn an explicit false into true.
|
||||
// CreateBox applies the true default itself.
|
||||
Framed bool `gorm:"not null" json:"framed"`
|
||||
// Shadow is a CSS box-shadow value drawn around the box, or "" for none.
|
||||
// It is independent of Framed, so an unframed box can still cast one.
|
||||
Shadow string `gorm:"not null;default:''" json:"shadow"`
|
||||
HideOnMobile bool `gorm:"not null;default:false" json:"hideOnMobile"`
|
||||
// AdminOnly boxes are never sent to anyone but an admin (the boxes
|
||||
// resolver filters them out), so they suit private notes.
|
||||
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
|
||||
// ComponentID links an html box to a Component, whose HTML it shows
|
||||
// instead of its own: the row's HTML is nil, and the resolvers fill it in
|
||||
// from the component before answering (graph/component_helpers.go). There
|
||||
// is deliberately no association field — with one, DB.Save(&box) would
|
||||
// write the component back too.
|
||||
ComponentID *uint `gorm:"index" json:"componentId"`
|
||||
}
|
||||
|
||||
// Page is an admin-created canvas page, served by the SPA's catch-all route
|
||||
// at /<Slug> (e.g. "shrines/evangelion"). Its content is the Boxes whose Page
|
||||
// equals Slug. The unique index is partial so that a deleted page's slug can
|
||||
// be reused — a plain uniqueIndex would still collide with the soft-deleted
|
||||
// row.
|
||||
type Page struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Slug string `gorm:"not null;index:idx_pages_slug,unique,where:deleted_at IS NULL" json:"slug"`
|
||||
Title string `gorm:"not null" json:"title"`
|
||||
// AdminOnly hides the whole page, boxes included, from everyone else.
|
||||
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
|
||||
}
|
||||
|
||||
// Background is the page background behind one canvas (Page is the same page
|
||||
// key a Box has: "index" for the landing page, or a Page's slug), so
|
||||
// built-in canvases and admin-created pages are set the same way. A page with
|
||||
// no row shows the theme's halftone; deleting the row is "reset to default".
|
||||
// The unique index is partial for the same reason as Page's.
|
||||
type Background struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Page string `gorm:"not null;index:idx_backgrounds_page,unique,where:deleted_at IS NULL" json:"page"`
|
||||
// Color is a CSS colour, or "" for the theme's page colour.
|
||||
Color string `gorm:"not null;default:''" json:"color"`
|
||||
// Image is a URL, or "" for none. Drawn over Color.
|
||||
Image string `gorm:"not null;default:''" json:"image"`
|
||||
// Fit is how Image fills the window: "cover", "contain" or "tile".
|
||||
Fit string `gorm:"not null;default:cover" json:"fit"`
|
||||
}
|
||||
|
||||
// Layout is a named copy of one canvas page's boxes and background, saved so
|
||||
// it can be loaded onto any page later (graph/layout_helpers.go). It is a
|
||||
// snapshot, not a link: loading it creates new boxes that belong to the
|
||||
// target page, so editing either page afterwards never touches the other or
|
||||
// the layout. The content is JSON rather than child rows because nothing
|
||||
// queries inside it — it is only ever written whole and read whole. The
|
||||
// unique index is partial for the same reason as Page's.
|
||||
type Layout struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Name string `gorm:"not null;index:idx_layouts_name,unique,where:deleted_at IS NULL" json:"name"`
|
||||
// SourcePage is the page key it was saved from, for the list only.
|
||||
SourcePage string `gorm:"not null" json:"sourcePage"`
|
||||
// Boxes is a JSON array of the boxes' content and geometry, without id
|
||||
// or page.
|
||||
Boxes string `gorm:"type:text;not null" json:"-"`
|
||||
// Background is the page's background as JSON, or nil if it had none.
|
||||
Background *string `gorm:"type:text" json:"-"`
|
||||
}
|
||||
|
||||
// Component is a named HTML box that can be placed on any canvas page, either
|
||||
// as a copy (an ordinary box) or linked (a box with ComponentID set). Linked
|
||||
// boxes share only the HTML — editing it changes every one of them at once —
|
||||
// while title, geometry, frame and visibility stay each box's own, since
|
||||
// those are about where it sits on a page rather than what it is. Title, W,
|
||||
// H, Framed, Shadow and AdminOnly are the defaults a newly placed box starts
|
||||
// with.
|
||||
// Widgets are not components: a widget box is just a name, with nothing
|
||||
// worth sharing. The unique index is partial for the same reason as Page's.
|
||||
type Component struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Name string `gorm:"not null;index:idx_components_name,unique,where:deleted_at IS NULL" json:"name"`
|
||||
Title *string `json:"title"`
|
||||
HTML string `gorm:"type:text;not null" json:"html"`
|
||||
W int `gorm:"not null" json:"w"`
|
||||
H int `gorm:"not null" json:"h"`
|
||||
// No gorm default on Framed, for the same reason as Box.Framed.
|
||||
Framed bool `gorm:"not null" json:"framed"`
|
||||
Shadow string `gorm:"not null;default:''" json:"shadow"`
|
||||
AdminOnly bool `gorm:"not null;default:false" json:"adminOnly"`
|
||||
}
|
||||
|
||||
// CoverLetter is a saved letter from the /cv Cover Letter tab. Body is the
|
||||
// whole letter as JSON (contact block, sections, paragraphs; the shape is
|
||||
// views/CV/coverLetter.js's) because only the frontend ever reads inside it —
|
||||
// the same reasoning as Layout.Boxes. The unique index is partial for the
|
||||
// same reason as Page's.
|
||||
type CoverLetter struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Name string `gorm:"not null;index:idx_cover_letters_name,unique,where:deleted_at IS NULL" json:"name"`
|
||||
Body string `gorm:"type:text;not null" json:"body"`
|
||||
}
|
||||
|
||||
// CoverSnippet is a reusable paragraph in the cover-letter bank, dragged into
|
||||
// a letter as a copy. Section is the title of the section it was written for,
|
||||
// only used to group the bank; a snippet can be dropped into any section.
|
||||
type CoverSnippet struct {
|
||||
ID uint `gorm:"primarykey" json:"id"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"index" json:"deletedAt"`
|
||||
Text string `gorm:"type:text;not null" json:"text"`
|
||||
Section string `gorm:"not null;default:''" json:"section"`
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -18,7 +18,9 @@ import (
|
||||
|
||||
func testAuth() *Auth {
|
||||
return InitAuth(&AuthConfig{
|
||||
Secret: []byte("test-secret"),
|
||||
// InitAuth panics on anything under 32 bytes, so the fixture has to be
|
||||
// a realistic length even though nothing here depends on its value.
|
||||
Secret: []byte("test-secret-0123456789abcdef0123456789"),
|
||||
Domain: "example.test",
|
||||
AccessTokenLifetime: time.Hour,
|
||||
RefreshTokenLifetime: 24 * time.Hour,
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CAPTURE_TOKEN_JSON_PATH sits beside the Spotify and Graph tokens, in the
|
||||
// directory docker-compose bind-mounts so that it survives a rebuild.
|
||||
const CAPTURE_TOKEN_JSON_PATH = "/backend/token/job_capture_token.json"
|
||||
|
||||
// CaptureToken holds the bearer token the job capture userscript presents
|
||||
// (handlers/handle_job_capture.go). The token is minted from the admin panel
|
||||
// rather than set in .env, so it can be replaced without a redeploy when the
|
||||
// browser profile holding it is lost.
|
||||
//
|
||||
// Only a SHA-256 of the token is kept, in memory and on disk: the token is
|
||||
// shown once, when generated, and cannot be read back afterwards. A plain
|
||||
// hash is enough because the token is 32 random bytes, not a password — there
|
||||
// is nothing to brute-force.
|
||||
//
|
||||
// There is at most one token. Generating replaces it, which is also how a
|
||||
// leaked one is rotated.
|
||||
type CaptureToken struct {
|
||||
path string
|
||||
|
||||
mu sync.RWMutex
|
||||
hash []byte
|
||||
createdAt time.Time
|
||||
}
|
||||
|
||||
type captureTokenFile struct {
|
||||
SHA256 string `json:"sha256"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// InitCaptureToken loads the token file if there is one. A missing file is
|
||||
// the normal first-run state and means "no token": the capture routes stay
|
||||
// off until one is generated. A file that cannot be read or parsed is
|
||||
// reported, and likewise leaves the routes off rather than open.
|
||||
func InitCaptureToken(path string) (*CaptureToken, error) {
|
||||
t := &CaptureToken{path: path}
|
||||
|
||||
raw, err := os.ReadFile(path)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return t, nil
|
||||
}
|
||||
if err != nil {
|
||||
return t, fmt.Errorf("reading capture token: %w", err)
|
||||
}
|
||||
var stored captureTokenFile
|
||||
if err := json.Unmarshal(raw, &stored); err != nil {
|
||||
return t, fmt.Errorf("parsing capture token: %w", err)
|
||||
}
|
||||
hash, err := hex.DecodeString(stored.SHA256)
|
||||
if err != nil || len(hash) != sha256.Size {
|
||||
return t, fmt.Errorf("capture token file holds no valid hash")
|
||||
}
|
||||
t.hash, t.createdAt = hash, stored.CreatedAt
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// Generate mints a new token, replacing any existing one, and returns it.
|
||||
// This is the only moment the token itself exists on the server.
|
||||
//
|
||||
// The file is written before the in-memory hash is swapped, so a failed write
|
||||
// leaves the old token working instead of handing out one that would stop
|
||||
// working at the next restart.
|
||||
func (t *CaptureToken) Generate() (string, time.Time, error) {
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
token := hex.EncodeToString(raw)
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
now := time.Now().UTC()
|
||||
|
||||
data, err := json.MarshalIndent(captureTokenFile{SHA256: hex.EncodeToString(sum[:]), CreatedAt: now}, "", " ")
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(t.path), 0755); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("creating token directory: %w", err)
|
||||
}
|
||||
if err := os.WriteFile(t.path, data, 0600); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("writing capture token: %w", err)
|
||||
}
|
||||
|
||||
t.mu.Lock()
|
||||
t.hash, t.createdAt = sum[:], now
|
||||
t.mu.Unlock()
|
||||
return token, now, nil
|
||||
}
|
||||
|
||||
// Revoke deletes the token, switching the capture routes off.
|
||||
func (t *CaptureToken) Revoke() error {
|
||||
if err := os.Remove(t.path); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing capture token: %w", err)
|
||||
}
|
||||
t.mu.Lock()
|
||||
t.hash, t.createdAt = nil, time.Time{}
|
||||
t.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Status reports whether a token exists and when it was generated.
|
||||
func (t *CaptureToken) Status() (set bool, createdAt time.Time) {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
return t.hash != nil, t.createdAt
|
||||
}
|
||||
|
||||
// Verify reports whether presented is the current token. With no token it is
|
||||
// false for every input, the empty string included.
|
||||
func (t *CaptureToken) Verify(presented string) bool {
|
||||
t.mu.RLock()
|
||||
defer t.mu.RUnlock()
|
||||
if t.hash == nil {
|
||||
return false
|
||||
}
|
||||
sum := sha256.Sum256([]byte(presented))
|
||||
return subtle.ConstantTimeCompare(sum[:], t.hash) == 1
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func newCaptureToken(t *testing.T) (*CaptureToken, string) {
|
||||
t.Helper()
|
||||
// A nested path: the token directory may not exist on a fresh checkout.
|
||||
path := filepath.Join(t.TempDir(), "token", "job_capture_token.json")
|
||||
tok, err := InitCaptureToken(path)
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
return tok, path
|
||||
}
|
||||
|
||||
func TestCaptureTokenStartsUnsetAndRejectsEverything(t *testing.T) {
|
||||
tok, _ := newCaptureToken(t)
|
||||
if set, _ := tok.Status(); set {
|
||||
t.Fatal("a fresh store reports a token")
|
||||
}
|
||||
// The empty string is the credential of a request with no token at all.
|
||||
for _, presented := range []string{"", "anything"} {
|
||||
if tok.Verify(presented) {
|
||||
t.Fatalf("Verify(%q) passed with no token generated", presented)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenGenerateVerifyAndRotate(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
|
||||
first, createdAt, err := tok.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if len(first) != 64 {
|
||||
t.Fatalf("token is %d chars, want 64 hex chars (32 bytes)", len(first))
|
||||
}
|
||||
if set, at := tok.Status(); !set || !at.Equal(createdAt) {
|
||||
t.Fatalf("Status = %v, %v", set, at)
|
||||
}
|
||||
if !tok.Verify(first) || tok.Verify(first+"x") || tok.Verify("") {
|
||||
t.Fatal("Verify does not accept exactly the generated token")
|
||||
}
|
||||
|
||||
// The file must be useless to someone who reads it, and private anyway.
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("reading token file: %v", err)
|
||||
}
|
||||
if strings.Contains(string(raw), first) {
|
||||
t.Fatal("the token itself was written to disk")
|
||||
}
|
||||
if info, _ := os.Stat(path); info.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("token file mode = %v, want 0600", info.Mode().Perm())
|
||||
}
|
||||
|
||||
second, _, err := tok.Generate()
|
||||
if err != nil {
|
||||
t.Fatalf("Generate: %v", err)
|
||||
}
|
||||
if tok.Verify(first) || !tok.Verify(second) {
|
||||
t.Fatal("generating again must replace the old token")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenSurvivesRestart(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
token, createdAt, _ := tok.Generate()
|
||||
|
||||
reloaded, err := InitCaptureToken(path)
|
||||
if err != nil {
|
||||
t.Fatalf("InitCaptureToken: %v", err)
|
||||
}
|
||||
if !reloaded.Verify(token) {
|
||||
t.Fatal("token no longer verifies after a reload")
|
||||
}
|
||||
if _, at := reloaded.Status(); !at.Equal(createdAt) {
|
||||
t.Fatalf("createdAt = %v, want %v", at, createdAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureTokenRevoke(t *testing.T) {
|
||||
tok, path := newCaptureToken(t)
|
||||
token, _, _ := tok.Generate()
|
||||
|
||||
if err := tok.Revoke(); err != nil {
|
||||
t.Fatalf("Revoke: %v", err)
|
||||
}
|
||||
if tok.Verify(token) {
|
||||
t.Fatal("token still verifies after Revoke")
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("token file still exists, so the token would return on restart")
|
||||
}
|
||||
if err := tok.Revoke(); err != nil {
|
||||
t.Fatalf("revoking with nothing to revoke: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A damaged file must leave the routes off, never open and never fatal.
|
||||
func TestCaptureTokenCorruptFile(t *testing.T) {
|
||||
for name, content := range map[string]string{
|
||||
"not json": "{",
|
||||
"not a hash": `{"sha256": "zz"}`,
|
||||
"short hash": `{"sha256": "abcd"}`,
|
||||
"empty object": `{}`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "t.json")
|
||||
os.WriteFile(path, []byte(content), 0o600)
|
||||
tok, err := InitCaptureToken(path)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
if tok == nil || tok.Verify("") {
|
||||
t.Fatal("a corrupt file must yield a usable store that rejects everything")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"github.com/anthropics/anthropic-sdk-go/option"
|
||||
)
|
||||
|
||||
// ClaudeConfig holds the Anthropic API credentials.
|
||||
type ClaudeConfig struct {
|
||||
APIKey string
|
||||
}
|
||||
|
||||
// InitClaude builds the Anthropic client used to classify job-application
|
||||
// emails (EmailSyncService.processEmail). The other Claude caller, the rowing
|
||||
// photo reader, lives in the Python service and builds its own client from
|
||||
// the same CLAUDE_API_KEY.
|
||||
//
|
||||
// No validation happens here: with an empty or wrong API key construction
|
||||
// still succeeds and the failure only surfaces on the first request.
|
||||
func InitClaude(config *ClaudeConfig) *anthropic.Client {
|
||||
// anthropic.NewClient returns a value, not a pointer, so take its address
|
||||
// so it can be handed around without copying.
|
||||
client := anthropic.NewClient(option.WithAPIKey(config.APIKey))
|
||||
return &client
|
||||
}
|
||||
@@ -49,17 +49,37 @@ func migrateDatabase(db *gorm.DB) error {
|
||||
&models.Favorite{},
|
||||
&models.Rowing{},
|
||||
&models.Message{},
|
||||
&models.JobApplication{},
|
||||
&models.JobAppReference{},
|
||||
&models.Bookmark{},
|
||||
&models.Place{},
|
||||
&models.ProcessedEmail{},
|
||||
&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.
|
||||
|
||||
@@ -1,420 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"mime/multipart"
|
||||
"net"
|
||||
"net/mail"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// This file is a hand-rolled IMAP client, used as an alternative mail source
|
||||
// to Microsoft Graph. It exists because the Graph path needs an Azure app
|
||||
// registration and admin consent, while IMAP needs only an app password.
|
||||
//
|
||||
// It implements the bare minimum of RFC 3501 — LOGIN, SELECT, SEARCH, FETCH,
|
||||
// LOGOUT — by matching on string prefixes rather than parsing IMAP's grammar
|
||||
// properly. It works against Outlook and similar servers with the response
|
||||
// shapes seen in practice; it is not a general-purpose IMAP client.
|
||||
|
||||
// IMAPConfig holds the mailbox credentials. Password is an app password, not
|
||||
// an account password.
|
||||
type IMAPConfig struct {
|
||||
Host string
|
||||
Port string
|
||||
Email string
|
||||
Password string
|
||||
}
|
||||
|
||||
// imapClient is a minimal, lenient IMAP client that tolerates
|
||||
// Outlook's non-standard response formatting.
|
||||
type imapClient struct {
|
||||
conn net.Conn
|
||||
reader *bufio.Reader
|
||||
// tag numbers the commands. IMAP allows several in flight at once
|
||||
// identified by tag; this client never does that, so the atomic is
|
||||
// belt-and-braces rather than load-bearing.
|
||||
tag atomic.Int64
|
||||
}
|
||||
|
||||
// imapDial opens an implicit-TLS IMAP connection (port 993 style, TLS from the
|
||||
// first byte — there is no STARTTLS support here) and consumes the server
|
||||
// greeting, which arrives unsolicited before any command.
|
||||
func imapDial(addr string) (*imapClient, error) {
|
||||
conn, err := tls.Dial("tcp", addr, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &imapClient{
|
||||
conn: conn,
|
||||
reader: bufio.NewReader(conn),
|
||||
}
|
||||
// Read server greeting
|
||||
if _, err := c.readLine(); err != nil {
|
||||
conn.Close()
|
||||
return nil, fmt.Errorf("reading greeting: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Close drops the TCP connection. Callers normally send LOGOUT first.
|
||||
func (c *imapClient) Close() error {
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
// nextTag returns the next command tag, e.g. "A0001". The width is cosmetic:
|
||||
// past 9999 the tags simply get longer, and they stay unique.
|
||||
func (c *imapClient) nextTag() string {
|
||||
return fmt.Sprintf("A%04d", c.tag.Add(1))
|
||||
}
|
||||
|
||||
// readLine reads one CRLF-terminated protocol line with the terminator
|
||||
// stripped. There is no read deadline anywhere in this client, so an
|
||||
// unresponsive server can block a sync until the TCP connection itself fails.
|
||||
func (c *imapClient) readLine() (string, error) {
|
||||
line, err := c.reader.ReadString('\n')
|
||||
return strings.TrimRight(line, "\r\n"), err
|
||||
}
|
||||
|
||||
// sendCommand sends a tagged command and reads lines until the line beginning
|
||||
// with that tag, which is the server's final status for the command.
|
||||
// Everything before it is an untagged ("* ...") response and is returned.
|
||||
//
|
||||
// This must not be used for FETCH: it reads line by line and would mistake the
|
||||
// bytes of a literal for protocol lines. Use sendFetch instead.
|
||||
func (c *imapClient) sendCommand(cmd string) (untagged []string, status string, err error) {
|
||||
tag := c.nextTag()
|
||||
_, err = fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return untagged, "", err
|
||||
}
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
return untagged, line, nil
|
||||
}
|
||||
untagged = append(untagged, line)
|
||||
}
|
||||
}
|
||||
|
||||
// sendCommandOK sends a command and returns an error if the response is not OK.
|
||||
func (c *imapClient) sendCommandOK(cmd string) ([]string, error) {
|
||||
untagged, status, err := c.sendCommand(cmd)
|
||||
if err != nil {
|
||||
return untagged, err
|
||||
}
|
||||
// Status line is "<tag> OK ..." on success, "<tag> NO ..." or
|
||||
// "<tag> BAD ..." otherwise; only the second field matters.
|
||||
parts := strings.SplitN(status, " ", 3)
|
||||
if len(parts) < 2 || parts[1] != "OK" {
|
||||
return untagged, fmt.Errorf("command %q failed: %s", cmd, status)
|
||||
}
|
||||
return untagged, nil
|
||||
}
|
||||
|
||||
// readLiteral reads exactly size bytes of an IMAP literal, i.e. the payload
|
||||
// announced by a trailing "{N}" on the preceding line. It must read by byte
|
||||
// count rather than by line because the payload is arbitrary binary data that
|
||||
// will itself contain CRLFs.
|
||||
func (c *imapClient) readLiteral(size int) (string, error) {
|
||||
buf := make([]byte, size)
|
||||
_, err := io.ReadFull(c.reader, buf)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(buf), nil
|
||||
}
|
||||
|
||||
// fetchPart is one FETCH response line plus the literal payload that followed
|
||||
// it, if any. Pairing them in the type removes the need for callers to walk an
|
||||
// interleaved slice and manually skip every second entry — the previous shape,
|
||||
// where a literal was simply the next element and a caller that forgot to
|
||||
// advance would parse message bytes as a protocol line.
|
||||
type fetchPart struct {
|
||||
Line string
|
||||
// Literal is the payload that followed Line, valid only when HasLiteral.
|
||||
Literal string
|
||||
HasLiteral bool
|
||||
}
|
||||
|
||||
// sendFetch sends a FETCH and collects its response, handling literals.
|
||||
//
|
||||
// The literal is detected with LastIndex("{") plus a "}" suffix rather than a
|
||||
// real parse, so a line whose text merely ends in braces could be misread —
|
||||
// tolerable because only FETCH responses reach this code.
|
||||
func (c *imapClient) sendFetch(cmd string) ([]fetchPart, error) {
|
||||
tag := c.nextTag()
|
||||
_, err := fmt.Fprintf(c.conn, "%s %s\r\n", tag, cmd)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var parts []fetchPart
|
||||
for {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return parts, err
|
||||
}
|
||||
|
||||
// Check for literal marker {N} at end of line
|
||||
if idx := strings.LastIndex(line, "{"); idx >= 0 && strings.HasSuffix(line, "}") {
|
||||
sizeStr := line[idx+1 : len(line)-1]
|
||||
var size int
|
||||
if _, err := fmt.Sscanf(sizeStr, "%d", &size); err == nil && size > 0 {
|
||||
literal, err := c.readLiteral(size)
|
||||
if err != nil {
|
||||
return parts, fmt.Errorf("reading literal of %d bytes: %w", size, err)
|
||||
}
|
||||
parts = append(parts, fetchPart{Line: line, Literal: literal, HasLiteral: true})
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasPrefix(line, tag+" ") {
|
||||
// Check for OK
|
||||
fields := strings.SplitN(line, " ", 3)
|
||||
if len(fields) >= 2 && fields[1] != "OK" {
|
||||
return parts, fmt.Errorf("FETCH failed: %s", line)
|
||||
}
|
||||
return parts, nil
|
||||
}
|
||||
parts = append(parts, fetchPart{Line: line})
|
||||
}
|
||||
}
|
||||
|
||||
// fetchEmailsIMAP connects to an IMAP server and retrieves emails since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsIMAP(since time.Time) ([]graphMessage, error) {
|
||||
addr := fmt.Sprintf("%s:%s", s.Config.IMAP.Host, s.Config.IMAP.Port)
|
||||
|
||||
c, err := imapDial(addr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP connect: %w", err)
|
||||
}
|
||||
defer c.Close()
|
||||
|
||||
// %q wraps the password in double quotes and backslash-escapes any quote
|
||||
// or backslash inside it, which happens to be exactly IMAP's quoted-string
|
||||
// syntax. The username is NOT quoted: an address needs no escaping.
|
||||
// Note this sends the password in a LOGIN command, so it is only safe
|
||||
// because the connection is TLS from the first byte.
|
||||
quotedPass := fmt.Sprintf("%q", s.Config.IMAP.Password)
|
||||
if _, err := c.sendCommandOK(fmt.Sprintf("LOGIN %s %s", s.Config.IMAP.Email, quotedPass)); err != nil {
|
||||
return nil, fmt.Errorf("IMAP login: %w", err)
|
||||
}
|
||||
|
||||
if _, err := c.sendCommandOK("SELECT INBOX"); err != nil {
|
||||
return nil, fmt.Errorf("IMAP select INBOX: %w", err)
|
||||
}
|
||||
|
||||
// SEARCH SINCE has day granularity only — the time of day is not
|
||||
// expressible — so this always over-fetches back to midnight of `since`.
|
||||
// Harmless: SyncEmails deduplicates by message id. The date must be in
|
||||
// IMAP's dd-Mon-yyyy form, hence this exact layout string.
|
||||
dateStr := since.UTC().Format("02-Jan-2006")
|
||||
untagged, err := c.sendCommandOK(fmt.Sprintf("SEARCH SINCE %s", dateStr))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP search: %w", err)
|
||||
}
|
||||
|
||||
// Parse sequence numbers from "* SEARCH 1 2 3 ...". parts[2:] skips the
|
||||
// "*" and "SEARCH" tokens; a bare "* SEARCH" (no matches) has len 2 and
|
||||
// is skipped by the length test.
|
||||
var seqNums []string
|
||||
for _, line := range untagged {
|
||||
if strings.HasPrefix(line, "* SEARCH") {
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) > 2 {
|
||||
seqNums = append(seqNums, parts[2:]...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(seqNums) == 0 {
|
||||
log.Printf("[EmailSync/IMAP] No messages found since %s", dateStr)
|
||||
c.sendCommand("LOGOUT")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync/IMAP] Found %d messages since %s", len(seqNums), dateStr)
|
||||
|
||||
// Every matching message is fetched in one command with a comma-separated
|
||||
// sequence set, and each full body is held in memory. A mailbox with a
|
||||
// very busy day could make this large — there is no batching.
|
||||
seqSet := strings.Join(seqNums, ",")
|
||||
fetchParts, err := c.sendFetch(fmt.Sprintf("FETCH %s (BODY[])", seqSet))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("IMAP fetch: %w", err)
|
||||
}
|
||||
|
||||
// Each body arrives as a "... BODY[] {N}" line carrying its literal, so
|
||||
// the pairing is now part of the value rather than something this loop has
|
||||
// to reconstruct by skipping entries. A message that fails to parse is
|
||||
// logged and skipped rather than failing the whole sync.
|
||||
var messages []graphMessage
|
||||
for _, part := range fetchParts {
|
||||
if part.HasLiteral && strings.Contains(part.Line, "BODY[]") {
|
||||
gm, err := parseRawEmail(part.Literal)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync/IMAP] Error parsing email: %v", err)
|
||||
continue
|
||||
}
|
||||
messages = append(messages, gm)
|
||||
}
|
||||
}
|
||||
|
||||
// LOGOUT errors are ignored: the emails are already in hand and the
|
||||
// deferred Close will drop the connection regardless.
|
||||
c.sendCommand("LOGOUT")
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// parseRawEmail parses a raw RFC822 message into the same graphMessage struct
|
||||
// the Graph API path produces, so everything downstream is source-agnostic.
|
||||
// An unparseable Date falls back to now, and a missing From leaves both name
|
||||
// and address empty rather than failing.
|
||||
func parseRawEmail(raw string) (graphMessage, error) {
|
||||
msg, err := mail.ReadMessage(strings.NewReader(raw))
|
||||
if err != nil {
|
||||
return graphMessage{}, fmt.Errorf("parsing message: %w", err)
|
||||
}
|
||||
|
||||
header := msg.Header
|
||||
|
||||
// Parse From
|
||||
var fromName, fromAddr string
|
||||
if fromList, err := header.AddressList("From"); err == nil && len(fromList) > 0 {
|
||||
fromName = fromList[0].Name
|
||||
fromAddr = fromList[0].Address
|
||||
}
|
||||
|
||||
// Parse Date
|
||||
dateStr := header.Get("Date")
|
||||
parsedDate, err := mail.ParseDate(dateStr)
|
||||
if err != nil {
|
||||
parsedDate = time.Now()
|
||||
}
|
||||
|
||||
// Extract body text
|
||||
bodyContent := extractTextBody(msg.Header, msg.Body)
|
||||
|
||||
// Dedup is keyed on GraphMessageID: a missing Message-ID header would
|
||||
// yield "", which collides every headerless message onto one shared row
|
||||
// (the first one processed, forever). Synthesise an id from stable
|
||||
// message traits instead — hashing because From/Date/Subject/size are not
|
||||
// unique alone but their combination is stable across retries.
|
||||
msgID := header.Get("Message-ID")
|
||||
if msgID == "" {
|
||||
hash := sha256.Sum256([]byte(fromAddr + "|" + dateStr + "|" + header.Get("Subject") + "|" + bodyContent))
|
||||
msgID = "synth-" + hex.EncodeToString(hash[:8])
|
||||
}
|
||||
|
||||
return graphMessage{
|
||||
ID: msgID,
|
||||
Subject: decodeHeader(header.Get("Subject")),
|
||||
ReceivedDateTime: parsedDate.Format(time.RFC3339),
|
||||
From: graphFrom{
|
||||
EmailAddress: graphEmailAddress{
|
||||
Name: fromName,
|
||||
Address: fromAddr,
|
||||
},
|
||||
},
|
||||
Body: graphBody{
|
||||
ContentType: "text",
|
||||
Content: bodyContent,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// extractTextBody pulls readable content out of a message body, preferring
|
||||
// text/plain and falling back to text/html.
|
||||
//
|
||||
// It recurses into nested multipart parts by re-wrapping the part's bytes in a
|
||||
// synthetic mail.Header carrying just its Content-Type — a shortcut that works
|
||||
// because this function only ever reads Content-Type.
|
||||
//
|
||||
// Quoted-printable and base64 transfer encodings are NOT decoded, so a
|
||||
// base64-encoded body reaches Claude as base64. Read errors on a part are
|
||||
// swallowed and the part is skipped.
|
||||
func extractTextBody(header mail.Header, body io.Reader) string {
|
||||
contentType := header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
mediaType, params, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
// Try reading as plain text
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(mediaType, "multipart/") {
|
||||
boundary := params["boundary"]
|
||||
if boundary == "" {
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
mr := multipart.NewReader(body, boundary)
|
||||
var textContent, htmlContent string
|
||||
for {
|
||||
part, err := mr.NextPart()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
partType := part.Header.Get("Content-Type")
|
||||
partMedia, _, _ := mime.ParseMediaType(partType)
|
||||
b, err := io.ReadAll(part)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
switch partMedia {
|
||||
case "text/plain":
|
||||
textContent = string(b)
|
||||
case "text/html":
|
||||
htmlContent = string(b)
|
||||
case "multipart/alternative", "multipart/related", "multipart/mixed":
|
||||
// Recursively handle nested multipart
|
||||
nested := extractTextBody(
|
||||
mail.Header{"Content-Type": {partType}},
|
||||
strings.NewReader(string(b)),
|
||||
)
|
||||
if nested != "" && textContent == "" {
|
||||
textContent = nested
|
||||
}
|
||||
}
|
||||
}
|
||||
if textContent != "" {
|
||||
return textContent
|
||||
}
|
||||
return htmlContent
|
||||
}
|
||||
|
||||
b, _ := io.ReadAll(body)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// decodeHeader decodes RFC 2047 encoded-words (the "=?UTF-8?Q?...?=" form
|
||||
// used for non-ASCII subjects), returning the input unchanged if it is not
|
||||
// encoded or cannot be decoded.
|
||||
func decodeHeader(s string) string {
|
||||
dec := new(mime.WordDecoder)
|
||||
decoded, err := dec.DecodeHeader(s)
|
||||
if err != nil {
|
||||
return s
|
||||
}
|
||||
return decoded
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package services
|
||||
|
||||
import "testing"
|
||||
|
||||
// These tests cover the status progression rule only — StatusAdvances, the
|
||||
// predicate extracted out of updateJobApplication. The rest of
|
||||
// updateJobApplication (note appending, the DB.Save, the returned counters)
|
||||
// needs a live *gorm.DB and the only driver in go.mod is postgres, so it is
|
||||
// deliberately not exercised here. Nothing in this file touches Claude or the
|
||||
// Graph API either; email classification is a network call by construction.
|
||||
|
||||
func TestStatusAdvances(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
current string
|
||||
next string
|
||||
want bool
|
||||
}{
|
||||
{"one step forward is the normal case", "applied", "screening", true},
|
||||
{"skipping intermediate stages still advances", "applied", "offer", true},
|
||||
{"adjacent step backwards is refused", "interviewing", "assessment", false},
|
||||
{"a long way backwards is refused", "offer", "applied", false},
|
||||
{"same status is not progression, so a duplicate email is a no-op", "screening", "screening", false},
|
||||
|
||||
// rejected and withdrawn sit at the top of statusOrder: once an
|
||||
// application lands there, no later email may move it.
|
||||
{"rejected cannot fall back to interviewing", "rejected", "interviewing", false},
|
||||
{"rejected cannot fall back to offer", "rejected", "offer", false},
|
||||
{"rejected cannot repeat", "rejected", "rejected", false},
|
||||
{"withdrawn cannot fall back to offer", "withdrawn", "offer", false},
|
||||
{"withdrawn cannot fall back to rejected", "withdrawn", "rejected", false},
|
||||
{"withdrawn cannot repeat", "withdrawn", "withdrawn", false},
|
||||
// The one ordering asymmetry between the two terminals: withdrawn
|
||||
// ranks above rejected, so this single pair is allowed.
|
||||
{"rejected may still become withdrawn because withdrawn ranks higher", "rejected", "withdrawn", true},
|
||||
|
||||
// saved is a browser capture that has not been applied to yet.
|
||||
{"a saved posting advances once the application is confirmed", "saved", "applied", true},
|
||||
{"an applied row cannot fall back to saved", "applied", "saved", false},
|
||||
|
||||
{"an unknown new status is never applied", "applied", "hired", false},
|
||||
{"an empty new status is never applied", "applied", "", false},
|
||||
{"an unknown new status cannot escape a terminal state either", "rejected", "ghosted", false},
|
||||
{"a recognised status takes over from an unknown current status", "ghosted", "applied", true},
|
||||
{"a recognised status takes over from an empty current status", "", "offer", true},
|
||||
{"unknown to unknown stays put", "ghosted", "hired", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StatusAdvances(c.current, c.next); got != c.want {
|
||||
t.Errorf("StatusAdvances(%q, %q) = %v, want %v", c.current, c.next, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Guards the claim the other tests rest on: rejected and withdrawn really are
|
||||
// the top of the ranking, so adding a stage below them cannot silently make
|
||||
// them non-terminal.
|
||||
func TestTerminalStatusesRankHighest(t *testing.T) {
|
||||
for status, order := range statusOrder {
|
||||
if status == "rejected" || status == "withdrawn" {
|
||||
continue
|
||||
}
|
||||
if order >= statusOrder["rejected"] {
|
||||
t.Errorf("%q ranks %d, at or above rejected (%d)", status, order, statusOrder["rejected"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NormalizeStatus is the guard that keeps Claude's occasional casing drift
|
||||
// ("Interview", "on hold") out of the status column: an unrecognised value
|
||||
// stored verbatim makes StatusAdvances treat the row's current status as
|
||||
// unknown, which switches the forward-only rule off for that row entirely.
|
||||
func TestNormalizeStatus(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"a tracked status passes through", "interviewing", "interviewing"},
|
||||
{"saved is tracked, so a capture keeps it", "saved", "saved"},
|
||||
{"casing drift is lowered, not rejected", "Interviewing", "interviewing"},
|
||||
{"surrounding whitespace is trimmed", " offer ", "offer"},
|
||||
{"an untracked status falls back to the pipeline default", "on hold", "applied"},
|
||||
{"the UI's old Title Case value is recognised once lowered", "Rejected", "rejected"},
|
||||
{"a value the UI once allowed but the pipeline never had is rejected", "Interview", "applied"},
|
||||
{"empty falls back rather than storing a blank status", "", "applied"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := NormalizeStatus(c.in); got != c.want {
|
||||
t.Errorf("NormalizeStatus(%q) = %q, want %q", c.in, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,983 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
"github.com/anthropics/anthropic-sdk-go"
|
||||
"golang.org/x/oauth2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// This file is the job-application email pipeline. On a timer it fetches
|
||||
// recent mail (via Microsoft Graph or plain IMAP), keeps the ones that look
|
||||
// recruitment-related, asks Claude to turn each into structured data, and
|
||||
// creates or advances a models.JobApplication row. Every email it has looked
|
||||
// at is recorded as a models.ProcessedEmail so it is never handled twice.
|
||||
|
||||
// MSGRAPH_TOKEN_JSON_PATH lives in a Docker volume so the OAuth refresh token
|
||||
// survives restarts, exactly like the Spotify token.
|
||||
const MSGRAPH_TOKEN_JSON_PATH = "/backend/token/msgraph_token.json"
|
||||
|
||||
// EmailSyncConfig configures the pipeline. Backend picks the mail source;
|
||||
// anything other than "graph" or "imap" leaves the service permanently idle.
|
||||
type EmailSyncConfig struct {
|
||||
Backend string // "graph" or "imap"
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
TenantID string
|
||||
RedirectURI string
|
||||
IMAP *IMAPConfig
|
||||
SyncInterval time.Duration
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// EmailSyncService owns the sync pipeline.
|
||||
type EmailSyncService struct {
|
||||
Config *EmailSyncConfig
|
||||
OAuthConfig *oauth2.Config
|
||||
// HTTPClient doubles as the readiness flag: nil means "not configured or
|
||||
// not yet authenticated", and both the scheduler and the manual-trigger
|
||||
// handler refuse to run while it is nil. On the Graph backend it is a
|
||||
// real token-injecting client; on the IMAP backend it is set to
|
||||
// http.DefaultClient purely so this check passes (IMAP never uses it).
|
||||
HTTPClient *http.Client
|
||||
DB *gorm.DB
|
||||
ClaudeClient *anthropic.Client
|
||||
// mu is used with TryLock, not Lock: it makes a sync a no-op while
|
||||
// another one is running rather than queueing behind it, so the manual
|
||||
// admin trigger cannot pile up on top of the scheduled run.
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// Microsoft Graph API response types
|
||||
|
||||
// Microsoft Graph API response types. The IMAP backend parses raw RFC822
|
||||
// messages into these same structs (see parseRawEmail) so that everything
|
||||
// downstream of fetchEmails is backend-agnostic.
|
||||
|
||||
// graphMessagesResponse is one page of /me/messages; NextLink is Graph's
|
||||
// cursor for the next page and is empty on the last one.
|
||||
type graphMessagesResponse struct {
|
||||
Value []graphMessage `json:"value"`
|
||||
NextLink string `json:"@odata.nextLink"`
|
||||
}
|
||||
|
||||
// graphMessage is a single email.
|
||||
type graphMessage struct {
|
||||
ID string `json:"id"`
|
||||
Subject string `json:"subject"`
|
||||
ReceivedDateTime string `json:"receivedDateTime"`
|
||||
From graphFrom `json:"from"`
|
||||
Body graphBody `json:"body"`
|
||||
BodyPreview string `json:"bodyPreview"`
|
||||
}
|
||||
|
||||
// graphFrom wraps the sender, which Graph nests one level deep.
|
||||
type graphFrom struct {
|
||||
EmailAddress graphEmailAddress `json:"emailAddress"`
|
||||
}
|
||||
|
||||
// graphEmailAddress is a display name plus address.
|
||||
type graphEmailAddress struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
}
|
||||
|
||||
// graphBody is the message body; ContentType is "html" or "text".
|
||||
type graphBody struct {
|
||||
ContentType string `json:"contentType"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// Claude response type
|
||||
|
||||
// EmailAnalysis is the JSON contract Claude is asked to return; the keys here
|
||||
// must stay in step with emailClassificationPrompt at the bottom of this file.
|
||||
// Pointer fields are the ones Claude is allowed to answer null for.
|
||||
type EmailAnalysis struct {
|
||||
IsJobEmail bool `json:"isJobEmail"`
|
||||
Action string `json:"action"`
|
||||
Company string `json:"company"`
|
||||
JobTitle string `json:"jobTitle"`
|
||||
Status string `json:"status"`
|
||||
Location *string `json:"location"`
|
||||
URL *string `json:"url"`
|
||||
AppliedAt *string `json:"appliedAt"`
|
||||
Notes *string `json:"notes"`
|
||||
}
|
||||
|
||||
// Email filtering config
|
||||
|
||||
// Cheap pre-filter, applied before any Claude call so that the bulk of a
|
||||
// mailbox never costs an API request. It is intentionally over-inclusive:
|
||||
// false positives are cheap (Claude rejects them), false negatives are not
|
||||
// (the email is never looked at again once its window has passed).
|
||||
|
||||
// subjectKeywords match case-insensitively anywhere in the subject line.
|
||||
var subjectKeywords = []string{
|
||||
"application", "interview", "offer", "rejected", "assessment",
|
||||
"applied", "candidate", "position", "role", "hiring",
|
||||
"thank you for applying", "we regret", "move forward",
|
||||
"next steps", "coding challenge", "take-home",
|
||||
}
|
||||
|
||||
// senderDomains are applicant-tracking systems; mail from any of them is
|
||||
// considered job-related whatever the subject says.
|
||||
var senderDomains = []string{
|
||||
"greenhouse.io", "lever.co", "workday.com", "myworkday.com",
|
||||
"ashbyhq.com", "smartrecruiters.com", "icims.com",
|
||||
"jobvite.com", "taleo.net", "breezy.hr", "recruitee.com",
|
||||
"applytojob.com", "jazz.co", "dover.com",
|
||||
}
|
||||
|
||||
// Status progression order
|
||||
|
||||
// statusOrder ranks the application lifecycle so updates can only move an
|
||||
// application forwards (see updateJobApplication). A status missing from this
|
||||
// map is treated as unknown and never applied. Note that "rejected" and
|
||||
// "withdrawn" sit at the top, so once an application reaches them nothing can
|
||||
// move it back.
|
||||
//
|
||||
// "saved" is the one status no email can produce: it marks a posting captured
|
||||
// from the browser but not applied to yet (handlers/handle_job_capture.go).
|
||||
// It ranks lowest so that the "thanks for applying" email advances the row.
|
||||
var statusOrder = map[string]int{
|
||||
"saved": 0,
|
||||
"applied": 1,
|
||||
"screening": 2,
|
||||
"assessment": 3,
|
||||
"interviewing": 4,
|
||||
"offer": 5,
|
||||
"rejected": 6,
|
||||
"withdrawn": 7,
|
||||
}
|
||||
|
||||
// Token persistence
|
||||
|
||||
// SaveMSGraphToken persists an OAuth token to disk with 0600 permissions.
|
||||
// Like the Spotify equivalent it copies into a local struct so the on-disk
|
||||
// shape does not depend on the oauth2 package's own JSON tags.
|
||||
func SaveMSGraphToken(path string, tok *oauth2.Token) error {
|
||||
data := struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}{
|
||||
AccessToken: tok.AccessToken,
|
||||
RefreshToken: tok.RefreshToken,
|
||||
TokenType: tok.TokenType,
|
||||
Expiry: tok.Expiry,
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return fmt.Errorf("creating token directory: %w", err)
|
||||
}
|
||||
|
||||
jsonBytes, err := json.MarshalIndent(data, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return os.WriteFile(path, jsonBytes, 0600)
|
||||
}
|
||||
|
||||
// LoadMSGraphToken reads a token written by SaveMSGraphToken. A missing file
|
||||
// is reported as an error and means "not yet authenticated".
|
||||
func LoadMSGraphToken(path string) (*oauth2.Token, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var saved struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
TokenType string `json:"token_type"`
|
||||
Expiry time.Time `json:"expiry"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &saved); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oauth2.Token{
|
||||
AccessToken: saved.AccessToken,
|
||||
RefreshToken: saved.RefreshToken,
|
||||
TokenType: saved.TokenType,
|
||||
Expiry: saved.Expiry,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// persistingTokenSource wraps an oauth2.TokenSource to save refreshed tokens to disk.
|
||||
type persistingTokenSource struct {
|
||||
base oauth2.TokenSource
|
||||
path string
|
||||
lastToken *oauth2.Token
|
||||
}
|
||||
|
||||
// Token returns a valid token, refreshing through the wrapped source when
|
||||
// needed and writing any new token back to disk.
|
||||
//
|
||||
// Without this wrapper the oauth2 client would refresh happily in memory but
|
||||
// the file on disk would keep the original refresh token; Microsoft rotates
|
||||
// refresh tokens, so after the original expired the service would have to be
|
||||
// re-authorised by hand on the next restart.
|
||||
//
|
||||
// There is no mutex here even though oauth2's client may call Token from
|
||||
// several goroutines. In practice syncs are serialised by EmailSyncService.mu
|
||||
// so concurrent calls do not arise; the worst case if they ever did is a
|
||||
// duplicate write of the same token.
|
||||
func (p *persistingTokenSource) Token() (*oauth2.Token, error) {
|
||||
tok, err := p.base.Token()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Save only when the token actually changed (i.e. was refreshed)
|
||||
if p.lastToken == nil || tok.AccessToken != p.lastToken.AccessToken {
|
||||
p.lastToken = tok
|
||||
if saveErr := SaveMSGraphToken(p.path, tok); saveErr != nil {
|
||||
log.Printf("[EmailSync] Warning: failed to persist refreshed token: %v", saveErr)
|
||||
}
|
||||
}
|
||||
return tok, nil
|
||||
}
|
||||
|
||||
// InitEmailSync builds the service and, for the Graph backend, restores a
|
||||
// saved OAuth session. It never fails: a misconfigured or unauthenticated
|
||||
// service is returned with a nil HTTPClient, which leaves the pipeline idle
|
||||
// while the rest of the backend starts normally. For Graph, the authorisation
|
||||
// URL is printed to the container log for a one-off manual sign-in that
|
||||
// lands on GET /email/callback.
|
||||
func InitEmailSync(config *EmailSyncConfig, db *gorm.DB, claudeClient *anthropic.Client) *EmailSyncService {
|
||||
svc := &EmailSyncService{
|
||||
Config: config,
|
||||
DB: db,
|
||||
ClaudeClient: claudeClient,
|
||||
}
|
||||
|
||||
switch config.Backend {
|
||||
case "imap":
|
||||
if config.IMAP == nil || config.IMAP.Email == "" {
|
||||
log.Println("[EmailSync] IMAP backend selected but not configured")
|
||||
return svc
|
||||
}
|
||||
// IMAP connects per-sync, no persistent client needed.
|
||||
// Mark as ready by setting a non-nil HTTPClient (used as readiness flag).
|
||||
svc.HTTPClient = http.DefaultClient
|
||||
log.Printf("[EmailSync] Configured with IMAP backend (%s)", config.IMAP.Host)
|
||||
|
||||
case "graph":
|
||||
oauthConfig := &oauth2.Config{
|
||||
ClientID: config.ClientID,
|
||||
ClientSecret: config.ClientSecret,
|
||||
Endpoint: oauth2.Endpoint{
|
||||
AuthURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/authorize", config.TenantID),
|
||||
TokenURL: fmt.Sprintf("https://login.microsoftonline.com/%s/oauth2/v2.0/token", config.TenantID),
|
||||
},
|
||||
RedirectURL: config.RedirectURI,
|
||||
Scopes: []string{"https://graph.microsoft.com/Mail.Read", "offline_access"},
|
||||
}
|
||||
svc.OAuthConfig = oauthConfig
|
||||
|
||||
token, err := LoadMSGraphToken(MSGRAPH_TOKEN_JSON_PATH)
|
||||
if err != nil || token == nil {
|
||||
authURL := oauthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
log.Println("[EmailSync] No token saved. Authenticate Microsoft Graph with:")
|
||||
log.Println(authURL)
|
||||
return svc
|
||||
}
|
||||
|
||||
baseSource := oauthConfig.TokenSource(context.Background(), token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
svc.HTTPClient = oauth2.NewClient(context.Background(), persistSource)
|
||||
log.Println("[EmailSync] Authenticated with Microsoft Graph")
|
||||
|
||||
default:
|
||||
log.Printf("[EmailSync] Unknown backend %q, defaulting to disabled", config.Backend)
|
||||
}
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
// AuthURL returns the OAuth2 authorization URL for initial setup.
|
||||
func (s *EmailSyncService) AuthURL() string {
|
||||
return s.OAuthConfig.AuthCodeURL("state", oauth2.AccessTypeOffline)
|
||||
}
|
||||
|
||||
// CompleteAuth exchanges an authorization code for a token and initializes the HTTP client.
|
||||
func (s *EmailSyncService) CompleteAuth(ctx context.Context, code string) error {
|
||||
token, err := s.OAuthConfig.Exchange(ctx, code)
|
||||
if err != nil {
|
||||
return fmt.Errorf("token exchange failed: %w", err)
|
||||
}
|
||||
|
||||
if err := SaveMSGraphToken(MSGRAPH_TOKEN_JSON_PATH, token); err != nil {
|
||||
return fmt.Errorf("saving token: %w", err)
|
||||
}
|
||||
|
||||
baseSource := s.OAuthConfig.TokenSource(ctx, token)
|
||||
persistSource := &persistingTokenSource{base: baseSource, path: MSGRAPH_TOKEN_JSON_PATH, lastToken: token}
|
||||
s.HTTPClient = oauth2.NewClient(ctx, persistSource)
|
||||
|
||||
log.Println("[EmailSync] Authentication completed successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartScheduler runs SyncEmails immediately and then on every tick until ctx
|
||||
// is cancelled. It is meant to be run in its own goroutine and returns
|
||||
// straight away when the service is disabled or unauthenticated.
|
||||
//
|
||||
// Because readiness is only checked once here, authenticating later via
|
||||
// /email/callback does NOT start the scheduler; the backend has to be
|
||||
// restarted, or syncs triggered by hand through POST /email/sync.
|
||||
func (s *EmailSyncService) StartScheduler(ctx context.Context) {
|
||||
if !s.Config.Enabled {
|
||||
log.Println("[EmailSync] Disabled, skipping scheduler")
|
||||
return
|
||||
}
|
||||
if s.HTTPClient == nil {
|
||||
log.Println("[EmailSync] Not authenticated, skipping scheduler")
|
||||
return
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Starting scheduler, interval: %s", s.Config.SyncInterval)
|
||||
|
||||
// Run once immediately on startup
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Initial sync error: %v", err)
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(s.Config.SyncInterval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
log.Println("[EmailSync] Scheduler stopped")
|
||||
return
|
||||
case <-ticker.C:
|
||||
if err := s.SyncEmails(ctx); err != nil {
|
||||
log.Printf("[EmailSync] Sync error: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SyncEmails is the main pipeline: fetch, filter, dedup, classify, create/update.
|
||||
func (s *EmailSyncService) SyncEmails(ctx context.Context) error {
|
||||
// TryLock, so a manual trigger during a scheduled run is rejected
|
||||
// immediately instead of blocking a request for minutes.
|
||||
if !s.mu.TryLock() {
|
||||
return fmt.Errorf("sync already in progress")
|
||||
}
|
||||
defer s.mu.Unlock()
|
||||
|
||||
// Registered after the unlock defer, therefore it runs BEFORE it: the
|
||||
// panic is absorbed here and the mutex is still released afterwards.
|
||||
// A recovered panic makes SyncEmails return nil, so the caller sees a
|
||||
// successful sync — the log line is the only evidence.
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
log.Printf("[EmailSync] PANIC recovered: %v", r)
|
||||
}
|
||||
}()
|
||||
|
||||
log.Println("[EmailSync] Starting sync...")
|
||||
|
||||
// Window start comes from the newest email we have ever *received* (one of
|
||||
// two clocks in play) rather than from when we processed it: receive time
|
||||
// lags processing time by up to one sync duration, and a later window
|
||||
// anchored to processing time would start AFTER mail that arrived just at
|
||||
// the previous fetch — a permanent hole (the overlap the code always meant
|
||||
// to have is produced only when both edges speak the same clock).
|
||||
// Anchoring on ReceivedAt keeps the window behind the fetch, the
|
||||
// ProcessedEmail dedup absorbs the deliberate re-fetch overlap, and on a
|
||||
// cold database it falls back to the last 24 hours so the pipeline never
|
||||
// tries to ingest an entire mailbox.
|
||||
since := time.Now().Add(-24 * time.Hour)
|
||||
var latest models.ProcessedEmail
|
||||
if err := s.DB.Where("received_at > ?", time.Time{}).Order("received_at DESC").First(&latest).Error; err == nil {
|
||||
// Pull the window back one slack period so mail delivered a second or
|
||||
// two after the last fetch (or indexed late by the provider) is still
|
||||
// inside the next window; dedup makes re-processing it harmless.
|
||||
since = latest.ReceivedAt.Add(-fetchSlack)
|
||||
}
|
||||
|
||||
// Pull the window back to cover any still-retryable failure. Without this
|
||||
// the clamp above would have advanced past a failed email — the error row
|
||||
// is written now, so the next window starts after it — and the retry
|
||||
// below could never see the email again. Rows predating ReceivedAt have
|
||||
// a zero value and are ignored rather than dragging the window to 0001.
|
||||
//
|
||||
// Old failures are age-capped: attempts only advance when the email is
|
||||
// actually re-fetched, so a message that has left the mailbox would stay
|
||||
// under the cap forever and rewind every sync on this day's fetch. After
|
||||
// maxRewindAge the email is treated as gone, like any abandoned retry.
|
||||
var oldestRetryable models.ProcessedEmail
|
||||
if err := s.DB.
|
||||
Where("action = ? AND attempts < ? AND received_at > ? AND received_at > ?",
|
||||
"error", maxEmailAttempts, time.Time{}, time.Now().Add(-maxRewindAge)).
|
||||
Order("received_at ASC").
|
||||
First(&oldestRetryable).Error; err == nil && oldestRetryable.ReceivedAt.Before(since) {
|
||||
log.Printf("[EmailSync] Rewinding window to %s to retry a previous failure",
|
||||
oldestRetryable.ReceivedAt.Format(time.RFC3339))
|
||||
since = oldestRetryable.ReceivedAt
|
||||
}
|
||||
|
||||
// Fetch emails from Microsoft Graph
|
||||
emails, err := s.fetchEmails(ctx, since)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetching emails: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Fetched %d emails since %s", len(emails), since.Format(time.RFC3339))
|
||||
|
||||
// Filter by subject/sender patterns
|
||||
filtered := s.filterEmails(emails)
|
||||
log.Printf("[EmailSync] %d emails passed filters", len(filtered))
|
||||
|
||||
var created, updated, skipped, errored int
|
||||
|
||||
for _, email := range filtered {
|
||||
// Dedup check. A row is terminal — and so genuinely skippable — if it
|
||||
// succeeded, or if it failed the maximum number of times. A row that
|
||||
// failed but has attempts left is deliberately NOT skipped: it is
|
||||
// reprocessed below and the same row updated, so a transient Claude
|
||||
// or network outage no longer drops the email permanently.
|
||||
var existing models.ProcessedEmail
|
||||
found := s.DB.Where("graph_message_id = ?", email.ID).First(&existing).Error == nil
|
||||
if found && !retryableFailure(&existing) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
if found {
|
||||
log.Printf("[EmailSync] Retrying previously failed email %q (attempt %d of %d)",
|
||||
email.Subject, existing.Attempts+1, maxEmailAttempts)
|
||||
}
|
||||
|
||||
action, jobAppID, processErr := s.processEmail(ctx, email)
|
||||
|
||||
// The row carries the outcome either way. On failure the attempt
|
||||
// counter advances, so repeated failures walk the row towards the cap
|
||||
// and it eventually stops being retried. A cancelled sync (the admin
|
||||
// closed the tab mid-backlog, or nginx cut the request) is not a
|
||||
// failure of the email, though: attempts must not advance for it, or
|
||||
// two closed tabs would strand a healthy email at the cap and skip it
|
||||
// forever. Writing nothing preserves the existing row untouched, so it
|
||||
// is simply retried at the next sync.
|
||||
if processErr != nil && errors.Is(processErr, context.Canceled) {
|
||||
skipped++
|
||||
continue
|
||||
}
|
||||
|
||||
record := models.ProcessedEmail{
|
||||
GraphMessageID: email.ID,
|
||||
Subject: truncate(email.Subject, 255),
|
||||
Action: action,
|
||||
JobAppID: jobAppID,
|
||||
ReceivedAt: parseReceivedAt(email.ReceivedDateTime),
|
||||
Attempts: existing.Attempts + 1,
|
||||
}
|
||||
|
||||
if processErr != nil {
|
||||
log.Printf("[EmailSync] Error processing email %q: %v", email.Subject, processErr)
|
||||
record.Action = "error"
|
||||
record.JobAppID = nil
|
||||
if record.Attempts >= maxEmailAttempts {
|
||||
log.Printf("[EmailSync] Email %q has failed %d times; giving up on it",
|
||||
email.Subject, record.Attempts)
|
||||
}
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
errored++
|
||||
continue
|
||||
}
|
||||
|
||||
s.saveProcessed(found, &existing, &record)
|
||||
|
||||
switch action {
|
||||
case "created":
|
||||
created++
|
||||
case "updated":
|
||||
updated++
|
||||
default:
|
||||
skipped++
|
||||
}
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Sync complete: %d fetched, %d filtered, %d created, %d updated, %d skipped, %d errors",
|
||||
len(emails), len(filtered), created, updated, skipped, errored)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchEmails retrieves emails since the given time using the configured
|
||||
// backend, normalising both into []graphMessage.
|
||||
func (s *EmailSyncService) fetchEmails(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
if s.Config.Backend == "imap" {
|
||||
return s.fetchEmailsIMAP(since)
|
||||
}
|
||||
return s.fetchEmailsGraph(ctx, since)
|
||||
}
|
||||
|
||||
// fetchEmailsGraph retrieves emails from the Microsoft Graph API since the given time.
|
||||
func (s *EmailSyncService) fetchEmailsGraph(ctx context.Context, since time.Time) ([]graphMessage, error) {
|
||||
var all []graphMessage
|
||||
|
||||
sinceStr := since.UTC().Format("2006-01-02T15:04:05Z")
|
||||
params := url.Values{
|
||||
"$filter": {fmt.Sprintf("receivedDateTime ge %s", sinceStr)},
|
||||
"$select": {"id,subject,from,receivedDateTime,body,bodyPreview"},
|
||||
"$top": {"50"},
|
||||
"$orderby": {"receivedDateTime asc"},
|
||||
}
|
||||
|
||||
// Graph paginates with @odata.nextLink, which already carries every query
|
||||
// parameter, so the loop below only builds this first URL by hand.
|
||||
nextURL := fmt.Sprintf("https://graph.microsoft.com/v1.0/me/messages?%s", params.Encode())
|
||||
|
||||
for nextURL != "" {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", nextURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := s.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
|
||||
// Status is checked before the read error so that a non-200 reports
|
||||
// Graph's own error body rather than a generic read failure.
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("Graph API returned %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var result graphMessagesResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
return nil, fmt.Errorf("parsing response: %w", err)
|
||||
}
|
||||
|
||||
all = append(all, result.Value...)
|
||||
nextURL = result.NextLink
|
||||
}
|
||||
|
||||
return all, nil
|
||||
}
|
||||
|
||||
// filterEmails returns only emails that match subject keywords or sender domains.
|
||||
func (s *EmailSyncService) filterEmails(emails []graphMessage) []graphMessage {
|
||||
var matched []graphMessage
|
||||
for _, email := range emails {
|
||||
if s.matchesFilter(email) {
|
||||
matched = append(matched, email)
|
||||
}
|
||||
}
|
||||
return matched
|
||||
}
|
||||
|
||||
// matchesFilter reports whether an email looks job-related on subject or
|
||||
// sender alone. See subjectKeywords for why this errs towards including too
|
||||
// much.
|
||||
func (s *EmailSyncService) matchesFilter(email graphMessage) bool {
|
||||
subjectLower := strings.ToLower(email.Subject)
|
||||
for _, kw := range subjectKeywords {
|
||||
if strings.Contains(subjectLower, kw) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
senderAddr := strings.ToLower(email.From.EmailAddress.Address)
|
||||
for _, domain := range senderDomains {
|
||||
if strings.HasSuffix(senderAddr, "@"+domain) || strings.HasSuffix(senderAddr, "."+domain) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// processEmail sends a single email to Claude and creates/updates a JobApplication.
|
||||
// Returns the action taken ("created", "updated", "skipped") and the job application ID if applicable.
|
||||
func (s *EmailSyncService) processEmail(ctx context.Context, email graphMessage) (string, *uint, error) {
|
||||
cleaned := cleanEmailBody(email.Body.Content, email.Body.ContentType)
|
||||
|
||||
userMsg := fmt.Sprintf("Subject: %s\nFrom: %s <%s>\nDate: %s\n\n%s",
|
||||
email.Subject,
|
||||
email.From.EmailAddress.Name,
|
||||
email.From.EmailAddress.Address,
|
||||
email.ReceivedDateTime,
|
||||
cleaned,
|
||||
)
|
||||
|
||||
message, err := s.ClaudeClient.Messages.New(ctx, anthropic.MessageNewParams{
|
||||
Model: anthropic.ModelClaudeHaiku4_5,
|
||||
MaxTokens: 512,
|
||||
System: []anthropic.TextBlockParam{
|
||||
{Text: emailClassificationPrompt},
|
||||
},
|
||||
Messages: []anthropic.MessageParam{
|
||||
{
|
||||
Role: "user",
|
||||
Content: []anthropic.ContentBlockParamUnion{anthropic.NewTextBlock(userMsg)},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return "", nil, fmt.Errorf("Claude API error: %w", err)
|
||||
}
|
||||
|
||||
if len(message.Content) == 0 {
|
||||
return "", nil, fmt.Errorf("empty response from Claude")
|
||||
}
|
||||
|
||||
// Only the first content block is read, and the prompt asks for bare JSON,
|
||||
// but models still wrap output in a markdown fence often enough that it is
|
||||
// stripped defensively here.
|
||||
raw := StripMarkdownFence(message.Content[0].Text)
|
||||
|
||||
var analysis EmailAnalysis
|
||||
if err := json.Unmarshal([]byte(raw), &analysis); err != nil {
|
||||
return "", nil, fmt.Errorf("parsing Claude response: %w (raw: %s)", err, raw)
|
||||
}
|
||||
|
||||
if !analysis.IsJobEmail {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if analysis.Company == "" || analysis.JobTitle == "" {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
// Applications are identified by (company, job title) compared
|
||||
// case-insensitively — there is no external id to match on. Claude
|
||||
// wording the same role slightly differently therefore creates a second
|
||||
// application rather than updating the first. The most recent match wins
|
||||
// when there are several.
|
||||
// The lookup is Unscoped: a deleted-with-notes row is stored, not purged
|
||||
// (see models.JobApplication), so invisibility here makes the matcher
|
||||
// believe the application never existed and a follow-up email in the same
|
||||
// thread re-creates it — the admin deletes it, it comes back. A hit on a
|
||||
// deleted row instead becomes a suppression: nothing is updated, nothing
|
||||
// is created, and the pipeline leaves the deletion to stand.
|
||||
var existing models.JobApplication
|
||||
found := s.DB.Unscoped().Where("LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)",
|
||||
analysis.Company, analysis.JobTitle).
|
||||
Order("created_at DESC").
|
||||
First(&existing).Error == nil
|
||||
|
||||
if found && existing.DeletedAt.Valid {
|
||||
return "skipped", nil, nil
|
||||
}
|
||||
|
||||
if found && analysis.Action == "update" {
|
||||
return s.updateJobApplication(&existing, &analysis)
|
||||
}
|
||||
|
||||
if !found {
|
||||
return s.createJobApplication(&analysis)
|
||||
}
|
||||
|
||||
// Found but action is "create" — the record already exists, skip
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
// NormalizeStatus coerces Claude's status guess into the tracked vocabulary,
|
||||
// lowering the case it occasionally drifts on and rejecting anything outside
|
||||
// statusOrder. An unrecognised status stored verbatim would disable the
|
||||
// forward-only guard for that row (updateJobApplication allows any recognised
|
||||
// status over an unknown one), so the safe fallback is the pipeline's default.
|
||||
func NormalizeStatus(s string) string {
|
||||
lowered := strings.ToLower(strings.TrimSpace(s))
|
||||
if _, ok := statusOrder[lowered]; ok {
|
||||
return lowered
|
||||
}
|
||||
return "applied"
|
||||
}
|
||||
|
||||
// createJobApplication inserts a new application from Claude's analysis.
|
||||
func (s *EmailSyncService) createJobApplication(analysis *EmailAnalysis) (string, *uint, error) {
|
||||
app := models.JobApplication{
|
||||
Company: analysis.Company,
|
||||
JobTitle: analysis.JobTitle,
|
||||
Status: NormalizeStatus(analysis.Status),
|
||||
Location: analysis.Location,
|
||||
URL: analysis.URL,
|
||||
Notes: analysis.Notes,
|
||||
}
|
||||
|
||||
// The prompt asks for YYYY-MM-DD but full RFC3339 comes back often enough
|
||||
// to be worth trying first; an unparseable date is dropped silently.
|
||||
if analysis.AppliedAt != nil {
|
||||
if t, err := time.Parse(time.RFC3339, *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
} else if t, err := time.Parse("2006-01-02", *analysis.AppliedAt); err == nil {
|
||||
app.AppliedAt = &t
|
||||
}
|
||||
}
|
||||
|
||||
if app.Status == "" {
|
||||
app.Status = "applied"
|
||||
}
|
||||
|
||||
if err := s.DB.Create(&app).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("creating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Created job application: %s at %s (status: %s)", app.JobTitle, app.Company, app.Status)
|
||||
return "created", &app.ID, nil
|
||||
}
|
||||
|
||||
// StatusAdvances reports whether next is a forward move from current through
|
||||
// statusOrder. Emails commonly arrive out of order (a delayed "thanks for
|
||||
// applying" after an interview invite), and this is what stops a stale email
|
||||
// dragging an application backwards. An unknown next status is never applied;
|
||||
// an unknown current status is treated as "anywhere before the start", so any
|
||||
// recognised status can take over from it.
|
||||
//
|
||||
// Exported because the browser capture endpoint applies the same rule.
|
||||
func StatusAdvances(current, next string) bool {
|
||||
nextOrder, nextExists := statusOrder[next]
|
||||
currentOrder, currentExists := statusOrder[current]
|
||||
return nextExists && (!currentExists || nextOrder > currentOrder)
|
||||
}
|
||||
|
||||
// updateJobApplication advances an existing application's status, but only
|
||||
// ever forwards (see StatusAdvances).
|
||||
func (s *EmailSyncService) updateJobApplication(existing *models.JobApplication, analysis *EmailAnalysis) (string, *uint, error) {
|
||||
if !StatusAdvances(existing.Status, analysis.Status) {
|
||||
return "skipped", &existing.ID, nil
|
||||
}
|
||||
|
||||
existing.Status = analysis.Status
|
||||
|
||||
// A row captured as "saved" has no applied date; the email that moves it
|
||||
// to "applied" is the best evidence of when that happened.
|
||||
if existing.AppliedAt == nil && existing.Status == "applied" {
|
||||
now := time.Now()
|
||||
existing.AppliedAt = &now
|
||||
}
|
||||
|
||||
// Append to notes if Claude provided any
|
||||
if analysis.Notes != nil && *analysis.Notes != "" {
|
||||
if existing.Notes != nil && *existing.Notes != "" {
|
||||
combined := *existing.Notes + "\n" + *analysis.Notes
|
||||
existing.Notes = &combined
|
||||
} else {
|
||||
existing.Notes = analysis.Notes
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.DB.Save(existing).Error; err != nil {
|
||||
return "", nil, fmt.Errorf("updating job application: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("[EmailSync] Updated job application: %s at %s (status: %s)", existing.JobTitle, existing.Company, existing.Status)
|
||||
return "updated", &existing.ID, nil
|
||||
}
|
||||
|
||||
// cleanEmailBody reduces an email body to plain-ish text before it is sent to
|
||||
// Claude, cutting token cost and noise.
|
||||
//
|
||||
// The HTML handling is a regex tag-strip, not a parser: fine for extracting
|
||||
// prose, but it would mangle inline <script>/<style> content and mis-handle
|
||||
// tags inside attribute values. That is acceptable because the output is only
|
||||
// ever read by a language model, never rendered.
|
||||
func cleanEmailBody(content string, contentType string) string {
|
||||
text := content
|
||||
|
||||
if strings.EqualFold(contentType, "html") {
|
||||
// Strip HTML tags
|
||||
tagRegex := regexp.MustCompile(`<[^>]*>`)
|
||||
text = tagRegex.ReplaceAllString(text, " ")
|
||||
|
||||
// Decode common HTML entities
|
||||
replacer := strings.NewReplacer(
|
||||
" ", " ",
|
||||
"&", "&",
|
||||
"<", "<",
|
||||
">", ">",
|
||||
""", `"`,
|
||||
"'", "'",
|
||||
"'", "'",
|
||||
)
|
||||
text = replacer.Replace(text)
|
||||
}
|
||||
|
||||
// Collapse whitespace
|
||||
spaceRegex := regexp.MustCompile(`[ \t]+`)
|
||||
text = spaceRegex.ReplaceAllString(text, " ")
|
||||
nlRegex := regexp.MustCompile(`\n{3,}`)
|
||||
text = nlRegex.ReplaceAllString(text, "\n\n")
|
||||
text = strings.TrimSpace(text)
|
||||
|
||||
// Cut everything from the first signature marker onwards. The idx > 0
|
||||
// test (not >= 0) means a body that begins with a marker is left alone,
|
||||
// which avoids blanking the whole message.
|
||||
sigPatterns := []string{
|
||||
"\n-- \n",
|
||||
"\nSent from my iPhone",
|
||||
"\nSent from my iPad",
|
||||
"\nGet Outlook for",
|
||||
}
|
||||
for _, pattern := range sigPatterns {
|
||||
if idx := strings.Index(text, pattern); idx > 0 {
|
||||
text = text[:idx]
|
||||
}
|
||||
}
|
||||
|
||||
// Remove forwarded email chains
|
||||
lines := strings.Split(text, "\n")
|
||||
var cleaned []string
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(strings.TrimSpace(line), ">") {
|
||||
continue
|
||||
}
|
||||
cleaned = append(cleaned, line)
|
||||
}
|
||||
text = strings.Join(cleaned, "\n")
|
||||
|
||||
// Cap the prompt size. This slices by bytes, so a cut can land mid-rune
|
||||
// and leave an invalid UTF-8 tail; harmless for a model prompt.
|
||||
if len(text) > 4000 {
|
||||
text = text[:4000]
|
||||
}
|
||||
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
|
||||
// truncate caps a string at maxLen bytes (not runes) before it is stored in
|
||||
// ProcessedEmail.Subject.
|
||||
func truncate(s string, maxLen int) string {
|
||||
if len(s) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return s[:maxLen]
|
||||
}
|
||||
|
||||
// emailClassificationPrompt must stay in sync with the EmailAnalysis struct:
|
||||
// every key it names is a field there, and the status values it lists are the
|
||||
// keys of statusOrder — all but "saved", which only the browser capture sets
|
||||
// and no email can mean.
|
||||
const emailClassificationPrompt = `You are an email classifier for job applications. You will receive the subject line, sender, and body of an email. Determine if this email is related to a job application, and if so, extract structured data.
|
||||
|
||||
Return ONLY a JSON object with these exact keys:
|
||||
- "isJobEmail": boolean - true if this email is about a job application
|
||||
- "action": "create" | "update" | "none" - whether this represents a new application confirmation or an update to an existing one
|
||||
- "company": string - the company name
|
||||
- "jobTitle": string - the job title/position
|
||||
- "status": string - one of: "applied", "screening", "interviewing", "assessment", "offer", "rejected", "withdrawn"
|
||||
- "location": string or null - job location if mentioned
|
||||
- "url": string or null - any application portal URL
|
||||
- "appliedAt": string or null - ISO 8601 date if an application date is mentioned (YYYY-MM-DD format)
|
||||
- "notes": string or null - brief summary of what this email communicates (e.g. "Interview scheduled for March 15", "Application confirmed via Greenhouse")
|
||||
|
||||
If isJobEmail is false, only include that field. No text, no markdown, no explanation. Just the JSON object.`
|
||||
|
||||
// StripMarkdownFence removes a surrounding markdown code fence from a model's
|
||||
// response, so text that should have been bare JSON can be unmarshalled
|
||||
// whether or not the model wrapped it.
|
||||
//
|
||||
// The two TrimPrefix calls are ordered so that "```json" is removed first and
|
||||
// a plain "```" otherwise. It is deliberately forgiving: unfenced input is
|
||||
// returned unchanged apart from surrounding whitespace.
|
||||
//
|
||||
// python/app/rowing.py carries a port of this for the rowing photo reader,
|
||||
// which prompts for bare JSON in the same way and gets the same fenced output.
|
||||
func StripMarkdownFence(raw string) string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
raw = strings.TrimPrefix(raw, "```json")
|
||||
raw = strings.TrimPrefix(raw, "```")
|
||||
raw = strings.TrimSuffix(raw, "```")
|
||||
|
||||
return strings.TrimSpace(raw)
|
||||
}
|
||||
|
||||
// maxEmailAttempts caps how many times a failing email is reprocessed. Each
|
||||
// attempt costs a Claude call, so the cap is what stops one permanently
|
||||
// unparseable email billing on every sync forever. Three gives a transient
|
||||
// outage two further chances across subsequent syncs.
|
||||
const maxEmailAttempts = 3
|
||||
|
||||
// fetchSlack pulls each sync's window edge back by this much so mail that was
|
||||
// delayed between fetch and filter (or index-registered late) is still caught
|
||||
// by the next window. Consumers pay for it with deliberate re-fetches, which
|
||||
// the ProcessedEmail dedup makes free.
|
||||
const fetchSlack = 30 * time.Second
|
||||
|
||||
// maxRewindAge stops a stuck retry from pinning the window open forever. A
|
||||
// failed email is only rewound for while it is younger than this; past that it
|
||||
// has probably been deleted from the mailbox or fallen out of the provider's
|
||||
// returns, so re-fetching for it would never yield anything.
|
||||
const maxRewindAge = 7 * 24 * time.Hour
|
||||
|
||||
// retryableFailure reports whether a previously recorded email should be
|
||||
// processed again. Only failures are retried, and only while they have
|
||||
// attempts left; anything that succeeded is terminal.
|
||||
func retryableFailure(row *models.ProcessedEmail) bool {
|
||||
return row.Action == "error" && row.Attempts < maxEmailAttempts
|
||||
}
|
||||
|
||||
// parseReceivedAt converts the provider's timestamp to a time.Time, returning
|
||||
// the zero value if it is missing or malformed. A zero value is safe: it only
|
||||
// means this row cannot pull the fetch window back, so the email is retried
|
||||
// on the next sync that happens to cover it rather than being chased.
|
||||
func parseReceivedAt(raw string) time.Time {
|
||||
if raw == "" {
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
received, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Unparseable receivedDateTime %q: %v", raw, err)
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
return received
|
||||
}
|
||||
|
||||
// saveProcessed writes the outcome of an attempt: updating the existing row
|
||||
// when this was a retry, inserting when it is the first attempt. Update is
|
||||
// used rather than Save so the row keeps its original CreatedAt, which the
|
||||
// fetch window depends on.
|
||||
func (s *EmailSyncService) saveProcessed(found bool, existing, record *models.ProcessedEmail) {
|
||||
var err error
|
||||
if found {
|
||||
err = s.DB.Model(existing).Updates(map[string]any{
|
||||
"action": record.Action,
|
||||
"job_app_id": record.JobAppID,
|
||||
"attempts": record.Attempts,
|
||||
"received_at": record.ReceivedAt,
|
||||
}).Error
|
||||
} else {
|
||||
err = s.DB.Create(record).Error
|
||||
}
|
||||
|
||||
// Logged rather than returned: a bookkeeping failure must not abort the
|
||||
// rest of the batch. It does mean the email is reprocessed next sync,
|
||||
// which the dedup treats as a first attempt.
|
||||
if err != nil {
|
||||
log.Printf("[EmailSync] Failed to record processed email %q: %v", record.Subject, err)
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"adam-french.co.uk/backend/models"
|
||||
)
|
||||
|
||||
// These tests cover only the pure helpers of the email sync: body cleaning,
|
||||
// truncation, fence stripping, timestamp parsing, the retry predicate and the
|
||||
// filter. Everything else in email_sync.go — token acquisition, the Graph
|
||||
// paging loop, processEmail and the create/update paths — needs either a live
|
||||
// *gorm.DB, a Microsoft Graph endpoint or a Claude call, none of which exist
|
||||
// in a test run, so they are deliberately not exercised here.
|
||||
//
|
||||
// matchesFilter is a method but reads no field of the receiver (it matches
|
||||
// against the package-level subjectKeywords/senderDomains), which is why a
|
||||
// zero-value &EmailSyncService{} is a legitimate receiver below.
|
||||
|
||||
func TestCleanEmailBody(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
content string
|
||||
contentType string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"html tags are stripped and entities decoded",
|
||||
"<p>Hi Adam & team</p><b>thanks</b>",
|
||||
"html",
|
||||
"Hi Adam & team thanks",
|
||||
},
|
||||
{
|
||||
"contentType match is case-insensitive",
|
||||
"<p>hello</p>",
|
||||
"HTML",
|
||||
"hello",
|
||||
},
|
||||
{
|
||||
// Entities are only decoded on the HTML path, so plain text keeps
|
||||
// them verbatim rather than being silently rewritten.
|
||||
"text bodies are not entity-decoded",
|
||||
"a & b",
|
||||
"text",
|
||||
"a & b",
|
||||
},
|
||||
{
|
||||
"runs of spaces and tabs collapse to one space",
|
||||
"one \t two",
|
||||
"text",
|
||||
"one two",
|
||||
},
|
||||
{
|
||||
"three or more newlines collapse to a blank line",
|
||||
"a\n\n\n\n\nb",
|
||||
"text",
|
||||
"a\n\nb",
|
||||
},
|
||||
{
|
||||
"signature marker cuts the tail",
|
||||
"body text\n-- \nAdam French\n07000",
|
||||
"text",
|
||||
"body text",
|
||||
},
|
||||
{
|
||||
"Sent from my iPhone is treated as a signature",
|
||||
"see attached\nSent from my iPhone",
|
||||
"text",
|
||||
"see attached",
|
||||
},
|
||||
{
|
||||
// idx > 0, not >= 0: a body that is nothing but a signature would
|
||||
// otherwise be blanked entirely, losing the only content there is.
|
||||
"a body starting with a signature marker is left intact",
|
||||
"Sent from my iPhone\nreal content",
|
||||
"text",
|
||||
"Sent from my iPhone\nreal content",
|
||||
},
|
||||
{
|
||||
"quoted lines are dropped",
|
||||
"my reply\n> their mail\n > indented quote\nmore reply",
|
||||
"text",
|
||||
"my reply\nmore reply",
|
||||
},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := cleanEmailBody(c.content, c.contentType); got != c.want {
|
||||
t.Fatalf("cleanEmailBody(%q, %q) = %q, want %q", c.content, c.contentType, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The 4000-byte cap is what bounds the prompt cost, so it gets its own test:
|
||||
// the cut is by bytes and is applied before the final TrimSpace.
|
||||
func TestCleanEmailBodyCap(t *testing.T) {
|
||||
got := cleanEmailBody(strings.Repeat("a", 5000), "text")
|
||||
if len(got) != 4000 {
|
||||
t.Fatalf("len = %d, want 4000", len(got))
|
||||
}
|
||||
|
||||
// A body exactly at the cap must pass through untouched.
|
||||
exact := strings.Repeat("b", 4000)
|
||||
if got := cleanEmailBody(exact, "text"); got != exact {
|
||||
t.Fatalf("body at the cap was modified: len = %d", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
s string
|
||||
maxLen int
|
||||
want string
|
||||
}{
|
||||
{"shorter than the cap is unchanged", "abc", 10, "abc"},
|
||||
{"exactly at the cap is unchanged", "abcde", 5, "abcde"},
|
||||
{"longer is cut to the cap", "abcdef", 3, "abc"},
|
||||
{"zero cap yields the empty string", "abc", 0, ""},
|
||||
{"empty input", "", 5, ""},
|
||||
// Bytes, not runes: the cut can land mid-rune. Asserted so the
|
||||
// behaviour is a documented choice rather than a lurking surprise.
|
||||
{"multi-byte runes are cut by byte", "é", 1, "\xc3"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := truncate(c.s, c.maxLen); got != c.want {
|
||||
t.Fatalf("truncate(%q, %d) = %q, want %q", c.s, c.maxLen, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripMarkdownFence(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want string
|
||||
}{
|
||||
{"json-tagged fence", "```json\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"bare fence", "```\n{\"a\":1}\n```", `{"a":1}`},
|
||||
{"unfenced input is returned as-is", `{"a":1}`, `{"a":1}`},
|
||||
{"surrounding whitespace is trimmed", "\n\n {\"a\":1} \n", `{"a":1}`},
|
||||
{"leading whitespace before the fence", " ```json\n{\"a\":1}\n``` ", `{"a":1}`},
|
||||
{"opening fence only", "```json\n{\"a\":1}", `{"a":1}`},
|
||||
{"empty input", "", ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := StripMarkdownFence(c.raw); got != c.want {
|
||||
t.Fatalf("StripMarkdownFence(%q) = %q, want %q", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseReceivedAt(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want time.Time
|
||||
}{
|
||||
{"valid RFC3339", "2024-03-15T10:30:00Z", time.Date(2024, 3, 15, 10, 30, 0, 0, time.UTC)},
|
||||
{"empty means no timestamp", "", time.Time{}},
|
||||
{"malformed falls back to zero rather than failing the sync", "15/03/2024", time.Time{}},
|
||||
{"a date without a time is not RFC3339", "2024-03-15", time.Time{}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if got := parseReceivedAt(c.raw); !got.Equal(c.want) {
|
||||
t.Fatalf("parseReceivedAt(%q) = %v, want %v", c.raw, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryableFailure(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
attempts int
|
||||
want bool
|
||||
}{
|
||||
{"a failure with attempts left is retried", "error", maxEmailAttempts - 1, true},
|
||||
{"a failure at the cap is abandoned", "error", maxEmailAttempts, false},
|
||||
{"a failure past the cap is abandoned", "error", maxEmailAttempts + 1, false},
|
||||
{"a success is terminal even with attempts left", "created", 0, false},
|
||||
{"a skip is terminal too", "skipped", 0, false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
row := &models.ProcessedEmail{Action: c.action, Attempts: c.attempts}
|
||||
if got := retryableFailure(row); got != c.want {
|
||||
t.Fatalf("retryableFailure(%s, %d) = %v, want %v", c.action, c.attempts, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchesFilter(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
subject string
|
||||
sender string
|
||||
want bool
|
||||
}{
|
||||
{"subject keyword anywhere in the line", "Your application to Acme", "[email protected]", true},
|
||||
{"subject keyword is case-insensitive", "INTERVIEW CONFIRMED", "[email protected]", true},
|
||||
{"sender on a tracked ATS domain", "hello", "[email protected]", true},
|
||||
{"sender on a subdomain of a tracked domain", "hello", "[email protected]", true},
|
||||
{"sender domain match is case-insensitive", "hello", "[email protected]", true},
|
||||
// The rule is an @ or . boundary, so a lookalike domain that merely
|
||||
// ends in the same letters must not match.
|
||||
{"lookalike domain does not match", "hello", "[email protected]", false},
|
||||
{"neither subject nor sender matches", "lunch tomorrow?", "[email protected]", false},
|
||||
}
|
||||
|
||||
s := &EmailSyncService{}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
email := graphMessage{Subject: c.subject}
|
||||
email.From.EmailAddress.Address = c.sender
|
||||
if got := s.matchesFilter(email); got != c.want {
|
||||
t.Fatalf("matchesFilter(%q, %q) = %v, want %v", c.subject, c.sender, got, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,377 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
_ "embed"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ENV_APPLY_DIR is the directory shared with the host (./env-apply/run in the
|
||||
// checkout, bind-mounted by docker-compose). It is the whole interface
|
||||
// between this process and the host script that edits .env.
|
||||
const ENV_APPLY_DIR = "/backend/env-apply"
|
||||
|
||||
// The registry is JSON rather than a Go literal because the host script
|
||||
// (env-apply/apply.py) reads the same file from the checkout: one list
|
||||
// decides both what the panel offers and what the host will accept.
|
||||
//
|
||||
//go:embed env_registry.json
|
||||
var envRegistryJSON []byte
|
||||
|
||||
// EnvVar is one registry entry.
|
||||
//
|
||||
// Kind decides how a value is validated and how the panel renders it:
|
||||
// "secret" and "generated" are never sent to the browser; "generated" can
|
||||
// also be minted here. Services lists the compose services that read the
|
||||
// variable, which is what the host recreates after a change.
|
||||
type EnvVar struct {
|
||||
Name string `json:"name"`
|
||||
Group string `json:"group"`
|
||||
Purpose string `json:"purpose"`
|
||||
Kind string `json:"kind"`
|
||||
Editable bool `json:"editable"`
|
||||
LockedReason string `json:"lockedReason,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
DocsURL string `json:"docsUrl,omitempty"`
|
||||
Options []string `json:"options,omitempty"`
|
||||
Warning string `json:"warning,omitempty"`
|
||||
}
|
||||
|
||||
// Secret reports whether the variable's value must stay on the server.
|
||||
func (v EnvVar) Secret() bool {
|
||||
return v.Kind == "secret" || v.Kind == "generated"
|
||||
}
|
||||
|
||||
// EnvManager turns an edit made in the admin panel into a request for the
|
||||
// host to apply.
|
||||
//
|
||||
// The backend deliberately cannot write .env or restart containers itself:
|
||||
// it is the internet-facing process, and either ability would make a
|
||||
// compromised admin session a compromised host. Instead it validates the
|
||||
// change and leaves request.json in the shared directory; the host's watcher
|
||||
// (env-apply/apply.py, run by a systemd path unit) merges it into .env,
|
||||
// recreates the affected containers and reports back through status.json.
|
||||
type EnvManager struct {
|
||||
dir string
|
||||
vars []EnvVar
|
||||
byName map[string]EnvVar
|
||||
|
||||
// Serialises Submit and Cancel so two requests cannot interleave their
|
||||
// read-merge-write of request.json. The host is a separate process and is
|
||||
// handled by renames instead (see Submit).
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// envApplyRequest is request.json. Clearing a variable is setting it to "".
|
||||
type envApplyRequest struct {
|
||||
ID string `json:"id"`
|
||||
RequestedAt time.Time `json:"requestedAt"`
|
||||
Set map[string]string `json:"set"`
|
||||
}
|
||||
|
||||
// EnvApplyStatus is what the panel polls. State is one of idle, pending
|
||||
// (request written, host has not picked it up), applying, applied, failed.
|
||||
type EnvApplyStatus struct {
|
||||
State string `json:"state"`
|
||||
ID string `json:"id,omitempty"`
|
||||
// When the state was entered.
|
||||
At *time.Time `json:"at,omitempty"`
|
||||
// Names in a pending request. Values are never reported.
|
||||
Pending []string `json:"pending,omitempty"`
|
||||
Services []string `json:"services,omitempty"`
|
||||
Changed []string `json:"changed,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
// False once a request has waited long enough that nothing on the host
|
||||
// can be watching for it (a dev machine, or the units not installed).
|
||||
Watcher bool `json:"watcher"`
|
||||
}
|
||||
|
||||
const (
|
||||
envRequestFile = "request.json"
|
||||
envStatusFile = "status.json"
|
||||
|
||||
// The path unit fires within a second, so a request still unclaimed
|
||||
// after this long means there is no watcher.
|
||||
envWatcherGrace = 15 * time.Second
|
||||
// An "applying" status older than this is a host script that died
|
||||
// mid-run; stop letting it block new requests.
|
||||
envApplyingStale = 5 * time.Minute
|
||||
|
||||
envValueMaxLen = 4096
|
||||
)
|
||||
|
||||
// ErrEnvApplying is returned by Submit while the host is mid-apply.
|
||||
var ErrEnvApplying = errors.New("a change is being applied; try again in a moment")
|
||||
|
||||
// NewEnvManager parses the embedded registry. dir need not exist yet: without
|
||||
// the bind mount, reads report "idle" and Submit fails with a clear error.
|
||||
func NewEnvManager(dir string) (*EnvManager, error) {
|
||||
var vars []EnvVar
|
||||
if err := json.Unmarshal(envRegistryJSON, &vars); err != nil {
|
||||
return nil, fmt.Errorf("parsing env registry: %w", err)
|
||||
}
|
||||
byName := make(map[string]EnvVar, len(vars))
|
||||
for _, v := range vars {
|
||||
if _, dup := byName[v.Name]; dup {
|
||||
return nil, fmt.Errorf("env registry lists %s twice", v.Name)
|
||||
}
|
||||
byName[v.Name] = v
|
||||
}
|
||||
return &EnvManager{dir: dir, vars: vars, byName: byName}, nil
|
||||
}
|
||||
|
||||
// Vars returns the registry in file order, which is the order the panel
|
||||
// shows.
|
||||
func (m *EnvManager) Vars() []EnvVar {
|
||||
return m.vars
|
||||
}
|
||||
|
||||
// Validate checks one proposed value. The empty string clears the variable
|
||||
// and is always acceptable for an editable one.
|
||||
//
|
||||
// The control-character rule is the security-relevant one: .env is line
|
||||
// oriented, so a newline in a value would let an edit to an allowed variable
|
||||
// write a second, arbitrary one.
|
||||
func (m *EnvManager) Validate(name, value string) error {
|
||||
v, ok := m.byName[name]
|
||||
if !ok {
|
||||
return fmt.Errorf("%s is not a known variable", name)
|
||||
}
|
||||
if !v.Editable {
|
||||
return fmt.Errorf("%s cannot be changed from the panel", name)
|
||||
}
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
if len(value) > envValueMaxLen {
|
||||
return fmt.Errorf("%s is too long", name)
|
||||
}
|
||||
for _, r := range value {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return fmt.Errorf("%s contains a control character", name)
|
||||
}
|
||||
}
|
||||
// The host writes values single-quoted, and a dotenv single-quoted
|
||||
// string has no escape for the quote itself.
|
||||
if strings.ContainsRune(value, '\'') {
|
||||
return fmt.Errorf("%s cannot contain a single quote", name)
|
||||
}
|
||||
|
||||
switch v.Kind {
|
||||
case "url":
|
||||
u, err := url.Parse(value)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return fmt.Errorf("%s must be an http(s) URL", name)
|
||||
}
|
||||
case "bool":
|
||||
if value != "true" && value != "false" {
|
||||
return fmt.Errorf("%s must be true or false", name)
|
||||
}
|
||||
case "duration":
|
||||
if d, err := time.ParseDuration(value); err != nil || d <= 0 {
|
||||
return fmt.Errorf("%s must be a duration such as 30m", name)
|
||||
}
|
||||
case "number":
|
||||
if n, err := strconv.Atoi(value); err != nil || n <= 0 {
|
||||
return fmt.Errorf("%s must be a positive whole number", name)
|
||||
}
|
||||
case "enum":
|
||||
if !slices.Contains(v.Options, value) {
|
||||
return fmt.Errorf("%s must be one of: %s", name, strings.Join(v.Options, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ServicesFor is the set of compose services a change to names recreates.
|
||||
// The backend is always among them: the panel reports state from this
|
||||
// process's own environment, which only a recreate refreshes.
|
||||
func (m *EnvManager) ServicesFor(names []string) []string {
|
||||
services := []string{"backend"}
|
||||
for _, name := range names {
|
||||
for _, s := range m.byName[name].Services {
|
||||
if !slices.Contains(services, s) {
|
||||
services = append(services, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
slices.Sort(services)
|
||||
return services
|
||||
}
|
||||
|
||||
// Submit validates a batch of edits and hands it to the host. set holds
|
||||
// explicit values ("" clears); generate names variables to mint a random
|
||||
// value for. The generated values are returned and exist nowhere else on
|
||||
// this side — the caller shows them once.
|
||||
//
|
||||
// Nothing is written unless the whole batch is valid.
|
||||
//
|
||||
// A request the host has not yet claimed is merged into rather than
|
||||
// refused, so edits are not stuck behind an absent watcher. The host claims
|
||||
// a request by renaming it, so the worst a race can do is hand it values it
|
||||
// has already applied.
|
||||
func (m *EnvManager) Submit(set map[string]string, generate []string) (map[string]string, []string, error) {
|
||||
changes := make(map[string]string, len(set)+len(generate))
|
||||
for name, value := range set {
|
||||
value = strings.TrimSpace(value)
|
||||
if err := m.Validate(name, value); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
changes[name] = value
|
||||
}
|
||||
generated := make(map[string]string, len(generate))
|
||||
for _, name := range generate {
|
||||
if v, ok := m.byName[name]; !ok || !v.Editable || v.Kind != "generated" {
|
||||
return nil, nil, fmt.Errorf("%s cannot be generated", name)
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
generated[name] = hex.EncodeToString(raw)
|
||||
changes[name] = generated[name]
|
||||
}
|
||||
if len(changes) == 0 {
|
||||
return nil, nil, errors.New("no changes given")
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if status := m.readStatus(); status != nil && status.State == "applying" &&
|
||||
status.At != nil && time.Since(*status.At) < envApplyingStale {
|
||||
return nil, nil, ErrEnvApplying
|
||||
}
|
||||
|
||||
request := envApplyRequest{Set: changes}
|
||||
if pending := m.readRequest(); pending != nil {
|
||||
for name, value := range pending.Set {
|
||||
if _, replaced := changes[name]; !replaced {
|
||||
request.Set[name] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
id := make([]byte, 8)
|
||||
if _, err := rand.Read(id); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
request.ID = hex.EncodeToString(id)
|
||||
request.RequestedAt = time.Now().UTC()
|
||||
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
return generated, m.ServicesFor(names), nil
|
||||
}
|
||||
|
||||
// writeRequest writes request.json so the host only ever sees a complete
|
||||
// file it can read: temp name, owner and mode set, then rename.
|
||||
//
|
||||
// This process runs as root in the container while the host script runs as
|
||||
// the checkout's owner, so the file is handed to whoever owns the shared
|
||||
// directory. 0600 because it holds the new secrets in the clear until the
|
||||
// host consumes it.
|
||||
func (m *EnvManager) writeRequest(request *envApplyRequest) error {
|
||||
info, err := os.Stat(m.dir)
|
||||
if err != nil {
|
||||
return fmt.Errorf("the env-apply directory is not mounted: %w", err)
|
||||
}
|
||||
data, err := json.Marshal(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := filepath.Join(m.dir, envRequestFile+".tmp")
|
||||
if err := os.WriteFile(tmp, data, 0600); err != nil {
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
|
||||
if err := os.Chown(tmp, int(stat.Uid), int(stat.Gid)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("handing env request to the host user: %w", err)
|
||||
}
|
||||
}
|
||||
if err := os.Rename(tmp, filepath.Join(m.dir, envRequestFile)); err != nil {
|
||||
os.Remove(tmp)
|
||||
return fmt.Errorf("writing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Cancel withdraws a request the host has not claimed. Once claimed it is
|
||||
// too late, and this is a no-op.
|
||||
func (m *EnvManager) Cancel() error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if err := os.Remove(filepath.Join(m.dir, envRequestFile)); err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return fmt.Errorf("removing env request: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *EnvManager) readRequest() *envApplyRequest {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var request envApplyRequest
|
||||
if json.Unmarshal(raw, &request) != nil {
|
||||
return nil
|
||||
}
|
||||
return &request
|
||||
}
|
||||
|
||||
func (m *EnvManager) readStatus() *EnvApplyStatus {
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envStatusFile))
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var status EnvApplyStatus
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
return nil
|
||||
}
|
||||
return &status
|
||||
}
|
||||
|
||||
// Status reports where the latest change has got to. An unclaimed request
|
||||
// takes precedence over status.json, which then describes an older change.
|
||||
func (m *EnvManager) Status() EnvApplyStatus {
|
||||
if request := m.readRequest(); request != nil {
|
||||
names := make([]string, 0, len(request.Set))
|
||||
for name := range request.Set {
|
||||
names = append(names, name)
|
||||
}
|
||||
slices.Sort(names)
|
||||
at := request.RequestedAt
|
||||
return EnvApplyStatus{
|
||||
State: "pending",
|
||||
ID: request.ID,
|
||||
At: &at,
|
||||
Pending: names,
|
||||
Services: m.ServicesFor(names),
|
||||
Watcher: time.Since(at) < envWatcherGrace,
|
||||
}
|
||||
}
|
||||
if status := m.readStatus(); status != nil {
|
||||
status.Watcher = true
|
||||
return *status
|
||||
}
|
||||
return EnvApplyStatus{State: "idle", Watcher: true}
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func newEnvManager(t *testing.T) *EnvManager {
|
||||
t.Helper()
|
||||
m, err := NewEnvManager(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func readRequestFile(t *testing.T, m *EnvManager) envApplyRequest {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatalf("reading request: %v", err)
|
||||
}
|
||||
var request envApplyRequest
|
||||
if err := json.Unmarshal(raw, &request); err != nil {
|
||||
t.Fatalf("parsing request: %v", err)
|
||||
}
|
||||
return request
|
||||
}
|
||||
|
||||
// The registry and .env.example describe the same variables; a name added to
|
||||
// one and not the other is either invisible in the panel or undocumented.
|
||||
func TestEnvRegistryMatchesEnvExample(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../.env.example")
|
||||
if err != nil {
|
||||
t.Fatalf("reading .env.example: %v", err)
|
||||
}
|
||||
var example []string
|
||||
for _, match := range regexp.MustCompile(`(?m)^([A-Z][A-Z0-9_]*)=`).FindAllStringSubmatch(string(raw), -1) {
|
||||
example = append(example, match[1])
|
||||
}
|
||||
|
||||
var registry []string
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
registry = append(registry, v.Name)
|
||||
}
|
||||
|
||||
for _, name := range example {
|
||||
if !slices.Contains(registry, name) {
|
||||
t.Errorf("%s is in .env.example but not in env_registry.json", name)
|
||||
}
|
||||
}
|
||||
for _, name := range registry {
|
||||
if !slices.Contains(example, name) {
|
||||
t.Errorf("%s is in env_registry.json but not in .env.example", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvRegistryEntriesAreWellFormed(t *testing.T) {
|
||||
kinds := []string{"secret", "generated", "text", "url", "bool", "duration", "number", "enum"}
|
||||
for _, v := range newEnvManager(t).Vars() {
|
||||
if !slices.Contains(kinds, v.Kind) {
|
||||
t.Errorf("%s has unknown kind %q", v.Name, v.Kind)
|
||||
}
|
||||
if v.Group == "" || v.Purpose == "" {
|
||||
t.Errorf("%s is missing its group or purpose", v.Name)
|
||||
}
|
||||
if v.Editable && len(v.Services) == 0 {
|
||||
t.Errorf("%s is editable but names no service to recreate", v.Name)
|
||||
}
|
||||
if !v.Editable && v.LockedReason == "" {
|
||||
t.Errorf("%s is locked without a reason", v.Name)
|
||||
}
|
||||
if v.Kind == "enum" && len(v.Options) == 0 {
|
||||
t.Errorf("%s is an enum with no options", v.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvValidate(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name, value string
|
||||
ok bool
|
||||
}{
|
||||
{"CLAUDE_API_KEY", "sk-ant-abc123", true},
|
||||
{"CLAUDE_API_KEY", "", true},
|
||||
// The injection case: a newline would start a second variable.
|
||||
{"CLAUDE_API_KEY", "x\nPOSTGRES_PASSWORD=owned", false},
|
||||
{"CLAUDE_API_KEY", "x\rY", false},
|
||||
{"CLAUDE_API_KEY", "it's", false},
|
||||
{"CLAUDE_API_KEY", strings.Repeat("a", envValueMaxLen+1), false},
|
||||
{"POSTGRES_PASSWORD", "anything", false},
|
||||
{"NOT_A_VARIABLE", "anything", false},
|
||||
{"EMAIL_BACKEND", "graph", true},
|
||||
{"EMAIL_BACKEND", "pop3", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "45m", true},
|
||||
{"EMAIL_SYNC_INTERVAL", "soon", false},
|
||||
{"EMAIL_SYNC_INTERVAL", "-5m", false},
|
||||
{"EMAIL_SYNC_ENABLED", "true", true},
|
||||
{"EMAIL_SYNC_ENABLED", "yes", false},
|
||||
{"IMAP_PORT", "993", true},
|
||||
{"IMAP_PORT", "imaps", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "https://example.com/api/spotify/callback", true},
|
||||
{"SPOTIFY_REDIRECT_URI", "example.com/callback", false},
|
||||
{"SPOTIFY_REDIRECT_URI", "javascript:alert(1)", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
err := m.Validate(c.name, c.value)
|
||||
if (err == nil) != c.ok {
|
||||
t.Errorf("Validate(%s, %q) error = %v, want ok = %v", c.name, c.value, err, c.ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWritesRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
generated, services, err := m.Submit(
|
||||
map[string]string{"TFL_APP_KEY": " tfl-key ", "STEAM_ID": ""},
|
||||
[]string{"ICECAST_RELAY_PASSWORD"},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
if len(generated["ICECAST_RELAY_PASSWORD"]) != 64 {
|
||||
t.Fatalf("generated value = %q, want 64 hex characters", generated["ICECAST_RELAY_PASSWORD"])
|
||||
}
|
||||
if want := []string{"backend", "icecast2", "python"}; !slices.Equal(services, want) {
|
||||
t.Fatalf("services = %v, want %v", services, want)
|
||||
}
|
||||
|
||||
request := readRequestFile(t, m)
|
||||
want := map[string]string{
|
||||
"TFL_APP_KEY": "tfl-key", // surrounding whitespace from a paste is dropped
|
||||
"STEAM_ID": "",
|
||||
"ICECAST_RELAY_PASSWORD": generated["ICECAST_RELAY_PASSWORD"],
|
||||
}
|
||||
if len(request.Set) != len(want) {
|
||||
t.Fatalf("request.Set = %v, want %v", request.Set, want)
|
||||
}
|
||||
for name, value := range want {
|
||||
if request.Set[name] != value {
|
||||
t.Errorf("request.Set[%s] = %q, want %q", name, request.Set[name], value)
|
||||
}
|
||||
}
|
||||
|
||||
info, err := os.Stat(filepath.Join(m.dir, envRequestFile))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Mode().Perm() != 0600 {
|
||||
t.Errorf("request mode = %v, want 0600: it holds secrets in the clear", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRejectsWholeBatch(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
cases := []struct {
|
||||
name string
|
||||
set map[string]string
|
||||
generate []string
|
||||
}{
|
||||
{"one bad value", map[string]string{"STEAM_ID": "1", "EMAIL_BACKEND": "pop3"}, nil},
|
||||
{"a locked variable", map[string]string{"STEAM_ID": "1", "DOMAIN": "evil.example"}, nil},
|
||||
{"generating a pasted secret", nil, []string{"CLAUDE_API_KEY"}},
|
||||
{"generating a locked secret", nil, []string{"POSTGRES_PASSWORD"}},
|
||||
{"nothing at all", nil, nil},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
if _, _, err := m.Submit(c.set, c.generate); err == nil {
|
||||
t.Fatal("Submit succeeded, want an error")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(m.dir, envRequestFile)); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("a rejected batch left a request file behind")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitMergesUnclaimedRequest(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1", "TFL_APP_KEY": "old"}, nil); err != nil {
|
||||
t.Fatalf("first Submit: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"TFL_APP_KEY": "new"}, nil); err != nil {
|
||||
t.Fatalf("second Submit: %v", err)
|
||||
}
|
||||
request := readRequestFile(t, m)
|
||||
if request.Set["STEAM_ID"] != "1" || request.Set["TFL_APP_KEY"] != "new" {
|
||||
t.Fatalf("merged request = %v, want the earlier STEAM_ID kept and TFL_APP_KEY replaced", request.Set)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitWithoutMount(t *testing.T) {
|
||||
m, err := NewEnvManager(filepath.Join(t.TempDir(), "absent"))
|
||||
if err != nil {
|
||||
t.Fatalf("NewEnvManager: %v", err)
|
||||
}
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err == nil {
|
||||
t.Fatal("Submit succeeded with no shared directory")
|
||||
}
|
||||
if got := m.Status().State; got != "idle" {
|
||||
t.Fatalf("Status().State = %q, want idle", got)
|
||||
}
|
||||
}
|
||||
|
||||
func writeStatusFile(t *testing.T, m *EnvManager, state string, at time.Time) {
|
||||
t.Helper()
|
||||
data, _ := json.Marshal(EnvApplyStatus{State: state, ID: "abc", At: &at})
|
||||
if err := os.WriteFile(filepath.Join(m.dir, envStatusFile), data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvStatus(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
if got := m.Status(); got.State != "idle" || !got.Watcher {
|
||||
t.Fatalf("fresh status = %+v, want idle with watcher assumed", got)
|
||||
}
|
||||
|
||||
writeStatusFile(t, m, "applied", time.Now())
|
||||
if got := m.Status(); got.State != "applied" || got.ID != "abc" {
|
||||
t.Fatalf("status = %+v, want the host's applied report", got)
|
||||
}
|
||||
|
||||
// An unclaimed request outranks the report of an older change.
|
||||
if _, _, err := m.Submit(map[string]string{"CLAUDE_API_KEY": "sk-secret"}, nil); err != nil {
|
||||
t.Fatalf("Submit: %v", err)
|
||||
}
|
||||
got := m.Status()
|
||||
if got.State != "pending" || !slices.Equal(got.Pending, []string{"CLAUDE_API_KEY"}) || !got.Watcher {
|
||||
t.Fatalf("status = %+v, want pending CLAUDE_API_KEY", got)
|
||||
}
|
||||
if encoded, _ := json.Marshal(got); strings.Contains(string(encoded), "sk-secret") {
|
||||
t.Fatal("the status leaks a pending value")
|
||||
}
|
||||
|
||||
// Backdate the request past the grace period: nothing is watching.
|
||||
request := readRequestFile(t, m)
|
||||
request.RequestedAt = time.Now().Add(-2 * envWatcherGrace)
|
||||
if err := m.writeRequest(&request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if m.Status().Watcher {
|
||||
t.Fatal("a long-unclaimed request still reports a watcher")
|
||||
}
|
||||
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel: %v", err)
|
||||
}
|
||||
if got := m.Status().State; got != "applied" {
|
||||
t.Fatalf("after Cancel state = %q, want the earlier applied report", got)
|
||||
}
|
||||
if err := m.Cancel(); err != nil {
|
||||
t.Fatalf("Cancel with nothing pending: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvSubmitRefusedWhileApplying(t *testing.T) {
|
||||
m := newEnvManager(t)
|
||||
writeStatusFile(t, m, "applying", time.Now())
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); !errors.Is(err, ErrEnvApplying) {
|
||||
t.Fatalf("Submit error = %v, want ErrEnvApplying", err)
|
||||
}
|
||||
|
||||
// A host script that died mid-run must not block the panel for ever.
|
||||
writeStatusFile(t, m, "applying", time.Now().Add(-2*envApplyingStale))
|
||||
if _, _, err := m.Submit(map[string]string{"STEAM_ID": "1"}, nil); err != nil {
|
||||
t.Fatalf("Submit after a stale applying status: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
[
|
||||
{"name": "CLAUDE_API_KEY", "group": "API keys", "purpose": "Email pipeline, rowing photo reader, job posting reader", "kind": "secret", "editable": true, "services": ["backend", "python"], "docsUrl": "https://console.anthropic.com/settings/keys"},
|
||||
{"name": "STEAM_API_KEY", "group": "API keys", "purpose": "Steam status widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://steamcommunity.com/dev/apikey"},
|
||||
{"name": "STEAM_ID", "group": "API keys", "purpose": "Steam account the widget reports on (64-bit ID)", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "TFL_APP_KEY", "group": "API keys", "purpose": "TfL Unified API, used by the hotel finder", "kind": "secret", "editable": true, "services": ["python"], "docsUrl": "https://api-portal.tfl.gov.uk/profile"},
|
||||
|
||||
{"name": "SPOTIFY_CLIENT_ID", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_CLIENT_SECRET", "group": "Spotify", "purpose": "Spotify listening widget", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://developer.spotify.com/dashboard"},
|
||||
{"name": "SPOTIFY_REDIRECT_URI", "group": "Spotify", "purpose": "Must match the URI registered in the Spotify dashboard exactly", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "SPOTIFY_AUTH_STATE", "group": "Spotify", "purpose": "Former fixed OAuth state", "kind": "secret", "editable": false, "lockedReason": "No longer read: the OAuth state is a per-request nonce."},
|
||||
|
||||
{"name": "EMAIL_BACKEND", "group": "Email ingest", "purpose": "Mail source for the email pipeline", "kind": "enum", "options": ["graph", "imap"], "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_ENABLED", "group": "Email ingest", "purpose": "Run the periodic email sync", "kind": "bool", "editable": true, "services": ["backend"]},
|
||||
{"name": "EMAIL_SYNC_INTERVAL", "group": "Email ingest", "purpose": "Time between syncs, as a Go duration such as 30m (default 30m)", "kind": "duration", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_CLIENT_ID", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "text", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_CLIENT_SECRET", "group": "Email ingest", "purpose": "Microsoft Graph app registration", "kind": "secret", "editable": true, "services": ["backend"], "docsUrl": "https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps/ApplicationsListBlade"},
|
||||
{"name": "MSGRAPH_TENANT_ID", "group": "Email ingest", "purpose": "\"consumers\" for a personal outlook.com account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "MSGRAPH_REDIRECT_URI", "group": "Email ingest", "purpose": "OAuth callback, behind the site's HTTPS origin", "kind": "url", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_HOST", "group": "Email ingest", "purpose": "IMAP fallback server", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PORT", "group": "Email ingest", "purpose": "IMAP fallback port (993)", "kind": "number", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_EMAIL", "group": "Email ingest", "purpose": "IMAP fallback account", "kind": "text", "editable": true, "services": ["backend"]},
|
||||
{"name": "IMAP_PASSWORD", "group": "Email ingest", "purpose": "App-specific password, not the account password", "kind": "secret", "editable": true, "services": ["backend"]},
|
||||
|
||||
{"name": "ICECAST_SOURCE_PASSWORD", "group": "Radio", "purpose": "Liquidsoap to Icecast, and live broadcasters to the harbor port", "kind": "generated", "editable": true, "services": ["icecast2"], "warning": "Live broadcasting clients must be given the new password."},
|
||||
{"name": "ICECAST_RELAY_PASSWORD", "group": "Radio", "purpose": "Icecast relay clients", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_USER", "group": "Radio", "purpose": "Icecast web admin login", "kind": "text", "editable": true, "services": ["icecast2"]},
|
||||
{"name": "ICECAST_ADMIN_PASSWORD", "group": "Radio", "purpose": "Icecast web admin login", "kind": "generated", "editable": true, "services": ["icecast2"]},
|
||||
|
||||
{"name": "BACKEND_SECRET", "group": "Backend", "purpose": "Signs the JWTs in the auth cookies", "kind": "generated", "editable": true, "services": ["backend"], "warning": "Rotating this logs everyone out, including you."},
|
||||
{"name": "SILVERBULLET_GIT_INTERVAL", "group": "Backend", "purpose": "Seconds between notes commit/push cycles (default 300)", "kind": "number", "editable": true, "services": ["silverbullet-git"]},
|
||||
|
||||
{"name": "DOMAIN", "group": "Infrastructure", "purpose": "Apex domain: TLS certificate, cookie domain, nginx server name", "kind": "text", "editable": false, "lockedReason": "Changing the domain needs a new certificate and a full restart."},
|
||||
{"name": "EMAIL", "group": "Infrastructure", "purpose": "Let's Encrypt account address", "kind": "text", "editable": false, "lockedReason": "Only read by certbot when it registers the account."},
|
||||
{"name": "OBSIDIAN_DIR", "group": "Infrastructure", "purpose": "Host path of the notes vault", "kind": "text", "editable": false, "lockedReason": "A bind-mount path: a wrong value stops the stack from starting."},
|
||||
{"name": "SEED_DB", "group": "Infrastructure", "purpose": "Development-only test data switch", "kind": "bool", "editable": false, "lockedReason": "Would inject test data into the live site."},
|
||||
{"name": "BACKEND_HOST", "group": "Infrastructure", "purpose": "Backend container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "BACKEND_PORT", "group": "Infrastructure", "purpose": "Backend listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "BACKEND_ENDPOINT", "group": "Infrastructure", "purpose": "URL prefix nginx mounts the API at", "kind": "text", "editable": false, "lockedReason": "The Vue app assumes /api."},
|
||||
{"name": "PYTHON_HOST", "group": "Infrastructure", "purpose": "Python container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "PYTHON_PORT", "group": "Infrastructure", "purpose": "Python listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_HOST", "group": "Infrastructure", "purpose": "Icecast container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "ICECAST_PORT", "group": "Infrastructure", "purpose": "Icecast listen port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "ICECAST_MOUNT", "group": "Infrastructure", "purpose": "Listener-facing stream mount", "kind": "text", "editable": false, "lockedReason": "The player and nginx both assume this mount."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_MOUNT", "group": "Infrastructure", "purpose": "Live broadcast mount", "kind": "text", "editable": false, "lockedReason": "Broadcasting clients are configured against it."},
|
||||
{"name": "LIQUIDSOAP_HARBOR_PORT", "group": "Infrastructure", "purpose": "Live broadcast port, published to the host", "kind": "text", "editable": false, "lockedReason": "A published port: changing it needs the router and clients updated."},
|
||||
{"name": "SILVERBULLET_HOST", "group": "Infrastructure", "purpose": "Notes editor container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PORT", "group": "Infrastructure", "purpose": "Notes editor port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_HOST", "group": "Infrastructure", "purpose": "Public notes container name", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "SILVERBULLET_PUBLIC_PORT", "group": "Infrastructure", "purpose": "Public notes port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
|
||||
{"name": "POSTGRES_HOST", "group": "Database", "purpose": "Database container name", "kind": "text", "editable": false, "lockedReason": "Renames the database container."},
|
||||
{"name": "POSTGRES_PORT", "group": "Database", "purpose": "Database port", "kind": "text", "editable": false, "lockedReason": "Every client of the database assumes it."},
|
||||
{"name": "POSTGRES_USER", "group": "Database", "purpose": "Database role", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_PASSWORD", "group": "Database", "purpose": "Database password", "kind": "secret", "editable": false, "lockedReason": "Only applied when the volume is first initialised; changing it here locks the backend out."},
|
||||
{"name": "POSTGRES_DB", "group": "Database", "purpose": "Backend database name", "kind": "text", "editable": false, "lockedReason": "Only applied when the volume is first initialised."},
|
||||
{"name": "POSTGRES_GITEA_DB", "group": "Database", "purpose": "Gitea database name", "kind": "text", "editable": false, "lockedReason": "Created by hand on a fresh volume."},
|
||||
|
||||
{"name": "GITEA_HOST", "group": "Gitea", "purpose": "Gitea container name and nginx upstream", "kind": "text", "editable": false, "lockedReason": "Renames a container and repoints nginx."},
|
||||
{"name": "GITEA_PORT", "group": "Gitea", "purpose": "Gitea HTTP port", "kind": "text", "editable": false, "lockedReason": "Renames a container or repoints nginx."},
|
||||
{"name": "GITEA_INTERNAL_TOKEN", "group": "Gitea", "purpose": "Gitea internal API token", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_LFS_JWT_SECRET", "group": "Gitea", "purpose": "Gitea LFS token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_OAUTH2_JWT_SECRET", "group": "Gitea", "purpose": "Gitea OAuth2 token signing", "kind": "secret", "editable": false, "lockedReason": "Rotating Gitea's own secrets can invalidate its sessions and LFS links."},
|
||||
{"name": "GITEA_RUNNER_HOST", "group": "Gitea", "purpose": "Gitea URL the Actions runner registers against", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_NAME", "group": "Gitea", "purpose": "Actions runner name", "kind": "text", "editable": false, "lockedReason": "Read by gitea-runner/run.sh on the host, not by a container."},
|
||||
{"name": "GITEA_RUNNER_REGISTRATION_TOKEN", "group": "Gitea", "purpose": "Single-use runner registration token", "kind": "secret", "editable": false, "lockedReason": "Single-use, and ignored once the runner is registered."}
|
||||
]
|
||||
@@ -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)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user