Version banner, File locations section, final CSP (no unsafe-inline styles, frame-src none, object-src none)

The MTR viewer draws PDFs with pdf.js instead of an iframe the server's frame-ancestors refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-30 17:50:05 -06:00
co-authored by Claude Opus 5.5
parent da31b0a87a
commit 6e820ba0a5
17 changed files with 845 additions and 49 deletions
+33 -14
View File
@@ -8,20 +8,37 @@ import time
from starlette.datastructures import MutableHeaders
from starlette.types import ASGIApp, Message, Receive, Scope, Send
CSP = "; ".join(
[
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'", # React inline styles; tighten in phase 10
"img-src 'self' data: blob:",
"font-src 'self'",
"connect-src 'self'",
"worker-src 'self' blob:", # pdf.js
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
]
)
def _policy(object_src: str) -> str:
return "; ".join(
[
"default-src 'self'",
# The built bundle only: Vite emits no inline script, and pdf.js 6 needs no eval (wasm stays off).
"script-src 'self'",
# No 'unsafe-inline'. React style props and pdf.js set CSSOM properties, which CSP allows. The print
# rules live in theme.css; pdf.js adds fonts through the FontFace API, not a <style> element.
"style-src 'self'",
# blob: for the page images printPdf.ts draws before it opens the print dialog. No data: images.
"img-src 'self' blob:",
"font-src 'self'",
"connect-src 'self'",
# The pdf.js worker is a same-origin file from the build, so it needs no blob: wrapper.
"worker-src 'self'",
# No frames: PDFs draw on a canvas through pdf.js, and "Open in new tab" is a top-level page.
"frame-src 'none'",
f"object-src {object_src}",
"frame-ancestors 'none'",
"base-uri 'self'",
"form-action 'self'",
]
)
CSP = _policy("'none'")
# A PDF opened in its own tab is a plugin document: Chrome checks the PDF's own URL against object-src, so 'none'
# would leave the tab blank. The PDF runs none of our script, so 'self' there costs nothing.
PDF_CSP = _policy("'self'")
HEADERS: dict[str, str] = {
"Strict-Transport-Security": "max-age=31536000; includeSubDomains",
@@ -52,6 +69,8 @@ class SecurityHeadersMiddleware:
headers = MutableHeaders(scope=message)
for k, v in HEADERS.items():
headers[k] = v
if headers.get("content-type", "").lower().startswith("application/pdf"):
headers["Content-Security-Policy"] = PDF_CSP
if is_api:
headers["Cache-Control"] = "no-store"
await send(message)