diff --git a/.env.example b/.env.example
index 3c3ce62..be5c731 100644
--- a/.env.example
+++ b/.env.example
@@ -11,8 +11,8 @@ APP_ENV=production
APP_BASE_URL=http://localhost
# Where this module is mounted on the platform: /sygna. Empty = standalone, at the root of its
-# own host. Whatever is set here reaches uvicorn as --root-path too, and the reverse proxy in
-# front must strip the same prefix — the two are one decision (see Caddyfile).
+# own host. Whatever is set here reaches uvicorn as --root-path too, and the front door must
+# strip the same prefix (Atrium forwards /sygna/* without it) — the two are one decision.
ROOT_PATH=
# ── Database ─────────────────────────────────────────────────────────────────
@@ -184,9 +184,18 @@ GALENA_EMBED=false
# Point a container restart policy at the first and a load balancer at the second. Using the
# first for both is how a dead instance keeps its share of the traffic.
-# ── Reverse proxy ────────────────────────────────────────────────────────────
-# Plain HTTP on :80 by default. Set to your domain for automatic TLS.
-CADDY_SITE_ADDRESS=:80
+# ── The edge (no reverse proxy) ──────────────────────────────────────────────
+# The backend serves the console and sets its own security headers; docker-compose.yml publishes it
+# on :80, plain HTTP. For TLS put your own terminator in front, or run Sygna on the platform.
+#
+# Which upstream IPs uvicorn trusts for X-Forwarded-For / X-Forwarded-Proto, so the real client IP
+# lands in the audit log. Empty = loopback only (the image's default), right for this stack, where
+# nothing sits in front of the backend. Behind your own TLS terminator, set its address or subnet;
+# never `*`. docker-compose.yml sets it empty, overriding this line.
+FORWARDED_ALLOW_IPS=
+# Who may frame Sygna: 'none' (default; X-Frame-Options DENY) or 'self' (SAMEORIGIN). Anything else
+# refuses start-up.
+FRAME_ANCESTORS='none'
# ── OpenTelemetry (opt-in) ───────────────────────────────────────────────────
OTEL_ENABLED=false
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index bb5f0d6..fa4c6f6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -99,7 +99,7 @@ jobs:
- name: Deploy pre-flight
working-directory: backend
# Catches the failures the test suite cannot: a setting the code reads that .env.example
- # never mentions, a healthcheck aimed at a route that moved, a Caddy matcher that misses
+ # never mentions, a healthcheck aimed at a route that moved, a console mount that swallows
# the API prefix.
run: python scripts/deploy_check.py
- name: Shared-file drift vs Galena
@@ -308,9 +308,9 @@ jobs:
# ── the deployment itself ─────────────────────────────────────────────────────
# Everything above runs Sygna from source against a Postgres service container. None of it
- # executes docker-compose.yml, the Dockerfile, the Caddyfile or db/init — they were verified only
+ # executes docker-compose.yml, the Dockerfile or db/init — they were verified only
# by deploy_check.py READING them, and the machine this project is developed on cannot run
- # containers at all (a VM without nested virtualization). This job is the first place those four
+ # containers at all (a VM without nested virtualization). This job is the first place those three
# files run. It found on its first attempt that the image could not be built by anyone, since the
# private dredd-core dependency needs git and a credential and the slim image had neither.
compose-smoke:
@@ -338,10 +338,10 @@ jobs:
DREDD_CORE_TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
run: docker compose up -d --build
- - name: Wait for readiness through Caddy
- # Caddy starts only once the backend's deep healthcheck passes, and the backend only once the
- # migration has completed — so one successful response here proves the whole ordering:
- # postgres healthy → migrate + seed → backend ready → proxy up.
+ - name: Wait for readiness on the published port
+ # The backend starts only once the migration has completed, and it is published on :80
+ # itself (no proxy) — so one successful deep response here proves the whole ordering:
+ # postgres healthy → migrate + seed → backend ready.
run: |
for i in $(seq 1 60); do
if curl -fsS "http://localhost/healthz?deep=1" >/dev/null 2>&1; then
@@ -353,7 +353,7 @@ jobs:
docker compose ps
exit 1
- - name: Drive it through the proxy
+ - name: Drive it through the published port
run: |
set -euo pipefail
echo "--- liveness and readiness"
@@ -364,6 +364,16 @@ jobs:
headers=$(curl -fsSI http://localhost/)
echo "$headers" | grep -qi "content-security-policy" || { echo "::error::no CSP on the console"; exit 1; }
echo "$headers" | grep -qi "x-frame-options: DENY" || { echo "::error::console is frameable"; exit 1; }
+ echo "$headers" | grep -qi "referrer-policy: same-origin" || { echo "::error::no Referrer-Policy"; exit 1; }
+ echo "$headers" | grep -qi "cross-origin-opener-policy: same-origin" || { echo "::error::no COOP"; exit 1; }
+ echo "$headers" | grep -qi "cache-control: no-cache" || { echo "::error::console not revalidated"; exit 1; }
+ if echo "$headers" | grep -qi "^server:"; then echo "::error::Server header leaked"; exit 1; fi
+
+ echo "--- a deep link survives a reload (SPA fallback), the API never falls to the console"
+ curl -fsS http://localhost/matters/1 | grep -q "
Sygna" || { echo "::error::no SPA fallback"; exit 1; }
+ code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost/api/v1/nope)
+ [ "$code" = "404" ] || { echo "::error::unknown API path answered $code"; exit 1; }
+ curl -s http://localhost/api/v1/nope | jq -e '.status == 404' >/dev/null || { echo "::error::unknown API path is not a problem response"; exit 1; }
curl -fsS http://localhost/ | grep -q "Sygna" || { echo "::error::console did not render"; exit 1; }
echo "--- log in as the seeded administrator"
diff --git a/CLAUDE.md b/CLAUDE.md
index e5e9576..2cbe0c2 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -7,7 +7,7 @@ Guidance for Claude Code when working in this repository.
**Sygna** — practice management (CRM + matters + time) for **Polish law firms**. It is a **module
of the Dredd platform**, served under the path **`/sygna`** alongside Atrium, Galena and Counsel.
Stack: **FastAPI + SQLAlchemy 2 + Alembic + PostgreSQL 16 / 17**, Argon2id auth + server-side
-cookie sessions, a **no-build static console** (vanilla JS), Docker Compose + Caddy. License
+cookie sessions, a **no-build static console** (vanilla JS), Docker Compose (no reverse proxy — the backend is its own edge). License
**Apache-2.0**; every dependency is permissive (no copyleft).
**One platform, one account, one admin pane.** The family runs at one origin, one module per path
@@ -96,7 +96,7 @@ frontend/ index.html · app.css · app.js (no build step, PL-firs
db/init/ 01-roles.sh (creates the app + migrator roles)
db/managed/ provision.sql (dredd-core's rendering, CI-checked) · README.md (Sygna's runbook
in the family's shared managed database, plus the database-wide checklist)
-docker-compose.yml · docker-compose.managed-db.yml · Caddyfile · .env.example · .github/workflows/ci.yml
+docker-compose.yml · docker-compose.managed-db.yml · .env.example · .github/workflows/ci.yml
docs/CRMecenas-Discovery-Report.md (research; §4 superseded by PLAN.md)
```
@@ -107,7 +107,7 @@ DREDD_CORE_TOKEN=… docker compose up -d --build # full stack; the token is a
cd backend && pytest # DB-free unit tests; integration auto-skips
SYGNA_RUN_INTEGRATION=1 pytest # full API loop (needs a migrated+seeded Postgres)
python scripts/license_gate.py # CI license gate locally
-python scripts/deploy_check.py # compose/Dockerfile/Caddyfile/.env coherence
+python scripts/deploy_check.py # compose/Dockerfile/edge/.env coherence
python scripts/deploy_check.py --env ../.env # + the managed-database URLs (TLS, pooler, roles)
python -m app.restore [NAME --yes] # list backups / restore one, one-shot (needs the migrator URL)
python -m dredd_core.managed check --url DATABASE_URL --expect-schema sygna --require-tls \
@@ -570,6 +570,24 @@ BOOTSTRAP_ADMIN_PASSWORD=… python scripts/walkthrough.py # drive the whole p
- **Console security:** `esc()` every dynamic value; bearer token in memory only, cookie session
primary; nothing loads from a CDN (the CSP has no third-party origins). `frame-src` names
Galena's origin only when `GALENA_EMBED` is on.
+- **No Caddy, anywhere.** On the platform Atrium's backend is the front door and forwards
+ `/sygna/*` here with the prefix stripped (uvicorn's `--root-path "$ROOT_PATH"` puts it back);
+ standalone, `docker-compose.yml` publishes the backend on :80 with nothing in front. The backend
+ is its own edge (`app/edge.py`, wired in `main.py`): it serves the console (`frontend/`,
+ `/frontend` in the image via the `frontend` build context) at `/` LAST, behind
+ `ConsoleUnlessApi`, so `/api/*` and `/healthz` never fall to it (unknown → 404 problem, wrong
+ method → 405 + `Allow`); any other GET for a missing file gets `index.html` (Caddy's
+ `try_files {path} /index.html`). `SecurityHeaders` (pure ASGI, outermost) stamps every response,
+ errors included, with Caddy's set (except Referrer-Policy, the family's `same-origin`):
+ nosniff, X-Frame-Options, `Referrer-Policy: same-origin`, `Cross-Origin-Opener-Policy: same-origin`; the console (not
+ the API — `/api/v1/docs` is Swagger from a CDN) also gets the CSP and `Cache-Control: no-cache`.
+ `FRAME_ANCESTORS` is `'none'` (default, XFO DENY) or `'self'` (SAMEORIGIN); anything else
+ refuses start-up. No HSTS (Caddy never sent one here). Also gzip (min 1000 B), a 100 MB
+ request-body cap (`BodySizeLimit`, 413), and uvicorn `--proxy-headers --forwarded-allow-ips
+ "${FORWARDED_ALLOW_IPS:-127.0.0.1}" --no-server-header` — those flags live ONLY in
+ `backend/Dockerfile`'s CMD, never a compose `command:`. `FORWARDED_ALLOW_IPS` is never `*`
+ (the port is published). Every path comparison reads `get_route_path(scope)`, never
+ `request.url.path` (ROOT_PATH).
- **Icons are Tabler (MIT), path data vendored into the `ICN` map** — the same family Galena
uses, so the two consoles match in a shared launcher. Never load them from a CDN; see
CREDITS.md for the list.
@@ -669,8 +687,9 @@ has to be **provisioned** with `--identity-schema` before the hub grants any tie
schema, and `USAGE` comes from provisioning. db/managed/README.md §4a has the sequence.
**The container stack runs in CI** (`compose-smoke`, 2026-09-12): the image builds, compose brings
-postgres → migrate+seed → backend → Caddy up in order, and the job logs in through the proxy,
-reads the seeded matters, checks the console's CSP and frame headers, and confirms from inside
+postgres → migrate+seed → backend (published on :80) up in order, and the job logs in through
+that port, reads the seeded matters, checks the console's security headers, the SPA fallback and
+that an unknown API path is a 404 problem rather than the console, and confirms from inside
the database container that the `app` role is refused on `audit_log` and `conflict_check`. It is
the only place those files execute — the development machine is a VM without nested
virtualization and cannot run containers. **Building the image needs `DREDD_CORE_TOKEN`** as a
diff --git a/CREDITS.md b/CREDITS.md
index 1ae3e42..481f459 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -34,7 +34,6 @@ same palette. Only the hex values are used, not the stylesheet.
| httpx | BSD-3-Clause |
| OpenTelemetry SDK + instrumentation | Apache-2.0 |
| PostgreSQL | PostgreSQL Licence |
-| Caddy | Apache-2.0 |
## Data sources
diff --git a/Caddyfile b/Caddyfile
deleted file mode 100644
index 1a87f77..0000000
--- a/Caddyfile
+++ /dev/null
@@ -1,64 +0,0 @@
-# Caddy serves the static console and reverse-proxies the API to the backend.
-# Default: plain HTTP on :80. For TLS, set CADDY_SITE_ADDRESS to your domain in .env
-# (Caddy then provisions a certificate automatically).
-#
-# ── This is the STANDALONE shell. The platform's shell lives in Atrium ───────
-# The family runs at ONE ORIGIN, one module per path — /atrium, /galena, /sygna, /counsel — and
-# that site block is in Atrium's deploy tree, not here. This file stays for running Sygna on its
-# own: one app at `/`, with ROOT_PATH empty. Same image, same console, both ways; what differs is
-# the .env and which Caddyfile is in front.
-#
-# ── If you do mount this under a path, it is ONE decision, never two ─────────
-#
-# handle_path /sygna/* (Caddy strips) ⟺ --root-path /sygna (uvicorn prepends)
-#
-# uvicorn prepends `root_path` to the request path, on the assumption that the proxy already
-# stripped it. So plain `handle` plus `--root-path` doubles the prefix and 404s everything, and
-# stripping without `--root-path` makes every server-generated URL escape the prefix. There is no
-# X-Forwarded-Prefix support anywhere in the chain; the prefix has to be an explicit flag.
-#
-# ── The rejection of path mounting that used to be written here was wrong ────
-# It said path mounting was "considered and rejected — both consoles assume root-relative asset
-# and API paths, so it is a rewrite of two frontends to save one DNS record". Both halves were
-# false. Every asset reference in every console is already document-relative (`href="app.css"`,
-# `src="app.js"`), every route is a hash fragment the server never sees, and every API call
-# funnels through one constant — so the real cost was one line per console (`const API = new
-# URL('api/v1', document.baseURI).pathname`) and one flag per backend. Do not re-derive the old
-# conclusion from the old premise.
-#
-# ── The embedded case file, at one origin ────────────────────────────────────
-# The session-cookie half of the old plan dissolves: Galena's cookie is this origin's cookie, so
-# there is no parent-domain scoping to arrange and no SameSite dance. The CSP half does not —
-# Galena still defaults to `frame-ancestors 'none'` and `GALENA_FRAME_ANCESTORS` takes an origin
-# list, so enabling the embed is still a deliberate change in the GALENA repository. Until it is
-# made, leave GALENA_EMBED=false: Sygna links to the case file instead, and says so.
-{$CADDY_SITE_ADDRESS::80} {
- encode gzip
-
- # API + health → backend
- @api path /api/v1/* /healthz
- handle @api {
- reverse_proxy backend:8000
- }
-
- # Everything else → the static console (SPA fallback to index.html)
- handle {
- root * /srv
- try_files {path} /index.html
- # Revalidate the console assets (ETag) so a rebuilt app.js/app.css is picked up
- # without a manual hard refresh.
- header Cache-Control "no-cache"
- # Content-Security-Policy for the console. 'unsafe-inline' covers the theme
- # pre-paint inline script + inline style attributes. No third-party origins:
- # Sygna's console loads nothing from a CDN.
- header Content-Security-Policy "default-src 'self'; base-uri 'self'; object-src 'none'; frame-ancestors 'none'; form-action 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; connect-src 'self'"
- file_server
- }
-
- header {
- X-Content-Type-Options nosniff
- X-Frame-Options DENY
- Referrer-Policy strict-origin-when-cross-origin
- Cross-Origin-Opener-Policy same-origin
- }
-}
diff --git a/README.md b/README.md
index 8bc824b..cc1eb42 100644
--- a/README.md
+++ b/README.md
@@ -55,8 +55,11 @@ cp .env.example .env # then edit the passwords
docker compose up -d --build
```
-Postgres → migrate (+seed) → backend → Caddy on `:80`. Only Caddy is published; the backend and
-database are expose-only. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
+Postgres → migrate (+seed) → backend on `:80`. There is no reverse proxy: the backend serves the
+API, the console and its own security headers, and is the only published service; the database is
+expose-only. For HTTPS put your own TLS terminator in front (and set `FORWARDED_ALLOW_IPS` to its
+address), or run Sygna as a module of the platform, where Atrium is the front door. `FRAME_ANCESTORS`
+(`'none'` by default, or `'self'`) decides who may frame the console. Sign in with `BOOTSTRAP_ADMIN_EMAIL` / `BOOTSTRAP_ADMIN_PASSWORD`.
### Deploying on a managed PostgreSQL provider
@@ -101,7 +104,7 @@ entirely in the browser against an invented Warsaw firm — three matters, a wal
deadline, an unpaid invoice — with the data in `localStorage` and nothing leaving the page. That
is what makes the URL something you can send to somebody. `SYGNA_DEMO=0` opts out.
-A real firm keeps the console on the **same origin** as its API, served by Caddy: everything here
+A real firm keeps the console on the **same origin** as its API, served by its own backend: everything here
is privileged material, and a proxy in front of it is one more place that sees it.
### Local development
@@ -128,8 +131,8 @@ cd backend && alembic upgrade head && python -m app.seed
cd backend && .venv/bin/python -m uvicorn app.main:app --port 8032 --app-dir .
```
-The console is served by the backend at `http://localhost:8032` (Caddy serves it directly in
-production). On Windows write `.env` **without a BOM** — see the gotchas in
+The console is served by the backend at `http://localhost:8032` (in production too: the backend
+is its own edge, with the SPA fallback and the security headers). On Windows write `.env` **without a BOM** — see the gotchas in
[`CLAUDE.md`](CLAUDE.md).
`SEED_DEMO=true` creates a small firm whose demo data is chosen to exercise the conflict engine:
diff --git a/backend/Dockerfile b/backend/Dockerfile
index 435a78b..bda4ef5 100644
--- a/backend/Dockerfile
+++ b/backend/Dockerfile
@@ -33,6 +33,13 @@ COPY --from=build /install /usr/local
WORKDIR /app
COPY . .
+# The static console, which this backend now serves itself (app/main.py mounts it at "/"; there is
+# no Caddy in front any more). It lives in the repo's frontend/, outside this build context, so it
+# arrives as a NAMED build context: compose passes `additional_contexts: { frontend: ./frontend }`,
+# and a bare build from backend/ needs `docker build --build-context frontend=../frontend .`.
+# /frontend is exactly where main.py's default (two levels above app/main.py) looks.
+COPY --from=frontend . /frontend
+
RUN useradd -m app && mkdir -p /data && chown -R app /data /app
ENV DATA_DIR=/data
USER app
@@ -40,16 +47,19 @@ USER app
EXPOSE 8000
HEALTHCHECK --interval=15s --timeout=5s --retries=10 \
CMD python -c "import urllib.request,sys; sys.exit(0 if urllib.request.urlopen('http://localhost:8000/api/v1/health').status==200 else 1)"
-# Trust X-Forwarded-For only from the reverse proxy. The default '*' is safe ONLY because the
-# backend is expose-only in docker-compose (never host-published) — Caddy is the sole ingress.
-# If you publish this port directly, set FORWARDED_ALLOW_IPS to the proxy's address so client IPs
-# in the audit log can't be spoofed.
-ENV FORWARDED_ALLOW_IPS=*
+# Which proxy may set X-Forwarded-For / -Proto. On the platform that is Atrium's front door, pinned to
+# Sygna's network in Atrium's compose.yaml; standalone the backend is published directly and nothing
+# sits in front, so the default trusts loopback only (empty means the same — `:-` below treats empty
+# as unset). Never `*`: with the port published, anyone could then forge the audit log's client IP.
+ENV FORWARDED_ALLOW_IPS=
# Where this module is mounted on the platform. Empty by default, which is the standalone stack:
-# Sygna at the root of its own host. Set ROOT_PATH=/sygna and the reverse proxy in front MUST
-# strip that prefix (`handle_path /sygna/*`) — uvicorn PREPENDS root_path to the request path, so
+# Sygna at the root of its own host. Set ROOT_PATH=/sygna and the front door MUST
+# strip that prefix (Atrium forwards `/sygna/*` without it) — uvicorn PREPENDS root_path to the request path, so
# a proxy that does not strip gives `/sygna/sygna/...` and 404s everything, and a proxy that
# strips without this flag makes every server-generated URL escape the prefix. One decision, two
# places, one variable. The HEALTHCHECK above needs no change: uvicorn prepends, Starlette strips.
ENV ROOT_PATH=
-CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --forwarded-allow-ips \"$FORWARDED_ALLOW_IPS\" --root-path \"$ROOT_PATH\""]
+# `sh -c` so the variables expand at start-up; `exec` so uvicorn keeps PID 1 and gets SIGTERM.
+# --no-server-header: nothing in front strips `Server` any more. These flags live ONLY here — no
+# compose `command:` override, here or in Atrium's compose.yaml.
+CMD ["sh", "-c", "exec uvicorn app.main:app --host 0.0.0.0 --port 8000 --root-path \"$ROOT_PATH\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-127.0.0.1}\" --no-server-header"]
diff --git a/backend/app/config.py b/backend/app/config.py
index c2a356a..c875dd7 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -31,8 +31,8 @@ class Settings(BaseSettings):
# Where this module is mounted on the platform — `/sygna` — or empty when Sygna runs
# standalone at the root of its own host. The SAME value is handed to uvicorn as
- # `--root-path` (backend/Dockerfile), because the two halves are one decision: Caddy strips
- # the prefix with `handle_path /sygna/*` and uvicorn puts it back. They read one environment
+ # `--root-path` (backend/Dockerfile), because the two halves are one decision: the front door
+ # strips the prefix (Atrium forwards `/sygna/*` without it) and uvicorn puts it back. They read one environment
# variable so they cannot be set apart; FastAPI is told as well, so /docs and the OpenAPI
# `servers` entry point at the prefixed address rather than the origin root.
root_path: str = ""
@@ -240,6 +240,22 @@ class Settings(BaseSettings):
# separately-served console in dev.
cors_allow_origins: str = ""
+ # CSP `frame-ancestors` on the console, and the matching X-Frame-Options on every response this
+ # backend sends (app/edge.py). `'none'` (the default) = nobody may frame Sygna (X-Frame-Options:
+ # DENY), what Caddy sent before this backend served its own console. `'self'` = only this
+ # origin may (SAMEORIGIN), for a platform page that embeds Sygna. Nothing else: an origin list
+ # cannot be expressed in X-Frame-Options, and a typo here must not quietly widen framing, so
+ # anything else refuses start-up. The quotes are optional (an .env loader may strip them).
+ frame_ancestors: str = "'none'"
+
+ @field_validator("frame_ancestors")
+ @classmethod
+ def _known_frame_ancestors(cls, v: str) -> str:
+ bare = v.strip().strip("'")
+ if bare not in ("none", "self"):
+ raise ValueError("FRAME_ANCESTORS must be 'none' or 'self'")
+ return f"'{bare}'"
+
# Bootstrap admin (seed)
bootstrap_admin_email: str = "admin@example.com"
bootstrap_admin_password: str = "admin12345"
diff --git a/backend/app/edge.py b/backend/app/edge.py
new file mode 100644
index 0000000..749fb99
--- /dev/null
+++ b/backend/app/edge.py
@@ -0,0 +1,223 @@
+"""What Caddy used to do in front of this backend: security headers, the body cap, the console.
+
+The platform no longer runs Caddy. Atrium's backend is the front door and forwards `/sygna/*` here
+with the prefix stripped (exactly as `handle_path /sygna/*` did), and a standalone install runs
+uvicorn on :80 with nothing in front. Either way this process now answers for everything a browser
+gets, so the rules Sygna's Caddyfile applied live here, unchanged in substance. Same shape as
+Counsel Scorecard's `app/edge.py`.
+
+**Every path comparison reads the ROUTE path** (`starlette._utils.get_route_path`), never
+`request.url.path` / `scope["path"]`: with ROOT_PATH=/sygna uvicorn re-prepends the prefix, so the
+raw path reads `/sygna/api/v1/...` and an `/api` match would silently miss, handing the API the
+console's CSP and Cache-Control, and handing unknown API paths to the console.
+"""
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+from fastapi import HTTPException as FastAPIHTTPException
+from starlette._utils import get_route_path
+from starlette.datastructures import MutableHeaders
+from starlette.exceptions import HTTPException
+from starlette.responses import JSONResponse, Response
+from starlette.routing import BaseRoute, Match
+from starlette.staticfiles import StaticFiles
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+
+# Paths the backend owns. Caddy's split was `@api path /api/v1/* /healthz` → backend, everything
+# else → the static console; nothing under these is ever answered by the console. `/api` as a
+# whole rather than `/api/v1` only: an `/api/v2/x` that renders the console's HTML with a 200 is a
+# misleading answer to a client, not a deep link.
+API_PATHS = ("/api", "/healthz")
+
+# The owner's ceiling for one request body. Caddy set none. It bounds memory; it does not shape the
+# API (document and template uploads keep their own, smaller limits).
+MAX_BODY_BYTES = 100 * 1024 * 1024
+
+
+def owns_path(path: str) -> bool:
+ return any(path == p or path.startswith(f"{p}/") for p in API_PATHS)
+
+
+def content_security_policy(frame_ancestors: str, frame_src: str = "'self'") -> str:
+ """The console's policy: Sygna's Caddyfile CSP, plus `frame-src`, with frame-ancestors from the
+ setting. 'unsafe-inline' is required by the theme pre-paint inline