Files

112 lines
4.0 KiB
Python

"""The Content-Security-Policy the static route sends (main.py), since
2026-11-15 (docs/security.md → the second pass).
Two documents get one:
* **the app shell** (``index.html``, the owner's and the guest host's) —
``script-src 'self'`` plus the hash of each inline ``<script>`` the build
ships (the theme bootstrap), ``object-src 'none'``, ``base-uri 'self'``,
``frame-ancestors 'self'``. A script injected into the app's DOM, an inline
handler or a ``javascript:`` URL (a link, an iframe ``src``) does not run on
the app's origin. Nothing else is restricted: styles, images, connections
and frames stay as they were (forms keep inline ``style=""``, the ask-form
and deploy previews are cross-origin frames).
* **the sandbox frame page** (``sandbox-frame.html``, where a form's scripted
HTML is written — ``frontend/src/lib/sandboxFrame.ts``) — ``sandbox
allow-scripts …``: an opaque origin whoever loads it, however. It has no
``script-src``: the form author's scripts and CDN libraries are the point,
and they run with no access to the app. The flags are the frontend's
``SANDBOX`` (the ``<iframe>`` attribute); ``test_csp.py`` holds them equal.
Why the shell's policy forces that page to exist: a ``srcdoc`` or ``blob:``
document inherits its embedder's policy, so ``script-src 'self'`` on the shell
would have stopped every scripted form block.
"""
from __future__ import annotations
import base64
import hashlib
import pathlib
import re
import threading
SANDBOX_FRAME = "sandbox-frame.html"
SANDBOX_FLAGS = "allow-scripts allow-popups allow-popups-to-escape-sandbox"
SANDBOX_FRAME_CSP = f"sandbox {SANDBOX_FLAGS}; frame-ancestors 'self'"
# An inline script: a <script> element without a src attribute.
_INLINE_SCRIPT = re.compile(r"<script(?![^>]*\ssrc\s*=)[^>]*>(.*?)</script\s*>",
re.IGNORECASE | re.DOTALL)
_lock = threading.Lock()
_cache: dict[str, tuple[tuple[int, int], str]] = {}
def script_hashes(html: str) -> list[str]:
"""``'sha256-…'`` for each inline script of ``html``, as a browser
computes it (over the element's text, newlines normalised by the parser)."""
out: list[str] = []
for m in _INLINE_SCRIPT.finditer(html):
text = m.group(1).replace("\r\n", "\n").replace("\r", "\n")
if not text.strip():
continue
digest = base64.b64encode(hashlib.sha256(text.encode("utf-8")).digest()).decode()
src = f"'sha256-{digest}'"
if src not in out:
out.append(src)
return out
def shell_policy(html: str) -> str:
sources = " ".join(["'self'", *script_hashes(html)])
return (f"script-src {sources}; object-src 'none'; base-uri 'self'; "
"frame-ancestors 'self'")
def shell_csp(index: pathlib.Path) -> str:
"""The shell's policy for the built ``index.html`` (re-read when the file
changes: a deploy swaps the image, a dev build rewrites it)."""
try:
st = index.stat()
stamp = (st.st_mtime_ns, st.st_size)
except OSError:
return shell_policy("")
key = str(index)
with _lock:
hit = _cache.get(key)
if hit and hit[0] == stamp:
return hit[1]
try:
policy = shell_policy(index.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError):
return shell_policy("")
with _lock:
_cache[key] = (stamp, policy)
return policy
_frame_cache: dict[str, tuple[tuple[int, int], str]] = {}
def sandbox_frame_hash(path: pathlib.Path) -> str:
"""The first 12 hex of the sandbox frame page's sha256 — the ``?v=`` that
makes it cacheable for good (re-read when the file changes)."""
try:
st = path.stat()
stamp = (st.st_mtime_ns, st.st_size)
except OSError:
return ""
key = str(path)
with _lock:
hit = _frame_cache.get(key)
if hit and hit[0] == stamp:
return hit[1]
try:
digest = hashlib.sha256(path.read_bytes()).hexdigest()[:12]
except OSError:
return ""
with _lock:
_frame_cache[key] = (stamp, digest)
return digest