The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): send a Content-Security-Policy with the Webapp page
unsupportedpastels38e6d6fd13fa
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex cfa4c32eb59..1aec6da6e87 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -225,7 +225,8 @@ def mount_spa(application: FastAPI):if theme_bootstrap:html = html.replace("</head>", f"{theme_bootstrap}</head>", 1)html = html.replace("</head>", f"{bootstrap_script}</head>", 1)- return HTMLResponse(html, headers=_NO_STORE)+ from hermes_cli.webapp_page_policy import page_headers+ return HTMLResponse(html, headers=page_headers(application.state, _NO_STORE))# Built CSS contains absolute ``url(/fonts/...)`` / ``url(/ds-assets/...)`` references that# browsers resolve against the document origin — wrong under a proxy prefix. Intercept CSSdiff --git a/hermes_cli/webapp_page_policy.py b/hermes_cli/webapp_page_policy.pynew file mode 100644index 00000000000..fcd15db553c--- /dev/null+++ b/hermes_cli/webapp_page_policy.py@@ -0,0 +1,49 @@+"""The Content-Security-Policy the gateway's Webapp page (the Desktop renderer in a browser) is served under.++Each source is one the built renderer (``apps/desktop/dist-webapp``) uses:++- ``script-src``: its entry and lazy chunks (``'self'``); runtime plugins and the SDK shims they import, which+ load as ``blob:`` modules (``contrib/runtime-loader.ts``); the Oniguruma WebAssembly code highlighting+ compiles (``'wasm-unsafe-eval'``); and inline scripts (``'unsafe-inline'``). Inline scripts cannot be+ narrowed to a nonce: the page's own pre-paint and bootstrap scripts could carry one, but the live HTML+ previews (``::preview`` and artifacts) run their scripts in sandboxed ``srcdoc`` frames, which inherit this+ policy, and a nonce would stop them. No ``'unsafe-eval'``: the bundle evaluates no strings.+- ``style-src``: its stylesheets, the inline styles React, KaTeX, Mermaid and Shiki write, and a theme's+ Google Fonts stylesheet; ``font-src`` the bundled fonts, ``data:`` fonts and Google's font files.+- ``connect-src``: the gateway's REST routes and its sockets on this same origin (``'self'`` covers+ ``ws:``/``wss:`` there), ``blob:``/``data:`` reads, and the public HTTPS APIs plugins call (Radio's station+ directory and track lookups).+- ``img-src``/``media-src``: gateway media, ``data:``/``blob:`` previews and recordings, images a message links+ and Radio's HTTPS streams; ``worker-src`` same-origin and ``blob:`` workers.+- ``frame-src``: previews in ``blob:``/``data:``/``srcdoc`` frames, embeds (YouTube, Spotify, maps, posts) and+ the sandboxed preview of a site (``http:`` for a local dev server).++Everything else stays shut: no plugins (``object-src``), no ``<base>`` or form posts to another origin, and no+page may frame the Webapp (``frame-ancestors``).+"""+from __future__ import annotations++CONTENT_SECURITY_POLICY = "; ".join((+ "default-src 'self'",+ "script-src 'self' 'unsafe-inline' blob: 'wasm-unsafe-eval'",+ "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",+ "font-src 'self' data: https://fonts.gstatic.com",+ "connect-src 'self' blob: data: https:",+ "img-src 'self' data: blob: https: http:",+ "media-src 'self' data: blob: https:",+ "worker-src 'self' blob:",+ "frame-src 'self' blob: data: https: http:",+ "manifest-src 'self'",+ "object-src 'none'",+ "base-uri 'self'",+ "form-action 'self'",+ "frame-ancestors 'none'",+))+++def page_headers(state, headers: dict) -> dict:+ """*headers* for the renderer's page on *state*'s app, with :data:`CONTENT_SECURITY_POLICY` when that app+ serves the Webapp. The dashboard's page keeps main's headers."""+ if getattr(state, "ui_surface", "dashboard") != "webapp":+ return headers+ return {**headers, "Content-Security-Policy": CONTENT_SECURITY_POLICY}diff --git a/tests/hermes_cli/test_webapp_page_csp.py b/tests/hermes_cli/test_webapp_page_csp.pynew file mode 100644index 00000000000..5bc6fd18228--- /dev/null+++ b/tests/hermes_cli/test_webapp_page_csp.py@@ -0,0 +1,102 @@+"""The Webapp page's Content-Security-Policy (``hermes_cli.webapp_page_policy``).++The gateway serves the Desktop renderer to a browser; its page carries a policy that the renderer, its+lazy chunks, workers, plugins, media, previews and same-origin sockets work under, and that shuts+everything else. The sources below are what the built bundle uses (see the module's docstring).+"""+import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient+++def _page(monkeypatch, tmp_path, surface: str):+ from hermes_cli import web_server as server+ from hermes_cli.web_server_dashboard import mount_spa++ (tmp_path / "index.html").write_text(+ "<html><head><script>document.documentElement.dataset.boot = '1'</script></head><body></body></html>")+ application = FastAPI()+ application.state.ui_surface = surface+ application.state.auth_required = False+ monkeypatch.setattr(server, "app", application)+ monkeypatch.setattr(server, "WEB_DIST", tmp_path)+ monkeypatch.delenv("HERMES_SERVE_HEADLESS", raising=False)+ mount_spa(application)+ return TestClient(application)+++def _directives(policy: str) -> dict[str, list[str]]:+ parsed = {}+ for part in policy.split(";"):+ name, *sources = part.split()+ assert name not in parsed, f"{name} appears twice"+ parsed[name] = sources+ return parsed++[email protected]("path", ["/", "/chat", "/settings", "/index.html"])+def test_the_webapp_page_sends_a_content_security_policy(monkeypatch, tmp_path, path):+ from hermes_cli.webapp_page_policy import CONTENT_SECURITY_POLICY++ response = _page(monkeypatch, tmp_path, "webapp").get(path)+ assert response.status_code == 200+ assert response.headers["content-security-policy"] == CONTENT_SECURITY_POLICY+ assert response.headers["cache-control"].startswith("no-store")+++def test_the_dashboards_page_keeps_mains_headers(monkeypatch, tmp_path):+ assert "content-security-policy" not in _page(monkeypatch, tmp_path, "dashboard").get("/").headers+++# (directive, source, what in the built renderer needs it)+NEEDED = [+ ("script-src", "'self'", "the entry module and its lazy chunks"),+ ("script-src", "'unsafe-inline'", "the pre-paint and bootstrap scripts, and scripts in srcdoc previews"),+ ("script-src", "blob:", "runtime plugins and the SDK shims they import (contrib/runtime-loader.ts)"),+ ("script-src", "'wasm-unsafe-eval'", "Shiki's Oniguruma WebAssembly"),+ ("worker-src", "blob:", "blob: workers"),+ ("worker-src", "'self'", "same-origin workers"),+ ("connect-src", "'self'", "REST, /api/ws, the host terminal and voice sockets on this origin"),+ ("connect-src", "https:", "public APIs plugins call (Radio's directory and track lookups)"),+ ("connect-src", "blob:", "reads of blob: previews and downloads"),+ ("style-src", "'unsafe-inline'", "inline styles from React, KaTeX, Mermaid and Shiki"),+ ("style-src", "https://fonts.googleapis.com", "a theme's Google Fonts stylesheet"),+ ("font-src", "https://fonts.gstatic.com", "Google's font files"),+ ("font-src", "'self'", "the bundled KaTeX and JetBrains Mono fonts"),+ ("font-src", "data:", "inlined fonts"),+ ("img-src", "data:", "data: previews"),+ ("img-src", "blob:", "blob: previews"),+ ("img-src", "https:", "images a message links"),+ ("media-src", "blob:", "voice playback"),+ ("media-src", "'self'", "gateway media links"),+ ("media-src", "https:", "Radio's streams"),+ ("frame-src", "blob:", "the PDF preview"),+ ("frame-src", "data:", "data: HTML previews"),+ ("frame-src", "https:", "YouTube, Spotify, map and post embeds"),+ ("frame-src", "http:", "the sandboxed preview of a local dev server"),+]++[email protected](("directive", "source", "need"), NEEDED, ids=[f"{d} {s}" for d, s, _ in NEEDED])+def test_the_policy_allows_each_source_the_renderer_uses(directive, source, need):+ from hermes_cli.webapp_page_policy import CONTENT_SECURITY_POLICY++ directives = _directives(CONTENT_SECURITY_POLICY)+ assert source in directives.get(directive, directives["default-src"]), need+++def test_the_policy_shuts_everything_the_renderer_does_not_use():+ """No string evaluation, no plugins, no <base> or form posts elsewhere, no page framing the+ Webapp, no wildcard source, and no socket or plain-HTTP fetch to another origin."""+ from hermes_cli.webapp_page_policy import CONTENT_SECURITY_POLICY++ directives = _directives(CONTENT_SECURITY_POLICY)+ assert directives["default-src"] == ["'self'"]+ assert directives["object-src"] == ["'none'"]+ assert directives["base-uri"] == ["'self'"]+ assert directives["form-action"] == ["'self'"]+ assert directives["frame-ancestors"] == ["'none'"]+ assert all("'unsafe-eval'" not in sources for sources in directives.values())+ assert all("*" not in sources for sources in directives.values())+ assert not {"http:", "ws:", "wss:"} & set(directives["connect-src"])+ assert set(directives["script-src"]) == {"'self'", "'unsafe-inline'", "blob:", "'wasm-unsafe-eval'"}