Author SHA1 Message Date
renovate d0da12e943 Update Go modules (non-major)
renovate/stability-days Updates have met minimum release age requirement
Test and deploy / test (push) Successful in 42s
Test and deploy / deploy (push) Skipped
2026-11-30 04:03:03 +00:00
adamfandClaude Opus 5.5 ffc68bc151 Move the CI runners to adamf/stprunner
Test and deploy / test (push) Successful in 23s
Test and deploy / deploy (push) Successful in 3s
stpvm's and stpbuild's runners are now gitea-runner v6.0.1 systemd
services installed by stprunner's install.sh (hosts/<host>.env per VM),
replacing gitea-runner/run.sh from @reboot cron and the untracked copy on
stpbuild. act_runner 0.2.11 could not run node24 actions. stpvm's runner
is renamed from stppi to stpvm. The GITEA_RUNNER_* env vars had no reader
left. Renovate now also watches stprunner, for gitea-runner releases.

The ignore rules stay: the old directory is still on stpvm with its
.runner credentials.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 13:47:03 +00:00
adamfandClaude Opus 5.5 66173d96e3 CI: scratch directories per run, not per commit
Test and deploy / test (push) Successful in 26s
Test and deploy / deploy (push) Successful in 26s
The build runner takes two jobs at once, so the same commit pushed to
two branches (main and a feature branch) ran its test job twice in
parallel against one src-<sha> directory, and each run's clean-up
deleted the other's source mid-test. Suffix the scratch directories
(and activity-tracker's throwaway Postgres and network) with the run id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:14:45 +00:00
adamfandClaude Opus 5.5 d383774e97 Harden auth: same-origin check, live admin flag, 90-day refresh
Test and deploy / test (push) Failing after 28s
Test and deploy / deploy (push) Has been skipped
- Refuse non-GET requests whose Origin (or Sec-Fetch-Site) is not the
  apex or www. SameSite=Lax lets sibling subdomains such as radar. and
  git. send the auth cookies. The WebSocket check shares the helper and
  no longer accepts localhost in production.
- Take the admin flag from the user row the token check already loads,
  so a demotion applies on the next request, not on token expiry.
- Cut the refresh token lifetime from 365 to 90 days; refreshes renew it.
- Docs: fix the stale revocation notes in backend/README.md and the
  Cloudflare Access comment in routes.caddy.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:12:01 +00:00
adamfandClaude Opus 5.5 3139e8e239 CI: run tests and Renovate on the build VM
Test and deploy / test (push) Successful in 1m40s
Test and deploy / deploy (push) Successful in 4s
The test job and Renovate move to stpbuild's runner (label `build`), a
new Proxmox VM; deploy and maintenance stay on stpvm (`self-hosted`).
test fetches over HTTP with the job's own GITEA_TOKEN. DEPLOYMENT.md
gains a "Build VM" section, and CLAUDE.md says where each job runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 16:00:13 +00:00
adamfandClaude Opus 5.5 18265871e1 Harden the chat hub, evict idle rate-limit keys, isolate Dozzle
Test and deploy / test (push) Successful in 16s
Test and deploy / deploy (push) Successful in 30s
- Chat: cap frame, message and file URL sizes, put a write deadline on
  every send so a stalled client can't hold the hub lock, and check the
  save, prune and history errors instead of broadcasting an unsaved
  message. ChatPanel's maxlength stays under the server cap.
- RateLimiter: sweep keys idle past the window, at most once a window.
- Dozzle: move to an internal dozzle-net shared only with Caddy, so the
  admin gate is the only way to reach the Docker socket.
- Drop the GraphQL WebSocket transport: the route is POST-only and the
  schema has no subscriptions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 15:15:31 +00:00
adamfandClaude Opus 5.5 223c8ae35a Move Garage and garage-webui to stpcore
Test and deploy / test (push) Successful in 18s
Test and deploy / deploy (push) Successful in 30s
Garage now runs on the stpcore LXC (adamf/stpcore), the shared core
other stacks depend on. caddy, backend and usaco pin the name `garage`
to it with GARAGE_UPSTREAM; /garage/ goes to stpcore's Caddy with
X-Core-Token. The disk fallback for /uploads/ is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 14:32:33 +00:00
30 changed files with 417 additions and 425 deletions
+7 -14
View File
@@ -16,7 +16,7 @@
#
# 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, the S3 key id) are dummies in the exact shape it requires, or that service won't start.
# a service parses (the S3 key id and secret) 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
@@ -42,12 +42,6 @@ GITEA_HOST=git.localhost
GITEA_PORT=3000
GITEA_UPSTREAM=192.0.2.1
# --- 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
# --- SilverBullet (notes) ---------------------------------------------------
SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public
@@ -124,17 +118,16 @@ 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
# --- Garage object store (public /uploads/, on stpcore) -----------------------
# Uploads fall back to the `uploads` volume unless a dev stpcore is running
# with LAN_BIND=172.17.0.1 and these same dummy values (see stpcore's README).
# Shapes Garage enforces: "GK" + 24 hex for the key id, 64 hex for the secret.
GARAGE_UPSTREAM=host-gateway
GARAGE_WEBUI_TOKEN=dev-garage-webui-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
STPPRIV_LAN_IP=192.0.2.1
+24 -35
View File
@@ -60,15 +60,6 @@ GITEA_HOST=git.adam-french.co.uk
GITEA_PORT=3000
GITEA_UPSTREAM=
# --- Gitea Actions runner ----------------------------------------------------
# The runner is NOT a container; it runs on stpvm via gitea-runner/run.sh.
# The registration token is SINGLE-USE: it is exchanged for a permanent
# identity in gitea-runner/.runner on first registration, after which this
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
GITEA_RUNNER_HOST=
GITEA_RUNNER_NAME=pi-runner
GITEA_RUNNER_REGISTRATION_TOKEN=
# --- SilverBullet (notes) ---------------------------------------------------
# The public read-only notes site at /notes/. The editor, and the vault's only
# writer, is stppriv (priv.DOMAIN/sb/); silverbullet-git here only pulls.
@@ -197,13 +188,12 @@ USACO_CLAUDE_MONTHLY_BUDGET=
# 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"
# Optional: keep the recordings for playback in a PRIVATE Garage bucket
# (`usaco-audio` on stpcore), never `uploads` (that one is served publicly at
# /uploads/). Its own key, same shapes as S3_ACCESS_KEY_ID /
# S3_SECRET_ACCESS_KEY below. With the key blank the recordings are thrown
# away once transcribed. Put the same pair in stpcore's .env and run its
# garage/bootstrap.sh, which creates the bucket and imports the key.
USACO_S3_ACCESS_KEY_ID=
USACO_S3_SECRET_ACCESS_KEY=
@@ -242,30 +232,29 @@ STPPRIV_LAN_IP=
# 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 object store (public /uploads/, on stpcore) -----------------------
# Garage runs on the stpcore LXC (adamf/stpcore); its README is the runbook
# and its .env holds Garage's own secrets. Everything here is optional for
# the site to run: with S3_ENDPOINT blank, or stpcore down, the backend
# writes uploads to the `uploads` volume and Caddy serves them from there.
#
# 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:
# stpcore's LAN IP: the name `garage` is pinned to it in caddy, backend and
# usaco. `host-gateway` in dev. Blank means 127.0.0.1, which fails fast.
GARAGE_UPSTREAM=
# Shared secret Caddy adds as X-Core-Token on /garage/, after the admin
# gate; the same value as GARAGE_WEBUI_TOKEN in stpcore's .env.
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`.
GARAGE_WEBUI_TOKEN=
# The backend's S3 key, the same values as in stpcore's .env (whose
# bootstrap.sh imports it). 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 Caddy serves the file from there.
# Blank keeps uploads on disk. http://garage:3900 stores 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.
S3_ENDPOINT=
# Optional; these defaults match garage.toml and bootstrap.sh.
# Optional; these defaults match stpcore's 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=
+17 -6
View File
@@ -1,4 +1,6 @@
# `test` runs on every push; `deploy` runs for main only after it passes.
# `test` runs on every push, on the build VM (stpbuild, label `build`);
# `deploy` runs for main only after it passes, on stpvm (`self-hosted`),
# since it recreates the stack there.
# The runner is in host mode with only git and docker on the host, so Go and
# Python run in containers pinned to the same images as their Dockerfiles
# (bump together), and checkout is plain git rather than actions/checkout.
@@ -11,16 +13,20 @@ on:
jobs:
test:
runs-on: self-hosted
runs-on: build
env:
# Via env so a branch name is never parsed as shell.
SHA: ${{ github.sha }}
REF: ${{ github.ref }}
REMOTE: ssh://[email protected]:2222/adamf/stpweb.git
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
# Over HTTP with the job's own token (read access to this repo while
# the job runs), so the runner needs no SSH key or Gitea user.
REMOTE: http://git.adam-french.co.uk:3000/adamf/stpweb.git
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
# Kept between runs so fetches are incremental.
CACHE: /home/adamf/.cache/stpweb-ci/repo.git
SRC: /home/adamf/.cache/stpweb-ci/src-${{ github.sha }}
# Per run, not just per commit: the build runner takes two jobs at
# once, and the same commit pushed to two branches runs twice.
SRC: /home/adamf/.cache/stpweb-ci/src-${{ github.sha }}-${{ github.run_id }}
steps:
- name: Export the pushed commit to a scratch directory
shell: bash
@@ -30,7 +36,12 @@ jobs:
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
# $SHA, not FETCH_HEAD: test this run's commit even if the
# branch has moved on.
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
# The job's token as a Basic auth header, passed via env rather
# than -c so it never shows in the process list.
auth=$(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)
GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader \
GIT_CONFIG_VALUE_0="Authorization: Basic $auth" \
git --git-dir="$CACHE" fetch --quiet --no-tags "$REMOTE" "$REF"
rm -rf "$SRC"
mkdir -p "$SRC"
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
+4 -3
View File
@@ -1,4 +1,5 @@
# Weekly Renovate run (config in /renovate.json5). --network host uses the
# Weekly Renovate run (config in /renovate.json5), on the build VM (stpbuild,
# label `build`). --network host uses the
# host's /etc/hosts pin to reach Gitea on the LAN, and RENOVATE_GIT_URL=endpoint
# stops it cloning via the public ROOT_URL. Secrets are passed as bare `-e NAME`
# so they never appear in the process list. Gitea refuses secret names starting
@@ -13,7 +14,7 @@ on:
jobs:
renovate:
runs-on: self-hosted
runs-on: build
steps:
- name: Run Renovate
shell: bash
@@ -30,7 +31,7 @@ jobs:
-e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://git.adam-french.co.uk:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv \
-e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore,adamf/stprunner \
-e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \
+6 -1
View File
@@ -20,9 +20,14 @@ usaco-data/
.deprecated/gitea/config/
.deprecated/gitea/dev-leftovers/
# Gitea runner
# The old runner directory: gone from git, but still on stpvm holding the
# previous .runner credentials (runners are installed from adamf/stprunner)
gitea-runner/.runner
gitea-runner/act_runner
gitea-runner/gitea-runner
gitea-runner/.runner.lock
# Old registrations: credentials, like .runner
gitea-runner/.runner.bak*
gitea-runner/nohup.out
# Python bytecode
+4 -4
View File
@@ -19,7 +19,7 @@ cp .env.dev .env
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
```
`.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 serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. 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 serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. Visit `http://localhost`. Uploads stay on disk unless a dev stpcore is also running (from that repo, with `LAN_BIND=172.17.0.1` and the same dummy keys as `.env.dev`), which `GARAGE_UPSTREAM=host-gateway` reaches.
### Full stack (production, HTTPS)
@@ -63,9 +63,9 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
**Job tracker and notes editor** (on stppriv): the job tracker (`adamf/job-tracker`) and the SilverBullet editor run on their own LXC, from the `adamf/stppriv` repo, at `priv.<DOMAIN>`. stppriv's Caddy gates them with this site's admin session (the cookie is set for the parent domain), asking `/api/auth/validate-admin` over the LAN; requests from `STPPRIV_LAN_IP` to that path skip the api rate limit. Caddy here 301s `/sb/`, `/jobs/` and the old `/cv/jobs`, `/cv/leads` and userscript URLs there. stppriv is the notes vault's only writer; `silverbullet-git` here runs with `SYNC_MODE=pull` and feeds `/notes/`.
**Gitea** (own repo, `adamf/stpgit`): git, Actions and the image registry (`<DOMAIN>/adamf/...`) run in their own Proxmox LXC since 2026-11-24, from the `adamf/stpgit` repo (this repo's `gitea/` directory until then) with their own Postgres (`gitea-db`) and `.env`, deployed by hand there and never by CI. Everything on stpvm reaches it as `GITEA_HOST` (`git.<DOMAIN>`, :3000 HTTP and :2222 SSH), pinned to the LXC's LAN IP (`GITEA_UPSTREAM`) by `extra_hosts` in containers and `/etc/hosts` on the host; public DNS for that name is Cloudflare, which carries only HTTPS. There is no Gitea container or forwarder in this stack since 2026-11-24. The act_runner stays on stpvm. Runbook: that repo's README, summarised in "Gitea LXC" in `DEPLOYMENT.md` §7.
**Gitea** (own repo, `adamf/stpgit`): git, Actions and the image registry (`<DOMAIN>/adamf/...`) run in their own Proxmox LXC since 2026-11-24, from the `adamf/stpgit` repo (this repo's `gitea/` directory until then) with their own Postgres (`gitea-db`) and `.env`, deployed by hand there and never by CI. Everything on stpvm reaches it as `GITEA_HOST` (`git.<DOMAIN>`, :3000 HTTP and :2222 SSH), pinned to the LXC's LAN IP (`GITEA_UPSTREAM`) by `extra_hosts` in containers and `/etc/hosts` on the host; public DNS for that name is Cloudflare, which carries only HTTPS. There is no Gitea container or forwarder in this stack since 2026-11-24. stpvm keeps a gitea-runner (registered as `stpvm`, label `self-hosted`) for the jobs that touch the stack (deploys, maintenance); tests, image builds and Renovate run on the build VM `stpbuild` (Proxmox VM 123, 192.168.178.240, runner `stpbuild-runner`, label `build`) since 2026-11-26, which fetches over HTTP with each job's own `GITEA_TOKEN`. Both runners are installed from the `adamf/stprunner` repo (systemd, `hosts/<host>.env` per VM). See "Build VM" in `DEPLOYMENT.md` §7. Runbook: that repo's README, summarised in "Gitea LXC" in `DEPLOYMENT.md` §7.
**Uploads / Garage** (`garage/`): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in a self-hosted Garage container (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Caddy serves `/uploads/` from Garage's anonymous website endpoint first and the volume second, so the bucket is the source of truth and a Garage outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `garage-webui` at `/garage/` (admin-gated) manages the bucket. First run on a fresh volume needs `garage/bootstrap.sh`; the full runbook is "Garage" in `DEPLOYMENT.md` §7.
**Uploads / Garage** (Garage itself on stpcore): 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 Garage (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Garage and `garage-webui` are not in this stack: they run on the `stpcore` LXC, from the `adamf/stpcore` repo (the shared core other stacks depend on; its README is the runbook, including `garage/bootstrap.sh`), and the name `garage` is pinned to its LAN IP (`GARAGE_UPSTREAM`) by `extra_hosts` in `caddy`, `backend` and `usaco`. Caddy serves `/uploads/` from Garage's anonymous website endpoint (`garage:3902`) first and the volume second, so the bucket is the source of truth and a Garage or stpcore outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `/garage/` (admin-gated) proxies to stpcore's Caddy on `garage:3909`, adding `X-Core-Token` (`GARAGE_WEBUI_TOKEN`), which that Caddy requires before it forwards to garage-webui. A new consumer of the store gets its own key and bucket on stpcore and the same `extra_hosts` pin. "Garage" in `DEPLOYMENT.md` §7 covers this side.
**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit <zone> <events> <window>`) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. 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. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea is not proxied any more: it lives at `git.<DOMAIN>` (its own tunnel, from the stpgit repo) and `/gitea/*` 301s there; only the registry at the apex's `/v2/` still goes through Caddy. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7.
@@ -95,7 +95,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
## 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. 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).
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (90 days, renewed on every refresh) as HTTP-only cookies (`backend/main.go`). `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. The admin flag is read from the user row on every request (`AuthenticateTokenWithClaims` overwrites the claim), so a demotion applies at once. `services.RequireSameOrigin` refuses any non-GET request whose `Origin` is not the apex or www, since SameSite=Lax lets sibling subdomains (radar., git.) send the cookies. 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. Caddy's *permission gate* (`import permission_gate <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) 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 route from `import admin_gate` to `import permission_gate <key>`. `/auth/validate-admin` and the admin gate are unchanged.
+68 -48
View File
@@ -76,6 +76,26 @@ forwarder here published 3000/2222 and everything used `localhost`.)
A new machine or container that talks to Gitea needs the same pin, or a
`~/.ssh/config` entry pointing the name at the tailnet name `stpgit` for SSH.
### Garage runs on stpcore
Garage (the S3 object store behind `/uploads/`) and garage-webui are not in
this stack either. They run on the `stpcore` LXC, from `adamf/stpcore`, the
shared core every other stack depends on; its README is the runbook. The name
`garage` is pinned to that LXC's LAN IP (`GARAGE_UPSTREAM`) by `extra_hosts`
in `caddy`, `backend` and `usaco`, so the configs still say `garage:3900`
(S3), `garage:3902` (website) and `garage:3909` (stpcore's Caddy in front of
garage-webui, which wants the `X-Core-Token` this Caddy adds after the admin
gate). Nothing here depends on it being up: see "Garage" in §7.
```
stpvm (pin: garage -> stpcore LAN IP) stpcore LXC (LAN IP)
backend S3 PUT (uploads) ------+ +----------------------+
usaco S3 (usaco-audio) ------+--> garage:3900 ---> | garage :3900 S3 |
caddy /uploads/ -----------------> garage:3902 --> | :3902 web |
caddy /garage/ (+X-Core-Token) --> garage:3909 --> | caddy -> garage-webui|
+----------------------+
```
Gitea's public address is `https://git.<DOMAIN>/` (its `ROOT_URL`), served by
the LXC's own Cloudflare tunnel, not by this edge; Caddy only 301s the old
`/gitea/*` URLs there and still proxies the registry at the apex's `/v2/`.
@@ -96,13 +116,13 @@ Deploys of this stack never touch Gitea.
| icecast2 + liquidsoap | `${ICECAST_HOST}` | `${ICECAST_PORT}` | `/radio/` | **harbor port only** |
| vue | `vue` | 5173 (dev only) | `/` (dev only) | no |
| cloudflared | `cloudflared` | — (fixed IP `172.28.255.250`) | all of Caddy, via Cloudflare | no (outbound only) |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by Caddy `forward_auth`; reads the Docker socket) | no |
| dozzle (log viewer) | `dozzle` | 8080 | `/dozzle/` (admin-gated by Caddy `forward_auth`; reads the Docker socket; on `dozzle-net`, shared only with Caddy) | 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 Caddy `forward_auth`; Caddy adds `X-Receipt-Token` and `X-Remote-User`). The only upstream off this host; 503 "offline" when stppi is down | no |
| Partner Radar (adamf/cto, its own compose project) | `radar-web` (alias of that project's `web`, on app-network) | 80 | `radar.<DOMAIN>`, the whole host (its own login, no gate; zones `radar` and `radar_login`). Started from the cto checkout with `make stpvm`; 503 "offline" when that stack is down | no |
| traffic (tails the payload log) | `traffic` | — (no network) | none; its stdout is what Dozzle shows | no |
| autoheal (restarts unhealthy caddy) | `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 Caddy `forward_auth`) | no |
| garage (S3 object store, adamf/stpcore) | — (runs on the **stpcore** LXC; `garage` pinned to `GARAGE_UPSTREAM`) | 3900 S3, 3902 web | `/uploads/` from its website endpoint first, then the `uploads` volume; backend and usaco use S3 | no |
| garage-webui (Garage admin UI, adamf/stpcore) | — (on **stpcore**, behind its Caddy) | 3909 on stpcore | `/garage/` (admin-gated by Caddy `forward_auth`; Caddy adds `X-Core-Token`). 503 "offline" when stpcore is down | no |
Container names come from `.env`, and Caddy builds its upstreams from the same
variables (passed through the caddy service's `environment:` list). **Renaming
@@ -407,8 +427,6 @@ Setup, once:
| ---------- | ----------------------------------------------------- | -------------------------------------------------- |
| `dbdata` | Postgres: the app database and the trackers' databases | All posts, users and messages, and the trackers' data |
| `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 |
| `caddy_config` | Caddy's autosaved JSON config | Nothing — rewritten on every start |
@@ -621,43 +639,35 @@ The app schema is recreated by GORM auto-migration on backend start (there are n
migration files). The job and activity trackers' databases are not
auto-created; their READMEs have the commands.
**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:
**Garage (the `/uploads/` bucket).** Public uploads live in a Garage bucket
on the stpcore LXC (`adamf/stpcore`, whose README is the runbook: setup,
keys, the move from this host, backups), with the `uploads` volume here as a
safety net. Nothing breaks while stpcore 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;
disk (with a log line) whenever Garage refuses a write or can't be reached;
- Caddy serves `/uploads/` from Garage and falls back to the volume when
Garage has no such file or is unreachable, and it starts without the
`garage` container.
Garage has no such file or is unreachable (2s connect timeout);
- `/garage/` answers 503 "offline".
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.
Pointing this stack at it: set `GARAGE_UPSTREAM` (stpcore's LAN IP),
`GARAGE_WEBUI_TOKEN` (same as stpcore's), `S3_ACCESS_KEY_ID` /
`S3_SECRET_ACCESS_KEY` (same as stpcore's, imported by its
`garage/bootstrap.sh`) and `S3_ENDPOINT=http://garage:3900`, then
`docker compose up -d caddy backend usaco`. The backend logs
`[upload] storing uploads in bucket uploads ...` on start.
Moving the old files in (so they show in garage-webui, and so the bucket
holds everything):
```
export $(grep -E '^S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=' .env)
docker run --rm --network web_server_app-network \
export $(grep -E '^(S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY|GARAGE_UPSTREAM)=' .env)
docker run --rm \
-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
--endpoint-url "http://$GARAGE_UPSTREAM:3900"
```
The copies left on the volume are then only a fallback for when Garage is
@@ -666,19 +676,14 @@ 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;
written to the bucket in the meantime stay reachable as long as stpcore 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 2 GB by Caddy.
**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`.
capped at 2 GB by Caddy, here and on stpcore.
**Gitea LXC.** Gitea runs in its own Proxmox LXC (§1), from a checkout of its
own repo, `adamf/stpgit` (until 2026-11-24 this repo's `gitea/` directory),
@@ -718,19 +723,34 @@ nothing, so pull and `up -d` there afterwards.
`docker compose -f docker-compose.yml -f .deprecated/gitea/docker-compose.gitea.yml up -d gitea`.
`.deprecated/README.md` has the details.
**Set up the CI runner on a fresh host:**
**Build VM (stpbuild).** Since 2026-11-26 CI is split over two runners.
stpvm's (`stpvm`, label `self-hosted`) keeps only the jobs that
touch this stack: `deploy` in this repo's deploy.yaml and in usaco's and
activity-tracker's ci.yaml, and maintenance.yaml. Everything that only needs
git and docker (tests, image builds and pushes, Renovate) runs on
`stpbuild-runner` (label `build`, instance-wide, capacity 2), on the Proxmox
VM `stpbuild` (VMID 123, `192.168.178.240`, Ubuntu 24.04, 4 cores, 2 GB + 4 GB
swapfile). Its `/etc/hosts` pins `git.<DOMAIN>` to stpgit's LAN IP and the apex to
stpvm's (registry pushes go to this Caddy over the LAN, not Cloudflare). It
has no SSH key: build jobs fetch from `http://git.<DOMAIN>:3000/` with the
job's own `secrets.GITEA_TOKEN`, so a new repo needs no Gitea setup, only
`runs-on: build`. A `publish` job reuses its `test` job's git cache, so both
must stay on `build`. stpweb's own images are still built here by
`up --build`; moving them is the next step.
```
cd gitea-runner
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_
a fresh token.
**The runners** are installed by the `adamf/stprunner` repo, not from here:
on each VM, `~/deploy/stprunner` and `sudo ./install.sh <host>` run
gitea-runner (formerly act_runner) as the systemd service `gitea-runner`,
with that host's name, labels and capacity in `hosts/<host>.env` there. Its
README covers a fresh VM, upgrades (Renovate bumps the pinned version) and
renames. Both run in host mode as `adamf`, outside Docker on purpose: the
deploy job runs `docker compose up` against this stack, so it cannot be a
container in it. Since 2026-11-27: gitea-runner v6.0.1, which needs Gitea
1.26.2+ (act_runner 0.2.x could not run `node24` actions such as
`actions/checkout@v5`). Until then each VM ran its own copy of this repo's
old `gitea-runner/` scripts from an `@reboot` crontab line, and stpvm's runner
was registered as `stppi` (the Pi it moved from). Those directories are still
on the VMs, unused, with the old `.runner` files.
**Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday
+1 -8
View File
@@ -215,9 +215,6 @@ Create a `.env` file in the project root. All services read from this file.
| `SILVERBULLET_PUBLIC_HOST` | Public notes SilverBullet hostname (defaults to `silverbullet-public`) |
| `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_GIT_INTERVAL` | Seconds between notes pulls (defaults to `300`) |
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
| `GITEA_RUNNER_NAME` | Gitea runner display name |
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
| `BACKEND_PORT` | Backend port (typically `8080`) |
| `BACKEND_HOST` | Backend hostname (use `backend` for Docker) |
| `BACKEND_SECRET` | JWT signing secret |
@@ -281,9 +278,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
### Gitea Runner
1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/`
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
3. The runner registers automatically on first startup
The CI runners (stpvm's and the build VM's) are installed from the `adamf/stprunner` repo, not from here. See its README and "Build VM" in `DEPLOYMENT.md` §7.
## Dev Mode
@@ -332,8 +327,6 @@ These files are git-ignored and must be created manually:
| `caddy/data/` | Created automatically by Caddy (certificates and their keys) |
| `backend/token/` | Created automatically by Docker volume mount |
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file |
| `gitea-runner/act_runner` | Download from Gitea releases |
| `gitea-runner/.runner` | Generated on first runner startup |
## Future Ideas
+12 -9
View File
@@ -55,12 +55,12 @@ graph/ GraphQL layer
- `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary
requests authorise without a database hit;
- `refresh_token` (365 days) carries only `id`.
- `access_token` (7 days) carries `id`, `username`, `admin` and `tv`;
- `refresh_token` (90 days) carries `id` and `tv`.
Every check loads the user row (one SELECT) to compare `tv`, and takes
`admin` from the row, not the token.
- `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
token for a new pair, re-reading the user — and therefore the admin flag —
from the database.
token for a new pair, so the 90 days slide while the account is in use.
- `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.
@@ -74,10 +74,13 @@ graph/ GraphQL layer
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
Caddy 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
their next refresh, not immediately.
- Revocation is by `User.TokenVersion`: logout and a password change bump it,
which invalidates every token already issued to that user. Demoting an admin
applies on their next request.
- Any request that is not GET/HEAD/OPTIONS must come from the site's own
origin (`services.RequireSameOrigin`). SameSite=Lax alone would let a page on
a sibling subdomain such as radar. or git. post with the cookies. Requests
without `Origin` or `Sec-Fetch-Site` (curl, server-to-server) pass.
The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
`graph/auth.resolvers.go`) are parallel by design, since the front end uses
+12 -12
View File
@@ -4,9 +4,9 @@ go 1.26.0
require (
github.com/99designs/gqlgen v0.17.98
github.com/aws/aws-sdk-go-v2 v1.48.0
github.com/aws/aws-sdk-go-v2/credentials v1.21.0
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
github.com/aws/aws-sdk-go-v2 v1.48.1
github.com/aws/aws-sdk-go-v2/credentials v1.21.4
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.1
github.com/gin-gonic/gin v1.12.0
github.com/golang-jwt/jwt/v5 v5.3.1
github.com/gorilla/websocket v1.5.3
@@ -21,15 +21,15 @@ require (
require (
github.com/agnivade/levenshtein v1.2.2 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
github.com/aws/smithy-go v1.28.9 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.28 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.26 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.14 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.13 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.13 // indirect
github.com/aws/smithy-go v1.28.10 // indirect
github.com/bytedance/gopkg v0.1.3 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.0 // indirect
+24 -24
View File
@@ -39,30 +39,30 @@ github.com/agnivade/levenshtein v1.2.2 h1:fI8RgiztYX1Nn5pBHHqQ9EMCCklhrmXqPRIedF
github.com/agnivade/levenshtein v1.2.2/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
github.com/aws/aws-sdk-go-v2/credentials v1.21.0 h1:OViwhqeipkQzSHuO2eQDUCdLrI6r3nzGxFUyM8GqnCs=
github.com/aws/aws-sdk-go-v2/credentials v1.21.0/go.mod h1:OffaVQod3fyZzhZJyPtw11WpHPF1uIHADc+/MYlXmbA=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/aws-sdk-go-v2 v1.48.1 h1:j6ro6IvbxUe8BCulc/6uWMrhmx6+i5HNIc1GZEJRT9k=
github.com/aws/aws-sdk-go-v2 v1.48.1/go.mod h1:HP8Jzg1FDurJomtx40YM0eiLoJrwjjZ9X+4BNpy4OXc=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.28 h1:/LppjvqoI0KYB6gDrG/b77okSNPrVJI7CJtK5ITYoZ0=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.28/go.mod h1:E7HQl8N3fZeO2DT1X3xSleOe+gG0O2k7nMgrKWDCfHw=
github.com/aws/aws-sdk-go-v2/credentials v1.21.4 h1:FWXJfHDIHV4r5GfgOqvkr+4EddYMT9ZRzIemxwoiPzg=
github.com/aws/aws-sdk-go-v2/credentials v1.21.4/go.mod h1:1+m37dCFDT1N/gqK2/qJcRfDF7j7/MEDZqf2fzr40XU=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13 h1:ZFqKPVQYSIYOXVoG/YRGXYNPqcGslzu/N2J3kev/Djc=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.13/go.mod h1:3guCF5FBy7MYWRVt7+gdRxPPTSIBQnImwEVW5BdnOCE=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13 h1:0pHWAgLjLZWSc9GtdpMVFT7bvpUcm9xZYcaJ9bmyLGo=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.13/go.mod h1:yVcS5ysT0fDsQKA6mqaI5QU1p9q5bj7NyM4bu91yNmU=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13 h1:a6vUTTG7Vsf0LTCuy/GPJsLhz3L6YcS1WkwR5Nxyz8g=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.13/go.mod h1:vlylLTRubgSLfSBOy7blRhV2CC1nVY1VDIgV5nlKi5Y=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.26 h1:PgkTkbD4VhN7KX1fQXiNMsSZqPnEfXmi+UuISMDEuy8=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.26/go.mod h1:s/8QtHBYqNVL+E6bD1yltZrmEo+I4S1bt2kQDxP54sY=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.14 h1:xZolVZk8AKg8m9Axl7IZreaUEOrFmomgaXjWzpiAiWM=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.14/go.mod h1:BbYaE19KUZA0gxBjw3uWWz2v7wMgpxfi1OPLB26Ktw0=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.13 h1:D67JeihKdQFL5Zks8rFmf0V0sOZO+iAOjQUW03O3R2E=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.13/go.mod h1:lyzwhnQkZD/SVyTZAG8TqE2XSLRndMZtysOl9KM3ErA=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.13 h1:MJaFheEZeJDd2qGObzRjsCdDTvRzApb6EqwZ5yBHzwE=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.13/go.mod h1:BH0PWDkM/i0ewpxH5g6tELXxzS933YZ3Q/PTGWc8+9c=
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.1 h1:qFQ1JjNGG8fdKBFNdQ641PXCaPdDulXlIpk3kntgqb0=
github.com/aws/aws-sdk-go-v2/service/s3 v1.116.1/go.mod h1:VRFKxGYoQGYL9sQM49YVbB8TlgRnBkfqURzqesn06jA=
github.com/aws/smithy-go v1.28.10 h1:SfPnj8fGCVAI/P5YC4/1JjuMsucbPp2dROnSTYNo2PE=
github.com/aws/smithy-go v1.28.10/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
+1 -1
View File
@@ -40,7 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true
}
// IsAdminFromCtx reads the token, so a revoked flag applies on expiry.
// IsAdminFromCtx reads the claims, whose admin flag comes from the user row.
func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx)
if claims == nil {
+4 -9
View File
@@ -40,8 +40,8 @@ func (store *Store) AuthMiddleware(ctx *gin.Context) {
ctx.Next()
}
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so
// a revoked flag applies once the access token expires.
// AdminMiddleware must follow AuthMiddleware, whose claims carry the row's
// admin flag.
func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims")
if !exists {
@@ -69,13 +69,8 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
// gate and the jobs container. It falls back to the refresh token and may
// mint new cookies, so a returning admin needn't log in again.
func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
// The refresh path has no admin claim, so it reads the row.
if claims == nil {
return user.Admin
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
return user.Admin
})
}
+4 -3
View File
@@ -61,6 +61,7 @@ func main() {
// Used for both the WebSocket origin check and the cookie domain.
domainName := os.Getenv("DOMAIN")
services.InitWebSocket(db, domainName)
r.Use(services.RequireSameOrigin(domainName))
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
@@ -71,7 +72,8 @@ func main() {
authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
accessTokenLifetime := 7 * 24 * time.Hour
refreshTokenLifetime := 365 * 24 * time.Hour
// Sliding: every refresh, including the gates', mints a new one.
refreshTokenLifetime := 90 * 24 * time.Hour
authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
auth := services.InitAuth(&authConfig)
@@ -96,7 +98,7 @@ func main() {
}
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
// Defaults match garage/garage.toml and garage/bootstrap.sh.
// Defaults match stpcore's garage/garage.toml and garage/bootstrap.sh.
s3Region := os.Getenv("S3_REGION")
if s3Region == "" {
s3Region = "garage"
@@ -154,7 +156,6 @@ func main() {
Resolvers: &graph.Resolver{Store: &store},
Directives: graph.Directives(),
}))
gqlSrv.AddTransport(transport.Websocket{KeepAlivePingInterval: 10 * time.Second})
gqlSrv.AddTransport(transport.Options{})
gqlSrv.AddTransport(transport.POST{})
gqlSrv.AddTransport(transport.MultipartForm{})
+6 -2
View File
@@ -41,8 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config}
}
// GenerateJWT issues an access/refresh pair. Only the access token carries
// admin; refresh re-reads the row, so a revoked admin flag applies then.
// GenerateJWT issues an access/refresh pair. The admin claim is informational:
// AuthenticateTokenWithClaims overwrites it from the user row.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username,
@@ -140,6 +140,10 @@ func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*mo
return nil, nil, ErrTokenRevoked
}
// The row is already loaded, so it decides admin: a demotion applies on
// the next request rather than when the token expires.
(*claims)["admin"] = user.Admin
return &user, claims, nil
}
+44
View File
@@ -0,0 +1,44 @@
package services
import (
"net/http"
"net/url"
"github.com/gin-gonic/gin"
)
// IsSiteOrigin reports whether an Origin header names the site itself (the
// apex or www). In dev DOMAIN is localhost, which covers Vite on any port.
func IsSiteOrigin(origin, domain string) bool {
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return domain != "" && (host == domain || host == "www."+domain)
}
// RequireSameOrigin refuses state-changing requests a browser sent from
// elsewhere. SameSite=Lax does not cover this: radar. and git. are the same
// site, so their pages get the auth cookies. A request with neither header is
// not from a browser and passes.
func RequireSameOrigin(domain string) gin.HandlerFunc {
return func(c *gin.Context) {
switch c.Request.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
c.Next()
return
}
allowed := true
if origin := c.GetHeader("Origin"); origin != "" {
allowed = IsSiteOrigin(origin, domain)
} else if site := c.GetHeader("Sec-Fetch-Site"); site != "" {
allowed = site == "same-origin" || site == "none"
}
if !allowed {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "cross-origin request refused"})
return
}
c.Next()
}
}
+67
View File
@@ -0,0 +1,67 @@
package services
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestIsSiteOrigin(t *testing.T) {
cases := []struct {
origin, domain string
want bool
}{
{"https://www.example.com", "example.com", true},
{"https://example.com", "example.com", true},
{"https://radar.example.com", "example.com", false},
{"https://git.example.com", "example.com", false},
{"https://www.example.com.evil.test", "example.com", false},
{"https://evilexample.com", "example.com", false},
{"null", "example.com", false},
{"http://localhost:5173", "localhost", true},
{"http://localhost:5173", "example.com", false},
{"https://anything", "", false},
}
for _, c := range cases {
if got := IsSiteOrigin(c.origin, c.domain); got != c.want {
t.Errorf("IsSiteOrigin(%q, %q) = %v, want %v", c.origin, c.domain, got, c.want)
}
}
}
func TestRequireSameOrigin(t *testing.T) {
gin.SetMode(gin.TestMode)
cases := []struct {
name string
method string
headers map[string]string
want int
}{
{"GET is never checked", "GET", map[string]string{"Origin": "https://evil.test"}, 200},
{"POST from www", "POST", map[string]string{"Origin": "https://www.example.com"}, 200},
{"POST from a sibling subdomain", "POST", map[string]string{"Origin": "https://radar.example.com"}, 403},
{"POST from another site", "POST", map[string]string{"Origin": "https://evil.test"}, 403},
{"POST with an opaque origin", "POST", map[string]string{"Origin": "null"}, 403},
{"DELETE from another site", "DELETE", map[string]string{"Origin": "https://evil.test"}, 403},
{"no Origin, same-site fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-site"}, 403},
{"no Origin, same-origin fetch", "POST", map[string]string{"Sec-Fetch-Site": "same-origin"}, 200},
{"no browser headers (curl, server to server)", "POST", nil, 200},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := gin.New()
r.Use(RequireSameOrigin("example.com"))
r.Handle(c.method, "/x", func(ctx *gin.Context) { ctx.Status(200) })
req := httptest.NewRequest(c.method, "/x", nil)
for k, v := range c.headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
r.ServeHTTP(rec, req)
if rec.Code != c.want {
t.Fatalf("status %d, want %d", rec.Code, c.want)
}
})
}
}
+20 -5
View File
@@ -9,11 +9,11 @@ import (
// RateLimiter is an in-memory sliding window per key, behind Caddy's limits.
type RateLimiter struct {
mu sync.Mutex
// Never evicted; grows with distinct client IPs.
attempts map[string][]time.Time
max int
window time.Duration
mu sync.Mutex
attempts map[string][]time.Time
max int
window time.Duration
lastSweep time.Time
}
func NewRateLimiter(max int, window time.Duration) *RateLimiter {
@@ -31,6 +31,7 @@ func (rl *RateLimiter) Allow(key string) bool {
now := time.Now()
cutoff := now.Add(-rl.window)
rl.sweep(now, cutoff)
// Filtered in place, reusing the backing array.
valid := rl.attempts[key][:0]
@@ -48,3 +49,17 @@ func (rl *RateLimiter) Allow(key string) bool {
rl.attempts[key] = append(valid, now)
return true
}
// sweep drops keys with no attempt inside the window, at most once a window,
// so keys that are never seen again don't accumulate.
func (rl *RateLimiter) sweep(now, cutoff time.Time) {
if now.Sub(rl.lastSweep) < rl.window {
return
}
rl.lastSweep = now
for key, times := range rl.attempts {
if len(times) == 0 || !times[len(times)-1].After(cutoff) {
delete(rl.attempts, key)
}
}
}
+10
View File
@@ -58,6 +58,16 @@ func TestRateLimiterAllow(t *testing.T) {
}
})
t.Run("keys idle past the window are evicted", func(t *testing.T) {
rl := NewRateLimiter(1, 5*time.Millisecond)
rl.Allow("gone")
time.Sleep(10 * time.Millisecond)
rl.Allow("other")
if _, ok := rl.attempts["gone"]; ok {
t.Fatal("idle key still stored, want evicted")
}
})
t.Run("max of zero denies everything", func(t *testing.T) {
rl := NewRateLimiter(0, time.Minute)
if rl.Allow("ip") {
+40 -17
View File
@@ -1,8 +1,8 @@
package services
import (
"log"
"net/http"
"net/url"
"sync"
"time"
@@ -27,15 +27,7 @@ var Upgrader = websocket.Upgrader{
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin")
if origin == "" {
return false
}
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
return origin != "" && IsSiteOrigin(origin, allowedDomain)
},
}
@@ -54,6 +46,24 @@ const (
rateLimitMaxMsgs = 10
)
// The route is public, so frame and field sizes are capped. Writes happen
// under mu, so a stalled client may hold it for at most writeWait.
// ChatPanel's maxlength of 1000 UTF-16 units is at most 3000 bytes, under
// maxContentBytes; over-limit messages are dropped silently.
const (
maxFrameBytes = 16 << 10
maxContentBytes = 4000
maxFileURLBytes = 512
writeWait = 5 * time.Second
)
func writeJSON(conn *websocket.Conn, v any) error {
if err := conn.SetWriteDeadline(time.Now().Add(writeWait)); err != nil {
return err
}
return conn.WriteJSON(v)
}
type wsIncoming struct {
Action string `json:"action,omitempty"`
ID uint `json:"id,omitempty"`
@@ -81,6 +91,7 @@ func InitWebSocket(database *gorm.DB, domain string) {
// isAdmin allows seeing, sending and deleting private messages.
func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
defer conn.Close()
conn.SetReadLimit(maxFrameBytes)
// Register and snapshot under one lock, so a concurrent broadcast is
// either in the history or delivered after it, never lost or reordered.
@@ -94,9 +105,11 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
if !isAdmin {
historyQuery = historyQuery.Where("private = ?", false)
}
historyQuery.Find(&history)
if err := historyQuery.Find(&history).Error; err != nil {
log.Printf("[ws] loading history: %v", err)
}
if err := conn.WriteJSON(wsHistoryEvent{Action: "history", Messages: history}); err != nil {
if err := writeJSON(conn, wsHistoryEvent{Action: "history", Messages: history}); err != nil {
delete(clients, conn)
mu.Unlock()
return
@@ -130,6 +143,10 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
continue
}
if len(incoming.Text) > maxContentBytes || len(incoming.FileURL) > maxFileURLBytes {
continue
}
msg := models.Message{
Content: incoming.Text,
FileURL: incoming.FileURL,
@@ -138,17 +155,23 @@ func HandleWebSocket(conn *websocket.Conn, isAdmin bool) {
}
mu.Lock()
wsDB.Create(&msg)
if err := wsDB.Create(&msg).Error; err != nil {
mu.Unlock()
log.Printf("[ws] saving message: %v", err)
continue
}
// Soft delete, so the table still grows; the chat does not.
wsDB.Where("id NOT IN (?)",
if err := wsDB.Where("id NOT IN (?)",
wsDB.Model(&models.Message{}).Select("id").Order("created_at DESC").Limit(maxMessages),
).Delete(&models.Message{})
).Delete(&models.Message{}).Error; err != nil {
log.Printf("[ws] pruning messages: %v", err)
}
for client, clientAdmin := range clients {
if msg.Private && !clientAdmin {
continue
}
if err := client.WriteJSON(msg); err != nil {
if err := writeJSON(client, msg); err != nil {
client.Close()
delete(clients, client)
}
@@ -173,7 +196,7 @@ func deleteMessage(id uint) {
event := wsDeleteEvent{Action: "delete", ID: id}
for client := range clients {
if err := client.WriteJSON(event); err != nil {
if err := writeJSON(client, event); err != nil {
client.Close()
delete(clients, client)
}
+4
View File
@@ -159,6 +159,10 @@
handle @radar_offline {
respond "Partner Radar is offline." 503
}
@garage_offline vars garage_upstream yes
handle @garage_offline {
respond "The Garage admin UI (stpcore) is offline." 503
}
}
}
+19 -10
View File
@@ -124,14 +124,23 @@ handle /dozzle/* {
}
}
# Holds Garage's admin token. 2 GB for video uploads.
# garage-webui on stpcore, behind its Caddy, which wants X-Core-Token (header_up
# replaces any client-sent one). Holds Garage's admin token. 2 GB for video
# uploads. A `route` so garage_upstream is set only after the gate passes.
handle /garage/* {
import admin_gate
request_body {
max_size 2GB
}
reverse_proxy garage-webui:3909 {
import proxy
route {
import admin_gate
request_body {
max_size 2GB
}
vars garage_upstream yes
reverse_proxy garage:3909 {
import proxy
header_up X-Core-Token {env.GARAGE_WEBUI_TOKEN}
transport http {
dial_timeout 3s
}
}
}
}
@@ -144,7 +153,7 @@ handle /radio/admin/* {
}
}
# The notes editor is on stppriv, behind Cloudflare Access.
# The notes editor is on stppriv, behind its admin gate.
handle /sb/* {
redir https://priv.{$DOMAIN}{uri} 301
}
@@ -269,8 +278,8 @@ handle /uploads/private/* {
file_server
}
# Garage first, disk second: a 404, 5xx or dial error falls back to the
# volume, so the bucket is the source of truth.
# Garage (on stpcore) first, disk second: a 404, 5xx or dial error falls back
# to the volume, so the bucket is the source of truth.
handle /uploads/* {
import upload_headers
vars uploads_fallback yes
+13 -50
View File
@@ -17,18 +17,19 @@ networks:
usaco-runner-net:
driver: bridge
internal: true
# internal, and shared only with caddy: the admin gate is the only way in,
# since dozzle holds the Docker socket.
dozzle-net:
driver: bridge
internal: true
# Named volumes survive `down`; only `down -v` deletes them.
volumes:
# Deleting this wipes posts, users and messages.
dbdata:
# Private attachments, plus any upload Garage refused. Caddy serves
# /uploads/ from the bucket first, then from here.
# /uploads/ from the bucket (on stpcore) first, then from here.
uploads:
# Back up meta and data together: the bytes are unreadable without meta.
# A fresh pair needs garage/bootstrap.sh.
garage_meta:
garage_data:
# Written by the one-shot `vue` build container, served by Caddy.
vue_dist:
# Named only so the image's VOLUME doesn't leave anonymous volumes behind.
@@ -73,12 +74,15 @@ services:
- RECEIPT_WEB_UPSTREAM=${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}
- STPPRIV_LAN_IP=${STPPRIV_LAN_IP:-192.0.2.1}
- RECEIPT_WEB_TOKEN=${RECEIPT_WEB_TOKEN:-}
- GARAGE_WEBUI_TOKEN=${GARAGE_WEBUI_TOKEN:-}
# The adamf/cto stack's web container; "offline" while that stack is down.
- RADAR_UPSTREAM=${RADAR_UPSTREAM:-radar-web:80}
- CLOUDFLARE_DNS_API_TOKEN=${CLOUDFLARE_DNS_API_TOKEN:-}
# Keeps the Gitea hop on the LAN; public DNS points at Cloudflare.
# `garage` is on stpcore; the 127.0.0.1 default fails fast to disk.
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks:
app-network:
# So cloudflared's origin (https://www.DOMAIN) lands here under a name
@@ -89,6 +93,7 @@ services:
- radar.${DOMAIN}
# Matches cloudflared's extra_hosts.
ipv4_address: 172.28.255.251
dozzle-net:
ports:
- 80:80
- 443:443
@@ -141,6 +146,7 @@ services:
condition: service_healthy
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks:
- app-network
env_file:
@@ -286,6 +292,7 @@ services:
- usaco-runner
extra_hosts:
- "${GITEA_HOST}:${GITEA_UPSTREAM}"
- "garage:${GARAGE_UPSTREAM:-127.0.0.1}"
networks:
- app-network
- usaco-runner-net
@@ -359,7 +366,7 @@ services:
container_name: dozzle
restart: always
networks:
- app-network
- dozzle-net
environment:
- DOZZLE_BASE=/dozzle
- DOZZLE_NO_ANALYTICS=true
@@ -378,47 +385,3 @@ services:
- AUTOHEAL_CONTAINER_LABEL=autoheal
volumes:
- /var/run/docker.sock:/var/run/docker.sock
# Public uploads bucket. Nothing depends on it: Caddy and the backend fall
# back to the `uploads` volume. First run: garage/bootstrap.sh.
garage:
image: dxflrs/garage:v2.5.0
container_name: garage
restart: always
networks:
- app-network
environment:
- GARAGE_RPC_SECRET=${GARAGE_RPC_SECRET}
- GARAGE_ADMIN_TOKEN=${GARAGE_ADMIN_TOKEN}
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
- garage_meta:/var/lib/garage/meta
- garage_data:/var/lib/garage/data
healthcheck:
test: ["CMD", "/garage", "status"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
# Admin-gated at /garage/; holds the admin token, so never publish it.
# Files uploaded here are public at /uploads/ with no backend checks.
garage-webui:
image: khairul169/garage-webui:1.1.0
container_name: garage-webui
restart: always
depends_on:
- garage
networks:
- app-network
environment:
- BASE_PATH=/garage
- API_BASE_URL=http://garage:3903
- API_ADMIN_KEY=${GARAGE_ADMIN_TOKEN}
- S3_ENDPOINT_URL=http://garage:3900
- S3_REGION=garage
# No /tmp in the image; large multipart uploads spool there.
tmpfs:
- /tmp
volumes:
- ./garage/garage.toml:/etc/garage.toml:ro
-72
View File
@@ -1,72 +0,0 @@
#!/bin/sh
# One-time, idempotent setup of a fresh garage_meta volume, run on the host
# (the image has no shell): node layout, bucket, the backend's key imported
# from .env (so a wiped volume keeps the same credentials), and website access.
# Optional: S3_BUCKET, GARAGE_CAPACITY, COMPOSE (to add the dev override).
set -eu
COMPOSE=${COMPOSE:-docker compose}
# .env isn't guaranteed to be valid shell, so it isn't sourced.
envval() {
eval "current=\${$1:-}"
if [ -n "$current" ]; then
printf '%s' "$current"
return
fi
[ -f .env ] || return 0
grep -E "^$1=" .env | tail -n 1 | cut -d= -f2- | sed -e 's/^"\(.*\)"$/\1/' -e "s/^'\(.*\)'$/\1/"
}
garage() {
$COMPOSE exec -T garage /garage "$@"
}
KEY_ID=$(envval S3_ACCESS_KEY_ID)
SECRET=$(envval S3_SECRET_ACCESS_KEY)
BUCKET=$(envval S3_BUCKET)
BUCKET=${BUCKET:-uploads}
CAPACITY=$(envval GARAGE_CAPACITY)
CAPACITY=${CAPACITY:-20G}
KEY_NAME=site-backend
# Garage rejects other shapes at import time with a less helpful message.
if ! printf '%s' "$KEY_ID" | grep -Eq '^GK[0-9a-f]{24}$'; then
echo "S3_ACCESS_KEY_ID must be GK followed by 24 hex chars (try: echo GK\$(openssl rand -hex 12))" >&2
exit 1
fi
if ! printf '%s' "$SECRET" | grep -Eq '^[0-9a-f]{64}$'; then
echo "S3_SECRET_ACCESS_KEY must be 64 hex chars (try: openssl rand -hex 32)" >&2
exit 1
fi
# 1. Layout. `node id -q` prints "<full id>@<addr>"; the id is what
# `layout assign` takes.
if garage layout show 2>/dev/null | grep -q "No nodes currently have a role"; then
NODE_ID=$(garage node id -q 2>/dev/null | cut -d@ -f1)
echo "Assigning node $(printf '%s' "$NODE_ID" | cut -c1-16) (capacity $CAPACITY)"
garage layout assign -z dc1 -c "$CAPACITY" "$NODE_ID"
garage layout apply --version 1
else
echo "Layout already applied"
fi
# 2. Bucket.
if garage bucket info "$BUCKET" >/dev/null 2>&1; then
echo "Bucket $BUCKET exists"
else
garage bucket create "$BUCKET"
fi
# 3. Key.
if garage key info "$KEY_ID" >/dev/null 2>&1; then
echo "Key $KEY_ID exists"
else
garage key import -n "$KEY_NAME" --yes "$KEY_ID" "$SECRET"
fi
# 4 and 5 are idempotent in Garage itself.
garage bucket allow --read --write "$BUCKET" --key "$KEY_ID"
garage bucket website --allow "$BUCKET"
echo "Garage ready: bucket $BUCKET, key $KEY_ID"
-29
View File
@@ -1,29 +0,0 @@
# Single node, replication_factor 1: back the volumes up like any other.
# No secrets here; they come from GARAGE_RPC_SECRET / GARAGE_ADMIN_TOKEN.
# 0.0.0.0 because bridge networks may lack IPv6. Ports: 3900 S3, 3901 RPC,
# 3902 website (bucket chosen by Host "<bucket><root_domain>"), 3903 admin.
metadata_dir = "/var/lib/garage/meta"
data_dir = "/var/lib/garage/data"
db_engine = "lmdb"
# LMDB can be left unreadable by a crash mid-write; a periodic snapshot of
# the metadata is what `garage meta` restores from.
metadata_auto_snapshot_interval = "6h"
replication_factor = 1
rpc_bind_addr = "0.0.0.0:3901"
rpc_public_addr = "127.0.0.1:3901"
[s3_api]
api_bind_addr = "0.0.0.0:3900"
# Any string works; it only has to match what clients sign with (S3_REGION).
s3_region = "garage"
root_domain = ".s3.garage"
[s3_web]
bind_addr = "0.0.0.0:3902"
root_domain = ".web.garage"
index = "index.html"
[admin]
api_bind_addr = "0.0.0.0:3903"
-27
View File
@@ -1,27 +0,0 @@
#!/usr/bin/env bash
# Fetches the pinned act_runner for this CPU. The runner lives outside docker
# because its deploy job recreates the stack. To upgrade: bump VERSION, delete
# ./act_runner, re-run.
set -euo pipefail
VERSION="0.2.11"
BASE_URL="https://gitea.com/gitea/act_runner/releases/download/v${VERSION}"
ARCH=$(uname -m)
case "$ARCH" in
x86_64) ASSET="act_runner-${VERSION}-linux-amd64" ;;
aarch64) ASSET="act_runner-${VERSION}-linux-arm64" ;;
armv7l) ASSET="act_runner-${VERSION}-linux-armv7" ;;
*)
echo "Unsupported architecture: $ARCH" >&2
exit 1
;;
esac
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEST="${SCRIPT_DIR}/act_runner"
echo "Downloading act_runner v${VERSION} for ${ARCH}..."
curl -fSL "${BASE_URL}/${ASSET}" -o "$DEST"
chmod +x "$DEST"
echo "Downloaded to $DEST"
-31
View File
@@ -1,31 +0,0 @@
#!/usr/bin/env bash
# Registers (once) and runs the act_runner. Run from this directory.
# Waits for Gitea because registering against a down Gitea fails for good.
# GITEA_RUNNER_REGISTRATION_TOKEN is single-use: .runner is the real
# credential, so to re-register delete .runner and mint a fresh token.
# --labels must match `runs-on:` in .gitea/workflows/.
if [ ! -f ./act_runner ]; then
echo "act_runner binary not found. Downloading..." >&2
bash "$(dirname "$0")/download.sh"
fi
echo "Waiting for git.adam-french.co.uk:3000 to respond..." >&2
while ! curl -sf http://git.adam-french.co.uk:3000 > /dev/null 2>&1; do
sleep 2
done
echo "git.adam-french.co.uk:3000 is up." >&2
if [ ! -f .runner ]; then
echo "No .runner file found. Registering runner..." >&2
./act_runner register --no-interactive \
--instance http://git.adam-french.co.uk:3000 \
--token "${GITEA_RUNNER_REGISTRATION_TOKEN}" \
--name "${GITEA_RUNNER_NAME:-pi-runner}" \
--labels self-hosted
fi
echo "Starting act_runner daemon..." >&2
exec ./act_runner daemon
+1
View File
@@ -219,6 +219,7 @@ onUnmounted(() => {
<div>
<input
v-model="messageInput"
maxlength="1000"
@keyup.enter="sendMessage"
:aria-label="isPrivate ? 'Private chat message' : 'Chat message'"
:placeholder="isPrivate ? 'Admins only' : ''"
@@ -158,15 +158,15 @@
<path class="dg-edge dg-edge--pink" d="M712,819 H796" />
<rect class="dg-band" x="16" y="844" width="1068" height="30" opacity="0.18" />
<rect class="dg-box" x="800" y="847" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="863" style="fill: var(--color-primary)">garage-webui:3909</text>
<text class="dg-small" x="1070" y="863" text-anchor="end">bucket admin</text>
<text class="dg-code" x="812" y="863" style="fill: var(--color-primary)">garage:3909</text>
<text class="dg-small" x="1070" y="863" text-anchor="end">stpcore · bucket admin</text>
<circle class="dg-dot dg-dot--pink" cx="24" cy="859" r="4" />
<text class="dg-code" x="36" y="863" style="fill: var(--color-secondary)">/garage/</text>
<text class="dg-small" x="390" y="863">prefix kept · body up to 2G · unbuffered</text>
<path class="dg-edge dg-edge--pink" d="M712,859 H796" />
<rect class="dg-box" x="800" y="887" width="280" height="24" rx="3" />
<text class="dg-code" x="812" y="903" style="fill: var(--color-primary)">garage:3902</text>
<text class="dg-small" x="1070" y="903" text-anchor="end">S3 website endpoint</text>
<text class="dg-small" x="1070" y="903" text-anchor="end">stpcore · S3 website</text>
<circle class="dg-dot" cx="24" cy="899" r="4" />
<text class="dg-code" x="36" y="903" style="fill: var(--color-secondary)">/uploads/</text>
<text class="dg-small" x="390" y="903">strip · Host uploads.web.garage · 2s connect</text>
@@ -162,7 +162,7 @@
<g>
<rect class="dg-box" x="480" y="676" width="180" height="46" rx="4" />
<text class="dg-title" x="570" y="696" text-anchor="middle">GARAGE-WEBUI</text>
<text class="dg-code" x="570" y="713" text-anchor="middle">:3909</text>
<text class="dg-small" x="570" y="713" text-anchor="middle" style="fill: var(--color-tertiary)">:3909 · on the stpcore LXC</text>
<path class="dg-edge" d="M400,699 H476" />
<text class="dg-edge-label dg-edge-label--mint" x="440" y="692" text-anchor="middle">/garage/</text>
</g>
@@ -211,7 +211,7 @@
<rect class="dg-box dg-box--tint" x="740" y="676" width="200" height="154" rx="4" style="stroke: var(--color-secondary)" />
<text class="dg-title" x="840" y="700" text-anchor="middle" style="fill: var(--color-secondary)">GARAGE</text>
<text class="dg-small" x="840" y="716" text-anchor="middle">S3 object store</text>
<text class="dg-small" x="840" y="716" text-anchor="middle" style="fill: var(--color-tertiary)">S3 · on the stpcore LXC</text>
<text class="dg-code" x="756" y="740">:3900 S3 API</text>
<text class="dg-code" x="756" y="760">:3903 admin API</text>
<text class="dg-code" x="756" y="816">:3902 website</text>