Compare commits
99
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18265871e1 | ||
|
|
223c8ae35a | ||
|
|
d0ff2e125b | ||
|
|
705804c503 | ||
|
|
eadbc4fac3 | ||
|
|
41d8e70050 | ||
|
|
94a6abba97 | ||
|
|
65f2408ad4 | ||
|
|
46f06a033b | ||
|
|
bfe2fe2782 | ||
|
|
4530cb8dc4 | ||
|
|
effddd2794 | ||
|
|
ed87d04e04 | ||
|
|
180f6ac8b8 | ||
|
|
bb83c6bb03 | ||
|
|
fc777ba8b2 | ||
|
|
31b84b06d4 | ||
|
|
10606f4c77 | ||
|
|
aa4c3b1a67 | ||
|
|
0c2b2fa262 | ||
|
|
082ca4499b | ||
|
|
a40d842518 | ||
|
|
4c77117e60 | ||
|
|
49e38a076b | ||
|
|
930e134fee | ||
|
|
a1943f5c45 | ||
|
|
b6baf9c1a2 | ||
|
|
30d6056bc0 | ||
|
|
daa2a465fb | ||
|
|
e09b90afaa | ||
|
|
89aaf8d79e | ||
|
|
0022429541 | ||
|
|
372f12dbca | ||
|
|
79a9011212 | ||
|
|
8bf70c98e8 | ||
|
|
e764078aaf | ||
|
|
7969859955 | ||
|
|
263e16b70d | ||
|
|
acf21c69c2 | ||
|
|
efd74c1693 | ||
|
|
e181aa09bd | ||
|
|
2eacbc2e33 | ||
|
|
8c535b1cc2 | ||
|
|
3fa456a063 | ||
|
|
1ddaff0690 | ||
|
|
fce6821f84 | ||
|
|
582b190698 | ||
|
|
289b5a5a1d | ||
|
|
0e48befbc7 | ||
|
|
ece1b654c7 | ||
|
|
1af625f5c3 | ||
|
|
14f59a3d28 | ||
|
|
ae961c1cd3 | ||
|
|
3d504da94c | ||
|
|
48e18ba67d | ||
|
|
66db14d0c5 | ||
|
|
e5b19956a2 | ||
|
|
4533b55da0 | ||
|
|
65fddfcfa2 | ||
|
|
422cde4708 | ||
|
|
0ac3321c41 | ||
|
|
45d4aa6eb2 | ||
|
|
529e80242f | ||
|
|
f5ab1e81be | ||
|
|
a244bee184 | ||
|
|
efbec1006f | ||
|
|
58880a4e07 | ||
|
|
604ac32028 | ||
|
|
c9d599a371 | ||
|
|
6d5420fab2 | ||
|
|
602aa522d6 | ||
|
|
3da49f4b24 | ||
|
|
ca3cd4db30 | ||
|
|
e54aaac181 | ||
|
|
967b464779 | ||
|
|
a8c55148af | ||
|
|
30918eefaa | ||
|
|
30e1fb31d8 | ||
|
|
bb5fd2bef9 | ||
|
|
44347e40eb | ||
|
|
c5a722bd1e | ||
|
|
1b5c8fc4a9 | ||
|
|
746f20158e | ||
|
|
d28524e8c0 | ||
|
|
e788e16898 | ||
|
|
f66d9c52ee | ||
|
|
99fe175ebf | ||
|
|
931b02c9e4 | ||
|
|
148b94959d | ||
|
|
da2ab9fb17 | ||
|
|
8b902350ad | ||
|
|
3764ea9c0b | ||
|
|
299b5f5224 | ||
|
|
af50e6c8ab | ||
|
|
810d3118b3 | ||
|
|
b832dd68b4 | ||
|
|
d3f722d077 | ||
|
|
71344a1f8d | ||
|
|
307268fbea |
+53
-1
@@ -1,6 +1,6 @@
|
|||||||
# .deprecated
|
# .deprecated
|
||||||
|
|
||||||
STATUS: nothing in here is live. No compose file, nginx template or script
|
STATUS: nothing in here is live. No compose file, Caddyfile or script
|
||||||
references this directory. It is kept, not deleted, in line with the repo's
|
references this directory. It is kept, not deleted, in line with the repo's
|
||||||
"legacy is kept" convention; the full history is also in git.
|
"legacy is kept" convention; the full history is also in git.
|
||||||
|
|
||||||
@@ -32,3 +32,55 @@ Watchdog that restarted any container docker marked `unhealthy` (only `backend`
|
|||||||
and `python` define healthchecks). It mounts the docker socket, which is
|
and `python` define healthchecks). It mounts the docker socket, which is
|
||||||
effectively root on the host. To bring it back, layer
|
effectively root on the host. To bring it back, layer
|
||||||
`docker-compose.autoheal.yml` the same way as above.
|
`docker-compose.autoheal.yml` the same way as above.
|
||||||
|
|
||||||
|
Since 2026-10-19 it is back in `docker-compose.yml`, watching only containers
|
||||||
|
labelled `autoheal=true` (caddy; nginx until 2026-11-17). This copy is the old
|
||||||
|
`all` variant, kept for reference.
|
||||||
|
|
||||||
|
## nginx/ and certbot/
|
||||||
|
|
||||||
|
The public edge until 2026-11-17, when Caddy (`caddy/`) replaced both:
|
||||||
|
`nginx/` is the image (three templates chosen at start by `entrypoint.sh`,
|
||||||
|
the shared route table, the payload log and security-header includes), and
|
||||||
|
`certbot/entrypoint.sh` obtained and renewed the certificate that nginx
|
||||||
|
reloaded through a sentinel file. Their compose services were removed in
|
||||||
|
`daa2a46`. The last certbot certificate is still in `./certbot/conf` on the
|
||||||
|
host, valid until 2027-01-20.
|
||||||
|
|
||||||
|
To bring them back: revert the commit that moved them here and then `daa2a46`;
|
||||||
|
DEPLOYMENT.md §7 ("Roll back to nginx") has the commands.
|
||||||
|
|
||||||
|
## gitea/
|
||||||
|
|
||||||
|
Gitea as it ran inside this stack on stpvm until 2026-11-24, when it moved to
|
||||||
|
its own Proxmox LXC (`stpgit`, run from the `adamf/stpgit` repo) and stpvm's
|
||||||
|
`gitea` service became a forwarder to it.
|
||||||
|
|
||||||
|
- `docker-compose.gitea.yml` — the old service, with its state mounts
|
||||||
|
repointed at this directory.
|
||||||
|
- `entrypoint.sh` — its app.ini-seeding wrapper, copied here when `gitea/`
|
||||||
|
moved to its own repo, so the rollback does not depend on that repo.
|
||||||
|
- `data/` and `config/app.ini` (gitignored, on stpvm only) — the pre-move
|
||||||
|
copy of the repositories and the live config, moved here from `gitea/`.
|
||||||
|
Gitea's pre-move database is still the `gitea` database in stpvm's `db`.
|
||||||
|
|
||||||
|
To bring it back on stpvm: stop Gitea on stpgit, copy anything pushed since
|
||||||
|
the move back (its `data/`, and a `pg_dump` of `gitea-db` restored into
|
||||||
|
`db`'s `gitea` database), then
|
||||||
|
`docker compose -f docker-compose.yml -f .deprecated/gitea/docker-compose.gitea.yml up -d gitea`.
|
||||||
|
The service still reads `POSTGRES_GITEA_DB` and the three `GITEA_*`
|
||||||
|
secrets from `.env`; stpvm's `.env` still has them, so keep them there until
|
||||||
|
this copy is deleted. Delete `data/`, `config/app.ini` and the old database once the LXC has run
|
||||||
|
cleanly for a few weeks (from about 2026-12-08).
|
||||||
|
|
||||||
|
Since later on 2026-11-24 the stack has no `gitea` service at all (the
|
||||||
|
forwarder is gone) and Gitea's address is `git.<DOMAIN>`, so a rollback
|
||||||
|
also needs: `GITEA_HOST=gitea` in stpvm's `.env` (the containers'
|
||||||
|
`extra_hosts` pin then becomes harmless), the `/gitea/` proxy route back in
|
||||||
|
`caddy/routes.caddy` (revert `180f6ac`), `ROOT_URL` back to
|
||||||
|
`https://<DOMAIN>/gitea/` in `config/app.ini` here, and the CI remotes,
|
||||||
|
`.runner`'s address and Renovate's endpoint back to `localhost`.
|
||||||
|
|
||||||
|
The laptop's own leftovers (an old dev `gitea/data` and `app.ini`, and a
|
||||||
|
stale `gitea-runner/.runner`) are under `dev-leftovers/` here, also
|
||||||
|
gitignored, and can simply be deleted.
|
||||||
|
|||||||
@@ -12,8 +12,24 @@
|
|||||||
# profile, so `docker compose -f docker-compose.yml -f docker-compose.dev.yml
|
# profile, so `docker compose -f docker-compose.yml -f docker-compose.dev.yml
|
||||||
# up` never starts it and dev uses nginx's self-signed localhost cert instead.
|
# up` never starts it and dev uses nginx's self-signed localhost cert instead.
|
||||||
#
|
#
|
||||||
# HOW VALIDATION WORKS (--webroot)
|
# HOW VALIDATION WORKS: DNS-01 (--dns-cloudflare) when CLOUDFLARE_DNS_API_TOKEN
|
||||||
# Let's Encrypt HTTP-01: certbot writes a challenge token into
|
# is set, otherwise HTTP-01 (--webroot)
|
||||||
|
# DNS-01: certbot creates a _acme-challenge TXT record through the Cloudflare
|
||||||
|
# API, Let's Encrypt looks it up, and certbot deletes it. Nothing has to
|
||||||
|
# reach the Pi, which is the point: with the site behind the Cloudflare
|
||||||
|
# tunnel, ports 80 and 443 need not be forwarded at all. The token needs
|
||||||
|
# Zone -> DNS -> Edit on this zone only. certbot insists its credentials
|
||||||
|
# arrive as a mode-600 ini file, not an environment variable, so the script
|
||||||
|
# writes one to /tmp on every start; nothing is stored on disk outside the
|
||||||
|
# container.
|
||||||
|
#
|
||||||
|
# Switching method on an existing certificate: certbot records the method
|
||||||
|
# in renewal/<DOMAIN>.conf and `renew` would keep using webroot. Flags on
|
||||||
|
# the command line override the stored ones, and the next successful
|
||||||
|
# renewal saves them, so the method flags are passed to BOTH commands below.
|
||||||
|
# An unset token after a switch therefore puts it back on webroot, too.
|
||||||
|
#
|
||||||
|
# HTTP-01, the fallback: certbot writes a challenge token into certbot writes a challenge token into
|
||||||
# /var/www/certbot/.well-known/acme-challenge/ and Let's Encrypt fetches it
|
# /var/www/certbot/.well-known/acme-challenge/ and Let's Encrypt fetches it
|
||||||
# over plain HTTP on port 80. certbot itself listens on nothing — nginx is
|
# over plain HTTP on port 80. certbot itself listens on nothing — nginx is
|
||||||
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
|
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
|
||||||
@@ -47,12 +63,14 @@
|
|||||||
# root-equivalent on the host, and the shared cert directory is a capability
|
# root-equivalent on the host, and the shared cert directory is a capability
|
||||||
# both containers already have.
|
# both containers already have.
|
||||||
#
|
#
|
||||||
# ENV VARS REQUIRED (from ./.env via `env_file`)
|
# ENV VARS (from ./.env via `env_file`)
|
||||||
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
|
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
|
||||||
# filed under --cert-name $DOMAIN so the path nginx expects
|
# filed under --cert-name $DOMAIN so the path nginx expects
|
||||||
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
|
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
|
||||||
# name certbot would otherwise have chosen.
|
# name certbot would otherwise have chosen.
|
||||||
# EMAIL registration/expiry-notice address for the ACME account.
|
# EMAIL registration/expiry-notice address for the ACME account.
|
||||||
|
# CLOUDFLARE_DNS_API_TOKEN
|
||||||
|
# optional; selects DNS-01. See HOW VALIDATION WORKS.
|
||||||
#
|
#
|
||||||
# FLAGS WORTH KNOWING
|
# FLAGS WORTH KNOWING
|
||||||
# --agree-tos --non-interactive never prompt; required in a container.
|
# --agree-tos --non-interactive never prompt; required in a container.
|
||||||
@@ -61,9 +79,10 @@
|
|||||||
# rather than erroring out.
|
# rather than erroring out.
|
||||||
#
|
#
|
||||||
# ASSUMES EXISTS
|
# ASSUMES EXISTS
|
||||||
# /var/www/certbot (shared ACME webroot, served by nginx on port 80)
|
|
||||||
# /etc/letsencrypt (persistent cert store, shared with nginx)
|
# /etc/letsencrypt (persistent cert store, shared with nginx)
|
||||||
# Port 80 reachable from the public internet for $DOMAIN and www.$DOMAIN.
|
# Webroot method only: /var/www/certbot (shared ACME webroot, served by
|
||||||
|
# nginx on port 80) and port 80 reachable from the public internet for
|
||||||
|
# $DOMAIN and www.$DOMAIN.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
# The reload sentinel: a file in the SHARED /etc/letsencrypt mount that nginx's
|
# The reload sentinel: a file in the SHARED /etc/letsencrypt mount that nginx's
|
||||||
@@ -71,7 +90,23 @@
|
|||||||
# — see RELOAD SIGNAL above.
|
# — see RELOAD SIGNAL above.
|
||||||
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
|
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
|
||||||
|
|
||||||
certbot certonly --webroot -w /var/www/certbot \
|
if [ -n "${CLOUDFLARE_DNS_API_TOKEN}" ]; then
|
||||||
|
CREDENTIALS=/tmp/cloudflare.ini
|
||||||
|
# umask rather than a chmod afterwards, so the token is never readable
|
||||||
|
# by anyone else even for an instant.
|
||||||
|
(umask 077 && printf 'dns_cloudflare_api_token = %s\n' "${CLOUDFLARE_DNS_API_TOKEN}" >"${CREDENTIALS}")
|
||||||
|
# 30s rather than the plugin's 10: Let's Encrypt queries from several
|
||||||
|
# vantage points, and a lookup that lands before Cloudflare has the record
|
||||||
|
# everywhere fails the whole order.
|
||||||
|
set -- --dns-cloudflare --dns-cloudflare-credentials "${CREDENTIALS}" \
|
||||||
|
--dns-cloudflare-propagation-seconds 30
|
||||||
|
echo "Validating over DNS (Cloudflare API)."
|
||||||
|
else
|
||||||
|
set -- --webroot -w /var/www/certbot
|
||||||
|
echo "Validating over HTTP (webroot); needs port 80 reachable."
|
||||||
|
fi
|
||||||
|
|
||||||
|
certbot certonly "$@" \
|
||||||
--email "${EMAIL}" \
|
--email "${EMAIL}" \
|
||||||
-d "${DOMAIN}" -d "www.${DOMAIN}" \
|
-d "${DOMAIN}" -d "www.${DOMAIN}" \
|
||||||
--cert-name "${DOMAIN}" \
|
--cert-name "${DOMAIN}" \
|
||||||
@@ -82,7 +117,7 @@ certbot certonly --webroot -w /var/www/certbot \
|
|||||||
trap exit TERM;
|
trap exit TERM;
|
||||||
|
|
||||||
while :; do
|
while :; do
|
||||||
certbot renew --webroot -w /var/www/certbot \
|
certbot renew "$@" \
|
||||||
--deploy-hook "touch ${RELOAD_SENTINEL}";
|
--deploy-hook "touch ${RELOAD_SENTINEL}";
|
||||||
sleep 12h;
|
sleep 12h;
|
||||||
done
|
done
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# .deprecated/gitea/docker-compose.gitea.yml — Gitea as it ran on stpvm until
|
||||||
|
# 2026-11-24, kept as the rollback from the move to its own LXC.
|
||||||
|
#
|
||||||
|
# STATUS: not live. Gitea runs on stpgit (the adamf/stpgit repo); stpvm's
|
||||||
|
# `gitea` service is an haproxy forwarder to it.
|
||||||
|
#
|
||||||
|
# This is the old service verbatim except for the two state mounts, which now
|
||||||
|
# point at the pre-move copy moved in beside this file (gitignored). Layered
|
||||||
|
# over docker-compose.yml it replaces the forwarder under the same name;
|
||||||
|
# compose merges the forwarder's GITEA_UPSTREAM and haproxy.cfg mount in
|
||||||
|
# too, and both are harmless to Gitea. Relative paths resolve against the
|
||||||
|
# project directory (the repo root), not this file. See README.md here and
|
||||||
|
# DEPLOYMENT.md §7, "Gitea LXC", for the full rollback.
|
||||||
|
# =============================================================================
|
||||||
|
services:
|
||||||
|
# Self-hosted git, served at /gitea/ and on port 3000 directly. Also the CI
|
||||||
|
# server: .gitea/workflows/deploy.yaml redeploys this whole stack on push to
|
||||||
|
# main, executed by the act_runner that lives outside docker (gitea-runner/).
|
||||||
|
#
|
||||||
|
# ROOTLESS image: runs as an unprivileged user, so config lives in /etc/gitea
|
||||||
|
# and data in /var/lib/gitea (not /data as in the root image) — that is why
|
||||||
|
# the bind mounts look unlike most Gitea compose examples.
|
||||||
|
#
|
||||||
|
# The GITEA__section__KEY environment convention is Gitea's own: each maps to
|
||||||
|
# an app.ini key and overrides the file at runtime, which is how the secrets
|
||||||
|
# stay in .env instead of in the committed app.ini.template.
|
||||||
|
#
|
||||||
|
# entrypoint is overridden to run our wrapper (which materialises app.ini
|
||||||
|
# from the template on first boot) before handing off to Gitea's real
|
||||||
|
# docker-entrypoint.sh. dumb-init is kept as PID 1 for correct signal/zombie
|
||||||
|
# handling, exactly as the stock image does it.
|
||||||
|
gitea:
|
||||||
|
image: docker.gitea.com/gitea:1.25.4-rootless
|
||||||
|
container_name: "${GITEA_HOST}"
|
||||||
|
entrypoint: ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"]
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
environment:
|
||||||
|
- GITEA__database__DB_TYPE=postgres
|
||||||
|
- GITEA__database__HOST=${POSTGRES_HOST}
|
||||||
|
- GITEA__database__NAME=${POSTGRES_GITEA_DB}
|
||||||
|
- GITEA__database__USER=${POSTGRES_USER}
|
||||||
|
- GITEA__database__PASSWD=${POSTGRES_PASSWORD}
|
||||||
|
- GITEA__server__LFS_JWT_SECRET=${GITEA_LFS_JWT_SECRET}
|
||||||
|
- GITEA__security__INTERNAL_TOKEN=${GITEA_INTERNAL_TOKEN}
|
||||||
|
- GITEA__oauth2__JWT_SECRET=${GITEA_OAUTH2_JWT_SECRET}
|
||||||
|
# The host's own name, which Gitea prints in SSH clone URLs. It lives in
|
||||||
|
# .env, not app.ini, so moving to another host is a one-line change;
|
||||||
|
# environment-to-ini writes it into the live app.ini on every start.
|
||||||
|
# localhost suits dev.
|
||||||
|
- GITEA__server__SSH_DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
|
||||||
|
- GITEA__server__DOMAIN=${GITEA_SSH_DOMAIN:-localhost}
|
||||||
|
# Webhooks are refused to private addresses by default ("external").
|
||||||
|
# The usaco site's push hook targets http://usaco:8080 on the Docker
|
||||||
|
# network, so that one host is allowed by name.
|
||||||
|
- GITEA__webhook__ALLOWED_HOST_LIST=external,usaco
|
||||||
|
- USER_UID=1000
|
||||||
|
- USER_GID=1000
|
||||||
|
restart: always
|
||||||
|
volumes:
|
||||||
|
# PERSISTENT: repositories, LFS objects, avatars, sessions. The git data
|
||||||
|
# itself. (Gitea's *relational* data is in Postgres, not here.)
|
||||||
|
- ./.deprecated/gitea/data:/var/lib/gitea
|
||||||
|
# PERSISTENT: app.ini is generated into this host directory on first boot
|
||||||
|
# and then edited by Gitea itself, so it is gitignored — only the
|
||||||
|
# template is committed.
|
||||||
|
- ./.deprecated/gitea/config:/etc/gitea
|
||||||
|
# Mounted over the config dir so the wrapper script is available at the
|
||||||
|
# path the overridden entrypoint points at.
|
||||||
|
- ./.deprecated/gitea/entrypoint.sh:/etc/gitea/entrypoint.sh:ro
|
||||||
|
# Match the Pi's clock/zone so commit and CI timestamps are local time.
|
||||||
|
- /etc/timezone:/etc/timezone:ro
|
||||||
|
- /etc/localtime:/etc/localtime:ro
|
||||||
|
ports:
|
||||||
|
# 2222 = Gitea's *built-in* SSH server (the rootless image cannot use 22).
|
||||||
|
# Clones use ssh://git@host:2222/... — including the deploy workflow,
|
||||||
|
# which fetches from ssh://git@localhost:2222.
|
||||||
|
- "2222:2222"
|
||||||
|
# 3000 = HTTP, published directly as well as proxied at /gitea/, because
|
||||||
|
# the act_runner registers against http://localhost:3000 from the host.
|
||||||
|
- "3000:3000"
|
||||||
|
depends_on:
|
||||||
|
- db
|
||||||
@@ -17,15 +17,15 @@
|
|||||||
# it to re-seed, which loses any UI-made settings).
|
# it to re-seed, which loses any UI-made settings).
|
||||||
#
|
#
|
||||||
# WHEN IT RUNS
|
# WHEN IT RUNS
|
||||||
# Container start. docker-compose.yml overrides gitea's entrypoint to
|
# Container start. gitea/docker-compose.yml overrides gitea's entrypoint to
|
||||||
# ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init
|
# ["/usr/bin/dumb-init", "--", "/etc/gitea/entrypoint.sh"], keeping dumb-init
|
||||||
# as PID 1 for signal handling exactly as the stock image does, and inserting
|
# as PID 1 for signal handling exactly as the stock image does, and inserting
|
||||||
# this script ahead of Gitea's own docker-entrypoint.sh.
|
# this script ahead of Gitea's own docker-entrypoint.sh.
|
||||||
#
|
#
|
||||||
# WHERE THE SECRETS ACTUALLY COME FROM
|
# WHERE THE SECRETS ACTUALLY COME FROM
|
||||||
# Not from the template. docker-compose.yml passes GITEA__section__KEY
|
# Not from the template. gitea/docker-compose.yml passes GITEA__section__KEY
|
||||||
# environment variables (database credentials, LFS_JWT_SECRET,
|
# environment variables (database credentials, LFS_JWT_SECRET,
|
||||||
# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from ./.env; Gitea applies those
|
# INTERNAL_TOKEN, OAUTH2 JWT_SECRET) sourced from gitea/.env; Gitea applies those
|
||||||
# over whatever app.ini says. That is why the template can safely ship with
|
# over whatever app.ini says. That is why the template can safely ship with
|
||||||
# those fields empty.
|
# those fields empty.
|
||||||
#
|
#
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
# nginx image — the public edge. Stock nginx plus two tools and three templates.
|
# nginx image — the public edge. Stock nginx plus two tools, three config
|
||||||
|
# templates, the two partials they include and two static includes.
|
||||||
#
|
#
|
||||||
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are
|
# BASE: nginx:1.27, pinned to a minor version. Official nginx images are
|
||||||
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
|
# multi-arch, so the same tag resolves to the arm64 build on the Raspberry Pi
|
||||||
@@ -19,9 +20,11 @@
|
|||||||
#
|
#
|
||||||
# apt lists are deleted in the SAME RUN layer so they never end up in the image.
|
# apt lists are deleted in the SAME RUN layer so they never end up in the image.
|
||||||
#
|
#
|
||||||
# NO nginx.conf IS COPIED IN. All three templates (plus the dev partial) are,
|
# NO nginx.conf IS COPIED IN. All three templates (plus the two partials) are,
|
||||||
# and entrypoint.sh picks one at container start. See nginx/entrypoint.sh for
|
# and entrypoint.sh picks one at container start. See nginx/entrypoint.sh for
|
||||||
# that decision.
|
# that decision. A new partial needs BOTH a COPY here and an envsubst render in
|
||||||
|
# the entrypoint, or nginx fails at start with "open() ... failed" on the
|
||||||
|
# include.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
FROM nginx:1.27
|
FROM nginx:1.27
|
||||||
RUN rm -rf /etc/nginx/html/* && \
|
RUN rm -rf /etc/nginx/html/* && \
|
||||||
@@ -34,8 +37,18 @@ COPY nginx_dev.conf.template /etc/nginx/nginx_dev.conf.template
|
|||||||
# (same envsubst allow-list) to /etc/nginx/nginx_dev_common.conf, which is the
|
# (same envsubst allow-list) to /etc/nginx/nginx_dev_common.conf, which is the
|
||||||
# path both `include` directives in nginx_dev.conf.template point at.
|
# path both `include` directives in nginx_dev.conf.template point at.
|
||||||
COPY nginx_dev_common.conf.template /etc/nginx/nginx_dev_common.conf.template
|
COPY nginx_dev_common.conf.template /etc/nginx/nginx_dev_common.conf.template
|
||||||
|
# The proxy route table shared by production and dev. entrypoint.sh renders it
|
||||||
|
# (same envsubst allow-list) to /etc/nginx/nginx_routes.conf, the path
|
||||||
|
# nginx.conf.template and nginx_dev_common.conf.template both `include`.
|
||||||
|
COPY nginx_routes.conf.template /etc/nginx/nginx_routes.conf.template
|
||||||
# Static security-header include, referenced from nginx.conf.template (and
|
# Static security-header include, referenced from nginx.conf.template (and
|
||||||
# any location that sets its own add_header). Not templated — no envsubst.
|
# any location that sets its own add_header). Not templated — no envsubst.
|
||||||
COPY security_headers.conf /etc/nginx/security_headers.conf
|
COPY security_headers.conf /etc/nginx/security_headers.conf
|
||||||
|
# Static http-level include for the JSON request-body log (both configs). Not
|
||||||
|
# templated: its $request_body etc. are nginx variables, not env vars.
|
||||||
|
COPY payload_log.conf /etc/nginx/payload_log.conf
|
||||||
|
# The payload log's directory. Normally a bind mount (./logs/nginx); created
|
||||||
|
# here so nginx still starts when run without it.
|
||||||
|
RUN mkdir -p /var/log/nginx/payloads
|
||||||
COPY entrypoint.sh /entrypoint.sh
|
COPY entrypoint.sh /entrypoint.sh
|
||||||
ENTRYPOINT ["/entrypoint.sh"]
|
ENTRYPOINT ["/entrypoint.sh"]
|
||||||
@@ -6,8 +6,11 @@
|
|||||||
# WHAT IT DOES
|
# WHAT IT DOES
|
||||||
# nginx.conf is not shipped in the image. Instead three *templates* are baked
|
# nginx.conf is not shipped in the image. Instead three *templates* are baked
|
||||||
# in (see nginx/Dockerfile) and this script renders exactly one of them to
|
# in (see nginx/Dockerfile) and this script renders exactly one of them to
|
||||||
# /etc/nginx/nginx.conf before starting nginx in the foreground. In dev it
|
# /etc/nginx/nginx.conf before starting nginx in the foreground. It also
|
||||||
# also renders the shared server-block partial the dev template includes.
|
# renders the PARTIALS those templates `include`: the proxy route table
|
||||||
|
# shared by production and dev (nginx_routes.conf, every boot path) and, in
|
||||||
|
# dev only, the body shared by the two dev server blocks
|
||||||
|
# (nginx_dev_common.conf). See RENDERED FILES below.
|
||||||
# After nginx starts, a background watcher handles certificates appearing or
|
# After nginx starts, a background watcher handles certificates appearing or
|
||||||
# being renewed — see CERTIFICATE WATCHER at the bottom of this file.
|
# being renewed — see CERTIFICATE WATCHER at the bottom of this file.
|
||||||
#
|
#
|
||||||
@@ -47,6 +50,19 @@
|
|||||||
# Step (c) IS automatic now. A first deploy on a new domain no longer needs a
|
# Step (c) IS automatic now. A first deploy on a new domain no longer needs a
|
||||||
# manual `docker compose restart nginx`; a restart remains a valid fallback.
|
# manual `docker compose restart nginx`; a restart remains a valid fallback.
|
||||||
#
|
#
|
||||||
|
# RENDERED FILES (template in the image -> path nginx reads)
|
||||||
|
# nginx.conf.template | nginx_dev.conf.template | nginx_setup.conf.template
|
||||||
|
# -> /etc/nginx/nginx.conf (one of three)
|
||||||
|
# nginx_routes.conf.template -> /etc/nginx/nginx_routes.conf
|
||||||
|
# The reverse-proxy locations common to production and dev. Included
|
||||||
|
# by nginx.conf.template directly and by nginx_dev_common.conf. This is
|
||||||
|
# where a new proxied route goes.
|
||||||
|
# nginx_dev_common.conf.template -> /etc/nginx/nginx_dev_common.conf
|
||||||
|
# Dev only: included by both server blocks of nginx_dev.conf.template.
|
||||||
|
# The `include` directives name those rendered paths literally, so a partial
|
||||||
|
# must be written BEFORE anything runs nginx (or `nginx -t`) against a config
|
||||||
|
# that includes it.
|
||||||
|
#
|
||||||
# THE envsubst TEMPLATING PATTERN
|
# THE envsubst TEMPLATING PATTERN
|
||||||
# The templates are plain nginx configs containing $VARIABLES. Two different
|
# The templates are plain nginx configs containing $VARIABLES. Two different
|
||||||
# kinds of $VAR live in the same file:
|
# kinds of $VAR live in the same file:
|
||||||
@@ -71,6 +87,11 @@
|
|||||||
# SILVERBULLET_PUBLIC_HOST / _PORT
|
# SILVERBULLET_PUBLIC_HOST / _PORT
|
||||||
# public notes viewer upstream (defaulted below)
|
# public notes viewer upstream (defaulted below)
|
||||||
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
|
# PYTHON_HOST / PYTHON_PORT FastAPI upstream (defaulted below)
|
||||||
|
# RECEIPT_WEB_UPSTREAM host:port of the receipt printer server on
|
||||||
|
# stppi, over Tailscale (defaulted below to
|
||||||
|
# a dead port, so /receipt/ reads "offline")
|
||||||
|
# RECEIPT_WEB_TOKEN shared secret nginx adds to /receipt/
|
||||||
|
# requests (defaulted below to empty)
|
||||||
# DEV_MODE "true" only via docker-compose.dev.yml
|
# DEV_MODE "true" only via docker-compose.dev.yml
|
||||||
# CERT_WATCH_INTERVAL optional, seconds between certificate-watch
|
# CERT_WATCH_INTERVAL optional, seconds between certificate-watch
|
||||||
# polls (default 60). Production only.
|
# polls (default 60). Production only.
|
||||||
@@ -91,11 +112,30 @@ export SILVERBULLET_HOST="${SILVERBULLET_HOST:-silverbullet}"
|
|||||||
export SILVERBULLET_PORT="${SILVERBULLET_PORT:-3000}"
|
export SILVERBULLET_PORT="${SILVERBULLET_PORT:-3000}"
|
||||||
export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}"
|
export SILVERBULLET_PUBLIC_HOST="${SILVERBULLET_PUBLIC_HOST:-silverbullet-public}"
|
||||||
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
|
export SILVERBULLET_PUBLIC_PORT="${SILVERBULLET_PUBLIC_PORT:-3000}"
|
||||||
|
export RECEIPT_WEB_UPSTREAM="${RECEIPT_WEB_UPSTREAM:-127.0.0.1:9}"
|
||||||
|
export RECEIPT_WEB_TOKEN="${RECEIPT_WEB_TOKEN:-}"
|
||||||
|
|
||||||
# The envsubst allow-list, defined once and reused by both full-config branches
|
# The envsubst allow-list, defined once and reused by both full-config branches
|
||||||
# so the two lists cannot drift apart. It MUST stay single-quoted here and be
|
# and by every partial, so the lists cannot drift apart. It MUST stay
|
||||||
# passed as "$ENVSUBST_VARS" (one argument) below.
|
# single-quoted here and be passed as "$ENVSUBST_VARS" (one argument) below.
|
||||||
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT}'
|
ENVSUBST_VARS='${DOMAIN} ${BACKEND_HOST} ${BACKEND_PORT} ${BACKEND_ENDPOINT} ${ICECAST_HOST} ${ICECAST_PORT} ${GITEA_HOST} ${GITEA_PORT} ${SILVERBULLET_HOST} ${SILVERBULLET_PORT} ${SILVERBULLET_PUBLIC_HOST} ${SILVERBULLET_PUBLIC_PORT} ${PYTHON_HOST} ${PYTHON_PORT} ${RECEIPT_WEB_UPSTREAM} ${RECEIPT_WEB_TOKEN}'
|
||||||
|
|
||||||
|
# Render the shared proxy route table. Done ONCE, here, ahead of the three-way
|
||||||
|
# decision, rather than inside each branch:
|
||||||
|
# - dev and production both include it, so both need it before nginx starts;
|
||||||
|
# - the setup branch does not include it, but the certificate watcher at the
|
||||||
|
# bottom of this file later switches setup -> production by validating a
|
||||||
|
# candidate production config with `nginx -t`, and that candidate includes
|
||||||
|
# this path. Having it already on disk means the watcher has nothing extra
|
||||||
|
# to render and no ordering to get wrong.
|
||||||
|
# It is safe to write straight to the live path (no temp file + validate, as
|
||||||
|
# the watcher does for nginx.conf): this runs before nginx has started, and
|
||||||
|
# its content depends only on the image's template and the container's
|
||||||
|
# environment, neither of which can change while the container lives — so
|
||||||
|
# there is never a newer version to swap in under a running nginx.
|
||||||
|
envsubst "$ENVSUBST_VARS" \
|
||||||
|
</etc/nginx/nginx_routes.conf.template \
|
||||||
|
>/etc/nginx/nginx_routes.conf
|
||||||
|
|
||||||
# Check if DEV_MODE
|
# Check if DEV_MODE
|
||||||
if [ "$DEV_MODE" = "true" ]; then
|
if [ "$DEV_MODE" = "true" ]; then
|
||||||
@@ -112,7 +152,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
|||||||
fi
|
fi
|
||||||
# In dev mode, so use nginx_dev.conf.template. Its two server blocks both
|
# In dev mode, so use nginx_dev.conf.template. Its two server blocks both
|
||||||
# `include /etc/nginx/nginx_dev_common.conf`, so the shared partial has to be
|
# `include /etc/nginx/nginx_dev_common.conf`, so the shared partial has to be
|
||||||
# rendered through the SAME allow-list, into exactly that path, first.
|
# rendered through the SAME allow-list, into exactly that path, first. (That
|
||||||
|
# partial in turn includes nginx_routes.conf, rendered above.)
|
||||||
envsubst "$ENVSUBST_VARS" \
|
envsubst "$ENVSUBST_VARS" \
|
||||||
</etc/nginx/nginx_dev_common.conf.template \
|
</etc/nginx/nginx_dev_common.conf.template \
|
||||||
>/etc/nginx/nginx_dev_common.conf
|
>/etc/nginx/nginx_dev_common.conf
|
||||||
@@ -122,7 +163,8 @@ if [ "$DEV_MODE" = "true" ]; then
|
|||||||
CONFIG_MODE=dev
|
CONFIG_MODE=dev
|
||||||
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencrypt/live/$DOMAIN/privkey.pem" ]; then
|
||||||
echo "Certificates found. Using production nginx config."
|
echo "Certificates found. Using production nginx config."
|
||||||
# In production with certificates already existing, so use nginx.conf.template
|
# In production with certificates already existing, so use nginx.conf.template.
|
||||||
|
# It includes nginx_routes.conf, rendered above.
|
||||||
envsubst "$ENVSUBST_VARS" \
|
envsubst "$ENVSUBST_VARS" \
|
||||||
</etc/nginx/nginx.conf.template \
|
</etc/nginx/nginx.conf.template \
|
||||||
>/etc/nginx/nginx.conf
|
>/etc/nginx/nginx.conf
|
||||||
@@ -130,7 +172,9 @@ elif [ -f "/etc/letsencrypt/live/$DOMAIN/fullchain.pem" ] && [ -f "/etc/letsencr
|
|||||||
else
|
else
|
||||||
echo "Certificates NOT found. Using setup nginx config."
|
echo "Certificates NOT found. Using setup nginx config."
|
||||||
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
# In production with no certificates, so use nginx_setup.conf.template and will need restart after generation
|
||||||
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all.
|
# Only ${DOMAIN} is substituted: the setup config has no upstreams at all
|
||||||
|
# (and does not include nginx_routes.conf — that file is on disk only so the
|
||||||
|
# certificate watcher can switch to the production config later).
|
||||||
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
envsubst '${DOMAIN}' </etc/nginx/nginx_setup.conf.template >/etc/nginx/nginx.conf
|
||||||
CONFIG_MODE=setup
|
CONFIG_MODE=setup
|
||||||
fi
|
fi
|
||||||
@@ -202,6 +246,12 @@ CERT_WATCH_INTERVAL="${CERT_WATCH_INTERVAL:-60}"
|
|||||||
|
|
||||||
# Render the production template to a temp file, validate it, and only then
|
# Render the production template to a temp file, validate it, and only then
|
||||||
# install it. Returns non-zero (installing nothing) if either step fails.
|
# install it. Returns non-zero (installing nothing) if either step fails.
|
||||||
|
# The candidate `include`s /etc/nginx/nginx_routes.conf by absolute path, so
|
||||||
|
# `nginx -t` here validates the shared route table too; that file was rendered
|
||||||
|
# once at the top of this script and is deliberately NOT re-rendered here (it
|
||||||
|
# cannot have changed — see the comment where it is rendered — and rewriting a
|
||||||
|
# file the running nginx may be about to re-read would only add a window in
|
||||||
|
# which it is truncated).
|
||||||
render_prod_config() {
|
render_prod_config() {
|
||||||
_candidate=/tmp/nginx.conf.candidate
|
_candidate=/tmp/nginx.conf.candidate
|
||||||
envsubst "$ENVSUBST_VARS" </etc/nginx/nginx.conf.template >"$_candidate" 2>/dev/null || return 1
|
envsubst "$ENVSUBST_VARS" </etc/nginx/nginx.conf.template >"$_candidate" 2>/dev/null || return 1
|
||||||
@@ -0,0 +1,434 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# nginx.conf.template — PRODUCTION config (steady state, certificates present).
|
||||||
|
#
|
||||||
|
# WHEN IT IS USED
|
||||||
|
# Rendered to /etc/nginx/nginx.conf by nginx/entrypoint.sh when DEV_MODE is
|
||||||
|
# not "true" AND a real certificate exists at
|
||||||
|
# /etc/letsencrypt/live/<DOMAIN>/. The other two templates cover dev
|
||||||
|
# (nginx_dev.conf.template) and first-boot bootstrap
|
||||||
|
# (nginx_setup.conf.template).
|
||||||
|
#
|
||||||
|
# TEMPLATING
|
||||||
|
# Only the names in the envsubst allow-list in nginx/entrypoint.sh are
|
||||||
|
# substituted: DOMAIN, BACKEND_HOST/PORT/ENDPOINT, ICECAST_*, GITEA_*,
|
||||||
|
# SILVERBULLET_*, PYTHON_*. Every other dollar
|
||||||
|
# token in this file is an nginx RUNTIME variable (host, remote_addr, uri,
|
||||||
|
# http_upgrade, proxy_add_x_forwarded_for, binary_remote_addr, request_uri,
|
||||||
|
# scheme, http_cookie) and must be left alone — that restriction is the whole
|
||||||
|
# reason the allow-list exists.
|
||||||
|
#
|
||||||
|
# SERVER BLOCKS (three, in order)
|
||||||
|
# 1. :80 any name -> serves the ACME challenge, 301s everything else to
|
||||||
|
# https://www.DOMAIN. Certbot renewal depends on this
|
||||||
|
# block staying reachable on plain HTTP.
|
||||||
|
# 2. :443 apex -> TLS terminates, then 301s to the www host, so there
|
||||||
|
# is exactly one canonical origin (important: cookies,
|
||||||
|
# CORS and the SPA all assume www).
|
||||||
|
# 3. :443 www -> the real site.
|
||||||
|
#
|
||||||
|
# WHERE THE PROXY ROUTES ARE
|
||||||
|
# Not in this file. The reverse-proxied locations (/api, /radio, /gitea,
|
||||||
|
# /notes, /sb, /py and the admin-gate subrequest) and the `set $upstream_*`
|
||||||
|
# variables are shared with dev and live in nginx_routes.conf.template,
|
||||||
|
# which the www server block includes. ADD NEW PROXIED ROUTES THERE. What
|
||||||
|
# stays here is what only production has: TLS, the redirects, the security
|
||||||
|
# headers, static-asset caching, the SPA fallback, the /uploads/ blocks
|
||||||
|
# (which carry the security headers), the `graphql` rate-limit zone and its
|
||||||
|
# location, and the limit_req_zone declarations the shared routes refer to.
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# One worker per CPU. Unset, nginx runs a single worker, and on 2026-10-19 that
|
||||||
|
# one worker stalled for 4.6 hours: the master kept the container "Up" and the
|
||||||
|
# tunnel stayed connected, but every request timed out in the TLS handshake.
|
||||||
|
# With several workers a stuck one only loses the connections it holds; the
|
||||||
|
# others keep accepting. The healthcheck in docker-compose.yml (and autoheal
|
||||||
|
# restarting on it) covers the case where they all stall.
|
||||||
|
worker_processes auto;
|
||||||
|
|
||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
include /etc/nginx/mime.types;
|
||||||
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
server_tokens off;
|
||||||
|
charset utf-8;
|
||||||
|
|
||||||
|
# Docker's embedded DNS. Required because upstreams are referenced through
|
||||||
|
# `set $upstream_* ...` variables below; using a variable in proxy_pass
|
||||||
|
# makes nginx resolve the name PER REQUEST instead of once at startup.
|
||||||
|
# That is the trick that lets nginx boot even when a backend container is
|
||||||
|
# down or not yet created (it 502s until the container appears, rather than
|
||||||
|
# refusing to start with "host not found in upstream"). valid=10s caps how
|
||||||
|
# long a stale container IP can be cached after a redeploy.
|
||||||
|
resolver 127.0.0.11 valid=10s;
|
||||||
|
|
||||||
|
# Caps request bodies; must be >= the largest allowed chat image upload or
|
||||||
|
# nginx rejects with 413 before the backend ever sees the request.
|
||||||
|
client_max_body_size 50M;
|
||||||
|
|
||||||
|
# ---- Rate limiting -------------------------------------------------------
|
||||||
|
# Each zone is a shared-memory table keyed by $binary_remote_addr (the
|
||||||
|
# client IP in packed 4/16-byte form rather than a string — that is why
|
||||||
|
# "binary": it makes each entry ~64 bytes instead of ~128). 10m therefore
|
||||||
|
# holds roughly 160k distinct IPs, far more than this site will ever see;
|
||||||
|
# 10m is simply the safe round number, not a tuned value. If a zone fills,
|
||||||
|
# nginx evicts the oldest entries and logs a warning.
|
||||||
|
#
|
||||||
|
# `rate` is enforced as a smoothed leaky bucket, not a per-minute counter:
|
||||||
|
# 5r/m means one request allowed every 12 seconds, not 5 at once then
|
||||||
|
# nothing. `burst=N` at the use site allows N requests to queue ahead of
|
||||||
|
# that drip, and `nodelay` (used everywhere here) serves those N
|
||||||
|
# immediately rather than spacing them out — so the practical behaviour is
|
||||||
|
# "N instant requests, then throttled to the drip rate". Anything over the
|
||||||
|
# burst gets 503 immediately.
|
||||||
|
#
|
||||||
|
# Chosen limits and why:
|
||||||
|
# login 5r/m burst=3 - brute-force defence on password auth. A human
|
||||||
|
# mistyping gets 3 instant tries, then one every
|
||||||
|
# 12s. Painless for a real user, useless for a
|
||||||
|
# credential-stuffing script.
|
||||||
|
# api 30r/s burst=20 - generous; a normal SPA page load fans out to
|
||||||
|
# several API calls and must never be throttled.
|
||||||
|
# This is an abuse ceiling, not a quota.
|
||||||
|
# graphql 10r/s burst=10 - tighter than REST because a single GraphQL
|
||||||
|
# query can be arbitrarily expensive to resolve.
|
||||||
|
# (Production only; the dev template omits it.
|
||||||
|
# Its location is at the bottom of this file,
|
||||||
|
# not in the shared route table.)
|
||||||
|
# upload 30r/m burst=20 - uploads hit disk; this bounds how fast one IP
|
||||||
|
# can fill the volume. Generous because only a
|
||||||
|
# signed-in user can upload and accounts are
|
||||||
|
# admin-created, and because dropping a batch of
|
||||||
|
# pictures onto a canvas page uploads them all
|
||||||
|
# at once — the burst lets ~20 through together.
|
||||||
|
# hotel_search 3r/m burst=2 - each request holds an upstream call to
|
||||||
|
# Travelodge/TfL for up to a few minutes and the
|
||||||
|
# Python side has a single search slot, so this is
|
||||||
|
# really concurrency protection, not abuse
|
||||||
|
# protection.
|
||||||
|
#
|
||||||
|
# NOTE: the key is the client IP, which is only right because of the
|
||||||
|
# real-IP lines below. Traffic through the Cloudflare tunnel reaches nginx
|
||||||
|
# from the cloudflared container, so without them every tunnel visitor
|
||||||
|
# would share that one address and one bucket.
|
||||||
|
#
|
||||||
|
# login, api, upload and hotel_search are USED from
|
||||||
|
# nginx_routes.conf.template, which dev includes too — so
|
||||||
|
# nginx_dev.conf.template must declare the same four zones, or the dev
|
||||||
|
# config fails to load with "zero size shared memory zone".
|
||||||
|
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||||
|
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||||
|
limit_req_zone $binary_remote_addr zone=graphql:10m rate=10r/s;
|
||||||
|
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
|
||||||
|
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
|
||||||
|
|
||||||
|
# ---- Real client IP behind the Cloudflare tunnel -------------------------
|
||||||
|
# For connections from the cloudflared container, and only those, replace
|
||||||
|
# $remote_addr with the visitor's address from Cloudflare's
|
||||||
|
# CF-Connecting-IP header. Everything downstream then just works: the
|
||||||
|
# rate-limit keys above, the access log, and the X-Real-IP /
|
||||||
|
# X-Forwarded-For headers sent upstream.
|
||||||
|
#
|
||||||
|
# The trust is pinned to cloudflared's fixed address (ipv4_address in
|
||||||
|
# docker-compose.yml; change both together), NOT the whole app-network
|
||||||
|
# subnet. Direct visitors on the forwarded 80/443 can arrive from the
|
||||||
|
# bridge gateway, 172.28.0.1, when docker's userland proxy handles the
|
||||||
|
# connection, so trusting the subnet would let anyone pick their own IP,
|
||||||
|
# and so their own rate-limit bucket, by sending the header themselves.
|
||||||
|
# Production only: dev has no tunnel.
|
||||||
|
set_real_ip_from 172.28.255.250;
|
||||||
|
real_ip_header CF-Connecting-IP;
|
||||||
|
|
||||||
|
log_format compact
|
||||||
|
'$remote_addr "$request" $status rt=$request_time';
|
||||||
|
|
||||||
|
access_log /var/log/nginx/access.log compact;
|
||||||
|
|
||||||
|
# JSON request-body log for Dozzle; see payload_log.conf.
|
||||||
|
include /etc/nginx/payload_log.conf;
|
||||||
|
|
||||||
|
# nginx's bundled mime.types has no entry for .mjs, so ES modules would be
|
||||||
|
# served as application/octet-stream and browsers refuse to execute them.
|
||||||
|
# This adds the missing mapping without editing the shipped mime.types.
|
||||||
|
types {
|
||||||
|
text/javascript mjs;
|
||||||
|
}
|
||||||
|
|
||||||
|
# TLS protocol versions, pinned: nginx's defaults still include TLSv1 and
|
||||||
|
# TLSv1.1, which are deprecated and fail modern compliance scans.
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_tickets off;
|
||||||
|
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_proxied any;
|
||||||
|
gzip_comp_level 6;
|
||||||
|
gzip_min_length 256;
|
||||||
|
gzip_types
|
||||||
|
text/plain
|
||||||
|
text/css
|
||||||
|
text/javascript
|
||||||
|
application/javascript
|
||||||
|
application/json
|
||||||
|
application/xml
|
||||||
|
image/svg+xml
|
||||||
|
font/woff2
|
||||||
|
application/font-woff2;
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name $DOMAIN www.$DOMAIN;
|
||||||
|
|
||||||
|
# Allow Certbot to access the ACME challenge
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The container healthcheck's target (docker-compose.yml). Answered by
|
||||||
|
# nginx itself, so it measures whether a worker is serving and nothing
|
||||||
|
# upstream. Unlogged, or it would put a line in the payload log every
|
||||||
|
# 30s. Every config's default :80 server has one, setup and dev too.
|
||||||
|
location = /nginx-health {
|
||||||
|
access_log off;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Redirect everything else to HTTPS
|
||||||
|
location / {
|
||||||
|
return 301 https://www.$DOMAIN$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name $DOMAIN;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
||||||
|
|
||||||
|
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
|
||||||
|
|
||||||
|
# Gitea's container registry, which publishes images such as
|
||||||
|
# $DOMAIN/adamf/job-tracker. Docker always talks to /v2/ at the root
|
||||||
|
# of the host, whatever Gitea's ROOT_URL says, and Gitea advertises
|
||||||
|
# its token endpoint at https://$DOMAIN/v2/token: on the apex, not
|
||||||
|
# under /gitea/ and not on www. So the apex serves /v2/ itself rather
|
||||||
|
# than redirecting it; a redirect on a blob upload is not something
|
||||||
|
# every Docker client follows. Everything else still goes to www.
|
||||||
|
#
|
||||||
|
# The redirect is a `location /` rather than the server-level return
|
||||||
|
# it used to be, because a server-level return runs before any
|
||||||
|
# location is chosen. The HSTS add_header above is inherited by both
|
||||||
|
# locations, which declare none of their own.
|
||||||
|
location /v2/ {
|
||||||
|
# Image layers are far larger than the http block's 50M, and are
|
||||||
|
# streamed to Gitea rather than spooled to disk first.
|
||||||
|
client_max_body_size 0;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_read_timeout 900s;
|
||||||
|
proxy_send_timeout 900s;
|
||||||
|
# $upstream_gitea is set in nginx_routes.conf, which only the www
|
||||||
|
# server includes.
|
||||||
|
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||||
|
proxy_pass $upstream_gitea;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 301 https://www.$DOMAIN$request_uri;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
http2 on;
|
||||||
|
server_name www.$DOMAIN;
|
||||||
|
|
||||||
|
# The `set $upstream_*` variables used by proxy_pass are declared in
|
||||||
|
# nginx_routes.conf (included below), alongside the routes that use
|
||||||
|
# them.
|
||||||
|
|
||||||
|
root /etc/nginx/html;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/$DOMAIN/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/$DOMAIN/privkey.pem;
|
||||||
|
|
||||||
|
# Security headers live in nginx/security_headers.conf and are
|
||||||
|
# included there instead of here, because any location that declares
|
||||||
|
# so much as one add_header of its own otherwise inherits none of
|
||||||
|
# these (nginx's add_header inheritance is all-or-nothing).
|
||||||
|
# The shared proxy routes in nginx_routes.conf rely on exactly this
|
||||||
|
# server-level include: none of them declares an add_header, so they
|
||||||
|
# all inherit these headers here, and inherit nothing in dev.
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
|
||||||
|
# Vite hashed assets - immutable, cache 1 year
|
||||||
|
location /assets/ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fonts - cache 30 days
|
||||||
|
location /fonts/ {
|
||||||
|
expires 30d;
|
||||||
|
add_header Cache-Control "public";
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Images - cache 7 days
|
||||||
|
location /img/ {
|
||||||
|
expires 7d;
|
||||||
|
add_header Cache-Control "public";
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||||
|
# messages are written by the backend to /backend/uploads/private/ and
|
||||||
|
# must not be readable by the public, so this subpath is put behind the
|
||||||
|
# same admin `auth_request` used for /sb/. nginx picks
|
||||||
|
# the LONGEST matching prefix location, so this block wins over the
|
||||||
|
# public /uploads/ block below for /uploads/private/* regardless of
|
||||||
|
# ordering. Same three hardening headers as the public block, because
|
||||||
|
# the bytes are just as attacker-supplied.
|
||||||
|
location /uploads/private/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
alias /uploads/private/;
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# User-uploaded files, served by nginx so the Go process never has to
|
||||||
|
# stream them. Because these are attacker-supplied bytes on our own
|
||||||
|
# origin, three headers neutralise them: nosniff stops content-type
|
||||||
|
# guessing, Content-Disposition inline keeps them from being treated
|
||||||
|
# as downloads, and the locked-down CSP means even an uploaded .html
|
||||||
|
# can run no script and load no resource.
|
||||||
|
#
|
||||||
|
# GARAGE FIRST, DISK SECOND. /uploads/<name> is fetched from the
|
||||||
|
# Garage bucket's website endpoint, which serves the bucket
|
||||||
|
# anonymously and picks it by the Host header (garage/garage.toml:
|
||||||
|
# s3_web); the bucket is reachable only over app-network, so this is
|
||||||
|
# the only public way in. If Garage has no such file, or is down, the
|
||||||
|
# request falls through to the shared `uploads` volume
|
||||||
|
# (@uploads_disk), which holds uploads from before Garage and anything
|
||||||
|
# the backend wrote there because Garage refused it
|
||||||
|
# (backend/services/uploads.go). So the bucket is the source of truth
|
||||||
|
# — deleting a file in garage-webui unpublishes it unless a disk copy
|
||||||
|
# exists — while a Garage outage only costs files that are nowhere
|
||||||
|
# else.
|
||||||
|
# proxy_connect_timeout 2s - Garage is on the same bridge network,
|
||||||
|
# so a slow connect means it is down; fall back quickly rather
|
||||||
|
# than after the 60s default.
|
||||||
|
# proxy_intercept_errors + error_page - Garage's 404 and any 5xx
|
||||||
|
# (including nginx's own 502 when the garage container doesn't
|
||||||
|
# exist) become a look at the disk instead.
|
||||||
|
# Range requests pass through either way, so video seeks.
|
||||||
|
# @uploads_disk sees the URI after the rewrite (/<name>), hence
|
||||||
|
# `root /uploads`. The headers are repeated, not inherited: a named
|
||||||
|
# location is its own location.
|
||||||
|
location /uploads/ {
|
||||||
|
rewrite ^/uploads/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_garage_web;
|
||||||
|
proxy_set_header Host uploads.web.garage;
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
error_page 404 500 502 503 504 = @uploads_disk;
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @uploads_disk {
|
||||||
|
root /uploads;
|
||||||
|
try_files $uri =404;
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# SPA fallback: serve the file if it exists, otherwise hand index.html
|
||||||
|
# to the browser so Vue Router can resolve the path client-side. This
|
||||||
|
# is what makes deep links like /notes-page or /admin work on refresh.
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /robots.txt {
|
||||||
|
allow all;
|
||||||
|
log_not_found off;
|
||||||
|
access_log off;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Belt-and-braces: HTTP-01 validation always happens on port 80 (the
|
||||||
|
# :80 block above), so this duplicate on :443 never actually serves a
|
||||||
|
# challenge. Harmless, and kept in case a future challenge type or a
|
||||||
|
# redirect chain lands here. Note it is a regex location (~), so it
|
||||||
|
# matches the path anywhere in the URI, not just at the start.
|
||||||
|
location ~ /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
# One-off: this GIF is a "web stamp" other people's sites hot-link, so
|
||||||
|
# it needs an explicit CORS header. It is a public, deliberately
|
||||||
|
# hot-linkable image, so the allowed origin is `*` — it used to be our
|
||||||
|
# own origin, which defeated the point (no cross-origin embedder was
|
||||||
|
# actually permitted). Nothing here is credentialed, so `*` is safe.
|
||||||
|
location = /img/stamps/mine.gif {
|
||||||
|
add_header Access-Control-Allow-Origin "*";
|
||||||
|
expires 7d;
|
||||||
|
add_header Cache-Control "public";
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /sound/ {
|
||||||
|
expires 7d;
|
||||||
|
add_header Cache-Control "public";
|
||||||
|
include /etc/nginx/security_headers.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Shared proxy route table ----------------------------------------
|
||||||
|
# Every reverse-proxied location (/api, /radio, /gitea, /notes, /sb,
|
||||||
|
# /py), the admin auth_request gate and the `set $upstream_*` variables
|
||||||
|
# come from nginx_routes.conf.template, rendered by the entrypoint to
|
||||||
|
# this path and shared with the dev config. The prefix-strip rewrite,
|
||||||
|
# the forwarding headers and the websocket upgrade are annotated there.
|
||||||
|
#
|
||||||
|
# Position matters for one thing only: regex locations are tried in
|
||||||
|
# file order, so the ACME regex above stays ahead of the /notes and
|
||||||
|
# /py/hotels regexes inside this include, as it always was.
|
||||||
|
include /etc/nginx/nginx_routes.conf;
|
||||||
|
|
||||||
|
# GraphQL, PRODUCTION ONLY — which is why it is here and not in the
|
||||||
|
# shared table. Longest-prefix matching makes it win over the shared
|
||||||
|
# $BACKEND_ENDPOINT/ catch-all, swapping the general `api` limit for
|
||||||
|
# the tighter `graphql` zone declared at the top of this file. Dev has
|
||||||
|
# no such location, so GraphQL there falls under `api`. Apart from the
|
||||||
|
# limit_req line the body must stay identical to $BACKEND_ENDPOINT/ in
|
||||||
|
# nginx_routes.conf.template.
|
||||||
|
location $BACKEND_ENDPOINT/graphql {
|
||||||
|
limit_req zone=graphql burst=10 nodelay;
|
||||||
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -11,8 +11,7 @@
|
|||||||
# for Vite's HMR websocket, not for the app.
|
# for Vite's HMR websocket, not for the app.
|
||||||
# - No HTTP->HTTPS redirect and no apex->www redirect: BOTH :80 and :443
|
# - No HTTP->HTTPS redirect and no apex->www redirect: BOTH :80 and :443
|
||||||
# serve the full site, so http://localhost just works. The two server
|
# serve the full site, so http://localhost just works. The two server
|
||||||
# blocks are therefore near-identical copies of each other (see the
|
# blocks therefore share one body, nginx_dev_common.conf.template.
|
||||||
# duplication note in DEPLOYMENT.md).
|
|
||||||
# - TLS uses the self-signed /etc/letsencrypt/live/localhost/ certificate that
|
# - TLS uses the self-signed /etc/letsencrypt/live/localhost/ certificate that
|
||||||
# the entrypoint generates, not a Let's Encrypt one. Browsers will warn.
|
# the entrypoint generates, not a Let's Encrypt one. Browsers will warn.
|
||||||
# - No HSTS or other security headers — HSTS on localhost would poison the
|
# - No HSTS or other security headers — HSTS on localhost would poison the
|
||||||
@@ -26,11 +25,18 @@
|
|||||||
# Same envsubst allow-list as production. Every other dollar token is an
|
# Same envsubst allow-list as production. Every other dollar token is an
|
||||||
# nginx runtime variable and must survive substitution untouched.
|
# nginx runtime variable and must survive substitution untouched.
|
||||||
#
|
#
|
||||||
# For the rate-limit reasoning, the prefix-strip rewrite, the four forwarding
|
# INCLUDE CHAIN
|
||||||
# headers, the websocket upgrade block and the auth_request admin gate, see the
|
# this file -> nginx_dev_common.conf (once per server block: the dev-only
|
||||||
# fully-annotated equivalents in nginx.conf.template — the mechanics here are
|
# /uploads/ and `/` locations) -> nginx_routes.conf (the proxy route table
|
||||||
# identical.
|
# shared with production). The prefix-strip rewrite, the four forwarding
|
||||||
|
# headers, the websocket upgrade block and the auth_request admin gate are
|
||||||
|
# annotated in nginx_routes.conf.template; the rate-limit reasoning is in
|
||||||
|
# nginx.conf.template.
|
||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
|
# As in production; why is in nginx.conf.template.
|
||||||
|
worker_processes auto;
|
||||||
|
|
||||||
events {
|
events {
|
||||||
worker_connections 1024;
|
worker_connections 1024;
|
||||||
}
|
}
|
||||||
@@ -46,9 +52,13 @@ http {
|
|||||||
|
|
||||||
client_max_body_size 50M;
|
client_max_body_size 50M;
|
||||||
|
|
||||||
|
# These four zones are referenced by limit_req lines in the SHARED
|
||||||
|
# nginx_routes.conf.template, so they must exist here with the same names
|
||||||
|
# as in nginx.conf.template or nginx refuses to load the config. Rates are
|
||||||
|
# kept equal to production so a limit that would bite there bites here too.
|
||||||
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
|
||||||
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
limit_req_zone $binary_remote_addr zone=api:10m rate=30r/s;
|
||||||
limit_req_zone $binary_remote_addr zone=upload:10m rate=5r/m;
|
limit_req_zone $binary_remote_addr zone=upload:10m rate=30r/m;
|
||||||
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
|
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
|
||||||
|
|
||||||
log_format compact
|
log_format compact
|
||||||
@@ -56,6 +66,9 @@ http {
|
|||||||
|
|
||||||
access_log /var/log/nginx/access.log compact;
|
access_log /var/log/nginx/access.log compact;
|
||||||
|
|
||||||
|
# JSON request-body log for Dozzle; see payload_log.conf.
|
||||||
|
include /etc/nginx/payload_log.conf;
|
||||||
|
|
||||||
types {
|
types {
|
||||||
text/javascript mjs;
|
text/javascript mjs;
|
||||||
}
|
}
|
||||||
@@ -80,6 +93,13 @@ http {
|
|||||||
listen 80;
|
listen 80;
|
||||||
server_name $DOMAIN www.$DOMAIN;
|
server_name $DOMAIN www.$DOMAIN;
|
||||||
|
|
||||||
|
# The container healthcheck's target; see nginx.conf.template. Only in
|
||||||
|
# this block, as in production, where it sits in the :80 server too.
|
||||||
|
location = /nginx-health {
|
||||||
|
access_log off;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
include /etc/nginx/nginx_dev_common.conf;
|
include /etc/nginx/nginx_dev_common.conf;
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# nginx_dev_common.conf.template — SHARED BODY of the dev :80 and :443 server
|
||||||
|
# blocks.
|
||||||
|
#
|
||||||
|
# WHY THIS FILE EXISTS
|
||||||
|
# In dev the :80 and :443 server blocks are byte-for-byte identical apart
|
||||||
|
# from `listen` and the self-signed `ssl_certificate` pair. They used to be
|
||||||
|
# ~190 duplicated lines, so every routing fix had to be made twice and could
|
||||||
|
# silently drift. Both blocks now `include` this partial instead.
|
||||||
|
#
|
||||||
|
# HOW IT IS RENDERED
|
||||||
|
# nginx/entrypoint.sh runs the SAME envsubst allow-list over this file as
|
||||||
|
# over nginx_dev.conf.template, writing the result to
|
||||||
|
# /etc/nginx/nginx_dev_common.conf — which is exactly the path the two
|
||||||
|
# `include` directives in the rendered nginx.conf point at. If you add
|
||||||
|
# a new substituted variable here, it must also be added to ENVSUBST_VARS in
|
||||||
|
# the entrypoint, or it will reach nginx unsubstituted.
|
||||||
|
#
|
||||||
|
# WHAT BELONGS HERE
|
||||||
|
# Only what dev does DIFFERENTLY from production inside a server block: the
|
||||||
|
# /uploads/ locations without security headers, and `/` proxied to Vite.
|
||||||
|
# Everything else — the `set $upstream_*` vars and every reverse-proxied
|
||||||
|
# route — is in nginx_routes.conf.template, shared with production and
|
||||||
|
# included at the bottom of this file. ADD NEW PROXIED ROUTES THERE, not
|
||||||
|
# here.
|
||||||
|
# NOT `listen`, `server_name` or the ssl_certificate lines (those differ
|
||||||
|
# between the two blocks), and NOT the enclosing braces — this file must be
|
||||||
|
# brace-balanced on its own.
|
||||||
|
#
|
||||||
|
# This is the DEV file only. Production's single :443 www server block in
|
||||||
|
# nginx.conf.template includes nginx_routes.conf directly.
|
||||||
|
# =============================================================================
|
||||||
|
# PRIVATE attachments (admin-only). Attachments on *private* chat
|
||||||
|
# messages are written by the backend to /backend/uploads/private/ and
|
||||||
|
# must not be readable by the public, so this subpath is put behind the
|
||||||
|
# same admin `auth_request` used for /sb/. nginx picks
|
||||||
|
# the LONGEST matching prefix location, so this block wins over the
|
||||||
|
# public /uploads/ block below for /uploads/private/* regardless of
|
||||||
|
# ordering. Same three hardening headers as the public block, because
|
||||||
|
# the bytes are just as attacker-supplied.
|
||||||
|
location /uploads/private/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
alias /uploads/private/;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The /uploads/ blocks (and @uploads_disk) are the production ones MINUS
|
||||||
|
# `include security_headers.conf`: that file carries HSTS, which must
|
||||||
|
# never be sent from localhost. That one line is why they are not in
|
||||||
|
# the shared route table (see WHAT DOES NOT in
|
||||||
|
# nginx_routes.conf.template). Keep the rest in step with
|
||||||
|
# nginx.conf.template.
|
||||||
|
location /uploads/ {
|
||||||
|
rewrite ^/uploads/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_garage_web;
|
||||||
|
proxy_set_header Host uploads.web.garage;
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_intercept_errors on;
|
||||||
|
error_page 404 500 502 503 504 = @uploads_disk;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @uploads_disk {
|
||||||
|
root /uploads;
|
||||||
|
try_files $uri =404;
|
||||||
|
add_header X-Content-Type-Options nosniff always;
|
||||||
|
add_header Content-Disposition "inline" always;
|
||||||
|
add_header Content-Security-Policy "default-src 'none'; img-src 'self'; style-src 'none'; script-src 'none'" always;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The Vite dev server; Upgrade/Connection carry its HMR websocket.
|
||||||
|
location / {
|
||||||
|
proxy_pass http://vue:5173;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Every other route, shared with production. This file has no regex
|
||||||
|
# locations of its own, so where the include sits is cosmetic.
|
||||||
|
include /etc/nginx/nginx_routes.conf;
|
||||||
@@ -0,0 +1,681 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# nginx_routes.conf.template — the PROXY ROUTE TABLE shared by production and
|
||||||
|
# dev. Add a new proxied route HERE, once.
|
||||||
|
#
|
||||||
|
# WHY THIS FILE EXISTS
|
||||||
|
# nginx.conf.template (production) and nginx_dev_common.conf.template (dev)
|
||||||
|
# used to each carry their own copy of these ~25 locations, so every new
|
||||||
|
# route was two edits and the copies could drift — which matters more than
|
||||||
|
# usual here, because this table holds the admin auth gates (/sb/,
|
||||||
|
# /radio/admin/), the /py/internal/ 404 and the /notes privacy denials. A
|
||||||
|
# route that exists in one copy but not the other is a hole that only shows
|
||||||
|
# up in the environment you were not testing.
|
||||||
|
#
|
||||||
|
# WHO INCLUDES IT
|
||||||
|
# - nginx.conf.template, inside its :443 www server block.
|
||||||
|
# - nginx_dev_common.conf.template, which is itself included by BOTH dev
|
||||||
|
# server blocks — so in dev this file is pulled in twice. That is fine:
|
||||||
|
# each inclusion lands in a different `server`, and everything below is
|
||||||
|
# server-scoped.
|
||||||
|
#
|
||||||
|
# HOW IT IS RENDERED
|
||||||
|
# nginx/entrypoint.sh runs the SAME envsubst allow-list over this file as
|
||||||
|
# over the main templates and writes the result to
|
||||||
|
# /etc/nginx/nginx_routes.conf, the path the `include` directives name. It
|
||||||
|
# does so on every boot path, before the main config is chosen. A new
|
||||||
|
# substituted variable used here must be added to ENVSUBST_VARS in the
|
||||||
|
# entrypoint, or it reaches nginx unsubstituted.
|
||||||
|
#
|
||||||
|
# WHAT BELONGS HERE
|
||||||
|
# The `set $upstream_*` variables and every reverse-proxied location that
|
||||||
|
# behaves the same in production and dev, plus the admin-gate subrequest
|
||||||
|
# they rely on. It must stay brace-balanced on its own (no enclosing
|
||||||
|
# `server {`).
|
||||||
|
#
|
||||||
|
# WHAT DOES NOT, AND WHY
|
||||||
|
# - add_header, in any location here. nginx's add_header inheritance is
|
||||||
|
# all-or-nothing: a location with none of its own inherits the including
|
||||||
|
# server block's set. Production's server block includes
|
||||||
|
# security_headers.conf (HSTS etc.) and dev's deliberately does not, so
|
||||||
|
# leaving these locations header-free is what lets the same text carry
|
||||||
|
# security headers in production and none on localhost. Adding a single
|
||||||
|
# add_header to a location below would silently drop production's
|
||||||
|
# security headers from it.
|
||||||
|
# - /uploads/ and /uploads/private/. They need add_header lines of their
|
||||||
|
# own AND, in production only, security_headers.conf alongside them, so
|
||||||
|
# for the reason above they cannot be shared. Each template has its copy;
|
||||||
|
# keep the auth_request pair on /uploads/private/ identical in both.
|
||||||
|
# - `location /`. Production serves the built SPA from disk, dev proxies to
|
||||||
|
# the Vite dev server.
|
||||||
|
# - $BACKEND_ENDPOINT/graphql. Production-only, with its own tighter
|
||||||
|
# rate-limit zone; in dev GraphQL falls through to $BACKEND_ENDPOINT/
|
||||||
|
# below. It lives in nginx.conf.template.
|
||||||
|
# - Static asset caching, robots.txt, the ACME challenge and TLS: production
|
||||||
|
# only, in nginx.conf.template.
|
||||||
|
#
|
||||||
|
# RATE LIMITS
|
||||||
|
# The limit_req lines below name the zones `login`, `upload`, `api` and
|
||||||
|
# `hotel_search`. A zone must be declared with limit_req_zone in the `http`
|
||||||
|
# block of whichever config includes this file, or nginx refuses to load it
|
||||||
|
# — so BOTH nginx.conf.template and nginx_dev.conf.template declare all
|
||||||
|
# four (same rates; the reasoning is annotated in the production one). If
|
||||||
|
# you use a new zone here, declare it in both.
|
||||||
|
#
|
||||||
|
# ORDER
|
||||||
|
# Prefix locations are matched longest-first, so their order here is
|
||||||
|
# cosmetic. REGEX locations (`~`, `~*`) are tried in file order and the
|
||||||
|
# first match wins: keep the two /notes deny regexes ahead of the
|
||||||
|
# /py/hotels one, and remember production's ACME regex location is declared
|
||||||
|
# before this file is included.
|
||||||
|
# =============================================================================
|
||||||
|
set $upstream_backend http://$BACKEND_HOST:$BACKEND_PORT;
|
||||||
|
set $upstream_icecast http://$ICECAST_HOST:$ICECAST_PORT;
|
||||||
|
set $upstream_gitea http://$GITEA_HOST:$GITEA_PORT;
|
||||||
|
set $upstream_silverbullet http://$SILVERBULLET_HOST:$SILVERBULLET_PORT;
|
||||||
|
set $upstream_silverbullet_public http://$SILVERBULLET_PUBLIC_HOST:$SILVERBULLET_PUBLIC_PORT;
|
||||||
|
set $upstream_python http://$PYTHON_HOST:$PYTHON_PORT;
|
||||||
|
# The job tracker's container name is fixed in docker-compose.yml, so
|
||||||
|
# it needs no variable (and no ENVSUBST_VARS entry).
|
||||||
|
set $upstream_jobs http://jobs:8080;
|
||||||
|
# Likewise the activity tracker's.
|
||||||
|
set $upstream_tracker http://activity-tracker:8080;
|
||||||
|
# And the USACO site's.
|
||||||
|
set $upstream_usaco http://usaco:8080;
|
||||||
|
# And the Dozzle log viewer's.
|
||||||
|
set $upstream_dozzle http://dozzle:8080;
|
||||||
|
# Garage: its website endpoint (where /uploads/ is served from; see the
|
||||||
|
# /uploads/ location in nginx.conf.template and
|
||||||
|
# nginx_dev_common.conf.template) and the garage-webui admin UI.
|
||||||
|
set $upstream_garage_web http://garage:3902;
|
||||||
|
set $upstream_garage_webui http://garage-webui:3909;
|
||||||
|
# The receipt printer's server is the one upstream OFF this host: it
|
||||||
|
# runs on stppi, which reaches the printer over the home LAN, and is
|
||||||
|
# reached over Tailscale by IP (MagicDNS names don't resolve in this
|
||||||
|
# container).
|
||||||
|
set $upstream_receipt "http://${RECEIPT_WEB_UPSTREAM}";
|
||||||
|
|
||||||
|
# ---- Backend API -----------------------------------------------------
|
||||||
|
# Two patterns repeat through every proxied location below:
|
||||||
|
#
|
||||||
|
# 1. THE PREFIX-STRIP REWRITE
|
||||||
|
# rewrite ^<PREFIX>/(.*)$ /$1 break;
|
||||||
|
# The public URL carries a prefix (/api, /radio, /gitea, /py) but the upstream service serves its routes from /. The
|
||||||
|
# rewrite strips the prefix and `break` stops rewrite processing so
|
||||||
|
# the request stays in this location and goes to proxy_pass with the
|
||||||
|
# rewritten URI. (This is why proxy_pass here has no trailing path —
|
||||||
|
# with a variable upstream, nginx would not do the strip for us.)
|
||||||
|
# The bare `location <PREFIX>` blocks that 301 to `<PREFIX>/` exist
|
||||||
|
# only so a user typing /gitea without the slash lands correctly.
|
||||||
|
#
|
||||||
|
# 2. THE FOUR FORWARDING HEADERS
|
||||||
|
# Host preserve the browser's hostname so the app
|
||||||
|
# builds correct absolute URLs and cookies.
|
||||||
|
# X-Real-IP the true client IP (the upstream otherwise
|
||||||
|
# sees only nginx's container IP).
|
||||||
|
# X-Forwarded-For appends the client to any existing chain.
|
||||||
|
# X-Forwarded-Proto tells the app the ORIGINAL request was
|
||||||
|
# https even though this hop is plain http.
|
||||||
|
# Without it the backend would issue
|
||||||
|
# non-Secure cookies and http:// redirects,
|
||||||
|
# breaking auth behind TLS termination.
|
||||||
|
#
|
||||||
|
# Ordering matters: nginx picks the longest matching prefix location,
|
||||||
|
# so the specific /ws, /auth/login and /uploads blocks (and
|
||||||
|
# production's /graphql block in nginx.conf.template) win over the
|
||||||
|
# catch-all <PREFIX>/ block regardless of file order.
|
||||||
|
location $BACKEND_ENDPOINT {
|
||||||
|
return 301 $BACKEND_ENDPOINT/;
|
||||||
|
}
|
||||||
|
|
||||||
|
# WebSocket endpoint (live chat / activity feed).
|
||||||
|
# The three lines that make an upgrade work, and why each is needed:
|
||||||
|
# proxy_http_version 1.1 - HTTP/1.0 has no Upgrade mechanism at all.
|
||||||
|
# Upgrade $http_upgrade - hop-by-hop headers are NOT forwarded by
|
||||||
|
# Connection "upgrade" default, so they must be re-set by hand.
|
||||||
|
# Note the Connection value is hardcoded rather than using the usual
|
||||||
|
# $connection_upgrade map: this location only ever serves websockets, so
|
||||||
|
# there is no plain-HTTP case to fall back to.
|
||||||
|
# Deliberately NOT rate limited — a websocket is one long-lived request
|
||||||
|
# and a limit_req here would drop reconnect storms, not abuse.
|
||||||
|
location $BACKEND_ENDPOINT/ws {
|
||||||
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location $BACKEND_ENDPOINT/auth/login {
|
||||||
|
limit_req zone=login burst=3 nodelay;
|
||||||
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location $BACKEND_ENDPOINT/uploads {
|
||||||
|
limit_req zone=upload burst=20 nodelay;
|
||||||
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Catch-all for the REST API. In production GraphQL does NOT land here:
|
||||||
|
# nginx.conf.template declares a longer $BACKEND_ENDPOINT/graphql
|
||||||
|
# location with a tighter zone. In dev it does.
|
||||||
|
location $BACKEND_ENDPOINT/ {
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
rewrite ^$BACKEND_ENDPOINT/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /radio {
|
||||||
|
return 301 /radio/;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Dozzle: live view of every container's logs, including the `traffic`
|
||||||
|
# container's JSON request-body log (see payload_log.conf). It reads
|
||||||
|
# the Docker socket, so it sits behind the same admin `auth_request`
|
||||||
|
# as /radio/admin/. No prefix-strip rewrite: DOZZLE_BASE=/dozzle makes
|
||||||
|
# it serve under the prefix itself. Buffering is off and the read
|
||||||
|
# timeout long because log tails stream over server-sent events.
|
||||||
|
location = /dozzle {
|
||||||
|
return 301 /dozzle/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /dozzle/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
proxy_pass $upstream_dozzle;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_read_timeout 1h;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# garage-webui: buckets, keys and a file browser for the Garage object
|
||||||
|
# store. It holds Garage's admin token, so it sits behind the admin
|
||||||
|
# `auth_request` like /dozzle/, and its own login is left unset (one
|
||||||
|
# login, not two). No prefix-strip rewrite: BASE_PATH=/garage makes it
|
||||||
|
# serve under the prefix itself. The body limit is lifted past the
|
||||||
|
# server-wide 50M so videos can be uploaded through it, and request
|
||||||
|
# buffering is off so a large upload streams through instead of
|
||||||
|
# landing on nginx's disk first.
|
||||||
|
location = /garage {
|
||||||
|
return 301 /garage/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /garage/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
client_max_body_size 2G;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_pass $upstream_garage_webui;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The icecast ADMIN UI (/radio/admin/*) is a full station-control
|
||||||
|
# surface — kick sources, change metadata — protected only by the
|
||||||
|
# icecast admin password, and it was reachable from the public
|
||||||
|
# internet through this proxy. Put it behind the same admin
|
||||||
|
# `auth_request` as /sb/ so an admin session cookie is
|
||||||
|
# required before the request ever reaches icecast. Longest-prefix
|
||||||
|
# matching means this wins over /radio/ below; listener traffic
|
||||||
|
# (/radio/$ICECAST_MOUNT, /radio/status.xsl) is untouched.
|
||||||
|
location /radio/admin/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
rewrite ^/radio/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_icecast;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /radio/ {
|
||||||
|
rewrite ^/radio/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_icecast;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /gitea {
|
||||||
|
return 301 /gitea/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /gitea/ {
|
||||||
|
rewrite ^/gitea/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_gitea;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Gitea's history views and archives, behind the admin gate. A crawler
|
||||||
|
# swarm (129k requests from 103k IPs over 2026-10-18/19, so per-IP rate
|
||||||
|
# limits are useless) walks every file at every commit, and those pages
|
||||||
|
# are the expensive ones: diffs, blame, tarballs nginx spools to disk.
|
||||||
|
# 89% of its requests were these shapes; people browsing the code use
|
||||||
|
# the branch views (src/branch/..., commits/branch/...), which stay
|
||||||
|
# public, so the CV's repo links still work. Gitea's own
|
||||||
|
# REQUIRE_SIGNIN_VIEW=expensive would also block src/branch, hence
|
||||||
|
# doing it here. A regex location, so it wins over /gitea/ above.
|
||||||
|
location ~ ^/gitea/[^/]+/[^/]+/((src|raw|blame|commits|media)/commit/|commit/|archive/|compare/) {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
rewrite ^/gitea/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_gitea;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /notes {
|
||||||
|
return 301 /notes/;
|
||||||
|
}
|
||||||
|
|
||||||
|
# PUBLIC notes viewer: a second, read-only SilverBullet over the same
|
||||||
|
# vault the /sb/ editor edits. No auth_request — this is the public
|
||||||
|
# site. See the silverbullet-public service in docker-compose.yml.
|
||||||
|
#
|
||||||
|
# THE DENY BLOCKS BELOW ARE THE PRIVACY BOUNDARY, not decoration.
|
||||||
|
# SB_SPACE_IGNORE only hides paths from the file LIST. Everything else
|
||||||
|
# happily serves them (all verified against 2.11.0 with curl):
|
||||||
|
# /notes/.fs/private/x.md raw file, straight off disk
|
||||||
|
# /notes/private/x the page URL: the server pre-renders the
|
||||||
|
# note's content into the HTML shell
|
||||||
|
# /notes/.fs/.git/... the vault's whole git repo, i.e. every
|
||||||
|
# version of every private note ever
|
||||||
|
# and gitignore semantics mean `private/` in SB_SPACE_IGNORE hides a
|
||||||
|
# private/ folder at ANY depth from the list, so the block must too.
|
||||||
|
#
|
||||||
|
# 1. private/ or templates/ as any path segment, page URL or /.fs/.
|
||||||
|
# ~* so Private/ is caught; (/|$) so the folder itself matches.
|
||||||
|
# 2. Any dot-segment below the first: .git, .obsidian, .env, ... The
|
||||||
|
# first segment is exempt because that is where SilverBullet's own
|
||||||
|
# endpoints live (/.fs, /.config, /.client, /.events ...). Nothing
|
||||||
|
# the client legitimately loads has a dot-segment deeper than that.
|
||||||
|
# nginx matches against the normalised URI (percent-decoded, `..`
|
||||||
|
# resolved, slashes merged), so %2F, // or ../ tricks cannot slip past.
|
||||||
|
# Keep the folder list in step with SB_SPACE_IGNORE on
|
||||||
|
# silverbullet-public. 404 rather than 403 so the response does not
|
||||||
|
# confirm a private path exists.
|
||||||
|
location ~* ^/notes/(.*/)?(private|templates)(/|$) {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ~ ^/notes/.+/\. {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Revisions are read from the vault's own .git, i.e. the full history
|
||||||
|
# of every file INCLUDING private/ and anything ever deleted.
|
||||||
|
# SB_REVISIONS=disabled already turns this off upstream; this is the
|
||||||
|
# second lock in case that env var is ever dropped. ^~ so no regex
|
||||||
|
# location can take precedence.
|
||||||
|
location ^~ /notes/.revisions {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Same as /sb/: deliberately NO prefix-strip rewrite. The app is told
|
||||||
|
# its base path via SB_URL_PREFIX=/notes and builds its service worker
|
||||||
|
# scope and asset URLs from it; strip the prefix and it loads blank.
|
||||||
|
# Upgrade/Connection are for its live-update event stream.
|
||||||
|
location /notes/ {
|
||||||
|
proxy_pass $upstream_silverbullet_public;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /sb {
|
||||||
|
return 301 /sb/;
|
||||||
|
}
|
||||||
|
|
||||||
|
# SilverBullet: the admin-only EDITOR for the vault /notes/ publishes.
|
||||||
|
# Deliberately NO prefix-strip rewrite, unlike every other proxied app
|
||||||
|
# here. SilverBullet is a PWA told its own base path via SB_URL_PREFIX=/sb,
|
||||||
|
# and its service worker scope and asset URLs are built from that. Strip
|
||||||
|
# the prefix and the app loads a blank page with no error in the log.
|
||||||
|
# Upgrade/Connection are for its sync websocket.
|
||||||
|
location /sb/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
proxy_pass $upstream_silverbullet;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /py {
|
||||||
|
return 301 /py/;
|
||||||
|
}
|
||||||
|
|
||||||
|
# /py/hotels/search[/stream] and /py/hotels/scan/stream: long-running NDJSON streams
|
||||||
|
location ~ ^/py/hotels/(search|scan) {
|
||||||
|
# Public, up-to-a-minute upstream call with a single search slot: keep it to a few per minute per IP
|
||||||
|
limit_req zone=hotel_search burst=2 nodelay;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_send_timeout 300s;
|
||||||
|
# The stream variant sends NDJSON progress lines; pass them through as they arrive
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_cache off;
|
||||||
|
gzip off;
|
||||||
|
rewrite ^/py/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_python;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# /py/internal/: routes the Go backend calls directly over app-network
|
||||||
|
# (the rowing photo reader and the job posting reader, which spend a
|
||||||
|
# paid Claude call and have no auth of their own). Never proxied. ^~ so no regex location can claim
|
||||||
|
# the path first. The Python side also refuses anything carrying the
|
||||||
|
# X-Real-IP / X-Forwarded-For headers set below, as a second layer.
|
||||||
|
location ^~ /py/internal/ {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
location /py/ {
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
# Hotel search blocks for up to a few minutes while it calls Travelodge and TfL
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_send_timeout 300s;
|
||||||
|
rewrite ^/py/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_python;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Job tracker (/jobs/) ----
|
||||||
|
# Its own container (the adamf/job-tracker repo), which serves its SPA
|
||||||
|
# and its API from the same prefix. The prefix is NOT stripped: the
|
||||||
|
# app is built to live at /jobs/. Gated like /sb/: everything under
|
||||||
|
# /jobs/ needs the admin session, checked here by auth_request before
|
||||||
|
# the app sees it (the app still checks the session itself too). Two
|
||||||
|
# exceptions, below, that a session cookie can never reach. ^~ so no
|
||||||
|
# regex location can claim a /jobs/ path.
|
||||||
|
location = /jobs {
|
||||||
|
return 301 /jobs/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /jobs/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
# "Sync now" on the Settings page runs a whole email sync before
|
||||||
|
# answering.
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_pass $upstream_jobs;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The capture API is called by the userscript from job sites' origins,
|
||||||
|
# with the capture bearer token rather than cookies, so it cannot pass
|
||||||
|
# the session gate; the app's CaptureTokenMiddleware guards it.
|
||||||
|
location ^~ /jobs/api/capture {
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
proxy_pass $upstream_jobs;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# The userscript itself: userscript managers fetch its @updateURL
|
||||||
|
# without the session, and it holds no secrets (the token is entered
|
||||||
|
# after install).
|
||||||
|
location = /jobs/job-capture.user.js {
|
||||||
|
proxy_pass $upstream_jobs;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- USACO practice log (/usaco/) ----
|
||||||
|
# Its own container (the usaco repo's site/), shaped like /jobs/: SPA
|
||||||
|
# and API under one prefix that is NOT stripped, and no
|
||||||
|
# auth_request, because most of it is public and the app checks the
|
||||||
|
# session itself for the admin's edits. Gitea's push webhook does not
|
||||||
|
# come through here: it calls the container directly on the Docker
|
||||||
|
# network. ^~ so no regex location can claim a /usaco/ path.
|
||||||
|
location = /usaco {
|
||||||
|
return 301 /usaco/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /usaco/ {
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
# An admin edit commits and pushes to Gitea before answering.
|
||||||
|
proxy_read_timeout 120s;
|
||||||
|
proxy_pass $upstream_usaco;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Activity tracker (/tracker/) ----
|
||||||
|
# Its own container (the adamf/ccp repo): an ingest API for device
|
||||||
|
# collectors, which send batches of events with a per-device bearer
|
||||||
|
# key, plus a dashboard and setup page. Gated like /sb/: the pages
|
||||||
|
# and their assets need the admin session, checked here by
|
||||||
|
# auth_request (the app also checks it itself). Two exceptions,
|
||||||
|
# below: the API, which collectors call with bearer keys and no
|
||||||
|
# cookies (the app guards each route, by device key, admin session or
|
||||||
|
# either), and the public /tracker.user.js. Unlike /jobs/ the prefix
|
||||||
|
# IS stripped: the server serves /api/v1/... and /readyz from /.
|
||||||
|
# Collectors must use the www host: the apex 301 would turn their
|
||||||
|
# POSTs into GETs. Health Auto Export bodies can be several MB; the
|
||||||
|
# server-wide 50M client_max_body_size covers them.
|
||||||
|
location = /tracker {
|
||||||
|
return 301 /tracker/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /tracker/ {
|
||||||
|
auth_request /internal/auth/admin-validate;
|
||||||
|
error_page 401 403 = @auth_denied;
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
rewrite ^/tracker/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_tracker;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /tracker/api/v1/ {
|
||||||
|
limit_req zone=api burst=20 nodelay;
|
||||||
|
rewrite ^/tracker/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_tracker;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location = /tracker/tracker.user.js {
|
||||||
|
rewrite ^/tracker/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_tracker;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Receipt printer (/receipt/) ----
|
||||||
|
# The adamf/receipt_maker repo's `receipt serve`, running on stppi
|
||||||
|
# (not in this stack: that machine reaches the printer on the home LAN). A page
|
||||||
|
# for printing a note or an uploaded image, plus its API. Behind the
|
||||||
|
# permission gate on `receipt`, so an account granted it in the admin
|
||||||
|
# panel can print without being an admin; the prefix IS stripped. The
|
||||||
|
# server trusts nothing without X-Receipt-Token, which only this proxy
|
||||||
|
# adds (proxy_set_header replaces any copy the client sent), and is
|
||||||
|
# told who is printing in X-Remote-User, likewise only set here. The
|
||||||
|
# token is quoted so an unset one still renders a valid config. When
|
||||||
|
# stppi is off or unreachable the connect fails fast and
|
||||||
|
# @receipt_offline answers.
|
||||||
|
location = /receipt {
|
||||||
|
return 301 /receipt/;
|
||||||
|
}
|
||||||
|
|
||||||
|
location ^~ /receipt/ {
|
||||||
|
set $auth_permission receipt;
|
||||||
|
auth_request /internal/auth/validate;
|
||||||
|
auth_request_set $auth_user $upstream_http_x_auth_user;
|
||||||
|
error_page 401 = @auth_denied;
|
||||||
|
error_page 403 = @auth_forbidden;
|
||||||
|
error_page 502 504 = @receipt_offline;
|
||||||
|
limit_req zone=api burst=10 nodelay;
|
||||||
|
# The server caps uploads at 16 MB; this leaves room for the
|
||||||
|
# multipart framing around one.
|
||||||
|
client_max_body_size 17m;
|
||||||
|
rewrite ^/receipt/(.*)$ /$1 break;
|
||||||
|
proxy_pass $upstream_receipt;
|
||||||
|
proxy_connect_timeout 3s;
|
||||||
|
# An image print (connect, dither, send) takes a few seconds; a
|
||||||
|
# dead printer socket gives up after escpos's 60 s timeout.
|
||||||
|
proxy_read_timeout 90s;
|
||||||
|
proxy_set_header X-Receipt-Token "${RECEIPT_WEB_TOKEN}";
|
||||||
|
proxy_set_header X-Remote-User $auth_user;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @receipt_offline {
|
||||||
|
default_type text/plain;
|
||||||
|
return 503 "The receipt printer machine is offline.\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Where the tracker used to be. The SPA routes were client-side, so
|
||||||
|
# these only catch bookmarks and typed URLs. The userscript's old
|
||||||
|
# @updateURL lands on the third, which is how installed copies find
|
||||||
|
# version 2.0.0 and its new API base.
|
||||||
|
location = /cv/jobs {
|
||||||
|
return 301 /jobs/;
|
||||||
|
}
|
||||||
|
location = /cv/leads {
|
||||||
|
return 301 /jobs/leads;
|
||||||
|
}
|
||||||
|
location = /job-capture.user.js {
|
||||||
|
return 301 /jobs/job-capture.user.js;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Admin gate (/sb/, /jobs/, /tracker/, /dozzle/, /garage/, /radio/admin/, /uploads/private/) ----
|
||||||
|
# (/uploads/private/ is declared in the including template, not here;
|
||||||
|
# it points at the two locations below by name.)
|
||||||
|
# `auth_request` makes nginx fire a subrequest here before serving the
|
||||||
|
# real one; a 2xx lets it through, 401/403 triggers error_page ->
|
||||||
|
# @auth_denied -> redirect to the SPA login. This puts the Go backend's
|
||||||
|
# session cookie in front of services that have no idea it exists.
|
||||||
|
# internal; - unreachable from outside, subrequest only.
|
||||||
|
# proxy_pass_request_body off + Content-Length ""
|
||||||
|
# - the subrequest must not replay the
|
||||||
|
# original body (it could be a 50MB
|
||||||
|
# upload); clearing Content-Length stops
|
||||||
|
# the backend waiting for a body that is
|
||||||
|
# not coming.
|
||||||
|
# Cookie $http_cookie - the whole point: forward the session
|
||||||
|
# cookie so the backend can validate it.
|
||||||
|
# client_max_body_size 0 - the subrequest is checked against THIS
|
||||||
|
# location's limit using the original
|
||||||
|
# request's Content-Length, so without it
|
||||||
|
# a gated location with a higher limit
|
||||||
|
# (/garage/, 2G) 413s inside the auth
|
||||||
|
# check and the user sees a 500. Safe:
|
||||||
|
# the location is internal and never
|
||||||
|
# reads a body; the real limit is the
|
||||||
|
# gated location's own.
|
||||||
|
location = /internal/auth/admin-validate {
|
||||||
|
internal;
|
||||||
|
client_max_body_size 0;
|
||||||
|
rewrite ^ /auth/validate-admin break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_pass_request_body off;
|
||||||
|
proxy_set_header Content-Length "";
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @auth_denied {
|
||||||
|
return 302 /admin/login?redirect=$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Permission gate (/receipt/) ----
|
||||||
|
# The same auth_request mechanism as the admin gate above, but asking
|
||||||
|
# GET /auth/validate/<key> whether the session holds one named
|
||||||
|
# permission (services/permissions.go; admins hold them all). A gated
|
||||||
|
# location sets $auth_permission and points auth_request here:
|
||||||
|
#
|
||||||
|
# set $auth_permission <key>;
|
||||||
|
# auth_request /internal/auth/validate;
|
||||||
|
# error_page 401 = @auth_denied;
|
||||||
|
# error_page 403 = @auth_forbidden;
|
||||||
|
#
|
||||||
|
# The variable reaches the subrequest because nginx subrequests share
|
||||||
|
# the parent request's variables, and `set` runs in the rewrite phase,
|
||||||
|
# before auth_request's access phase. It must NOT also be given a
|
||||||
|
# default at server level: a subrequest re-runs the server-level
|
||||||
|
# rewrite phase, so that `set` would blank the shared value before
|
||||||
|
# this location reads it. (A location that forgets to set it asks for
|
||||||
|
# /auth/validate/, which matches no route: denied.) 401 (not signed in) goes to the
|
||||||
|
# login page as before; 403 (signed in, not granted) goes to a page
|
||||||
|
# that says so, since sending a signed-in user to log in again only
|
||||||
|
# shows them "Already signed in". On success the backend returns the
|
||||||
|
# username in X-Auth-User, which a location can forward with
|
||||||
|
# auth_request_set (see /receipt/). The body/limit settings are the
|
||||||
|
# admin-validate location's, for the same reasons.
|
||||||
|
location = /internal/auth/validate {
|
||||||
|
internal;
|
||||||
|
client_max_body_size 0;
|
||||||
|
rewrite ^ /auth/validate/$auth_permission break;
|
||||||
|
proxy_pass $upstream_backend;
|
||||||
|
proxy_pass_request_body off;
|
||||||
|
proxy_set_header Content-Length "";
|
||||||
|
proxy_set_header Cookie $http_cookie;
|
||||||
|
}
|
||||||
|
|
||||||
|
location @auth_forbidden {
|
||||||
|
return 302 /no-access?path=$request_uri;
|
||||||
|
}
|
||||||
@@ -45,6 +45,12 @@ http {
|
|||||||
root /var/www/certbot;
|
root /var/www/certbot;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# The container healthcheck's target; see nginx.conf.template.
|
||||||
|
location = /nginx-health {
|
||||||
|
access_log off;
|
||||||
|
return 204;
|
||||||
|
}
|
||||||
|
|
||||||
# All other requests should return 404
|
# All other requests should return 404
|
||||||
location / {
|
location / {
|
||||||
return 404;
|
return 404;
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# Payload log: one JSON line per request, body included, for inspecting what
|
||||||
|
# actually arrives at the edge. Included at http level by BOTH nginx.conf and
|
||||||
|
# nginx_dev.conf, so it is plain nginx (no envsubst) like security_headers.conf.
|
||||||
|
#
|
||||||
|
# WHERE IT GOES
|
||||||
|
# /var/log/nginx/payloads/ is bind-mounted from ./logs/nginx on the host.
|
||||||
|
# The `traffic` container tails the file to its stdout so Dozzle (/dozzle/)
|
||||||
|
# shows it as its own clean stream of JSON. The `compact` access log is
|
||||||
|
# untouched and still goes to the container's stdout.
|
||||||
|
#
|
||||||
|
# WHAT IS NOT CAPTURED
|
||||||
|
# - Bodies larger than client_body_buffer_size: nginx spools those to a
|
||||||
|
# temp file and leaves $request_body empty. Uploads therefore log with an
|
||||||
|
# empty body (their size is still in `len`).
|
||||||
|
# - Bodies of requests nginx answers itself (redirects, static files): it
|
||||||
|
# never reads them, so $request_body is empty there too.
|
||||||
|
# - Responses. nginx cannot log a proxied response body.
|
||||||
|
# - auth_request subrequests: log_subrequest is off by default.
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# 64k keeps ordinary JSON/GraphQL bodies in memory (the default is 16k on
|
||||||
|
# 64-bit), which is the only case where $request_body is filled. It is a
|
||||||
|
# per-request buffer only allocated when a body arrives, so the cost is small.
|
||||||
|
client_body_buffer_size 64k;
|
||||||
|
|
||||||
|
# Redaction: any body mentioning a password, token or secret is logged as a
|
||||||
|
# placeholder rather than having the field stripped, because nginx has no JSON
|
||||||
|
# parser. That catches /auth/login, the GraphQL login and change-password
|
||||||
|
# mutations and the refresh-token call in one rule. Over-matching (a query that
|
||||||
|
# merely selects a field named *token*) costs a hidden body, never a leak.
|
||||||
|
# map is evaluated lazily at log time, after the body has been read.
|
||||||
|
map $request_body $logged_body {
|
||||||
|
"~*(password|token|secret)" "[redacted]";
|
||||||
|
default $request_body;
|
||||||
|
}
|
||||||
|
|
||||||
|
# escape=json makes each line valid JSON (quotes, newlines and control bytes
|
||||||
|
# in the body are escaped), so Dozzle renders it as fields and `jq` reads it.
|
||||||
|
log_format payloads escape=json '{'
|
||||||
|
'"time":"$time_iso8601",'
|
||||||
|
'"ip":"$remote_addr",'
|
||||||
|
'"method":"$request_method",'
|
||||||
|
'"host":"$host",'
|
||||||
|
'"uri":"$request_uri",'
|
||||||
|
'"status":"$status",'
|
||||||
|
'"rt":"$request_time",'
|
||||||
|
'"ctype":"$content_type",'
|
||||||
|
'"len":"$content_length",'
|
||||||
|
'"referer":"$http_referer",'
|
||||||
|
'"ua":"$http_user_agent",'
|
||||||
|
'"body":"$logged_body"'
|
||||||
|
'}';
|
||||||
|
|
||||||
|
access_log /var/log/nginx/payloads/payloads.log payloads;
|
||||||
@@ -15,9 +15,8 @@ add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" alway
|
|||||||
# locked-down CSP by declaring Content-Security-Policy again themselves
|
# locked-down CSP by declaring Content-Security-Policy again themselves
|
||||||
# (a later add_header of the same name within one response wins).
|
# (a later add_header of the same name within one response wins).
|
||||||
#
|
#
|
||||||
# ponytail: no site-wide CSP from nginx here. The SPA needs
|
# ponytail: no site-wide CSP from nginx here. Gitea (proxied at /gitea/)
|
||||||
# 'wasm-unsafe-eval' for its Rust module, Gitea (proxied at /gitea/) relies
|
# relies on inline <script> blocks its own templates generate, so a shared
|
||||||
# on inline <script> blocks its own templates generate, so a shared
|
|
||||||
# script-src would need 'unsafe-inline' — which voids almost all of CSP's
|
# script-src would need 'unsafe-inline' — which voids almost all of CSP's
|
||||||
# value. If a real CSP matters again, give the SPA document its own
|
# value. If a real CSP matters again, give the SPA document its own
|
||||||
# script-src 'self' 'wasm-unsafe-eval' location, separate from Gitea.
|
# script-src 'self' location, separate from Gitea.
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
# =============================================================================
|
||||||
|
# .env.dev — COMMITTED settings for the local dev stack. EVERY VALUE IS A DUMMY.
|
||||||
|
#
|
||||||
|
# Use it by copying it over the gitignored .env, then starting the dev stack:
|
||||||
|
# cp .env.dev .env
|
||||||
|
# docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||||
|
# It has to BE .env, not be passed with --env-file: several services declare
|
||||||
|
# `env_file: ./.env`, which compose reads regardless (see check-compose in the
|
||||||
|
# Makefile).
|
||||||
|
#
|
||||||
|
# Nothing here is secret and nothing here may ever be used in production: the
|
||||||
|
# passwords and signing keys only guard containers on your own machine, and
|
||||||
|
# every third-party credential is fake, so those integrations fail at the
|
||||||
|
# provider instead of reaching a real account. The background jobs that would
|
||||||
|
# act on real accounts are switched off as well.
|
||||||
|
#
|
||||||
|
# Keep it in step with .env.example: a new variable goes in both. Settings that
|
||||||
|
# are not secrets (hosts, ports, timezone) keep .env.example's defaults; values
|
||||||
|
# a service parses (the S3 key id and secret) are dummies in the exact shape it requires, or that service won't start.
|
||||||
|
#
|
||||||
|
# The dummy Postgres credentials only work on a database volume created with
|
||||||
|
# them: an existing dbdata volume keeps whatever password it was initialised
|
||||||
|
# with. Only POSTGRES_DB is created on a fresh volume; the tracker database
|
||||||
|
# and role still have to be created by hand (.env.example).
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# --- Postgres ----------------------------------------------------------------
|
||||||
|
POSTGRES_USER=dev
|
||||||
|
POSTGRES_PASSWORD=dev-postgres-password
|
||||||
|
POSTGRES_DB=site
|
||||||
|
POSTGRES_PORT=5432
|
||||||
|
POSTGRES_HOST=db
|
||||||
|
POSTGRES_TRACKER_DB=tracker
|
||||||
|
POSTGRES_TRACKER_USER=tracker
|
||||||
|
POSTGRES_TRACKER_PASSWORD=dev-tracker-password
|
||||||
|
|
||||||
|
# --- Gitea -------------------------------------------------------------------
|
||||||
|
# Dev has no Gitea: GITEA_HOST is pinned to a TEST-NET address that never
|
||||||
|
# answers, so the home page's git feed is empty (and /gitea/ redirects to
|
||||||
|
# git.localhost, which goes nowhere).
|
||||||
|
GITEA_HOST=git.localhost
|
||||||
|
GITEA_PORT=3000
|
||||||
|
GITEA_UPSTREAM=192.0.2.1
|
||||||
|
|
||||||
|
# --- Gitea Actions runner ----------------------------------------------------
|
||||||
|
# The runner is not part of the compose stack; nothing in dev reads these.
|
||||||
|
GITEA_RUNNER_HOST=
|
||||||
|
GITEA_RUNNER_NAME=dev-runner
|
||||||
|
GITEA_RUNNER_REGISTRATION_TOKEN=dev-dummy-runner-token
|
||||||
|
|
||||||
|
# --- SilverBullet (notes) ---------------------------------------------------
|
||||||
|
SILVERBULLET_PORT=3000
|
||||||
|
SILVERBULLET_PUBLIC_HOST=silverbullet-public
|
||||||
|
SILVERBULLET_PUBLIC_PORT=3000
|
||||||
|
SILVERBULLET_GIT_INTERVAL=300
|
||||||
|
|
||||||
|
# --- Go backend --------------------------------------------------------------
|
||||||
|
# Must be at least 32 bytes or the backend refuses to start.
|
||||||
|
BACKEND_PORT=8080
|
||||||
|
BACKEND_HOST=backend
|
||||||
|
BACKEND_SECRET=dev-only-jwt-signing-secret-not-for-production
|
||||||
|
BACKEND_ENDPOINT=/api
|
||||||
|
|
||||||
|
# --- Obsidian vault ----------------------------------------------------------
|
||||||
|
# A checked-in, mostly-gitignored folder, so the bind mount always has a
|
||||||
|
# source owned by you; a missing path would be created by Docker as root and
|
||||||
|
# SilverBullet (uid 1000) could not write to it. It is not a git repository,
|
||||||
|
# so silverbullet-git logs that and idles instead of pushing anywhere.
|
||||||
|
OBSIDIAN_DIR=./dev/notes
|
||||||
|
|
||||||
|
# --- Spotify -----------------------------------------------------------------
|
||||||
|
# docker-compose.dev.yml overrides the redirect URI.
|
||||||
|
SPOTIFY_CLIENT_ID=dev-dummy-spotify-client-id
|
||||||
|
SPOTIFY_CLIENT_SECRET=dev-dummy-spotify-client-secret
|
||||||
|
SPOTIFY_REDIRECT_URI=
|
||||||
|
SPOTIFY_AUTH_STATE=dev-dummy-spotify-state
|
||||||
|
|
||||||
|
# --- Icecast / liquidsoap radio ----------------------------------------------
|
||||||
|
ICECAST_SOURCE_PASSWORD=dev-icecast-source-password
|
||||||
|
ICECAST_RELAY_PASSWORD=dev-icecast-relay-password
|
||||||
|
ICECAST_ADMIN_USER=admin
|
||||||
|
ICECAST_ADMIN_PASSWORD=dev-icecast-admin-password
|
||||||
|
ICECAST_HOST=icecast2
|
||||||
|
ICECAST_PORT=8000
|
||||||
|
ICECAST_MOUNT=/stream
|
||||||
|
LIQUIDSOAP_HARBOR_MOUNT=/live
|
||||||
|
LIQUIDSOAP_HARBOR_PORT=8001
|
||||||
|
|
||||||
|
# --- TLS / identity ----------------------------------------------------------
|
||||||
|
# DOMAIN is also the auth cookie's domain, so it must be the host the browser
|
||||||
|
# is on. Nothing reads EMAIL any more (it was certbot's).
|
||||||
|
DOMAIN=localhost
|
||||||
|
EMAIL=[email protected]
|
||||||
|
|
||||||
|
# --- Cloudflare Tunnel -------------------------------------------------------
|
||||||
|
# cloudflared is disabled in dev, and dev's Caddy sites use `tls internal`,
|
||||||
|
# so neither token is ever used.
|
||||||
|
CLOUDFLARE_TUNNEL_TOKEN=dev-dummy-tunnel-token
|
||||||
|
CLOUDFLARE_DNS_API_TOKEN=dev-dummy-dns-token
|
||||||
|
|
||||||
|
# --- Third-party API keys ----------------------------------------------------
|
||||||
|
# Fake keys: Claude calls (rowing photos, job posting reader) get a 401 from
|
||||||
|
# Anthropic, and the Steam widget gets nothing back.
|
||||||
|
CLAUDE_API_KEY=sk-ant-dev-dummy-key
|
||||||
|
CLAUDE_MODEL=
|
||||||
|
STEAM_API_KEY=DEVDUMMYSTEAMKEY
|
||||||
|
STEAM_ID=76561190000000000
|
||||||
|
|
||||||
|
# --- Development-only switch -------------------------------------------------
|
||||||
|
SEED_DB=true
|
||||||
|
|
||||||
|
# --- Python FastAPI service (/py/) -------------------------------------------
|
||||||
|
PYTHON_HOST=python
|
||||||
|
PYTHON_PORT=8000
|
||||||
|
|
||||||
|
# --- USACO site (/usaco/) ------------------------------------------------------
|
||||||
|
USACO_IMAGE_TAG=
|
||||||
|
USACO_GIT_TOKEN=dev-dummy-gitea-token
|
||||||
|
USACO_WEBHOOK_SECRET=dev-dummy-webhook-secret
|
||||||
|
|
||||||
|
# --- Activity tracker (/tracker/) --------------------------------------------
|
||||||
|
ACTIVITY_TRACKER_IMAGE_TAG=
|
||||||
|
TRACKER_TZ=Europe/London
|
||||||
|
|
||||||
|
TFL_APP_KEY=dev-dummy-tfl-key
|
||||||
|
|
||||||
|
# --- Garage object store (public /uploads/, on stpcore) -----------------------
|
||||||
|
# Uploads fall back to the `uploads` volume unless a dev stpcore is running
|
||||||
|
# with LAN_BIND=172.17.0.1 and these same dummy values (see stpcore's README).
|
||||||
|
# Shapes Garage enforces: "GK" + 24 hex for the key id, 64 hex for the secret.
|
||||||
|
GARAGE_UPSTREAM=host-gateway
|
||||||
|
GARAGE_WEBUI_TOKEN=dev-garage-webui-token
|
||||||
|
S3_ACCESS_KEY_ID=GK0123456789abcdef01234567
|
||||||
|
S3_SECRET_ACCESS_KEY=fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210
|
||||||
|
S3_ENDPOINT=http://garage:3900
|
||||||
|
S3_REGION=garage
|
||||||
|
S3_BUCKET=uploads
|
||||||
|
|
||||||
|
STPPRIV_LAN_IP=192.0.2.1
|
||||||
+164
-79
@@ -7,26 +7,22 @@
|
|||||||
# it parses the file, before any container exists. This is how container
|
# it parses the file, before any container exists. This is how container
|
||||||
# names and published ports are built.
|
# names and published ports are built.
|
||||||
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
# 2. `env_file: ./.env` on a service. Injects the WHOLE file as environment
|
||||||
# variables inside that container. nginx, backend, db, icecast2,
|
# variables inside that container. backend, db and icecast2 do this.
|
||||||
# certbot and gitea all do this.
|
# The `python` service deliberately does neither wholesale — each
|
||||||
# The `python` service deliberately does neither wholesale — it uses an
|
# uses an explicit `environment:` allow-list, so it never sees the site's
|
||||||
# explicit `environment:` allow-list, so it never sees the database password
|
# database password, the JWT secret, or any key it does not use.
|
||||||
# or any API key other than the two it uses (TFL_APP_KEY, CLAUDE_API_KEY).
|
|
||||||
#
|
#
|
||||||
# HOW TO USE
|
# HOW TO USE
|
||||||
# cp .env.example .env then fill in every value.
|
# cp .env.example .env then fill in every value.
|
||||||
# Distribute to the Raspberry Pi with ./sync-secrets.sh (newer file wins in
|
# On the host, edit .env in place. After changing a value, recreate the
|
||||||
# either direction — see that script's header before editing on both hosts).
|
# services that read it:
|
||||||
# On the Pi, keys and settings can also be changed from the admin panel's
|
# docker compose up -d <service>.
|
||||||
# Environment tab, which rewrites this file in place (previous version kept
|
|
||||||
# as .env.bak) and restarts what reads the change. See "Editing from the
|
|
||||||
# admin panel" in DEPLOYMENT.md.
|
|
||||||
#
|
#
|
||||||
# ADDING A VARIABLE
|
# ADDING A VARIABLE
|
||||||
# Add it to backend/services/env_registry.json as well. That file decides
|
# Add it to .env.dev as well, with a dummy value, so the dev stack keeps
|
||||||
# whether the admin panel shows it, whether it is editable there, and which
|
# starting. If the python service reads it, add it to that service's
|
||||||
# services are restarted when it changes; a backend test fails if the two
|
# `environment:` list in docker-compose.yml too, or the container never
|
||||||
# lists differ.
|
# receives it.
|
||||||
#
|
#
|
||||||
# CAUTION: an unset variable does not fail loudly. envsubst renders it as an
|
# CAUTION: an unset variable does not fail loudly. envsubst renders it as an
|
||||||
# empty string, which for a password field means "no password". After editing,
|
# empty string, which for a password field means "no password". After editing,
|
||||||
@@ -37,30 +33,35 @@
|
|||||||
# =============================================================================
|
# =============================================================================
|
||||||
|
|
||||||
# --- Postgres ----------------------------------------------------------------
|
# --- Postgres ----------------------------------------------------------------
|
||||||
# One instance, two databases: POSTGRES_DB for the Go backend, POSTGRES_GITEA_DB
|
# One instance, two databases: POSTGRES_DB for the Go backend and
|
||||||
# for Gitea. Only POSTGRES_DB is auto-created on first init; the Gitea one must
|
# POSTGRES_TRACKER_DB for the activity tracker (with its own role). The job
|
||||||
# be created by hand on a fresh volume.
|
# tracker and Gitea have their own Postgres on stppriv and stpgit. Only
|
||||||
|
# POSTGRES_DB is auto-created on first init; the tracker database must be
|
||||||
|
# created by hand on a fresh volume (the ccp README has the commands).
|
||||||
# POSTGRES_HOST doubles as the db container's name.
|
# POSTGRES_HOST doubles as the db container's name.
|
||||||
POSTGRES_USER=
|
POSTGRES_USER=
|
||||||
POSTGRES_PASSWORD=
|
POSTGRES_PASSWORD=
|
||||||
POSTGRES_DB=
|
POSTGRES_DB=
|
||||||
POSTGRES_PORT=5432
|
POSTGRES_PORT=5432
|
||||||
POSTGRES_HOST=db
|
POSTGRES_HOST=db
|
||||||
|
POSTGRES_TRACKER_DB=tracker
|
||||||
|
POSTGRES_TRACKER_USER=tracker
|
||||||
|
POSTGRES_TRACKER_PASSWORD=
|
||||||
|
|
||||||
# --- Gitea -------------------------------------------------------------------
|
# --- Gitea -------------------------------------------------------------------
|
||||||
# GITEA_HOST is the container name AND the nginx upstream host.
|
# Gitea runs in its own LXC (the adamf/stpgit repo, whose variables are in its
|
||||||
# The three secrets below are passed as GITEA__section__KEY overrides so the
|
# .env.example); this stack has no Gitea container. GITEA_HOST is its public
|
||||||
# committed app.ini.template can keep those fields blank. Generate each as a
|
# name, used on its plain-HTTP port GITEA_PORT by Caddy's /v2/, the backend's
|
||||||
# long random hex string.
|
# feed and usaco, and as the SSH host for silverbullet-git. GITEA_UPSTREAM is
|
||||||
GITEA_HOST=gitea
|
# the LXC's LAN IP, which those containers pin GITEA_HOST to (extra_hosts), so
|
||||||
|
# the hop stays on the LAN instead of going to Cloudflare. On the host itself
|
||||||
|
# (the runner, CI, Renovate) the same pin is a line in /etc/hosts.
|
||||||
|
GITEA_HOST=git.adam-french.co.uk
|
||||||
GITEA_PORT=3000
|
GITEA_PORT=3000
|
||||||
GITEA_INTERNAL_TOKEN=
|
GITEA_UPSTREAM=
|
||||||
GITEA_LFS_JWT_SECRET=
|
|
||||||
GITEA_OAUTH2_JWT_SECRET=
|
|
||||||
POSTGRES_GITEA_DB=gitea
|
|
||||||
|
|
||||||
# --- Gitea Actions runner ----------------------------------------------------
|
# --- Gitea Actions runner ----------------------------------------------------
|
||||||
# The runner is NOT a container; it runs on the Pi via gitea-runner/run.sh.
|
# 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
|
# The registration token is SINGLE-USE: it is exchanged for a permanent
|
||||||
# identity in gitea-runner/.runner on first registration, after which this
|
# identity in gitea-runner/.runner on first registration, after which this
|
||||||
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
|
# value is ignored. Mint it in Site Administration -> Actions -> Runners.
|
||||||
@@ -68,54 +69,18 @@ GITEA_RUNNER_HOST=
|
|||||||
GITEA_RUNNER_NAME=pi-runner
|
GITEA_RUNNER_NAME=pi-runner
|
||||||
GITEA_RUNNER_REGISTRATION_TOKEN=
|
GITEA_RUNNER_REGISTRATION_TOKEN=
|
||||||
|
|
||||||
# --- Email ingest (backend) --------------------------------------------------
|
|
||||||
# EMAIL_BACKEND selects the mail source: "graph" (Microsoft Graph API, OAuth)
|
|
||||||
# or "imap" (fallback; Microsoft has retired IMAP basic auth for outlook.com,
|
|
||||||
# so imap+app-password only works with non-Microsoft providers like Gmail).
|
|
||||||
# For "graph": register an Entra "app registration" for a personal Microsoft
|
|
||||||
# account at azure.microsoft.com > Microsoft Entra ID > App registrations
|
|
||||||
# (default tenant = "consumers"); add a delegated Mail.Read permission with
|
|
||||||
# admin/user consent, and create a client secret. Redirect URI type "Web",
|
|
||||||
# value must live behind the site's real HTTPS origin, e.g.
|
|
||||||
# https://<YOUR_DOMAIN>/email/callback (callback route already exists in the
|
|
||||||
# backend). Backend code exchanges a code there. TenantID must be "consumers"
|
|
||||||
# for a personal outlook.com account.
|
|
||||||
# The first sync prints an authorisation URL into the container log; visit it,
|
|
||||||
# consent, and the refresh token is persisted to backend/token/msgraph_token.json.
|
|
||||||
# OAuth flow reference: https://learn.microsoft.com/en-us/graph/auth-v2-user
|
|
||||||
EMAIL_BACKEND=
|
|
||||||
MSGRAPH_CLIENT_ID=
|
|
||||||
MSGRAPH_CLIENT_SECRET=
|
|
||||||
MSGRAPH_TENANT_ID=consumers
|
|
||||||
MSGRAPH_REDIRECT_URI=
|
|
||||||
# IMAP_PASSWORD should be an app-specific password, not the account password.
|
|
||||||
# Only read when EMAIL_BACKEND=imap.
|
|
||||||
IMAP_HOST=
|
|
||||||
IMAP_PORT=993
|
|
||||||
IMAP_EMAIL=
|
|
||||||
IMAP_PASSWORD=
|
|
||||||
EMAIL_SYNC_INTERVAL=
|
|
||||||
EMAIL_SYNC_ENABLED=
|
|
||||||
|
|
||||||
# --- Services that nginx substitutes but no longer runs -----------------------
|
|
||||||
# Kept because nginx/entrypoint.sh lists them in its envsubst allow-list; no
|
|
||||||
# compose service uses them today. Harmless if blank.
|
|
||||||
|
|
||||||
# --- SilverBullet (notes) ---------------------------------------------------
|
# --- SilverBullet (notes) ---------------------------------------------------
|
||||||
# Two instances over the same vault: the admin-only editor at /sb/, and the
|
# The public read-only notes site at /notes/. The editor, and the vault's only
|
||||||
# public read-only notes site at /notes/ (which replaced Quartz). All four
|
# writer, is stppriv (priv.DOMAIN/sb/); silverbullet-git here only pulls.
|
||||||
# default in nginx/entrypoint.sh and docker-compose.yml, so they can be left
|
# Both default in docker-compose.yml.
|
||||||
# blank.
|
|
||||||
SILVERBULLET_HOST=silverbullet
|
|
||||||
SILVERBULLET_PORT=3000
|
|
||||||
SILVERBULLET_PUBLIC_HOST=silverbullet-public
|
SILVERBULLET_PUBLIC_HOST=silverbullet-public
|
||||||
SILVERBULLET_PUBLIC_PORT=3000
|
SILVERBULLET_PUBLIC_PORT=3000
|
||||||
# Seconds between notes commit/push cycles (default 300).
|
# Seconds between notes pulls (default 300).
|
||||||
SILVERBULLET_GIT_INTERVAL=
|
SILVERBULLET_GIT_INTERVAL=
|
||||||
|
|
||||||
# --- Go backend --------------------------------------------------------------
|
# --- Go backend --------------------------------------------------------------
|
||||||
# BACKEND_HOST is the container name and the nginx upstream.
|
# BACKEND_HOST is the container name and the Caddy upstream.
|
||||||
# BACKEND_ENDPOINT is the public URL prefix nginx mounts the API at and then
|
# BACKEND_ENDPOINT is the public URL prefix Caddy mounts the API at and then
|
||||||
# strips; the Vue app's GraphQL client assumes /api.
|
# strips; the Vue app's GraphQL client assumes /api.
|
||||||
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
|
# BACKEND_SECRET signs the JWTs stored in the auth cookies — rotating it logs
|
||||||
# everyone out.
|
# everyone out.
|
||||||
@@ -125,8 +90,8 @@ BACKEND_SECRET=
|
|||||||
BACKEND_ENDPOINT=/api
|
BACKEND_ENDPOINT=/api
|
||||||
|
|
||||||
# --- Obsidian vault ----------------------------------------------------------
|
# --- Obsidian vault ----------------------------------------------------------
|
||||||
# HOST path, interpolated straight into the bind mounts: read-write into the
|
# HOST path, interpolated straight into the bind mounts: read-write into
|
||||||
# backend, silverbullet and silverbullet-git, read-only into
|
# silverbullet-git (which pulls it), read-only into the backend and
|
||||||
# silverbullet-public. Must be an absolute path that exists on the host or the
|
# silverbullet-public. Must be an absolute path that exists on the host or the
|
||||||
# stack will not start.
|
# stack will not start.
|
||||||
OBSIDIAN_DIR=
|
OBSIDIAN_DIR=
|
||||||
@@ -145,7 +110,7 @@ SPOTIFY_AUTH_STATE=
|
|||||||
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
|
# ICECAST_SOURCE_PASSWORD is used TWICE: liquidsoap authenticates to icecast
|
||||||
# with it, and a live-broadcasting client authenticates to the liquidsoap
|
# with it, and a live-broadcasting client authenticates to the liquidsoap
|
||||||
# harbor port with it. Anyone holding it can take over the stream.
|
# harbor port with it. Anyone holding it can take over the stream.
|
||||||
# LIQUIDSOAP_HARBOR_PORT is the only non-nginx port published to the host.
|
# LIQUIDSOAP_HARBOR_PORT is the only non-Caddy port published to the host.
|
||||||
ICECAST_SOURCE_PASSWORD=
|
ICECAST_SOURCE_PASSWORD=
|
||||||
ICECAST_RELAY_PASSWORD=
|
ICECAST_RELAY_PASSWORD=
|
||||||
ICECAST_ADMIN_USER=
|
ICECAST_ADMIN_USER=
|
||||||
@@ -157,17 +122,39 @@ LIQUIDSOAP_HARBOR_MOUNT=/live
|
|||||||
LIQUIDSOAP_HARBOR_PORT=8001
|
LIQUIDSOAP_HARBOR_PORT=8001
|
||||||
|
|
||||||
# --- TLS / identity ----------------------------------------------------------
|
# --- TLS / identity ----------------------------------------------------------
|
||||||
# DOMAIN is the APEX domain with no scheme and no www; certbot requests both
|
# DOMAIN is the APEX domain with no scheme and no www; Caddy gets a
|
||||||
# it and www.DOMAIN on one certificate, and nginx canonicalises to www.
|
# certificate for it and for www.DOMAIN, and canonicalises to www.
|
||||||
# EMAIL is the Let's Encrypt account address for expiry notices.
|
# EMAIL was certbot's Let's Encrypt account address. Nothing reads it since
|
||||||
|
# the move to Caddy, which registers its ACME account without one; it stays
|
||||||
|
# for the nginx/certbot rollback (.deprecated/, DEPLOYMENT.md §7).
|
||||||
DOMAIN=
|
DOMAIN=
|
||||||
EMAIL=
|
EMAIL=
|
||||||
|
|
||||||
|
# --- Cloudflare Tunnel -------------------------------------------------------
|
||||||
|
# Token of the remotely managed tunnel the `cloudflared` container runs
|
||||||
|
# (Zero Trust -> Networks -> Tunnels -> your tunnel -> the `--token` value in
|
||||||
|
# the install command). Hostnames and origin settings are configured in the
|
||||||
|
# dashboard, not here; see "Cloudflare Tunnel" in DEPLOYMENT.md. Blank leaves
|
||||||
|
# the container restarting with an error and the site reachable directly.
|
||||||
|
CLOUDFLARE_TUNNEL_TOKEN=
|
||||||
|
# Cloudflare API token for Caddy's DNS-01 challenge (caddy/sites/prod.caddy):
|
||||||
|
# My Profile -> API Tokens -> Create Token -> "Edit zone DNS", limited to this
|
||||||
|
# zone, then add Zone -> Zone -> Read on the same zone (the template only has
|
||||||
|
# DNS -> Edit). Certificates are issued and renewed with no inbound port, so
|
||||||
|
# the router forwards nothing. Required in production: Caddy has no HTTP
|
||||||
|
# challenge to fall back to. Changing it needs `docker compose up -d caddy`.
|
||||||
|
CLOUDFLARE_DNS_API_TOKEN=
|
||||||
|
|
||||||
# --- Third-party API keys (backend) ------------------------------------------
|
# --- Third-party API keys (backend) ------------------------------------------
|
||||||
# CLAUDE_API_KEY is also passed to the python service, which makes the Claude
|
# CLAUDE_API_KEY is used by the python service, which makes the main site's
|
||||||
# calls for the rowing photo reader and the job posting reader; the backend
|
# Claude calls: the rowing photo reader, the job posting reader and the email
|
||||||
# uses it for the email pipeline.
|
# pipeline's classifier. The backend no longer calls Claude itself. The usaco
|
||||||
|
# container gets the same key for its own calls.
|
||||||
CLAUDE_API_KEY=
|
CLAUDE_API_KEY=
|
||||||
|
# Which model those calls use: claude-haiku-4-5 (cheapest), claude-sonnet-5-5
|
||||||
|
# (the default when blank) or claude-opus-5-5. Recreate the python service
|
||||||
|
# to apply a change.
|
||||||
|
CLAUDE_MODEL=
|
||||||
STEAM_API_KEY=
|
STEAM_API_KEY=
|
||||||
STEAM_ID=
|
STEAM_ID=
|
||||||
|
|
||||||
@@ -180,5 +167,103 @@ SEED_DB=
|
|||||||
PYTHON_HOST=python
|
PYTHON_HOST=python
|
||||||
PYTHON_PORT=8000
|
PYTHON_PORT=8000
|
||||||
|
|
||||||
|
# --- USACO site (/usaco/) ------------------------------------------------------
|
||||||
|
# An image built and published by the usaco repo's CI. Blank runs :latest; set
|
||||||
|
# a commit sha to pin. Changing it needs
|
||||||
|
# `docker compose pull usaco && docker compose up -d usaco`.
|
||||||
|
USACO_IMAGE_TAG=
|
||||||
|
# The same for its code runner (usaco-runner), which the usaco repo's CI
|
||||||
|
# publishes and rolls alongside it. It takes no other settings: it has no
|
||||||
|
# secrets by design.
|
||||||
|
USACO_RUNNER_IMAGE_TAG=
|
||||||
|
# Gitea access token (repository: read and write on adamf/usaco). The site
|
||||||
|
# clones with it and pushes the admin's edits back.
|
||||||
|
USACO_GIT_TOKEN=
|
||||||
|
# Shared secret of the usaco repo's push webhook in Gitea
|
||||||
|
# (http://usaco:8080/usaco/api/hooks/gitea). Blank turns the hook off and
|
||||||
|
# the site only pulls every 10 minutes. Generate with `openssl rand -hex 32`.
|
||||||
|
USACO_WEBHOOK_SECRET=
|
||||||
|
# Model for the problem explanations (the admin's Explain button), separate
|
||||||
|
# from CLAUDE_MODEL because those are long, considered answers rather than
|
||||||
|
# extraction. Blank means claude-opus-5-5. The key is CLAUDE_API_KEY above;
|
||||||
|
# without it the button is off and the rest of the site works.
|
||||||
|
USACO_CLAUDE_MODEL=
|
||||||
|
# Monthly cap on the USACO site's estimated Claude spend, in dollars (e.g.
|
||||||
|
# 20). Once a calendar month (UTC) reaches it, new Explain/review/concept/
|
||||||
|
# evaluate jobs are refused until the 1st. Blank: no cap; the spend is still
|
||||||
|
# shown on the site's stats page to the admin.
|
||||||
|
USACO_CLAUDE_MONTHLY_BUDGET=
|
||||||
|
# Recording reviews (the admin uploads themselves explaining a solution).
|
||||||
|
# Claude cannot take audio, so this OpenAI key transcribes it (whisper-1,
|
||||||
|
# about $0.006 a minute). Blank turns reviews off.
|
||||||
|
USACO_OPENAI_API_KEY=
|
||||||
|
# Optional: keep the recordings for playback in a PRIVATE Garage bucket
|
||||||
|
# (`usaco-audio` on stpcore), never `uploads` (that one is served publicly at
|
||||||
|
# /uploads/). Its own key, same shapes as S3_ACCESS_KEY_ID /
|
||||||
|
# S3_SECRET_ACCESS_KEY below. With the key blank the recordings are thrown
|
||||||
|
# away once transcribed. Put the same pair in stpcore's .env and run its
|
||||||
|
# garage/bootstrap.sh, which creates the bucket and imports the key.
|
||||||
|
USACO_S3_ACCESS_KEY_ID=
|
||||||
|
USACO_S3_SECRET_ACCESS_KEY=
|
||||||
|
|
||||||
|
# --- Activity tracker (/tracker/) --------------------------------------------
|
||||||
|
# An image built and published by the ccp repo's CI. Blank runs :latest; set a
|
||||||
|
# commit sha to pin. Changing it needs
|
||||||
|
# `docker compose pull activity-tracker && docker compose up -d activity-tracker`.
|
||||||
|
ACTIVITY_TRACKER_IMAGE_TAG=
|
||||||
|
# IANA timezone that decides where a "day" starts in daily summaries. Blank is UTC.
|
||||||
|
TRACKER_TZ=Europe/London
|
||||||
|
|
||||||
|
# --- Receipt printer (/receipt/) ---------------------------------------------
|
||||||
|
# Not a container here: `receipt serve` (adamf/receipt_maker) runs on stppi,
|
||||||
|
# which reaches the printer over the home LAN, and Caddy proxies to it over
|
||||||
|
# Tailscale.
|
||||||
|
# host:port of that server, by Tailscale IP. Blank points nowhere and
|
||||||
|
# /receipt/ answers "offline".
|
||||||
|
RECEIPT_WEB_UPSTREAM=100.107.152.119:8765
|
||||||
|
# Shared secret Caddy adds as X-Receipt-Token; the same value as
|
||||||
|
# RECEIPT_WEB_TOKEN in stppi's ~/.config/receipt-web.env. Generate with
|
||||||
|
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`.
|
||||||
|
RECEIPT_WEB_TOKEN=
|
||||||
|
|
||||||
|
# --- stppriv (priv.DOMAIN) ---------------------------------------------------
|
||||||
|
# The private-tools LXC's LAN IP. Its Caddy asks /api/auth/validate-admin
|
||||||
|
# directly, not via the tunnel, and requests from this IP skip the api rate
|
||||||
|
# limit. Blank matches nothing.
|
||||||
|
STPPRIV_LAN_IP=
|
||||||
|
|
||||||
|
# --- Partner Radar (radar.DOMAIN) ----------------------------------------------
|
||||||
|
# A separate compose project on this host (adamf/cto, `make stpvm`), whose web
|
||||||
|
# container joins app-network as `radar-web`. Only set this to point
|
||||||
|
# radar.DOMAIN somewhere else.
|
||||||
|
# RADAR_UPSTREAM=radar-web:80
|
||||||
|
|
||||||
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
# TfL Unified API key (500 req/min); used by the Python hotel finder
|
||||||
TFL_APP_KEY=
|
TFL_APP_KEY=
|
||||||
|
|
||||||
|
# --- Garage object store (public /uploads/, on stpcore) -----------------------
|
||||||
|
# Garage runs on the stpcore LXC (adamf/stpcore); its README is the runbook
|
||||||
|
# and its .env holds Garage's own secrets. Everything here is optional for
|
||||||
|
# the site to run: with S3_ENDPOINT blank, or stpcore down, the backend
|
||||||
|
# writes uploads to the `uploads` volume and Caddy serves them from there.
|
||||||
|
#
|
||||||
|
# stpcore's LAN IP: the name `garage` is pinned to it in caddy, backend and
|
||||||
|
# usaco. `host-gateway` in dev. Blank means 127.0.0.1, which fails fast.
|
||||||
|
GARAGE_UPSTREAM=
|
||||||
|
# Shared secret Caddy adds as X-Core-Token on /garage/, after the admin
|
||||||
|
# gate; the same value as GARAGE_WEBUI_TOKEN in stpcore's .env.
|
||||||
|
# `openssl rand -hex 32`. Changing it needs `docker compose up -d caddy`.
|
||||||
|
GARAGE_WEBUI_TOKEN=
|
||||||
|
# The backend's S3 key, the same values as in stpcore's .env (whose
|
||||||
|
# bootstrap.sh imports it). Garage only accepts this shape:
|
||||||
|
# S3_ACCESS_KEY_ID "GK" + 24 hex (echo GK$(openssl rand -hex 12))
|
||||||
|
# S3_SECRET_ACCESS_KEY 64 hex (openssl rand -hex 32)
|
||||||
|
S3_ACCESS_KEY_ID=
|
||||||
|
S3_SECRET_ACCESS_KEY=
|
||||||
|
# Blank keeps uploads on disk. http://garage:3900 stores new public uploads
|
||||||
|
# in the bucket; recreate the backend after changing it. If a write to Garage
|
||||||
|
# fails the backend logs it and writes to disk instead.
|
||||||
|
S3_ENDPOINT=
|
||||||
|
# Optional; these defaults match stpcore's garage.toml and bootstrap.sh.
|
||||||
|
S3_REGION=garage
|
||||||
|
S3_BUCKET=uploads
|
||||||
|
|||||||
@@ -1,31 +1,106 @@
|
|||||||
name: Deploy with Docker Compose
|
# `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:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: self-hosted
|
||||||
|
env:
|
||||||
|
# Via env so a branch name is never parsed as shell.
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
|
REF: ${{ github.ref }}
|
||||||
|
REMOTE: ssh://[email protected]:2222/adamf/stpweb.git
|
||||||
|
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||||
|
# Kept between runs so fetches are incremental.
|
||||||
|
CACHE: /home/adamf/.cache/stpweb-ci/repo.git
|
||||||
|
SRC: /home/adamf/.cache/stpweb-ci/src-${{ github.sha }}
|
||||||
|
steps:
|
||||||
|
- name: Export the pushed commit to a scratch directory
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
mkdir -p "$(dirname "$CACHE")"
|
||||||
|
[ -d "$CACHE" ] || git init --quiet --bare "$CACHE"
|
||||||
|
# $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 --git-dir="$CACHE" archive --format=tar "$SHA" | tar -x -C "$SRC"
|
||||||
|
# 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"
|
||||||
|
|
||||||
|
# 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: |
|
||||||
|
set -eu
|
||||||
|
docker run --rm \
|
||||||
|
-v "$SRC":/src:ro \
|
||||||
|
-w /src/backend \
|
||||||
|
-v stpweb_ci_gomod:/go/pkg/mod \
|
||||||
|
-v stpweb_ci_gobuild:/root/.cache/go-build \
|
||||||
|
golang:1.26 \
|
||||||
|
sh -c 'go vet ./... && go test ./...'
|
||||||
|
|
||||||
|
# Read-only source, so bytecode and the pytest cache are off.
|
||||||
|
- name: Python - pytest
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
docker run --rm \
|
||||||
|
-v "$SRC":/src:ro \
|
||||||
|
-w /src/python \
|
||||||
|
-v stpweb_ci_pip:/root/.cache/pip \
|
||||||
|
-e PYTHONDONTWRITEBYTECODE=1 \
|
||||||
|
python:3.12-slim \
|
||||||
|
sh -c 'pip install --quiet --disable-pip-version-check --root-user-action=ignore -r requirements-dev.txt && python -m pytest tests -q -p no:cacheprovider'
|
||||||
|
|
||||||
|
- name: Remove the scratch directory
|
||||||
|
if: always()
|
||||||
|
shell: bash
|
||||||
|
run: rm -rf "$SRC"
|
||||||
|
|
||||||
deploy:
|
deploy:
|
||||||
|
needs: test
|
||||||
|
if: github.ref == 'refs/heads/main'
|
||||||
runs-on: self-hosted
|
runs-on: self-hosted
|
||||||
steps:
|
steps:
|
||||||
- name: Pull changes
|
- name: Pull changes
|
||||||
working-directory: /home/adamf/deploy/web_server
|
working-directory: /home/adamf/deploy/stpweb
|
||||||
env:
|
env:
|
||||||
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
GIT_SSH_COMMAND: "ssh -o StrictHostKeyChecking=no"
|
||||||
|
SHA: ${{ github.sha }}
|
||||||
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
git config --global --add safe.directory /home/adamf/deploy/web_server
|
set -eu
|
||||||
git fetch ssh://git@localhost:2222/adamf/web_server.git main
|
git config --global --add safe.directory /home/adamf/deploy/stpweb
|
||||||
|
git fetch ssh://[email protected]:2222/adamf/stpweb.git main
|
||||||
|
# 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."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
git reset --hard FETCH_HEAD
|
git reset --hard FETCH_HEAD
|
||||||
|
|
||||||
- name: Run docker compose up
|
- name: Run docker compose up
|
||||||
working-directory: /home/adamf/deploy/web_server
|
working-directory: /home/adamf/deploy/stpweb
|
||||||
env:
|
env:
|
||||||
DOCKER_API_VERSION: "1.41"
|
|
||||||
COMPOSE_BAKE: "false"
|
COMPOSE_BAKE: "false"
|
||||||
# The lock is shared with env-apply/apply.py, so a deploy and a
|
# Shared with maintenance.yaml so the two never run compose at once.
|
||||||
# .env change made from the admin panel cannot run compose at
|
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||||
# the same time.
|
|
||||||
run: flock env-apply/run/lock docker compose up -d --build --remove-orphans
|
|
||||||
|
|
||||||
- name: Prune unused Docker resources
|
- name: Prune unused Docker resources
|
||||||
run: docker image prune -f
|
run: docker image prune -f
|
||||||
|
|||||||
@@ -2,7 +2,8 @@ name: Weekly Maintenance
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: "0 1 * * 0"
|
# Restarts dockerd, so it runs when nobody is likely mid-edit.
|
||||||
|
- cron: "0 5 * * 0"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
@@ -21,17 +22,15 @@ jobs:
|
|||||||
- name: Autoremove obsolete packages
|
- name: Autoremove obsolete packages
|
||||||
run: sudo apt-get -y autoremove --purge
|
run: sudo apt-get -y autoremove --purge
|
||||||
|
|
||||||
|
# .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
|
- name: Pull latest base images
|
||||||
working-directory: /home/adamf/deploy/web_server
|
working-directory: /home/adamf/deploy/stpweb
|
||||||
env:
|
run: flock .compose.lock docker compose pull
|
||||||
DOCKER_API_VERSION: "1.41"
|
|
||||||
run: docker compose pull
|
|
||||||
|
|
||||||
- name: Rebuild and restart containers
|
- name: Rebuild and restart containers
|
||||||
working-directory: /home/adamf/deploy/web_server
|
working-directory: /home/adamf/deploy/stpweb
|
||||||
env:
|
run: flock .compose.lock docker compose up -d --build --remove-orphans
|
||||||
DOCKER_API_VERSION: "1.41"
|
|
||||||
run: docker compose up -d --build --remove-orphans
|
|
||||||
|
|
||||||
- name: Prune unused Docker images
|
- name: Prune unused Docker images
|
||||||
run: docker image prune -af
|
run: docker image prune -af
|
||||||
@@ -41,7 +40,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Show running containers
|
- name: Show running containers
|
||||||
run: docker compose ps
|
run: docker compose ps
|
||||||
working-directory: /home/adamf/deploy/web_server
|
working-directory: /home/adamf/deploy/stpweb
|
||||||
|
|
||||||
- name: Show disk usage after
|
- name: Show disk usage after
|
||||||
run: df -h /
|
run: df -h /
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# 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:
|
||||||
|
# Clear of the Sunday maintenance rebuild.
|
||||||
|
- cron: "0 4 * * 1"
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
renovate:
|
||||||
|
runs-on: self-hosted
|
||||||
|
steps:
|
||||||
|
- name: Run Renovate
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
RENOVATE_TOKEN: ${{ secrets.RENOVATE_TOKEN }}
|
||||||
|
GITHUB_COM_TOKEN: ${{ secrets.RENOVATE_GITHUB_COM_TOKEN }}
|
||||||
|
run: |
|
||||||
|
set -eu
|
||||||
|
if [ -z "$RENOVATE_TOKEN" ]; then
|
||||||
|
echo "The RENOVATE_TOKEN Actions secret is not set (repo Settings -> Actions -> Secrets)."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
docker run --rm --pull always --network host \
|
||||||
|
-e RENOVATE_PLATFORM=gitea \
|
||||||
|
-e RENOVATE_ENDPOINT=http://git.adam-french.co.uk:3000/api/v1 \
|
||||||
|
-e RENOVATE_GIT_URL=endpoint \
|
||||||
|
-e RENOVATE_REPOSITORIES=adamf/stpweb,adamf/stpgit,adamf/stppriv,adamf/stpcore \
|
||||||
|
-e RENOVATE_TOKEN \
|
||||||
|
-e GITHUB_COM_TOKEN \
|
||||||
|
-e LOG_LEVEL=info \
|
||||||
|
renovate/renovate:44
|
||||||
+19
-11
@@ -1,32 +1,37 @@
|
|||||||
icecast2/fallback_music/*
|
icecast2/fallback_music/*
|
||||||
|
.claude/
|
||||||
!icecast2/fallback_music/.gitkeep
|
!icecast2/fallback_music/.gitkeep
|
||||||
|
# The retired certbot's data (code in .deprecated/certbot/), still on the
|
||||||
|
# host as the rollback certificate
|
||||||
certbot/conf
|
certbot/conf
|
||||||
certbot/www
|
certbot/www
|
||||||
|
# Caddy's certificates, keys and ACME account (docker-compose.yml)
|
||||||
|
caddy/data/
|
||||||
backend/token/
|
backend/token/
|
||||||
|
usaco-data/
|
||||||
.env
|
.env
|
||||||
.env.bak
|
.env.bak
|
||||||
|
|
||||||
# Admin panel -> host hand-off (request and status files, holds secrets)
|
# flock taken by the deploy and maintenance workflows around docker compose
|
||||||
env-apply/run/*
|
.compose.lock
|
||||||
!env-apply/run/.gitkeep
|
|
||||||
|
|
||||||
gitea/data/*
|
# Gitea's pre-move state, kept as the rollback (.deprecated/gitea/README)
|
||||||
gitea/config/app.ini
|
.deprecated/gitea/data/
|
||||||
|
.deprecated/gitea/config/
|
||||||
|
.deprecated/gitea/dev-leftovers/
|
||||||
|
|
||||||
# Gitea runner
|
# Gitea runner
|
||||||
gitea-runner/.runner
|
gitea-runner/.runner
|
||||||
gitea-runner/act_runner
|
gitea-runner/act_runner
|
||||||
gitea-runner/nohup.out
|
gitea-runner/nohup.out
|
||||||
|
|
||||||
# Rust build artifacts
|
|
||||||
**/target/
|
|
||||||
|
|
||||||
# Python bytecode
|
# Python bytecode
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.pyc
|
*.pyc
|
||||||
|
.pytest_cache/
|
||||||
|
|
||||||
# Generated WASM output
|
# Virtualenv `make check-python` builds on demand from python/requirements-dev.txt
|
||||||
vue/src/wasm/
|
/.venv/
|
||||||
|
|
||||||
# Logs
|
# Logs
|
||||||
logs
|
logs
|
||||||
@@ -69,7 +74,6 @@ __screenshots__/
|
|||||||
|
|
||||||
.deploy
|
.deploy
|
||||||
*.xcf
|
*.xcf
|
||||||
sync-secrets.sh
|
|
||||||
|
|
||||||
# Local-only outstanding-work notes, deliberately not published
|
# Local-only outstanding-work notes, deliberately not published
|
||||||
TODO-NEXT.md
|
TODO-NEXT.md
|
||||||
@@ -77,3 +81,7 @@ TODO-NEXT.md
|
|||||||
# SilverBullet git deploy key (key material only; the README stays)
|
# SilverBullet git deploy key (key material only; the README stays)
|
||||||
silverbullet/ssh/*
|
silverbullet/ssh/*
|
||||||
!silverbullet/ssh/README.md
|
!silverbullet/ssh/README.md
|
||||||
|
# Dev notes vault (OBSIDIAN_DIR in .env.dev); only the README is tracked
|
||||||
|
dev/notes/*
|
||||||
|
!dev/notes/README.md
|
||||||
|
.gstack/
|
||||||
|
|||||||
@@ -4,13 +4,22 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
|
|
||||||
## Build & Run Commands
|
## Build & Run Commands
|
||||||
|
|
||||||
|
### Check everything
|
||||||
|
|
||||||
|
```
|
||||||
|
make check
|
||||||
|
```
|
||||||
|
|
||||||
|
Runs `go vet` + `go test` (backend), pytest in a venv built from `python/requirements-dev.txt` (kept in `/.venv/`), a Vite build, `docker compose config` for both compose files, and the Caddy image build, which validates `caddy/` for both modes. Each part is also its own target (`check-backend`, `check-python`, `check-vue`, `check-compose`, `check-caddy`); `make help` lists them. The Gitea deploy workflow runs the backend and Python checks in containers on every push, and `main` only deploys if they pass — so run `make check` before pushing. Dependency-update PRs come from Renovate (`renovate.json5`, run weekly by `.gitea/workflows/renovate.yaml`), since Dependabot is GitHub-only; that `test` job skips the Vue build, so run `make check-vue` on an npm PR before merging it.
|
||||||
|
|
||||||
### Full stack (dev mode, HTTP only)
|
### Full stack (dev mode, HTTP only)
|
||||||
|
|
||||||
```
|
```
|
||||||
|
cp .env.dev .env
|
||||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
Dev mode seeds the database with test data (`SEED_DB=true`) and disables certbot/SSL. Visit `http://localhost`.
|
`.env.dev` is committed and every value in it is a dummy: local-only passwords, fake third-party keys, `DOMAIN=localhost`, background jobs that touch real accounts switched off. It has to be copied to `.env` because several services read `env_file: ./.env` directly. Never put a real credential in it. Dev mode seeds the database with test data (`SEED_DB=true`) and serves the site on both http and https (a certificate from Caddy's local CA), with no redirects or security headers. Visit `http://localhost`. Uploads stay on disk unless a dev stpcore is also running (from that repo, with `LAN_BIND=172.17.0.1` and the same dummy keys as `.env.dev`), which `GARAGE_UPSTREAM=host-gateway` reaches.
|
||||||
|
|
||||||
### Full stack (production, HTTPS)
|
### Full stack (production, HTTPS)
|
||||||
|
|
||||||
@@ -24,7 +33,7 @@ docker compose up --build
|
|||||||
cd vue && npm run dev
|
cd vue && npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`; the targets default to `localhost:8080`, `:3000`, `:8000` and `:8000` and are overridden with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (shell or `vue/.env.local`). Compose publishes none of the backend, Python or Icecast ports to the host, and `/py` and `/radio` share a default, so set these to wherever the services really are — see the comment in `vue/vite.config.js`.
|
||||||
|
|
||||||
### Frontend build
|
### Frontend build
|
||||||
|
|
||||||
@@ -32,6 +41,8 @@ Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`
|
|||||||
cd vue && npm run build
|
cd vue && npm run build
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`npm run build` is a plain `vite build`.
|
||||||
|
|
||||||
### Regenerate GraphQL (after editing schema files)
|
### Regenerate GraphQL (after editing schema files)
|
||||||
|
|
||||||
```
|
```
|
||||||
@@ -42,46 +53,56 @@ This regenerates `graph/generated.go` and `graph/model/models_gen.go`. Resolver
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
Dockerized multi-service personal website self-hosted on a Raspberry Pi.
|
Dockerized multi-service personal website self-hosted on `stpvm` (an x86-64 Ubuntu VM; formerly a Raspberry Pi).
|
||||||
|
|
||||||
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
|
**Backend** (`backend/`): Go with Gin router. GraphQL API via gqlgen at `POST /api/graphql`. REST endpoints for auth, file uploads, Spotify OAuth, and WebSockets. GORM for PostgreSQL with auto-migrations (no separate migration files). JWT auth stored in HTTP-only cookies.
|
||||||
|
|
||||||
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served through Nginx (production) or proxied to Vite dev server (dev mode).
|
**Frontend** (`vue/`): Vue 3 SPA with Vite, Tailwind CSS v4, Pinia stores, Vue Router. Built in a separate container; assets served by Caddy (production) or proxied to Vite dev server (dev mode).
|
||||||
|
|
||||||
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Nginx proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. Two routes are internal — `/internal/rowing/read` (the Claude call behind `POST /api/rowing`) and `/internal/jobs/extract` (behind `POST /api/jobs/capture/extract`): the Go backend calls them directly over the Docker network and nginx 404s `/py/internal/`.
|
**Python API** (`python/`): FastAPI app served by uvicorn on port 8000. Caddy proxies `/py/` to it and strips the prefix, so routes in `python/app/main.py` are written relative to `/`. Swagger UI at `/py/docs`. Dev mode mounts `python/app` and runs uvicorn with `--reload`. **The site's Claude call lives here**, behind an internal route: `/internal/rowing/read` (behind `POST /api/rowing`). The Go backend calls it directly over the Docker network through `services.CallPython`, and Caddy 404s `/py/internal/`. The model is one setting, `CLAUDE_MODEL` (default `claude-sonnet-5-5`), set in `.env`; `python/app/claude.py` shapes the request per model. Adding another route is a short recipe in `python/README.md` ("Internal routes").
|
||||||
|
|
||||||
**Nginx** (`nginx/`): Reverse proxy + SPA server. Config is templated (`nginx.conf.template`) and selected at runtime by `entrypoint.sh` based on `DEV_MODE` and certificate presence. Rate limiting on login (5/min), API (30/sec), uploads (5/min).
|
**Job tracker 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.
|
||||||
|
|
||||||
|
**Uploads / Garage** (Garage itself on stpcore): every stored file goes through one path. Frontend: `vue/src/uploads.js` (`uploadFile(file)` → URL, plus `ACCEPT` for pickers, `kindOf`, `isUploadUrl`, `tagFor`). Backend: `POST /api/uploads` (`handlers/handle_upload.go`), a thin wrapper over `services.Uploads.Save` (`services/uploads.go`), which owns the type table (`UploadTypes`), the 10MB limit, random naming and storage. A new feature that takes a file calls those, never its own endpoint. `GET /api/uploads` (admin only, `Uploads.List`, `listUploads()`) lists what is stored, bucket and disk merged, for `components/util/UploadPicker.vue`, the "choose an existing upload" modal used by the canvas's Background panel, Box editor and admin bar. Public files go to a bucket in Garage (the `uploads` volume when `S3_ENDPOINT` is unset, or when Garage refuses a write). Garage and `garage-webui` are not in this stack: they run on the `stpcore` LXC, from the `adamf/stpcore` repo (the shared core other stacks depend on; its README is the runbook, including `garage/bootstrap.sh`), and the name `garage` is pinned to its LAN IP (`GARAGE_UPSTREAM`) by `extra_hosts` in `caddy`, `backend` and `usaco`. Caddy serves `/uploads/` from Garage's anonymous website endpoint (`garage:3902`) first and the volume second, so the bucket is the source of truth and a Garage or stpcore outage only affects bucket-only files. Private attachments (`/uploads/private/`) always stay on disk. `/garage/` (admin-gated) proxies to stpcore's Caddy on `garage:3909`, adding `X-Core-Token` (`GARAGE_WEBUI_TOKEN`), which that Caddy requires before it forwards to garage-webui. A new consumer of the store gets its own key and bucket on stpcore and the same `extra_hosts` pin. "Garage" in `DEPLOYMENT.md` §7 covers this side.
|
||||||
|
|
||||||
|
**Caddy** (`caddy/`): the public edge since 2026-11-17 — TLS, the SPA and the reverse proxy in front of every service. It obtains and renews its own certificates (DNS-01 through the Cloudflare API, into `./caddy/data`), so there is no certbot. `caddy/Caddyfile` holds the global options and the shared snippets (`proxy`, `limit`, `admin_gate`, `permission_gate`, the upload headers, logging); `caddy/routes.caddy` is the one route table both modes use — add a new route there, in the right place, because inside its `route` block the first matching `handle` wins; `caddy/sites/prod.caddy` and `sites/dev.caddy` hold what differs (TLS, security headers, the apex, static caching, `/`), picked by `CADDY_SITE`. Every variable the config reads goes through the caddy service's explicit `environment:` list. The image build runs `caddy validate`, so `make check-caddy` (or a failed deploy build) catches a bad config before any container is replaced; the first build on a host compiles Caddy with its two plugins (rate limiting, the Cloudflare DNS provider) and is slow, later ones are cached. Rate limits (`import limit <zone> <events> <window>`) are sliding windows keyed on the real client IP, and a refused request gets 503; a zone name shared by several routes shares one bucket, so it must always carry the same numbers. Every request is also logged as a JSON line, body included (redacted if it mentions a password, token or secret), to `logs/caddy/payloads.log`. The `traffic` container tails that file so it shows up in Dozzle, which is served at `/dozzle/` behind the admin login; the admin panel no longer has a log view. Caddy has a healthcheck (`http://127.0.0.1/caddy-health`); the `autoheal` container restarts it when that fails, since Docker never restarts an unhealthy container itself. Gitea is not proxied any more: it lives at `git.<DOMAIN>` (its own tunnel, from the stpgit repo) and `/gitea/*` 301s there; only the registry at the apex's `/v2/` still goes through Caddy. `caddy/edge_test.sh` checks the privacy denials and every gate against a running edge. The pre-cutover nginx and certbot configs are in `.deprecated/nginx/` and `.deprecated/certbot/`, kept for the rollback in `DEPLOYMENT.md` §7.
|
||||||
|
|
||||||
## Backend Structure
|
## Backend Structure
|
||||||
|
|
||||||
- `main.go` — entry point: wires up DB, services, router
|
- `main.go` — entry point: wires up DB, services, router
|
||||||
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, EmailSync, etc. Passed to all handlers
|
- `handlers/store.go` — `Store` struct holds DB, SpotifyAuth, Auth, Notes, etc. Passed to all handlers
|
||||||
- `handlers/handle_*.go` — REST handlers grouped by domain
|
- `handlers/handle_*.go` — REST handlers grouped by domain
|
||||||
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
|
- `graph/schema/*.graphql` — GraphQL schema files (source of truth)
|
||||||
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
|
- `graph/*.resolvers.go` — resolver implementations (one per schema file, `follow-schema` layout)
|
||||||
- `graph/generated.go` — auto-generated by gqlgen, do not edit
|
- `graph/generated.go` — auto-generated by gqlgen, do not edit
|
||||||
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
|
- `graph/model/models_gen.go` — auto-generated GraphQL models, do not edit
|
||||||
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing)
|
- `models/models.go` — GORM database models (User, Post, Message, Activity, Favorite, Rowing, Bookmark, Place, Box, Page, Background, Layout, Component, CoverLetter, CoverSnippet)
|
||||||
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, Claude client, DB seeding
|
- `graph/directives.go` — the `@admin` / `@signedIn` schema directives (see Key Patterns)
|
||||||
|
- `services/` — database init, JWT auth, WebSocket server, Spotify OAuth, Gitea feed, the Python-service call helper (`python_call.go`), uploads (`uploads.go`: validation, naming, Garage bucket with disk fallback), DB seeding. There is no Claude client in Go any more
|
||||||
|
|
||||||
## Frontend Structure
|
## Frontend Structure
|
||||||
|
|
||||||
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
- `src/graphql.js` — thin axios-based GraphQL client (`POST /api/graphql`)
|
||||||
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData
|
- `src/api.js` — thin REST client for the `/api` JSON endpoints; failures become an `ApiError` carrying the backend's `error` message and the status
|
||||||
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines)
|
- `src/uploads.js` — storing and showing uploaded files: `uploadFile(file)` → public `/uploads/...` URL, `ACCEPT` for file pickers, `kindOf`/`tagFor`/`isUploadUrl`/`mediaSize`. Every upload goes through it
|
||||||
|
- `src/stores/` — Pinia stores for auth, posts, favorites, activities, songs, messages, homeData, places, boxes, pages, layouts, components, coverLetters, coverSnippets. `createCrudStore.js` is the factory behind places, boxes and pages; `createMirrorStore.js` is the one behind the home-page slices
|
||||||
|
- `src/views/` — page components (Home, Admin, CV, Notes, Bookmarks, shrines). Canvas pages are admin-arranged boxes (built-in widgets or sandboxed-iframe HTML) stored as the `Box` GraphQL type, drawn by `views/home3/BoxCanvas.vue` per page key: the landing page (`/`, key `index`) is one, and admin-created `Page`s (e.g. shrines, and `/stp`, the `Page` with slug `stp`) are served at `/<slug>` by the router's catch-all, `views/canvas/CanvasPage.vue`. A `Layout` is a saved, named copy of a page's boxes and background that can be loaded onto any canvas (the canvas's Layouts button, or the admin Pages tab). A `Component` is a saved, named HTML box: "+ New box" places copies of it, and the canvas's Components button also places it *linked* (`Box.componentId`), so the box shows the component's HTML and editing it edits every linked box; the built-in starters in `templates.js` become components through that panel's "Import built-ins". Boxes and pages can be admin-only, filtered server-side. Each canvas page key also has an optional `Background`, set from the canvas's Background button and painted by `DefaultLayout`. See "The /stp canvas" in `vue/README.md`
|
||||||
- `src/components/` — reusable UI components
|
- `src/components/` — reusable UI components
|
||||||
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
|
- `src/assets/styles.css` — design tokens (Tailwind `@theme`), base element styles, shared classes and transitions. `layouts/CVLayout.vue` re-points the colour tokens for the light CV theme. See "Styling" in `vue/README.md`.
|
||||||
|
|
||||||
## Key Patterns
|
## 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. There is no token revocation — logout only clears cookies.
|
- **Auth flow**: Login sets `access_token` (7 days) and `refresh_token` (365 days) as HTTP-only cookies (`backend/main.go:96`). `AuthMiddleware` validates tokens and injects user into Gin context. `AuthContextMiddleware` passes Gin context into GraphQL resolver context. Revocation is by `User.TokenVersion`: every token carries the version it was minted with, and logout or a password change bumps it, invalidating all of that user's tokens. On the frontend the router guard awaits `auth.ensureLoaded()` (a standalone `me` query), not the home query; `homeData` exposes `settled` (finished either way) as well as `loaded` (succeeded).
|
||||||
- **GraphQL resolvers authorise themselves.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. Every resolver that needs auth must check it itself. See `backend/graph/doc.go`.
|
- **GraphQL auth is declared in the schema.** The `/api/graphql` endpoint has no guarding middleware; `AuthContextMiddleware` only makes the user *available*. A field is protected by annotating it `@admin` or `@signedIn` in `graph/schema/*.graphql` (implemented in `graph/directives.go`). `graph/directives_test.go` fails if a mutation has neither directive and is not on its short public allow-list (`login`, `logout`, `refreshToken`), so a new mutation cannot ship unguarded by accident; a new *query* is public unless you annotate it. Finer rules (post ownership, hiding private messages) stay in the resolver. See `backend/graph/doc.go`.
|
||||||
|
- **Adding a GraphQL entity**: model in `models/models.go` (and the AutoMigrate list), schema file with directives, mapping in `gqlgen.yml`, `make generate`, fill in the resolvers; on the frontend a store built with `createCrudStore`. Model `ID uint` binds directly via `graphql.UintID` — there are no hand-written ID resolvers. Full recipe in `backend/README.md`.
|
||||||
|
- **Per-service permissions**: a non-admin account can be granted individual gated services (today only `receipt`, for `/receipt/`) in the admin panel's Manage Users tab. The keys are the registry `services.PermissionTypes` (`backend/services/permissions.go`), stored in `User.Permissions`; admins hold them all. Caddy's *permission gate* (`import permission_gate <key>` in a route, see `caddy/routes.caddy` and the snippet in `caddy/Caddyfile`) asks `GET /auth/validate/<key>`, which reads the user row, so grants apply on the next request. Making another service grantable is a registry entry plus swapping its route from `import admin_gate` to `import permission_gate <key>`. `/auth/validate-admin` and the admin gate are unchanged.
|
||||||
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
|
- **Spotify tokens**: Persisted to `/backend/token/spotify_token.json` inside the container, surviving restarts.
|
||||||
- **Job capture**: `vue/public/job-capture.user.js` is a Violentmonkey userscript, served by the site and installed from `/cv/jobs`, that adds the posting open in the browser to the tracker. It calls the three `/api/jobs/capture` REST routes with a bearer token because cookies do not travel from other origins. The token is generated on the admin panel and stored hashed in `backend/token/job_capture_token.json`; there is no env var for it. Bump its `@version` on every edit or installed copies will not update. See "Job capture" in `backend/README.md`.
|
- **Environment variables**: every variable goes in `.env.example`, and a dummy value for it in `.env.dev`. One the Python service reads must also be added to the `python` service's explicit `environment:` list in `docker-compose.yml`, or the container never receives it. `.env` is edited by hand on the host; there is no admin-panel editor.
|
||||||
- **Environment tab**: `/admin` → Environment edits `.env` on the Pi. The backend never touches the file: it validates the edit and writes `env-apply/run/request.json`; `env-apply/apply.py`, run on the host by a systemd path unit (`env-apply/install.sh`), rewrites `.env` and recreates only the services that read the change. `backend/services/env_registry.json` is the single list of variables — **add new variables there as well as `.env.example`** (a test enforces it), with `editable: false` for anything that renames a container, moves a port or is only read at first init. Secrets are write-only: no endpoint returns one. See "Environment tab" in `backend/README.md`.
|
|
||||||
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
- **Gitea feed**: Backend proxies and caches (1 min TTL) the Gitea activity feed API.
|
||||||
- **All GORM models use soft delete** (`gorm.DeletedAt` field) — except `ProcessedEmail`, whose dedup must see history. Note that a `uniqueIndex` still collides with soft-deleted rows.
|
- **All GORM models use soft delete** (`gorm.DeletedAt` field). Note that a `uniqueIndex` still collides with soft-deleted rows.
|
||||||
|
|
||||||
## Further documentation
|
## Further documentation
|
||||||
|
|
||||||
@@ -95,7 +116,7 @@ Each area has its own README with the detail that doesn't belong here:
|
|||||||
|
|
||||||
## Conventions
|
## Conventions
|
||||||
|
|
||||||
- **Comments explain *why*, not *what*.** The codebase is deliberately heavily commented at the points where behaviour is non-obvious (concurrency, caching, auth, scraping, nginx templating). Preserve these when editing; if you change the behaviour they describe, update them.
|
- **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.
|
- **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.
|
- **Schema files use `#` comments**, not triple-quoted description blocks — descriptions would change GraphQL introspection output.
|
||||||
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead — e.g. `views/unused/CoverLetters.vue` is actually live on `/cv`.
|
- **Legacy views are kept, not deleted.** `vue/src/views/unused/`, `Intro.vue`, `Gym.vue`, the unlisted CV templates and similar carry a `STATUS:` header comment saying whether they are live. They are tree-shaken out of the build. Check the header before assuming a file is dead; being in `views/unused/` is not proof.
|
||||||
|
|||||||
+602
-260
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
|||||||
|
# `make check` before pushing; `make help` lists targets. A missing toolchain
|
||||||
|
# fails only the targets that need it.
|
||||||
|
|
||||||
|
.DEFAULT_GOAL := help
|
||||||
|
|
||||||
|
PYTHON ?= python3
|
||||||
|
|
||||||
|
# At the root, not in python/, which is a docker build context.
|
||||||
|
VENV := .venv
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Targets:"
|
||||||
|
@echo " make check run every check below"
|
||||||
|
@echo " make check-backend go vet + go test in backend/"
|
||||||
|
@echo " make check-python pytest in python/ (venv created on demand in $(VENV)/)"
|
||||||
|
@echo " make check-vue vite build of vue/ into a throwaway directory"
|
||||||
|
@echo " make check-compose validate docker-compose.yml, alone and with the dev override"
|
||||||
|
@echo " make check-caddy build the Caddy image, which validates caddy/ for prod and dev"
|
||||||
|
@echo " make generate regenerate the gqlgen GraphQL code after a schema edit"
|
||||||
|
@echo " make dev build and run the dev stack (http://localhost)"
|
||||||
|
|
||||||
|
check: check-backend check-python check-vue check-compose check-caddy
|
||||||
|
|
||||||
|
check-backend:
|
||||||
|
cd backend && go vet ./... && go test ./...
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
$(VENV)/bin/python -m pip install --quiet --upgrade pip
|
||||||
|
$(VENV)/bin/python -m pip install --quiet -r python/requirements-dev.txt
|
||||||
|
touch $@
|
||||||
|
|
||||||
|
check-python: $(VENV_STAMP)
|
||||||
|
cd python && ../$(VENV)/bin/python -m pytest tests -q
|
||||||
|
|
||||||
|
# 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"; \
|
||||||
|
exit 1; }
|
||||||
|
@out=$$(mktemp -d) && trap 'rm -rf "$$out"' EXIT && \
|
||||||
|
cd vue && npx vite build --outDir "$$out" --emptyOutDir
|
||||||
|
|
||||||
|
# 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 \
|
||||||
|
pd="."; \
|
||||||
|
else \
|
||||||
|
echo "check-compose: no .env, validating against .env.example"; \
|
||||||
|
pd=$$(mktemp -d); trap 'rm -rf "$$pd"' EXIT; \
|
||||||
|
cp .env.example "$$pd/.env"; \
|
||||||
|
echo "OBSIDIAN_DIR=/placeholder/obsidian" >> "$$pd/.env"; \
|
||||||
|
fi; \
|
||||||
|
echo "docker compose -f docker-compose.yml config -q"; \
|
||||||
|
docker compose --project-directory "$$pd" -f docker-compose.yml config -q; \
|
||||||
|
echo "docker compose -f docker-compose.yml -f docker-compose.dev.yml config -q"; \
|
||||||
|
docker compose --project-directory "$$pd" -f docker-compose.yml -f docker-compose.dev.yml config -q
|
||||||
|
|
||||||
|
# The image build runs `caddy validate` for both modes.
|
||||||
|
check-caddy:
|
||||||
|
docker build -q -t stpweb-caddy:check caddy/
|
||||||
|
|
||||||
|
generate:
|
||||||
|
cd backend && go run github.com/99designs/gqlgen generate
|
||||||
|
|
||||||
|
dev:
|
||||||
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||||
@@ -14,31 +14,29 @@ After hearing all the hype on LinkedIn and feeling the pressure to keep up a hig
|
|||||||
|
|
||||||
## Architecture
|
## Architecture
|
||||||
|
|
||||||
All services run in Docker containers orchestrated by Docker Compose behind Nginx as a reverse proxy on a single bridge network.
|
All services run in Docker containers orchestrated by Docker Compose behind Caddy as a reverse proxy on a single bridge network. (nginx and certbot did that job until 2026-11-17.)
|
||||||
|
|
||||||
```
|
```
|
||||||
vue ── Frontend build (outputs dist to shared volume)
|
vue ── Frontend build (outputs dist to shared volume)
|
||||||
nginx (80, 443) ── Frontend SPA + Reverse Proxy
|
caddy (80, 443) ── Frontend SPA + Reverse Proxy + TLS certificates
|
||||||
backend (8080) ── Go API (GraphQL + REST)
|
backend (8080) ── Go API (GraphQL + REST)
|
||||||
db (5432) ── PostgreSQL 16
|
db (5432) ── PostgreSQL 16
|
||||||
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
|
icecast2 (8000) ── Audio Streaming (Icecast2 + Liquidsoap)
|
||||||
gitea (3000) ── Self-Hosted Git
|
gitea (3000) ── Self-Hosted Git
|
||||||
silverbullet (3000) ── Obsidian Notes Editor (SilverBullet 2.11.0)
|
|
||||||
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
|
silverbullet-public (3000) ── Public read-only notes site (same image, SB_READ_ONLY)
|
||||||
silverbullet-git ── Commits/pushes notes edits to the notes repo
|
silverbullet-git ── Pulls the notes repo (the editor and its pushes are on stppriv)
|
||||||
python (8000) ── Python API (FastAPI)
|
python (8000) ── Python API (FastAPI)
|
||||||
certbot ── SSL Certificate Management (disabled in dev)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Tech Stack
|
## Tech Stack
|
||||||
|
|
||||||
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX), Rust/WASM
|
**Frontend** - Vue 3, Vite, Tailwind CSS v4, Pinia, Vue Router, markdown-it (wikilinks + KaTeX)
|
||||||
|
|
||||||
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
|
**Backend** - Go (Gin), gqlgen (GraphQL), GORM, PostgreSQL, JWT auth, WebSockets
|
||||||
|
|
||||||
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
|
**Integrations** - Spotify API, Steam API, Anthropic Claude API, Icecast2
|
||||||
|
|
||||||
**Infrastructure** - Docker Compose, Nginx, Let's Encrypt (Certbot), Gitea + Act Runner
|
**Infrastructure** - Docker Compose, Caddy, Let's Encrypt (DNS-01 via Cloudflare), Cloudflare Tunnel, Gitea + Act Runner
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
@@ -53,9 +51,9 @@ certbot ── SSL Certificate Management (disabled in dev)
|
|||||||
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
|
- Fan shrines (GTO, Evangelion, Demoman, Skip Skip Benben)
|
||||||
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
|
- Self-hosted Git (Gitea) with CI/CD and commit feed on homepage
|
||||||
- Printable CV with role-specific sections
|
- Printable CV with role-specific sections
|
||||||
- Job application tracker with status workflow and CSV export (admin-only, `/cv/jobs`)
|
- Job application tracker: runs on stppriv (`priv.<DOMAIN>/jobs/`), from the `adamf/job-tracker` repo
|
||||||
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
- Database-backed bookmarks grouped by category, managed via GraphQL (admin-only)
|
||||||
- Admin-gated routes: `/notes`, `/sb` require admin JWT via Nginx `auth_request`
|
- Admin-gated routes: `/tracker`, `/dozzle`, `/garage` and more require the admin session, checked by Caddy's `forward_auth` against the backend
|
||||||
- Landing page with animated stamps section
|
- Landing page with animated stamps section
|
||||||
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
- Route transitions (slide/fade) and performance optimizations (gzip, WOFF2 fonts, lazy loading)
|
||||||
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
|
- Backend healthcheck (reported in `docker ps`; nothing restarts on it)
|
||||||
@@ -68,10 +66,10 @@ certbot ── SSL Certificate Management (disabled in dev)
|
|||||||
| `/stp` | Home dashboard with grid layout |
|
| `/stp` | Home dashboard with grid layout |
|
||||||
| `/admin` | Admin login + panel (authenticated) |
|
| `/admin` | Admin login + panel (authenticated) |
|
||||||
| `/cv` | Curriculum Vitae (printable) |
|
| `/cv` | Curriculum Vitae (printable) |
|
||||||
| `/cv/jobs` | Job application tracker (admin-only, hidden print) |
|
| `/cv/jobs` | 301 to the job tracker on stppriv |
|
||||||
| `/bookmarks` | Bookmarks (database-backed, grouped by category) |
|
| `/bookmarks` | Bookmarks (database-backed, grouped by category) |
|
||||||
| `/notes/:path` | Obsidian notes (read-only SilverBullet, public; `private/` excluded) |
|
| `/notes/:path` | Obsidian notes (read-only SilverBullet, public; `private/` excluded) |
|
||||||
| `/sb/` | Obsidian note editor (via SilverBullet, admin-only) |
|
| `/sb/` | 301 to the note editor on stppriv (`priv.<DOMAIN>/sb/`) |
|
||||||
| `/shrines` | Fan shrine index + individual shrines |
|
| `/shrines` | Fan shrine index + individual shrines |
|
||||||
|
|
||||||
## API
|
## API
|
||||||
@@ -122,7 +120,7 @@ certbot ── SSL Certificate Management (disabled in dev)
|
|||||||
| POST | `/api/auth/refresh` | Refresh token |
|
| POST | `/api/auth/refresh` | Refresh token |
|
||||||
| GET | `/api/auth/check` | Check token validity |
|
| GET | `/api/auth/check` | Check token validity |
|
||||||
| POST | `/api/auth/logout` | Logout |
|
| POST | `/api/auth/logout` | Logout |
|
||||||
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Nginx auth_request) |
|
| GET | `/api/auth/validate-admin` | Validate admin JWT (used by Caddy's `forward_auth` admin gate) |
|
||||||
|
|
||||||
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
|
Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin` also refreshes the access token if it is within 24 hours of expiry.
|
||||||
|
|
||||||
@@ -147,7 +145,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
|||||||
**Protected (auth required)**
|
**Protected (auth required)**
|
||||||
| Method | Path | Description |
|
| Method | Path | Description |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| POST | `/api/messages/upload` | Upload message file (rate limited: 5/min) |
|
| POST | `/api/messages/upload` | Upload a file for a chat message or a canvas box (rate limited: 30/min, burst 20) |
|
||||||
|
|
||||||
**Admin (auth + admin required)**
|
**Admin (auth + admin required)**
|
||||||
| Method | Path | Description |
|
| Method | Path | Description |
|
||||||
@@ -173,7 +171,7 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
|||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
|
| GET | `/api/ws` | WebSocket chat (10s ping keepalive) |
|
||||||
|
|
||||||
### Nginx Proxy Routes
|
### Proxy Routes (Caddy)
|
||||||
|
|
||||||
| Route | Target | Notes |
|
| Route | Target | Notes |
|
||||||
| ---------- | ------------ | ------------------------------------------ |
|
| ---------- | ------------ | ------------------------------------------ |
|
||||||
@@ -181,11 +179,11 @@ Access tokens are valid for 7 days; refresh tokens for 365 days. `ValidateAdmin`
|
|||||||
| `/radio` | icecast:8000 | Audio streaming |
|
| `/radio` | icecast:8000 | Audio streaming |
|
||||||
| `/gitea` | gitea:3000 | Git service |
|
| `/gitea` | gitea:3000 | Git service |
|
||||||
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
|
| `/notes` | silverbullet-public:3000 | Obsidian notes (public, read-only) |
|
||||||
| `/sb` | silverbullet:3000 | Obsidian notes editor (admin-only) |
|
| `/sb`, `/jobs` | 301 to `priv.<DOMAIN>` | Editor and job tracker, on stppriv |
|
||||||
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
|
| `/py` | python:8000 | Python API (FastAPI; docs at `/py/docs`) |
|
||||||
| `/uploads` | local alias | User-uploaded files |
|
| `/uploads` | local alias | User-uploaded files |
|
||||||
|
|
||||||
`/sb` is protected by `auth_request` to `GET /api/auth/validate-admin`. Requests without a valid admin JWT are rejected with 401.
|
Admin-only routes such as `/tracker` are protected by `forward_auth` to the backend's `/auth/validate-admin`. Requests without a valid admin session are redirected to `/admin/login`. The full table is `caddy/routes.caddy`; `DEPLOYMENT.md` §1 explains it.
|
||||||
|
|
||||||
### Deprecated Endpoints
|
### Deprecated Endpoints
|
||||||
|
|
||||||
@@ -214,11 +212,9 @@ Create a `.env` file in the project root. All services read from this file.
|
|||||||
| `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) |
|
| `UPTIMEKUMA_PORT` | Uptime Kuma port (planned) |
|
||||||
| `WALLABAG_HOST` | Wallabag hostname (planned) |
|
| `WALLABAG_HOST` | Wallabag hostname (planned) |
|
||||||
| `WALLABAG_PORT` | Wallabag port (planned) |
|
| `WALLABAG_PORT` | Wallabag port (planned) |
|
||||||
| `SILVERBULLET_HOST` | SilverBullet hostname (defaults to `silverbullet`) |
|
|
||||||
| `SILVERBULLET_PORT` | SilverBullet port (defaults to `3000`) |
|
|
||||||
| `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 commit/push cycles (defaults to `300`) |
|
| `SILVERBULLET_GIT_INTERVAL` | Seconds between notes pulls (defaults to `300`) |
|
||||||
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
|
| `GITEA_RUNNER_HOST` | Gitea runner hostname |
|
||||||
| `GITEA_RUNNER_NAME` | Gitea runner display name |
|
| `GITEA_RUNNER_NAME` | Gitea runner display name |
|
||||||
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
|
| `GITEA_RUNNER_REGISTRATION_TOKEN` | Token to register Gitea Actions runner |
|
||||||
@@ -242,7 +238,7 @@ Create a `.env` file in the project root. All services read from this file.
|
|||||||
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
| `LIQUIDSOAP_HARBOR_PORT` | Liquidsoap harbor port (e.g. `8005`) |
|
||||||
| `DOMAIN` | Production domain name |
|
| `DOMAIN` | Production domain name |
|
||||||
| `EMAIL` | Email for Let's Encrypt registration |
|
| `EMAIL` | Email for Let's Encrypt registration |
|
||||||
| `CLAUDE_API_KEY` | Anthropic Claude API key |
|
| `CLAUDE_API_KEY` | Anthropic Claude API key (read by the Python service, which makes every Claude call) |
|
||||||
| `STEAM_API_KEY` | Steam Web API key |
|
| `STEAM_API_KEY` | Steam Web API key |
|
||||||
| `STEAM_ID` | Steam user ID |
|
| `STEAM_ID` | Steam user ID |
|
||||||
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
|
| `PYTHON_HOST` | Python API hostname (defaults to `python`) |
|
||||||
@@ -251,13 +247,7 @@ Create a `.env` file in the project root. All services read from this file.
|
|||||||
|
|
||||||
### Gitea Config
|
### Gitea Config
|
||||||
|
|
||||||
Copy from the template and fill in secrets:
|
Gitea is not part of this stack. It runs in its own LXC from the `adamf/stpgit` repo, whose README covers its config; this stack reaches it as `GITEA_HOST`, pinned to its LAN IP (`GITEA_UPSTREAM`).
|
||||||
|
|
||||||
```sh
|
|
||||||
cp gitea/config/app.ini.template gitea/config/app.ini
|
|
||||||
```
|
|
||||||
|
|
||||||
Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the database `PASSWD`. Alternatively, the Gitea entrypoint generates `app.ini` from the template using environment variables.
|
|
||||||
|
|
||||||
### Spotify Token Setup
|
### Spotify Token Setup
|
||||||
|
|
||||||
@@ -267,25 +257,23 @@ Populate `LFS_JWT_SECRET`, `SECRET_KEY`, `INTERNAL_TOKEN`, `JWT_SECRET`, and the
|
|||||||
### Obsidian Notes Setup
|
### Obsidian Notes Setup
|
||||||
|
|
||||||
1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine
|
1. Set `OBSIDIAN_DIR` in `.env` to the absolute path of your Obsidian vault on the host machine
|
||||||
2. The vault is mounted read-write into `silverbullet` at `/data`, which serves it as an
|
2. The vault is a pull-only clone of the notes repo (`silverbullet-git`, `SYNC_MODE=pull`),
|
||||||
editor at `/sb/`, and read-only into `silverbullet-public`, which serves it publicly at
|
mounted read-only into `silverbullet-public`, which serves it publicly at `/notes/` with
|
||||||
`/notes/` with `SB_READ_ONLY`
|
`SB_READ_ONLY`. The editor, and the vault's only writer, is on stppriv (`priv.<DOMAIN>/sb/`)
|
||||||
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
|
3. `private/` and `templates/` (at any depth), and dot-folders such as `.git`, are kept off
|
||||||
`/notes/` by `SB_SPACE_IGNORE` **and** nginx deny blocks — the nginx blocks are the ones that
|
`/notes/` by `SB_SPACE_IGNORE` **and** Caddy deny rules — the Caddy rules are the ones that
|
||||||
actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary")
|
actually enforce it. See `DEPLOYMENT.md` ("Public notes privacy boundary")
|
||||||
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
|
4. The backend also mounts the vault at `/backend/notes` (legacy, see deprecated endpoints above)
|
||||||
|
|
||||||
### SSL Certificates (Certbot)
|
### TLS certificates
|
||||||
|
|
||||||
**Initial setup (production):**
|
Caddy obtains and renews them itself, over DNS-01 through the Cloudflare API, so no port has to be reachable from the internet:
|
||||||
|
|
||||||
1. Set `DOMAIN` and `EMAIL` in `.env`
|
1. Set `DOMAIN` and `CLOUDFLARE_DNS_API_TOKEN` in `.env` (the token needs Zone → Zone → Read and Zone → DNS → Edit on the zone)
|
||||||
2. On first run, Nginx starts with `nginx_setup.conf.template` which only serves the ACME challenge route at `/.well-known/acme-challenge/`
|
2. `docker compose up -d`. Caddy serves immediately and fetches both certificates (apex and www) into `./caddy/data` within seconds
|
||||||
3. Certbot requests a certificate via `certbot certonly --webroot`
|
3. Renewal is automatic and needs no restart
|
||||||
4. Once the certificate is issued to `certbot/conf/live/<DOMAIN>/`, restart Nginx — it will detect the certs and switch to the full `nginx.conf.template`
|
|
||||||
5. Certbot checks for renewal every 12 hours automatically
|
|
||||||
|
|
||||||
**Dev mode:** Nginx generates a self-signed certificate for localhost automatically.
|
**Dev mode:** Caddy issues a certificate for localhost from its own local CA.
|
||||||
|
|
||||||
### Icecast Radio
|
### Icecast Radio
|
||||||
|
|
||||||
@@ -302,14 +290,15 @@ Place at least one `.mp3` file in `icecast2/fallback_music/`. Liquidsoap plays t
|
|||||||
Run the full stack over plain HTTP without SSL certificates:
|
Run the full stack over plain HTTP without SSL certificates:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
cp .env.dev .env # committed, dummy values only
|
||||||
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build
|
||||||
```
|
```
|
||||||
|
|
||||||
This:
|
This:
|
||||||
|
|
||||||
- Uses an HTTP-only Nginx config with all routing (SPA, backend proxy, radio, gitea, etc.)
|
- Loads Caddy's dev sites (`caddy/sites/dev.caddy`): all the same routing (SPA via Vite, backend proxy, radio, gitea, etc.) on both http and https, with no redirects or security headers
|
||||||
- Generates a self-signed certificate for localhost
|
- Uses a localhost certificate from Caddy's local CA
|
||||||
- Disables certbot
|
- Disables the Cloudflare tunnel
|
||||||
- Seeds the database with test data (`SEED_DB=true`)
|
- Seeds the database with test data (`SEED_DB=true`)
|
||||||
- Enables GraphQL playground and introspection
|
- Enables GraphQL playground and introspection
|
||||||
|
|
||||||
@@ -321,7 +310,17 @@ Visit `http://localhost` to test.
|
|||||||
cd vue && npm run dev
|
cd vue && npm run dev
|
||||||
```
|
```
|
||||||
|
|
||||||
Vite dev server proxies `/api` to `localhost:8080`, `/gitea` to `localhost:3000`, `/radio` to `localhost:8000`.
|
Vite dev server proxies `/api`, `/gitea`, `/py` and `/radio`. The targets default to `localhost:8080`, `:3000`, `:8000` and `:8000`; override them with `VITE_PROXY_API`, `VITE_PROXY_GITEA`, `VITE_PROXY_PY` and `VITE_PROXY_RADIO` (see the comment in `vue/vite.config.js` — compose does not publish the backend, Python or Icecast ports to the host).
|
||||||
|
|
||||||
|
### Checks
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make check
|
||||||
|
```
|
||||||
|
|
||||||
|
Runs the backend's `go vet` and tests, the Python tests (in a virtualenv created from `python/requirements-dev.txt`), a Vite build, `docker compose config` validation and the Caddy image build, which validates the edge config. `make help` lists the individual targets, plus `make generate` (regenerate the GraphQL code after a schema edit) and `make dev`.
|
||||||
|
|
||||||
|
The same backend and Python checks run in containers on the Pi on every push; a push to `main` is only deployed if they pass.
|
||||||
|
|
||||||
## Untracked Files
|
## Untracked Files
|
||||||
|
|
||||||
@@ -330,8 +329,7 @@ These files are git-ignored and must be created manually:
|
|||||||
| File | Notes |
|
| File | Notes |
|
||||||
| ------------------------------- | --------------------------------------------------------------- |
|
| ------------------------------- | --------------------------------------------------------------- |
|
||||||
| `.env` | See setup section above |
|
| `.env` | See setup section above |
|
||||||
| `gitea/config/app.ini` | Copy from `app.ini.template` or let entrypoint generate it |
|
| `caddy/data/` | Created automatically by Caddy (certificates and their keys) |
|
||||||
| `certbot/conf/`, `certbot/www/` | Created automatically by certbot; use dev mode to skip |
|
|
||||||
| `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/act_runner` | Download from Gitea releases |
|
||||||
@@ -339,7 +337,6 @@ These files are git-ignored and must be created manually:
|
|||||||
|
|
||||||
## Future Ideas
|
## Future Ideas
|
||||||
|
|
||||||
- More Rust to WASM
|
|
||||||
- ML for chatboards
|
- ML for chatboards
|
||||||
- Cache requests
|
- Cache requests
|
||||||
- Design more webpages
|
- Design more webpages
|
||||||
|
|||||||
+3
-33
@@ -1,32 +1,5 @@
|
|||||||
# =============================================================================
|
# Static binary (CGO_ENABLED=0) on a slim base. ca-certificates for outbound
|
||||||
# Go backend image — multi-stage: build with the full toolchain, ship a slim
|
# HTTPS; the cache mounts keep rebuilds fast.
|
||||||
# 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.
|
|
||||||
# nginx 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.
|
|
||||||
# =============================================================================
|
|
||||||
FROM golang:1.26 AS builder
|
FROM golang:1.26 AS builder
|
||||||
|
|
||||||
WORKDIR /backend
|
WORKDIR /backend
|
||||||
@@ -44,10 +17,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \
|
|||||||
|
|
||||||
FROM debian:bookworm-slim
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
# wget is not just for humans: the compose healthcheck probes the server with
|
# For the compose healthcheck.
|
||||||
# `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.
|
|
||||||
RUN apt-get update \
|
RUN apt-get update \
|
||||||
&& apt-get install --yes --no-install-recommends ca-certificates wget \
|
&& apt-get install --yes --no-install-recommends ca-certificates wget \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|||||||
+183
-106
@@ -1,10 +1,11 @@
|
|||||||
# Backend
|
# Backend
|
||||||
|
|
||||||
The Go API for adam-french.co.uk. It is one process behind nginx, serving a
|
The Go API for adam-french.co.uk. It is one process behind Caddy, serving a
|
||||||
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
GraphQL endpoint, a handful of REST endpoints, and the chat WebSocket, backed
|
||||||
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea, Anthropic).
|
by PostgreSQL and a few third-party APIs (Spotify, Steam, Gitea). Anything
|
||||||
|
that needs Claude is asked of the Python service, not called from here.
|
||||||
|
|
||||||
Nginx strips the `/api` prefix before proxying, so a browser request to
|
Caddy strips the `/api` prefix before proxying, so a browser request to
|
||||||
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
`/api/graphql` arrives here as `/graphql`. Every path below is as this service
|
||||||
sees it.
|
sees it.
|
||||||
|
|
||||||
@@ -18,9 +19,11 @@ handlers/ REST endpoints + the shared Store dependency container
|
|||||||
handle_*.go one file per domain
|
handle_*.go one file per domain
|
||||||
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
services/ stateful collaborators (DB, auth, chat hub, API clients)
|
||||||
graph/ GraphQL layer
|
graph/ GraphQL layer
|
||||||
schema/*.graphql source of truth for the schema
|
schema/*.graphql source of truth for the schema, including who may call what
|
||||||
*.resolvers.go resolver implementations, one per schema file
|
*.resolvers.go resolver implementations, one per schema file
|
||||||
*_helpers.go hand-written mapping helpers (never regenerated)
|
*_helpers.go hand-written mapping helpers (never regenerated)
|
||||||
|
directives.go @admin / @signedIn: the authorisation checks, written once
|
||||||
|
directives_test.go fails when a mutation is added without one
|
||||||
context.go reading identity out of the resolver context
|
context.go reading identity out of the resolver context
|
||||||
middleware.go putting it in
|
middleware.go putting it in
|
||||||
doc.go package overview — read this before touching resolvers
|
doc.go package overview — read this before touching resolvers
|
||||||
@@ -30,20 +33,21 @@ graph/ GraphQL layer
|
|||||||
|
|
||||||
## Request lifecycle
|
## Request lifecycle
|
||||||
|
|
||||||
1. Nginx terminates TLS, applies its own rate limits, strips `/api`, and
|
1. Caddy terminates TLS, applies its own rate limits, strips `/api`, and
|
||||||
proxies to this service.
|
proxies to this service.
|
||||||
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
2. Gin routes the request. `SetTrustedProxies` pins the Docker network CIDR so
|
||||||
that `ClientIP()` — which the login rate limiter keys on — cannot be
|
that `ClientIP()` — which the login rate limiter keys on — cannot be
|
||||||
spoofed via `X-Forwarded-For`.
|
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;
|
valid access token and stashes the claims in the Gin context;
|
||||||
`AdminMiddleware` then requires `admin: true` in those claims. A handler
|
`AdminMiddleware` then requires `admin: true` in those claims. A handler
|
||||||
reached through the `admin` group can assume both.
|
reached through the `admin` group can assume both.
|
||||||
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
4. **GraphQL**: there is no guarding middleware. `AuthContextMiddleware` only
|
||||||
*annotates* the request context with the Gin context and, if a valid access
|
*annotates* the request context with the Gin context and, if a valid access
|
||||||
token is present, the JWT claims — and then lets everything through. Each
|
token is present, the JWT claims — and then lets everything through. A
|
||||||
resolver authorises itself with `IsAdminFromCtx` / `UserIDFromCtx`.
|
field is guarded by a directive on it in the schema, `@admin` or
|
||||||
**A resolver that forgets to check is public.**
|
`@signedIn`, which runs before the resolver. **A field with neither is
|
||||||
|
public.** See [GraphQL authorisation](#graphql-authorisation).
|
||||||
5. Handlers and resolvers both reach the database and the caches through the
|
5. Handlers and resolvers both reach the database and the caches through the
|
||||||
single `handlers.Store` built in `main`.
|
single `handlers.Store` built in `main`.
|
||||||
|
|
||||||
@@ -60,6 +64,16 @@ graph/ GraphQL layer
|
|||||||
- `GET /auth/validate-admin` answers with a bare status code (200 / 403 / 401)
|
- `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.
|
||||||
|
- `GET /auth/validate/:permission` is the same for one named permission
|
||||||
|
(200 / 403 / 401, and 404 for a key that does not exist). It backs Caddy's
|
||||||
|
*permission gate*, which lets a non-admin account into one service — the
|
||||||
|
receipt printer at `/receipt/` — without making it an admin. Grantable keys
|
||||||
|
are the registry `services.PermissionTypes` (`services/permissions.go`);
|
||||||
|
a user's grants are `User.Permissions`, set from the admin panel's Manage
|
||||||
|
Users tab (`setUserPermissions`). Admins pass every permission check. The
|
||||||
|
check reads the user row, not the token, so a grant or revoke applies on
|
||||||
|
the next request. On 200 it returns the username in `X-Auth-User`, which
|
||||||
|
Caddy forwards to the gated service as `X-Remote-User`.
|
||||||
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
- Tokens are stateless. **Logout only clears the browser's cookies**; nothing
|
||||||
is revoked server-side, and a token that has already been issued stays valid
|
is revoked server-side, and a token that has already been issued stays valid
|
||||||
until it expires. The same is true of demoting an admin: it takes effect on
|
until it expires. The same is true of demoting an admin: it takes effect on
|
||||||
@@ -70,6 +84,95 @@ The two implementations (REST in `handlers/handle_auth.go`, GraphQL in
|
|||||||
both. They share `services.Auth` and the rate limiter, but each has its own
|
both. They share `services.Auth` and the rate limiter, but each has its own
|
||||||
cookie-writing helper — change one and you must change the other.
|
cookie-writing helper — change one and you must change the other.
|
||||||
|
|
||||||
|
## GraphQL authorisation
|
||||||
|
|
||||||
|
Who may call a field is written in the schema, on the field:
|
||||||
|
|
||||||
|
```graphql
|
||||||
|
extend type Query {
|
||||||
|
bookmarks: [Bookmark!]! # public
|
||||||
|
places: [Place!]! @signedIn # any signed-in user
|
||||||
|
users: [User!]! @admin # admins only
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| directive | passes when | error otherwise |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `@admin` | the access token's `admin` claim is true | `admin access required` |
|
||||||
|
| `@signedIn` | there is a valid access token at all | `authentication required` |
|
||||||
|
| *(none)* | always | — |
|
||||||
|
|
||||||
|
Both are declared in `graph/schema/schema.graphql`, implemented once in
|
||||||
|
`graph/directives.go`, and handed to gqlgen in `main.go`
|
||||||
|
(`graph.Config{Directives: graph.Directives()}`). gqlgen calls the directive
|
||||||
|
before the resolver; on an error the resolver never runs and the client gets
|
||||||
|
that message for the field. The two strings are shown as-is by the front end,
|
||||||
|
so they are part of the API. If the `Directives` line were ever dropped from
|
||||||
|
`main.go` the guarded fields would all fail (`directive admin is not
|
||||||
|
implemented`), not open.
|
||||||
|
|
||||||
|
This replaced an `if !IsAdminFromCtx(ctx) { return ... }` that was pasted into
|
||||||
|
the top of every guarded resolver, where leaving it out was invisible. Now a
|
||||||
|
guarded resolver has no check in it, and the absence of a guard is something a
|
||||||
|
test can see.
|
||||||
|
|
||||||
|
**What is guarded.** Queries are public and mutations are `@admin`, except:
|
||||||
|
|
||||||
|
- `login`, `logout`, `refreshToken` — public; they are how a session starts
|
||||||
|
and ends.
|
||||||
|
- `createPlace`, `updatePlace`, `deletePlace` and the `places` query —
|
||||||
|
`@signedIn`. Places are a shared list with no per-user ownership.
|
||||||
|
- `users`, `user` — queries, but `@admin`: private data.
|
||||||
|
|
||||||
|
**What a directive cannot say stays in the resolver**, using `IsAdminFromCtx` /
|
||||||
|
`UserIDFromCtx` from `graph/context.go`:
|
||||||
|
|
||||||
|
- `updatePost` / `deletePost` are `@admin` *and* require the caller to be the
|
||||||
|
post's author; `setUserAdmin` refuses to change the caller's own flag.
|
||||||
|
- `me` has no directive: it returns its own `unauthorized` error.
|
||||||
|
- `messages` has no directive: it filters private messages out for non-admins
|
||||||
|
instead of refusing.
|
||||||
|
- `spotifyNeedsReauth` has no directive: it is `false` for non-admins.
|
||||||
|
|
||||||
|
**The safety net** is `graph/directives_test.go`, which walks the parsed
|
||||||
|
schema:
|
||||||
|
|
||||||
|
- every `Mutation` field must carry `@admin` or `@signedIn`, unless it is in
|
||||||
|
the `publicMutations` list in that file (the three above). A new mutation
|
||||||
|
with no directive fails the build's tests until one or the other is done;
|
||||||
|
- the `@signedIn` mutations and the guarded queries are pinned by name, so
|
||||||
|
loosening `@admin` to `@signedIn`, or dropping a guard from a private query,
|
||||||
|
has to be done in the test as well;
|
||||||
|
- the directive functions are unit-tested, and a handful of operations are run
|
||||||
|
through the real executable schema to pin the messages on the wire.
|
||||||
|
|
||||||
|
One caveat: the test reads the `.graphql` files, but enforcement is in
|
||||||
|
`generated.go`. Adding a directive to an existing field does nothing until
|
||||||
|
gqlgen is re-run.
|
||||||
|
|
||||||
|
## Adding an entity
|
||||||
|
|
||||||
|
1. **Model** — add the struct to `models/models.go` with `ID uint`
|
||||||
|
(`gorm:"primarykey"`) and a `gorm.DeletedAt`, and list it in `AutoMigrate`
|
||||||
|
in `services/database.go`. There are no migration files.
|
||||||
|
2. **Schema** — add `graph/schema/<name>.graphql` with the type, its inputs,
|
||||||
|
and `extend type Query` / `extend type Mutation`. Put `@admin` or
|
||||||
|
`@signedIn` on every mutation, and on any query that is not for the public.
|
||||||
|
Use `#` comments, not `"""` descriptions.
|
||||||
|
3. **Binding** — map the type onto the model in `gqlgen.yml`, with
|
||||||
|
`deletedAt: resolver: false`. Without the entry gqlgen generates a second,
|
||||||
|
unrelated struct in `graph/model/`.
|
||||||
|
4. **Generate** — `go run github.com/99designs/gqlgen generate` (below). This
|
||||||
|
creates `graph/<name>.resolvers.go` with a stub per query and mutation.
|
||||||
|
5. **Resolvers** — fill the stubs in. Do not write an auth check; the
|
||||||
|
directive has run. Do not write an `ID` resolver; `ID uint` binds by itself
|
||||||
|
(see [IDs](#gotchas)). Put commentary inside the function bodies, since
|
||||||
|
gqlgen rewrites what is above the signature. A delete should load the row
|
||||||
|
first and return an error for a missing id, as the existing ones do.
|
||||||
|
6. **Test** — `go test ./...`. `directives_test.go` will tell you if a
|
||||||
|
mutation was left unguarded; if you added a guarded *query*, add it to the
|
||||||
|
pinned list there.
|
||||||
|
|
||||||
## GraphQL vs REST
|
## GraphQL vs REST
|
||||||
|
|
||||||
GraphQL is the default and covers essentially all the site's data. REST exists
|
GraphQL is the default and covers essentially all the site's data. REST exists
|
||||||
@@ -78,84 +181,46 @@ for the things GraphQL cannot do:
|
|||||||
| REST endpoint | why it is not GraphQL |
|
| REST endpoint | why it is not GraphQL |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
| `/auth/*` | cookie handling and the status-code-only admin probe |
|
||||||
| `/spotify/callback`, `/email/callback` | OAuth providers redirect a *browser* here |
|
| `/spotify/callback` | OAuth providers redirect a *browser* here |
|
||||||
| `/messages/upload`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
| `/uploads`, `/radio/upload`, `/rowing` (POST) | multipart file uploads |
|
||||||
|
| `/uploads` (GET, admin) | lists the stored files, next to the endpoint that stores them |
|
||||||
| `/notes/*path` | streams a file download, not JSON |
|
| `/notes/*path` | streams a file download, not JSON |
|
||||||
| `/ws` | WebSocket upgrade |
|
| `/ws` | WebSocket upgrade |
|
||||||
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
| `/rowing` (GET), `/spotify/listening`, `/spotify/recent` | predate the equivalent queries; kept working |
|
||||||
| `/admin/env`, `/admin/logs`, `/admin/capture-token` | process environment and files on disk, not the data model |
|
|
||||||
| `/jobs/capture`, `/jobs/capture/status`, `/jobs/capture/extract` | called by a userscript on other sites' origins, where the `SameSite=Lax` auth cookies are never sent; they take a bearer token instead |
|
|
||||||
|
|
||||||
### Environment tab
|
## Calling the Python service
|
||||||
|
|
||||||
`handlers/handle_env.go` and `services/env_manager.go` let the admin panel
|
Every Claude call the site makes lives in the Python service; this backend has
|
||||||
change `.env` on the Pi without SSH. The backend never reads or writes the
|
no Anthropic client and does not read `CLAUDE_API_KEY`. (The job tracker at
|
||||||
file and has no Docker access: it validates an edit and leaves it for the
|
`/jobs/` is a separate app with its own Claude calls.) It reaches the
|
||||||
host, which is the part trusted to act.
|
internal routes directly over the Docker network
|
||||||
|
(`http://$PYTHON_HOST:$PYTHON_PORT`, default `python:8000`), never through
|
||||||
|
Caddy, which answers 404 for `/py/internal/`:
|
||||||
|
|
||||||
- **`services/env_registry.json`** lists every variable in `.env.example`
|
| route | caller | sends | gets back |
|
||||||
with its group, kind, whether it is editable, and the compose services that
|
| --- | --- | --- | --- |
|
||||||
read it. It is embedded in the binary and read from the checkout by the host
|
| `/internal/rowing/read` | `POST /rowing` (`handlers/handle_rowing.go`) | `{media_type, data}` (image, base64) | `{timeMinutes, timeSeconds, distance}` |
|
||||||
script, so one file decides what the panel offers and what the host accepts.
|
Every route goes through one function, `services.CallPython[T]` in
|
||||||
A test fails if it and `.env.example` disagree.
|
`services/python_call.go`: marshal the body, POST it, decode a 200 into `T`.
|
||||||
- `GET /admin/env` — the registry plus state from this process's own
|
It has the one HTTP client (two-minute timeout, above the Python side's own
|
||||||
environment. A secret's value is never sent, only "set" and, for values of
|
worst case of a retried Claude call) and the one rule for failures:
|
||||||
12+ characters, the last four.
|
|
||||||
- `PUT /admin/env` — `{"set": {NAME: value}, "generate": [NAME]}`; `""`
|
|
||||||
clears. The whole batch is validated first. Control characters are refused
|
|
||||||
because `.env` is line oriented: a newline would let an edit to an allowed
|
|
||||||
variable write a second, arbitrary one. Generated values (32 random bytes,
|
|
||||||
hex) are returned once.
|
|
||||||
- The change is written to `/backend/env-apply/request.json` (`./env-apply/run`
|
|
||||||
on the host), `0600` and chowned to that directory's owner so the
|
|
||||||
unprivileged host user can read it. `env-apply/apply.py` claims it, rewrites
|
|
||||||
`.env`, recreates the affected services and writes `status.json`.
|
|
||||||
- `GET /admin/env/status` — `idle`, `pending`, `applying`, `applied` or
|
|
||||||
`failed`. `watcher: false` means a request has sat unclaimed for 15 seconds,
|
|
||||||
i.e. nothing on the host is watching. `DELETE /admin/env/pending` withdraws
|
|
||||||
an unclaimed request.
|
|
||||||
|
|
||||||
The backend is always among the recreated services, because the values the
|
- a **502 whose `detail` is a string** is a message the route wrote for a
|
||||||
panel shows are the ones this process started with.
|
person ("failed to parse image data"). It comes back as a
|
||||||
|
`*services.PythonError`, and the HTTP handler relays it to the browser;
|
||||||
|
- **anything else** — connection refused, a 422 (its `detail` is a list), a
|
||||||
|
503 for an unset `CLAUDE_API_KEY`, a reply that will not decode — is an
|
||||||
|
ordinary error. Callers log it and show something generic.
|
||||||
|
|
||||||
### Job capture
|
It lives in `services` so that a background job there could use it as well
|
||||||
|
as a handler. A new internal route needs only a
|
||||||
`handlers/handle_job_capture.go` is the server half of the browser userscript
|
request struct, a reply struct and a one-line call.
|
||||||
(`vue/public/job-capture.user.js`, installed from the tracker page) that adds
|
|
||||||
the posting open in the browser to the job tracker.
|
|
||||||
|
|
||||||
- **Auth** is `Authorization: Bearer <token>`, checked by
|
|
||||||
`CaptureTokenMiddleware`. The token opens these three routes and nothing
|
|
||||||
else — it cannot read the tracker or reach GraphQL. **With no token
|
|
||||||
generated the routes are off (503)**; that never means "no auth".
|
|
||||||
- **The token is generated in the admin panel**, not set in `.env`
|
|
||||||
(`services/capture_token.go`; `GET`/`POST`/`DELETE /admin/capture-token`,
|
|
||||||
cookie-authenticated like the rest of the admin group). It is 32 random
|
|
||||||
bytes, shown once; only its SHA-256 is kept, in
|
|
||||||
`/backend/token/job_capture_token.json` beside the OAuth tokens, so it
|
|
||||||
survives restarts and rebuilds. There is one token at a time: generating
|
|
||||||
again replaces it, which is how a leaked one is rotated.
|
|
||||||
- `GET /jobs/capture/status?url=` — is this posting already tracked, and at
|
|
||||||
what status. Drives the script's badge.
|
|
||||||
- `POST /jobs/capture/extract` — page text in, `{jobTitle, company, location,
|
|
||||||
notes}` out, read by Claude through the Python service
|
|
||||||
(`/internal/jobs/extract`). Stores nothing.
|
|
||||||
- `POST /jobs/capture` — an **upsert**. A posting is matched by its canonical
|
|
||||||
URL (`canonicalJobURL` strips tracking parameters and folds LinkedIn's
|
|
||||||
several URL shapes into one), then by `(company, job title)` the way the
|
|
||||||
email pipeline matches. A repeat capture only ever adds: status moves
|
|
||||||
forwards, empty fields are filled, nothing is overwritten.
|
|
||||||
|
|
||||||
The upsert is what keeps this and the email pipeline from making two rows for
|
|
||||||
one application. It is not watertight: the pipeline still matches on the exact
|
|
||||||
title, so a posting captured as "Senior Engineer" whose confirmation email
|
|
||||||
says "Senior Engineer (Platform)" becomes a second row.
|
|
||||||
|
|
||||||
## Services
|
## Services
|
||||||
|
|
||||||
Everything is constructed in `main` from environment variables and handed to
|
Everything is constructed in `main` from environment variables and handed to
|
||||||
`handlers.Store`. Nothing here fails start-up: a missing Spotify token, an
|
`handlers.Store`. Nothing here fails start-up: a missing Spotify token or an
|
||||||
unconfigured mailbox or an absent Steam key all just leave that feature
|
absent Steam key all just leave that feature
|
||||||
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||||
|
|
||||||
- **database.go** — Postgres via GORM. There are no migration files:
|
- **database.go** — Postgres via GORM. There are no migration files:
|
||||||
@@ -170,14 +235,21 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
|||||||
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
- **spotify.go**, **steam.go**, **gitea.go** — third-party reads. Results are
|
||||||
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
cached on `Store` with TTLs of 1 min (Spotify recent, Gitea) and 5 min
|
||||||
(Steam).
|
(Steam).
|
||||||
- **email_sync.go** / **email_imap.go** — the job-application pipeline: fetch
|
- **python_call.go** — `CallPython`, the one way to reach the Python service's
|
||||||
recent mail (Microsoft Graph *or* a hand-rolled IMAP client), keyword-filter
|
internal routes. See [Calling the Python service](#calling-the-python-service).
|
||||||
it, ask Claude to extract structured data, create or advance a
|
- **uploads.go** — every stored file. `Uploads.Save(ctx, fileHeader, private)`
|
||||||
`JobApplication`. Runs on a timer and can be triggered by an admin.
|
validates against `UploadTypes` (extension, stored Content-Type, content
|
||||||
- **claude.go** — the Anthropic client, used by the email pipeline. (The
|
sniff) and `MaxUploadSize`, names the file randomly, stores it and returns
|
||||||
rowing photo reader's and the job posting reader's Claude calls live in the
|
its `/uploads/...` URL; an `*UploadError` is the uploader's fault and safe
|
||||||
Python service; `POST /rowing` and `POST /jobs/capture/extract` reach it
|
to show them. Public files go to the Garage bucket wrapped in
|
||||||
directly at `http://$PYTHON_HOST:$PYTHON_PORT/internal/...`.)
|
`FallbackFileStore` (a failed S3 write is logged and retried on disk), or
|
||||||
|
to disk alone when `S3_ENDPOINT` is unset; private ones always to disk
|
||||||
|
(the edge cannot gate a bucket). Caddy serves `/uploads/` from the bucket
|
||||||
|
first and disk second, so either store's files work at the same URL. A new
|
||||||
|
handler that takes a file calls `store.Uploads.Save`. `Uploads.List` (behind
|
||||||
|
admin-only `GET /uploads`, for the canvas's upload picker) returns the union
|
||||||
|
of bucket and disk, allow-listed types only, newest first; it is admin-only
|
||||||
|
because listing would give away every unguessable URL.
|
||||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||||
@@ -205,16 +277,30 @@ the end of it — which is why shared helpers live in `*_helpers.go` instead.
|
|||||||
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
to the schema without a corresponding entry in `gqlgen.yml` gets you a fresh
|
||||||
generated struct rather than the model you expected.
|
generated struct rather than the model you expected.
|
||||||
|
|
||||||
|
One scalar-level binding in `gqlgen.yml` is worth knowing about: `ID` lists
|
||||||
|
both `graphql.IntID` and `graphql.UintID` (see IDs under Gotchas).
|
||||||
|
|
||||||
|
If you delete a field or stop needing a resolver, delete the resolver function
|
||||||
|
by hand before regenerating; otherwise gqlgen keeps it, commented out, in a
|
||||||
|
warning block at the end of the file.
|
||||||
|
|
||||||
## Gotchas
|
## Gotchas
|
||||||
|
|
||||||
- **Soft delete everywhere.** Every model except `ProcessedEmail` has a
|
- **Soft delete everywhere.** Every model has a `gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
||||||
`gorm.DeletedAt`, so `Delete` sets a timestamp and later queries filter the
|
|
||||||
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
row out. Rows are never actually removed, and a `uniqueIndex` still collides
|
||||||
with deleted rows — a soft-deleted username cannot be reused.
|
with deleted rows — a soft-deleted username cannot be reused.
|
||||||
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
- **`Preload` is not lazy.** `Post.Author` is nil unless the query preloads it;
|
||||||
there is no error to tell you why the field came back null.
|
there is no error to tell you why the field came back null.
|
||||||
- **IDs.** Models use `uint`, GraphQL uses `Int`. That is why nearly every type
|
- **IDs.** Models use `uint`; the schema uses `ID`. `gqlgen.yml` binds `ID` to
|
||||||
has a hand-written `ID` resolver doing `int(obj.ID)`.
|
`graphql.IntID` *and* `graphql.UintID`, so a model's `ID uint` field is
|
||||||
|
served directly — there are no `ID` resolvers, and a new type does not need
|
||||||
|
one. `IntID` is listed first, which is why resolver *arguments* are still
|
||||||
|
`id int`. Both write an id as a quoted decimal string (`"12"`) and accept a
|
||||||
|
string or a number, so the wire format is the same either way. Other
|
||||||
|
unsigned fields are not IDs and still have resolvers: `Message.authorId`,
|
||||||
|
`Rowing.time`, `Rowing.distance`.
|
||||||
|
- **Deletes error on a missing id.** Every delete mutation loads the row
|
||||||
|
first, so a wrong id is a `record not found` error.
|
||||||
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
- **`Message.AuthorID` is not a user id.** It is a per-process counter handed
|
||||||
out by the chat hub on connect, meaningless across restarts.
|
out by the chat hub on connect, meaningless across restarts.
|
||||||
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
- **The chat table is capped.** Every insert soft-deletes all but the newest
|
||||||
@@ -222,19 +308,10 @@ generated struct rather than the model you expected.
|
|||||||
- **Store's caches are unsynchronised** and shared by all requests. The races
|
- **Store's caches are unsynchronised** and shared by all requests. The races
|
||||||
are benign (at worst a duplicate upstream fetch), but do not add a field
|
are benign (at worst a duplicate upstream fetch), but do not add a field
|
||||||
there that would be unsafe to tear.
|
there that would be unsafe to tear.
|
||||||
- **Claude output is parsed as JSON** after stripping a possible markdown code
|
- **Claude's output is never parsed here.** Prompts, the markdown-fence
|
||||||
fence — `services.StripMarkdownFence` in `email_sync.go`, with a port of it
|
stripping and the JSON parsing are all in the Python service; this side
|
||||||
in `python/app/rowing.py` for the rowing photo reader.
|
receives typed JSON or an error (see
|
||||||
- **The email pipeline retries a failure up to `maxEmailAttempts` (3) times.**
|
[Calling the Python service](#calling-the-python-service)).
|
||||||
A failed email is recorded with action `"error"` and an attempt counter;
|
|
||||||
while it has attempts left the next sync reprocesses it and updates the same
|
|
||||||
row. Because the fetch window is anchored to *processing* time, which has
|
|
||||||
already moved past the failure, the sync also rewinds the window to the
|
|
||||||
oldest retryable row's `ReceivedAt` — otherwise the email could never be
|
|
||||||
re-fetched. Once the cap is reached the row is terminal, so an email Claude
|
|
||||||
can never parse stops costing API calls.
|
|
||||||
- **Authenticating email after start-up does not start the scheduler**, which
|
|
||||||
only checks readiness once — restart, or trigger syncs by hand.
|
|
||||||
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
- **Introspection and the playground are off** unless `DEV_MODE=true` *and*
|
||||||
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
`GQL_INTROSPECTION` / `GQL_PLAYGROUND` are set.
|
||||||
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
- **No graceful shutdown.** `r.Run` blocks forever and its error is ignored;
|
||||||
@@ -253,15 +330,15 @@ generated struct rather than the model you expected.
|
|||||||
| `SEED_DB` | seed dev test data (never in production) |
|
| `SEED_DB` | seed dev test data (never in production) |
|
||||||
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
| `GQL_INTROSPECTION` / `GQL_PLAYGROUND` | dev-only GraphQL extras |
|
||||||
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
| `SPOTIFY_CLIENT_ID` / `_SECRET` / `_REDIRECT_URI` / `SPOTIFY_AUTH_STATE` | Spotify OAuth |
|
||||||
| `CLAUDE_API_KEY` | Anthropic API (email pipeline; the python service reads it too) |
|
|
||||||
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
|
| `PYTHON_HOST` / `PYTHON_PORT` | Python service, for the rowing photo reader (default `python:8000`) |
|
||||||
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
| `GITEA_HOST` / `GITEA_PORT` | Gitea activity feed |
|
||||||
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
| `STEAM_API_KEY` / `STEAM_ID` | Steam presence |
|
||||||
| `EMAIL_SYNC_ENABLED` / `EMAIL_BACKEND` / `EMAIL_SYNC_INTERVAL` | email pipeline (`graph` or `imap`) |
|
|
||||||
| `MSGRAPH_CLIENT_ID` / `_SECRET` / `_TENANT_ID` / `_REDIRECT_URI` | Microsoft Graph backend |
|
|
||||||
| `IMAP_HOST` / `_PORT` / `_EMAIL` / `_PASSWORD` | IMAP backend |
|
|
||||||
|
|
||||||
Paths baked into the code, all inside mounted volumes so they survive a
|
Paths baked into the code, all inside mounted volumes so they survive a
|
||||||
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
container restart: `/backend/logs`, `/backend/notes`, `/backend/uploads`,
|
||||||
`/backend/fallback_music`, `/backend/token/` (Spotify and Microsoft Graph
|
`/backend/fallback_music`, `/backend/token/` (the Spotify OAuth token).
|
||||||
OAuth tokens).
|
|
||||||
|
`CLAUDE_API_KEY` is not in the table: the backend does not read it. The
|
||||||
|
`python` and `jobs` containers, the two that use it, get it through their
|
||||||
|
explicit `environment:` lists in `docker-compose.yml`. The email and job-lead variables still in `.env` belong to the job
|
||||||
|
tracker (`jobs`), which has its own repo and README.
|
||||||
|
|||||||
+39
-33
@@ -1,41 +1,53 @@
|
|||||||
module adam-french.co.uk/backend
|
module adam-french.co.uk/backend
|
||||||
|
|
||||||
go 1.26
|
go 1.26.0
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/99designs/gqlgen v0.17.95
|
github.com/99designs/gqlgen v0.17.98
|
||||||
github.com/anthropics/anthropic-sdk-go v1.26.0
|
github.com/aws/aws-sdk-go-v2 v1.48.0
|
||||||
github.com/gin-gonic/gin v1.11.0
|
github.com/aws/aws-sdk-go-v2/credentials v1.21.0
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10
|
||||||
|
github.com/gin-gonic/gin v1.12.0
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.1
|
||||||
github.com/gorilla/websocket v1.5.3
|
github.com/gorilla/websocket v1.5.3
|
||||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
|
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd
|
||||||
github.com/vektah/gqlparser/v2 v2.5.37
|
github.com/vektah/gqlparser/v2 v2.5.64
|
||||||
github.com/zmb3/spotify/v2 v2.4.3
|
github.com/zmb3/spotify/v2 v2.4.3
|
||||||
golang.org/x/crypto v0.55.0
|
golang.org/x/crypto v0.59.0
|
||||||
golang.org/x/oauth2 v0.30.0
|
golang.org/x/oauth2 v0.38.0
|
||||||
gorm.io/driver/postgres v1.6.0
|
gorm.io/driver/postgres v1.6.3
|
||||||
gorm.io/gorm v1.31.1
|
gorm.io/gorm v1.31.2
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/agnivade/levenshtein v1.2.1 // indirect
|
github.com/agnivade/levenshtein v1.2.2 // indirect
|
||||||
github.com/bytedance/sonic v1.14.0 // indirect
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 // indirect
|
||||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 // indirect
|
||||||
|
github.com/aws/smithy-go v1.28.9 // indirect
|
||||||
|
github.com/bytedance/gopkg v0.1.3 // indirect
|
||||||
|
github.com/bytedance/sonic v1.15.0 // indirect
|
||||||
|
github.com/bytedance/sonic/loader v0.5.0 // indirect
|
||||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||||
github.com/coder/websocket v1.8.15 // indirect
|
github.com/coder/websocket v1.8.15 // indirect
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
github.com/gabriel-vasile/mimetype v1.4.12 // indirect
|
||||||
github.com/gin-contrib/sse v1.1.0 // indirect
|
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||||
github.com/go-playground/locales v0.14.1 // indirect
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
github.com/go-playground/validator/v10 v10.30.1 // indirect
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||||
github.com/goccy/go-json v0.10.2 // indirect
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
github.com/jackc/pgx/v5 v5.10.0 // indirect
|
||||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
github.com/jinzhu/now v1.1.5 // indirect
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
@@ -43,25 +55,19 @@ require (
|
|||||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||||
github.com/quic-go/qpack v0.5.1 // indirect
|
github.com/quic-go/qpack v0.6.0 // indirect
|
||||||
github.com/quic-go/quic-go v0.54.0 // indirect
|
github.com/quic-go/quic-go v0.59.0 // indirect
|
||||||
github.com/sosodev/duration v1.4.0 // indirect
|
github.com/sosodev/duration v1.4.0 // indirect
|
||||||
github.com/tidwall/gjson v1.18.0 // indirect
|
|
||||||
github.com/tidwall/match v1.1.1 // indirect
|
|
||||||
github.com/tidwall/pretty v1.2.1 // indirect
|
|
||||||
github.com/tidwall/sjson v1.2.5 // indirect
|
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
github.com/ugorji/go/codec v1.3.0 // indirect
|
github.com/ugorji/go/codec v1.3.1 // indirect
|
||||||
go.uber.org/mock v0.5.0 // indirect
|
go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect
|
||||||
golang.org/x/arch v0.20.0 // indirect
|
golang.org/x/arch v0.22.0 // indirect
|
||||||
golang.org/x/mod v0.40.0 // indirect
|
golang.org/x/net v0.62.0 // indirect
|
||||||
golang.org/x/net v0.58.0 // indirect
|
golang.org/x/sync v0.25.0 // indirect
|
||||||
golang.org/x/sync v0.22.0 // indirect
|
golang.org/x/sys v0.50.0 // indirect
|
||||||
golang.org/x/sys v0.47.0 // indirect
|
golang.org/x/text v0.44.0 // indirect
|
||||||
golang.org/x/text v0.41.0 // indirect
|
|
||||||
golang.org/x/tools v0.49.0 // indirect
|
|
||||||
google.golang.org/protobuf v1.36.12 // indirect
|
google.golang.org/protobuf v1.36.12 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
+85
-70
@@ -31,20 +31,44 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
|
|||||||
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
|
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
|
||||||
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
|
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
|
||||||
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
|
||||||
github.com/99designs/gqlgen v0.17.95 h1:882h7F5iJImgtyUVttc4MOK2NbzbMYc2oyNeHqkjpP4=
|
github.com/99designs/gqlgen v0.17.98 h1:t7UTlygkXMx1tJmKyR0LxttcufXnJ7fF6fAaeHSofAc=
|
||||||
github.com/99designs/gqlgen v0.17.95/go.mod h1:kHYPrpwOXDU1OQyxIg3Z7nVXSnlUoHVWBY7CMJCAM4M=
|
github.com/99designs/gqlgen v0.17.98/go.mod h1:tIoiUl+cgIT7nayvObZkKDgplxd1pHcUAmEXAyv+8f4=
|
||||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
github.com/agnivade/levenshtein v1.2.2 h1:fI8RgiztYX1Nn5pBHHqQ9EMCCklhrmXqPRIedFmx5M4=
|
||||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
github.com/agnivade/levenshtein v1.2.2/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||||
github.com/anthropics/anthropic-sdk-go v1.26.0 h1:oUTzFaUpAevfuELAP1sjL6CQJ9HHAfT7CoSYSac11PY=
|
|
||||||
github.com/anthropics/anthropic-sdk-go v1.26.0/go.mod h1:qUKmaW+uuPB64iy1l+4kOSvaLqPXnHTTBKH6RVZ7q5Q=
|
|
||||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
github.com/aws/aws-sdk-go-v2 v1.48.0 h1:tFU7EJVm7MfyaXLsXdYTZ0Vd6vwt9OljCyqq0gqk0Mc=
|
||||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
github.com/aws/aws-sdk-go-v2 v1.48.0/go.mod h1:oeKU5p+TQBnpeLmU42WZLWvzv+ORLn+74n4QVLnm/Z0=
|
||||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27 h1:3dMP9eEmHVosFN1QiD24IJBKVY8m6iUfVYXqRCT118Q=
|
||||||
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.27/go.mod h1:KH4PKcqtjy1m0656eqQV2v53xE04ddJzuNloEKqlHkI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.21.0 h1:OViwhqeipkQzSHuO2eQDUCdLrI6r3nzGxFUyM8GqnCs=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.21.0/go.mod h1:OffaVQod3fyZzhZJyPtw11WpHPF1uIHADc+/MYlXmbA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12 h1:W0yUUzKBA8SofGQ0yZafEUuZq9UxfvijRgdc6vcRQPA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.12/go.mod h1:xwKv6vwBNdpPFOxEm/ld4IODZK2s/1ksHvdBqLfH6Gs=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12 h1:lqSi8qvAnKC1vfosImdmOsuiJLr/jdybZX5299beB6Q=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.12/go.mod h1:rqPQE2vqkW9YHx5+Gp55sx1wsTM4xtGQLl+TKMjxxrs=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12 h1:uvX2yaL+aMjkmnrLPPlR/zwjoKFRMoNhhJfeGjfk6qc=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.12/go.mod h1:dicT+2eNhHHqGkxHO7LoXw3QghIUGuzgdmFqaSTopgI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25 h1:rKwkY3Z+fvt2W0msjdNs6uNewPmXzPayQ961oyuWhes=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.25/go.mod h1:dBuAadQKd1F4Q4ZOg8gnFmuSHMRE40Pe3IfFwbtC4lE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13 h1:U5HZ8FpTr6tyvulf1nT11Nw4KG1CAsXkuQGdUrIjZ/E=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.13/go.mod h1:dUfvCU1NaE+b3vqNENDiJncUQW7Djl5pmgUlcjesVqk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12 h1:wzAqMZ2O4+ij9HQqIrk+P9PBGacE0wOTuWB7Mo97//I=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.12/go.mod h1:/0TfyruByHsOlphzP26xDTRe2DKD0J1I1Uyy2TyP8EI=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12 h1:H0IaQayT3TLiGIHiNnleQZTbndDlx7LGZ0NWZ5mDwjA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.12/go.mod h1:YuJJNxaOjnknLIrscBmkLhIpnmg9LzHd25sQRKUboGU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10 h1:WBJb2VxRzzKnuN94YWqZPiu5a5zc3IleFqgZnmVCyvU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.10/go.mod h1:8NhAIBVYkVHq0hIbbzujdoou0VkKwMdG+De9e5oX6qI=
|
||||||
|
github.com/aws/smithy-go v1.28.9 h1:zkZ058OpNX0iGTK24b+ZUEQSMc11CBA6oO7xtKZfzkY=
|
||||||
|
github.com/aws/smithy-go v1.28.9/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||||
|
github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M=
|
||||||
|
github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM=
|
||||||
|
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
|
||||||
|
github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k=
|
||||||
|
github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE=
|
||||||
|
github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo=
|
||||||
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
|
||||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
||||||
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
|
||||||
@@ -60,18 +84,16 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
|
|||||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
|
||||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
|
||||||
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
|
||||||
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
|
||||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
|
github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw=
|
||||||
github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
|
github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||||
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||||
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||||
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=
|
||||||
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc=
|
||||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||||
@@ -81,16 +103,16 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
|
|||||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w=
|
||||||
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM=
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||||
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||||
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||||
@@ -155,8 +177,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
|||||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0=
|
||||||
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
@@ -177,18 +199,21 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
|||||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
|
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||||
|
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||||
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
|
||||||
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
|
||||||
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
|
||||||
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
|
||||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
|
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd h1:CmH9+J6ZSsIjUK3dcGsnCnO41eRBOnY12zwkn5qVwgc=
|
||||||
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
|
github.com/rwcarlsen/goexif v0.0.0-20190401172101-9e8deecbddbd/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
|
||||||
@@ -197,47 +222,41 @@ github.com/sosodev/duration v1.4.0/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERA
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||||
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||||
github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
|
||||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
|
||||||
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
|
|
||||||
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
|
|
||||||
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
|
|
||||||
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
|
||||||
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
|
|
||||||
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
|
|
||||||
github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
|
||||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY=
|
||||||
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
github.com/vektah/gqlparser/v2 v2.5.37 h1:jbb1Ilv+xBklV6653tKb4oVUupPNTLb5LmrnBKVI12Y=
|
github.com/vektah/gqlparser/v2 v2.5.64 h1:N32yM6hQ6Kd5RdjCCEJsUrbCebVoA9yLLMOIa88Mkk0=
|
||||||
github.com/vektah/gqlparser/v2 v2.5.37/go.mod h1:9O4Ox6Ngd3Y12bMD3w6i3CRQXh8W1oC1q0m6olCymDM=
|
github.com/vektah/gqlparser/v2 v2.5.64/go.mod h1:nILRSUbsWDTuf8hSmAgFxuYh0SaMZdkvl6JSEbkJX8g=
|
||||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
github.com/zmb3/spotify/v2 v2.4.3 h1:4divquzK2Mzo90XVIij4K7Z98Hf+6A3qPnksqtcDIuo=
|
github.com/zmb3/spotify/v2 v2.4.3 h1:4divquzK2Mzo90XVIij4K7Z98Hf+6A3qPnksqtcDIuo=
|
||||||
github.com/zmb3/spotify/v2 v2.4.3/go.mod h1:XOV7BrThayFYB9AAfB+L0Q0wyxBuLCARk4fI/ZXCBW8=
|
github.com/zmb3/spotify/v2 v2.4.3/go.mod h1:XOV7BrThayFYB9AAfB+L0Q0wyxBuLCARk4fI/ZXCBW8=
|
||||||
|
go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE=
|
||||||
|
go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0=
|
||||||
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
|
||||||
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
|
||||||
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||||
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||||
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
|
||||||
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y=
|
||||||
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU=
|
||||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||||
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
|
||||||
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
@@ -246,8 +265,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh
|
|||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
|
||||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||||
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
|
||||||
@@ -280,8 +299,6 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
|||||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
||||||
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
|
||||||
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
|
||||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||||
@@ -314,16 +331,16 @@ golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
|||||||
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
|
||||||
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
|
||||||
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
|
||||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||||
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
|
||||||
golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
golang.org/x/oauth2 v0.0.0-20210810183815-faf39c7919d5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A=
|
||||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
golang.org/x/oauth2 v0.38.0 h1:uW7XQbcu1eoiQS7uMJvLOjPMl04bTbmY1VeRPxvbspI=
|
||||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
golang.org/x/oauth2 v0.38.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
@@ -334,8 +351,8 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJ
|
|||||||
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
@@ -369,8 +386,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|||||||
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
@@ -386,8 +403,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|||||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
|
||||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||||
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||||
@@ -433,8 +450,6 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc
|
|||||||
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
|
||||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
|
||||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
@@ -522,14 +537,14 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
|||||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
|
||||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
|
||||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
gorm.io/driver/postgres v1.6.3 h1:bAn6O2pUa8LtpWEvL5NFU4+52Tfx8Ut7IVaIacCLcI0=
|
||||||
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
gorm.io/driver/postgres v1.6.3/go.mod h1:0c4fQA44XhOklXDkgtuKqysHCycTa5i9e3EIpDGCwXk=
|
||||||
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||||
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||||
|
gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
|
||||||
|
gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||||
|
|||||||
+59
-12
@@ -16,9 +16,16 @@ resolver:
|
|||||||
filename_template: "{name}.resolvers.go"
|
filename_template: "{name}.resolvers.go"
|
||||||
|
|
||||||
models:
|
models:
|
||||||
|
# Two bindings, tried in order. IntID comes first, so it is what gqlgen
|
||||||
|
# picks where it has a free choice — resolver arguments stay `id int`.
|
||||||
|
# UintID is there so a model's `ID uint` field binds to `id: ID!` directly,
|
||||||
|
# with no hand-written resolver converting it. Both write an id as a quoted
|
||||||
|
# decimal string ("12") and read a string or a number, so which one a field
|
||||||
|
# uses is invisible on the wire.
|
||||||
ID:
|
ID:
|
||||||
model:
|
model:
|
||||||
- github.com/99designs/gqlgen/graphql.IntID
|
- github.com/99designs/gqlgen/graphql.IntID
|
||||||
|
- github.com/99designs/gqlgen/graphql.UintID
|
||||||
User:
|
User:
|
||||||
model:
|
model:
|
||||||
- adam-french.co.uk/backend/models.User
|
- adam-french.co.uk/backend/models.User
|
||||||
@@ -27,6 +34,10 @@ models:
|
|||||||
resolver: false
|
resolver: false
|
||||||
deletedAt:
|
deletedAt:
|
||||||
resolver: false
|
resolver: false
|
||||||
|
# Not a database model: the fixed registry in services/permissions.go.
|
||||||
|
PermissionType:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/services.PermissionType
|
||||||
Post:
|
Post:
|
||||||
model:
|
model:
|
||||||
- adam-french.co.uk/backend/models.Post
|
- adam-french.co.uk/backend/models.Post
|
||||||
@@ -63,21 +74,57 @@ models:
|
|||||||
fields:
|
fields:
|
||||||
deletedAt:
|
deletedAt:
|
||||||
resolver: false
|
resolver: false
|
||||||
JobApplication:
|
|
||||||
model:
|
|
||||||
- adam-french.co.uk/backend/models.JobApplication
|
|
||||||
fields:
|
|
||||||
deletedAt:
|
|
||||||
resolver: false
|
|
||||||
JobAppReference:
|
|
||||||
model:
|
|
||||||
- adam-french.co.uk/backend/models.JobAppReference
|
|
||||||
fields:
|
|
||||||
deletedAt:
|
|
||||||
resolver: false
|
|
||||||
Place:
|
Place:
|
||||||
model:
|
model:
|
||||||
- adam-french.co.uk/backend/models.Place
|
- adam-french.co.uk/backend/models.Place
|
||||||
fields:
|
fields:
|
||||||
deletedAt:
|
deletedAt:
|
||||||
resolver: false
|
resolver: false
|
||||||
|
Box:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.Box
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
Page:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.Page
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
Background:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.Background
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
Layout:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.Layout
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
boxCount:
|
||||||
|
resolver: true
|
||||||
|
hasBackground:
|
||||||
|
resolver: true
|
||||||
|
Component:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.Component
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
uses:
|
||||||
|
resolver: true
|
||||||
|
CoverLetter:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.CoverLetter
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
CoverSnippet:
|
||||||
|
model:
|
||||||
|
- adam-french.co.uk/backend/models.CoverSnippet
|
||||||
|
fields:
|
||||||
|
deletedAt:
|
||||||
|
resolver: false
|
||||||
|
|||||||
@@ -3,28 +3,17 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *activityResolver) ID(ctx context.Context, obj *models.Activity) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateActivity is the resolver for the createActivity field.
|
// CreateActivity is the resolver for the createActivity field.
|
||||||
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
func (r *mutationResolver) CreateActivity(ctx context.Context, input model.CreateActivityInput) (*models.Activity, error) {
|
||||||
// No middleware guards GraphQL, so each mutation checks for itself.
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
activity := models.Activity{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||||
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
if err := r.Store.DB.Create(&activity).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -41,8 +30,3 @@ func (r *queryResolver) Activities(ctx context.Context) ([]*models.Activity, err
|
|||||||
}
|
}
|
||||||
return ptrs(activities), nil
|
return ptrs(activities), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Activity returns ActivityResolver implementation.
|
|
||||||
func (r *Resolver) Activity() ActivityResolver { return &activityResolver{r} }
|
|
||||||
|
|
||||||
type activityResolver struct{ *Resolver }
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -19,12 +19,7 @@ import (
|
|||||||
|
|
||||||
// Login is the resolver for the login field.
|
// Login is the resolver for the login field.
|
||||||
func (r *mutationResolver) Login(ctx context.Context, input model.LoginInput) (*model.AuthPayload, error) {
|
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
|
// Gin context for the client IP and cookies. Shares the REST login's limiter.
|
||||||
// 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.
|
|
||||||
gc := GinContextFromCtx(ctx)
|
gc := GinContextFromCtx(ctx)
|
||||||
if gc == nil {
|
if gc == nil {
|
||||||
return nil, fmt.Errorf("could not get gin context")
|
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")
|
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
|
var user models.User
|
||||||
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
if err := r.Store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||||
return nil, fmt.Errorf("invalid credentials")
|
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)
|
services.SetAuthCookies(gc, r.Store.Auth.Config, tokens)
|
||||||
|
|
||||||
// The payload carries no token: the tokens only ever travel as HttpOnly
|
// Tokens travel only as HttpOnly cookies.
|
||||||
// cookies, so client JavaScript never sees them.
|
|
||||||
return &model.AuthPayload{User: &user}, nil
|
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")
|
return false, fmt.Errorf("could not get gin context")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bumping the token version is what actually revokes the tokens; clearing
|
// Best effort, always succeeds, like the REST endpoint.
|
||||||
// the cookies only stops the browser presenting them. Both are best
|
|
||||||
// effort and logout always reports success, matching the REST endpoint.
|
|
||||||
if userID, ok := UserIDFromCtx(ctx); ok {
|
if userID, ok := UserIDFromCtx(ctx); ok {
|
||||||
// The context only carries claims from a token that already
|
// Claims in ctx are already verified, so this can't target others.
|
||||||
// verified, so this cannot be used to revoke someone else's sessions.
|
|
||||||
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
|
if err := services.BumpTokenVersion(r.Store.DB, userID); err != nil {
|
||||||
log.Printf("logout: failed to revoke tokens for user %d: %v", userID, err)
|
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")
|
return nil, fmt.Errorf("unauthorized")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared with the REST refresh endpoint, but the messages below are the
|
// Re-reads admin and token version from the DB.
|
||||||
// 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.
|
|
||||||
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
|
user, err := r.Store.Auth.AuthenticateToken(r.Store.DB, refreshToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch {
|
switch {
|
||||||
@@ -121,13 +106,12 @@ func (r *mutationResolver) RefreshToken(ctx context.Context) (*model.AuthPayload
|
|||||||
|
|
||||||
// Me is the resolver for the me field.
|
// Me is the resolver for the me field.
|
||||||
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
func (r *queryResolver) Me(ctx context.Context) (*models.User, error) {
|
||||||
|
// Not @signedIn: this query's error has always been "unauthorized".
|
||||||
userID, ok := UserIDFromCtx(ctx)
|
userID, ok := UserIDFromCtx(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unauthorized")
|
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
|
var user models.User
|
||||||
user.ID = userID
|
user.ID = userID
|
||||||
if err := r.Store.DB.First(&user).Error; err != nil {
|
if err := r.Store.DB.First(&user).Error; err != nil {
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SetBackground is the resolver for the setBackground field.
|
||||||
|
func (r *mutationResolver) SetBackground(ctx context.Context, page string, input model.BackgroundInput) (*models.Background, error) {
|
||||||
|
// One row per page: replaced in place if there is one, so its id stays
|
||||||
|
// stable for the store on the front end.
|
||||||
|
bg, err := backgroundFrom(page, input)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var existing models.Background
|
||||||
|
err = r.Store.DB.Where("page = ?", page).First(&existing).Error
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
bg.ID, bg.CreatedAt = existing.ID, existing.CreatedAt
|
||||||
|
err = r.Store.DB.Save(&bg).Error
|
||||||
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
err = r.Store.DB.Create(&bg).Error
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &bg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ClearBackground is the resolver for the clearBackground field.
|
||||||
|
func (r *mutationResolver) ClearBackground(ctx context.Context, page string) (bool, error) {
|
||||||
|
res := r.Store.DB.Where("page = ?", page).Delete(&models.Background{})
|
||||||
|
return res.RowsAffected > 0, res.Error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Background is the resolver for the background field.
|
||||||
|
func (r *queryResolver) Background(ctx context.Context, page string) (*models.Background, error) {
|
||||||
|
// Null, not an error, when the page has none: that is the default look.
|
||||||
|
// Hidden along with an adminOnly page, like its boxes.
|
||||||
|
hidden, err := pageHiddenFrom(ctx, r.Store.DB, page)
|
||||||
|
if err != nil || hidden {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var bg models.Background
|
||||||
|
err = r.Store.DB.Where("page = ?", page).First(&bg).Error
|
||||||
|
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &bg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// Hand-written helpers for background.resolvers.go, kept out of the resolver
|
||||||
|
// file for the same reason as box_helpers.go.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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".
|
||||||
|
bgColorPattern = regexp.MustCompile(`^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+|(rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z.,%/ -]*\))$`)
|
||||||
|
// A site path (an upload, /img/...) or an http(s) URL, with no quotes,
|
||||||
|
// brackets, backslashes or spaces.
|
||||||
|
bgImagePattern = regexp.MustCompile(`^(/|https?://)[^\s"'()\\<>]*$`)
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxBgImageLen = 1000
|
||||||
|
|
||||||
|
var bgFits = map[string]bool{"cover": true, "contain": true, "tile": true}
|
||||||
|
|
||||||
|
// backgroundFrom validates input into a Background for page.
|
||||||
|
func backgroundFrom(page string, input model.BackgroundInput) (models.Background, error) {
|
||||||
|
bg := models.Background{
|
||||||
|
Page: page,
|
||||||
|
Color: strings.TrimSpace(input.Color),
|
||||||
|
Image: strings.TrimSpace(input.Image),
|
||||||
|
Fit: input.Fit,
|
||||||
|
}
|
||||||
|
if !validPageKey(page) {
|
||||||
|
return bg, errors.New("a background needs a valid page")
|
||||||
|
}
|
||||||
|
if bg.Color != "" && (len(bg.Color) > 64 || !bgColorPattern.MatchString(bg.Color)) {
|
||||||
|
return bg, errors.New(`colour must be a CSS colour such as #1b110e, black or rgb(0 0 0 / 50%)`)
|
||||||
|
}
|
||||||
|
if bg.Image != "" && (len(bg.Image) > maxBgImageLen || !bgImagePattern.MatchString(bg.Image)) {
|
||||||
|
return bg, errors.New("image must be a path on this site (e.g. /uploads/...) or an http(s) URL, without spaces or quotes")
|
||||||
|
}
|
||||||
|
if !bgFits[bg.Fit] {
|
||||||
|
return bg, errors.New(`fit must be "cover", "contain" or "tile"`)
|
||||||
|
}
|
||||||
|
return bg, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBackgroundFrom(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
page string
|
||||||
|
input model.BackgroundInput
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"index", model.BackgroundInput{Color: "#102030", Fit: "cover"}, true},
|
||||||
|
{"shrines/gto", model.BackgroundInput{Image: "/uploads/abc.gif", Fit: "tile"}, true},
|
||||||
|
{"stp", model.BackgroundInput{Color: "rgb(0 0 0 / 50%)", Image: "https://example.com/a.png", Fit: "contain"}, true},
|
||||||
|
{"index", model.BackgroundInput{Color: "rebeccapurple", Fit: "cover"}, true},
|
||||||
|
{"index", model.BackgroundInput{Fit: "cover"}, true}, // plain theme colour
|
||||||
|
{"Index", model.BackgroundInput{Fit: "cover"}, false}, // bad page key
|
||||||
|
{"index", model.BackgroundInput{Fit: "stretch"}, false}, // unknown fit
|
||||||
|
{"index", model.BackgroundInput{Color: "red; color: blue", Fit: "cover"}, false},
|
||||||
|
{"index", model.BackgroundInput{Color: "url(/x.png)", Fit: "cover"}, false}, // an image in disguise
|
||||||
|
{"index", model.BackgroundInput{Image: `/x.png") , url("/y`, Fit: "cover"}, false},
|
||||||
|
{"index", model.BackgroundInput{Image: "javascript:alert(1)", Fit: "cover"}, false},
|
||||||
|
{"index", model.BackgroundInput{Image: "uploads/relative.png", Fit: "cover"}, false},
|
||||||
|
} {
|
||||||
|
_, err := backgroundFrom(c.page, c.input)
|
||||||
|
if (err == nil) != c.ok {
|
||||||
|
t.Errorf("backgroundFrom(%q, %+v) = %v, want ok=%v", c.page, c.input, err, c.ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,26 +3,17 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *bookmarkResolver) ID(ctx context.Context, obj *models.Bookmark) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateBookmark is the resolver for the createBookmark field.
|
// CreateBookmark is the resolver for the createBookmark field.
|
||||||
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.CreateBookmarkInput) (*models.Bookmark, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
bookmark := models.Bookmark{Category: input.Category, Name: input.Name, Link: input.Link}
|
||||||
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
if err := r.Store.DB.Create(&bookmark).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -32,12 +23,7 @@ func (r *mutationResolver) CreateBookmark(ctx context.Context, input model.Creat
|
|||||||
|
|
||||||
// DeleteBookmark is the resolver for the deleteBookmark field.
|
// DeleteBookmark is the resolver for the deleteBookmark field.
|
||||||
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
func (r *mutationResolver) DeleteBookmark(ctx context.Context, id int) (*models.Bookmark, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
// Loaded first so the deleted record can be returned and a bad id is "not found".
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
// Loaded first so the deleted record can be returned to the client, and
|
|
||||||
// so a missing id is a clean "not found" rather than a silent no-op.
|
|
||||||
// Delete is a soft delete: deleted_at is set and the row stays.
|
|
||||||
var bookmark models.Bookmark
|
var bookmark models.Bookmark
|
||||||
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
if err := r.Store.DB.First(&bookmark, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -56,8 +42,3 @@ func (r *queryResolver) Bookmarks(ctx context.Context) ([]*models.Bookmark, erro
|
|||||||
}
|
}
|
||||||
return ptrs(bookmarks), nil
|
return ptrs(bookmarks), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bookmark returns BookmarkResolver implementation.
|
|
||||||
func (r *Resolver) Bookmark() BookmarkResolver { return &bookmarkResolver{r} }
|
|
||||||
|
|
||||||
type bookmarkResolver struct{ *Resolver }
|
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateBox is the resolver for the createBox field.
|
||||||
|
func (r *mutationResolver) CreateBox(ctx context.Context, input model.CreateBoxInput) (*models.Box, error) {
|
||||||
|
// Framed defaults here, not in the gorm tag; see models.Box.Framed.
|
||||||
|
box := models.Box{
|
||||||
|
Page: input.Page,
|
||||||
|
Kind: input.Kind,
|
||||||
|
Widget: input.Widget,
|
||||||
|
HTML: input.HTML,
|
||||||
|
Title: input.Title,
|
||||||
|
W: 300,
|
||||||
|
H: 200,
|
||||||
|
Framed: true,
|
||||||
|
}
|
||||||
|
setInt(&box.X, input.X)
|
||||||
|
setInt(&box.Y, input.Y)
|
||||||
|
setInt(&box.W, input.W)
|
||||||
|
setInt(&box.H, input.H)
|
||||||
|
setInt(&box.Z, input.Z)
|
||||||
|
if input.Framed != nil {
|
||||||
|
box.Framed = *input.Framed
|
||||||
|
}
|
||||||
|
if input.Shadow != nil {
|
||||||
|
box.Shadow = *input.Shadow
|
||||||
|
}
|
||||||
|
if input.HideOnMobile != nil {
|
||||||
|
box.HideOnMobile = *input.HideOnMobile
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
box.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
// A linked box's own html would only go stale.
|
||||||
|
if input.ComponentID != nil {
|
||||||
|
id := uint(*input.ComponentID)
|
||||||
|
exists, err := componentExists(r.Store.DB, id)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("there is no such component")
|
||||||
|
}
|
||||||
|
box.Kind = "html"
|
||||||
|
box.Widget = nil
|
||||||
|
box.HTML = nil
|
||||||
|
box.ComponentID = &id
|
||||||
|
}
|
||||||
|
if err := validateBox(&box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Create(&box).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &box, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateBox is the resolver for the updateBox field.
|
||||||
|
func (r *mutationResolver) UpdateBox(ctx context.Context, id int, input model.UpdateBoxInput) (*models.Box, error) {
|
||||||
|
// Partial: 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
|
||||||
|
}
|
||||||
|
if input.Widget != nil {
|
||||||
|
box.Widget = input.Widget
|
||||||
|
}
|
||||||
|
if input.HTML != nil {
|
||||||
|
// 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")
|
||||||
|
}
|
||||||
|
box.HTML = input.HTML
|
||||||
|
}
|
||||||
|
if input.Title != nil {
|
||||||
|
box.Title = input.Title
|
||||||
|
}
|
||||||
|
setInt(&box.X, input.X)
|
||||||
|
setInt(&box.Y, input.Y)
|
||||||
|
setInt(&box.W, input.W)
|
||||||
|
setInt(&box.H, input.H)
|
||||||
|
setInt(&box.Z, input.Z)
|
||||||
|
if input.Framed != nil {
|
||||||
|
box.Framed = *input.Framed
|
||||||
|
}
|
||||||
|
if input.Shadow != nil {
|
||||||
|
box.Shadow = *input.Shadow
|
||||||
|
}
|
||||||
|
if input.HideOnMobile != nil {
|
||||||
|
box.HideOnMobile = *input.HideOnMobile
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
box.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
if err := validateBox(&box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Save(&box).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &box, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteBox is the resolver for the deleteBox field.
|
||||||
|
func (r *mutationResolver) DeleteBox(ctx context.Context, id int) (*models.Box, error) {
|
||||||
|
var box models.Box
|
||||||
|
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Delete(&box).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &box, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Boxes is the resolver for the boxes field.
|
||||||
|
func (r *queryResolver) Boxes(ctx context.Context, page string) ([]*models.Box, error) {
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
if hidden {
|
||||||
|
return []*models.Box{}, nil
|
||||||
|
}
|
||||||
|
query := r.Store.DB.Where("page = ?", page)
|
||||||
|
if !IsAdminFromCtx(ctx) {
|
||||||
|
query = query.Where("admin_only = ?", false)
|
||||||
|
}
|
||||||
|
var boxes []models.Box
|
||||||
|
if err := query.Order("z ASC, id ASC").Find(&boxes).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := fillLinked(r.Store.DB, boxes); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(boxes), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// Helpers live outside *.resolvers.go because gqlgen moves unknown code there.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// minBoxSize stops a box being resized to nothing, after which it could not
|
||||||
|
// be grabbed again on the canvas.
|
||||||
|
const minBoxSize = 40
|
||||||
|
|
||||||
|
// maxShadowLen bounds a box's shadow, which is a single CSS value: even a
|
||||||
|
// stack of a few comma-separated shadows is well under it.
|
||||||
|
const maxShadowLen = 200
|
||||||
|
|
||||||
|
func setInt(dst *int, src *int) {
|
||||||
|
if src != nil {
|
||||||
|
*dst = *src
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateBox 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")
|
||||||
|
}
|
||||||
|
switch box.Kind {
|
||||||
|
case "widget":
|
||||||
|
if box.Widget == nil || *box.Widget == "" {
|
||||||
|
return errors.New("a widget box needs a widget name")
|
||||||
|
}
|
||||||
|
case "html":
|
||||||
|
// A linked box's html lives on its component (fillLinked).
|
||||||
|
if box.HTML == nil && box.ComponentID == nil {
|
||||||
|
return errors.New("an html box needs html")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return errors.New(`box kind must be "widget" or "html"`)
|
||||||
|
}
|
||||||
|
if box.ComponentID != nil && box.Kind != "html" {
|
||||||
|
return errors.New("only an html box can be linked to a component")
|
||||||
|
}
|
||||||
|
if err := validateShadow(&box.Shadow); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
box.Y = max(box.Y, 0)
|
||||||
|
box.W = max(box.W, minBoxSize)
|
||||||
|
box.H = max(box.H, minBoxSize)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 {
|
||||||
|
return fmt.Errorf("a shadow is at most %d characters", maxShadowLen)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestValidateBox(t *testing.T) {
|
||||||
|
str := func(s string) *string { return &s }
|
||||||
|
one := uint(1)
|
||||||
|
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
box models.Box
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"widget with a name", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat")}, false},
|
||||||
|
{"widget without a name", models.Box{Page: "stp", Kind: "widget"}, true},
|
||||||
|
{"widget with an empty name", models.Box{Page: "stp", Kind: "widget", Widget: str("")}, true},
|
||||||
|
{"html with html", models.Box{Page: "stp", Kind: "html", HTML: str("<p>hi</p>")}, false},
|
||||||
|
{"html with empty html", models.Box{Page: "stp", Kind: "html", HTML: str("")}, false},
|
||||||
|
{"html without html", models.Box{Page: "stp", Kind: "html"}, true},
|
||||||
|
{"linked html without html", models.Box{Page: "stp", Kind: "html", ComponentID: &one}, false},
|
||||||
|
{"linked widget", models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), ComponentID: &one}, true},
|
||||||
|
{"no page", models.Box{Kind: "widget", Widget: str("Chat")}, true},
|
||||||
|
{"bad page", models.Box{Page: "Shrines/GTO", Kind: "widget", Widget: str("Chat")}, true},
|
||||||
|
{"unknown kind", models.Box{Page: "stp", Kind: "iframe", HTML: str("x")}, true},
|
||||||
|
} {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
err := validateBox(&c.box)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Geometry is clamped, not rejected: x may go negative, into the margin
|
||||||
|
// left of a centred canvas, but nothing goes above the top or below a
|
||||||
|
// grabbable size.
|
||||||
|
box := models.Box{Page: "stp", Kind: "widget", Widget: str("Chat"), X: -30, Y: -1, W: 5, H: 0}
|
||||||
|
if err := validateBox(&box); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if box.X != -30 || box.Y != 0 || box.W != minBoxSize || box.H != minBoxSize {
|
||||||
|
t.Fatalf("clamped to %d,%d %dx%d; want -30,0 %dx%d", box.X, box.Y, box.W, box.H, minBoxSize, minBoxSize)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Uses is the resolver for the uses field.
|
||||||
|
func (r *componentResolver) Uses(ctx context.Context, obj *models.Component) (int, error) {
|
||||||
|
var count int64
|
||||||
|
if err := r.Store.DB.Model(&models.Box{}).Where("component_id = ?", obj.ID).Count(&count).Error; err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return int(count), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateComponent is the resolver for the createComponent field.
|
||||||
|
func (r *mutationResolver) CreateComponent(ctx context.Context, input model.CreateComponentInput) (*models.Component, error) {
|
||||||
|
name, err := usableComponentName(r.Store.DB, input.Name, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c := models.Component{Name: name, Title: input.Title, HTML: input.HTML, W: 300, H: 200, Framed: true}
|
||||||
|
setInt(&c.W, input.W)
|
||||||
|
setInt(&c.H, input.H)
|
||||||
|
if input.Framed != nil {
|
||||||
|
c.Framed = *input.Framed
|
||||||
|
}
|
||||||
|
if input.Shadow != nil {
|
||||||
|
c.Shadow = *input.Shadow
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
c.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
c.W = max(c.W, minBoxSize)
|
||||||
|
c.H = max(c.H, minBoxSize)
|
||||||
|
if err := validateShadow(&c.Shadow); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Create(&c).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateComponent is the resolver for the updateComponent field.
|
||||||
|
func (r *mutationResolver) UpdateComponent(ctx context.Context, id int, input model.UpdateComponentInput) (*models.Component, error) {
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
if input.Name != nil {
|
||||||
|
name, err := usableComponentName(r.Store.DB, *input.Name, c.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.Name = name
|
||||||
|
}
|
||||||
|
if input.Title != nil {
|
||||||
|
c.Title = input.Title
|
||||||
|
}
|
||||||
|
if input.HTML != nil {
|
||||||
|
c.HTML = *input.HTML
|
||||||
|
}
|
||||||
|
setInt(&c.W, input.W)
|
||||||
|
setInt(&c.H, input.H)
|
||||||
|
if input.Framed != nil {
|
||||||
|
c.Framed = *input.Framed
|
||||||
|
}
|
||||||
|
if input.Shadow != nil {
|
||||||
|
c.Shadow = *input.Shadow
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
c.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
c.W = max(c.W, minBoxSize)
|
||||||
|
c.H = max(c.H, minBoxSize)
|
||||||
|
if err := validateShadow(&c.Shadow); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Save(&c).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteComponent is the resolver for the deleteComponent field.
|
||||||
|
func (r *mutationResolver) DeleteComponent(ctx context.Context, id int) (*models.Component, error) {
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := detachFrom(tx, &c); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Delete(&c).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SaveBoxAsComponent is the resolver for the saveBoxAsComponent field.
|
||||||
|
func (r *mutationResolver) SaveBoxAsComponent(ctx context.Context, id int, name string) (*models.Box, error) {
|
||||||
|
// The box becomes the 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
|
||||||
|
}
|
||||||
|
if box.Kind != "html" || box.HTML == nil {
|
||||||
|
return nil, errors.New("only an html box can be saved as a component")
|
||||||
|
}
|
||||||
|
if box.ComponentID != nil {
|
||||||
|
return nil, errors.New("that box is already linked to a component")
|
||||||
|
}
|
||||||
|
name, err := usableComponentName(r.Store.DB, name, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c := models.Component{
|
||||||
|
Name: name, Title: box.Title, HTML: *box.HTML,
|
||||||
|
W: box.W, H: box.H, Framed: box.Framed, Shadow: box.Shadow, AdminOnly: box.AdminOnly,
|
||||||
|
}
|
||||||
|
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Create(&c).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
box.ComponentID = &c.ID
|
||||||
|
box.HTML = nil
|
||||||
|
return tx.Save(&box).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &box, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetachBox is the resolver for the detachBox field.
|
||||||
|
func (r *mutationResolver) DetachBox(ctx context.Context, id int) (*models.Box, error) {
|
||||||
|
var box models.Box
|
||||||
|
if err := r.Store.DB.First(&box, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if box.ComponentID == nil {
|
||||||
|
return nil, errors.New("that box isn't linked to a component")
|
||||||
|
}
|
||||||
|
if err := fillLinkedOne(r.Store.DB, &box); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
box.ComponentID = nil
|
||||||
|
if err := r.Store.DB.Save(&box).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &box, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Components is the resolver for the components field.
|
||||||
|
func (r *queryResolver) Components(ctx context.Context) ([]*models.Component, error) {
|
||||||
|
var components []models.Component
|
||||||
|
if err := r.Store.DB.Order("name ASC").Find(&components).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(components), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Component returns ComponentResolver implementation.
|
||||||
|
func (r *Resolver) Component() ComponentResolver { return &componentResolver{r} }
|
||||||
|
|
||||||
|
type componentResolver struct{ *Resolver }
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// Hand-written helpers for component.resolvers.go, kept out of the resolver
|
||||||
|
// file for the same reason as box_helpers.go.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxComponentNameLen = 100
|
||||||
|
|
||||||
|
// cleanComponentName trims name and reports why it can't be a component's
|
||||||
|
// name.
|
||||||
|
func cleanComponentName(name string) (string, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
return name, errors.New("a component needs a name")
|
||||||
|
}
|
||||||
|
if len(name) > maxComponentNameLen {
|
||||||
|
return name, fmt.Errorf("a component name is at most %d characters", maxComponentNameLen)
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func componentNameTaken(db *gorm.DB, name string, exceptID uint) (bool, error) {
|
||||||
|
var count int64
|
||||||
|
err := db.Model(&models.Component{}).Where("name = ? AND id <> ?", name, exceptID).Count(&count).Error
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// usableComponentName checks name and answers with a sentence if it can't be
|
||||||
|
// used, so the resolvers that name a component share one set of messages.
|
||||||
|
func usableComponentName(db *gorm.DB, name string, exceptID uint) (string, error) {
|
||||||
|
name, err := cleanComponentName(name)
|
||||||
|
if err != nil {
|
||||||
|
return name, err
|
||||||
|
}
|
||||||
|
taken, err := componentNameTaken(db, name, exceptID)
|
||||||
|
if err != nil {
|
||||||
|
return name, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return name, errors.New("there is already a component with that name")
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fillLinked sets 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 {
|
||||||
|
if b.ComponentID != nil {
|
||||||
|
ids = append(ids, *b.ComponentID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
var components []models.Component
|
||||||
|
if err := db.Where("id IN ?", ids).Find(&components).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
html := make(map[uint]string, len(components))
|
||||||
|
for _, c := range components {
|
||||||
|
html[c.ID] = c.HTML
|
||||||
|
}
|
||||||
|
for i := range boxes {
|
||||||
|
if id := boxes[i].ComponentID; id != nil {
|
||||||
|
h := html[*id]
|
||||||
|
boxes[i].HTML = &h
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fillLinkedOne is fillLinked for a single box.
|
||||||
|
func fillLinkedOne(db *gorm.DB, box *models.Box) error {
|
||||||
|
boxes := []models.Box{*box}
|
||||||
|
if err := fillLinked(db, boxes); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
*box = boxes[0]
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// componentExists reports whether id is a live component, for linking a box
|
||||||
|
// to it.
|
||||||
|
func componentExists(db *gorm.DB, id uint) (bool, error) {
|
||||||
|
var count int64
|
||||||
|
err := db.Model(&models.Component{}).Where("id = ?", id).Count(&count).Error
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// detachFrom gives every box linked to component c its own copy of c's HTML
|
||||||
|
// and unlinks it, inside tx.
|
||||||
|
func detachFrom(tx *gorm.DB, c *models.Component) error {
|
||||||
|
return tx.Model(&models.Box{}).Where("component_id = ?", c.ID).
|
||||||
|
Updates(map[string]any{"html": c.HTML, "component_id": nil}).Error
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCleanComponentName(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
name, in, want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"plain", "Clock", "Clock", false},
|
||||||
|
{"trimmed", " Clock \n", "Clock", false},
|
||||||
|
{"empty", "", "", true},
|
||||||
|
{"only spaces", " ", "", true},
|
||||||
|
{"at the limit", strings.Repeat("a", maxComponentNameLen), strings.Repeat("a", maxComponentNameLen), false},
|
||||||
|
{"too long", strings.Repeat("a", maxComponentNameLen+1), "", true},
|
||||||
|
} {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got, err := cleanComponentName(c.in)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||||
|
}
|
||||||
|
if !c.wantErr && got != c.want {
|
||||||
|
t.Fatalf("got %q, want %q", got, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,17 +7,10 @@ import (
|
|||||||
"github.com/golang-jwt/jwt/v5"
|
"github.com/golang-jwt/jwt/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
// This file is the bridge between Gin's request handling and gqlgen's
|
// Resolvers get only a context.Context; AuthContextMiddleware puts the
|
||||||
// resolvers. gqlgen resolvers receive only a context.Context, so
|
// verified claims and the *gin.Context into it.
|
||||||
// AuthContextMiddleware (middleware.go) smuggles the verified JWT claims and
|
|
||||||
// the *gin.Context itself into that context, and these accessors read them
|
|
||||||
// back out.
|
|
||||||
|
|
||||||
// contextKey is a private named type so that these keys can never collide
|
// Unrelated to the "userClaims" key handlers.AuthMiddleware sets on Gin's context.
|
||||||
// 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.
|
|
||||||
type contextKey string
|
type contextKey string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -25,9 +18,8 @@ const (
|
|||||||
ginContextKey contextKey = "ginContext"
|
ginContextKey contextKey = "ginContext"
|
||||||
)
|
)
|
||||||
|
|
||||||
// UserClaimsFromCtx returns the verified JWT claims, or nil when the request
|
// UserClaimsFromCtx returns nil for anonymous requests; refusing is the
|
||||||
// is anonymous. nil means "not authenticated": a missing or invalid token is
|
// directives' job.
|
||||||
// not an error here, because many queries are public.
|
|
||||||
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
||||||
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
claims, ok := ctx.Value(userClaimsKey).(*jwt.MapClaims)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -36,8 +28,6 @@ func UserClaimsFromCtx(ctx context.Context) *jwt.MapClaims {
|
|||||||
return claims
|
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.
|
|
||||||
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
||||||
claims := UserClaimsFromCtx(ctx)
|
claims := UserClaimsFromCtx(ctx)
|
||||||
if claims == nil {
|
if claims == nil {
|
||||||
@@ -50,11 +40,7 @@ func UserIDFromCtx(ctx context.Context) (uint, bool) {
|
|||||||
return uint(idF), true
|
return uint(idF), true
|
||||||
}
|
}
|
||||||
|
|
||||||
// IsAdminFromCtx reports whether the request carries an admin token. This is
|
// IsAdminFromCtx reads the token, so a revoked flag applies on expiry.
|
||||||
// the authorisation check for nearly every mutation — there is no middleware
|
|
||||||
// in front of the GraphQL endpoint, so a resolver that forgets to call this
|
|
||||||
// is public. Admin comes from the token, not the database, so a revoked admin
|
|
||||||
// flag only bites once the access token expires.
|
|
||||||
func IsAdminFromCtx(ctx context.Context) bool {
|
func IsAdminFromCtx(ctx context.Context) bool {
|
||||||
claims := UserClaimsFromCtx(ctx)
|
claims := UserClaimsFromCtx(ctx)
|
||||||
if claims == nil {
|
if claims == nil {
|
||||||
@@ -64,10 +50,7 @@ func IsAdminFromCtx(ctx context.Context) bool {
|
|||||||
return ok && admin
|
return ok && admin
|
||||||
}
|
}
|
||||||
|
|
||||||
// GinContextFromCtx returns the underlying *gin.Context, which resolvers need
|
// GinContextFromCtx is nil if the middleware wasn't installed.
|
||||||
// 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.
|
|
||||||
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
func GinContextFromCtx(ctx context.Context) *gin.Context {
|
||||||
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
gc, ok := ctx.Value(ginContextKey).(*gin.Context)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -0,0 +1,153 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreateCoverLetter is the resolver for the createCoverLetter field.
|
||||||
|
func (r *mutationResolver) CreateCoverLetter(ctx context.Context, input model.CreateCoverLetterInput) (*models.CoverLetter, error) {
|
||||||
|
name, err := cleanCoverLetterName(input.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := checkCoverLetterBody(input.Body); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
taken, err := coverLetterNameTaken(r.Store.DB, name, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a cover letter with that name")
|
||||||
|
}
|
||||||
|
letter := models.CoverLetter{Name: name, Body: input.Body}
|
||||||
|
if err := r.Store.DB.Create(&letter).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &letter, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCoverLetter is the resolver for the updateCoverLetter field.
|
||||||
|
func (r *mutationResolver) UpdateCoverLetter(ctx context.Context, id int, input model.UpdateCoverLetterInput) (*models.CoverLetter, error) {
|
||||||
|
var letter models.CoverLetter
|
||||||
|
if err := r.Store.DB.First(&letter, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if input.Name != nil {
|
||||||
|
name, err := cleanCoverLetterName(*input.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
taken, err := coverLetterNameTaken(r.Store.DB, name, letter.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a cover letter with that name")
|
||||||
|
}
|
||||||
|
letter.Name = name
|
||||||
|
}
|
||||||
|
if input.Body != nil {
|
||||||
|
if err := checkCoverLetterBody(*input.Body); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
letter.Body = *input.Body
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Save(&letter).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &letter, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCoverLetter is the resolver for the deleteCoverLetter field.
|
||||||
|
func (r *mutationResolver) DeleteCoverLetter(ctx context.Context, id int) (*models.CoverLetter, error) {
|
||||||
|
var letter models.CoverLetter
|
||||||
|
if err := r.Store.DB.First(&letter, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Delete(&letter).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &letter, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateCoverSnippet is the resolver for the createCoverSnippet field.
|
||||||
|
func (r *mutationResolver) CreateCoverSnippet(ctx context.Context, input model.CreateCoverSnippetInput) (*models.CoverSnippet, error) {
|
||||||
|
text, err := cleanSnippetText(input.Text)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
snippet := models.CoverSnippet{Text: text}
|
||||||
|
if input.Section != nil {
|
||||||
|
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Create(&snippet).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &snippet, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateCoverSnippet is the resolver for the updateCoverSnippet field.
|
||||||
|
func (r *mutationResolver) UpdateCoverSnippet(ctx context.Context, id int, input model.UpdateCoverSnippetInput) (*models.CoverSnippet, error) {
|
||||||
|
// Letters it was dropped into keep their own copy of the old text.
|
||||||
|
var snippet models.CoverSnippet
|
||||||
|
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
if input.Text != nil {
|
||||||
|
if snippet.Text, err = cleanSnippetText(*input.Text); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if input.Section != nil {
|
||||||
|
if snippet.Section, err = cleanSnippetSection(*input.Section); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Save(&snippet).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &snippet, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteCoverSnippet is the resolver for the deleteCoverSnippet field.
|
||||||
|
func (r *mutationResolver) DeleteCoverSnippet(ctx context.Context, id int) (*models.CoverSnippet, error) {
|
||||||
|
var snippet models.CoverSnippet
|
||||||
|
if err := r.Store.DB.First(&snippet, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Delete(&snippet).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &snippet, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CoverLetters is the resolver for the coverLetters field.
|
||||||
|
func (r *queryResolver) CoverLetters(ctx context.Context) ([]*models.CoverLetter, error) {
|
||||||
|
var letters []models.CoverLetter
|
||||||
|
if err := r.Store.DB.Order("updated_at DESC").Find(&letters).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(letters), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CoverSnippets is the resolver for the coverSnippets field.
|
||||||
|
func (r *queryResolver) CoverSnippets(ctx context.Context) ([]*models.CoverSnippet, error) {
|
||||||
|
var snippets []models.CoverSnippet
|
||||||
|
if err := r.Store.DB.Order("section ASC, created_at DESC").Find(&snippets).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(snippets), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// Hand-written helpers for cover_letter.resolvers.go, kept out of the
|
||||||
|
// resolver file for the same reason as box_helpers.go.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxCoverLetterNameLen = 100
|
||||||
|
// A letter is a page of text; 100 KB is far beyond any real one and
|
||||||
|
// still small enough that a runaway client can't fill the table.
|
||||||
|
maxCoverLetterBodyLen = 100 * 1024
|
||||||
|
maxSnippetTextLen = 5000
|
||||||
|
maxSnippetSectionLen = 100
|
||||||
|
)
|
||||||
|
|
||||||
|
// cleanCoverLetterName trims name and reports why it can't be a letter's
|
||||||
|
// name.
|
||||||
|
func cleanCoverLetterName(name string) (string, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
return name, errors.New("a cover letter needs a name")
|
||||||
|
}
|
||||||
|
if len(name) > maxCoverLetterNameLen {
|
||||||
|
return name, fmt.Errorf("a cover letter name is at most %d characters", maxCoverLetterNameLen)
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
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: 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)
|
||||||
|
}
|
||||||
|
var obj map[string]json.RawMessage
|
||||||
|
// null unmarshals into a nil map without error, so it is caught here too.
|
||||||
|
if err := json.Unmarshal([]byte(body), &obj); err != nil || obj == nil {
|
||||||
|
return errors.New("a cover letter body must be a JSON object")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanSnippetText counts characters, not bytes.
|
||||||
|
func cleanSnippetText(text string) (string, error) {
|
||||||
|
text = strings.TrimSpace(text)
|
||||||
|
if text == "" {
|
||||||
|
return text, errors.New("a paragraph can't be empty")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(text) > maxSnippetTextLen {
|
||||||
|
return text, fmt.Errorf("a paragraph is at most %d characters", maxSnippetTextLen)
|
||||||
|
}
|
||||||
|
return text, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanSnippetSection trims a snippet's section title.
|
||||||
|
func cleanSnippetSection(section string) (string, error) {
|
||||||
|
section = strings.TrimSpace(section)
|
||||||
|
if utf8.RuneCountInString(section) > maxSnippetSectionLen {
|
||||||
|
return section, fmt.Errorf("a section title is at most %d characters", maxSnippetSectionLen)
|
||||||
|
}
|
||||||
|
return section, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCleanCoverLetterName(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
name, in, want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"plain", "Acme", "Acme", false},
|
||||||
|
{"trimmed", " Acme \n", "Acme", false},
|
||||||
|
{"empty", "", "", true},
|
||||||
|
{"only spaces", " ", "", true},
|
||||||
|
{"at the limit", strings.Repeat("a", maxCoverLetterNameLen), strings.Repeat("a", maxCoverLetterNameLen), false},
|
||||||
|
{"too long", strings.Repeat("a", maxCoverLetterNameLen+1), "", true},
|
||||||
|
} {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got, err := cleanCoverLetterName(c.in)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||||
|
}
|
||||||
|
if !c.wantErr && got != c.want {
|
||||||
|
t.Fatalf("got %q, want %q", got, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckCoverLetterBody(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
name, in string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"object", `{"v":1,"sections":[]}`, false},
|
||||||
|
{"empty object", `{}`, false},
|
||||||
|
{"array", `[]`, true},
|
||||||
|
{"string", `"hi"`, true},
|
||||||
|
{"null", `null`, true},
|
||||||
|
{"not json", `{`, true},
|
||||||
|
{"empty", ``, true},
|
||||||
|
{"too big", `{"x":"` + strings.Repeat("a", maxCoverLetterBodyLen) + `"}`, true},
|
||||||
|
} {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
if err := checkCoverLetterBody(c.in); (err != nil) != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCleanSnippetText(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
name, in, want string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{"plain", "I like Go.", "I like Go.", false},
|
||||||
|
{"trimmed", "\n I like Go. ", "I like Go.", false},
|
||||||
|
{"empty", " ", "", true},
|
||||||
|
// Characters, not bytes: 5000 two-byte runes still fit.
|
||||||
|
{"multibyte at the limit", strings.Repeat("é", maxSnippetTextLen), strings.Repeat("é", maxSnippetTextLen), false},
|
||||||
|
{"too long", strings.Repeat("a", maxSnippetTextLen+1), "", true},
|
||||||
|
} {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got, err := cleanSnippetText(c.in)
|
||||||
|
if (err != nil) != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, wantErr %v", err, c.wantErr)
|
||||||
|
}
|
||||||
|
if !c.wantErr && got != c.want {
|
||||||
|
t.Fatalf("got %q, want %q", got, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/99designs/gqlgen/graphql"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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 shared by main and the tests. A nil directive fails closed.
|
||||||
|
func Directives() DirectiveRoot {
|
||||||
|
return DirectiveRoot{
|
||||||
|
Admin: requireAdmin,
|
||||||
|
SignedIn: requireSignedIn,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireAdmin(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||||
|
if !IsAdminFromCtx(ctx) {
|
||||||
|
return nil, fmt.Errorf(errAdminRequired)
|
||||||
|
}
|
||||||
|
return next(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requireSignedIn(ctx context.Context, _ any, next graphql.Resolver) (any, error) {
|
||||||
|
if _, ok := UserIDFromCtx(ctx); !ok {
|
||||||
|
return nil, fmt.Errorf(errSignedInRequired)
|
||||||
|
}
|
||||||
|
return next(ctx)
|
||||||
|
}
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"slices"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/99designs/gqlgen/graphql"
|
||||||
|
"github.com/99designs/gqlgen/graphql/handler"
|
||||||
|
"github.com/99designs/gqlgen/graphql/handler/transport"
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
"github.com/vektah/gqlparser/v2/ast"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/handlers"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
func withClaims(id float64, admin bool) context.Context {
|
||||||
|
claims := jwt.MapClaims{"id": id, "admin": admin}
|
||||||
|
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDirectives(t *testing.T) {
|
||||||
|
anonymous := context.Background()
|
||||||
|
user := withClaims(2, false)
|
||||||
|
admin := withClaims(1, true)
|
||||||
|
// A token that verified but carries no id: not something GenerateJWT
|
||||||
|
// mints, but it must not count as signed in.
|
||||||
|
noID := func() context.Context {
|
||||||
|
claims := jwt.MapClaims{"admin": false}
|
||||||
|
return context.WithValue(context.Background(), userClaimsKey, &claims)
|
||||||
|
}()
|
||||||
|
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
directive func(context.Context, any, graphql.Resolver) (any, error)
|
||||||
|
ctx context.Context
|
||||||
|
wantErr string // "" means the resolver must run
|
||||||
|
}{
|
||||||
|
{"@admin refuses an anonymous request", requireAdmin, anonymous, "admin access required"},
|
||||||
|
{"@admin refuses a signed-in non-admin", requireAdmin, user, "admin access required"},
|
||||||
|
{"@admin admits an admin", requireAdmin, admin, ""},
|
||||||
|
{"@signedIn refuses an anonymous request", requireSignedIn, anonymous, "authentication required"},
|
||||||
|
{"@signedIn refuses a token with no id", requireSignedIn, noID, "authentication required"},
|
||||||
|
{"@signedIn admits a non-admin", requireSignedIn, user, ""},
|
||||||
|
{"@signedIn admits an admin", requireSignedIn, admin, ""},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
called := false
|
||||||
|
next := func(ctx context.Context) (any, error) {
|
||||||
|
called = true
|
||||||
|
return "resolved", nil
|
||||||
|
}
|
||||||
|
res, err := c.directive(c.ctx, nil, next)
|
||||||
|
|
||||||
|
if c.wantErr == "" {
|
||||||
|
if err != nil || !called || res != "resolved" {
|
||||||
|
t.Fatalf("res = %v, err = %v, resolver called = %v; want the resolver's result", res, err, called)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// The exact strings are what the front end displays.
|
||||||
|
if err == nil || err.Error() != c.wantErr {
|
||||||
|
t.Fatalf("err = %v, want %q", err, c.wantErr)
|
||||||
|
}
|
||||||
|
if called {
|
||||||
|
t.Fatal("the resolver ran for a refused request")
|
||||||
|
}
|
||||||
|
if res != nil {
|
||||||
|
t.Fatalf("res = %v, want nil alongside the error", res)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Directives() must supply every directive the schema declares; a nil one
|
||||||
|
// makes gqlgen fail each field that uses it.
|
||||||
|
func TestDirectivesAreAllImplemented(t *testing.T) {
|
||||||
|
d := Directives()
|
||||||
|
if d.Admin == nil || d.SignedIn == nil {
|
||||||
|
t.Fatal("Directives() left a directive unimplemented")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// guardOf 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
|
||||||
|
signedIn := field.Directives.ForName("signedIn") != nil
|
||||||
|
switch {
|
||||||
|
case admin && signedIn:
|
||||||
|
t.Errorf("%s carries both @admin and @signedIn", field.Name)
|
||||||
|
return "admin"
|
||||||
|
case admin:
|
||||||
|
return "admin"
|
||||||
|
case signedIn:
|
||||||
|
return "signedIn"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func schemaUnderTest() *ast.Schema {
|
||||||
|
return NewExecutableSchema(Config{}).Schema()
|
||||||
|
}
|
||||||
|
|
||||||
|
// publicMutations is the allow-list; any other unguarded mutation fails
|
||||||
|
// TestEveryMutationIsGuarded.
|
||||||
|
var publicMutations = []string{"login", "logout", "refreshToken"}
|
||||||
|
|
||||||
|
func TestEveryMutationIsGuarded(t *testing.T) {
|
||||||
|
schema := schemaUnderTest()
|
||||||
|
var seen []string
|
||||||
|
for _, field := range schema.Mutation.Fields {
|
||||||
|
if strings.HasPrefix(field.Name, "__") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen = append(seen, field.Name)
|
||||||
|
guard := guardOf(t, field)
|
||||||
|
public := slices.Contains(publicMutations, field.Name)
|
||||||
|
switch {
|
||||||
|
case guard == "" && !public:
|
||||||
|
t.Errorf("mutation %s has neither @admin nor @signedIn, so anyone can call it; "+
|
||||||
|
"add a directive in the schema, or add it to publicMutations if that is intended", field.Name)
|
||||||
|
case guard != "" && public:
|
||||||
|
t.Errorf("mutation %s is listed as public but carries @%s", field.Name, guard)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A renamed or removed mutation must not leave a stale exemption behind.
|
||||||
|
for _, name := range publicMutations {
|
||||||
|
if !slices.Contains(seen, name) {
|
||||||
|
t.Errorf("publicMutations lists %s, which is not in the schema", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pinned so loosening @admin to @signedIn needs a change here.
|
||||||
|
func TestSignedInMutationsArePinned(t *testing.T) {
|
||||||
|
want := []string{"createPlace", "deletePlace", "updatePlace"}
|
||||||
|
var got []string
|
||||||
|
for _, field := range schemaUnderTest().Mutation.Fields {
|
||||||
|
if guardOf(t, field) == "signedIn" {
|
||||||
|
got = append(got, field.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Strings(got)
|
||||||
|
if !slices.Equal(got, want) {
|
||||||
|
t.Fatalf("@signedIn mutations = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Queries are public by default, 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",
|
||||||
|
"user": "admin",
|
||||||
|
"places": "signedIn",
|
||||||
|
"layouts": "admin",
|
||||||
|
"components": "admin",
|
||||||
|
"coverLetters": "admin",
|
||||||
|
"coverSnippets": "admin",
|
||||||
|
"permissionTypes": "signedIn",
|
||||||
|
}
|
||||||
|
got := map[string]string{}
|
||||||
|
for _, field := range schemaUnderTest().Query.Fields {
|
||||||
|
if strings.HasPrefix(field.Name, "__") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if guard := guardOf(t, field); guard != "" {
|
||||||
|
got[field.Name] = guard
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, guard := range want {
|
||||||
|
if got[name] != guard {
|
||||||
|
t.Errorf("query %s: guard = %q, want @%s", name, got[name], guard)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for name, guard := range got {
|
||||||
|
if _, ok := want[name]; !ok {
|
||||||
|
t.Errorf("query %s carries @%s but is not in the pinned list; add it there if the guard is intended", name, guard)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep directives on root fields: the tests above only look there.
|
||||||
|
func TestDirectivesOnlyOnRootFields(t *testing.T) {
|
||||||
|
schema := schemaUnderTest()
|
||||||
|
for name, def := range schema.Types {
|
||||||
|
if def == schema.Query || def == schema.Mutation || strings.HasPrefix(name, "__") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, field := range def.Fields {
|
||||||
|
if guardOf(t, field) != "" {
|
||||||
|
t.Errorf("%s.%s carries an authorisation directive outside Query/Mutation", name, field.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// execute runs 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{
|
||||||
|
Resolvers: &Resolver{Store: &handlers.Store{}},
|
||||||
|
Directives: Directives(),
|
||||||
|
}))
|
||||||
|
srv.AddTransport(transport.POST{})
|
||||||
|
|
||||||
|
body, err := json.Marshal(map[string]any{"query": query, "variables": variables})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req := httptest.NewRequest(http.MethodPost, "/graphql", bytes.NewReader(body)).WithContext(ctx)
|
||||||
|
req.Header.Set("Content-Type", "application/json")
|
||||||
|
rec := httptest.NewRecorder()
|
||||||
|
srv.ServeHTTP(rec, req)
|
||||||
|
|
||||||
|
var resp struct {
|
||||||
|
Errors []struct {
|
||||||
|
Message string `json:"message"`
|
||||||
|
} `json:"errors"`
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||||
|
t.Fatalf("decoding response %s: %v", rec.Body, err)
|
||||||
|
}
|
||||||
|
var messages []string
|
||||||
|
for _, e := range resp.Errors {
|
||||||
|
messages = append(messages, e.Message)
|
||||||
|
}
|
||||||
|
return messages
|
||||||
|
}
|
||||||
|
|
||||||
|
// End to end: the message a client receives for a refused field is the bare
|
||||||
|
// string the resolvers used to return, with nothing wrapped around it.
|
||||||
|
func TestGuardedFieldsRefuseOverTheWire(t *testing.T) {
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
ctx context.Context
|
||||||
|
query string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{"anonymous admin query", context.Background(), `{ users { id } }`, "admin access required"},
|
||||||
|
{"non-admin admin query", withClaims(2, false), `{ users { id } }`, "admin access required"},
|
||||||
|
{"anonymous admin mutation", context.Background(), `mutation { deleteBookmark(id: 1) { id } }`, "admin access required"},
|
||||||
|
{"non-admin admin mutation", withClaims(2, false), `mutation { deleteUser(id: 1) { id } }`, "admin access required"},
|
||||||
|
{"anonymous signed-in query", context.Background(), `{ places { id } }`, "authentication required"},
|
||||||
|
{"anonymous signed-in mutation", context.Background(), `mutation { deletePlace(id: 1) { id } }`, "authentication required"},
|
||||||
|
// Not a directive, and a different message on purpose.
|
||||||
|
{"me keeps its own message", context.Background(), `{ me { id } }`, "unauthorized"},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
t.Run(c.name, func(t *testing.T) {
|
||||||
|
got := execute(t, c.ctx, c.query, nil)
|
||||||
|
if !slices.Equal(got, []string{c.want}) {
|
||||||
|
t.Fatalf("errors = %q, want exactly %q", got, c.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// IDs 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
|
||||||
|
graphql.MarshalUintID(id).MarshalGQL(&asUint)
|
||||||
|
graphql.MarshalIntID(int(id)).MarshalGQL(&asInt)
|
||||||
|
if asUint.String() != asInt.String() {
|
||||||
|
t.Errorf("id %d: UintID writes %s, IntID wrote %s", id, &asUint, &asInt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := func() string {
|
||||||
|
var b bytes.Buffer
|
||||||
|
graphql.MarshalUintID(12).MarshalGQL(&b)
|
||||||
|
return b.String()
|
||||||
|
}(); got != `"12"` {
|
||||||
|
t.Errorf("MarshalUintID(12) = %s, want \"12\"", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
+11
-28
@@ -1,32 +1,15 @@
|
|||||||
// Package graph is the GraphQL layer: the single POST /graphql endpoint that
|
// Package graph is the GraphQL layer behind POST /graphql.
|
||||||
// serves most of the site's data.
|
|
||||||
//
|
//
|
||||||
// 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
|
// Nothing guards the endpoint itself. A field is protected only by an
|
||||||
// `go run github.com/99designs/gqlgen generate` regenerates generated.go
|
// @admin or @signedIn directive (directives.go); a field with neither is
|
||||||
// and model/models_gen.go, and adds stubs for any new field to the
|
// public. directives_test.go fails if a mutation has neither and isn't on its
|
||||||
// matching *.resolvers.go. Never edit those two generated files.
|
// public allow-list. Finer rules (post ownership, hiding private messages)
|
||||||
// - gqlgen.yml maps most GraphQL object types straight onto the GORM
|
// live in resolvers via IsAdminFromCtx / UserIDFromCtx.
|
||||||
// structs in backend/models, so model/ holds only input and payload
|
|
||||||
// types. That is also why almost every type has a hand-written ID
|
|
||||||
// resolver: model IDs are uint, GraphQL's Int is a Go int.
|
|
||||||
// - 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.
|
|
||||||
//
|
//
|
||||||
// Authorisation, which is the thing most likely to catch out a newcomer:
|
// gqlgen may move hand-written code in *.resolvers.go; _helpers.go files are
|
||||||
// there is NO middleware guarding this endpoint. AuthContextMiddleware only
|
// untouched.
|
||||||
// annotates the context and lets everything through, so each resolver checks
|
|
||||||
// for itself with IsAdminFromCtx or UserIDFromCtx. A resolver that omits that
|
|
||||||
// check is fully public. The rule of thumb in this schema is that queries are
|
|
||||||
// public and mutations are admin-only, with these exceptions: the job
|
|
||||||
// application and job reference queries are admin-only (they are private
|
|
||||||
// data), the places mutations need only a signed-in user, and the messages
|
|
||||||
// query hides private messages from non-admins rather than refusing.
|
|
||||||
//
|
|
||||||
// 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.
|
|
||||||
package graph
|
package graph
|
||||||
|
|||||||
@@ -3,27 +3,17 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *favoriteResolver) ID(ctx context.Context, obj *models.Favorite) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateFavorite is the resolver for the createFavorite field.
|
// CreateFavorite is the resolver for the createFavorite field.
|
||||||
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
func (r *mutationResolver) CreateFavorite(ctx context.Context, input model.CreateFavoriteInput) (*models.Favorite, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
favorite := models.Favorite{Type: input.Type, Name: input.Name, Link: input.Link}
|
||||||
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
if err := r.Store.DB.Create(&favorite).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -40,8 +30,3 @@ func (r *queryResolver) Favorites(ctx context.Context) ([]*models.Favorite, erro
|
|||||||
}
|
}
|
||||||
return ptrs(favorites), nil
|
return ptrs(favorites), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Favorite returns FavoriteResolver implementation.
|
|
||||||
func (r *Resolver) Favorite() FavoriteResolver { return &favoriteResolver{r} }
|
|
||||||
|
|
||||||
type favoriteResolver struct{ *Resolver }
|
|
||||||
|
|||||||
+6775
-2434
File diff suppressed because it is too large
Load Diff
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -24,10 +24,7 @@ func (r *queryResolver) GiteaFeed(ctx context.Context) (*model.GiteaFeedItem, er
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// FetchLatestFeed returns (nil, nil) for an empty feed; mapGiteaFeed
|
// Not cached, so an empty feed is retried next time.
|
||||||
// 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.
|
|
||||||
if feed == nil {
|
if feed == nil {
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,7 @@ import (
|
|||||||
"adam-french.co.uk/backend/services"
|
"adam-french.co.uk/backend/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
// mapGiteaFeed flattens a Gitea feed entry into the GraphQL shape, pulling the
|
// mapGiteaFeed requires a non-nil feed.
|
||||||
// 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.
|
|
||||||
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
func mapGiteaFeed(feed *services.GiteaFeedResponse) *model.GiteaFeedItem {
|
||||||
return &model.GiteaFeedItem{
|
return &model.GiteaFeedItem{
|
||||||
AvatarURL: feed.ActUser.AvatarURL,
|
AvatarURL: feed.ActUser.AvatarURL,
|
||||||
|
|||||||
@@ -1,95 +0,0 @@
|
|||||||
package graph
|
|
||||||
|
|
||||||
// This file will be automatically regenerated based on the schema, any resolver
|
|
||||||
// implementations
|
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
|
||||||
"adam-french.co.uk/backend/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *jobAppReferenceResolver) ID(ctx context.Context, obj *models.JobAppReference) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateJobAppReference is the resolver for the createJobAppReference field.
|
|
||||||
func (r *mutationResolver) CreateJobAppReference(ctx context.Context, input model.CreateJobAppReferenceInput) (*models.JobAppReference, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
ref := models.JobAppReference{
|
|
||||||
Category: input.Category,
|
|
||||||
Label: input.Label,
|
|
||||||
Value: input.Value,
|
|
||||||
}
|
|
||||||
if input.SortOrder != nil {
|
|
||||||
ref.SortOrder = *input.SortOrder
|
|
||||||
}
|
|
||||||
if err := r.Store.DB.Create(&ref).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &ref, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateJobAppReference is the resolver for the updateJobAppReference field.
|
|
||||||
func (r *mutationResolver) UpdateJobAppReference(ctx context.Context, id int, input model.UpdateJobAppReferenceInput) (*models.JobAppReference, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
var ref models.JobAppReference
|
|
||||||
if err := r.Store.DB.First(&ref, id).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if input.Category != nil {
|
|
||||||
ref.Category = *input.Category
|
|
||||||
}
|
|
||||||
if input.Label != nil {
|
|
||||||
ref.Label = *input.Label
|
|
||||||
}
|
|
||||||
if input.Value != nil {
|
|
||||||
ref.Value = *input.Value
|
|
||||||
}
|
|
||||||
if input.SortOrder != nil {
|
|
||||||
ref.SortOrder = *input.SortOrder
|
|
||||||
}
|
|
||||||
if err := r.Store.DB.Save(&ref).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &ref, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteJobAppReference is the resolver for the deleteJobAppReference field.
|
|
||||||
func (r *mutationResolver) DeleteJobAppReference(ctx context.Context, id int) (bool, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return false, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
if err := r.Store.DB.Delete(&models.JobAppReference{}, id).Error; err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobAppReferences is the resolver for the jobAppReferences field.
|
|
||||||
func (r *queryResolver) JobAppReferences(ctx context.Context) ([]*models.JobAppReference, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
var refs []*models.JobAppReference
|
|
||||||
// created_at is the final tie-break so entries sharing a sort_order (the
|
|
||||||
// default 0) keep a stable, insertion-ordered sequence.
|
|
||||||
if err := r.Store.DB.Order("category ASC, sort_order ASC, created_at ASC").Find(&refs).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return refs, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobAppReference returns JobAppReferenceResolver implementation.
|
|
||||||
func (r *Resolver) JobAppReference() JobAppReferenceResolver { return &jobAppReferenceResolver{r} }
|
|
||||||
|
|
||||||
type jobAppReferenceResolver struct{ *Resolver }
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
package graph
|
|
||||||
|
|
||||||
// This file will be automatically regenerated based on the schema, any resolver
|
|
||||||
// implementations
|
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
|
||||||
"adam-french.co.uk/backend/models"
|
|
||||||
"adam-french.co.uk/backend/services"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *jobApplicationResolver) ID(ctx context.Context, obj *models.JobApplication) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// CreateJobApplication is the resolver for the createJobApplication field.
|
|
||||||
func (r *mutationResolver) CreateJobApplication(ctx context.Context, input model.CreateJobApplicationInput) (*models.JobApplication, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
// String! is non-null but not non-empty, and the columns are only
|
|
||||||
// `not null`, so "" stores happily and then never matches the email
|
|
||||||
// pipeline's LOWER(company) lookup — an orphan row no sync can advance.
|
|
||||||
jobTitle := strings.TrimSpace(input.JobTitle)
|
|
||||||
company := strings.TrimSpace(input.Company)
|
|
||||||
if jobTitle == "" || company == "" {
|
|
||||||
return nil, fmt.Errorf("jobTitle and company are required")
|
|
||||||
}
|
|
||||||
app := models.JobApplication{
|
|
||||||
JobTitle: jobTitle,
|
|
||||||
Company: company,
|
|
||||||
Location: input.Location,
|
|
||||||
URL: input.URL,
|
|
||||||
Status: services.NormalizeStatus(input.Status),
|
|
||||||
Notes: input.Notes,
|
|
||||||
AppliedAt: input.AppliedAt,
|
|
||||||
Description: input.Description,
|
|
||||||
}
|
|
||||||
if err := r.Store.DB.Create(&app).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &app, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateJobApplication is the resolver for the updateJobApplication field.
|
|
||||||
func (r *mutationResolver) UpdateJobApplication(ctx context.Context, id int, input model.UpdateJobApplicationInput) (*models.JobApplication, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
// Partial update: every input field is a pointer so that "not supplied"
|
|
||||||
// is distinguishable from "set to empty". A nil field is left untouched.
|
|
||||||
// An explicit "" on a nullable column does clear it — that is how the UI
|
|
||||||
// empties a wrong URL or stale notes — but the same value on a required
|
|
||||||
// column is rejected rather than blanking a live row.
|
|
||||||
var app models.JobApplication
|
|
||||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if input.JobTitle != nil {
|
|
||||||
if strings.TrimSpace(*input.JobTitle) == "" {
|
|
||||||
return nil, fmt.Errorf("jobTitle cannot be empty")
|
|
||||||
}
|
|
||||||
app.JobTitle = strings.TrimSpace(*input.JobTitle)
|
|
||||||
}
|
|
||||||
if input.Company != nil {
|
|
||||||
if strings.TrimSpace(*input.Company) == "" {
|
|
||||||
return nil, fmt.Errorf("company cannot be empty")
|
|
||||||
}
|
|
||||||
app.Company = strings.TrimSpace(*input.Company)
|
|
||||||
}
|
|
||||||
if input.Location != nil {
|
|
||||||
app.Location = input.Location
|
|
||||||
}
|
|
||||||
if input.URL != nil {
|
|
||||||
app.URL = input.URL
|
|
||||||
}
|
|
||||||
if input.Status != nil {
|
|
||||||
app.Status = services.NormalizeStatus(*input.Status)
|
|
||||||
}
|
|
||||||
if input.Notes != nil {
|
|
||||||
app.Notes = input.Notes
|
|
||||||
}
|
|
||||||
if input.AppliedAt != nil {
|
|
||||||
app.AppliedAt = input.AppliedAt
|
|
||||||
}
|
|
||||||
if input.Description != nil {
|
|
||||||
app.Description = input.Description
|
|
||||||
}
|
|
||||||
if err := r.Store.DB.Save(&app).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &app, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteJobApplication is the resolver for the deleteJobApplication field.
|
|
||||||
func (r *mutationResolver) DeleteJobApplication(ctx context.Context, id int) (bool, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return false, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
// Soft delete straight by id, without loading first — so deleting an id
|
|
||||||
// that does not exist still returns true.
|
|
||||||
if err := r.Store.DB.Delete(&models.JobApplication{}, id).Error; err != nil {
|
|
||||||
return false, err
|
|
||||||
}
|
|
||||||
return true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobApplications is the resolver for the jobApplications field.
|
|
||||||
func (r *queryResolver) JobApplications(ctx context.Context) ([]*models.JobApplication, error) {
|
|
||||||
// Admin-only even though it is a query: job applications are private.
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
// Find can populate a slice of pointers directly, avoiding the
|
|
||||||
// copy-to-pointers loop the other list resolvers need.
|
|
||||||
var apps []*models.JobApplication
|
|
||||||
// id is the tie-break: one sync loop inserts several rows inside the same
|
|
||||||
// timestamp, and Postgres gives no stable order for equal sort keys, so
|
|
||||||
// without it the list can reshuffle between two identical page loads.
|
|
||||||
if err := r.Store.DB.Order("created_at desc, id desc").Find(&apps).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return apps, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobApplication is the resolver for the jobApplication field.
|
|
||||||
func (r *queryResolver) JobApplication(ctx context.Context, id int) (*models.JobApplication, error) {
|
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
var app models.JobApplication
|
|
||||||
if err := r.Store.DB.First(&app, id).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return &app, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobApplication returns JobApplicationResolver implementation.
|
|
||||||
func (r *Resolver) JobApplication() JobApplicationResolver { return &jobApplicationResolver{r} }
|
|
||||||
|
|
||||||
type jobApplicationResolver struct{ *Resolver }
|
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// BoxCount is the resolver for the boxCount field.
|
||||||
|
func (r *layoutResolver) BoxCount(ctx context.Context, obj *models.Layout) (int, error) {
|
||||||
|
// Decoded rather than stored, so it can never disagree with the boxes.
|
||||||
|
boxes, err := decodeLayoutBoxes(obj)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return len(boxes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasBackground is the resolver for the hasBackground field.
|
||||||
|
func (r *layoutResolver) HasBackground(ctx context.Context, obj *models.Layout) (bool, error) {
|
||||||
|
return obj.Background != nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateLayout is the resolver for the createLayout field.
|
||||||
|
func (r *mutationResolver) CreateLayout(ctx context.Context, input model.CreateLayoutInput) (*models.Layout, error) {
|
||||||
|
// A snapshot of the page as it is now, adminOnly boxes included —
|
||||||
|
// which is why every layout field is @admin.
|
||||||
|
name, err := cleanLayoutName(input.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !validPageKey(input.Page) {
|
||||||
|
return nil, errors.New("a layout needs a valid page")
|
||||||
|
}
|
||||||
|
taken, err := layoutNameTaken(r.Store.DB, name, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a layout with that name")
|
||||||
|
}
|
||||||
|
layout, empty, err := snapshotPage(r.Store.DB, input.Page, name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if empty {
|
||||||
|
return nil, errors.New("that page has nothing on it to save")
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Create(&layout).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &layout, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateLayout is the resolver for the updateLayout field.
|
||||||
|
func (r *mutationResolver) UpdateLayout(ctx context.Context, id int, input model.UpdateLayoutInput) (*models.Layout, error) {
|
||||||
|
// Only the name changes: a layout is a snapshot, and saving the page
|
||||||
|
// again under a new name is how its content is refreshed.
|
||||||
|
var layout models.Layout
|
||||||
|
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if input.Name != nil {
|
||||||
|
name, err := cleanLayoutName(*input.Name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
taken, err := layoutNameTaken(r.Store.DB, name, layout.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a layout with that name")
|
||||||
|
}
|
||||||
|
layout.Name = name
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Save(&layout).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &layout, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteLayout is the resolver for the deleteLayout field.
|
||||||
|
func (r *mutationResolver) DeleteLayout(ctx context.Context, id int) (*models.Layout, error) {
|
||||||
|
// Pages it was loaded onto keep their boxes: they were copies.
|
||||||
|
var layout models.Layout
|
||||||
|
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Delete(&layout).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &layout, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyLayout is the resolver for the applyLayout field.
|
||||||
|
func (r *mutationResolver) ApplyLayout(ctx context.Context, id int, page string, replace bool) ([]*models.Box, error) {
|
||||||
|
// One transaction, so a replace that fails partway leaves the page as
|
||||||
|
// it was rather than half emptied.
|
||||||
|
var layout models.Layout
|
||||||
|
if err := r.Store.DB.First(&layout, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
exists, err := canvasExists(r.Store.DB, page)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
return nil, errors.New("there is no page at that address")
|
||||||
|
}
|
||||||
|
err = r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
return applyLayoutTo(tx, &layout, page, replace)
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
boxes, err := pageBoxes(r.Store.DB, page)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := fillLinked(r.Store.DB, boxes); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(boxes), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layouts is the resolver for the layouts field.
|
||||||
|
func (r *queryResolver) Layouts(ctx context.Context) ([]*models.Layout, error) {
|
||||||
|
var layouts []models.Layout
|
||||||
|
if err := r.Store.DB.Order("created_at DESC").Find(&layouts).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(layouts), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Layout returns LayoutResolver implementation.
|
||||||
|
func (r *Resolver) Layout() LayoutResolver { return &layoutResolver{r} }
|
||||||
|
|
||||||
|
type layoutResolver struct{ *Resolver }
|
||||||
@@ -0,0 +1,250 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
const maxLayoutNameLen = 100
|
||||||
|
|
||||||
|
// layoutBox is a box minus id and page. Renaming fields breaks saved layouts.
|
||||||
|
type layoutBox struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Widget *string `json:"widget,omitempty"`
|
||||||
|
HTML *string `json:"html,omitempty"`
|
||||||
|
Title *string `json:"title,omitempty"`
|
||||||
|
X int `json:"x"`
|
||||||
|
Y int `json:"y"`
|
||||||
|
W int `json:"w"`
|
||||||
|
H int `json:"h"`
|
||||||
|
Z int `json:"z"`
|
||||||
|
Framed bool `json:"framed"`
|
||||||
|
Shadow string `json:"shadow,omitempty"`
|
||||||
|
HideOnMobile bool `json:"hideOnMobile"`
|
||||||
|
AdminOnly bool `json:"adminOnly"`
|
||||||
|
// HTML is kept too, so a layout outlives a deleted component.
|
||||||
|
ComponentID *uint `json:"componentId,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type layoutBackground struct {
|
||||||
|
Color string `json:"color"`
|
||||||
|
Image string `json:"image"`
|
||||||
|
Fit string `json:"fit"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func cleanLayoutName(name string) (string, error) {
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" {
|
||||||
|
return name, errors.New("a layout needs a name")
|
||||||
|
}
|
||||||
|
if len(name) > maxLayoutNameLen {
|
||||||
|
return name, fmt.Errorf("a layout name is at most %d characters", maxLayoutNameLen)
|
||||||
|
}
|
||||||
|
return name, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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: boxes on any other key would never be shown.
|
||||||
|
func canvasExists(db *gorm.DB, page string) (bool, error) {
|
||||||
|
if page == "index" {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if !validPageKey(page) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
err := db.Model(&models.Page{}).Where("slug = ?", page).Count(&count).Error
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageBoxes 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
|
||||||
|
}
|
||||||
|
|
||||||
|
func snapshotPage(db *gorm.DB, page, name string) (layout models.Layout, empty bool, err error) {
|
||||||
|
boxes, err := pageBoxes(db, page)
|
||||||
|
if err != nil {
|
||||||
|
return layout, false, err
|
||||||
|
}
|
||||||
|
if err := fillLinked(db, boxes); err != nil {
|
||||||
|
return layout, false, err
|
||||||
|
}
|
||||||
|
stored := make([]layoutBox, len(boxes))
|
||||||
|
for i, b := range boxes {
|
||||||
|
stored[i] = layoutBox{
|
||||||
|
Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
|
||||||
|
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z,
|
||||||
|
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
|
||||||
|
ComponentID: b.ComponentID,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
boxesJSON, err := json.Marshal(stored)
|
||||||
|
if err != nil {
|
||||||
|
return layout, false, err
|
||||||
|
}
|
||||||
|
layout = models.Layout{Name: name, SourcePage: page, Boxes: string(boxesJSON)}
|
||||||
|
|
||||||
|
var bg models.Background
|
||||||
|
err = db.Where("page = ?", page).First(&bg).Error
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
bgJSON, err := json.Marshal(layoutBackground{Color: bg.Color, Image: bg.Image, Fit: bg.Fit})
|
||||||
|
if err != nil {
|
||||||
|
return layout, false, err
|
||||||
|
}
|
||||||
|
s := string(bgJSON)
|
||||||
|
layout.Background = &s
|
||||||
|
case !errors.Is(err, gorm.ErrRecordNotFound):
|
||||||
|
return layout, false, err
|
||||||
|
}
|
||||||
|
return layout, len(boxes) == 0 && layout.Background == nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeLayoutBoxes(layout *models.Layout) ([]layoutBox, error) {
|
||||||
|
var boxes []layoutBox
|
||||||
|
if err := json.Unmarshal([]byte(layout.Boxes), &boxes); err != nil {
|
||||||
|
return nil, fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
|
||||||
|
}
|
||||||
|
return boxes, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func pageLabel(page string) string {
|
||||||
|
if page == "index" {
|
||||||
|
return "/"
|
||||||
|
}
|
||||||
|
return "/" + page
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniqueLayoutName(db *gorm.DB, base string) (string, error) {
|
||||||
|
name := base
|
||||||
|
for n := 2; ; n++ {
|
||||||
|
taken, err := layoutNameTaken(db, name, 0)
|
||||||
|
if err != nil || !taken {
|
||||||
|
return name, err
|
||||||
|
}
|
||||||
|
name = fmt.Sprintf("%s (%d)", base, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// applyLayoutTo 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 copies stack above the page's existing boxes.
|
||||||
|
zShift := 0
|
||||||
|
if replace {
|
||||||
|
// 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 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
backup, empty, err := snapshotPage(tx, page, name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !empty {
|
||||||
|
if err := tx.Create(&backup).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := tx.Where("page = ?", page).Delete(&models.Box{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("page = ?", page).Delete(&models.Background{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
} else if len(stored) > 0 {
|
||||||
|
var top *int
|
||||||
|
if err := tx.Model(&models.Box{}).Where("page = ?", page).Select("MAX(z)").Scan(&top).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if top != nil {
|
||||||
|
lowest := stored[0].Z
|
||||||
|
for _, b := range stored {
|
||||||
|
lowest = min(lowest, b.Z)
|
||||||
|
}
|
||||||
|
zShift = *top + 1 - lowest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
live, err := liveComponents(tx, stored)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
boxes := make([]models.Box, len(stored))
|
||||||
|
for i, b := range stored {
|
||||||
|
boxes[i] = models.Box{
|
||||||
|
Page: page, Kind: b.Kind, Widget: b.Widget, HTML: b.HTML, Title: b.Title,
|
||||||
|
X: b.X, Y: b.Y, W: b.W, H: b.H, Z: b.Z + zShift,
|
||||||
|
Framed: b.Framed, Shadow: b.Shadow, HideOnMobile: b.HideOnMobile, AdminOnly: b.AdminOnly,
|
||||||
|
}
|
||||||
|
if b.ComponentID != nil && live[*b.ComponentID] {
|
||||||
|
boxes[i].ComponentID = b.ComponentID
|
||||||
|
boxes[i].HTML = nil
|
||||||
|
}
|
||||||
|
if err := validateBox(&boxes[i]); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(boxes) > 0 {
|
||||||
|
if err := tx.Create(&boxes).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if replace && layout.Background != nil {
|
||||||
|
var saved layoutBackground
|
||||||
|
if err := json.Unmarshal([]byte(*layout.Background), &saved); err != nil {
|
||||||
|
return fmt.Errorf("layout %q is unreadable: %w", layout.Name, err)
|
||||||
|
}
|
||||||
|
bg, err := backgroundFrom(page, model.BackgroundInput{Color: saved.Color, Image: saved.Image, Fit: saved.Fit})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Create(&bg).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func liveComponents(db *gorm.DB, stored []layoutBox) (map[uint]bool, error) {
|
||||||
|
var ids []uint
|
||||||
|
for _, b := range stored {
|
||||||
|
if b.ComponentID != nil {
|
||||||
|
ids = append(ids, *b.ComponentID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
live := map[uint]bool{}
|
||||||
|
if len(ids) == 0 {
|
||||||
|
return live, nil
|
||||||
|
}
|
||||||
|
var found []uint
|
||||||
|
if err := db.Model(&models.Component{}).Where("id IN ?", ids).Pluck("id", &found).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for _, id := range found {
|
||||||
|
live[id] = true
|
||||||
|
}
|
||||||
|
return live, nil
|
||||||
|
}
|
||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -11,27 +11,16 @@ import (
|
|||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *messageResolver) ID(ctx context.Context, obj *models.Message) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// AuthorID is the resolver for the authorId field.
|
// AuthorID is the resolver for the authorId field.
|
||||||
// AuthorID is the resolver for the authorId field. The value is the chat
|
// The chat hub's connection number, not a User id.
|
||||||
// hub's per-connection counter, not a User id — see models.Message.
|
|
||||||
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
|
func (r *messageResolver) AuthorID(ctx context.Context, obj *models.Message) (int, error) {
|
||||||
return int(obj.AuthorID), nil
|
return int(obj.AuthorID), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Messages is the resolver for the messages field.
|
// Messages is the resolver for the messages field.
|
||||||
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
func (r *queryResolver) Messages(ctx context.Context) ([]*models.Message, error) {
|
||||||
// Non-admins get the public subset rather than an error, so the chat
|
// Non-admins get the public subset. Keep in step with the WebSocket
|
||||||
// history loads for everyone. The same filter is applied to the history
|
// history filter (services.HandleWebSocket), which is oldest first.
|
||||||
// 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.
|
|
||||||
var messages []models.Message
|
var messages []models.Message
|
||||||
query := r.Store.DB.Order("created_at DESC")
|
query := r.Store.DB.Order("created_at DESC")
|
||||||
if !IsAdminFromCtx(ctx) {
|
if !IsAdminFromCtx(ctx) {
|
||||||
|
|||||||
@@ -8,38 +8,20 @@ import (
|
|||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AuthContextMiddleware prepares the request context for the GraphQL handler.
|
// AuthContextMiddleware never rejects: a bad or missing token leaves the
|
||||||
//
|
// context anonymous and the directives decide. No refresh fallback.
|
||||||
// It always attaches the *gin.Context, and attaches the JWT claims only when a
|
|
||||||
// valid access token is present. Crucially it never rejects a request: a
|
|
||||||
// missing, expired or forged token simply leaves the context anonymous, which
|
|
||||||
// is what lets public queries work and pushes every authorisation decision
|
|
||||||
// into the individual resolvers (see IsAdminFromCtx). Both cookie and verify
|
|
||||||
// errors are swallowed for exactly that reason.
|
|
||||||
//
|
|
||||||
// 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.
|
|
||||||
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
|
func AuthContextMiddleware(auth *services.Auth, db *gorm.DB) gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
ctx := context.WithValue(c.Request.Context(), ginContextKey, c)
|
||||||
|
|
||||||
accessToken, err := c.Cookie("access_token")
|
accessToken, err := c.Cookie("access_token")
|
||||||
if err == nil {
|
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)
|
_, claims, err := auth.AuthenticateTokenWithClaims(db, accessToken)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
ctx = context.WithValue(ctx, userClaimsKey, claims)
|
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.Request = c.Request.WithContext(ctx)
|
||||||
c.Next()
|
c.Next()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,6 +12,12 @@ type AuthPayload struct {
|
|||||||
User *models.User `json:"user"`
|
User *models.User `json:"user"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type BackgroundInput struct {
|
||||||
|
Color string `json:"color"`
|
||||||
|
Image string `json:"image"`
|
||||||
|
Fit string `json:"fit"`
|
||||||
|
}
|
||||||
|
|
||||||
type CreateActivityInput struct {
|
type CreateActivityInput struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
@@ -24,28 +30,60 @@ type CreateBookmarkInput struct {
|
|||||||
Link string `json:"link"`
|
Link string `json:"link"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type CreateBoxInput struct {
|
||||||
|
Page string `json:"page"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Widget *string `json:"widget,omitempty"`
|
||||||
|
HTML *string `json:"html,omitempty"`
|
||||||
|
Title *string `json:"title,omitempty"`
|
||||||
|
X *int `json:"x,omitempty"`
|
||||||
|
Y *int `json:"y,omitempty"`
|
||||||
|
W *int `json:"w,omitempty"`
|
||||||
|
H *int `json:"h,omitempty"`
|
||||||
|
Z *int `json:"z,omitempty"`
|
||||||
|
Framed *bool `json:"framed,omitempty"`
|
||||||
|
Shadow *string `json:"shadow,omitempty"`
|
||||||
|
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
|
||||||
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
|
ComponentID *int `json:"componentId,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateComponentInput struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Title *string `json:"title,omitempty"`
|
||||||
|
HTML string `json:"html"`
|
||||||
|
W *int `json:"w,omitempty"`
|
||||||
|
H *int `json:"h,omitempty"`
|
||||||
|
Framed *bool `json:"framed,omitempty"`
|
||||||
|
Shadow *string `json:"shadow,omitempty"`
|
||||||
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateCoverLetterInput struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateCoverSnippetInput struct {
|
||||||
|
Text string `json:"text"`
|
||||||
|
Section *string `json:"section,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
type CreateFavoriteInput struct {
|
type CreateFavoriteInput struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Link *string `json:"link,omitempty"`
|
Link *string `json:"link,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateJobAppReferenceInput struct {
|
type CreateLayoutInput struct {
|
||||||
Category string `json:"category"`
|
Name string `json:"name"`
|
||||||
Label string `json:"label"`
|
Page string `json:"page"`
|
||||||
Value string `json:"value"`
|
|
||||||
SortOrder *int `json:"sortOrder,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateJobApplicationInput struct {
|
type CreatePageInput struct {
|
||||||
JobTitle string `json:"jobTitle"`
|
Slug string `json:"slug"`
|
||||||
Company string `json:"company"`
|
Title string `json:"title"`
|
||||||
Location *string `json:"location,omitempty"`
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
URL *string `json:"url,omitempty"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
Notes *string `json:"notes,omitempty"`
|
|
||||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
|
||||||
Description *string `json:"description,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreatePlaceInput struct {
|
type CreatePlaceInput struct {
|
||||||
@@ -131,22 +169,50 @@ type SteamStatus struct {
|
|||||||
RecentGames []*SteamGame `json:"recentGames"`
|
RecentGames []*SteamGame `json:"recentGames"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateJobAppReferenceInput struct {
|
type UpdateBoxInput struct {
|
||||||
Category *string `json:"category,omitempty"`
|
Widget *string `json:"widget,omitempty"`
|
||||||
Label *string `json:"label,omitempty"`
|
HTML *string `json:"html,omitempty"`
|
||||||
Value *string `json:"value,omitempty"`
|
Title *string `json:"title,omitempty"`
|
||||||
SortOrder *int `json:"sortOrder,omitempty"`
|
X *int `json:"x,omitempty"`
|
||||||
|
Y *int `json:"y,omitempty"`
|
||||||
|
W *int `json:"w,omitempty"`
|
||||||
|
H *int `json:"h,omitempty"`
|
||||||
|
Z *int `json:"z,omitempty"`
|
||||||
|
Framed *bool `json:"framed,omitempty"`
|
||||||
|
Shadow *string `json:"shadow,omitempty"`
|
||||||
|
HideOnMobile *bool `json:"hideOnMobile,omitempty"`
|
||||||
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdateJobApplicationInput struct {
|
type UpdateComponentInput struct {
|
||||||
JobTitle *string `json:"jobTitle,omitempty"`
|
Name *string `json:"name,omitempty"`
|
||||||
Company *string `json:"company,omitempty"`
|
Title *string `json:"title,omitempty"`
|
||||||
Location *string `json:"location,omitempty"`
|
HTML *string `json:"html,omitempty"`
|
||||||
URL *string `json:"url,omitempty"`
|
W *int `json:"w,omitempty"`
|
||||||
Status *string `json:"status,omitempty"`
|
H *int `json:"h,omitempty"`
|
||||||
Notes *string `json:"notes,omitempty"`
|
Framed *bool `json:"framed,omitempty"`
|
||||||
AppliedAt *time.Time `json:"appliedAt,omitempty"`
|
Shadow *string `json:"shadow,omitempty"`
|
||||||
Description *string `json:"description,omitempty"`
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateCoverLetterInput struct {
|
||||||
|
Name *string `json:"name,omitempty"`
|
||||||
|
Body *string `json:"body,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateCoverSnippetInput struct {
|
||||||
|
Text *string `json:"text,omitempty"`
|
||||||
|
Section *string `json:"section,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateLayoutInput struct {
|
||||||
|
Name *string `json:"name,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdatePageInput struct {
|
||||||
|
Slug *string `json:"slug,omitempty"`
|
||||||
|
Title *string `json:"title,omitempty"`
|
||||||
|
AdminOnly *bool `json:"adminOnly,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpdatePlaceInput struct {
|
type UpdatePlaceInput struct {
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
|
// implementations
|
||||||
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/graph/model"
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CreatePage is the resolver for the createPage field.
|
||||||
|
func (r *mutationResolver) CreatePage(ctx context.Context, input model.CreatePageInput) (*models.Page, error) {
|
||||||
|
page := models.Page{
|
||||||
|
Slug: input.Slug,
|
||||||
|
Title: strings.TrimSpace(input.Title),
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
page.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
if err := validateSlug(page.Slug); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if page.Title == "" {
|
||||||
|
return nil, errors.New("a page needs a title")
|
||||||
|
}
|
||||||
|
taken, err := slugTaken(r.Store.DB, page.Slug, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a page at that address")
|
||||||
|
}
|
||||||
|
if err := r.Store.DB.Create(&page).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdatePage is the resolver for the updatePage field.
|
||||||
|
func (r *mutationResolver) UpdatePage(ctx context.Context, id int, input model.UpdatePageInput) (*models.Page, error) {
|
||||||
|
// Partial. 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
|
||||||
|
}
|
||||||
|
oldSlug := page.Slug
|
||||||
|
if input.Slug != nil {
|
||||||
|
page.Slug = *input.Slug
|
||||||
|
}
|
||||||
|
if input.Title != nil {
|
||||||
|
page.Title = strings.TrimSpace(*input.Title)
|
||||||
|
}
|
||||||
|
if input.AdminOnly != nil {
|
||||||
|
page.AdminOnly = *input.AdminOnly
|
||||||
|
}
|
||||||
|
if page.Title == "" {
|
||||||
|
return nil, errors.New("a page needs a title")
|
||||||
|
}
|
||||||
|
if page.Slug != oldSlug {
|
||||||
|
if err := validateSlug(page.Slug); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
taken, err := slugTaken(r.Store.DB, page.Slug, page.ID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if taken {
|
||||||
|
return nil, errors.New("there is already a page at that address")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if page.Slug != oldSlug {
|
||||||
|
if err := tx.Model(&models.Box{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Model(&models.Background{}).Where("page = ?", oldSlug).Update("page", page.Slug).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return tx.Save(&page).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeletePage is the resolver for the deletePage field.
|
||||||
|
func (r *mutationResolver) DeletePage(ctx context.Context, id int) (*models.Page, error) {
|
||||||
|
// The boxes and background go too: left behind, they would reappear on
|
||||||
|
// any page later created at the same address.
|
||||||
|
var page models.Page
|
||||||
|
if err := r.Store.DB.First(&page, id).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err := r.Store.DB.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Where("page = ?", page.Slug).Delete(&models.Box{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Where("page = ?", page.Slug).Delete(&models.Background{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return tx.Delete(&page).Error
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pages is the resolver for the pages field.
|
||||||
|
func (r *queryResolver) Pages(ctx context.Context) ([]*models.Page, error) {
|
||||||
|
// Public, for page indexes such as /shrines; adminOnly pages are only
|
||||||
|
// listed for an admin.
|
||||||
|
query := r.Store.DB.Order("slug ASC")
|
||||||
|
if !IsAdminFromCtx(ctx) {
|
||||||
|
query = query.Where("admin_only = ?", false)
|
||||||
|
}
|
||||||
|
var pages []models.Page
|
||||||
|
if err := query.Find(&pages).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ptrs(pages), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page is the resolver for the page field.
|
||||||
|
func (r *queryResolver) Page(ctx context.Context, slug string) (*models.Page, error) {
|
||||||
|
// Null 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) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if page.AdminOnly && !IsAdminFromCtx(ctx) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return &page, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
// Hand-written helpers for page.resolvers.go and box.resolvers.go, kept out
|
||||||
|
// of the resolver files for the same reason as box_helpers.go.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"adam-french.co.uk/backend/models"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
// 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,
|
||||||
|
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
|
||||||
|
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
|
||||||
|
"sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true,
|
||||||
|
}
|
||||||
|
|
||||||
|
func validPageKey(key string) bool {
|
||||||
|
return len(key) <= maxSlugLen && pageKeyPattern.MatchString(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateSlug reports why slug can't be a page's address, or nil.
|
||||||
|
func validateSlug(slug string) error {
|
||||||
|
if !validPageKey(slug) {
|
||||||
|
return errors.New("a page address is lower-case letters, digits and hyphens, in /-separated parts, e.g. shrines/evangelion")
|
||||||
|
}
|
||||||
|
first, _, _ := strings.Cut(slug, "/")
|
||||||
|
if reservedFirstSegments[first] {
|
||||||
|
return errors.New("that address is already used by the site")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
var count int64
|
||||||
|
err := db.Model(&models.Page{}).Where("slug = ? AND admin_only = ?", key, true).Count(&count).Error
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
return count > 0, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package graph
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateSlug(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
slug string
|
||||||
|
ok bool
|
||||||
|
}{
|
||||||
|
{"notes-to-self", true},
|
||||||
|
{"shrines/evangelion", true},
|
||||||
|
{"shrines/neon-genesis/rei2", true},
|
||||||
|
{"", false},
|
||||||
|
{"Shrines/GTO", false}, // upper case
|
||||||
|
{"shrines/", false}, // empty segment
|
||||||
|
{"/shrines/gto", false}, // leading slash
|
||||||
|
{"shrines//gto", false}, // empty segment
|
||||||
|
{"shrines/gto-", false}, // trailing hyphen
|
||||||
|
{"shrines/../admin", false}, // dots
|
||||||
|
{"shrines", true}, // the index is a canvas page too
|
||||||
|
{"shrines/demoman", true}, // no longer an SPA route
|
||||||
|
{"admin/pages", false}, // under an SPA route
|
||||||
|
{"jobs/x", false}, // under a Caddy route
|
||||||
|
{"stp", true}, // the home page is a canvas page too
|
||||||
|
{"stp2", false}, // an SPA route
|
||||||
|
{"index", false}, // the landing canvas's key
|
||||||
|
{"stp-fan-page", true}, // only whole segments are reserved
|
||||||
|
} {
|
||||||
|
err := validateSlug(c.slug)
|
||||||
|
if (err == nil) != c.ok {
|
||||||
|
t.Errorf("validateSlug(%q) = %v, want ok=%v", c.slug, err, c.ok)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,10 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
@@ -15,12 +14,7 @@ import (
|
|||||||
|
|
||||||
// CreatePlace is the resolver for the createPlace field.
|
// CreatePlace is the resolver for the createPlace field.
|
||||||
func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePlaceInput) (*models.Place, error) {
|
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,
|
// @signedIn: places are the site's one shared list, with no ownership.
|
||||||
// collaboratively edited list on the site. There is no per-user
|
|
||||||
// ownership, so any signed-in user can edit or delete any place.
|
|
||||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
|
||||||
return nil, fmt.Errorf("authentication required")
|
|
||||||
}
|
|
||||||
place := models.Place{
|
place := models.Place{
|
||||||
Title: input.Title,
|
Title: input.Title,
|
||||||
Location: input.Location,
|
Location: input.Location,
|
||||||
@@ -43,9 +37,6 @@ func (r *mutationResolver) CreatePlace(ctx context.Context, input model.CreatePl
|
|||||||
|
|
||||||
// UpdatePlace is the resolver for the updatePlace field.
|
// UpdatePlace is the resolver for the updatePlace field.
|
||||||
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.UpdatePlaceInput) (*models.Place, error) {
|
||||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
|
||||||
return nil, fmt.Errorf("authentication required")
|
|
||||||
}
|
|
||||||
// Partial update, same pointer-means-supplied convention as job
|
// Partial update, same pointer-means-supplied convention as job
|
||||||
// applications: nil fields are left as they are.
|
// applications: nil fields are left as they are.
|
||||||
var place models.Place
|
var place models.Place
|
||||||
@@ -84,9 +75,6 @@ func (r *mutationResolver) UpdatePlace(ctx context.Context, id int, input model.
|
|||||||
|
|
||||||
// DeletePlace is the resolver for the deletePlace field.
|
// DeletePlace is the resolver for the deletePlace field.
|
||||||
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Place, error) {
|
||||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
|
||||||
return nil, fmt.Errorf("authentication required")
|
|
||||||
}
|
|
||||||
var place models.Place
|
var place models.Place
|
||||||
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
if err := r.Store.DB.First(&place, id).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -97,24 +85,11 @@ func (r *mutationResolver) DeletePlace(ctx context.Context, id int) (*models.Pla
|
|||||||
return &place, nil
|
return &place, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *placeResolver) ID(ctx context.Context, obj *models.Place) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Places is the resolver for the places field.
|
// Places is the resolver for the places field.
|
||||||
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
func (r *queryResolver) Places(ctx context.Context) ([]*models.Place, error) {
|
||||||
if _, ok := UserIDFromCtx(ctx); !ok {
|
|
||||||
return nil, fmt.Errorf("authentication required")
|
|
||||||
}
|
|
||||||
var places []models.Place
|
var places []models.Place
|
||||||
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
if err := r.Store.DB.Order("done ASC, priority DESC, created_at DESC").Find(&places).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return ptrs(places), nil
|
return ptrs(places), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Place returns PlaceResolver implementation.
|
|
||||||
func (r *Resolver) Place() PlaceResolver { return &placeResolver{r} }
|
|
||||||
|
|
||||||
type placeResolver struct{ *Resolver }
|
|
||||||
|
|||||||
@@ -3,11 +3,12 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
@@ -15,15 +16,16 @@ import (
|
|||||||
|
|
||||||
// CreatePost is the resolver for the createPost field.
|
// CreatePost is the resolver for the createPost field.
|
||||||
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePostInput) (*models.Post, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
userID, ok := UserIDFromCtx(ctx)
|
userID, ok := UserIDFromCtx(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unauthorized")
|
return nil, fmt.Errorf("unauthorized")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Stops a stray click publishing a blank post.
|
||||||
|
if strings.TrimSpace(input.Title) == "" {
|
||||||
|
return nil, fmt.Errorf("a post needs a title")
|
||||||
|
}
|
||||||
|
|
||||||
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
|
post := models.Post{Title: input.Title, Content: input.Content, AuthorID: userID}
|
||||||
if err := r.Store.DB.Create(&post).Error; err != nil {
|
if err := r.Store.DB.Create(&post).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -34,10 +36,6 @@ func (r *mutationResolver) CreatePost(ctx context.Context, input model.CreatePos
|
|||||||
|
|
||||||
// UpdatePost is the resolver for the updatePost field.
|
// UpdatePost is the resolver for the updatePost field.
|
||||||
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.UpdatePostInput) (*models.Post, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
userID, ok := UserIDFromCtx(ctx)
|
userID, ok := UserIDFromCtx(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unauthorized")
|
return nil, fmt.Errorf("unauthorized")
|
||||||
@@ -48,14 +46,12 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
|||||||
return nil, fmt.Errorf("post not found")
|
return nil, fmt.Errorf("post not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Admin alone is not enough: a post may only be edited by its author, so
|
// Only the author may edit, even among admins.
|
||||||
// one admin cannot rewrite another's posts.
|
|
||||||
if post.AuthorID != userID {
|
if post.AuthorID != userID {
|
||||||
return nil, fmt.Errorf("you can only update your own posts")
|
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 —
|
// Full replace: an omitted field is blanked.
|
||||||
// omitting one in the mutation blanks it rather than leaving it alone.
|
|
||||||
post.Title = input.Title
|
post.Title = input.Title
|
||||||
post.Content = input.Content
|
post.Content = input.Content
|
||||||
if err := r.Store.DB.Save(&post).Error; err != nil {
|
if err := r.Store.DB.Save(&post).Error; err != nil {
|
||||||
@@ -67,10 +63,6 @@ func (r *mutationResolver) UpdatePost(ctx context.Context, id int, input model.U
|
|||||||
|
|
||||||
// DeletePost is the resolver for the deletePost field.
|
// DeletePost is the resolver for the deletePost field.
|
||||||
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
userID, ok := UserIDFromCtx(ctx)
|
userID, ok := UserIDFromCtx(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unauthorized")
|
return nil, fmt.Errorf("unauthorized")
|
||||||
@@ -85,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")
|
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 {
|
if err := r.Store.DB.Delete(&post).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -95,16 +84,9 @@ func (r *mutationResolver) DeletePost(ctx context.Context, id int) (*models.Post
|
|||||||
return &post, nil
|
return &post, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *postResolver) ID(ctx context.Context, obj *models.Post) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Posts is the resolver for the posts field.
|
// Posts is the resolver for the posts field.
|
||||||
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
func (r *queryResolver) Posts(ctx context.Context) ([]*models.Post, error) {
|
||||||
// Preload issues a second query for the authors and fills in Post.Author.
|
// Without Preload, author resolves to null silently.
|
||||||
// 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.
|
|
||||||
var posts []models.Post
|
var posts []models.Post
|
||||||
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
if err := r.Store.DB.Preload("Author").Order("created_at DESC").Find(&posts).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -120,8 +102,3 @@ func (r *queryResolver) Post(ctx context.Context, id int) (*models.Post, error)
|
|||||||
}
|
}
|
||||||
return &post, nil
|
return &post, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post returns PostResolver implementation.
|
|
||||||
func (r *Resolver) Post() PostResolver { return &postResolver{r} }
|
|
||||||
|
|
||||||
type postResolver struct{ *Resolver }
|
|
||||||
|
|||||||
@@ -7,15 +7,7 @@ import "adam-french.co.uk/backend/handlers"
|
|||||||
// It serves as dependency injection for your app, add any dependencies you require
|
// It serves as dependency injection for your app, add any dependencies you require
|
||||||
// here.
|
// here.
|
||||||
|
|
||||||
// Resolver is the root of the GraphQL schema and the only dependency every
|
// Resolver holds the same handlers.Store the REST handlers use.
|
||||||
// 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
|
|
||||||
// (queryResolver, mutationResolver, postResolver, ...), which is why those
|
|
||||||
// one-line `struct{ *Resolver }` declarations appear at the bottom of each
|
|
||||||
// resolvers file.
|
|
||||||
type Resolver struct {
|
type Resolver struct {
|
||||||
Store *handlers.Store
|
Store *handlers.Store
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -20,14 +20,7 @@ func (r *queryResolver) RowingSessions(ctx context.Context) ([]*models.Rowing, e
|
|||||||
return ptrs(rows), nil
|
return ptrs(rows), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
|
||||||
func (r *rowingResolver) ID(ctx context.Context, obj *models.Rowing) (int, error) {
|
|
||||||
return int(obj.ID), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Time is the resolver for the time field.
|
// Time is the resolver for the time field.
|
||||||
// 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) {
|
func (r *rowingResolver) Time(ctx context.Context, obj *models.Rowing) (int, error) {
|
||||||
return int(obj.Time), nil
|
return int(obj.Time), nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
// Mutation returns MutationResolver implementation.
|
// Mutation returns MutationResolver implementation.
|
||||||
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
|
func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} }
|
||||||
|
|||||||
@@ -18,5 +18,5 @@ extend type Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createActivity(input: CreateActivityInput!): Activity!
|
createActivity(input: CreateActivityInput!): Activity! @admin
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,10 +7,14 @@ type AuthPayload {
|
|||||||
user: User!
|
user: User!
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# `me` carries no directive although it needs a session: it answers
|
||||||
|
# "unauthorized", not @signedIn's "authentication required", and the front end
|
||||||
|
# relies on that query failing quietly for an anonymous visitor.
|
||||||
extend type Query {
|
extend type Query {
|
||||||
me: User
|
me: User
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Deliberately public: these are how a session is obtained and given up.
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
login(input: LoginInput!): AuthPayload!
|
login(input: LoginInput!): AuthPayload!
|
||||||
logout: Boolean!
|
logout: Boolean!
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# A page key's background; null for an adminOnly page unless admin.
|
||||||
|
|
||||||
|
type Background {
|
||||||
|
id: ID!
|
||||||
|
updatedAt: Time!
|
||||||
|
page: String!
|
||||||
|
# A CSS colour, or "" for the theme's page colour.
|
||||||
|
color: String!
|
||||||
|
# An image URL, or "" for none.
|
||||||
|
image: String!
|
||||||
|
# "cover", "contain" or "tile".
|
||||||
|
fit: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
input BackgroundInput {
|
||||||
|
color: String!
|
||||||
|
image: String!
|
||||||
|
fit: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
# Null when the page has none, i.e. shows the theme's default.
|
||||||
|
background(page: String!): Background
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
# Creates or replaces the page's background.
|
||||||
|
setBackground(page: String!, input: BackgroundInput!): Background! @admin
|
||||||
|
# Back to the theme's default. True if there was one to remove.
|
||||||
|
clearBackground(page: String!): Boolean! @admin
|
||||||
|
}
|
||||||
@@ -18,6 +18,6 @@ extend type Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createBookmark(input: CreateBookmarkInput!): Bookmark!
|
createBookmark(input: CreateBookmarkInput!): Bookmark! @admin
|
||||||
deleteBookmark(id: ID!): Bookmark!
|
deleteBookmark(id: ID!): Bookmark! @admin
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# 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!
|
||||||
|
createdAt: Time!
|
||||||
|
updatedAt: Time!
|
||||||
|
page: String!
|
||||||
|
kind: String!
|
||||||
|
widget: String
|
||||||
|
html: String
|
||||||
|
title: String
|
||||||
|
x: Int!
|
||||||
|
y: Int!
|
||||||
|
w: Int!
|
||||||
|
h: Int!
|
||||||
|
z: Int!
|
||||||
|
framed: Boolean!
|
||||||
|
# A CSS box-shadow value, or "" for none.
|
||||||
|
shadow: String!
|
||||||
|
hideOnMobile: Boolean!
|
||||||
|
adminOnly: Boolean!
|
||||||
|
componentId: ID
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreateBoxInput {
|
||||||
|
page: String!
|
||||||
|
kind: String!
|
||||||
|
widget: String
|
||||||
|
html: String
|
||||||
|
title: String
|
||||||
|
x: Int
|
||||||
|
y: Int
|
||||||
|
w: Int
|
||||||
|
h: Int
|
||||||
|
z: Int
|
||||||
|
framed: Boolean
|
||||||
|
shadow: String
|
||||||
|
hideOnMobile: Boolean
|
||||||
|
adminOnly: Boolean
|
||||||
|
# Links the new box to this component; kind is then "html" and html is
|
||||||
|
# ignored.
|
||||||
|
componentId: ID
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdateBoxInput {
|
||||||
|
widget: String
|
||||||
|
html: String
|
||||||
|
title: String
|
||||||
|
x: Int
|
||||||
|
y: Int
|
||||||
|
w: Int
|
||||||
|
h: Int
|
||||||
|
z: Int
|
||||||
|
framed: Boolean
|
||||||
|
shadow: String
|
||||||
|
hideOnMobile: Boolean
|
||||||
|
adminOnly: Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
boxes(page: String!): [Box!]!
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createBox(input: CreateBoxInput!): Box! @admin
|
||||||
|
updateBox(id: ID!, input: UpdateBoxInput!): Box! @admin
|
||||||
|
deleteBox(id: ID!): Box! @admin
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Named HTML boxes, placed as copies or linked (Box.componentId); linked boxes
|
||||||
|
# share only the html. Admin only, reads included.
|
||||||
|
|
||||||
|
type Component {
|
||||||
|
id: ID!
|
||||||
|
createdAt: Time!
|
||||||
|
updatedAt: Time!
|
||||||
|
name: String!
|
||||||
|
title: String
|
||||||
|
html: String!
|
||||||
|
w: Int!
|
||||||
|
h: Int!
|
||||||
|
framed: Boolean!
|
||||||
|
shadow: String!
|
||||||
|
adminOnly: Boolean!
|
||||||
|
# How many boxes are linked to it.
|
||||||
|
uses: Int!
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreateComponentInput {
|
||||||
|
name: String!
|
||||||
|
title: String
|
||||||
|
html: String!
|
||||||
|
w: Int
|
||||||
|
h: Int
|
||||||
|
framed: Boolean
|
||||||
|
shadow: String
|
||||||
|
adminOnly: Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdateComponentInput {
|
||||||
|
name: String
|
||||||
|
title: String
|
||||||
|
html: String
|
||||||
|
w: Int
|
||||||
|
h: Int
|
||||||
|
framed: Boolean
|
||||||
|
shadow: String
|
||||||
|
adminOnly: Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
# By name.
|
||||||
|
components: [Component!]! @admin
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createComponent(input: CreateComponentInput!): Component! @admin
|
||||||
|
# A new html changes every box linked to it.
|
||||||
|
updateComponent(id: ID!, input: UpdateComponentInput!): Component! @admin
|
||||||
|
# Detaches every linked box first, giving each its own copy of the html, so
|
||||||
|
# no page changes.
|
||||||
|
deleteComponent(id: ID!): Component! @admin
|
||||||
|
# Makes html box `id` into a component named `name`, from its html, title,
|
||||||
|
# size, frame, shadow and adminOnly, and links the box to it. Answers with the box.
|
||||||
|
saveBoxAsComponent(id: ID!, name: String!): Box! @admin
|
||||||
|
# Gives linked box `id` its own copy of the component's html and unlinks it.
|
||||||
|
detachBox(id: ID!): Box! @admin
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
# Cover letters: saved letters from the /cv Cover Letter tab, and the bank of
|
||||||
|
# reusable paragraphs dragged into them. A letter's body is JSON the frontend
|
||||||
|
# owns (views/CV/coverLetter.js); the server only checks it is a JSON object
|
||||||
|
# of a sane size. See models.CoverLetter and graph/cover_letter_helpers.go.
|
||||||
|
#
|
||||||
|
# Admin only throughout, reads included: /cv is public, but the letters are
|
||||||
|
# drafts addressed to particular employers.
|
||||||
|
|
||||||
|
type CoverLetter {
|
||||||
|
id: ID!
|
||||||
|
createdAt: Time!
|
||||||
|
updatedAt: Time!
|
||||||
|
name: String!
|
||||||
|
# The whole letter, as a JSON object.
|
||||||
|
body: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
type CoverSnippet {
|
||||||
|
id: ID!
|
||||||
|
createdAt: Time!
|
||||||
|
text: String!
|
||||||
|
# The section title it was written for; "" for none. Only groups the bank.
|
||||||
|
section: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreateCoverLetterInput {
|
||||||
|
name: String!
|
||||||
|
body: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdateCoverLetterInput {
|
||||||
|
name: String
|
||||||
|
body: String
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreateCoverSnippetInput {
|
||||||
|
text: String!
|
||||||
|
section: String
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdateCoverSnippetInput {
|
||||||
|
text: String
|
||||||
|
section: String
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
# Most recently updated first.
|
||||||
|
coverLetters: [CoverLetter!]! @admin
|
||||||
|
# By section, then newest first.
|
||||||
|
coverSnippets: [CoverSnippet!]! @admin
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createCoverLetter(input: CreateCoverLetterInput!): CoverLetter! @admin
|
||||||
|
updateCoverLetter(id: ID!, input: UpdateCoverLetterInput!): CoverLetter! @admin
|
||||||
|
deleteCoverLetter(id: ID!): CoverLetter! @admin
|
||||||
|
createCoverSnippet(input: CreateCoverSnippetInput!): CoverSnippet! @admin
|
||||||
|
updateCoverSnippet(id: ID!, input: UpdateCoverSnippetInput!): CoverSnippet! @admin
|
||||||
|
deleteCoverSnippet(id: ID!): CoverSnippet! @admin
|
||||||
|
}
|
||||||
@@ -18,5 +18,5 @@ extend type Query {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createFavorite(input: CreateFavoriteInput!): Favorite!
|
createFavorite(input: CreateFavoriteInput!): Favorite! @admin
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
type JobAppReference {
|
|
||||||
id: ID!
|
|
||||||
createdAt: Time!
|
|
||||||
updatedAt: Time!
|
|
||||||
category: String!
|
|
||||||
label: String!
|
|
||||||
value: String!
|
|
||||||
sortOrder: Int!
|
|
||||||
}
|
|
||||||
|
|
||||||
input CreateJobAppReferenceInput {
|
|
||||||
category: String!
|
|
||||||
label: String!
|
|
||||||
value: String!
|
|
||||||
sortOrder: Int
|
|
||||||
}
|
|
||||||
|
|
||||||
input UpdateJobAppReferenceInput {
|
|
||||||
category: String
|
|
||||||
label: String
|
|
||||||
value: String
|
|
||||||
sortOrder: Int
|
|
||||||
}
|
|
||||||
|
|
||||||
extend type Query {
|
|
||||||
jobAppReferences: [JobAppReference!]!
|
|
||||||
}
|
|
||||||
|
|
||||||
extend type Mutation {
|
|
||||||
createJobAppReference(input: CreateJobAppReferenceInput!): JobAppReference!
|
|
||||||
updateJobAppReference(id: ID!, input: UpdateJobAppReferenceInput!): JobAppReference!
|
|
||||||
deleteJobAppReference(id: ID!): Boolean!
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
# Job application tracker. Rows come from these mutations, automatically from
|
|
||||||
# the email sync pipeline (backend/services/email_sync.go), or from the browser
|
|
||||||
# capture userscript (backend/handlers/handle_job_capture.go). These are
|
|
||||||
# private data, so the queries here are admin-only as well as the mutations.
|
|
||||||
#
|
|
||||||
# status is a free-form String, but only the values ranked in
|
|
||||||
# services.statusOrder can be advanced automatically by the email pipeline:
|
|
||||||
# saved, applied, screening, assessment, interviewing, offer, rejected,
|
|
||||||
# withdrawn.
|
|
||||||
#
|
|
||||||
# description is the captured posting text. It can run to tens of kilobytes,
|
|
||||||
# so the tracker's list query leaves it out and asks for it per row.
|
|
||||||
|
|
||||||
type JobApplication {
|
|
||||||
id: ID!
|
|
||||||
createdAt: Time!
|
|
||||||
updatedAt: Time!
|
|
||||||
jobTitle: String!
|
|
||||||
company: String!
|
|
||||||
location: String
|
|
||||||
url: String
|
|
||||||
status: String!
|
|
||||||
notes: String
|
|
||||||
appliedAt: Time
|
|
||||||
description: String
|
|
||||||
}
|
|
||||||
|
|
||||||
input CreateJobApplicationInput {
|
|
||||||
jobTitle: String!
|
|
||||||
company: String!
|
|
||||||
location: String
|
|
||||||
url: String
|
|
||||||
status: String!
|
|
||||||
notes: String
|
|
||||||
appliedAt: Time
|
|
||||||
description: String
|
|
||||||
}
|
|
||||||
|
|
||||||
input UpdateJobApplicationInput {
|
|
||||||
jobTitle: String
|
|
||||||
company: String
|
|
||||||
location: String
|
|
||||||
url: String
|
|
||||||
status: String
|
|
||||||
notes: String
|
|
||||||
appliedAt: Time
|
|
||||||
description: String
|
|
||||||
}
|
|
||||||
|
|
||||||
extend type Query {
|
|
||||||
jobApplications: [JobApplication!]!
|
|
||||||
jobApplication(id: ID!): JobApplication
|
|
||||||
}
|
|
||||||
|
|
||||||
extend type Mutation {
|
|
||||||
createJobApplication(input: CreateJobApplicationInput!): JobApplication!
|
|
||||||
updateJobApplication(id: ID!, input: UpdateJobApplicationInput!): JobApplication!
|
|
||||||
deleteJobApplication(id: ID!): Boolean!
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# 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!
|
||||||
|
createdAt: Time!
|
||||||
|
updatedAt: Time!
|
||||||
|
name: String!
|
||||||
|
# The page key it was saved from.
|
||||||
|
sourcePage: String!
|
||||||
|
boxCount: Int!
|
||||||
|
hasBackground: Boolean!
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreateLayoutInput {
|
||||||
|
name: String!
|
||||||
|
# The page key to save, as it is now.
|
||||||
|
page: String!
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdateLayoutInput {
|
||||||
|
name: String
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
# Newest first.
|
||||||
|
layouts: [Layout!]! @admin
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createLayout(input: CreateLayoutInput!): Layout! @admin
|
||||||
|
# Renames it; what a layout holds never changes after it is saved.
|
||||||
|
updateLayout(id: ID!, input: UpdateLayoutInput!): Layout! @admin
|
||||||
|
deleteLayout(id: ID!): Layout! @admin
|
||||||
|
# replace: true first saves the page as a layout, then swaps in this one.
|
||||||
|
applyLayout(id: ID!, page: String!, replace: Boolean!): [Box!]! @admin
|
||||||
|
}
|
||||||
@@ -3,7 +3,8 @@
|
|||||||
#
|
#
|
||||||
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
# Two gotchas: authorId is a per-connection counter from the chat hub, not a
|
||||||
# User id, and private messages are silently filtered out for non-admins
|
# User id, and private messages are silently filtered out for non-admins
|
||||||
# rather than causing an error.
|
# rather than causing an error — which is why the query has no @admin: the
|
||||||
|
# resolver makes that decision per row.
|
||||||
|
|
||||||
type Message {
|
type Message {
|
||||||
id: ID!
|
id: ID!
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
# Admin-created canvas pages. A page is just a slug and a title; its content
|
||||||
|
# is the boxes whose `page` is the slug (see box.graphql). The SPA serves it
|
||||||
|
# at /<slug> through its catch-all route, so a slug may not start with a path
|
||||||
|
# the site already uses — see validateSlug in page_helpers.go.
|
||||||
|
#
|
||||||
|
# adminOnly pages, and their boxes, are invisible to everyone but an admin:
|
||||||
|
# `page` answers null and `pages` leaves them out.
|
||||||
|
|
||||||
|
type Page {
|
||||||
|
id: ID!
|
||||||
|
createdAt: Time!
|
||||||
|
updatedAt: Time!
|
||||||
|
slug: String!
|
||||||
|
title: String!
|
||||||
|
adminOnly: Boolean!
|
||||||
|
}
|
||||||
|
|
||||||
|
input CreatePageInput {
|
||||||
|
slug: String!
|
||||||
|
title: String!
|
||||||
|
adminOnly: Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
input UpdatePageInput {
|
||||||
|
slug: String
|
||||||
|
title: String
|
||||||
|
adminOnly: Boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Query {
|
||||||
|
pages: [Page!]!
|
||||||
|
page(slug: String!): Page
|
||||||
|
}
|
||||||
|
|
||||||
|
extend type Mutation {
|
||||||
|
createPage(input: CreatePageInput!): Page! @admin
|
||||||
|
# Renaming a page moves its boxes with it.
|
||||||
|
updatePage(id: ID!, input: UpdatePageInput!): Page! @admin
|
||||||
|
# Deletes the page's boxes too.
|
||||||
|
deletePage(id: ID!): Page! @admin
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
# Places to go. Unlike most mutations these require only a signed-in user,
|
# Places to go. Unlike most mutations these require only a signed-in user
|
||||||
# not an admin, and there is no per-user ownership: the list is shared.
|
# (@signedIn), not an admin, and there is no per-user ownership: the list is
|
||||||
|
# shared. The query is guarded too — the list is not public.
|
||||||
|
|
||||||
type Place {
|
type Place {
|
||||||
id: ID!
|
id: ID!
|
||||||
@@ -38,11 +39,11 @@ input UpdatePlaceInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extend type Query {
|
extend type Query {
|
||||||
places: [Place!]!
|
places: [Place!]! @signedIn
|
||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createPlace(input: CreatePlaceInput!): Place!
|
createPlace(input: CreatePlaceInput!): Place! @signedIn
|
||||||
updatePlace(id: ID!, input: UpdatePlaceInput!): Place!
|
updatePlace(id: ID!, input: UpdatePlaceInput!): Place! @signedIn
|
||||||
deletePlace(id: ID!): Place!
|
deletePlace(id: ID!): Place! @signedIn
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -22,8 +22,10 @@ extend type Query {
|
|||||||
post(id: ID!): Post
|
post(id: ID!): Post
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# @admin is only the first half of the rule for updatePost and deletePost:
|
||||||
|
# the resolver also requires the caller to be the post's author.
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createPost(input: CreatePostInput!): Post!
|
createPost(input: CreatePostInput!): Post! @admin
|
||||||
updatePost(id: ID!, input: UpdatePostInput!): Post!
|
updatePost(id: ID!, input: UpdatePostInput!): Post! @admin
|
||||||
deletePost(id: ID!): Post!
|
deletePost(id: ID!): Post! @admin
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,20 +1,12 @@
|
|||||||
# Root of the GraphQL schema.
|
# Root types; each file extends Query and Mutation. Use # comments, not """
|
||||||
#
|
# (descriptions show up in introspection).
|
||||||
# Query and Mutation are declared here with no fields; every other file in this
|
|
||||||
# directory adds to them with `extend type Query` / `extend type Mutation`.
|
|
||||||
# That is what lets the schema be split one file per domain, matching the
|
|
||||||
# one-file-per-domain resolver layout (gqlgen.yml uses layout: follow-schema).
|
|
||||||
#
|
|
||||||
# Time is mapped to Go's time.Time by gqlgen's default scalar handling and is
|
|
||||||
# serialised as RFC 3339.
|
|
||||||
#
|
|
||||||
# These files are the source of truth: after editing one, run
|
|
||||||
# go run github.com/99designs/gqlgen generate
|
|
||||||
# from backend/ to regenerate graph/generated.go and graph/model/models_gen.go.
|
|
||||||
# Note that `#` comments like this one are invisible to clients; a `"""` block
|
|
||||||
# would become a schema description and show up in introspection.
|
|
||||||
|
|
||||||
scalar Time
|
scalar Time
|
||||||
|
|
||||||
|
# A field is public unless it has @admin or @signedIn (graph/directives.go).
|
||||||
|
# directives_test.go enforces this for mutations.
|
||||||
|
directive @admin on FIELD_DEFINITION
|
||||||
|
directive @signedIn on FIELD_DEFINITION
|
||||||
|
|
||||||
type Query
|
type Query
|
||||||
type Mutation
|
type Mutation
|
||||||
|
|||||||
@@ -36,6 +36,7 @@ extend type Query {
|
|||||||
spotifyRecent: [SpotifyRecentItem!]
|
spotifyRecent: [SpotifyRecentItem!]
|
||||||
# True only for an admin session while the backend lacks a Spotify client
|
# True only for an admin session while the backend lacks a Spotify client
|
||||||
# (OAuth never completed or the token was revoked), used by the Listening
|
# (OAuth never completed or the token was revoked), used by the Listening
|
||||||
# widget to offer a reconnect link. Everyone else gets false.
|
# widget to offer a reconnect link. Everyone else gets false — a soft
|
||||||
|
# check in the resolver, not @admin, so the home page query never errors.
|
||||||
spotifyNeedsReauth: Boolean!
|
spotifyNeedsReauth: Boolean!
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,17 @@ type User {
|
|||||||
updatedAt: Time!
|
updatedAt: Time!
|
||||||
username: String!
|
username: String!
|
||||||
admin: Boolean!
|
admin: Boolean!
|
||||||
|
# Keys of the gated services this user may use (see PermissionType). Admins
|
||||||
|
# pass every permission check whatever this holds.
|
||||||
|
permissions: [String!]!
|
||||||
|
}
|
||||||
|
|
||||||
|
# One grantable service, from services.PermissionTypes: `key` is what is
|
||||||
|
# stored and what Caddy gates on, `label` and `path` are for display.
|
||||||
|
type PermissionType {
|
||||||
|
key: String!
|
||||||
|
label: String!
|
||||||
|
path: String!
|
||||||
}
|
}
|
||||||
|
|
||||||
input CreateUserInput {
|
input CreateUserInput {
|
||||||
@@ -12,12 +23,17 @@ input CreateUserInput {
|
|||||||
}
|
}
|
||||||
|
|
||||||
extend type Query {
|
extend type Query {
|
||||||
users: [User!]!
|
users: [User!]! @admin
|
||||||
user(id: ID!): User
|
user(id: ID!): User @admin
|
||||||
|
# @signedIn rather than @admin: /account lists a non-admin's own services
|
||||||
|
# from it. The list itself is not a secret.
|
||||||
|
permissionTypes: [PermissionType!]! @signedIn
|
||||||
}
|
}
|
||||||
|
|
||||||
extend type Mutation {
|
extend type Mutation {
|
||||||
createUser(input: CreateUserInput!): User!
|
createUser(input: CreateUserInput!): User! @admin
|
||||||
deleteUser(id: ID!): User!
|
deleteUser(id: ID!): User! @admin
|
||||||
setUserAdmin(id: ID!, admin: Boolean!): User!
|
setUserAdmin(id: ID!, admin: Boolean!): User! @admin
|
||||||
|
# Replaces the user's whole permission list; unknown keys are rejected.
|
||||||
|
setUserPermissions(id: ID!, permissions: [String!]!): User! @admin
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,8 @@ package graph
|
|||||||
// This file is hand-written and is never regenerated by gqlgen — it is not
|
// This file is hand-written and is never regenerated by gqlgen — it is not
|
||||||
// named after a schema file, so `gqlgen generate` leaves it alone.
|
// named after a schema file, so `gqlgen generate` leaves it alone.
|
||||||
|
|
||||||
// ptrs copies a slice of values into a slice of pointers to those values.
|
// ptrs turns []T into []*T for gqlgen. Loading into []*T directly would
|
||||||
//
|
// change the SQL GORM emits.
|
||||||
// Every list query loads rows with Find(&xs) into a []T and then has to hand
|
|
||||||
// gqlgen a []*T, because the schema returns lists of nullable objects. Taking
|
|
||||||
// &xs[i] is safe: the slice is never appended to after this point, so the
|
|
||||||
// backing array cannot move and the pointers stay valid.
|
|
||||||
//
|
|
||||||
// Loading straight into a []*T would avoid the copy but changes the query
|
|
||||||
// GORM emits, so the copy is kept deliberately.
|
|
||||||
func ptrs[T any](xs []T) []*T {
|
func ptrs[T any](xs []T) []*T {
|
||||||
result := make([]*T, len(xs))
|
result := make([]*T, len(xs))
|
||||||
for i := range xs {
|
for i := range xs {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@@ -51,16 +51,14 @@ func (r *queryResolver) SpotifyRecent(ctx context.Context) ([]*model.SpotifyRece
|
|||||||
}
|
}
|
||||||
|
|
||||||
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
|
// SpotifyNeedsReauth is the resolver for the spotifyNeedsReauth field.
|
||||||
//
|
// False for non-admins.
|
||||||
// Admin-gated: false for everyone else, so this query leaks nothing. Admin is
|
|
||||||
// read from the access-token claims the AuthContextMiddleware resolved, not
|
|
||||||
// the database — the same trade-off AdminMiddleware makes (revocation waits
|
|
||||||
// for token expiry).
|
|
||||||
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
func (r *queryResolver) SpotifyNeedsReauth(ctx context.Context) (bool, error) {
|
||||||
if r.Store.SpotifyClient != nil {
|
if r.Store.SpotifyClient != nil {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A soft check, deliberately not @admin: the directive would turn this
|
||||||
|
// into an error on the public home page query.
|
||||||
if !IsAdminFromCtx(ctx) {
|
if !IsAdminFromCtx(ctx) {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,10 +5,6 @@ import (
|
|||||||
"github.com/zmb3/spotify/v2"
|
"github.com/zmb3/spotify/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Converters from the Spotify library's rich types to the deliberately narrow
|
|
||||||
// GraphQL types — the schema exposes only the handful of fields the home page
|
|
||||||
// renders.
|
|
||||||
|
|
||||||
// mapSpotifyImages keeps just the URLs of a set of album images.
|
// mapSpotifyImages keeps just the URLs of a set of album images.
|
||||||
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
func mapSpotifyImages(images []spotify.Image) []*model.SpotifyImage {
|
||||||
result := make([]*model.SpotifyImage, len(images))
|
result := make([]*model.SpotifyImage, len(images))
|
||||||
@@ -35,10 +31,7 @@ func mapSpotifyTrack(track *spotify.FullTrack) *model.SpotifyTrack {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// mapRecentItems converts recently played history entries.
|
// mapRecentItems converts recently played history entries.
|
||||||
//
|
// A RecentlyPlayedItem holds a SimpleTrack, so mapSpotifyTrack can't be reused.
|
||||||
// It rebuilds the track inline instead of calling mapSpotifyTrack because a
|
|
||||||
// RecentlyPlayedItem holds a SimpleTrack, not the FullTrack that function
|
|
||||||
// takes — the duplication is forced by the library's types.
|
|
||||||
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
func mapRecentItems(items []spotify.RecentlyPlayedItem) []*model.SpotifyRecentItem {
|
||||||
result := make([]*model.SpotifyRecentItem, len(items))
|
result := make([]*model.SpotifyRecentItem, len(items))
|
||||||
for i, item := range items {
|
for i, item := range items {
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|||||||
@@ -8,10 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// mapSteamGames converts Steam API games into the GraphQL shape.
|
// mapSteamGames converts Steam API games into the GraphQL shape.
|
||||||
//
|
// Header images follow a predictable CDN path, saving an API call per game.
|
||||||
// HeaderImageURL is synthesised rather than returned by the API: Steam's CDN
|
|
||||||
// serves every game's cover art at a predictable path keyed by app id, so
|
|
||||||
// building the URL here saves an extra API call per game.
|
|
||||||
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
func mapSteamGames(games []services.SteamRecentGame) []*model.SteamGame {
|
||||||
result := make([]*model.SteamGame, len(games))
|
result := make([]*model.SteamGame, len(games))
|
||||||
for i, g := range games {
|
for i, g := range games {
|
||||||
|
|||||||
@@ -3,25 +3,21 @@ package graph
|
|||||||
// This file will be automatically regenerated based on the schema, any resolver
|
// This file will be automatically regenerated based on the schema, any resolver
|
||||||
// implementations
|
// implementations
|
||||||
// will be copied through when generating and any unknown code will be moved to the end.
|
// will be copied through when generating and any unknown code will be moved to the end.
|
||||||
// Code generated by github.com/99designs/gqlgen version v0.17.95
|
// Code generated by github.com/99designs/gqlgen version v0.17.98
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
|
||||||
"adam-french.co.uk/backend/graph/model"
|
"adam-french.co.uk/backend/graph/model"
|
||||||
"adam-french.co.uk/backend/models"
|
"adam-french.co.uk/backend/models"
|
||||||
|
"adam-french.co.uk/backend/services"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CreateUser is the resolver for the createUser field.
|
// CreateUser is the resolver for the createUser field.
|
||||||
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUserInput) (*models.User, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Only an existing admin can create accounts — there is no public
|
|
||||||
// sign-up. New users are created non-admin; setUserAdmin promotes them.
|
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -37,10 +33,6 @@ func (r *mutationResolver) CreateUser(ctx context.Context, input model.CreateUse
|
|||||||
|
|
||||||
// DeleteUser is the resolver for the deleteUser field.
|
// DeleteUser is the resolver for the deleteUser field.
|
||||||
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
var user models.User
|
var user models.User
|
||||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||||
return nil, fmt.Errorf("user not found")
|
return nil, fmt.Errorf("user not found")
|
||||||
@@ -55,17 +47,12 @@ func (r *mutationResolver) DeleteUser(ctx context.Context, id int) (*models.User
|
|||||||
|
|
||||||
// SetUserAdmin is the resolver for the setUserAdmin field.
|
// SetUserAdmin is the resolver for the setUserAdmin field.
|
||||||
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool) (*models.User, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
|
|
||||||
callerID, ok := UserIDFromCtx(ctx)
|
callerID, ok := UserIDFromCtx(ctx)
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("unauthorized")
|
return nil, fmt.Errorf("unauthorized")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Guards against the last admin demoting themselves and locking everyone
|
// Stops the last admin locking everyone out.
|
||||||
// out of the admin UI.
|
|
||||||
if uint(id) == callerID {
|
if uint(id) == callerID {
|
||||||
return nil, fmt.Errorf("cannot change your own admin status")
|
return nil, fmt.Errorf("cannot change your own admin status")
|
||||||
}
|
}
|
||||||
@@ -83,11 +70,40 @@ func (r *mutationResolver) SetUserAdmin(ctx context.Context, id int, admin bool)
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetUserPermissions is the resolver for the setUserPermissions field.
|
||||||
|
func (r *mutationResolver) SetUserPermissions(ctx context.Context, id int, permissions []string) (*models.User, error) {
|
||||||
|
// Full replace. Unknown keys are refused so a stale UI can't silently
|
||||||
|
// save less than it showed.
|
||||||
|
want := map[string]bool{}
|
||||||
|
for _, key := range permissions {
|
||||||
|
if !services.ValidPermission(key) {
|
||||||
|
return nil, fmt.Errorf("unknown permission %q", key)
|
||||||
|
}
|
||||||
|
want[key] = true
|
||||||
|
}
|
||||||
|
granted := []string{}
|
||||||
|
for _, p := range services.PermissionTypes {
|
||||||
|
if want[p.Key] {
|
||||||
|
granted = append(granted, p.Key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var user models.User
|
||||||
|
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("user not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
// No token bump: the gate reads this column on every request.
|
||||||
|
user.Permissions = granted
|
||||||
|
if err := r.Store.DB.Save(&user).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &user, nil
|
||||||
|
}
|
||||||
|
|
||||||
// Users is the resolver for the users field.
|
// Users is the resolver for the users field.
|
||||||
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
var users []models.User
|
var users []models.User
|
||||||
if err := r.Store.DB.Find(&users).Error; err != nil {
|
if err := r.Store.DB.Find(&users).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -97,9 +113,6 @@ func (r *queryResolver) Users(ctx context.Context) ([]*models.User, error) {
|
|||||||
|
|
||||||
// User is the resolver for the user field.
|
// User is the resolver for the user field.
|
||||||
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error) {
|
||||||
if !IsAdminFromCtx(ctx) {
|
|
||||||
return nil, fmt.Errorf("admin access required")
|
|
||||||
}
|
|
||||||
var user models.User
|
var user models.User
|
||||||
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
if err := r.Store.DB.First(&user, id).Error; err != nil {
|
||||||
return nil, fmt.Errorf("user not found")
|
return nil, fmt.Errorf("user not found")
|
||||||
@@ -107,12 +120,7 @@ func (r *queryResolver) User(ctx context.Context, id int) (*models.User, error)
|
|||||||
return &user, nil
|
return &user, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ID is the resolver for the id field.
|
// PermissionTypes is the resolver for the permissionTypes field.
|
||||||
func (r *userResolver) ID(ctx context.Context, obj *models.User) (int, error) {
|
func (r *queryResolver) PermissionTypes(ctx context.Context) ([]*services.PermissionType, error) {
|
||||||
return int(obj.ID), nil
|
return ptrs(slices.Clone(services.PermissionTypes)), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// User returns UserResolver implementation.
|
|
||||||
func (r *Resolver) User() UserResolver { return &userResolver{r} }
|
|
||||||
|
|
||||||
type userResolver struct{ *Resolver }
|
|
||||||
|
|||||||
@@ -1,93 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// This file backs the admin diagnostics panel's log tail. It is an admin-only
|
|
||||||
// REST endpoint rather than GraphQL because it reads the filesystem — outside
|
|
||||||
// the data model the GraphQL schema describes. The configuration report that
|
|
||||||
// used to live here is now the Environment tab (handle_env.go).
|
|
||||||
|
|
||||||
// logTailBytes and logTailLines bound how much of the log file one request
|
|
||||||
// moves: 256 KiB is beyond any useful screen at log-ish line lengths, and is
|
|
||||||
// cheap even on the Pi.
|
|
||||||
const (
|
|
||||||
logTailBytes = 256 << 10
|
|
||||||
logTailLines = 500
|
|
||||||
)
|
|
||||||
|
|
||||||
// Logs backs GET /admin/logs. It returns the tail of the backend's own log
|
|
||||||
// file (go.log — Gin traffic plus application log lines), which lives on the
|
|
||||||
// bind-mounted ./logs volume.
|
|
||||||
//
|
|
||||||
// Why tail and not offer a range: the panel wants "what happened recently",
|
|
||||||
// and the file can grow unboundedly between rotations, so anything else
|
|
||||||
// invites reading the whole thing into memory.
|
|
||||||
func (store *Store) Logs(ctx *gin.Context) {
|
|
||||||
lines, size, err := tailLogFile(logPath)
|
|
||||||
if err != nil {
|
|
||||||
// The mount being absent is a deployment problem worth surfacing
|
|
||||||
// distinctly from "log file empty".
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "log unavailable: " + err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"lines": lines, "total_bytes": size})
|
|
||||||
}
|
|
||||||
|
|
||||||
// logPath matches the file main.go opens for gin.DefaultWriter.
|
|
||||||
const logPath = "/backend/logs/go.log"
|
|
||||||
|
|
||||||
// tailLogFile returns the last logTailLines lines of a file, reading at most
|
|
||||||
// logTailBytes from the end. Split out from the handler so the offset and
|
|
||||||
// partial-line rules are testable without a filesystem mount.
|
|
||||||
func tailLogFile(path string) ([]string, int64, error) {
|
|
||||||
f, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
defer f.Close()
|
|
||||||
|
|
||||||
info, err := f.Stat()
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read from near the end rather than head-to-toe so the read stays
|
|
||||||
// constant-size regardless of how old the file is.
|
|
||||||
start := int64(0)
|
|
||||||
if info.Size() > logTailBytes {
|
|
||||||
start = info.Size() - logTailBytes
|
|
||||||
}
|
|
||||||
buf := make([]byte, info.Size()-start)
|
|
||||||
if len(buf) > 0 {
|
|
||||||
if _, err := f.ReadAt(buf, start); err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Starting mid-file almost certainly lands mid-line; drop that fragment
|
|
||||||
// so the panel never renders a truncated first entry.
|
|
||||||
text := string(buf)
|
|
||||||
if start > 0 {
|
|
||||||
if i := strings.IndexByte(text, '\n'); i >= 0 {
|
|
||||||
text = text[i+1:]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
text = strings.TrimRight(text, "\n")
|
|
||||||
if text == "" {
|
|
||||||
return []string{}, info.Size(), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
lines := strings.Split(text, "\n")
|
|
||||||
if len(lines) > logTailLines {
|
|
||||||
lines = lines[len(lines)-logTailLines:]
|
|
||||||
}
|
|
||||||
return lines, info.Size(), nil
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// tailLogFile's rules that are easy to get wrong: the line cap, and dropping
|
|
||||||
// the partial first line when the read started mid-file.
|
|
||||||
|
|
||||||
func writeLog(t *testing.T, content string) string {
|
|
||||||
t.Helper()
|
|
||||||
path := filepath.Join(t.TempDir(), "go.log")
|
|
||||||
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
|
|
||||||
t.Fatalf("writing fixture: %v", err)
|
|
||||||
}
|
|
||||||
return path
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTailLogFileCapsLines(t *testing.T) {
|
|
||||||
var b strings.Builder
|
|
||||||
for range logTailLines + 50 {
|
|
||||||
b.WriteString("line\n")
|
|
||||||
}
|
|
||||||
lines, _, err := tailLogFile(writeLog(t, b.String()))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("tailLogFile: %v", err)
|
|
||||||
}
|
|
||||||
if len(lines) != logTailLines {
|
|
||||||
t.Fatalf("got %d lines, want the cap of %d", len(lines), logTailLines)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTailLogFileDropsPartialFirstLine(t *testing.T) {
|
|
||||||
// A file larger than the byte window: the read starts mid-file, so the
|
|
||||||
// first line it sees is a fragment and must be discarded.
|
|
||||||
filler := strings.Repeat("x", 100) + "\n"
|
|
||||||
var b strings.Builder
|
|
||||||
for b.Len() < logTailBytes+len(filler) {
|
|
||||||
b.WriteString(filler)
|
|
||||||
}
|
|
||||||
b.WriteString("FINAL\n")
|
|
||||||
|
|
||||||
lines, _, err := tailLogFile(writeLog(t, b.String()))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("tailLogFile: %v", err)
|
|
||||||
}
|
|
||||||
if len(lines) == 0 {
|
|
||||||
t.Fatal("expected some lines")
|
|
||||||
}
|
|
||||||
if lines[len(lines)-1] != "FINAL" {
|
|
||||||
t.Fatalf("last line = %q, want FINAL", lines[len(lines)-1])
|
|
||||||
}
|
|
||||||
// Every surviving line must be whole, i.e. a full filler line.
|
|
||||||
if got := lines[0]; got != strings.TrimSuffix(filler, "\n") {
|
|
||||||
t.Fatalf("first line = %q, want a complete filler line", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTailLogFileEmpty(t *testing.T) {
|
|
||||||
lines, size, err := tailLogFile(writeLog(t, ""))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("tailLogFile: %v", err)
|
|
||||||
}
|
|
||||||
if len(lines) != 0 || size != 0 {
|
|
||||||
t.Fatalf("got %d lines / %d bytes, want 0 / 0", len(lines), size)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTailLogFileMissing(t *testing.T) {
|
|
||||||
if _, _, err := tailLogFile(filepath.Join(t.TempDir(), "absent.log")); err == nil {
|
|
||||||
t.Fatal("expected an error for a missing log file")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+72
-129
@@ -12,62 +12,36 @@ import (
|
|||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
// This file holds the REST authentication endpoints and the Gin middleware
|
// REST auth endpoints and middleware. GraphQL's login/logout/refresh live in
|
||||||
// that guards the other REST routes. GraphQL has its own parallel
|
// graph/auth.resolvers.go; both mint cookies through services.Auth.
|
||||||
// implementation of login/logout/refresh in graph/auth.resolvers.go; both
|
|
||||||
// mint the same cookies through services.Auth.
|
|
||||||
//
|
|
||||||
// Cookie model: `access_token` is short-lived and carries id + admin, so most
|
|
||||||
// requests authorise without a database hit; `refresh_token` carries only the
|
|
||||||
// id and is exchanged for a fresh pair. Both are set HttpOnly and Secure, so
|
|
||||||
// JavaScript cannot read them and the browser attaches them automatically.
|
|
||||||
|
|
||||||
// UserCredentials is the JSON body of POST /auth/login. The binding tags make
|
|
||||||
// Gin reject a request missing either field.
|
|
||||||
type UserCredentials struct {
|
type UserCredentials struct {
|
||||||
Username string `json:"username" binding:"required"`
|
Username string `json:"username" binding:"required"`
|
||||||
Password string `json:"password" binding:"required"`
|
Password string `json:"password" binding:"required"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// AuthMiddlewear requires a valid access token on a REST route and stashes
|
// AuthMiddleware requires a valid, unrevoked access token. It does not fall
|
||||||
// the claims for AdminMiddleware to read.
|
// back to the refresh token: the client refreshes and retries on 401.
|
||||||
//
|
func (store *Store) AuthMiddleware(ctx *gin.Context) {
|
||||||
// (The name is misspelled but it is exported and referenced from main.go, so
|
|
||||||
// it is left alone rather than renamed.)
|
|
||||||
//
|
|
||||||
// It deliberately does NOT fall back to the refresh token: an expired access
|
|
||||||
// token yields a 401 and the front end is expected to call /auth/refresh and
|
|
||||||
// retry. A token whose version has been revoked is also a 401.
|
|
||||||
func (store *Store) AuthMiddlewear(ctx *gin.Context) {
|
|
||||||
access_token, err := ctx.Cookie("access_token")
|
access_token, err := ctx.Cookie("access_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
|
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validated against the database, not just cryptographically: that is
|
|
||||||
// what makes a logged-out or password-changed token stop working here
|
|
||||||
// rather than lingering until it expires.
|
|
||||||
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
|
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, access_token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
|
ctx.AbortWithStatusJSON(401, gin.H{"error": "unauthorized"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stored under a plain string key in the *Gin* context. This is a
|
// Gin context key; graph/context.go uses its own, separate mechanism.
|
||||||
// different mechanism from graph/context.go, which puts the same claims
|
|
||||||
// into the standard library request context under an unexported typed
|
|
||||||
// key; the two do not see each other's values.
|
|
||||||
ctx.Set("userClaims", claims)
|
ctx.Set("userClaims", claims)
|
||||||
ctx.Next()
|
ctx.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// AdminMiddleware requires the access token to carry admin=true. It must be
|
// AdminMiddleware must follow AuthMiddleware. Admin comes from the token, so
|
||||||
// chained after AuthMiddlewear, which is what populates "userClaims"; on its
|
// a revoked flag applies once the access token expires.
|
||||||
// own it always rejects.
|
|
||||||
//
|
|
||||||
// Admin is read from the token, not the database, so revoking someone's admin
|
|
||||||
// flag only takes effect once their current access token expires.
|
|
||||||
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 {
|
||||||
@@ -81,8 +55,7 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// A token minted before the admin claim existed simply has no "admin"
|
// Tokens minted before the admin claim have none: not an admin.
|
||||||
// key, so a failed type assertion is treated as "not an admin".
|
|
||||||
admin, ok := (*mapClaims)["admin"].(bool)
|
admin, ok := (*mapClaims)["admin"].(bool)
|
||||||
if !ok || !admin {
|
if !ok || !admin {
|
||||||
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
ctx.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
||||||
@@ -92,65 +65,71 @@ func (store *Store) AdminMiddleware(ctx *gin.Context) {
|
|||||||
ctx.Next()
|
ctx.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
// ValidateAdmin backs GET /auth/validate-admin, which the front end calls to
|
// ValidateAdmin answers 200/403/401 with no body, for the SPA, Caddy's admin
|
||||||
// decide whether to show admin UI. It answers with a bare status code and no
|
// gate and the jobs container. It falls back to the refresh token and may
|
||||||
// body: 200 admin, 403 authenticated but not admin, 401 not authenticated.
|
// mint new cookies, so a returning admin needn't log in again.
|
||||||
//
|
|
||||||
// Unlike AdminMiddleware it falls back to the refresh token, and will mint a
|
|
||||||
// new cookie pair as a side effect, so a returning admin is recognised
|
|
||||||
// without a visible re-login.
|
|
||||||
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
func (store *Store) ValidateAdmin(ctx *gin.Context) {
|
||||||
accessToken, err := ctx.Cookie("access_token")
|
store.validateSession(ctx, func(user *models.User, claims *jwt.MapClaims) bool {
|
||||||
if err != nil {
|
// The refresh path has no admin claim, so it reads the row.
|
||||||
// No access token — try refreshing
|
if claims == nil {
|
||||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
return user.Admin
|
||||||
ctx.Status(http.StatusUnauthorized)
|
|
||||||
}
|
}
|
||||||
return
|
admin, ok := (*claims)["admin"].(bool)
|
||||||
}
|
return ok && admin
|
||||||
|
})
|
||||||
_, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
|
|
||||||
if err != nil {
|
|
||||||
// Expired, invalid or revoked access token — try refreshing
|
|
||||||
if !store.tryRefreshAndValidateAdmin(ctx) {
|
|
||||||
ctx.Status(http.StatusUnauthorized)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
admin, ok := (*claims)["admin"].(bool)
|
|
||||||
if !ok || !admin {
|
|
||||||
ctx.Status(http.StatusForbidden)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.Status(http.StatusOK)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// tryRefreshAndValidateAdmin re-authenticates from the refresh token.
|
// ValidatePermission backs Caddy's permission gate, like ValidateAdmin but
|
||||||
//
|
// reading the user row. An unknown key is 404, so a typo in a Caddy route
|
||||||
// The bool does not mean "is an admin" — it means "this function already
|
// fails visibly rather than looking like a missing grant.
|
||||||
// wrote the response". It returns true both for a successful admin refresh
|
func (store *Store) ValidatePermission(ctx *gin.Context) {
|
||||||
// (200, new cookies set) and for a valid non-admin (403), and false only when
|
key := ctx.Param("permission")
|
||||||
// it could not decide, leaving the caller to send 401. Getting this backwards
|
if !services.ValidPermission(key) {
|
||||||
// would send two status codes for one request.
|
ctx.Status(http.StatusNotFound)
|
||||||
//
|
return
|
||||||
// Admin status is re-read from the database here, which is what makes the
|
}
|
||||||
// refresh path pick up a revoked admin flag.
|
store.validateSession(ctx, func(user *models.User, _ *jwt.MapClaims) bool {
|
||||||
func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
return services.HasPermission(user, key)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// validateSession identifies the caller by access token, else refresh token
|
||||||
|
// (allow then gets nil claims), and answers 200/403/401. On 200 the username
|
||||||
|
// goes in X-Auth-User for Caddy to pass upstream.
|
||||||
|
func (store *Store) validateSession(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) {
|
||||||
|
accessToken, err := ctx.Cookie("access_token")
|
||||||
|
if err == nil {
|
||||||
|
user, claims, err := store.Auth.AuthenticateTokenWithClaims(store.DB, accessToken)
|
||||||
|
if err == nil {
|
||||||
|
if !allow(user, claims) {
|
||||||
|
ctx.Status(http.StatusForbidden)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ctx.Header("X-Auth-User", user.Username)
|
||||||
|
ctx.Status(http.StatusOK)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !store.tryRefreshAndValidate(ctx, allow) {
|
||||||
|
ctx.Status(http.StatusUnauthorized)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRefreshAndValidate returns whether it wrote the response (200 or 403),
|
||||||
|
// not whether access is allowed. On false the caller sends 401.
|
||||||
|
func (store *Store) tryRefreshAndValidate(ctx *gin.Context, allow func(*models.User, *jwt.MapClaims) bool) bool {
|
||||||
refreshToken, err := ctx.Cookie("refresh_token")
|
refreshToken, err := ctx.Cookie("refresh_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Any failure at all (bad token, unknown user, revoked version) is
|
|
||||||
// "cannot decide" here, exactly as before: the caller sends 401.
|
|
||||||
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if !user.Admin {
|
if !allow(user, nil) {
|
||||||
ctx.Status(http.StatusForbidden)
|
ctx.Status(http.StatusForbidden)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -162,21 +141,17 @@ func (store *Store) tryRefreshAndValidateAdmin(ctx *gin.Context) bool {
|
|||||||
|
|
||||||
store.setAuthCookies(ctx, tokens)
|
store.setAuthCookies(ctx, tokens)
|
||||||
|
|
||||||
|
ctx.Header("X-Auth-User", user.Username)
|
||||||
ctx.Status(http.StatusOK)
|
ctx.Status(http.StatusOK)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// setAuthCookies writes the access/refresh cookie pair. The cookie
|
|
||||||
// attributes live in services.SetAuthCookies so that REST and GraphQL cannot
|
|
||||||
// disagree about them; this method is just the Store-shaped spelling of it.
|
|
||||||
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
|
func (store *Store) setAuthCookies(ctx *gin.Context, tokens *services.Tokens) {
|
||||||
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
|
services.SetAuthCookies(ctx, store.Auth.Config, tokens)
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckToken backs GET /auth/check: it returns the current user for a valid
|
// CheckToken returns the current user. A valid token for a deleted user gets
|
||||||
// access token, or 401. If the token is valid but the user no longer exists
|
// 404 and cleared cookies.
|
||||||
// it answers 404 and clears the cookies, so the browser stops presenting a
|
|
||||||
// token for a deleted account.
|
|
||||||
func (store *Store) CheckToken(ctx *gin.Context) {
|
func (store *Store) CheckToken(ctx *gin.Context) {
|
||||||
access_token, err := ctx.Cookie("access_token")
|
access_token, err := ctx.Cookie("access_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -184,11 +159,6 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Status codes here are unchanged from the hand-rolled version: a bad
|
|
||||||
// token or bad claims are both 401, and only a missing user is 404 with
|
|
||||||
// the cookies cleared. A revoked (out-of-date version) token joins the
|
|
||||||
// 401 case, since from the client's point of view it is simply no longer
|
|
||||||
// a valid token.
|
|
||||||
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
|
user, err := store.Auth.AuthenticateToken(store.DB, access_token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, services.ErrUserNotFound) {
|
if errors.Is(err, services.ErrUserNotFound) {
|
||||||
@@ -204,11 +174,8 @@ func (store *Store) CheckToken(ctx *gin.Context) {
|
|||||||
ctx.JSON(http.StatusOK, user)
|
ctx.JSON(http.StatusOK, user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// RefreshToken backs POST /auth/refresh: it exchanges a valid refresh token
|
// RefreshToken exchanges the refresh token for a new pair. It is not rotated,
|
||||||
// for a new cookie pair and returns the user.
|
// but logout and password changes revoke it via the token version.
|
||||||
//
|
|
||||||
// The old refresh token is not rotated, but it does die when the user logs out
|
|
||||||
// or changes their password, because those bump the token version this checks.
|
|
||||||
func (store *Store) RefreshToken(ctx *gin.Context) {
|
func (store *Store) RefreshToken(ctx *gin.Context) {
|
||||||
refreshToken, err := ctx.Cookie("refresh_token")
|
refreshToken, err := ctx.Cookie("refresh_token")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -216,11 +183,6 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// The three outcomes below preserve the original status codes exactly:
|
|
||||||
// an unusable token is 401, unreadable claims are 500, and a token for a
|
|
||||||
// user that no longer exists is 404 with the cookies cleared. A revoked
|
|
||||||
// token is treated as an unusable one (401) — the client's correct
|
|
||||||
// response is to log in again.
|
|
||||||
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
user, err := store.Auth.AuthenticateToken(store.DB, refreshToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
switch {
|
switch {
|
||||||
@@ -248,13 +210,9 @@ func (store *Store) RefreshToken(ctx *gin.Context) {
|
|||||||
ctx.JSON(http.StatusAccepted, user)
|
ctx.JSON(http.StatusAccepted, user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Login backs POST /auth/login. The user object it returns omits the password
|
|
||||||
// because models.User tags that field `json:"-"`.
|
|
||||||
func (store *Store) Login(ctx *gin.Context) {
|
func (store *Store) Login(ctx *gin.Context) {
|
||||||
// Per-IP limit (5/min) on top of nginx's own login rate limit.
|
// On top of Caddy's limit. ClientIP is trustworthy because main.go pins
|
||||||
// ctx.ClientIP is only trustworthy because main.go pins the trusted
|
// the trusted proxy range.
|
||||||
// proxy range, so the X-Forwarded-For header cannot be spoofed by a
|
|
||||||
// client talking through nginx.
|
|
||||||
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
if !store.LoginLimiter.Allow(ctx.ClientIP()) {
|
||||||
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
ctx.JSON(http.StatusTooManyRequests, gin.H{"error": "too many login attempts, please try again later"})
|
||||||
return
|
return
|
||||||
@@ -266,9 +224,7 @@ func (store *Store) Login(ctx *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unknown user and wrong password return the identical message, so the
|
// Same message for unknown user and wrong password.
|
||||||
// response cannot be used to enumerate usernames. (The timing does
|
|
||||||
// differ, since only the second path runs bcrypt.)
|
|
||||||
user := models.User{}
|
user := models.User{}
|
||||||
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
if err := store.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
|
||||||
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
|
ctx.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
|
||||||
@@ -292,13 +248,8 @@ func (store *Store) Login(ctx *gin.Context) {
|
|||||||
ctx.JSON(http.StatusAccepted, user)
|
ctx.JSON(http.StatusAccepted, user)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Logout backs POST /auth/logout. As well as clearing the browser's cookies
|
// Logout clears the cookies and bumps the token version, revoking every copy
|
||||||
// it bumps the user's token version, so the tokens it just discarded — and
|
// of the tokens. Always 200.
|
||||||
// any copy taken beforehand — stop being accepted immediately.
|
|
||||||
//
|
|
||||||
// It always answers 200: identifying the caller is best effort (the cookies
|
|
||||||
// may already be gone or expired), and a client that cannot be identified has
|
|
||||||
// nothing to revoke anyway.
|
|
||||||
func (store *Store) Logout(ctx *gin.Context) {
|
func (store *Store) Logout(ctx *gin.Context) {
|
||||||
store.revokeCallerTokens(ctx)
|
store.revokeCallerTokens(ctx)
|
||||||
store.removeCookies(ctx)
|
store.removeCookies(ctx)
|
||||||
@@ -306,12 +257,8 @@ func (store *Store) Logout(ctx *gin.Context) {
|
|||||||
ctx.Status(http.StatusOK)
|
ctx.Status(http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
// revokeCallerTokens bumps the token version of whoever made this request,
|
// revokeCallerTokens verifies the token before bumping, or a forged cookie
|
||||||
// identified from the access token or, failing that, the refresh token.
|
// could revoke any user's sessions.
|
||||||
//
|
|
||||||
// It deliberately verifies the token rather than just reading the id out of
|
|
||||||
// it: without that, anyone could bump an arbitrary user's version by posting a
|
|
||||||
// forged cookie, which is a denial-of-service on that account's sessions.
|
|
||||||
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
|
func (store *Store) revokeCallerTokens(ctx *gin.Context) {
|
||||||
for _, name := range []string{"access_token", "refresh_token"} {
|
for _, name := range []string{"access_token", "refresh_token"} {
|
||||||
token, err := ctx.Cookie(name)
|
token, err := ctx.Cookie(name)
|
||||||
@@ -323,16 +270,12 @@ func (store *Store) revokeCallerTokens(ctx *gin.Context) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
|
if err := services.BumpTokenVersion(store.DB, user.ID); err != nil {
|
||||||
// Logged rather than returned: the cookies are still cleared, but
|
|
||||||
// this means the logout did not actually revoke anything.
|
|
||||||
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
|
log.Printf("logout: failed to revoke tokens for user %d: %v", user.ID, err)
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// removeCookies expires both auth cookies; see services.ClearAuthCookies for
|
|
||||||
// why the attributes have to match those used when setting them.
|
|
||||||
func (store *Store) removeCookies(ctx *gin.Context) {
|
func (store *Store) removeCookies(ctx *gin.Context) {
|
||||||
services.ClearAuthCookies(ctx, store.Auth.Config)
|
services.ClearAuthCookies(ctx, store.Auth.Config)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// REST endpoints for the job-application email pipeline: a manual
|
|
||||||
// admin-triggered sync, and the OAuth redirect target (which has to be REST
|
|
||||||
// because Microsoft redirects a browser to it).
|
|
||||||
|
|
||||||
// TriggerEmailSync backs the admin-only POST /email/sync and runs one sync
|
|
||||||
// synchronously, so the response reflects the result. If the scheduler is
|
|
||||||
// mid-sync the service refuses via TryLock and this returns 500.
|
|
||||||
func (store *Store) TriggerEmailSync(ctx *gin.Context) {
|
|
||||||
// A nil HTTPClient is the service's readiness flag — see
|
|
||||||
// services.EmailSyncService.
|
|
||||||
if store.EmailSync == nil || store.EmailSync.HTTPClient == nil {
|
|
||||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured or not authenticated"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
err := store.EmailSync.SyncEmails(ctx.Request.Context())
|
|
||||||
if err != nil {
|
|
||||||
log.Printf("[EmailSync] Manual sync error: %v", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "sync failed", "details": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"message": "sync completed"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// CompleteEmailAuth handles Microsoft's OAuth redirect to
|
|
||||||
// GET /email/callback and stores the resulting token.
|
|
||||||
//
|
|
||||||
// The route is unauthenticated (Microsoft's redirect carries no site cookie),
|
|
||||||
// which is safe only because the code is worthless without the app's client
|
|
||||||
// secret. Note that completing auth here does not start the scheduler, which
|
|
||||||
// only checks readiness at start-up — a restart is needed for that.
|
|
||||||
func (store *Store) CompleteEmailAuth(ctx *gin.Context) {
|
|
||||||
if store.EmailSync == nil {
|
|
||||||
ctx.JSON(http.StatusServiceUnavailable, gin.H{"error": "email sync not configured"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
code := ctx.Query("code")
|
|
||||||
if code == "" {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "missing authorization code"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := store.EmailSync.CompleteAuth(ctx.Request.Context(), code); err != nil {
|
|
||||||
log.Printf("[EmailSync] Auth completion error: %v", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "authentication failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"message": "email authentication successful"})
|
|
||||||
}
|
|
||||||
@@ -1,133 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"errors"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/services"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// This file backs the admin panel's Environment tab: a report on every
|
|
||||||
// variable in .env, and a way to change the ones that are safe to change.
|
|
||||||
//
|
|
||||||
// The handlers never read or write .env. State is this process's own
|
|
||||||
// environment, and a change is a request left for the host to apply (see
|
|
||||||
// services.EnvManager). REST rather than GraphQL for the same reason as the
|
|
||||||
// rest of the admin endpoints: this is process and host state, not the data
|
|
||||||
// model the schema describes.
|
|
||||||
|
|
||||||
// envSecretHintMinLen is the shortest secret that gets its last four
|
|
||||||
// characters shown. Below it, four characters is too much of the value.
|
|
||||||
const envSecretHintMinLen = 12
|
|
||||||
|
|
||||||
type envVarView struct {
|
|
||||||
services.EnvVar
|
|
||||||
Secret bool `json:"secret"`
|
|
||||||
Set bool `json:"set"`
|
|
||||||
// Value is sent only for non-secret variables; Hint (the last four
|
|
||||||
// characters) is all a secret ever reveals.
|
|
||||||
Value string `json:"value,omitempty"`
|
|
||||||
Hint string `json:"hint,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type envGroupView struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Vars []envVarView `json:"vars"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetEnv backs GET /admin/env: every registry variable grouped for display,
|
|
||||||
// plus the state of the latest change.
|
|
||||||
//
|
|
||||||
// Values are what this process was started with, not what .env holds now —
|
|
||||||
// the two differ between a save and the recreate that follows it, which is
|
|
||||||
// what the status's pending list is for.
|
|
||||||
func (store *Store) GetEnv(ctx *gin.Context) {
|
|
||||||
var groups []envGroupView
|
|
||||||
index := map[string]int{}
|
|
||||||
for _, v := range store.Env.Vars() {
|
|
||||||
value := os.Getenv(v.Name)
|
|
||||||
view := envVarView{EnvVar: v, Secret: v.Secret(), Set: strings.TrimSpace(value) != ""}
|
|
||||||
switch {
|
|
||||||
case !view.Set:
|
|
||||||
case !view.Secret:
|
|
||||||
view.Value = value
|
|
||||||
case len(value) >= envSecretHintMinLen:
|
|
||||||
view.Hint = value[len(value)-4:]
|
|
||||||
}
|
|
||||||
|
|
||||||
i, seen := index[v.Group]
|
|
||||||
if !seen {
|
|
||||||
i = len(groups)
|
|
||||||
index[v.Group] = i
|
|
||||||
groups = append(groups, envGroupView{Name: v.Group})
|
|
||||||
}
|
|
||||||
groups[i].Vars = append(groups[i].Vars, view)
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"groups": groups, "status": store.Env.Status()})
|
|
||||||
}
|
|
||||||
|
|
||||||
type updateEnvRequest struct {
|
|
||||||
// Set maps a variable to its new value; "" clears it.
|
|
||||||
Set map[string]string `json:"set"`
|
|
||||||
// Generate names "generated" variables to mint a random value for.
|
|
||||||
Generate []string `json:"generate"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// UpdateEnv backs PUT /admin/env. It queues the change for the host and
|
|
||||||
// returns straight away; the panel follows progress on GET /admin/env/status,
|
|
||||||
// through the backend's own restart.
|
|
||||||
//
|
|
||||||
// The response is the only time a generated value is sent anywhere.
|
|
||||||
func (store *Store) UpdateEnv(ctx *gin.Context) {
|
|
||||||
var body updateEnvRequest
|
|
||||||
if err := ctx.ShouldBindJSON(&body); err != nil {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
generated, recreates, err := store.Env.Submit(body.Set, body.Generate)
|
|
||||||
if errors.Is(err, services.ErrEnvApplying) {
|
|
||||||
ctx.JSON(http.StatusConflict, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
// Validation messages name the variable, never the value.
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
names := make([]string, 0, len(body.Set)+len(body.Generate))
|
|
||||||
for name := range body.Set {
|
|
||||||
names = append(names, name)
|
|
||||||
}
|
|
||||||
names = append(names, body.Generate...)
|
|
||||||
log.Printf("[Env] change queued for %s", strings.Join(names, ", "))
|
|
||||||
|
|
||||||
ctx.Header("Cache-Control", "no-store")
|
|
||||||
ctx.JSON(http.StatusAccepted, gin.H{
|
|
||||||
"generated": generated,
|
|
||||||
"services": recreates,
|
|
||||||
"status": store.Env.Status(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetEnvStatus backs GET /admin/env/status.
|
|
||||||
func (store *Store) GetEnvStatus(ctx *gin.Context) {
|
|
||||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
|
||||||
}
|
|
||||||
|
|
||||||
// CancelEnv backs DELETE /admin/env/pending: withdraw a request nothing on
|
|
||||||
// the host has picked up, so new secrets do not sit in the shared directory
|
|
||||||
// waiting for a watcher that is not there.
|
|
||||||
func (store *Store) CancelEnv(ctx *gin.Context) {
|
|
||||||
if err := store.Env.Cancel(); err != nil {
|
|
||||||
log.Println("Cancelling env request failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to cancel the request"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, store.Env.Status())
|
|
||||||
}
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/services"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func envRouter(t *testing.T) (*gin.Engine, string) {
|
|
||||||
t.Helper()
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
dir := t.TempDir()
|
|
||||||
env, err := services.NewEnvManager(dir)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("NewEnvManager: %v", err)
|
|
||||||
}
|
|
||||||
store := &Store{Env: env}
|
|
||||||
r := gin.New()
|
|
||||||
r.GET("/admin/env", store.GetEnv)
|
|
||||||
r.PUT("/admin/env", store.UpdateEnv)
|
|
||||||
r.GET("/admin/env/status", store.GetEnvStatus)
|
|
||||||
r.DELETE("/admin/env/pending", store.CancelEnv)
|
|
||||||
return r, dir
|
|
||||||
}
|
|
||||||
|
|
||||||
func envDo(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder {
|
|
||||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
return rec
|
|
||||||
}
|
|
||||||
|
|
||||||
// The property the whole tab rests on: a secret's value never leaves the
|
|
||||||
// server, while a non-secret's does so it can be edited in place.
|
|
||||||
func TestGetEnvNeverReturnsSecrets(t *testing.T) {
|
|
||||||
r, _ := envRouter(t)
|
|
||||||
t.Setenv("CLAUDE_API_KEY", "sk-ant-very-secret-value-9f3a")
|
|
||||||
t.Setenv("POSTGRES_PASSWORD", "hunter2")
|
|
||||||
t.Setenv("STEAM_ID", "76561198000000000")
|
|
||||||
t.Setenv("TFL_APP_KEY", "")
|
|
||||||
|
|
||||||
rec := envDo(r, http.MethodGet, "/admin/env", "")
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
body := rec.Body.String()
|
|
||||||
for _, secret := range []string{"sk-ant-very-secret-value-9f3a", "hunter2"} {
|
|
||||||
if strings.Contains(body, secret) {
|
|
||||||
t.Fatalf("response contains the secret %q", secret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var parsed struct {
|
|
||||||
Groups []struct {
|
|
||||||
Vars []envVarView `json:"vars"`
|
|
||||||
} `json:"groups"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
|
||||||
t.Fatalf("parsing response: %v", err)
|
|
||||||
}
|
|
||||||
byName := map[string]envVarView{}
|
|
||||||
for _, g := range parsed.Groups {
|
|
||||||
for _, v := range g.Vars {
|
|
||||||
byName[v.Name] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if v := byName["CLAUDE_API_KEY"]; !v.Set || !v.Secret || v.Value != "" || v.Hint != "9f3a" {
|
|
||||||
t.Errorf("CLAUDE_API_KEY = %+v, want set, secret, no value, hint 9f3a", v)
|
|
||||||
}
|
|
||||||
// Too short for four characters to be a safe hint.
|
|
||||||
if v := byName["POSTGRES_PASSWORD"]; !v.Set || v.Hint != "" || v.Editable {
|
|
||||||
t.Errorf("POSTGRES_PASSWORD = %+v, want set, no hint, locked", v)
|
|
||||||
}
|
|
||||||
if v := byName["STEAM_ID"]; v.Value != "76561198000000000" || v.Secret {
|
|
||||||
t.Errorf("STEAM_ID = %+v, want its value shown", v)
|
|
||||||
}
|
|
||||||
if v := byName["TFL_APP_KEY"]; v.Set {
|
|
||||||
t.Errorf("TFL_APP_KEY = %+v, want unset", v)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUpdateEnv(t *testing.T) {
|
|
||||||
r, dir := envRouter(t)
|
|
||||||
requestPath := filepath.Join(dir, "request.json")
|
|
||||||
|
|
||||||
t.Run("a locked variable is refused and nothing is queued", func(t *testing.T) {
|
|
||||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"POSTGRES_PASSWORD":"x"}}`)
|
|
||||||
if rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("status = %d, want 400", rec.Code)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(requestPath); err == nil {
|
|
||||||
t.Fatal("a refused change left a request behind")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("a malformed body is refused", func(t *testing.T) {
|
|
||||||
if rec := envDo(r, http.MethodPut, "/admin/env", `{"set":`); rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("status = %d, want 400", rec.Code)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("a valid change is queued and a generated value returned once", func(t *testing.T) {
|
|
||||||
rec := envDo(r, http.MethodPut, "/admin/env", `{"set":{"STEAM_ID":"42"},"generate":["BACKEND_SECRET"]}`)
|
|
||||||
if rec.Code != http.StatusAccepted {
|
|
||||||
t.Fatalf("status = %d, want 202: %s", rec.Code, rec.Body)
|
|
||||||
}
|
|
||||||
var parsed struct {
|
|
||||||
Generated map[string]string `json:"generated"`
|
|
||||||
Status services.EnvApplyStatus `json:"status"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &parsed); err != nil {
|
|
||||||
t.Fatalf("parsing response: %v", err)
|
|
||||||
}
|
|
||||||
secret := parsed.Generated["BACKEND_SECRET"]
|
|
||||||
if len(secret) != 64 {
|
|
||||||
t.Fatalf("generated BACKEND_SECRET = %q, want 64 hex characters", secret)
|
|
||||||
}
|
|
||||||
if parsed.Status.State != "pending" {
|
|
||||||
t.Fatalf("status = %+v, want pending", parsed.Status)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Reading the state back must not repeat it.
|
|
||||||
for _, path := range []string{"/admin/env", "/admin/env/status"} {
|
|
||||||
if strings.Contains(envDo(r, http.MethodGet, path, "").Body.String(), secret) {
|
|
||||||
t.Fatalf("GET %s repeats the generated secret", path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("a pending change can be withdrawn", func(t *testing.T) {
|
|
||||||
rec := envDo(r, http.MethodDelete, "/admin/env/pending", "")
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, want 200", rec.Code)
|
|
||||||
}
|
|
||||||
if _, err := os.Stat(requestPath); err == nil {
|
|
||||||
t.Fatal("the request file survived the cancel")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
@@ -1,500 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
"net/url"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/models"
|
|
||||||
"adam-french.co.uk/backend/services"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Job capture: the three endpoints behind userscripts/job-capture.user.js,
|
|
||||||
// which adds the posting open in the browser to the job tracker.
|
|
||||||
//
|
|
||||||
// These are REST, and token-authenticated, because the caller is a userscript
|
|
||||||
// running on someone else's origin (linkedin.com, an ATS). The auth cookies
|
|
||||||
// are SameSite=Lax and never accompany such a request, so the GraphQL
|
|
||||||
// mutations, which rely on them, are out of reach from there.
|
|
||||||
//
|
|
||||||
// The token is deliberately narrow: it opens these routes and nothing else,
|
|
||||||
// so a token leaked from the browser can add rows to the tracker and spend
|
|
||||||
// Claude calls, but cannot read the tracker, edit other data or log in.
|
|
||||||
//
|
|
||||||
// As with rowing, the Claude call lives in the Python service
|
|
||||||
// (python/app/jobs.py) and everything touching the database stays here.
|
|
||||||
|
|
||||||
const (
|
|
||||||
// jobExtractPath is internal in the same way as rowingReadPath: nginx
|
|
||||||
// refuses /py/internal/ and the route refuses anything nginx forwarded.
|
|
||||||
jobExtractPath = "/internal/jobs/extract"
|
|
||||||
|
|
||||||
// maxCaptureBody bounds a capture request. A long posting is tens of
|
|
||||||
// kilobytes of text; the userscript trims the page to maxPageRunes before
|
|
||||||
// sending, so anything near this limit is not a job page.
|
|
||||||
maxCaptureBody = 512 << 10
|
|
||||||
|
|
||||||
// maxPageRunes caps both the text sent to Claude and the description
|
|
||||||
// stored. It mirrors MAX_TEXT_CHARS in python/app/jobs.py, which rejects
|
|
||||||
// anything longer, so the cut has to happen on this side.
|
|
||||||
maxPageRunes = 40_000
|
|
||||||
)
|
|
||||||
|
|
||||||
// jobExtractClient bounds the wait on the Python service; see
|
|
||||||
// rowingReadClient for why two minutes.
|
|
||||||
var jobExtractClient = &http.Client{Timeout: 2 * time.Minute}
|
|
||||||
|
|
||||||
// CaptureTokenMiddleware guards the capture routes with the token generated
|
|
||||||
// in the admin panel (services.CaptureToken), presented as
|
|
||||||
// "Authorization: Bearer <token>".
|
|
||||||
//
|
|
||||||
// Until a token has been generated the routes are off (503) rather than
|
|
||||||
// open; "no token" must never be satisfied by a request that sends none.
|
|
||||||
func (store *Store) CaptureTokenMiddleware(ctx *gin.Context) {
|
|
||||||
if store.CaptureToken == nil {
|
|
||||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "job capture is not configured"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if set, _ := store.CaptureToken.Status(); !set {
|
|
||||||
ctx.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": "no capture token has been generated"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
presented, ok := strings.CutPrefix(ctx.GetHeader("Authorization"), "Bearer ")
|
|
||||||
if !ok || !store.CaptureToken.Verify(presented) {
|
|
||||||
ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.Next()
|
|
||||||
}
|
|
||||||
|
|
||||||
// The three handlers below manage that token from the admin panel. They sit
|
|
||||||
// in the cookie-authenticated admin group, not behind the token: the token
|
|
||||||
// must not be able to replace itself.
|
|
||||||
|
|
||||||
func captureTokenStatus(token *services.CaptureToken) gin.H {
|
|
||||||
set, createdAt := token.Status()
|
|
||||||
if !set {
|
|
||||||
return gin.H{"set": false}
|
|
||||||
}
|
|
||||||
return gin.H{"set": true, "createdAt": createdAt}
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetCaptureToken backs GET /admin/capture-token: whether a token exists and
|
|
||||||
// when it was made. The token itself is not recoverable — only its hash is
|
|
||||||
// stored.
|
|
||||||
func (store *Store) GetCaptureToken(ctx *gin.Context) {
|
|
||||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
|
||||||
}
|
|
||||||
|
|
||||||
// GenerateCaptureToken backs POST /admin/capture-token. It replaces any
|
|
||||||
// existing token, so the userscript must be reconfigured with the new one,
|
|
||||||
// and its response is the only time the token is ever sent anywhere.
|
|
||||||
func (store *Store) GenerateCaptureToken(ctx *gin.Context) {
|
|
||||||
token, createdAt, err := store.CaptureToken.Generate()
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Generating capture token failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to store the token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// The response carries a credential; keep it out of any cache.
|
|
||||||
ctx.Header("Cache-Control", "no-store")
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"token": token, "createdAt": createdAt})
|
|
||||||
}
|
|
||||||
|
|
||||||
// RevokeCaptureToken backs DELETE /admin/capture-token, switching the capture
|
|
||||||
// routes off until a new token is generated.
|
|
||||||
func (store *Store) RevokeCaptureToken(ctx *gin.Context) {
|
|
||||||
if err := store.CaptureToken.Revoke(); err != nil {
|
|
||||||
log.Println("Revoking capture token failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to revoke the token"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, captureTokenStatus(store.CaptureToken))
|
|
||||||
}
|
|
||||||
|
|
||||||
// trackingParams are query parameters that say how the visitor arrived, not
|
|
||||||
// which posting this is. Anything not listed is kept: ATS boards identify the
|
|
||||||
// job in the query string often enough (gh_jid, jk, jobId) that dropping
|
|
||||||
// unknown parameters would merge different postings.
|
|
||||||
var trackingParams = map[string]bool{
|
|
||||||
"trk": true, "trackingid": true, "refid": true, "ebp": true,
|
|
||||||
"gh_src": true, "lever-source": true, "lever-origin": true,
|
|
||||||
"source": true, "src": true, "ref": true,
|
|
||||||
"fbclid": true, "gclid": true, "mc_cid": true, "mc_eid": true,
|
|
||||||
}
|
|
||||||
|
|
||||||
// linkedInJobPath matches both forms of a LinkedIn posting path: the bare
|
|
||||||
// /jobs/view/123 and the public slug form /jobs/view/some-title-at-co-123.
|
|
||||||
var linkedInJobPath = regexp.MustCompile(`^/jobs/view/(?:.*-)?(\d+)/?$`)
|
|
||||||
|
|
||||||
// canonicalJobURL reduces a posting URL to a form that is the same however
|
|
||||||
// the page was reached, so it can serve as the key that decides whether a
|
|
||||||
// posting is already tracked. ok is false for anything that is not an
|
|
||||||
// absolute http(s) URL.
|
|
||||||
//
|
|
||||||
// LinkedIn gets its own rule because the same posting appears under several
|
|
||||||
// paths (search results, collections, the recommended feed), all carrying the
|
|
||||||
// id in ?currentJobId= rather than in the path.
|
|
||||||
func canonicalJobURL(raw string) (canonical string, ok bool) {
|
|
||||||
u, err := url.Parse(strings.TrimSpace(raw))
|
|
||||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
|
||||||
return "", false
|
|
||||||
}
|
|
||||||
host := strings.ToLower(u.Host)
|
|
||||||
query := u.Query()
|
|
||||||
|
|
||||||
if host == "linkedin.com" || strings.HasSuffix(host, ".linkedin.com") {
|
|
||||||
id := query.Get("currentJobId")
|
|
||||||
if m := linkedInJobPath.FindStringSubmatch(u.Path); m != nil {
|
|
||||||
id = m[1]
|
|
||||||
}
|
|
||||||
if id != "" && strings.Trim(id, "0123456789") == "" {
|
|
||||||
return "https://www.linkedin.com/jobs/view/" + id + "/", true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for key := range query {
|
|
||||||
lowered := strings.ToLower(key)
|
|
||||||
if trackingParams[lowered] || strings.HasPrefix(lowered, "utm_") {
|
|
||||||
query.Del(key)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
out := url.URL{
|
|
||||||
Scheme: u.Scheme,
|
|
||||||
Host: host,
|
|
||||||
// A trailing slash is not a different posting.
|
|
||||||
Path: strings.TrimRight(u.Path, "/"),
|
|
||||||
// Encode sorts by key, so parameter order does not matter either.
|
|
||||||
RawQuery: query.Encode(),
|
|
||||||
}
|
|
||||||
return out.String(), true
|
|
||||||
}
|
|
||||||
|
|
||||||
// capturedJob is the slice of an application the userscript needs back: enough
|
|
||||||
// to show "already tracked as …" and no more. The token is not meant to be
|
|
||||||
// able to read the tracker, so notes and the description stay out of it.
|
|
||||||
type capturedJob struct {
|
|
||||||
ID uint `json:"id"`
|
|
||||||
JobTitle string `json:"jobTitle"`
|
|
||||||
Company string `json:"company"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func capturedJobOf(app *models.JobApplication) *capturedJob {
|
|
||||||
return &capturedJob{ID: app.ID, JobTitle: app.JobTitle, Company: app.Company, Status: app.Status}
|
|
||||||
}
|
|
||||||
|
|
||||||
// findByURL returns the newest live application stored under this posting's
|
|
||||||
// URL, or nil. The raw form is tried as well as the canonical one because rows
|
|
||||||
// typed into the tracker by hand hold whatever was pasted.
|
|
||||||
func (store *Store) findByURL(canonical, raw string) (*models.JobApplication, error) {
|
|
||||||
return firstApplication(store.DB.Where("url IN ?", []string{canonical, strings.TrimSpace(raw)}))
|
|
||||||
}
|
|
||||||
|
|
||||||
// firstApplication returns the newest row the query matches, or nil for none.
|
|
||||||
// Limit(1).Find rather than First: a miss is the ordinary answer here (every
|
|
||||||
// badge lookup on an untracked posting), and First reports one as
|
|
||||||
// ErrRecordNotFound, which GORM writes to the log as an error each time.
|
|
||||||
func firstApplication(query *gorm.DB) (*models.JobApplication, error) {
|
|
||||||
var apps []models.JobApplication
|
|
||||||
if err := query.Order("created_at DESC, id DESC").Limit(1).Find(&apps).Error; err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if len(apps) == 0 {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
return &apps[0], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobCaptureStatus backs GET /jobs/capture/status?url=. It is what lets the
|
|
||||||
// userscript show a posting's tracked status instead of an "add" button.
|
|
||||||
func (store *Store) JobCaptureStatus(ctx *gin.Context) {
|
|
||||||
raw := ctx.Query("url")
|
|
||||||
canonical, ok := canonicalJobURL(raw)
|
|
||||||
if !ok {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
app, err := store.findByURL(canonical, raw)
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Job capture status lookup failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if app == nil {
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"found": false})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"found": true, "application": capturedJobOf(app)})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ExtractedJobPosting is the JSON contract for what Claude reads off a job
|
|
||||||
// page: the body of the Python service's reply (JobPosting in
|
|
||||||
// python/app/jobs.py). Empty strings and nulls mean "not found on the page".
|
|
||||||
type ExtractedJobPosting struct {
|
|
||||||
JobTitle string `json:"jobTitle"`
|
|
||||||
Company string `json:"company"`
|
|
||||||
Location *string `json:"location"`
|
|
||||||
Notes *string `json:"notes"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// postingReadError is a failure the Python service reported in words that are
|
|
||||||
// safe to show in the capture popup (its 502 detail); the job-capture
|
|
||||||
// counterpart of displayReadError.
|
|
||||||
type postingReadError struct{ detail string }
|
|
||||||
|
|
||||||
func (e *postingReadError) Error() string { return e.detail }
|
|
||||||
|
|
||||||
// extractJobPosting sends a page's text to the Python service and returns the
|
|
||||||
// fields Claude picked out. It mirrors readRowingDisplay, including which
|
|
||||||
// replies are relayed and which are only logged.
|
|
||||||
func (store *Store) extractJobPosting(ctx context.Context, pageURL, title, text string) (ExtractedJobPosting, error) {
|
|
||||||
var posting ExtractedJobPosting
|
|
||||||
|
|
||||||
body, err := json.Marshal(struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
}{pageURL, title, text})
|
|
||||||
if err != nil {
|
|
||||||
return posting, err
|
|
||||||
}
|
|
||||||
|
|
||||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, store.PythonURL+jobExtractPath, bytes.NewReader(body))
|
|
||||||
if err != nil {
|
|
||||||
return posting, err
|
|
||||||
}
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
resp, err := jobExtractClient.Do(req)
|
|
||||||
if err != nil {
|
|
||||||
return posting, err
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
|
||||||
var failure struct {
|
|
||||||
Detail string `json:"detail"`
|
|
||||||
}
|
|
||||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<10))
|
|
||||||
if resp.StatusCode == http.StatusBadGateway && json.Unmarshal(raw, &failure) == nil && failure.Detail != "" {
|
|
||||||
return posting, &postingReadError{detail: failure.Detail}
|
|
||||||
}
|
|
||||||
return posting, fmt.Errorf("job extractor returned %d: %s", resp.StatusCode, raw)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&posting); err != nil {
|
|
||||||
return posting, fmt.Errorf("decoding job extractor response: %w", err)
|
|
||||||
}
|
|
||||||
return posting, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// truncateRunes cuts s to at most max runes, on a rune boundary so the result
|
|
||||||
// is still valid UTF-8 for Postgres and for JSON.
|
|
||||||
func truncateRunes(s string, max int) string {
|
|
||||||
runes := []rune(s)
|
|
||||||
if len(runes) <= max {
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
return string(runes[:max])
|
|
||||||
}
|
|
||||||
|
|
||||||
// bindCapture decodes a size-limited JSON body, answering 400 itself when it
|
|
||||||
// cannot.
|
|
||||||
func bindCapture(ctx *gin.Context, into any) bool {
|
|
||||||
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, maxCaptureBody)
|
|
||||||
if err := ctx.ShouldBindJSON(into); err != nil {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobCaptureExtract backs POST /jobs/capture/extract: page text in, the
|
|
||||||
// popup's pre-filled fields out. Nothing is stored; saving is a separate
|
|
||||||
// request made once the fields have been checked by eye.
|
|
||||||
func (store *Store) JobCaptureExtract(ctx *gin.Context) {
|
|
||||||
var input struct {
|
|
||||||
URL string `json:"url"`
|
|
||||||
Title string `json:"title"`
|
|
||||||
Text string `json:"text"`
|
|
||||||
}
|
|
||||||
if !bindCapture(ctx, &input) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
text := strings.TrimSpace(input.Text)
|
|
||||||
if text == "" {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "text is required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
posting, err := store.extractJobPosting(ctx.Request.Context(),
|
|
||||||
truncateRunes(input.URL, 2000), truncateRunes(input.Title, 500), truncateRunes(text, maxPageRunes))
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Job extract failed:", err)
|
|
||||||
var readErr *postingReadError
|
|
||||||
if errors.As(err, &readErr) {
|
|
||||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": readErr.detail})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusBadGateway, gin.H{"error": "failed to read the page"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, posting)
|
|
||||||
}
|
|
||||||
|
|
||||||
// captureInput is the body of POST /jobs/capture: the popup's fields.
|
|
||||||
type captureInput struct {
|
|
||||||
JobTitle string `json:"jobTitle"`
|
|
||||||
Company string `json:"company"`
|
|
||||||
Location string `json:"location"`
|
|
||||||
URL string `json:"url"`
|
|
||||||
Status string `json:"status"`
|
|
||||||
Notes string `json:"notes"`
|
|
||||||
Description string `json:"description"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func nonEmpty(p *string) bool { return p != nil && strings.TrimSpace(*p) != "" }
|
|
||||||
|
|
||||||
// mergeCapture folds a repeat capture into the application it matched and
|
|
||||||
// reports whether anything changed.
|
|
||||||
//
|
|
||||||
// It only ever adds: the status moves forwards or not at all (the same rule
|
|
||||||
// the email pipeline follows, so re-capturing a posting marked "saved" cannot
|
|
||||||
// pull an interviewing application back), and a field already holding a value
|
|
||||||
// is left alone, because the row may have been corrected by hand since. Title
|
|
||||||
// and company are never touched — they are the key the email pipeline matches
|
|
||||||
// on.
|
|
||||||
func mergeCapture(app *models.JobApplication, in captureInput, now time.Time) bool {
|
|
||||||
changed := false
|
|
||||||
|
|
||||||
if status := services.NormalizeStatus(in.Status); services.StatusAdvances(app.Status, status) {
|
|
||||||
app.Status = status
|
|
||||||
changed = true
|
|
||||||
}
|
|
||||||
// Saved-then-applied is the common path here, and the moment of the
|
|
||||||
// second capture is the application date.
|
|
||||||
if app.AppliedAt == nil && app.Status == "applied" {
|
|
||||||
app.AppliedAt = &now
|
|
||||||
changed = true
|
|
||||||
}
|
|
||||||
|
|
||||||
fill := func(field **string, value string) {
|
|
||||||
if value != "" && !nonEmpty(*field) {
|
|
||||||
*field = &value
|
|
||||||
changed = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fill(&app.Location, in.Location)
|
|
||||||
fill(&app.URL, in.URL)
|
|
||||||
fill(&app.Description, in.Description)
|
|
||||||
|
|
||||||
// Notes accumulate, as they do when the pipeline updates a row, but a
|
|
||||||
// repeat capture of the same page must not append the same line twice.
|
|
||||||
if in.Notes != "" {
|
|
||||||
switch {
|
|
||||||
case !nonEmpty(app.Notes):
|
|
||||||
app.Notes = &in.Notes
|
|
||||||
changed = true
|
|
||||||
case !strings.Contains(*app.Notes, in.Notes):
|
|
||||||
combined := *app.Notes + "\n" + in.Notes
|
|
||||||
app.Notes = &combined
|
|
||||||
changed = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return changed
|
|
||||||
}
|
|
||||||
|
|
||||||
// JobCapture backs POST /jobs/capture, an upsert.
|
|
||||||
//
|
|
||||||
// A posting already in the tracker is updated in place rather than added
|
|
||||||
// again. That matters beyond tidiness: the email pipeline identifies an
|
|
||||||
// application by (company, job title), so two rows for one posting means the
|
|
||||||
// confirmation email advances only one of them.
|
|
||||||
//
|
|
||||||
// Match order is the posting URL, then (company, job title) compared the way
|
|
||||||
// the pipeline compares them. Only live rows match — unlike the pipeline's
|
|
||||||
// lookup, which also sees deleted rows so that an email cannot resurrect one.
|
|
||||||
// A capture is a deliberate act, so capturing a posting whose row was deleted
|
|
||||||
// makes a new row.
|
|
||||||
func (store *Store) JobCapture(ctx *gin.Context) {
|
|
||||||
var input captureInput
|
|
||||||
if !bindCapture(ctx, &input) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
input.JobTitle = strings.TrimSpace(input.JobTitle)
|
|
||||||
input.Company = strings.TrimSpace(input.Company)
|
|
||||||
input.Location = strings.TrimSpace(input.Location)
|
|
||||||
input.Notes = strings.TrimSpace(input.Notes)
|
|
||||||
input.Description = truncateRunes(strings.TrimSpace(input.Description), maxPageRunes)
|
|
||||||
if input.JobTitle == "" || input.Company == "" {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "jobTitle and company are required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
rawURL := input.URL
|
|
||||||
if strings.TrimSpace(rawURL) != "" {
|
|
||||||
canonical, ok := canonicalJobURL(rawURL)
|
|
||||||
if !ok {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "url must be an absolute http(s) URL"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
input.URL = canonical
|
|
||||||
} else {
|
|
||||||
input.URL = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var existing *models.JobApplication
|
|
||||||
var err error
|
|
||||||
if input.URL != "" {
|
|
||||||
existing, err = store.findByURL(input.URL, rawURL)
|
|
||||||
}
|
|
||||||
if err == nil && existing == nil {
|
|
||||||
existing, err = firstApplication(store.DB.Where(
|
|
||||||
"LOWER(company) = LOWER(?) AND LOWER(job_title) = LOWER(?)", input.Company, input.JobTitle))
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
log.Println("Job capture lookup failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "lookup failed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
if existing != nil {
|
|
||||||
action := "unchanged"
|
|
||||||
if mergeCapture(existing, input, now) {
|
|
||||||
if err := store.DB.Save(existing).Error; err != nil {
|
|
||||||
log.Println("Job capture update failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
action = "updated"
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"action": action, "application": capturedJobOf(existing)})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// A new row is the merge of the capture into an empty application, which
|
|
||||||
// keeps the two paths agreeing on what an empty field and "applied" mean.
|
|
||||||
// The empty status counts as unknown, so any status takes over from it.
|
|
||||||
app := models.JobApplication{JobTitle: input.JobTitle, Company: input.Company}
|
|
||||||
mergeCapture(&app, input, now)
|
|
||||||
if err := store.DB.Create(&app).Error; err != nil {
|
|
||||||
log.Println("Job capture insert failed:", err)
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.JSON(http.StatusCreated, gin.H{"action": "created", "application": capturedJobOf(&app)})
|
|
||||||
}
|
|
||||||
@@ -1,379 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"adam-french.co.uk/backend/models"
|
|
||||||
"adam-french.co.uk/backend/services"
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The capture handlers themselves need a database, and the only driver in
|
|
||||||
// go.mod is postgres, so what is covered here is everything around the
|
|
||||||
// queries: the token gate, the URL key that decides whether a posting is
|
|
||||||
// already tracked, the merge rule for a repeat capture, and the call to the
|
|
||||||
// Python service.
|
|
||||||
|
|
||||||
func TestCaptureTokenMiddleware(t *testing.T) {
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
serve := func(store *Store, header string) int {
|
|
||||||
r := gin.New()
|
|
||||||
r.GET("/x", store.CaptureTokenMiddleware, func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/x", nil)
|
|
||||||
if header != "" {
|
|
||||||
req.Header.Set("Authorization", header)
|
|
||||||
}
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, req)
|
|
||||||
return rec.Code
|
|
||||||
}
|
|
||||||
newToken := func() *services.CaptureToken {
|
|
||||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitCaptureToken: %v", err)
|
|
||||||
}
|
|
||||||
return tok
|
|
||||||
}
|
|
||||||
|
|
||||||
// The case the middleware exists to get right: with no token generated,
|
|
||||||
// a request presenting nothing (or an empty bearer) must not get in.
|
|
||||||
t.Run("no token generated switches the routes off", func(t *testing.T) {
|
|
||||||
store := &Store{CaptureToken: newToken()}
|
|
||||||
for _, header := range []string{"", "Bearer ", "Bearer anything"} {
|
|
||||||
if got := serve(store, header); got != http.StatusServiceUnavailable {
|
|
||||||
t.Fatalf("header %q: status = %d, want 503", header, got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
t.Run("a store built without the token service is off too", func(t *testing.T) {
|
|
||||||
if got := serve(&Store{}, "Bearer x"); got != http.StatusServiceUnavailable {
|
|
||||||
t.Fatalf("status = %d, want 503", got)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
store := &Store{CaptureToken: newToken()}
|
|
||||||
token, _, err := store.CaptureToken.Generate()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Generate: %v", err)
|
|
||||||
}
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
header string
|
|
||||||
want int
|
|
||||||
}{
|
|
||||||
{"the generated token is let through", "Bearer " + token, http.StatusOK},
|
|
||||||
{"a wrong token is refused", "Bearer nope", http.StatusUnauthorized},
|
|
||||||
{"no header is refused", "", http.StatusUnauthorized},
|
|
||||||
{"the bare token without the scheme is refused", token, http.StatusUnauthorized},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
t.Run(c.name, func(t *testing.T) {
|
|
||||||
if got := serve(store, c.header); got != c.want {
|
|
||||||
t.Fatalf("status = %d, want %d", got, c.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The admin endpoints, driven without the admin middleware (covered
|
|
||||||
// elsewhere): generate shows the token once, status never does, and a second
|
|
||||||
// generate or a revoke stops the first token working.
|
|
||||||
func TestCaptureTokenAdminEndpoints(t *testing.T) {
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
tok, err := services.InitCaptureToken(filepath.Join(t.TempDir(), "token.json"))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("InitCaptureToken: %v", err)
|
|
||||||
}
|
|
||||||
store := &Store{CaptureToken: tok}
|
|
||||||
r := gin.New()
|
|
||||||
r.GET("/t", store.GetCaptureToken)
|
|
||||||
r.POST("/t", store.GenerateCaptureToken)
|
|
||||||
r.DELETE("/t", store.RevokeCaptureToken)
|
|
||||||
|
|
||||||
call := func(method string) (map[string]any, *httptest.ResponseRecorder) {
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, httptest.NewRequest(method, "/t", nil))
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("%s: status = %d, body = %s", method, rec.Code, rec.Body)
|
|
||||||
}
|
|
||||||
var out map[string]any
|
|
||||||
json.Unmarshal(rec.Body.Bytes(), &out)
|
|
||||||
return out, rec
|
|
||||||
}
|
|
||||||
|
|
||||||
if out, _ := call(http.MethodGet); out["set"] != false {
|
|
||||||
t.Fatalf("fresh status = %v", out)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, rec := call(http.MethodPost)
|
|
||||||
first, _ := out["token"].(string)
|
|
||||||
if !tok.Verify(first) {
|
|
||||||
t.Fatalf("generated token %q does not verify", first)
|
|
||||||
}
|
|
||||||
if rec.Header().Get("Cache-Control") != "no-store" {
|
|
||||||
t.Fatal("the response carrying the token must not be cacheable")
|
|
||||||
}
|
|
||||||
|
|
||||||
out, _ = call(http.MethodGet)
|
|
||||||
if out["set"] != true || out["createdAt"] == nil {
|
|
||||||
t.Fatalf("status after generate = %v", out)
|
|
||||||
}
|
|
||||||
if _, leaked := out["token"]; leaked {
|
|
||||||
t.Fatal("status must never return the token")
|
|
||||||
}
|
|
||||||
|
|
||||||
call(http.MethodPost)
|
|
||||||
if tok.Verify(first) {
|
|
||||||
t.Fatal("regenerating must invalidate the previous token")
|
|
||||||
}
|
|
||||||
|
|
||||||
if out, _ := call(http.MethodDelete); out["set"] != false {
|
|
||||||
t.Fatalf("status after revoke = %v", out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestCanonicalJobURL(t *testing.T) {
|
|
||||||
const linkedIn = "https://www.linkedin.com/jobs/view/4012345678/"
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
in string
|
|
||||||
want string // "" means rejected
|
|
||||||
}{
|
|
||||||
// One LinkedIn posting, reached four ways, must be one key.
|
|
||||||
{"linkedin direct", "https://www.linkedin.com/jobs/view/4012345678/?trk=public_jobs", linkedIn},
|
|
||||||
{"linkedin slug form", "https://uk.linkedin.com/jobs/view/backend-engineer-at-acme-4012345678?refId=abc", linkedIn},
|
|
||||||
{"linkedin search pane", "https://www.linkedin.com/jobs/search/?currentJobId=4012345678&keywords=go", linkedIn},
|
|
||||||
{"linkedin collections pane", "https://www.linkedin.com/jobs/collections/recommended/?currentJobId=4012345678", linkedIn},
|
|
||||||
{"linkedin page with no job id is left as a normal URL", "https://www.linkedin.com/jobs/search/?keywords=go", "https://www.linkedin.com/jobs/search?keywords=go"},
|
|
||||||
{"a non-numeric linkedin id is not trusted", "https://www.linkedin.com/jobs/search/?currentJobId=4/../x", "https://www.linkedin.com/jobs/search?currentJobId=4%2F..%2Fx"},
|
|
||||||
{"a lookalike host does not get the linkedin rule", "https://notlinkedin.com/jobs/view/42", "https://notlinkedin.com/jobs/view/42"},
|
|
||||||
|
|
||||||
{"tracking parameters and the fragment are dropped", "https://jobs.lever.co/acme/abc-123?lever-source=LinkedIn&utm_medium=x#apply", "https://jobs.lever.co/acme/abc-123"},
|
|
||||||
// gh_jid IS the posting on an embedded Greenhouse board.
|
|
||||||
{"a parameter that identifies the job is kept", "https://acme.com/careers?gh_jid=77&gh_src=abc", "https://acme.com/careers?gh_jid=77"},
|
|
||||||
{"parameter order does not matter", "https://x.com/job?b=2&a=1", "https://x.com/job?a=1&b=2"},
|
|
||||||
{"host case and a trailing slash do not matter", "https://Boards.Greenhouse.io/acme/jobs/55/", "https://boards.greenhouse.io/acme/jobs/55"},
|
|
||||||
|
|
||||||
{"a relative path is rejected", "/jobs/view/1", ""},
|
|
||||||
{"a non-http scheme is rejected", "javascript:alert(1)", ""},
|
|
||||||
{"empty is rejected", "", ""},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
t.Run(c.name, func(t *testing.T) {
|
|
||||||
got, ok := canonicalJobURL(c.in)
|
|
||||||
if ok != (c.want != "") || got != c.want {
|
|
||||||
t.Fatalf("canonicalJobURL(%q) = %q, %v; want %q", c.in, got, ok, c.want)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func strPtr(s string) *string { return &s }
|
|
||||||
|
|
||||||
func TestMergeCapture(t *testing.T) {
|
|
||||||
now := time.Date(2026, 10, 12, 9, 0, 0, 0, time.UTC)
|
|
||||||
earlier := now.Add(-48 * time.Hour)
|
|
||||||
|
|
||||||
t.Run("a new row takes every field and an applied date", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{JobTitle: "Engineer", Company: "Acme"}
|
|
||||||
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Notes: "Hybrid", Description: "Full text"}
|
|
||||||
if !mergeCapture(&app, in, now) {
|
|
||||||
t.Fatal("expected a change")
|
|
||||||
}
|
|
||||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
|
||||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
|
||||||
}
|
|
||||||
if *app.Location != "London" || *app.URL != "https://x.com/1" || *app.Notes != "Hybrid" || *app.Description != "Full text" {
|
|
||||||
t.Fatalf("fields not filled: %+v", app)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("a saved posting has no applied date", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{}
|
|
||||||
mergeCapture(&app, captureInput{Status: "saved"}, now)
|
|
||||||
if app.Status != "saved" || app.AppliedAt != nil {
|
|
||||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("saved then applied advances and dates the application", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{Status: "saved"}
|
|
||||||
if !mergeCapture(&app, captureInput{Status: "applied"}, now) {
|
|
||||||
t.Fatal("expected a change")
|
|
||||||
}
|
|
||||||
if app.Status != "applied" || app.AppliedAt == nil || !app.AppliedAt.Equal(now) {
|
|
||||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("a repeat capture cannot move an application backwards", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{Status: "interviewing", AppliedAt: &earlier}
|
|
||||||
if mergeCapture(&app, captureInput{Status: "saved"}, now) {
|
|
||||||
t.Fatal("expected no change")
|
|
||||||
}
|
|
||||||
if app.Status != "interviewing" || !app.AppliedAt.Equal(earlier) {
|
|
||||||
t.Fatalf("status = %q, appliedAt = %v", app.Status, app.AppliedAt)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("fields already set are kept, empty ones are filled", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Location: strPtr("Remote"), URL: strPtr("")}
|
|
||||||
in := captureInput{Status: "applied", Location: "London", URL: "https://x.com/1", Description: "Full text"}
|
|
||||||
if !mergeCapture(&app, in, now) {
|
|
||||||
t.Fatal("expected a change")
|
|
||||||
}
|
|
||||||
if *app.Location != "Remote" {
|
|
||||||
t.Fatalf("location overwritten: %q", *app.Location)
|
|
||||||
}
|
|
||||||
if *app.URL != "https://x.com/1" || *app.Description != "Full text" {
|
|
||||||
t.Fatalf("empty fields not filled: url=%q", *app.URL)
|
|
||||||
}
|
|
||||||
if !app.AppliedAt.Equal(earlier) {
|
|
||||||
t.Fatal("an existing applied date must not be replaced")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("notes append once", func(t *testing.T) {
|
|
||||||
app := models.JobApplication{Status: "applied", AppliedAt: &earlier, Notes: strPtr("Recruiter: Sam")}
|
|
||||||
in := captureInput{Status: "applied", Notes: "Hybrid, £70k"}
|
|
||||||
if !mergeCapture(&app, in, now) || *app.Notes != "Recruiter: Sam\nHybrid, £70k" {
|
|
||||||
t.Fatalf("notes = %q", *app.Notes)
|
|
||||||
}
|
|
||||||
if mergeCapture(&app, in, now) {
|
|
||||||
t.Fatalf("the same note was appended twice: %q", *app.Notes)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTruncateRunes(t *testing.T) {
|
|
||||||
if got := truncateRunes("££££", 2); got != "££" {
|
|
||||||
t.Fatalf("got %q; the cut must fall on a rune boundary", got)
|
|
||||||
}
|
|
||||||
if got := truncateRunes("short", 10); got != "short" {
|
|
||||||
t.Fatalf("got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func jobExtractor(t *testing.T, handler http.HandlerFunc) *Store {
|
|
||||||
t.Helper()
|
|
||||||
srv := httptest.NewServer(handler)
|
|
||||||
t.Cleanup(srv.Close)
|
|
||||||
return &Store{PythonURL: srv.URL}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExtractJobPostingRequestAndReply(t *testing.T) {
|
|
||||||
var got map[string]string
|
|
||||||
var path string
|
|
||||||
var forwarded bool
|
|
||||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
path = r.URL.Path
|
|
||||||
// As with the rowing reader, either header makes the Python route
|
|
||||||
// answer 404.
|
|
||||||
forwarded = r.Header.Get("X-Real-IP") != "" || r.Header.Get("X-Forwarded-For") != ""
|
|
||||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
|
||||||
t.Errorf("decoding request: %v", err)
|
|
||||||
}
|
|
||||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": null}`))
|
|
||||||
})
|
|
||||||
|
|
||||||
posting, err := store.extractJobPosting(context.Background(), "https://x.com/1", "Engineer | Acme", "page text")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("extractJobPosting: %v", err)
|
|
||||||
}
|
|
||||||
if posting.JobTitle != "Engineer" || posting.Company != "Acme" || posting.Location == nil || *posting.Location != "London" || posting.Notes != nil {
|
|
||||||
t.Fatalf("got %+v", posting)
|
|
||||||
}
|
|
||||||
if path != jobExtractPath {
|
|
||||||
t.Fatalf("path = %q, want %q", path, jobExtractPath)
|
|
||||||
}
|
|
||||||
if forwarded {
|
|
||||||
t.Fatal("request carried a proxy header the Python route rejects")
|
|
||||||
}
|
|
||||||
if got["url"] != "https://x.com/1" || got["title"] != "Engineer | Acme" || got["text"] != "page text" {
|
|
||||||
t.Fatalf("request body = %+v", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestExtractJobPostingErrors(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
name string
|
|
||||||
status int
|
|
||||||
body string
|
|
||||||
wantDetail string // non-empty: a postingReadError with this message
|
|
||||||
}{
|
|
||||||
{"extractor failure is relayed", http.StatusBadGateway, `{"detail": "failed to parse the posting"}`, "failed to parse the posting"},
|
|
||||||
{"validation error is not relayed", http.StatusUnprocessableEntity, `{"detail": [{"msg": "bad"}]}`, ""},
|
|
||||||
{"missing key is not relayed", http.StatusServiceUnavailable, `{"detail": "CLAUDE_API_KEY is not set"}`, ""},
|
|
||||||
{"malformed success body", http.StatusOK, `not json`, ""},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
t.Run(c.name, func(t *testing.T) {
|
|
||||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.WriteHeader(c.status)
|
|
||||||
w.Write([]byte(c.body))
|
|
||||||
})
|
|
||||||
_, err := store.extractJobPosting(context.Background(), "https://x.com/1", "t", "text")
|
|
||||||
if err == nil {
|
|
||||||
t.Fatal("expected an error")
|
|
||||||
}
|
|
||||||
var readErr *postingReadError
|
|
||||||
if relayed := errors.As(err, &readErr); relayed != (c.wantDetail != "") {
|
|
||||||
t.Fatalf("relayed = %v, err = %v", relayed, err)
|
|
||||||
}
|
|
||||||
if readErr != nil && readErr.detail != c.wantDetail {
|
|
||||||
t.Fatalf("detail = %q, want %q", readErr.detail, c.wantDetail)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The extract handler runs without a database, so it can be driven whole: the
|
|
||||||
// page text must be cut to the limit the Python side enforces before it is
|
|
||||||
// forwarded, or a long page would come back as an opaque 422.
|
|
||||||
func TestJobCaptureExtractTruncatesAndRelays(t *testing.T) {
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
var forwardedLen int
|
|
||||||
store := jobExtractor(t, func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
var body map[string]string
|
|
||||||
json.NewDecoder(r.Body).Decode(&body)
|
|
||||||
forwardedLen = len([]rune(body["text"]))
|
|
||||||
w.Write([]byte(`{"jobTitle": "Engineer", "company": "Acme", "location": null, "notes": null}`))
|
|
||||||
})
|
|
||||||
r := gin.New()
|
|
||||||
r.POST("/extract", store.JobCaptureExtract)
|
|
||||||
|
|
||||||
post := func(body string) *httptest.ResponseRecorder {
|
|
||||||
rec := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/extract", strings.NewReader(body)))
|
|
||||||
return rec
|
|
||||||
}
|
|
||||||
|
|
||||||
long, _ := json.Marshal(map[string]string{"url": "https://x.com/1", "title": "t", "text": strings.Repeat("é", maxPageRunes+500)})
|
|
||||||
rec := post(string(long))
|
|
||||||
if rec.Code != http.StatusOK {
|
|
||||||
t.Fatalf("status = %d, body = %s", rec.Code, rec.Body)
|
|
||||||
}
|
|
||||||
if forwardedLen != maxPageRunes {
|
|
||||||
t.Fatalf("forwarded %d runes, want %d", forwardedLen, maxPageRunes)
|
|
||||||
}
|
|
||||||
var out ExtractedJobPosting
|
|
||||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil || out.Company != "Acme" {
|
|
||||||
t.Fatalf("body = %s (%v)", rec.Body, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if rec := post(`{"url": "https://x.com/1", "text": " "}`); rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("blank text: status = %d", rec.Code)
|
|
||||||
}
|
|
||||||
if rec := post(`not json`); rec.Code != http.StatusBadRequest {
|
|
||||||
t.Fatalf("bad body: status = %d", rec.Code)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,178 +0,0 @@
|
|||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/hex"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
"github.com/golang-jwt/jwt/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Attachment upload for the chat.
|
|
||||||
//
|
|
||||||
// Files land in one of two directories. /backend/uploads/ is served by nginx
|
|
||||||
// at /uploads/ with no authentication, so anything written there is publicly
|
|
||||||
// reachable by URL — which is why the extension and content checks below
|
|
||||||
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
|
|
||||||
// messages and is served at /uploads/private/ behind an nginx auth_request
|
|
||||||
// gate; only an admin may upload there.
|
|
||||||
|
|
||||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
|
||||||
var allowedExtensions = map[string]bool{
|
|
||||||
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
|
|
||||||
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
|
|
||||||
".pdf": true, ".txt": true,
|
|
||||||
}
|
|
||||||
|
|
||||||
// extensionToMIMEPrefix cross-checks the sniffed content type against the
|
|
||||||
// claimed extension, to stop e.g. HTML being served from a .png URL.
|
|
||||||
//
|
|
||||||
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
|
|
||||||
// http.DetectContentType's answers for them are unreliable enough to reject
|
|
||||||
// legitimate files, so a missing entry means "extension allowed, content not
|
|
||||||
// verified".
|
|
||||||
var extensionToMIMEPrefix = map[string]string{
|
|
||||||
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
|
|
||||||
".mp4": "video/", ".webm": "video/",
|
|
||||||
".pdf": "application/pdf", ".txt": "text/",
|
|
||||||
}
|
|
||||||
|
|
||||||
// publicUploadDir and privateUploadDir are the two destinations; the private
|
|
||||||
// one is created on demand because nothing else guarantees it exists.
|
|
||||||
const (
|
|
||||||
publicUploadDir = "/backend/uploads/"
|
|
||||||
privateUploadDir = "/backend/uploads/private/"
|
|
||||||
)
|
|
||||||
|
|
||||||
// UploadMessageFile backs POST /messages/upload (login required) and returns
|
|
||||||
// the URL of the stored file, which the client then sends over the WebSocket
|
|
||||||
// as a message's fileUrl.
|
|
||||||
//
|
|
||||||
// The multipart form takes an optional "private" field: "true" stores the file
|
|
||||||
// under /uploads/private/ for use as a private message's attachment. That is
|
|
||||||
// admin-only, because private messages themselves are — an attachment URL
|
|
||||||
// leaking out is the same disclosure as the message leaking out.
|
|
||||||
func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
|
||||||
private := ctx.PostForm("private") == "true"
|
|
||||||
if private && !requestIsAdmin(ctx) {
|
|
||||||
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := ctx.FormFile("file")
|
|
||||||
if err != nil {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const maxSize = 10 << 20 // 10MB
|
|
||||||
if file.Size > maxSize {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ext := strings.ToLower(filepath.Ext(file.Filename))
|
|
||||||
if !allowedExtensions[ext] {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate actual content type matches extension
|
|
||||||
f, err := file.Open()
|
|
||||||
if err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// 512 bytes is exactly what http.DetectContentType inspects; reading more
|
|
||||||
// would be wasted. A single Read may return fewer bytes than asked for,
|
|
||||||
// which is fine — sniffing works on a short prefix — so only a read that
|
|
||||||
// produced nothing at all is an error.
|
|
||||||
buf := make([]byte, 512)
|
|
||||||
n, err := f.Read(buf)
|
|
||||||
f.Close()
|
|
||||||
if err != nil && n == 0 {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
detectedType := http.DetectContentType(buf[:n])
|
|
||||||
|
|
||||||
expectedPrefix, ok := extensionToMIMEPrefix[ext]
|
|
||||||
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
|
|
||||||
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// The uploaded name is discarded entirely in favour of 16 random bytes
|
|
||||||
// from crypto/rand. That kills path traversal and collisions in one go,
|
|
||||||
// and makes the resulting URL unguessable. Only the extension is carried
|
|
||||||
// over, and it has already been checked against the allow-list.
|
|
||||||
b := make([]byte, 16)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
filename := hex.EncodeToString(b) + ext
|
|
||||||
|
|
||||||
uploadDir := publicUploadDir
|
|
||||||
urlPrefix := "/uploads/"
|
|
||||||
if private {
|
|
||||||
uploadDir = privateUploadDir
|
|
||||||
urlPrefix = "/uploads/private/"
|
|
||||||
// 0755 so nginx (a different user) can traverse the directory to
|
|
||||||
// serve the files once its auth_request gate has approved.
|
|
||||||
if err := os.MkdirAll(uploadDir, 0755); err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dest := filepath.Join(uploadDir, filename)
|
|
||||||
|
|
||||||
// Reopened rather than rewound: the earlier handle was closed after
|
|
||||||
// sniffing, and multipart files may be backed by either memory or a temp
|
|
||||||
// file, so a fresh reader is the simplest correct option.
|
|
||||||
src, err := file.Open()
|
|
||||||
if err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer src.Close()
|
|
||||||
|
|
||||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer out.Close()
|
|
||||||
|
|
||||||
if _, err := io.Copy(out, src); err != nil {
|
|
||||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
|
|
||||||
}
|
|
||||||
|
|
||||||
// requestIsAdmin reports whether the caller's access token carries admin=true.
|
|
||||||
//
|
|
||||||
// This route sits in the `protected` group, which runs AuthMiddlewear but not
|
|
||||||
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
|
|
||||||
// public attachments — so the admin check is made here from the same
|
|
||||||
// "userClaims" value AdminMiddleware would have read.
|
|
||||||
func requestIsAdmin(ctx *gin.Context) bool {
|
|
||||||
claims, exists := ctx.Get("userClaims")
|
|
||||||
if !exists {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
mapClaims, ok := claims.(*jwt.MapClaims)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
admin, ok := (*mapClaims)["admin"].(bool)
|
|
||||||
|
|
||||||
return ok && admin
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user