4 Commits
Author SHA1 Message Date
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
19 changed files with 196 additions and 138 deletions
-6
View File
@@ -42,12 +42,6 @@ GITEA_HOST=git.localhost
GITEA_PORT=3000 GITEA_PORT=3000
GITEA_UPSTREAM=192.0.2.1 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 (notes) ---------------------------------------------------
SILVERBULLET_PORT=3000 SILVERBULLET_PORT=3000
SILVERBULLET_PUBLIC_HOST=silverbullet-public SILVERBULLET_PUBLIC_HOST=silverbullet-public
-9
View File
@@ -60,15 +60,6 @@ GITEA_HOST=git.adam-french.co.uk
GITEA_PORT=3000 GITEA_PORT=3000
GITEA_UPSTREAM= 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) --------------------------------------------------- # --- SilverBullet (notes) ---------------------------------------------------
# The public read-only notes site at /notes/. The editor, and the vault's only # 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. # writer, is stppriv (priv.DOMAIN/sb/); silverbullet-git here only pulls.
+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 # 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 # Python run in containers pinned to the same images as their Dockerfiles
# (bump together), and checkout is plain git rather than actions/checkout. # (bump together), and checkout is plain git rather than actions/checkout.
@@ -11,16 +13,20 @@ on:
jobs: jobs:
test: test:
runs-on: self-hosted runs-on: build
env: env:
# Via env so a branch name is never parsed as shell. # Via env so a branch name is never parsed as shell.
SHA: ${{ github.sha }} SHA: ${{ github.sha }}
REF: ${{ github.ref }} REF: ${{ github.ref }}
REMOTE: ssh://[email protected]:2222/adamf/stpweb.git # Over HTTP with the job's own token (read access to this repo while
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no" # 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. # Kept between runs so fetches are incremental.
CACHE: /home/adamf/.cache/stpweb-ci/repo.git 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: steps:
- name: Export the pushed commit to a scratch directory - name: Export the pushed commit to a scratch directory
shell: bash shell: bash
@@ -30,7 +36,12 @@ jobs:
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE" [ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
# $SHA, not FETCH_HEAD: test this run's commit even if the # $SHA, not FETCH_HEAD: test this run's commit even if the
# branch has moved on. # 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" rm -rf "$SRC"
mkdir -p "$SRC" mkdir -p "$SRC"
git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$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 # 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` # 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 # so they never appear in the process list. Gitea refuses secret names starting
@@ -13,7 +14,7 @@ on:
jobs: jobs:
renovate: renovate:
runs-on: self-hosted runs-on: build
steps: steps:
- name: Run Renovate - name: Run Renovate
shell: bash shell: bash
@@ -30,7 +31,7 @@ jobs:
-e RENOVATE_PLATFORM=gitea \ -e RENOVATE_PLATFORM=gitea \
-e RENOVATE_ENDPOINT=http://git.adam-french.co.uk:3000/api/v1 \ -e RENOVATE_ENDPOINT=http://git.adam-french.co.uk:3000/api/v1 \
-e RENOVATE_GIT_URL=endpoint \ -e RENOVATE_GIT_URL=endpoint \
-e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore \ -e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore,adamf/stprunner \
-e RENOVATE_TOKEN \ -e RENOVATE_TOKEN \
-e GITHUB_COM_TOKEN \ -e GITHUB_COM_TOKEN \
-e LOG_LEVEL=info \ -e LOG_LEVEL=info \
+6 -1
View File
@@ -20,9 +20,14 @@ usaco-data/
.deprecated/gitea/config/ .deprecated/gitea/config/
.deprecated/gitea/dev-leftovers/ .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/.runner
gitea-runner/act_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 gitea-runner/nohup.out
# Python bytecode # Python bytecode
+2 -2
View File
@@ -63,7 +63,7 @@ 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/`. **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 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. **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.
@@ -95,7 +95,7 @@ Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubun
## Key Patterns ## 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. - **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`. - **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`. - **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. - **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.
+27 -12
View File
@@ -723,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`. `docker compose -f docker-compose.yml -f .deprecated/gitea/docker-compose.gitea.yml up -d gitea`.
`.deprecated/README.md` has the details. `.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.
``` **The runners** are installed by the `adamf/stprunner` repo, not from here:
cd gitea-runner on each VM, `~/deploy/stprunner` and `sudo ./install.sh <host>` run
bash download.sh # pulls the binary for this CPU gitea-runner (formerly act_runner) as the systemd service `gitea-runner`,
# mint a registration token: Gitea -> Site Administration -> Actions -> Runners with that host's name, labels and capacity in `hosts/<host>.env` there. Its
GITEA_RUNNER_REGISTRATION_TOKEN=... ./run.sh # registers once, then daemonises 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
The runner lives **outside** Docker on purpose: it runs `docker compose up` container in it. Since 2026-11-27: gitea-runner v6.0.1, which needs Gitea
against this stack, so it cannot be a container in it. Registration is one-shot — 1.26.2+ (act_runner 0.2.x could not run `node24` actions such as
`.runner` is the lasting credential; re-registering needs that file deleted _and_ `actions/checkout@v5`). Until then each VM ran its own copy of this repo's
a fresh token. 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 **Dependency updates (Renovate).** Dependabot is GitHub-only, so
`.gitea/workflows/renovate.yaml` runs Renovate on the same runner every Monday `.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_HOST` | Public notes SilverBullet hostname (defaults to `silverbullet-public`) |
| `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) | | `SILVERBULLET_PUBLIC_PORT` | Public notes SilverBullet port (defaults to `3000`) |
| `SILVERBULLET_GIT_INTERVAL` | Seconds between notes pulls (defaults to `300`) | | `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_PORT` | Backend port (typically `8080`) |
| `BACKEND_HOST` | Backend hostname (use `backend` for Docker) | | `BACKEND_HOST` | Backend hostname (use `backend` for Docker) |
| `BACKEND_SECRET` | JWT signing secret | | `BACKEND_SECRET` | JWT signing secret |
@@ -281,9 +278,7 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
### Gitea Runner ### Gitea Runner
1. Download the `act_runner` binary from [Gitea releases](https://gitea.com/gitea/act_runner/releases) and place in `gitea-runner/` 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.
2. Set `GITEA_RUNNER_REGISTRATION_TOKEN` in `.env`
3. The runner registers automatically on first startup
## Dev Mode ## 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) | | `caddy/data/` | Created automatically by Caddy (certificates and their keys) |
| `backend/token/` | Created automatically by Docker volume mount | | `backend/token/` | Created automatically by Docker volume mount |
| `icecast2/fallback_music/*.mp3` | Place at least one MP3 file | | `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 ## 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 - `POST /auth/login` (or the `login` mutation) checks a bcrypt hash and sets
two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`: two cookies, both `HttpOnly` + `Secure` + `SameSite=Lax`:
- `access_token` (7 days) carries `id`, `username`, `admin`, so ordinary - `access_token` (7 days) carries `id`, `username`, `admin` and `tv`;
requests authorise without a database hit; - `refresh_token` (90 days) carries `id` and `tv`.
- `refresh_token` (365 days) carries only `id`. 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 - `POST /auth/refresh` (or the `refreshToken` mutation) exchanges the refresh
token for a new pair, re-reading the user — and therefore the admin flag — token for a new pair, so the 90 days slide while the account is in use.
from the database.
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401) - `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
and will transparently refresh, so returning admins are recognised without a and will transparently refresh, so returning admins are recognised without a
visible re-login. 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 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 the next request. On 200 it returns the username in `X-Auth-User`, which
Caddy forwards to the gated service as `X-Remote-User`. Caddy forwards to the gated service as `X-Remote-User`.
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing - Revocation is by `User.TokenVersion`: logout and a password change bump it,
is revoked server-side, and a token that has already been issued stays valid which invalidates every token already issued to that user. Demoting an admin
until it expires. The same is true of demoting an admin: it takes effect on applies on their next request.
their next refresh, not immediately. - 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 The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
`graph/auth.resolvers.go`) are parallel by design, since the front end uses `graph/auth.resolvers.go`) are parallel by design, since the front end uses
+1 -1
View File
@@ -40,7 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
return uint(idF), true 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 { func IsAdminFromCtx(ctx context.Context) bool {
claims := UserClaimsFromCtx(ctx) claims := UserClaimsFromCtx(ctx)
if claims == nil { if claims == nil {
+4 -9
View File
@@ -40,8 +40,8 @@ func (store *Store) AuthMiddleware(ctx *gin.Context) {
ctx.Next() ctx.Next()
} }
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so // AdminMiddleware must follow AuthMiddleware, whose claims carry the row's
// a revoked flag applies once the access token expires. // admin flag.
func (store *Store) AdminMiddleware(ctx *gin.Context) { func (store *Store) AdminMiddleware(ctx *gin.Context) {
claims, exists := ctx.Get("userClaims") claims, exists := ctx.Get("userClaims")
if !exists { 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 // 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. // mint new cookies, so a returning admin needn't log in again.
func (store *Store) ValidateAdmin(ctx *gin.Context) { func (store *Store) ValidateAdmin(ctx *gin.Context) {
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool { store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
// The refresh path has no admin claim, so it reads the row. return user.Admin
if claims == nil {
return user.Admin
}
admin, ok := (*claims)["admin"].(bool)
return ok && admin
}) })
} }
+3 -1
View File
@@ -61,6 +61,7 @@ func main() {
// Used for both the WebSocket origin check and the cookie domain. // Used for both the WebSocket origin check and the cookie domain.
domainName := os.Getenv("DOMAIN") domainName := os.Getenv("DOMAIN")
services.InitWebSocket(db, domainName) services.InitWebSocket(db, domainName)
r.Use(services.RequireSameOrigin(domainName))
spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI") spotifyRedirectURL := os.Getenv("SPOTIFY_REDIRECT_URI")
spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID") spotifyClientID := os.Getenv("SPOTIFY_CLIENT_ID")
@@ -71,7 +72,8 @@ func main() {
authSecret := os.Getenv("BACKEND_SECRET") authSecret := os.Getenv("BACKEND_SECRET")
backendEndpoint := os.Getenv("BACKEND_ENDPOINT") backendEndpoint := os.Getenv("BACKEND_ENDPOINT")
accessTokenLifetime := 7 * 24 * time.Hour 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} authConfig := services.AuthConfig{Secret: []byte(authSecret), Domain: domainName, RefreshTokenLifetime: refreshTokenLifetime, AccessTokenLifetime: accessTokenLifetime, Endpoint: backendEndpoint}
auth := services.InitAuth(&authConfig) auth := services.InitAuth(&authConfig)
+6 -2
View File
@@ -41,8 +41,8 @@ func InitAuth(config *AuthConfig) *Auth {
return &Auth{Config: config} return &Auth{Config: config}
} }
// GenerateJWT issues an access/refresh pair. Only the access token carries // GenerateJWT issues an access/refresh pair. The admin claim is informational:
// admin; refresh re-reads the row, so a revoked admin flag applies then. // AuthenticateTokenWithClaims overwrites it from the user row.
func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) { func (auth *Auth) GenerateJWT(user *models.User) (*Tokens, error) {
accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ accessToken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"username": user.Username, "username": user.Username,
@@ -140,6 +140,10 @@ func (auth *Auth) AuthenticateTokenWithClaims(db *gorm.DB, tokenStr string) (*mo
return nil, nil, ErrTokenRevoked 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 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)
}
})
}
}
+1 -10
View File
@@ -3,7 +3,6 @@ package services
import ( import (
"log" "log"
"net/http" "net/http"
"net/url"
"sync" "sync"
"time" "time"
@@ -28,15 +27,7 @@ var Upgrader = websocket.Upgrader{
WriteBufferSize: 1024, WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { CheckOrigin: func(r *http.Request) bool {
origin := r.Header.Get("Origin") origin := r.Header.Get("Origin")
if origin == "" { return origin != "" && IsSiteOrigin(origin, allowedDomain)
return false
}
u, err := url.Parse(origin)
if err != nil {
return false
}
host := u.Hostname()
return host == allowedDomain || host == "www."+allowedDomain || host == "localhost"
}, },
} }
+1 -1
View File
@@ -153,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/* { handle /sb/* {
redir https://priv.{$DOMAIN}{uri} 301 redir https://priv.{$DOMAIN}{uri} 301
} }
-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