# Harmony's self-host/Caddyfile (v1.9.6, AGPL-3.0-or-later with the additional
# terms in Harmony's LICENSE-ADDITIONAL-TERMS.md; https://github.com/y4my4my4m/harmony),
# changed for Kubernetes by ansible-role-harmony: ingress-nginx terminates TLS, so
# auto_https and the admin API are off, every site is plain http:// and the
# `tls` lines are gone, and /register redirects to {$SIGNUP_URL}. Service names resolve through the namespace's search domain.
# Re-diff against upstream on every Harmony upgrade.
# =============================================================================
# Harmony reverse proxy (Caddy)
# =============================================================================
#   https://{$DOMAIN}          app (web) + federation backend + bot gateway
#   https://{$DB_DOMAIN}       Supabase API gateway (Kong)
#   https://{$LIVEKIT_DOMAIN}  LiveKit, defined only when ENABLE_VOICE=true
#
# {$CADDY_TLS} is a contact email (public ACME) or the word "internal" (Caddy's
# local CA, for LAN/NAS without public DNS).
#
# Routing mirrors dev/nginx-harmony.template.conf location by location. nginx
# matches paths case-sensitively, hence path_regexp below where Caddy's `path`
# matcher would fold case.
# =============================================================================

# {client_ip} is the peer address, or the rightmost X-Forwarded-For entry outside
# trusted_proxies when the peer is inside them; entries further left are the client's own.
# Private peers (a proxy on this host or LAN, a Cloudflare Tunnel's cloudflared) and Cloudflare
# edges are trusted: such a client gets its real address with nothing configured. A private peer
# can name any address, and without this it is exempt from every limit anyway.
# CADDY_TRUSTED_PROXIES adds a proxy with a public address.
# Ranges: cloudflare.com/ips-v4, ips-v6, 2026-11-08.
{
	auto_https off
	admin off
	servers {
		trusted_proxies static private_ranges {$CADDY_TRUSTED_PROXIES:} 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
		trusted_proxies_strict
	}
}

# X-Real-IP is the address the federation backend keys its rate limits on
# (TRUST_PROXY names the trusted peers).
(federation_upstream) {
	reverse_proxy federation-server:3001 {
		header_up X-Real-IP {client_ip}
	}
}

# Voice site, imported as voice-{$ENABLE_VOICE}. Without voice no site block
# exists for the live domain, so Caddy requests no certificate for it.
(voice-true) {
	http://{$LIVEKIT_DOMAIN} {
		# WebSocket upgrades pass through; streams have no read timeout.
		reverse_proxy livekit:7880 {
			header_up X-Real-IP {client_ip}
		}
	}
}
(voice-false) {
}

