Files
stpweb/nginx/nginx.conf.template
adamfandClaude Opus 5.5 8d7606bbe8
Deploy with Docker Compose / deploy (push) Successful in 1m1s
Retire quartz, hasura and autoheal into .deprecated/
Quartz was already replaced by silverbullet-public; its build context moves
to .deprecated/quartz. Hasura and autoheal are removed from the stack, with
their compose services (and Hasura's nginx blocks) kept verbatim under
.deprecated/ alongside a README on how to bring each back.

Removes the /hasura/ route from both nginx templates and the envsubst
allow-list, and updates the docs and comments that referred to the three
services. With autoheal gone nothing restarts an unhealthy container; the
healthchecks are now informational only, and the docs say so.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 14:58:17 +01:00

565 lines
26 KiB
Plaintext

# =============================================================================
# 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_*, UPTIMEKUMA_*, WALLABAG_*. 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.
# =============================================================================
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.)
# upload 5r/m burst=3 - uploads are 50MB-capable and hit disk; this
# bounds how fast one IP can fill the volume.
# 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 direct client IP. Since nginx is the edge here (no
# CDN or upstream proxy in front), that is correct. If anything is ever put
# in front, these zones must switch to a trusted X-Forwarded-For or every
# visitor will share one bucket.
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=5r/m;
limit_req_zone $binary_remote_addr zone=hotel_search:10m rate=3r/m;
log_format compact
'$remote_addr "$request" $status rt=$request_time';
access_log /var/log/nginx/access.log compact;
# 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;
}
# 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;
return 301 https://www.$DOMAIN$request_uri;
}
server {
listen 443 ssl;
http2 on;
server_name www.$DOMAIN;
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;
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).
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 straight off the shared `uploads` volume
# 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.
location /uploads/ {
alias /uploads/;
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;
}
# ---- 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, /messages/upload and /graphql blocks
# 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/messages/upload {
limit_req zone=upload 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/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;
}
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/;
}
# 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;
}
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;
}
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;
}
# ---- Admin gate (/sb/, /radio/admin/, /uploads/private/) ----
# `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.
location = /internal/auth/admin-validate {
internal;
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;
}
}
}