Files
stpweb/certbot/entrypoint.sh
T
adamfandClaude Opus 5 25ac1cde1c Fix security issues, bugs, and convoluted code across the stack
Security:
- Token revocation. User gains a TokenVersion counter embedded in both
  tokens as a "tv" claim; AuthenticateToken rejects a token whose version
  no longer matches the row. Logout bumps it, so logging out now kills
  outstanding tokens rather than only clearing cookies. Costs one
  primary-key SELECT per authenticated request, which is the price of
  having revocation at all.
- Spotify OAuth CSRF. The fixed SPOTIFY_AUTH_STATE constant is replaced by
  a per-request one-shot nonce, verified and consumed on callback.
- Private chat attachments. Attachments on private messages are written to
  /backend/uploads/private/ and served at /uploads/private/, gated by the
  same nginx auth_request admin check used for /hasura/ and /notes/.
  Private uploads are rejected from non-admin callers.
- The icecast admin UI (/radio/admin/) is behind the admin gate; listener
  traffic is untouched.
- Store caches are mutex-guarded, so -race is clean.

Bugs:
- The email pipeline no longer drops emails permanently on transient
  failure. Failures record an attempt counter and are retried up to 3
  times; the fetch window rewinds to the oldest retryable email's
  ReceivedAt, without which a retry could never re-fetch it.
- Rowing duplicate detection distinguishes ErrRecordNotFound from a real
  DB error, so a transient failure no longer causes a duplicate insert
  plus a paid Claude call.
- DeletePost propagates its delete error instead of reporting success.
- RecentlyPlayed populates the cache it reads.
- main.go exits non-zero if r.Run fails, so a port conflict is visible.
- Python: the scan truncation flag is set on every deadline path;
  timed_out is reported by the worker rather than inferred from the clock;
  date validation uses Europe/London rather than server-local time.
- Vue: Time.vue and Radio.vue intervals are cleared on unmount; Feed.vue
  guards a missing author; Timer.vue gets an explicit state machine and
  compares total elapsed seconds; Elle.vue's comma-operator call and
  per-frame console.log are fixed.

Simplification:
- One TTLCache replaces three near-identical cache implementations, with
  the differing eviction rules as explicit parameters.
- run_scan's transport index no longer uses one object as both ordering
  record and live output; its three phases are separate functions.
- _price_hotels submits all work to a single pool, so the nested-executor
  deadlock hazard is gone by construction.
- The NDJSON event generators share one implementation.
- IMAP FETCH responses pair each line with its literal in the type, so
  callers no longer hand-skip alternate entries.
- Shared helpers for slice-of-pointers, markdown fences and auth cookies.
- Vue: useHotelSearch, createMirrorStore, useRotation, useCreateForm,
  useLinkAttrs, ListWidget and LinkTableItems replace duplicated blocks.
- nginx dev config's duplicated :80/:443 bodies share one partial.

Infra: certbot passes --deploy-hook touching a sentinel that nginx's
watcher reloads on, so renewed certs are served without a restart, and the
watcher also removes the manual restart after first issuance. db is gated
on service_healthy, autoheal is pinned, and the unused envsubst entries
are dropped.

Verified: go build/vet, npx vite build, py_compile, docker compose config
for both overlays, bash -n on all scripts, and an envsubst render of every
nginx template (no leftover placeholders, runtime vars preserved, braces
balanced).

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-09-16 16:12:21 +01:00

89 lines
4.3 KiB
Bash
Executable File

#!/bin/sh
# =============================================================================
# certbot entrypoint — obtains the TLS certificate once, then renews forever.
#
# WHAT IT DOES
# 1. One blocking `certonly` run to get (or confirm) a certificate for the
# apex domain and its www alias.
# 2. Then loops forever: `certbot renew` every 12 hours.
#
# WHEN IT RUNS
# Production only. docker-compose.dev.yml puts this service in the `disabled`
# 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.
#
# HOW VALIDATION WORKS (--webroot)
# Let's Encrypt HTTP-01: certbot writes a challenge token into
# /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
# the server that answers. /var/www/certbot is the ./certbot/www bind mount,
# mounted into BOTH containers, which is what makes this work. Every nginx
# template (including the bootstrap nginx_setup.conf) serves that path.
# See nginx/entrypoint.sh for the first-issuance chicken-and-egg ordering.
#
# CERT STORAGE / SHARING
# /etc/letsencrypt is the ./certbot/conf bind mount, also mounted read-write
# into nginx. That directory is the private key material — it is gitignored
# and must never be committed.
#
# RENEWAL TIMING AND THE RELOAD SIGNAL
# `certbot renew` is a no-op unless the cert is within 30 days of expiry, so
# running it every 12h is safe and well inside Let's Encrypt's rate limits —
# it just means the renewal window is checked twice a day rather than once a
# month. Certificates are valid 90 days, so a renewal lands ~day 60.
#
# nginx loads the certificate files at startup and keeps them in memory, so a
# renewed certificate is not served until nginx is reloaded. This container
# cannot signal nginx directly (no docker socket, no shared PID namespace),
# so --deploy-hook instead TOUCHES A SENTINEL FILE in /etc/letsencrypt, which
# is bind-mounted read-write into BOTH containers. A background watcher in
# nginx/entrypoint.sh polls for that file, deletes it and runs `nginx -s
# reload`. certbot only fires a deploy hook when a certificate was actually
# renewed, so the sentinel appears roughly once every 60 days, not twice a
# day. --deploy-hook is passed to both `certonly` and `renew`.
#
# The alternative — giving this container the docker socket so the hook could
# `docker exec nginx nginx -s reload` — was rejected: the socket is
# root-equivalent on the host, and the shared cert directory is a capability
# both containers already have.
#
# ENV VARS REQUIRED (from ./.env via `env_file`)
# DOMAIN apex domain; both $DOMAIN and www.$DOMAIN go on one certificate,
# filed under --cert-name $DOMAIN so the path nginx expects
# (/etc/letsencrypt/live/$DOMAIN/) is stable regardless of which
# name certbot would otherwise have chosen.
# EMAIL registration/expiry-notice address for the ACME account.
#
# FLAGS WORTH KNOWING
# --agree-tos --non-interactive never prompt; required in a container.
# --expand if a cert already exists under this name but
# covers a different set of names, replace it
# rather than erroring out.
#
# ASSUMES EXISTS
# /var/www/certbot (shared ACME webroot, served by nginx on port 80)
# /etc/letsencrypt (persistent cert store, shared with nginx)
# 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
# entrypoint polls for. Touching it is the entire "tell nginx to reload" signal
# — see RELOAD SIGNAL above.
RELOAD_SENTINEL=/etc/letsencrypt/.nginx-reload
certbot certonly --webroot -w /var/www/certbot \
--email "${EMAIL}" \
-d "${DOMAIN}" -d "www.${DOMAIN}" \
--cert-name "${DOMAIN}" \
--deploy-hook "touch ${RELOAD_SENTINEL}" \
--agree-tos --non-interactive --expand;
# Exit promptly on `docker compose stop` instead of sitting out the 12h sleep.
trap exit TERM;
while :; do
certbot renew --webroot -w /var/www/certbot \
--deploy-hook "touch ${RELOAD_SENTINEL}";
sleep 12h;
done