# --- Main app + federation ---------------------------------------------------
http://{$DOMAIN} {
	# eom.dev: accounts are made on the members page (ansible-role-harmony;
	# the web app's /eom/theme.js covers in-app navigation).
	redir /register {$SIGNUP_URL} 302
	redir /register/ {$SIGNUP_URL} 302

	encode zstd gzip

	# nginx: client_max_body_size 50M.
	request_body {
		max_size 50MB
	}

	# nginx adds these on every response; `?` keeps a value the upstream set.
	# The YouTube relay and the player page are framed by the native apps, and invite widgets by
	# any website; these carry frame-ancestors instead.
	@notYouTubeRelay not path /youtube-embed.html /embed-player.html /api/federation/widget/*
	header @notYouTubeRelay {
		?X-Frame-Options SAMEORIGIN
		?X-Content-Type-Options nosniff
		?X-XSS-Protection "1; mode=block"
		?Referrer-Policy strict-origin-when-cross-origin
	}

	# --- Federation backend ----------------------------------------------------

	# WebFinger, host-meta, NodeInfo discovery. CORS open as in nginx; the
	# deferred set replaces rather than duplicates a value from the backend.
	@fedDiscovery path_regexp ^/\.well-known/(webfinger|host-meta|host-meta\.json|nodeinfo)$
	handle @fedDiscovery {
		header Access-Control-Allow-Origin "*" {
			defer
		}
		import federation_upstream
	}

	@fedNodeinfo path_regexp ^/nodeinfo/2\.(0|1)$
	handle @fedNodeinfo {
		header Access-Control-Allow-Origin "*" {
			defer
		}
		import federation_upstream
	}

	# Shared inbox, oEmbed, actor collections, FEP-044f quote authorizations,
	# Group actors, post collections: always ActivityPub. Outboxes are per actor;
	# no shared outbox exists.
	@fedExact path_regexp ^/(inbox|oembed)$
	handle @fedExact {
		import federation_upstream
	}
	@fedActorCollections path_regexp ^/users/[^/]+/(inbox|outbox|followers|following|featured)$
	handle @fedActorCollections {
		import federation_upstream
	}
	@fedQuoteAuthorizations path_regexp ^/users/[^/]+/quote_authorizations/[^/]+$
	handle @fedQuoteAuthorizations {
		import federation_upstream
	}
	@fedServers path_regexp ^/servers/
	handle @fedServers {
		import federation_upstream
	}
	@fedPostCollections path_regexp ^/posts/[0-9a-f-]+/(likes|shares|replies|context)
	handle @fedPostCollections {
		import federation_upstream
	}
	# Chat and direct message Notes; the backend answers 406 to any other Accept.
	@fedMessages path_regexp ^/messages/[0-9a-f-]+$
	handle @fedMessages {
		import federation_upstream
	}
	# Threads, their members and a channel's threads; 406 to any other Accept, as messages.
	@fedThreads path_regexp ^/(threads/[0-9a-f-]+(/members)?|channels/[0-9a-f-]+/threads)$
	handle @fedThreads {
		import federation_upstream
	}

	# Post permalinks: the backend negotiates (AP Note JSON for fediverse
	# clients, HTML with OpenGraph tags for browsers and crawlers).
	@fedPost path_regexp ^/posts/[0-9a-f-]+$
	handle @fedPost {
		import federation_upstream
	}

	# Server invite links: link-preview crawlers get the backend's OpenGraph card, people the
	# SPA, at one URL. Crawler list as in the nginx map; the backend checks the code's length.
	# The web container serves index.html no-cache, so a shared cache revalidates per request.
	@inviteUnfurl {
		path_regexp ^/invite/[A-Za-z0-9_-]+/?$
		header_regexp User-Agent (?i)(discordbot|slackbot|twitterbot|facebookexternalhit|facebot|telegrambot|whatsapp|linkedinbot|mastodon|pleroma|akkoma|misskey|summalybot|gotosocial|friendica|lemmy|cardyb|synapse|mattermost-bot|zulipurlpreview|discourse|embedly|iframely|redditbot|skypeuripreview|microsoftpreview|vkshare|viber|kakaotalk-scrap)
	}
	handle @inviteUnfurl {
		import federation_upstream
	}

	# Drive files shared by link: link-preview crawlers get the backend's OpenGraph card of the
	# file, people the SPA. Crawler list as in the nginx map.
	@driveLinkUnfurl {
		path_regexp ^/d/[A-Za-z0-9_-]{16,64}/?$
		header_regexp User-Agent (?i)(discordbot|slackbot|twitterbot|facebookexternalhit|facebot|telegrambot|whatsapp|linkedinbot|mastodon|pleroma|akkoma|misskey|summalybot|gotosocial|friendica|lemmy|cardyb|synapse|mattermost-bot|zulipurlpreview|discourse|embedly|iframely|redditbot|skypeuripreview|microsoftpreview|vkshare|viber|kakaotalk-scrap)
	}
	handle @driveLinkUnfurl {
		import federation_upstream
	}

	# The SPA's post page, the URL people copy from the address bar: ActivityPub clients and
	# link-preview crawlers get /posts/<id> from the backend, browsers the SPA. The header
	# regexps capture nothing: a header_regexp in the same matcher fills {re.<matcher>.1}
	# too, and the rewrite would name the Accept or User-Agent match.
	@socialPostAp {
		path_regexp socialPostAp ^/social/post/([0-9a-f-]{36})/?$
		header_regexp Accept (?i)application/(?:activity|ld)\+json
	}
	handle @socialPostAp {
		rewrite * /posts/{re.socialPostAp.1}
		import federation_upstream
	}
	@socialPostUnfurl {
		path_regexp socialPostUnfurl ^/social/post/([0-9a-f-]{36})/?$
		header_regexp User-Agent (?i)(?:discordbot|slackbot|twitterbot|facebookexternalhit|facebot|telegrambot|whatsapp|linkedinbot|mastodon|pleroma|akkoma|misskey|summalybot|gotosocial|friendica|lemmy|cardyb|synapse|mattermost-bot|zulipurlpreview|discourse|embedly|iframely|redditbot|skypeuripreview|microsoftpreview|vkshare|viber|kakaotalk-scrap)
	}
	handle @socialPostUnfurl {
		rewrite * /posts/{re.socialPostUnfurl.1}
		import federation_upstream
	}

	# The app's earlier profile page; remote servers may hold it as an account's `url`.
	# ActivityPub clients get the actor from /users/<name>, a browser holding the app's cookie
	# the SPA (which moves to /@<name>), everyone else, link-preview crawlers among them, a 301
	# to /@<name>. nginx: location ~ ^/social/profile/.
	@socialProfileAp {
		path_regexp socialProfileAp ^/social/profile/([A-Za-z0-9_]+)/?$
		header_regexp Accept (?i)application/(?:activity|ld)\+json
	}
	handle @socialProfileAp {
		rewrite * /users/{re.socialProfileAp.1}
		import federation_upstream
	}
	@socialProfilePage {
		path_regexp socialProfilePage ^/social/profile/([A-Za-z0-9_]+)/?$
		not expression {http.request.cookie.harmony_app} == "1"
	}
	handle @socialProfilePage {
		redir * /@{re.socialProfilePage.1} 301
	}
	@socialProfileApp path_regexp ^/social/profile/[A-Za-z0-9_]+/?$
	handle @socialProfileApp {
		header {
			+Vary "Accept, Cookie"
			Cache-Control "private, no-cache"
			defer
		}
		reverse_proxy web:80
	}

	# Public profile and post pages, /@<name> and /@<name>/<post id>: an account's and a Note's
	# `url`. A browser that is not an ActivityPub client and holds the cookie harmony_app=1, which
	# the app sets while signed in, gets the SPA, not shared-cacheable; ActivityPub clients and
	# everyone else the backend: the actor, the Note or the page. nginx: map $public_page_app.
	@publicPageApp {
		path_regexp ^/@[^/]+(/[^/]+)?/?$
		expression {http.request.cookie.harmony_app} == "1"
		not header_regexp Accept (?i)application/(?:activity|ld)\+json
	}
	handle @publicPageApp {
		header {
			+Vary "Accept, Cookie"
			Cache-Control "private, no-cache"
			defer
		}
		reverse_proxy web:80
	}
	@publicPage path_regexp ^/@[^/]+(/[^/]+)?/?$
	handle @publicPage {
		import federation_upstream
	}

	# Create and Announce activities at the ids deliveries and outboxes carry.
	@fedActivities path_regexp ^/(users/[^/]+/)?activities/[0-9a-f-]+$
	handle @fedActivities {
		import federation_upstream
	}

	# Actor profile: ActivityPub clients get the actor, browsers the public page
	# /@<name>. nginx tests Accept with ~* (case-insensitive).
	@fedActor {
		path_regexp ^/users/[^/]+$
		header_regexp Accept (?i)application/(activity\+json|ld\+json|json)
	}
	handle @fedActor {
		import federation_upstream
	}
	@humanActor {
		path_regexp humanActor ^/users/([^/]+)$
		not header_regexp Accept (?i)application/(activity\+json|ld\+json|json)
	}
	handle @humanActor {
		# `*`: a first argument starting with / would parse as a path matcher.
		redir * /@{re.humanActor.1} 302
	}

	# Prefix locations without a trailing slash in nginx: /health matches
	# /health/maintenance, /link-preview matches /link-preview/enrich-message.
	@fedPrefix path_regexp ^/(health|link-preview)
	handle @fedPrefix {
		import federation_upstream
	}

	# LiveKit token API: mounted at /api/livekit on the backend, no rewrite.
	@fedLivekit path_regexp ^/api/livekit/
	handle @fedLivekit {
		import federation_upstream
	}

	# Federation API: the backend mounts most routes at the root only
	# (/lookup-user, /gifs/*, /invites/*, /instances/probe, /health/*, ...).
	# nginx: `location /api/federation/ { proxy_pass http://localhost:3001/; }`.
	@fedApi path_regexp ^/api/federation/
	handle @fedApi {
		uri strip_prefix /api/federation
		import federation_upstream
	}

	# Channel webhooks: GitHub deliveries reach 1 MB; the backend caps the plain route at
	# 64 KB itself.
	@fedChannelWebhooks path_regexp ^/webhooks/channels/
	handle @fedChannelWebhooks {
		request_body {
			max_size 1MB
		}
		import federation_upstream
	}

	# Donation webhooks (Ko-fi posts form-encoded bodies). nginx caps them at 64k.
	@fedWebhooks path_regexp ^/webhooks/
	handle @fedWebhooks {
		request_body {
			max_size 64KB
		}
		import federation_upstream
	}

	# --- Bot gateway (bots profile) --------------------------------------------
	# /bot-gateway/gateway is the WebSocket; the rest is the REST API. Both map
	# to the gateway's root, as nginx's `proxy_pass http://localhost:3002/;`.
	@botGateway path_regexp ^/bot-gateway/
	handle @botGateway {
		uri strip_prefix /bot-gateway
		reverse_proxy bot-gateway:3002 {
			header_up X-Real-IP {client_ip}
		}
	}

	# nginx answers a proxied prefix location requested without its trailing
	# slash with a 301 to the slashed form, query kept.
	@slashless path_regexp ^/(api/livekit|api/federation|webhooks|bot-gateway)$
	handle @slashless {
		redir * {path}/{?query} 301
	}

	# --- Frontend ----------------------------------------------------------------
	# The web container serves the SPA with its own index.html fallback and
	# cache headers (self-host/web-nginx.conf).
	handle {
		reverse_proxy web:80
	}
}

# --- Supabase API gateway ----------------------------------------------------
http://{$DB_DOMAIN} {

	# GoTrue's /logout accepts an aal1 token, and its global and others scopes
	# delete every session of the account: a password without the second factor
	# would sign every device out. Only ?scope=local passes; a missing scope is
	# GoTrue's global default. Other devices are signed out through
	# public.sign_out_my_sessions(). Same rule as dev/nginx-auth-logout.template.conf.
	# The path matcher compares the decoded, cleaned path, case-insensitively.
	@logoutScope {
		path /auth/v1/logout /auth/v1/logout/
		not method OPTIONS
		not expression {http.request.uri.query} == "scope=local"
	}
	handle @logoutScope {
		header Content-Type application/json
		header Access-Control-Allow-Origin *
		header Cache-Control no-store
		respond `{"code":403,"error_code":"logout_scope_forbidden","msg":"Only this device can be signed out here. Sign out other devices from Settings, Sessions."}` 403
	}

	# imgproxy answers a public render in WebP when Accept names image/webp and
	# in the source format otherwise, under one ETag and without Vary. A cache
	# in front (Cloudflare) would serve one client's format to all; the pinned
	# Accept makes every render WebP. Every Harmony client decodes WebP. Same
	# rule as the nginx Accept pin in docs/self-host/docker-compose.md.
	@publicRender path /storage/v1/render/image/public/*
	request_header @publicRender Accept "image/webp,*/*;q=0.8"

	# Public storage reads through the disk cache (media-cache.conf): a boosted post's
	# media is fetched by every server that receives it. message_media is a private bucket.
	@publicMedia {
		method GET HEAD
		path /storage/v1/object/public/* /storage/v1/render/image/public/*
		not path /storage/v1/object/public/message_media/* /storage/v1/render/image/public/message_media/*
	}
	handle @publicMedia {
		reverse_proxy media-cache:8080
	}

	# Sb-Forwarded-For: the client address of GoTrue's per-IP limiters and its sign-up hook.
	# Always overwritten; Kong forwards a client's value unchanged. Absent, so no limiter
	# runs, for a private address (the instance's LAN) and for a token refresh (auth-js signs out on a 429 there, and a refresh token cannot be
	# guessed). Same rule as dev/nginx-auth-client-ip.template.conf.
	@privateClient client_ip private_ranges
	handle @privateClient {
		reverse_proxy supabase-kong:8000 {
			header_up -Sb-Forwarded-For
		}
	}
	@tokenRefresh {
		path /auth/v1/token
		expression {http.request.uri.query} == "grant_type=refresh_token"
	}
	handle @tokenRefresh {
		reverse_proxy supabase-kong:8000 {
			header_up -Sb-Forwarded-For
		}
	}
	handle {
		reverse_proxy supabase-kong:8000 {
			header_up Sb-Forwarded-For {client_ip}
		}
	}
}

import voice-{$ENABLE_VOICE:false}
