diff --git a/.gitea/workflows/deploy.yaml b/.gitea/workflows/deploy.yaml index 6e2534f..339bdb8 100644 --- a/.gitea/workflows/deploy.yaml +++ b/.gitea/workflows/deploy.yaml @@ -1,47 +1,9 @@ -# ============================================================================= -# deploy.yaml — test every push; deploy pushes to main that pass. -# -# TWO JOBS -# test runs on every push, to any branch: `go vet` + `go test` for the -# backend and pytest for the Python service. These are the same -# checks as `make check-backend` and `make check-python`. -# deploy runs only for refs/heads/main, and only if `test` passed -# (`needs: test`). Before this gate existed every push to main went -# straight to the live site. -# -# WHERE THIS RUNS, AND WHAT THAT RULES OUT -# A self-hosted act_runner on the Pi itself, in HOST mode (see -# gitea-runner/run.sh): steps are shell commands on the Pi, not in a job -# container. So: -# - No host toolchains are assumed. The Pi is known to have git and docker -# and nothing else; Go and Python run inside `docker run` containers -# pinned to the same base images as backend/Dockerfile (golang:1.26) and -# python/Dockerfile (python:3.12-slim). Bump them together. -# - No `actions/checkout`. It is a JavaScript action and would need Node on -# the host. The source is fetched with plain git instead, over Gitea's SSH -# on its LXC (git.adam-french.co.uk:2222, pinned to the LAN IP in -# stpvm's /etc/hosts). -# -# THE LIVE DIRECTORY IS NOT TOUCHED UNTIL TESTS PASS -# The site runs out of /home/adamf/deploy/web_server. The test job never -# goes near it: it fetches into a separate bare cache repo and exports the -# pushed commit to a scratch directory. Only the deploy job, after `test` -# is green, does the `git reset --hard` there. -# -# NOT TESTED HERE: THE VUE BUILD -# Deliberately skipped. `docker compose up --build` in the deploy job -# already runs the full frontend build (npm ci + vite) while building the -# vue image, and a failed image build aborts `up` BEFORE any container is -# replaced, so the old site keeps serving. Building it a second time here -# would cost the Pi several minutes per push to learn nothing new. The same -# reasoning does not hold for Go and Python: their images build fine with -# failing tests, which is exactly why those are gated here. -# -# NO pull_request TRIGGER -# `push` with no branch filter already covers every branch, including the -# head branch of any PR in this repo, so adding pull_request would run the -# suite twice per push on a machine with little CPU to spare. -# ============================================================================= +# `test` runs on every push; `deploy` runs for main only after it passes. +# 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. +# The Vue build isn't tested here: a failed image build in `up --build` +# aborts before any container is replaced. name: Test and deploy on: @@ -51,19 +13,13 @@ jobs: test: runs-on: self-hosted env: - # The commit and ref this push delivered. Passed through env rather - # than interpolated into the scripts so a branch name can never be - # parsed as shell. + # Via env so a branch name is never parsed as shell. SHA: ${{ github.sha }} REF: ${{ github.ref }} REMOTE: ssh://git@git.adam-french.co.uk:2222/adamf/web_server.git GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no" - # Bare repo kept between runs so each fetch is incremental (the - # history is ~140MB; a fresh clone per push would be slow on the - # Pi's SD card). Lives outside the deploy directory on purpose. + # Kept between runs so fetches are incremental. CACHE: /home/adamf/.cache/web_server-ci/repo.git - # This run's source tree, exported from the cache and removed in - # the last step. Keyed by commit so two runs cannot share a tree. SRC: /home/adamf/.cache/web_server-ci/src-${{ github.sha }} steps: - name: Export the pushed commit to a scratch directory @@ -72,33 +28,19 @@ jobs: set -eu mkdir -p "$(dirname "$CACHE")" [ -d "$CACHE" ] || git init --quiet --bare "$CACHE" - # Fetch the pushed ref, then export the exact pushed commit. - # Using $SHA rather than FETCH_HEAD means that if the branch - # has moved on since this run was queued we still test the - # commit this run is about, not a newer one. + # $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" rm -rf "$SRC" mkdir -p "$SRC" - # `git archive` gives a clean tree of tracked files only: no - # .git, and nothing left over from an earlier run. git --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC" - # Do not rely on the shell having pipefail: if the archive - # half failed, make sure that is noticed here. + # In case the shell lacks pipefail. test -f "$SRC/backend/go.mod" test -f "$SRC/python/requirements-dev.txt" echo "Exported $SHA ($REF) to $SRC" - # The whole repo is mounted read-only. Tests write only to - # t.TempDir(), and a read-only mount means the container (root) - # cannot leave root-owned files in $SRC that the clean-up step, - # running as the runner user, could not delete. - # - # The two named volumes are the Go module cache and build cache. - # Without them every run would re-download every dependency and - # recompile gorm, gin and gqlgen from scratch — minutes on a Pi. - # They survive `docker image prune` and the weekly maintenance - # job; `docker volume rm web_server_ci_gomod web_server_ci_gobuild` - # resets them if they ever go bad. + # Read-only so root in the container can't leave files the + # clean-up step can't delete. The named volumes are Go caches. - name: Backend - go vet and go test shell: bash run: | @@ -111,12 +53,7 @@ jobs: golang:1.26 \ sh -c 'go vet ./... && go test ./...' - # requirements-dev.txt pulls in requirements.txt plus pytest. The - # install is repeated every run (the container is thrown away) but - # the pip cache volume means it is unpacking cached wheels, not - # downloading. Read-only source for the same reason as above, so - # bytecode and the pytest cache are switched off rather than left - # to fail noisily. + # Read-only source, so bytecode and the pytest cache are off. - name: Python - pytest shell: bash run: | @@ -129,16 +66,12 @@ jobs: python:3.12-slim \ sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider' - # always(): a failed test must not leave a source tree behind per - # push. The cache repo is kept; only this run's export goes. - name: Remove the scratch directory if: always() shell: bash run: rm -rf "$SRC" deploy: - # Both conditions matter: `needs` makes a red test job skip this one, - # and the `if` keeps pushes to other branches from deploying at all. needs: test if: github.ref == 'refs/heads/main' runs-on: self-hosted @@ -153,12 +86,8 @@ jobs: set -eu git config --global --add safe.directory /home/adamf/deploy/web_server git fetch ssh://git@git.adam-french.co.uk:2222/adamf/web_server.git main - # Deploy only the commit the test job just passed. If main - # has moved on since this run started, FETCH_HEAD is a newer - # commit that THIS run never tested — stop, and let that - # commit's own run test and deploy it. Failing (rather than - # resetting to $SHA anyway) also means re-running an old run - # can never roll the site back to an old commit. + # Deploy only the tested commit; a newer main gets its own + # run. This also stops a re-run rolling the site back. if [ "$(git rev-parse FETCH_HEAD)" != "$SHA" ]; then echo "main is at $(git rev-parse FETCH_HEAD), but this run tested $SHA." echo "Not deploying: the run for the newer commit will." @@ -170,8 +99,7 @@ jobs: working-directory: /home/adamf/deploy/web_server env: COMPOSE_BAKE: "false" - # The lock is shared with maintenance.yaml, so a deploy and the - # weekly rebuild cannot run compose at the same time. + # Shared with maintenance.yaml so the two never run compose at once. run: flock .compose.lock docker compose up -d --build --remove-orphans - name: Prune unused Docker resources diff --git a/.gitea/workflows/maintenance.yaml b/.gitea/workflows/maintenance.yaml index 03c8c73..a125097 100644 --- a/.gitea/workflows/maintenance.yaml +++ b/.gitea/workflows/maintenance.yaml @@ -2,9 +2,7 @@ name: Weekly Maintenance on: schedule: - # 05:00 UTC Sunday (06:00 in BST). The upgrade restarts dockerd and - # every container, so it runs when nobody is likely to be mid-edit; - # 01:00 kept catching late-night SilverBullet saves. + # Restarts dockerd, so it runs when nobody is likely mid-edit. - cron: "0 5 * * 0" workflow_dispatch: @@ -24,15 +22,8 @@ jobs: - name: Autoremove obsolete packages run: sudo apt-get -y autoremove --purge - # Both compose steps below take .compose.lock, the same flock - # deploy.yaml holds while it runs compose. Without it this weekly - # job could recreate containers while a deploy is mid-build, and - # two `compose up`s racing over the same project can each recreate - # a container the other just started. flock blocks until the other - # holder finishes, so the job waits rather than fails. The lock is - # taken per step, not across both: nothing needs pull and up to be - # atomic, and holding it for less time keeps a deploy from waiting - # behind a long pull. + # .compose.lock is shared with deploy.yaml, so two compose runs + # never race. Taken per step to keep deploys from waiting long. - name: Pull latest base images working-directory: /home/adamf/deploy/web_server run: flock .compose.lock docker compose pull diff --git a/.gitea/workflows/renovate.yaml b/.gitea/workflows/renovate.yaml index 5ea13fa..bcdf855 100644 --- a/.gitea/workflows/renovate.yaml +++ b/.gitea/workflows/renovate.yaml @@ -1,48 +1,13 @@ -# ============================================================================= -# renovate.yaml — weekly dependency-update PRs, opened against this repo. -# -# Renovate stands in for Dependabot, which does not exist outside GitHub. What -# it updates is configured in /renovate.json5; this file is only how it runs. -# -# HOW IT RUNS -# The same host-mode act_runner as deploy.yaml, so (as there) nothing but -# git and docker is assumed on the host: Renovate runs from its own image. -# --network host gives the container the host's /etc/hosts, which pins -# git.adam-french.co.uk to the Gitea LXC's LAN IP, so it reaches Gitea on -# :3000, the port the runner itself registers against, and keeps working -# while the tunnel is down. RENOVATE_GIT_URL=endpoint matters for the same -# reason: without it Renovate clones from the URL Gitea advertises, which is -# ROOT_URL — the public https://git.adam-french.co.uk through Cloudflare. -# -# WHAT HAPPENS AFTER -# Each update is pushed as a renovate/* branch, which triggers deploy.yaml's -# `test` job like any other push (and never its `deploy` job, which is -# main-only). Nothing is merged automatically: merging is deploying. -# Renovate also keeps a "Dependency Dashboard" issue open listing everything -# pending; ticking a box there is picked up on the next run, so run this -# workflow by hand (workflow_dispatch) to act on it sooner. -# -# THE TOKEN -# RENOVATE_TOKEN is a repo Actions secret: a Gitea access token for the -# account the PRs come from (a dedicated `renovate` user with write access -# to this repo, ideally), scopes read:user, read:organization, -# write:repository, write:issue. -# RENOVATE_GITHUB_COM_TOKEN is optional: any github.com token with no -# scopes. Without it Renovate is rate-limited by GitHub and leaves release -# notes out of the PRs. (Gitea refuses secret names starting GITHUB_, hence -# the prefix.) Both reach the container as `-e NAME` with no value, so they -# are copied from this step's env and never appear in the process list. -# -# The renovate/renovate:44 tag floats within the major (--pull always picks -# up the newest 44.x each week); Renovate itself proposes the next major via -# the regex manager in renovate.json5. -# ============================================================================= +# Weekly Renovate run (config in /renovate.json5). --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 +# GITHUB_, hence RENOVATE_GITHUB_COM_TOKEN. name: Renovate on: schedule: - # 04:00 UTC Monday: clear of the Sunday 05:00 maintenance rebuild, and - # done before the working week so the PRs are waiting. + # Clear of the Sunday maintenance rebuild. - cron: "0 4 * * 1" workflow_dispatch: diff --git a/CLAUDE.md b/CLAUDE.md index 44de40f..8763474 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -116,7 +116,7 @@ Each area has its own README with the detail that doesn't belong here: ## Conventions -- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, the edge's route order). Preserve these when editing; if you change the behaviour they describe, update them. +- **Keep comments rare and short.** Code should explain itself through names and structure. Comment only a non-obvious *why* (a security boundary, an upstream quirk, an ordering constraint), in a line or two. No history, dates, migration notes or narration of what the code does: those belong in commit messages and the READMEs. If you change behaviour a comment describes, update or delete it. - **Resolver commentary lives inside function bodies**, because gqlgen relocates or strips anything above the signature when regenerating. - **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output. - **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof. diff --git a/Makefile b/Makefile index 9f166c9..67de5ba 100644 --- a/Makefile +++ b/Makefile @@ -1,39 +1,14 @@ -# ============================================================================= -# Makefile — one place for the commands that verify and run this repo. -# -# WHY THIS FILE EXISTS -# The stack is four toolchains (Go, Python, Node, Docker) and the command -# that checks each one used to live only in a gitignored notes file. `make -# check` is the single thing to run before pushing; .gitea/workflows/ -# deploy.yaml runs the same backend and Python checks (in containers, since -# the Pi runner has no host toolchains) before it deploys. -# -# WHAT IT NEEDS ON THE HOST -# check-backend / generate Go (the version in backend/go.mod) -# check-python python3 with the venv module -# check-vue Node + `npm install` done in vue/ -# check-compose / dev Docker with the compose plugin -# check-caddy Docker -# Nothing here installs a toolchain; a missing one fails that target only. -# -# Recipes are plain `cd dir && cmd` one-liners on purpose: each line runs in -# its own shell, so the directory change cannot leak into the next line. -# ============================================================================= +# `make check` before pushing; `make help` lists targets. A missing toolchain +# fails only the targets that need it. -# `make` with no arguments prints the target list rather than running checks. .DEFAULT_GOAL := help -# Overridable: `make check-python PYTHON=python3.12` to match the image. PYTHON ?= python3 -# The virtualenv for the Python checks. At the repo root rather than inside -# python/, because python/ is a docker build context and a venv there would be -# sent to the daemon on every build. Gitignored (/.venv/). +# At the root, not in python/, which is a docker build context. VENV := .venv -# Written after a successful install. Being a file target that depends on both -# requirements files, it is what makes `check-python` re-install when either -# changes and skip the install otherwise. +# Re-installs only when a requirements file changes. VENV_STAMP := $(VENV)/.installed .PHONY: help check check-backend check-python check-vue check-compose check-caddy generate dev @@ -49,17 +24,12 @@ help: @echo " make generate regenerate the gqlgen GraphQL code after a schema edit" @echo " make dev build and run the dev stack (http://localhost)" -# Run with `make -k check` to keep going past the first failing area. check: check-backend check-python check-vue check-compose check-caddy check-backend: cd backend && go vet ./... && go test ./... -# requirements-dev.txt `-r`-includes requirements.txt, so one install covers -# the app's dependencies and pytest. The venv is recreated from scratch -# whenever a requirements file changes: upgrading in place would leave behind -# packages that were removed from the files, and the check would keep passing -# on a dependency the image no longer has. +# Recreated from scratch so packages dropped from the files don't linger. $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt rm -rf $(VENV) $(PYTHON) -m venv $(VENV) @@ -70,11 +40,7 @@ $(VENV_STAMP): python/requirements.txt python/requirements-dev.txt check-python: $(VENV_STAMP) cd python && ../$(VENV)/bin/python -m pytest tests -q -# A Vite build is enough to catch a broken import or template; there is no -# test runner or linter for the frontend. -# -# The build goes to a temp directory that is removed afterwards (success or -# failure), so the check never leaves a vue/dist behind or overwrites one. +# Builds into a temp directory, so vue/dist is never touched. check-vue: @test -d vue/node_modules || { \ echo "check-vue: vue/node_modules/ is missing. Run: cd vue && npm install"; \ @@ -82,22 +48,9 @@ check-vue: @out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \ cd vue && npx vite build --outDir "$$out" --emptyOutDir -# Validates the compose files: YAML, schema, and that every ${VAR} they -# interpolate resolves to something usable. -# -# With a real .env present this is simply `docker compose config -q`. -# -# Without one (a CI checkout, a fresh clone) two things break, and -# `--env-file .env.example` fixes neither: -# - several services declare `env_file: ./.env`, and compose refuses to load -# the project if that file does not exist; -# - .env.example has blank values, and OBSIDIAN_DIR is used as a bind-mount -# source, where an empty string is a hard "invalid spec" error. -# So in that case the files are validated against a temporary PROJECT -# DIRECTORY holding a copy of .env.example as its .env, with a placeholder for -# OBSIDIAN_DIR. `config` only resolves paths, it does not need them to exist, -# so the build contexts not being under the temp directory is fine. Nothing is -# written to the repo, and a real .env is never created by accident. +# Without a .env, validates against a temp project dir holding .env.example +# (compose refuses a missing env_file, and a blank OBSIDIAN_DIR is an invalid +# bind mount). A real .env is never created. check-compose: @set -e; \ if [ -f .env ]; then \ @@ -113,21 +66,12 @@ check-compose: echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \ docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q -# The edge config is validated by the image build itself (the last RUN in -# caddy/Dockerfile runs `caddy validate` for the production and dev sites), so -# this is that build and nothing more. The deploy's `docker compose up -# --build` runs the same build, and a failure there stops before any -# container is replaced. The first build compiles Caddy with its plugins and -# takes a few minutes; later ones reuse that layer unless the Dockerfile -# changes. +# The image build runs `caddy validate` for both modes. check-caddy: docker build -q -t web_server-caddy:check caddy/ -# Rewrites backend/graph/generated.go and graph/model/models_gen.go from -# graph/schema/*.graphql. Resolver bodies in *.resolvers.go are preserved. generate: cd backend && go run github.com/99designs/gqlgen generate -# Dev stack: http and https, seeded database, Vite hot reload behind Caddy. dev: docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build diff --git a/backend/Dockerfile b/backend/Dockerfile index d30860e..db03c42 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -1,32 +1,5 @@ -# ============================================================================= -# Go backend image — multi-stage: build with the full toolchain, ship a slim -# runtime containing one static binary. -# -# STAGE 1 (golang:1.26) -# go.mod/go.sum are copied and downloaded BEFORE the rest of the source, so -# the dependency layer is cached and only re-runs when the module files -# change — a meaningful saving when building on a Raspberry Pi. -# -# The `--mount=type=cache` lines are BuildKit cache mounts: the module cache -# and the Go build cache persist BETWEEN builds on the host without being -# baked into any image layer. This is the single biggest reason a rebuild on -# the Pi takes minutes rather than much longer. They require BuildKit, which -# is the default in modern `docker compose build`. -# -# CGO_ENABLED=0 produces a fully static binary with no libc dependency, which -# is what lets a golang-built binary run on a different, slimmer base image. -# -# STAGE 2 (debian:bookworm-slim) -# Carries only the binary plus ca-certificates — needed because the backend -# makes outbound HTTPS calls (Spotify, Claude, Steam, the Gitea feed) and -# would fail certificate verification without a trust store. -# -# EXPOSE 8080 is documentation only; the port is never published to the host. -# Caddy reaches it over app-network as BACKEND_HOST:BACKEND_PORT. -# -# Base images are multi-arch, so this builds unchanged on arm64 (the Pi) and -# amd64 (a dev laptop) with no platform pin. -# ============================================================================= +# Static binary (CGO_ENABLED=0) on a slim base. ca-certificates for outbound +# HTTPS; the cache mounts keep rebuilds fast. FROM golang:1.26 AS builder WORKDIR /backend @@ -44,10 +17,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \ FROM debian:bookworm-slim -# wget is not just for humans: the compose healthcheck probes the server with -# `wget -qO- http://localhost:8080/`, and without it in the image every probe -# fails as "executable file not found" and Docker marks the container -# unhealthy. +# For the compose healthcheck. RUN apt-get update \ && apt-get install --yes --no-install-recommends ca-certificates wget \ && rm -rf /var/lib/apt/lists/* diff --git a/backend/README.md b/backend/README.md index af53301..523b23b 100644 --- a/backend/README.md +++ b/backend/README.md @@ -38,7 +38,7 @@ graph/ GraphQL layer 2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so that `ClientIP()` — which the login rate limiter keys on — cannot be spoofed via `X-Forwarded-For`. -3. **REST**: the route's middleware chain runs. `AuthMiddlewear` requires a +3. **REST**: the route's middleware chain runs. `AuthMiddleware` requires a valid access token and stashes the claims in the Gin context; `AdminMiddleware` then requires `admin: true` in those claims. A handler reached through the `admin` group can assume both. diff --git a/backend/graph/activity.resolvers.go b/backend/graph/activity.resolvers.go index 339586e..6395901 100644 --- a/backend/graph/activity.resolvers.go +++ b/backend/graph/activity.resolvers.go @@ -14,9 +14,6 @@ import ( // CreateActivity is the resolver for the createActivity field. func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) { - // Admin-only, but there is no check to see here: the field is marked - // @admin in the schema and the directive (directives.go) has already - // refused anyone else by the time this runs. activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link} if err := r.Store.DB.Create(&activity).Error; err != nil { return nil, err diff --git a/backend/graph/auth.resolvers.go b/backend/graph/auth.resolvers.go index 6c7f3e6..77c5a8f 100644 --- a/backend/graph/auth.resolvers.go +++ b/backend/graph/auth.resolvers.go @@ -19,12 +19,7 @@ import ( // Login is the resolver for the login field. func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) { - // The Gin context is needed for two things GraphQL cannot express: the - // client IP for rate limiting, and setting response cookies. It is - // smuggled in by AuthContextMiddleware. - // - // This mutation mirrors handlers.Store.Login; the two share the limiter - // and services.Auth, so the same 5/min budget covers both entry points. + // Gin context for the client IP and cookies. Shares the REST login's limiter. gc := GinContextFromCtx(ctx) if gc == nil { return nil, fmt.Errorf("could not get gin context") @@ -34,8 +29,6 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (* return nil, fmt.Errorf("too many login attempts, please try again later") } - // Identical message for unknown user and wrong password, so the API - // cannot be used to enumerate usernames. var user models.User if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil { return nil, fmt.Errorf("invalid credentials") @@ -52,8 +45,7 @@ func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (* services.SetAuthCookies(gc, r.Store.Auth.Config, tokens) - // The payload carries no token: the tokens only ever travel as HttpOnly - // cookies, so client JavaScript never sees them. + // Tokens travel only as HttpOnly cookies. return &model.AuthPayload{User: &user}, nil } @@ -64,12 +56,9 @@ func (r *mutationResolver) Logout(ctx context.Context) (bool, error) { return false, fmt.Errorf("could not get gin context") } - // Bumping the token version is what actually revokes the tokens; clearing - // the cookies only stops the browser presenting them. Both are best - // effort and logout always reports success, matching the REST endpoint. + // Best effort, always succeeds, like the REST endpoint. if userID, ok := UserIDFromCtx(ctx); ok { - // The context only carries claims from a token that already - // verified, so this cannot be used to revoke someone else's sessions. + // Claims in ctx are already verified, so this can't target others. if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil { log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err) } @@ -92,11 +81,7 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload return nil, fmt.Errorf("unauthorized") } - // Shared with the REST refresh endpoint, but the messages below are the - // ones this resolver already returned, so the GraphQL error strings are - // unchanged. Admin status and the token version are both re-read from the - // database here, which is what lets a revoked admin flag or a logout take - // effect on refresh. + // Re-reads admin and token version from the DB. user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken) if err != nil { switch { @@ -121,16 +106,12 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload // Me is the resolver for the me field. func (r *queryResolver) Me(ctx context.Context) (*models.User, error) { - // Checked here rather than with @signedIn because the message differs: - // this query has always answered "unauthorized", and the directive's is - // "authentication required". + // Not @signedIn: this query's error has always been "unauthorized". userID, ok := UserIDFromCtx(ctx) if !ok { return nil, fmt.Errorf("unauthorized") } - // Read fresh from the database rather than returned from the token - // claims, so `me` reflects the current username and admin flag. var user models.User user.ID = userID if err := r.Store.DB.First(&user).Error; err != nil { diff --git a/backend/graph/background_helpers.go b/backend/graph/background_helpers.go index 3cf9f87..f2a8228 100644 --- a/backend/graph/background_helpers.go +++ b/backend/graph/background_helpers.go @@ -12,10 +12,8 @@ import ( "adam-french.co.uk/backend/models" ) -// The SPA puts these values straight into a style binding, as -// `background-color` and `url("")`. Vue sets them through the CSSOM, -// so nothing can escape into other properties, but a quote or bracket in the -// image could still end the url() early — hence the narrow shapes. +// These go into a style binding; a quote or bracket in the image could still +// end url() early, hence the narrow shapes. var ( // A hex colour, a colour name, or one of the colour functions — named, // so that url() and friends don't pass as a "function". diff --git a/backend/graph/bookmark.resolvers.go b/backend/graph/bookmark.resolvers.go index 94e5fbf..505223c 100644 --- a/backend/graph/bookmark.resolvers.go +++ b/backend/graph/bookmark.resolvers.go @@ -23,9 +23,7 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat // DeleteBookmark is the resolver for the deleteBookmark field. func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) { - // Loaded first so the deleted record can be returned to the client, and - // so a missing id is a clean "not found" rather than a silent no-op. - // Delete is a soft delete: deleted_at is set and the row stays. + // Loaded first so the deleted record can be returned and a bad id is "not found". var bookmark models.Bookmark if err := r.Store.DB.First(&bookmark, id).Error; err != nil { return nil, err diff --git a/backend/graph/box.resolvers.go b/backend/graph/box.resolvers.go index 7ca51b7..27b014a 100644 --- a/backend/graph/box.resolvers.go +++ b/backend/graph/box.resolvers.go @@ -15,9 +15,7 @@ import ( // CreateBox is the resolver for the createBox field. func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) { - // Framed defaults to true here rather than in the gorm tag — see the - // comment on models.Box.Framed. Sizes not supplied fall back to the - // same 300x200 the column defaults use. + // Framed defaults here, not in the gorm tag; see models.Box.Framed. box := models.Box{ Page: input.Page, Kind: input.Kind, @@ -45,8 +43,7 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI if input.AdminOnly != nil { box.AdminOnly = *input.AdminOnly } - // A linked box takes its html from the component, so its own is - // dropped rather than stored as a copy that would quietly go stale. + // A linked box's own html would only go stale. if input.ComponentID != nil { id := uint(*input.ComponentID) exists, err := componentExists(r.Store.DB, id) @@ -75,10 +72,8 @@ func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxI // UpdateBox is the resolver for the updateBox field. func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) { - // Partial update: nil fields are left alone. The canvas sends only the - // geometry after a drag and only the html after an edit, so this is - // what keeps the two from overwriting each other. Kind is not - // updatable — switching a widget box to html is a delete and create. + // Partial: the canvas sends only geometry after a drag and only html after + // an edit, so neither overwrites the other. var box models.Box if err := r.Store.DB.First(&box, id).Error; err != nil { return nil, err @@ -87,8 +82,7 @@ func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.Up box.Widget = input.Widget } if input.HTML != nil { - // A linked box's html is the component's; changing it here would - // only fork a copy. The editor sends it to updateComponent instead. + // Edit linked html via updateComponent, or it forks a copy. if box.ComponentID != nil { return nil, errors.New("that box is linked to a component: edit the component, or detach the box first") } @@ -140,12 +134,8 @@ func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box, // Boxes is the resolver for the boxes field. func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) { - // Public: this is the page layout every visitor loads. Ordered by z so - // DOM order matches stacking order, which keeps tab order sensible. - // - // What is admin-only is filtered here rather than hidden in the browser, - // so a private note never reaches anyone else: an adminOnly page answers - // with no boxes at all, and adminOnly boxes are left out of the rest. + // Ordered by z so DOM and tab order match stacking. Admin-only content is + // filtered server-side so it never reaches anyone else. hidden, err := pageHiddenFrom(ctx, r.Store.DB, page) if err != nil { return nil, err diff --git a/backend/graph/box_helpers.go b/backend/graph/box_helpers.go index 98a19d2..b9ce635 100644 --- a/backend/graph/box_helpers.go +++ b/backend/graph/box_helpers.go @@ -1,8 +1,6 @@ package graph -// Hand-written helpers for box.resolvers.go. Kept out of that file because -// gqlgen moves unknown code in a resolvers file to the end, under a warning -// comment, on every regenerate. +// Helpers live outside *.resolvers.go because gqlgen moves unknown code there. import ( "errors" @@ -26,9 +24,7 @@ func setInt(dst *int, src *int) { } } -// validateBox checks the fields a box needs to render and clamps geometry -// rather than rejecting it, because a drag that overshoots the canvas edge -// should land at the edge, not fail. +// validateBox clamps geometry, so an overshooting drag lands at the edge. func validateBox(box *models.Box) error { if !validPageKey(box.Page) { return errors.New("a box needs a valid page") @@ -59,9 +55,7 @@ func validateBox(box *models.Box) error { return nil } -// validateShadow trims a box-shadow value and bounds its length. The value is -// not parsed: the front end sets it through a style binding, so it can only -// ever be the one property, and an invalid value just draws no shadow. +// validateShadow doesn't parse: a style binding confines it to one property. func validateShadow(shadow *string) error { *shadow = strings.TrimSpace(*shadow) if len(*shadow) > maxShadowLen { diff --git a/backend/graph/component.resolvers.go b/backend/graph/component.resolvers.go index 45f1687..f49e36e 100644 --- a/backend/graph/component.resolvers.go +++ b/backend/graph/component.resolvers.go @@ -16,8 +16,6 @@ import ( // Uses is the resolver for the uses field. func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) { - // One count per component, which is fine for an admin-only list of a - // handful; soft-deleted boxes are excluded by GORM's default scope. var count int64 if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil { return 0, err @@ -27,7 +25,6 @@ func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (in // CreateComponent is the resolver for the createComponent field. func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) { - // Framed defaults to true and the size to 300x200, as for a new box. name, err := usableComponentName(r.Store.DB, input.Name, 0) if err != nil { return nil, err @@ -57,8 +54,7 @@ func (r *mutationResolver) CreateComponent(ctx context.Context, input model.Crea // UpdateComponent is the resolver for the updateComponent field. func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) { - // Partial, like updateBox. Nothing to do for the linked boxes: they - // read the html from here every time they are fetched. + // Linked boxes read the html from here, so nothing else to update. var c models.Component if err := r.Store.DB.First(&c, id).Error; err != nil { return nil, err @@ -100,9 +96,7 @@ func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input mo // DeleteComponent is the resolver for the deleteComponent field. func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) { - // The linked boxes keep showing what they showed, as copies, so - // deleting a component never changes a page. One transaction, so a - // failure can't leave boxes linked to a deleted component. + // Linked boxes become copies, so deleting never changes a page. var c models.Component if err := r.Store.DB.First(&c, id).Error; err != nil { return nil, err @@ -121,9 +115,8 @@ func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models // SaveBoxAsComponent is the resolver for the saveBoxAsComponent field. func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) { - // The box becomes the component's first linked instance, so carrying - // on editing it edits the component. A box that is already linked - // would make a component of a component's html; detach it first. + // The box becomes the first linked instance. A linked box must be + // detached first. var box models.Box if err := r.Store.DB.First(&box, id).Error; err != nil { return nil, err @@ -161,8 +154,6 @@ func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name // DetachBox is the resolver for the detachBox field. func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) { - // The html is filled in from the component and then saved, which is - // exactly the copy fillLinked otherwise never lets reach the row. var box models.Box if err := r.Store.DB.First(&box, id).Error; err != nil { return nil, err diff --git a/backend/graph/component_helpers.go b/backend/graph/component_helpers.go index d2e0d05..807787b 100644 --- a/backend/graph/component_helpers.go +++ b/backend/graph/component_helpers.go @@ -27,9 +27,6 @@ func cleanComponentName(name string) (string, error) { return name, nil } -// componentNameTaken reports whether a live component other than exceptID -// has this name. Checked up front, like layoutNameTaken, so the admin gets a -// sentence rather than a constraint violation. func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { var count int64 err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error @@ -53,12 +50,8 @@ func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error return name, nil } -// fillLinked sets each linked box's in-memory HTML to its component's, with -// one query for all of them. Only for boxes about to be returned or -// snapshotted: a linked row's own HTML is nil, and saving a filled box would -// freeze a copy of the component into it. A box whose component has gone -// (deleted outside deleteComponent, which detaches first) is left with -// empty HTML rather than failing the whole page. +// fillLinked sets linked boxes' HTML in memory only: saving a filled box would +// freeze a copy into it. A missing component leaves the HTML empty. func fillLinked(db *gorm.DB, boxes []models.Box) error { var ids []uint for _, b := range boxes { diff --git a/backend/graph/context.go b/backend/graph/context.go index 553e2ee..412f6ab 100644 --- a/backend/graph/context.go +++ b/backend/graph/context.go @@ -7,17 +7,10 @@ import ( "github.com/golang-jwt/jwt/v5" ) -// This file is the bridge between Gin's request handling and gqlgen's -// resolvers. gqlgen resolvers receive only a context.Context, so -// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and -// the *gin.Context itself into that context, and these accessors read them -// back out. +// Resolvers get only a context.Context; AuthContextMiddleware puts the +// verified claims and the *gin.Context into it. -// contextKey is a private named type so that these keys can never collide -// with a key set by another package — the reason the standard library warns -// against using bare strings as context keys. Note the string value -// "userClaims" happens to match the key handlers.AuthMiddlewear uses in the -// *Gin* context, but the two are unrelated and do not see each other. +// Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context. type contextKey string const ( @@ -25,10 +18,8 @@ const ( ginContextKey contextKey = "ginContext" ) -// UserClaimsFromCtx returns the verified JWT claims, or nil when the request -// is anonymous. nil means "not authenticated": a missing or invalid token is -// not an error here, because many queries are public. Turning "anonymous" -// into a refusal is the job of the schema directives, per field. +// UserClaimsFromCtx returns nil for anonymous requests; refusing is the +// directives' job. func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims { claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims) if !ok { @@ -37,12 +28,6 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims { return claims } -// UserIDFromCtx returns the authenticated user's id. The claim arrives as a -// float64 because claims are decoded by encoding/json, hence the conversion. -// -// ok is also the test behind the @signedIn directive. A resolver calls this -// itself when it needs the id for more than a gate: to record a post's -// author, or to compare the caller with a row's owner. func UserIDFromCtx(ctx context.Context) (uint, bool) { claims := UserClaimsFromCtx(ctx) if claims == nil { @@ -55,12 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) { return uint(idF), true } -// IsAdminFromCtx reports whether the request carries an admin token. It is -// what the @admin directive tests (directives.go), which is how nearly every -// mutation is authorised; resolvers call it directly only for the softer -// cases a directive cannot express, such as the messages query filtering -// rather than refusing. Admin comes from the token, not the database, so a -// revoked admin flag only bites once the access token expires. +// IsAdminFromCtx reads the token, so a revoked flag applies on expiry. func IsAdminFromCtx(ctx context.Context) bool { claims := UserClaimsFromCtx(ctx) if claims == nil { @@ -70,10 +50,7 @@ func IsAdminFromCtx(ctx context.Context) bool { return ok && admin } -// GinContextFromCtx returns the underlying *gin.Context, which resolvers need -// for things that live outside GraphQL's model: setting auth cookies and -// reading the client IP. Returns nil if the middleware was not installed, -// which the auth resolvers surface as an error rather than panicking. +// GinContextFromCtx is nil if the middleware wasn't installed. func GinContextFromCtx(ctx context.Context) *gin.Context { gc, ok := ctx.Value(ginContextKey).(*gin.Context) if !ok { diff --git a/backend/graph/cover_letter_helpers.go b/backend/graph/cover_letter_helpers.go index eb793f0..8396e99 100644 --- a/backend/graph/cover_letter_helpers.go +++ b/backend/graph/cover_letter_helpers.go @@ -36,18 +36,14 @@ func cleanCoverLetterName(name string) (string, error) { return name, nil } -// coverLetterNameTaken reports whether a live letter other than exceptID has -// this name. Checked up front, like layoutNameTaken, so the admin gets a -// sentence rather than a constraint violation. func coverLetterNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { var count int64 err := db.Model(&models.CoverLetter{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error return count > 0, err } -// checkCoverLetterBody reports why body can't be stored. The server never -// reads inside it, so it only has to be a JSON object of a sane size — an -// array or a bare string would be a frontend bug worth refusing early. +// checkCoverLetterBody: the server never reads inside it, so it need only be a +// JSON object of sane size. func checkCoverLetterBody(body string) error { if len(body) > maxCoverLetterBodyLen { return fmt.Errorf("a cover letter is at most %d KB", maxCoverLetterBodyLen/1024) @@ -60,9 +56,7 @@ func checkCoverLetterBody(body string) error { return nil } -// cleanSnippetText trims text and reports why it can't be a bank paragraph. -// Counted in characters, not bytes, since the limit is about how much prose -// fits rather than storage. +// cleanSnippetText counts characters, not bytes. func cleanSnippetText(text string) (string, error) { text = strings.TrimSpace(text) if text == "" { diff --git a/backend/graph/directives.go b/backend/graph/directives.go index 59abb64..a9b618c 100644 --- a/backend/graph/directives.go +++ b/backend/graph/directives.go @@ -7,34 +7,16 @@ import ( "github.com/99designs/gqlgen/graphql" ) -// The schema's two authorisation directives. A field marked @admin or -// @signedIn in graph/schema/*.graphql has the matching function here run -// before its resolver; if it returns an error the resolver is never called -// and the error is what the client receives for that field. -// -// This replaces a check that used to be copied into the top of every guarded -// resolver. The rule itself is unchanged — it is the same IsAdminFromCtx / -// UserIDFromCtx test against the claims AuthContextMiddleware verified — but -// it is now declared next to the field, where a missing one can be seen and -// tested for (directives_test.go), instead of being a line someone has to -// remember to paste. -// -// The two error strings are part of the contract with the front end, which -// shows them as they are; the tracker page, for one, explains "admin access -// required" as a lapsed session. Do not reword them. -// -// This file is hand-written and never touched by gqlgen. +// The @admin and @signedIn directives. The front end shows these error +// strings verbatim (the tracker reads "admin access required" as a lapsed +// session), so don't reword them. const ( errAdminRequired = "admin access required" errSignedInRequired = "authentication required" ) -// Directives is the set gqlgen needs in graph.Config. It is a function so -// that main and the tests wire exactly the same implementations. -// -// Leaving a directive nil in the Config does not open the fields that use it: -// the generated code answers "directive admin is not implemented" for each. +// Directives is shared by main and the tests. A nil directive fails closed. func Directives() DirectiveRoot { return DirectiveRoot{ Admin: requireAdmin, @@ -42,9 +24,6 @@ func Directives() DirectiveRoot { } } -// requireAdmin implements @admin: the request must carry an access token -// whose admin claim is true. Admin comes from the token, not the database, so -// demoting a user only bites once their access token is replaced. func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) { if !IsAdminFromCtx(ctx) { return nil, fmt.Errorf(errAdminRequired) @@ -52,9 +31,6 @@ func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error return next(ctx) } -// requireSignedIn implements @signedIn: any verified access token will do, -// admin or not. An admin is signed in, so this never needs pairing with -// @admin. func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) { if _, ok := UserIDFromCtx(ctx); !ok { return nil, fmt.Errorf(errSignedInRequired) diff --git a/backend/graph/directives_test.go b/backend/graph/directives_test.go index 844448e..7cfa89e 100644 --- a/backend/graph/directives_test.go +++ b/backend/graph/directives_test.go @@ -20,15 +20,8 @@ import ( "adam-french.co.uk/backend/handlers" ) -// Authorisation is declared in the schema (@admin / @signedIn) and enforced -// by directives.go. These tests cover both halves: that the two functions -// decide correctly, and that the schema marks the fields it should — the -// second being the one that matters day to day, since the way this goes -// wrong is a new field added without a directive. -// -// Nothing here needs a database: a refused field never reaches its resolver, -// and the tests only ever drive fields that are refused or that return before -// touching the Store. +// Covers both the directive functions and which fields carry them. No +// database: refused fields never reach their resolvers. // withClaims builds the context AuthContextMiddleware would for a verified // token. Claims are decoded from JSON in production, hence float64 for the id. @@ -100,9 +93,7 @@ func TestDirectivesAreAllImplemented(t *testing.T) { } } -// guardOf reports which authorisation directive a field carries: "admin", -// "signedIn", or "" for none. Carrying both is a mistake (@signedIn adds -// nothing to @admin) and fails the test rather than being quietly accepted. +// guardOf fails on both directives at once: @signedIn adds nothing to @admin. func guardOf(t *testing.T, field *ast.FieldDefinition) string { t.Helper() admin := field.Directives.ForName("admin") != nil @@ -123,14 +114,8 @@ func schemaUnderTest() *ast.Schema { return NewExecutableSchema(Config{}).Schema() } -// publicMutations is the complete list of mutations that anyone may call. -// A mutation is public only by being named here, so adding one to the schema -// without a directive fails TestEveryMutationIsGuarded until it is either -// guarded or deliberately listed. -// -// All three are how a session is obtained or given up, so they cannot require -// one: login checks a password, refreshToken checks the refresh cookie, and -// logout is a no-op for a visitor who is not signed in. +// publicMutations is the allow-list; any other unguarded mutation fails +// TestEveryMutationIsGuarded. var publicMutations = []string{"login", "logout", "refreshToken"} func TestEveryMutationIsGuarded(t *testing.T) { @@ -159,9 +144,7 @@ func TestEveryMutationIsGuarded(t *testing.T) { } } -// The mutations that need only a session rather than an admin. Pinned so that -// loosening a mutation from @admin to @signedIn — which the test above would -// accept — has to be done here too. +// Pinned so loosening @admin to @signedIn needs a change here. func TestSignedInMutationsArePinned(t *testing.T) { want := []string{"createPlace", "deletePlace", "updatePlace"} var got []string @@ -176,15 +159,8 @@ func TestSignedInMutationsArePinned(t *testing.T) { } } -// Queries are public by default — the home page is built from them — so the -// rule cannot be "every field is guarded". Instead the guarded set is pinned -// exactly: removing a directive from one of these, or adding a query that -// exposes private data without one, has to be a visible change to this map. -// -// Three queries are sensitive to who is asking without being in it, because -// they answer rather than refuse: `me` returns "unauthorized" itself, -// `messages` filters out private rows for non-admins, and -// `spotifyNeedsReauth` is false for non-admins. +// Queries are public by default, so the guarded set is pinned exactly. +// me, messages and spotifyNeedsReauth vary by caller without a directive. func TestGuardedQueriesArePinned(t *testing.T) { want := map[string]string{ "users": "admin", @@ -217,9 +193,7 @@ func TestGuardedQueriesArePinned(t *testing.T) { } } -// The directives are FIELD_DEFINITION only and are meant for the two root -// types. One on an object's field would be enforced, but nothing above would -// notice it being removed, so keep them where the tests look. +// Keep directives on root fields: the tests above only look there. func TestDirectivesOnlyOnRootFields(t *testing.T) { schema := schemaUnderTest() for name, def := range schema.Types { @@ -234,10 +208,7 @@ func TestDirectivesOnlyOnRootFields(t *testing.T) { } } -// execute runs one operation through the real executable schema, wired the -// way main wires it, and returns the response's error messages. The Store is -// empty: every operation below is refused, or returns, before its resolver -// would touch the database. +// execute runs an operation as main wires it, with an empty Store. func execute(t *testing.T, ctx context.Context, query string, variables map[string]any) []string { t.Helper() srv := handler.New(NewExecutableSchema(Config{ @@ -298,9 +269,7 @@ func TestGuardedFieldsRefuseOverTheWire(t *testing.T) { } } -// IDs: the wire form must be what it was when every type had a hand-written -// resolver returning int. Both marshallers write a quoted decimal string and -// both read a string or a number. +// IDs stay quoted decimal strings on the wire, accepting strings or numbers. func TestUintIDWireFormatMatchesIntID(t *testing.T) { for _, id := range []uint{0, 1, 12, 4294967295} { var asUint, asInt bytes.Buffer diff --git a/backend/graph/doc.go b/backend/graph/doc.go index f2f43a1..a84f17e 100644 --- a/backend/graph/doc.go +++ b/backend/graph/doc.go @@ -1,51 +1,15 @@ -// Package graph is the GraphQL layer: the single POST /graphql endpoint that -// serves most of the site's data. +// Package graph is the GraphQL layer behind POST /graphql. // -// How the pieces fit: +// graph/schema/*.graphql is the source of truth; gqlgen regenerates +// generated.go and model/models_gen.go (never edit them). gqlgen.yml maps +// object types onto the GORM structs in backend/models. // -// - graph/schema/*.graphql is the source of truth. Running -// `go run github.com/99designs/gqlgen generate` regenerates generated.go -// and model/models_gen.go, and adds stubs for any new field to the -// matching *.resolvers.go. Never edit those two generated files. -// - gqlgen.yml maps most GraphQL object types straight onto the GORM -// structs in backend/models, so model/ holds only input and payload -// types. A model's `ID uint` binds to `id: ID!` directly, because -// gqlgen.yml lists graphql.UintID for the ID scalar; no resolver is -// needed for it. A field resolver is only written where the Go type has -// no binding (Message.authorId and Rowing's time/distance are unsigned in -// Go and Int in the schema). -// - Resolvers reach the database and the third-party caches through -// Resolver.Store, the same handlers.Store the REST endpoints use. -// - context.go and middleware.go carry the caller's identity from Gin into -// the plain context.Context a resolver receives. +// Nothing guards the endpoint itself. A field is protected only by an +// @admin or @signedIn directive (directives.go); a field with neither is +// public. directives_test.go fails if a mutation has neither and isn't on its +// public allow-list. Finer rules (post ownership, hiding private messages) +// live in resolvers via IsAdminFromCtx / UserIDFromCtx. // -// Authorisation, which is the thing most likely to catch out a newcomer: -// there is NO middleware guarding this endpoint. AuthContextMiddleware only -// annotates the context and lets everything through. What guards a field is a -// directive on it in the schema: -// -// createUser(input: CreateUserInput!): User! @admin -// places: [Place!]! @signedIn -// -// @admin requires an admin's access token, @signedIn any valid one. Both are -// implemented once, in directives.go, and run before the resolver, so a -// guarded resolver contains no check of its own. A field with NEITHER -// directive is fully public. -// -// The rule of thumb in this schema is that queries are public and mutations -// are @admin, with these exceptions: login, logout and refreshToken are -// public; the places mutations and query are @signedIn; and the users -// queries are @admin (they are private data). -// directives_test.go holds that list and fails when the schema departs from -// it — in particular when a mutation is added with no directive. -// -// A directive is only a gate. Anything finer stays in the resolver and uses -// IsAdminFromCtx / UserIDFromCtx directly: a post can only be edited by its -// author, `me` answers for the caller (with its own "unauthorized" error), -// the messages query hides private messages from non-admins rather than -// refusing, and spotifyNeedsReauth is simply false for non-admins. -// -// The files ending in _helpers.go are hand-written and are not touched by -// gqlgen; the *.resolvers.go files are partly generated, so anything added to -// them by hand may be moved to the end of the file on the next generate. +// gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are +// untouched. package graph diff --git a/backend/graph/gitea.resolvers.go b/backend/graph/gitea.resolvers.go index fa29155..9c68140 100644 --- a/backend/graph/gitea.resolvers.go +++ b/backend/graph/gitea.resolvers.go @@ -24,10 +24,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er if err != nil { return nil, err } - // FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed - // would dereference it, so return null to the client instead. The cache - // is deliberately not written in that case, so an empty feed is retried - // on the next request. + // Not cached, so an empty feed is retried next time. if feed == nil { return nil, nil } diff --git a/backend/graph/gitea_helpers.go b/backend/graph/gitea_helpers.go index 58fa22d..ca8bce7 100644 --- a/backend/graph/gitea_helpers.go +++ b/backend/graph/gitea_helpers.go @@ -5,10 +5,7 @@ import ( "adam-french.co.uk/backend/services" ) -// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the -// commit message out of the doubly-encoded Content field as it goes. It -// dereferences feed, so callers must rule out the (nil, nil) that -// FetchLatestFeed returns for an empty feed. +// mapGiteaFeed requires a non-nil feed. func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem { return &model.GiteaFeedItem{ AvatarURL: feed.ActUser.AvatarURL, diff --git a/backend/graph/layout_helpers.go b/backend/graph/layout_helpers.go index d9d0205..69cdef2 100644 --- a/backend/graph/layout_helpers.go +++ b/backend/graph/layout_helpers.go @@ -1,8 +1,5 @@ package graph -// Hand-written helpers for layout.resolvers.go, kept out of the resolver file -// for the same reason as box_helpers.go. - import ( "encoding/json" "errors" @@ -17,9 +14,7 @@ import ( const maxLayoutNameLen = 100 -// layoutBox is one box as a layout stores it: what makes it look the way it -// does, without the id and page that tie a row to one canvas. Changing these -// field names would make older layouts load with the renamed fields empty. +// layoutBox is a box minus id and page. Renaming fields breaks saved layouts. type layoutBox struct { Kind string `json:"kind"` Widget *string `json:"widget,omitempty"` @@ -34,9 +29,7 @@ type layoutBox struct { Shadow string `json:"shadow,omitempty"` HideOnMobile bool `json:"hideOnMobile"` AdminOnly bool `json:"adminOnly"` - // ComponentID is the component a linked box was linked to. HTML is - // stored too, so that a layout outlives the component: loading links the - // box again if the component is still there and uses HTML if not. + // HTML is kept too, so a layout outlives a deleted component. ComponentID *uint `json:"componentId,omitempty"` } @@ -46,7 +39,6 @@ type layoutBackground struct { Fit string `json:"fit"` } -// cleanLayoutName trims name and reports why it can't be a layout's name. func cleanLayoutName(name string) (string, error) { name = strings.TrimSpace(name) if name == "" { @@ -58,18 +50,14 @@ func cleanLayoutName(name string) (string, error) { return name, nil } -// layoutNameTaken reports whether a live layout other than exceptID has this -// name. Checked up front, like slugTaken, so the admin gets a sentence rather -// than a constraint violation. +// Checked up front so the admin gets a sentence, not a constraint violation. func layoutNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) { var count int64 err := db.Model(&models.Layout{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error return count > 0, err } -// canvasExists reports whether page is a canvas boxes can be put on: the -// landing page, or a live Page. Loading a layout onto any other key would -// leave its boxes where nothing shows them. +// canvasExists: boxes on any other key would never be shown. func canvasExists(db *gorm.DB, page string) (bool, error) { if page == "index" { return true, nil @@ -82,16 +70,13 @@ func canvasExists(db *gorm.DB, page string) (bool, error) { return count > 0, err } -// pageBoxes is every box on page, adminOnly ones included, in the order the -// boxes query returns them. Only for admin-only callers. +// pageBoxes includes adminOnly boxes; admin callers only. func pageBoxes(db *gorm.DB, page string) ([]models.Box, error) { var boxes []models.Box err := db.Where("page = ?", page).Order("z ASC, id ASC").Find(&boxes).Error return boxes, err } -// snapshotPage is an unsaved Layout holding page's boxes and background as -// they are now. empty is true when there was nothing to keep. func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) { boxes, err := pageBoxes(db, page) if err != nil { @@ -139,7 +124,6 @@ func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) { return boxes, nil } -// pageLabel is how a page key reads in a generated layout name. func pageLabel(page string) string { if page == "index" { return "/" @@ -147,7 +131,6 @@ func pageLabel(page string) string { return "/" + page } -// uniqueLayoutName is base, or base with " (2)", " (3)"… if that is taken. func uniqueLayoutName(db *gorm.DB, base string) (string, error) { name := base for n := 2; ; n++ { @@ -159,22 +142,17 @@ func uniqueLayoutName(db *gorm.DB, base string) (string, error) { } } -// applyLayoutTo copies layout onto page inside tx; see applyLayout in -// layout.graphql for what replace does. The copies are new rows, so the page -// owns them outright. +// applyLayoutTo creates new rows, so nothing stays linked to the layout. func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool) error { stored, err := decodeLayoutBoxes(layout) if err != nil { return err } - // Added on top, the copies keep their own stacking order but all sit - // above what the page already has. + // Added copies stack above the page's existing boxes. zShift := 0 if replace { - // What is being replaced is kept first, so a replace can be undone by - // loading that layout back. A page with nothing on it has nothing to - // keep. + // Save what's being replaced first, so a replace can be undone. name, err := uniqueLayoutName(tx, fmt.Sprintf("%s before %s, %s", pageLabel(page), layout.Name, time.Now().Format("2 Jan 2006 15:04"))) if err != nil { @@ -234,7 +212,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool } } - // Adding on top leaves the page's own background alone. if replace && layout.Background != nil { var saved layoutBackground if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil { @@ -251,8 +228,6 @@ func applyLayoutTo(tx *gorm.DB, layout *models.Layout, page string, replace bool return nil } -// liveComponents is the set of components the stored boxes were linked to -// that still exist, so applyLayoutTo knows which boxes to link again. func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) { var ids []uint for _, b := range stored { diff --git a/backend/graph/message.resolvers.go b/backend/graph/message.resolvers.go index 3c826ed..77aaac3 100644 --- a/backend/graph/message.resolvers.go +++ b/backend/graph/message.resolvers.go @@ -12,21 +12,15 @@ import ( ) // AuthorID is the resolver for the authorId field. -// AuthorID is the resolver for the authorId field. The value is the chat -// hub's per-connection counter, not a User id — see models.Message. +// The chat hub's connection number, not a User id. func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) { return int(obj.AuthorID), nil } // Messages is the resolver for the messages field. func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) { - // Non-admins get the public subset rather than an error, so the chat - // history loads for everyone. The same filter is applied to the history - // replayed over the WebSocket (services.HandleWebSocket) — change one and - // the other must change too. - // - // Note the ordering differs between the two: newest first here, oldest - // first over the socket. + // Non-admins get the public subset. Keep in step with the WebSocket + // history filter (services.HandleWebSocket), which is oldest first. var messages []models.Message query := r.Store.DB.Order("created_at DESC") if !IsAdminFromCtx(ctx) { diff --git a/backend/graph/middleware.go b/backend/graph/middleware.go index 289e3fa..fcd374e 100644 --- a/backend/graph/middleware.go +++ b/backend/graph/middleware.go @@ -8,39 +8,20 @@ import ( "gorm.io/gorm" ) -// AuthContextMiddleware prepares the request context for the GraphQL handler. -// -// It always attaches the *gin.Context, and attaches the JWT claims only when a -// valid access token is present. Crucially it never rejects a request: a -// missing, expired or forged token simply leaves the context anonymous, which -// is what lets public queries work and leaves every authorisation decision -// to the field being resolved — the @admin / @signedIn directives on it (see -// directives.go), or the resolver itself for anything finer. Both cookie and -// verify errors are swallowed for exactly that reason. -// -// It takes the database because validating a token means loading the user to -// compare token versions; see services.Auth.AuthenticateTokenWithClaims. -// -// Unlike the REST path there is no refresh-token fallback here, so once the -// access token expires GraphQL treats the caller as anonymous until the front -// end refreshes. +// AuthContextMiddleware never rejects: a bad or missing token leaves the +// context anonymous and the directives decide. No refresh fallback. func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc { return func(c *gin.Context) { ctx := context.WithValue(c.Request.Context(), ginContextKey, c) accessToken, err := c.Cookie("access_token") if err == nil { - // The database is needed to check the token version, so a - // revoked token (logout, password change) leaves the request - // anonymous instead of continuing to authorise mutations. _, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken) if err == nil { ctx = context.WithValue(ctx, userClaimsKey, claims) } } - // The context is immutable, so the enriched one has to be written - // back onto the request for the gqlgen handler to see it. c.Request = c.Request.WithContext(ctx) c.Next() } diff --git a/backend/graph/page.resolvers.go b/backend/graph/page.resolvers.go index 284a3e8..6241a72 100644 --- a/backend/graph/page.resolvers.go +++ b/backend/graph/page.resolvers.go @@ -45,9 +45,7 @@ func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePag // UpdatePage is the resolver for the updatePage field. func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) { - // Partial update, like updateBox. A new slug moves the page's boxes and - // background with it in the same transaction, since both find their page - // by slug. + // Partial. A new slug moves the boxes and background in the same transaction. var page models.Page if err := r.Store.DB.First(&page, id).Error; err != nil { return nil, err @@ -134,9 +132,7 @@ func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) { // Page is the resolver for the page field. func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) { - // Null, not an error, for a missing page: the SPA's catch-all route asks - // this for every unknown path and shows its 404 on null. An adminOnly - // page reads as missing to everyone else, so its existence isn't leaked. + // Null for missing or hidden pages: the SPA shows its 404 on null. var page models.Page err := r.Store.DB.Where("slug = ?", slug).First(&page).Error if errors.Is(err, gorm.ErrRecordNotFound) { diff --git a/backend/graph/page_helpers.go b/backend/graph/page_helpers.go index 74e8a35..79e894f 100644 --- a/backend/graph/page_helpers.go +++ b/backend/graph/page_helpers.go @@ -13,20 +13,13 @@ import ( "gorm.io/gorm" ) -// pageKeyPattern is the shape of a box's page key and of a page slug: lower -// case words joined by hyphens, in one or more /-separated segments. It is -// URL-safe as it stands, so the front end can use a slug as a path without -// escaping it. +// Slugs are URL-safe as they stand. var pageKeyPattern = regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*(/[a-z0-9]+(-[a-z0-9]+)*)*$`) const maxSlugLen = 100 -// reservedFirstSegments are paths a page could never be reached at, because -// Caddy or one of the SPA's own routes answers them first (see -// caddy/routes.caddy and vue/src/router/index.js), plus the -// landing page's key "index", whose boxes a page of the same slug would -// share. "shrines" and "stp" are deliberately absent: /shrines, the shrine -// pages under it and the home page /stp are all canvas pages. +// Paths Caddy or the SPA's routes answer first, plus "index". "shrines" and +// "stp" are canvas pages, so not reserved. var reservedFirstSegments = map[string]bool{ "stp2": true, "index": true, "admin": true, "cv": true, "automata": true, "hotels": true, "api": true, "py": true, "radio": true, @@ -51,9 +44,7 @@ func validateSlug(slug string) error { return nil } -// pageHiddenFrom reports whether the page with this key is an adminOnly page -// and the caller is not an admin. A key with no Page row (the landing page, -// or a page that doesn't exist) is not hidden. +// A key with no Page row is never hidden. func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) { if IsAdminFromCtx(ctx) { return false, nil @@ -63,9 +54,7 @@ func pageHiddenFrom(ctx context.Context, db *gorm.DB, key string) (bool, error) return count > 0, err } -// slugTaken reports whether a live page other than exceptID has this slug. -// Checked up front so the admin gets a sentence rather than a constraint -// violation; the partial unique index still backs it up. +// Checked up front for a readable error; the partial unique index backs it. func slugTaken(db *gorm.DB, slug string, exceptID uint) (bool, error) { var count int64 err := db.Model(&models.Page{}).Where("slug = ? AND id <> ?", slug, exceptID).Count(&count).Error diff --git a/backend/graph/place.resolvers.go b/backend/graph/place.resolvers.go index ed5a427..f04b3eb 100644 --- a/backend/graph/place.resolvers.go +++ b/backend/graph/place.resolvers.go @@ -14,10 +14,7 @@ import ( // CreatePlace is the resolver for the createPlace field. func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) { - // Any signed-in user, not just an admin — places are the one shared, - // collaboratively edited list on the site, so the schema marks these - // fields @signedIn rather than @admin. There is no per-user ownership, so - // any signed-in user can edit or delete any place. + // @signedIn: places are the site's one shared list, with no ownership. place := models.Place{ Title: input.Title, Location: input.Location, diff --git a/backend/graph/post.resolvers.go b/backend/graph/post.resolvers.go index 6b7c022..dd4e10b 100644 --- a/backend/graph/post.resolvers.go +++ b/backend/graph/post.resolvers.go @@ -16,16 +16,12 @@ import ( // CreatePost is the resolver for the createPost field. func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) { - // @admin has already established that there is a session; the id is read - // here because the post needs an author, not as a second gate. The !ok - // branch is only reachable with a token that has admin but no usable id. userID, ok := UserIDFromCtx(ctx) if !ok { return nil, fmt.Errorf("unauthorized") } - // The admin form submits whatever is in its fields, so an accidental click - // on an empty form would otherwise publish a blank post to the feed. + // Stops a stray click publishing a blank post. if strings.TrimSpace(input.Title) == "" { return nil, fmt.Errorf("a post needs a title") } @@ -50,15 +46,12 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U return nil, fmt.Errorf("post not found") } - // Admin alone (the @admin on the field) is not enough: a post may only be - // edited by its author, so one admin cannot rewrite another's posts. This - // is the kind of rule a directive cannot express, so it stays here. + // Only the author may edit, even among admins. if post.AuthorID != userID { return nil, fmt.Errorf("you can only update your own posts") } - // Both fields are non-pointer in the input, so this is a full replace — - // omitting one in the mutation blanks it rather than leaving it alone. + // Full replace: an omitted field is blanked. post.Title = input.Title post.Content = input.Content if err := r.Store.DB.Save(&post).Error; err != nil { @@ -84,9 +77,6 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post return nil, fmt.Errorf("you can only delete your own posts") } - // Soft delete. The error is propagated: reporting success for a delete - // that did not happen would leave the client showing the post as gone - // until the next reload. if err := r.Store.DB.Delete(&post).Error; err != nil { return nil, err } @@ -96,9 +86,7 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post // Posts is the resolver for the posts field. func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) { - // Preload issues a second query for the authors and fills in Post.Author. - // Without it the field is nil and the schema's author field resolves to - // null — there is no lazy loading and no error to tell you why. + // Without Preload, author resolves to null silently. var posts []models.Post if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil { return nil, err diff --git a/backend/graph/resolver.go b/backend/graph/resolver.go index ed25757..2e678ec 100644 --- a/backend/graph/resolver.go +++ b/backend/graph/resolver.go @@ -7,17 +7,7 @@ import "adam-french.co.uk/backend/handlers" // It serves as dependency injection for your app, add any dependencies you require // here. -// Resolver is the root of the GraphQL schema and the only dependency every -// resolver has. Rather than listing dependencies individually it holds the -// same handlers.Store the REST handlers use, so GraphQL and REST share one -// database handle and one set of third-party caches. -// -// The generated code embeds *Resolver in per-type resolver structs, which is -// why one-line `struct{ *Resolver }` declarations appear at the bottom of some -// resolvers files. A type only gets one when a field of it needs a resolver: -// queryResolver and mutationResolver always, messageResolver and -// rowingResolver for their unsigned-to-Int fields. Most object types bind -// every field straight to the model and have none. +// Resolver holds the same handlers.Store the REST handlers use. type Resolver struct { Store *handlers.Store } diff --git a/backend/graph/rowing.resolvers.go b/backend/graph/rowing.resolvers.go index 79180f6..962ae5a 100644 --- a/backend/graph/rowing.resolvers.go +++ b/backend/graph/rowing.resolvers.go @@ -21,8 +21,6 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e } // Time is the resolver for the time field. -// Time is the resolver for the time field: total session seconds, narrowed -// from uint64 to GraphQL's Int. func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) { return int(obj.Time), nil } diff --git a/backend/graph/schema/background.graphql b/backend/graph/schema/background.graphql index 7b6e20d..877c3b5 100644 --- a/backend/graph/schema/background.graphql +++ b/backend/graph/schema/background.graphql @@ -1,10 +1,4 @@ -# The background behind a canvas page, keyed by the same page key as its -# boxes ("index" for the landing page, or a Page's slug), so the landing -# page and every other canvas page are set the same way. Edited from the -# canvas's "Background" button; see models.Background. -# -# Anyone may read it, as part of the page, except that an adminOnly page's -# background is null to everyone but an admin. +# A page key's background; null for an adminOnly page unless admin. type Background { id: ID! diff --git a/backend/graph/schema/box.graphql b/backend/graph/schema/box.graphql index 9cacd89..fee4b3e 100644 --- a/backend/graph/schema/box.graphql +++ b/backend/graph/schema/box.graphql @@ -1,13 +1,5 @@ -# Boxes on a canvas page: the landing page (page "index") or an -# admin-created Page (page = its slug; the home page /stp is the Page "stp"). -# Anyone may read a page's layout — it is the page — but only an admin may -# change it, and adminOnly boxes are only ever returned to an admin. x/y/w/h -# are px on a fixed 1400px-wide design canvas; see models.Box. -# -# kind is "widget" (a built-in Vue component named by `widget`) or "html" -# (`html` rendered in a sandboxed iframe on the front end). An html box with a -# componentId is linked to that Component: its html is the component's, and -# updateBox refuses to change it (component.graphql). +# Boxes on a page key. Public reads, admin writes; adminOnly boxes go to +# admins only. kind is "widget" or "html" (sandboxed iframe). type Box { id: ID! diff --git a/backend/graph/schema/component.graphql b/backend/graph/schema/component.graphql index 67703da..dea534d 100644 --- a/backend/graph/schema/component.graphql +++ b/backend/graph/schema/component.graphql @@ -1,13 +1,5 @@ -# Components: named HTML boxes that can be placed on any canvas page, either -# as a copy (an ordinary box) or linked (a Box whose componentId is set). -# Linked boxes share only the html — editing a component changes every box -# linked to it — while title, geometry, frame and visibility stay each box's -# own. title, w, h, framed, shadow and adminOnly here are what a newly placed box -# starts with. See models.Component and graph/component_helpers.go. -# -# Admin only throughout, reads included, because a component may have been -# saved from an adminOnly note. A linked box's html still reaches visitors -# through the boxes query, which is the point. +# Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes +# share only the html. Admin only, reads included. type Component { id: ID! diff --git a/backend/graph/schema/layout.graphql b/backend/graph/schema/layout.graphql index cb14166..b1ead60 100644 --- a/backend/graph/schema/layout.graphql +++ b/backend/graph/schema/layout.graphql @@ -1,12 +1,5 @@ -# Saved layouts: a named copy of one canvas page's boxes and background, -# which can be loaded onto any canvas page — the landing page ("index") or a -# Page's slug. Loading copies: the new boxes belong to the target page, so -# editing a page afterwards never changes the layout or another page. Moving -# a layout is saving it on one page and loading it on another with -# replace: true. See models.Layout and graph/layout_helpers.go. -# -# Admin only throughout, reads included, because a layout keeps a page's -# adminOnly boxes along with the rest. +# Saved snapshots of a page's boxes and background; loading copies them. +# Admin only, reads included, since layouts keep adminOnly boxes. type Layout { id: ID! @@ -39,10 +32,6 @@ extend type Mutation { # Renames it; what a layout holds never changes after it is saved. updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin deleteLayout(id: ID!): Layout! @admin - # Copies the layout onto `page` and answers with that page's boxes. - # replace: false adds the copies on top of what is there, leaving the - # background alone. replace: true first saves the page as a layout named - # " before ,