# Ramphearth self-host proxy (Caddy + caddy-l4), baked into the image built from
# packages/web/Dockerfile and mounted read-only over it by the compose files, so
# an edit here applies with `docker compose restart proxy`.
#
# {$VAR} placeholders come from the container environment. proxy-entrypoint.sh
# derives the computed ones before Caddy starts:
#   CADDY_TLS  "internal" for localhost/*.localhost, else ACME_EMAIL (ACME on 80/443)
#   ACME_MODE  default (Let's Encrypt, ZeroSSL as fallback) | ca (ACME_CA) |
#              ca_root (ACME_CA, trusting ACME_CA_ROOT for its HTTPS)
#   CSP, HSTS  built from PUBLIC_URL and LIVEKIT_WS_URL (+ PORTAL_EMBED_URL)
#   EMBED_MODE on (PORTAL_EMBED_URL set: EMBED_HOST is its hostname) | off
#   PROXY_ROLE all (one box) | app (two-box app box) | media (two-box media box)
#
# What it routes, on one public TLS port (443 inside the container):
#   PUBLIC_HOST   the SPA; /api/* -> server:4000 with /api stripped (the REST API
#                 and the /api/ws WebSocket); /rtc* -> LiveKit on a single box
#   EMBED_HOST    client portals' embedded tools (PORTAL_EMBED_URL, optional): only
#                 GET /embed/<handle> -> server:4000; anything else there is a 404
#   LIVEKIT_HOST  LiveKit signalling (wss) -> livekit:7880
#   TURN_HOST     TURN over TLS: caddy-l4 picks the connection out by SNI before
#                 the HTTP server sees it, terminates TLS and hands the TURN bytes
#                 to livekit:5349 (LiveKit runs turn.external_tls). Production
#                 parity: corporate networks that only allow 443 still connect.

# Which ACME server issues the certificates (global options import one). The
# default is Caddy's own: Let's Encrypt, with ZeroSSL as a fallback. ACME_CA
# points every ACME certificate at one other directory (a private CA such as
# step-ca, or Pebble in scripts/selfhost/test-local-server.sh) with no public
# fallback; ACME_CA_ROOT is a PEM file inside this container to trust for that
# server's own HTTPS. localhost sites keep `tls internal` either way.
(acme_default) {
}
(acme_ca) {
	cert_issuer acme {$ACME_CA}
}
(acme_ca_root) {
	cert_issuer acme {$ACME_CA} {
		trusted_roots {$ACME_CA_ROOT}
	}
}

{
	# (":default" keeps an older proxy image, whose entrypoint never sets
	# ACME_MODE, working with this file.)
	import acme_{$ACME_MODE:default}

	# Redirects are explicit below: with a non-443 HTTPS_PORT the automatic ones
	# would point at the container's port, not the published one.
	auto_https disable_redirects

	# TURN/TLS on the HTTPS port. Connections whose TLS SNI is TURN_HOST are taken
	# by the layer4 route; every other connection falls through to the normal TLS
	# + HTTP server, which still sees the real client address (no PROXY-protocol
	# hop). On the two-box app box (no TURN there) the entrypoint sets TURN_HOST
	# to turn.invalid, which no client ever sends.
	servers :443 {
		listener_wrappers {
			layer4 {
				@turn tls sni {$TURN_HOST}
				route @turn {
					tls
					proxy {$TURN_UPSTREAM}
				}
			}
			tls
		}
	}
}

# Security headers for the SPA — the self-host twin of packages/web/public/_headers
# (read the directive notes there). The API sets its own headers.
(spa_headers) {
	header {
		Content-Security-Policy "{$CSP}"
		Strict-Transport-Security "{$HSTS}"
		X-Content-Type-Options "nosniff"
		Referrer-Policy "strict-origin-when-cross-origin"
		X-Frame-Options "DENY"
		Permissions-Policy "microphone=(self), camera=(self), display-capture=(self), fullscreen=(self), autoplay=(self), geolocation=(), payment=(), usb=(), serial=(), hid=(), bluetooth=(), midi=(), magnetometer=(), gyroscope=(), accelerometer=(), browsing-topics=()"
		-Server
	}
}

