webapp_page_policy.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. """CSP for the browser-hosted Desktop, independently of its preview documents."""
  2. import base64
  3. import hashlib
  4. from html.parser import HTMLParser
  5. from fastapi import Request
  6. class _ScriptHashes(HTMLParser):
  7. """Hash the trusted build's inline scripts and the server's bootstrap verbatim."""
  8. def __init__(self, html: str):
  9. super().__init__(convert_charrefs=False)
  10. self.script = None
  11. self.hashes = []
  12. self.feed(html)
  13. def handle_starttag(self, tag, attrs):
  14. if tag == "script" and "src" not in dict(attrs):
  15. self.script = ""
  16. def handle_data(self, data):
  17. if self.script is not None:
  18. self.script += data
  19. def handle_endtag(self, tag):
  20. if tag == "script" and self.script is not None:
  21. digest = base64.b64encode(hashlib.sha256(self.script.encode("utf-8")).digest()).decode("ascii")
  22. self.hashes.append(f"'sha256-{digest}'")
  23. self.script = None
  24. def page_headers(request: Request, html: str, headers: dict) -> dict:
  25. """Only gateway-served Webapp HTML gets this policy; native Desktop is not served here."""
  26. if getattr(request.app.state, "ui_surface", None) != "webapp":
  27. return headers
  28. hashes = " ".join(_ScriptHashes(html).hashes)
  29. # Keep fetch and media sources open for voice, catalogs, Radio, update notes,
  30. # and local servers or sockets behind a Host-rewriting proxy.
  31. policy = "; ".join((
  32. "default-src 'none'",
  33. f"script-src 'self' blob: 'wasm-unsafe-eval' {hashes}",
  34. "script-src-attr 'none'",
  35. "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
  36. "font-src 'self' data: https://fonts.gstatic.com",
  37. "connect-src * ws: wss: data: blob:",
  38. "img-src 'self' data: blob: https: http:",
  39. "media-src * data: blob:",
  40. "worker-src 'self' blob:",
  41. "frame-src 'self' blob: data: https: http:",
  42. "manifest-src 'self'",
  43. "object-src 'none'",
  44. "base-uri 'none'",
  45. "form-action 'none'",
  46. "frame-ancestors 'none'",
  47. ))
  48. return {**headers, "Content-Security-Policy": policy, "X-Content-Type-Options": "nosniff"}