(spa) {
	handle {
		root * /srv
		import spa_headers
		# Hashed bundles never change; everything else revalidates (sw.js must,
		# so a new service worker ships with the next deploy).
		@assets path /assets/*
		header @assets Cache-Control "public, max-age=31536000, immutable"
		@revalidate not path /assets/*
		header @revalidate Cache-Control "no-cache"
		@manifest path /manifest.webmanifest
		header @manifest Content-Type "application/manifest+json"
		@aasa path /apple-app-site-association
		header @aasa Content-Type "application/pbinfo+json"
		@assetlinks path /.well-known/assetlinks.json
		header @assetlinks Content-Type "application/json"
		# Booking links (§EI): public booking pages live at /book/... on this install (BOOKING_PUBLIC_URL blank).
		@book path /book /book/*
		rewrite @book /book-app.html
		# Tickets (§FB T4): the public ticket form + status page live at /help/... (TICKETS_PUBLIC_URL blank).
		@help path /help /help/*
		rewrite @help /tickets-app.html
		# Engage's website chat box lives at /engage/... (ENGAGE_PUBLIC_URL blank); its script is /engage-embed.js.
		@engage path /engage /engage/*
		rewrite @engage /engage-app.html
		try_files {path} /index.html
		file_server
	}
}

(api) {
	# The SPA calls /api/...; the server's routes have no prefix. reverse_proxy
	# passes WebSocket upgrades through (/api/ws -> /ws) and sets X-Forwarded-For,
	# which the server trusts from private addresses (TRUST_PROXY default).
	handle_path /api/* {
		reverse_proxy {$API_UPSTREAM}
	}
	# OAuth and MCP discovery (§BN-v). Clients look for the metadata at the
	# host's root, with the API's path after the well-known prefix (RFC 8414
	# §3.1, RFC 9728 §3.1: /.well-known/oauth-authorization-server/api/oauth,
	# /.well-known/oauth-protected-resource/api/mcp). The SPA would answer
	# those with index.html, which an MCP client can't parse, so they go to the
	# server unchanged (it serves them; anything else there is a 404).
	@oauth_discovery path /.well-known/oauth-authorization-server /.well-known/oauth-authorization-server/* /.well-known/openid-configuration /.well-known/openid-configuration/* /.well-known/oauth-protected-resource /.well-known/oauth-protected-resource/*
	handle @oauth_discovery {
		reverse_proxy {$API_UPSTREAM}
	}
}

# The embedded tools' frame page (docs/PORTAL_EMBEDS_PLAN.md) on its own hostname:
# never PUBLIC_HOST, whose origin holds the sign-in cookie. The server answers it
# only on this host and answers nothing else here (registerEmbedHostGate).
(embed_site_on) {
	{$EMBED_HOST} {
		tls {$CADDY_TLS}
		@frame {
			method GET
			path_regexp ^/embed/[^/]+$
		}
		handle @frame {
			reverse_proxy {$API_UPSTREAM}
		}
		handle {
			respond 404
		}
	}
	http://{$EMBED_HOST} {
		redir https://{host}{uri} permanent
	}
}
(embed_site_off) {
	# PORTAL_EMBED_URL unset: no frame page site.
}

(role_all) {
	import embed_site_{$EMBED_MODE:off}
	{$PUBLIC_HOST} {
		tls {$CADDY_TLS}
		encode zstd gzip
		import api
		# LiveKit on the app hostname too, so a single-hostname install (localhost
		# mode: LIVEKIT_WS_URL=wss://localhost:<port>) needs one certificate.
		handle /rtc* {
			reverse_proxy {$LIVEKIT_UPSTREAM}
		}
		import spa
	}
	import livekit_sites
	http://{$PUBLIC_HOST} {
		redir {$PUBLIC_URL}{uri} permanent
	}
}

(role_app) {
	import embed_site_{$EMBED_MODE:off}
	{$PUBLIC_HOST} {
		tls {$CADDY_TLS}
		encode zstd gzip
		import api
		import spa
	}
	http://{$PUBLIC_HOST} {
		redir {$PUBLIC_URL}{uri} permanent
	}
}

(role_media) {
	import livekit_sites
}

(livekit_sites) {
	{$LIVEKIT_HOST} {
		tls {$CADDY_TLS}
		reverse_proxy {$LIVEKIT_UPSTREAM}
	}
	# Only TLS connections with this SNI reach TURN (above); this block exists so
	# Caddy obtains and renews the TURN certificate, and answers plain HTTPS.
	{$TURN_HOST} {
		tls {$CADDY_TLS}
		respond "TURN endpoint" 404
	}
	http://{$LIVEKIT_HOST}, http://{$TURN_HOST} {
		redir https://{host}{uri} permanent
	}
}

import role_{$PROXY_ROLE}
