The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): isolate preview documents from the renderer policy
dokterdoke0a3c6005553
diff --git a/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsxindex 278bcfd1bc0..fac84daf924 100644--- a/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx@@ -3,6 +3,7 @@ import DOMPurify from 'dompurify'import { useEffect, useMemo, useState } from 'react'import { CopyButton } from '@/components/ui/copy-button'+import { PreviewDocumentFrame } from '@/components/ui/preview-document-frame'import { Tip } from '@/components/ui/tooltip'import { useI18n } from '@/i18n'import { artifactDownloadName, type ArtifactKind } from '@/lib/artifact-detect'@@ -95,7 +96,7 @@ function ArtifactLiveView({ content, kind, title }: { content: string; kind: Art}return (- <iframe+ <PreviewDocumentFrameclassName="block size-full border-0 bg-white"sandbox="allow-scripts"srcDoc={composeArtifactHtml(content)}diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex 3a5c891033f..dae52260055 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -9,6 +9,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { requestComposerAttachImages, requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'import { openGuestContextMenu } from '@/app/context-menu/store'import { PanelEmpty } from '@/app/overlays/panel'+import { PreviewDocumentFrame } from '@/components/ui/preview-document-frame'import { Tip } from '@/components/ui/tooltip'import { type Translations, useI18n } from '@/i18n'import { isDesktopFsRemoteMode, isReadFileErrorResult } from '@/lib/desktop-fs'@@ -1542,7 +1543,7 @@ export function PreviewPane({ref={hostRef}/>{isRemoteHtml && (- <iframe+ <PreviewDocumentFrameclassName="absolute inset-0 size-full border-0 bg-white"referrerPolicy="no-referrer"sandbox=""diff --git a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsxindex 2d0ca408d98..061d9469b8e 100644--- a/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx+++ b/apps/desktop/src/components/assistant-ui/inline-preview-directive.tsx@@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react'import { requestComposerSubmit } from '@/app/chat/composer/focus'import { useSessionView } from '@/app/chat/session-view'import { PreviewAttachment } from '@/components/chat/preview-attachment'+import { PreviewDocumentFrame } from '@/components/ui/preview-document-frame'import { useThemeEpoch } from '@/hooks/use-theme-epoch'import { isReadFileErrorResult, readDesktopFileText } from '@/lib/desktop-fs'import { localPreviewTarget } from '@/lib/local-preview'@@ -524,7 +525,7 @@ function InlineHtmlFrame({className="relative block max-w-full transition-[height] duration-200"style={{ height, width: width ?? '100%' }}>- <iframe+ <PreviewDocumentFrameclassName="absolute inset-0 size-full border-0 bg-transparent"loading="lazy"sandbox="allow-scripts"diff --git a/apps/desktop/src/components/ui/preview-document-frame.test.tsx b/apps/desktop/src/components/ui/preview-document-frame.test.tsxnew file mode 100644index 00000000000..d8c8d8a427c--- /dev/null+++ b/apps/desktop/src/components/ui/preview-document-frame.test.tsx@@ -0,0 +1,36 @@+import { cleanup, fireEvent, render } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import { PreviewDocumentFrame } from './preview-document-frame'++afterEach(() => {+ cleanup()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ vi.unstubAllGlobals()+})++it.each(['allow-scripts', ''])('sends browser HTML only to its own isolated frame (%s)', sandbox => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('__HERMES_BASE_PATH__', '/hermes')+ vi.stubGlobal('__HERMES_UI_SURFACE__', 'webapp')+ const { container, rerender } = render(<PreviewDocumentFrame sandbox={sandbox} srcDoc="<h1>private</h1>" />)+ const frame = container.querySelector('iframe')!+ expect(frame.getAttribute('srcdoc')).toBeNull()+ expect(frame.src).toBe(`${window.location.origin}/hermes/assets/webapp-preview.html`)+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts')+ const send = vi.spyOn(frame.contentWindow!, 'postMessage')+ fireEvent.load(frame)+ expect(send).toHaveBeenLastCalledWith({+ type: 'hermes-preview-document', html: '<h1>private</h1>', scripts: sandbox === 'allow-scripts'+ }, '*')+ rerender(<PreviewDocumentFrame sandbox={sandbox} srcDoc="<h1>updated</h1>" />)+ expect(send).toHaveBeenLastCalledWith(expect.objectContaining({ html: '<h1>updated</h1>' }), '*')+})++it('keeps native Desktop srcdoc and its original script permission', () => {+ const { container } = render(<PreviewDocumentFrame sandbox="" srcDoc="<h1>native</h1>" />)+ const frame = container.querySelector('iframe')!+ expect(frame.getAttribute('srcdoc')).toBe('<h1>native</h1>')+ expect(frame.getAttribute('sandbox')).toBe('')+ expect(frame.getAttribute('src')).toBeNull()+})diff --git a/apps/desktop/src/components/ui/preview-document-frame.tsx b/apps/desktop/src/components/ui/preview-document-frame.tsxnew file mode 100644index 00000000000..7a477ab7a3a--- /dev/null+++ b/apps/desktop/src/components/ui/preview-document-frame.tsx@@ -0,0 +1,31 @@+import { type IframeHTMLAttributes, useCallback, useEffect, useRef } from 'react'++import { browserBootstrap, endpointUrl } from '@/lib/browser-transport'+import { isBrowserHostedDesktop } from '@/lib/platform'++interface PreviewDocumentFrameProps extends IframeHTMLAttributes<HTMLIFrameElement> {+ srcDoc: string+}++/** A served preview gets its own CSP; srcdoc would inherit the renderer's. */+export function PreviewDocumentFrame({ srcDoc, sandbox, ...props }: PreviewDocumentFrameProps) {+ const frame = useRef<HTMLIFrameElement>(null)+ const browser = isBrowserHostedDesktop()+ const src = browser ? endpointUrl('/assets/webapp-preview.html', browserBootstrap()?.basePath || '').href : undefined+ const scripts = sandbox === 'allow-scripts'++ const send = useCallback(() => {+ if (browser) {+ frame.current?.contentWindow?.postMessage({ type: 'hermes-preview-document', html: srcDoc, scripts }, '*')+ }+ }, [browser, srcDoc, scripts])++ useEffect(send, [send])++ if (!browser) {+ return <iframe {...props} sandbox={sandbox} srcDoc={srcDoc} />+ }++ return <iframe {...props} onLoad={send} ref={frame}+ referrerPolicy="no-referrer" sandbox="allow-scripts" src={src} />+}diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex 1f5c65f164f..9b66d6da29b 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -797,10 +797,12 @@ describe('browser-hosted Desktop bridge', () => {const wrapper = new DOMParser().parseFromString(await blobs[0]!.text(), 'text/html')const frame = wrapper.querySelector('iframe')!- expect(wrapper.querySelectorAll('iframe, script')).toHaveLength(1)+ expect(wrapper.querySelectorAll('iframe, script')).toHaveLength(2)+ expect(wrapper.querySelector('script')!.src).toContain('/assets/webapp-preview.js')expect(frame.getAttribute('sandbox')).toBe('allow-scripts')- expect(frame.hasAttribute('src')).toBe(false)- expect(frame.getAttribute('srcdoc')).toBe(+ expect(frame.src).toContain('/assets/webapp-preview.html')+ expect(frame.hasAttribute('srcdoc')).toBe(false)+ expect(frame.getAttribute('data-preview-html')).toBe(page.replace('<!doctype html>', '<!doctype html><base href="about:srcdoc">'))})@@ -822,7 +824,7 @@ describe('browser-hosted Desktop bridge', () => {await win.hermesDesktop!.saveImageBuffer(new TextEncoder().encode(page), '.html')const wrapper = new DOMParser().parseFromString(await blobs.at(-1)!.text(), 'text/html')- return wrapper.querySelector('iframe')!.getAttribute('srcdoc')!+ return wrapper.querySelector('iframe')!.getAttribute('data-preview-html')!}// Without a base of its own, the page inherits the wrapper's blob: URL and href="#sec" goes nowhere.@@ -858,7 +860,7 @@ describe('browser-hosted Desktop bridge', () => {const parsedSrcdocOf = async (page: string) => {await win.hermesDesktop!.saveImageBuffer(new TextEncoder().encode(page), '.html')const wrapper = new DOMParser().parseFromString(await blobs.at(-1)!.text(), 'text/html')- const srcdoc = wrapper.querySelector('iframe')!.getAttribute('srcdoc')!+ const srcdoc = wrapper.querySelector('iframe')!.getAttribute('data-preview-html')!return { doc: new DOMParser().parseFromString(srcdoc, 'text/html'), srcdoc }}@@ -915,7 +917,7 @@ describe('browser-hosted Desktop bridge', () => {expect(wrapper).toContain('sandbox="allow-scripts"')expect(wrapper).not.toContain('allow-same-origin')expect(wrapper).not.toContain('<h1>preview</h1>')- expect(wrapper).toContain('srcdoc="<base href="about:srcdoc"><h1>preview</h1>"')+ expect(wrapper).toContain('data-preview-html="<base href="about:srcdoc"><h1>preview</h1>"')expect(wrapper).not.toMatch(/\ssrc="data:/)await win.hermesDesktop!.openPreviewInBrowser!(staged)diff --git a/apps/desktop/src/lib/browser-uploads.ts b/apps/desktop/src/lib/browser-uploads.tsindex 3c0bbc25867..25ac070159d 100644--- a/apps/desktop/src/lib/browser-uploads.ts+++ b/apps/desktop/src/lib/browser-uploads.ts@@ -1,6 +1,6 @@import type { HermesApiRequest, HermesSelectPathsOptions, HermesStagedUpload } from '@/global'import { blobToDataUrl } from '@/lib/base64'-import { type BrowserBootstrap, browserFetch } from '@/lib/browser-transport'+import { type BrowserBootstrap, browserFetch, endpointUrl } from '@/lib/browser-transport'const STAGED_UPLOAD_CACHE_LIMIT = 256@@ -51,15 +51,10 @@ function rememberBounded<K, V>(cache: Map<K, V>, key: K, value: V): void {}}-// The page reaches its opaque-origin frame through srcdoc, never a URL: Chromium refuses to-// navigate a frame to a URL over 2 MiB, so a base64 data URL left any page above ~1.5 MB blank.-// Decoded as the data URL's charset=utf-8 did, and escaped for a double-quoted attribute (`&`-// first) so no byte of the page parses as markup of this same-origin wrapper.-// A srcdoc document inherits the wrapper's blob: base URL, so `#anchor` links would resolve to-// blob:…#anchor and do nothing. A page without its own <base> gets about:srcdoc, placed inside-// the page's own <head> start tag (else its <html> tag, else after any doctype): a base before-// <head> opens an implicit head, and the parser then drops the authored tag and its attributes.-// After the doctype, the page keeps its rendering mode.+// Keep HTML as inert attribute data until the external loader sends it to the preview+// route. A blob/srcdoc would inherit the app CSP; a data URL hits Chromium's 2 MiB+// navigation limit. The preview's inner srcdoc needs an explicit base for #anchors.+// Insert it inside the authored head (or after the doctype) to retain attributes and mode.const SRCDOC_BASE = '<base href="about:srcdoc">'const LEADING_DOCTYPE = /^\s*<!doctype[^>]*>/iconst BASE_ELEMENT = /<base[\s/>]/i@@ -78,7 +73,7 @@ function withSrcdocBase(page: string): string {return page.slice(0, at) + SRCDOC_BASE + page.slice(at)}-function sandboxedHtmlBlob(bytes: Uint8Array): Blob {+function sandboxedHtmlBlob(bytes: Uint8Array, bootstrap: BrowserBootstrap): Blob {const srcdoc = withSrcdocBase(new TextDecoder('utf-8').decode(bytes)).replace(/&/g, '&').replace(/"/g, '"')@@ -90,7 +85,8 @@ function sandboxedHtmlBlob(bytes: Uint8Array): Blob {'<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">','<style>html,body,iframe{box-sizing:border-box;width:100%;height:100%;margin:0;border:0}</style>','</head><body>',- `<iframe sandbox="allow-scripts" referrerpolicy="no-referrer" srcdoc="${srcdoc}"></iframe>`,+ `<iframe sandbox="allow-scripts" referrerpolicy="no-referrer" data-preview-html="${srcdoc}" src="${endpointUrl('/assets/webapp-preview.html', bootstrap.basePath).href}"></iframe>`,+ `<script src="${endpointUrl('/assets/webapp-preview.js', bootstrap.basePath).href}"></script>`,'</body></html>'].join('')@@ -281,7 +277,7 @@ export function createBrowserUploadsBridge({const isHtml = extension === '.htm' || extension === '.html'const blob = isHtml- ? sandboxedHtmlBlob(bytes)+ ? sandboxedHtmlBlob(bytes, bootstrap): new Blob([bytes.buffer], { type: 'application/octet-stream' })const url = URL.createObjectURL(blob)diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex 6551e6f6f5b..5c8aa038750 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -265,6 +265,8 @@ def mount_spa(application: FastAPI):asset_files[directory] = _ImmutableAssetFiles(directory=directory, check_dir=False)await asset_files[directory](scope, receive, send)+ from hermes_cli.webapp_previews import mount_preview_assets+ mount_preview_assets(application)application.mount("/assets", serve_assets, name="assets")@application.get("/{full_path:path}")diff --git a/hermes_cli/webapp_previews.py b/hermes_cli/webapp_previews.pynew file mode 100644index 00000000000..daa8d2aafa6--- /dev/null+++ b/hermes_cli/webapp_previews.py@@ -0,0 +1,70 @@+"""Credential-free preview assets: private HTML crosses only a parent/frame message."""++from fastapi import Depends, FastAPI+from fastapi.responses import HTMLResponse, Response++from hermes_cli.web_server_surface import route_on++# Previews keep the freedom they have under no policy at all (any http(s) library, image,+# fetch, worker or embed); their isolation is the opaque sandbox, not a source list.+PREVIEW_POLICY = (+ "default-src 'none'; sandbox allow-scripts; "+ "script-src * data: blob: 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'; "+ "style-src * data: 'unsafe-inline'; img-src * data: blob:; font-src * data:; "+ "media-src * data: blob:; connect-src * data: blob:; worker-src * data: blob:; "+ "frame-src * data: blob: about:; object-src 'none'; base-uri * about:; form-action 'none'; "+ "frame-ancestors 'self'"+)++# D3's CSV/TSV parsers need `new Function` within the opaque preview origin.+# An inner sandbox keeps file previews inert while the shell receives their HTML.+PREVIEW_HTML = """<!doctype html><html><head><meta charset="utf-8">+<style>html,body,iframe{width:100%;height:100%;margin:0;border:0;display:block}</style>+</head><body><script>+const frame = document.createElement('iframe');+frame.referrerPolicy = 'no-referrer';+frame.title = 'Preview content';+addEventListener('message', event => {+ if (event.source === parent && parent !== window &&+ event.origin === new URL(location.href).origin &&+ event.data?.type === 'hermes-preview-document' && typeof event.data.html === 'string') {+ frame.setAttribute('sandbox', event.data.scripts === true ? 'allow-scripts' : '');+ frame.srcdoc = event.data.html;+ document.body.append(frame);+ } else if (event.source === parent && event.origin === new URL(location.href).origin) {+ frame.contentWindow?.postMessage(event.data, '*');+ } else if (event.source === frame.contentWindow) {+ parent.postMessage(event.data, '*');+ }+});+</script></body></html>"""++# An external same-origin loader can run under the blob wrapper's inherited app CSP.+PREVIEW_LOADER = """const frame = document.querySelector('iframe[data-preview-html]');+function send() {+ frame.contentWindow.postMessage({type: 'hermes-preview-document',+ html: frame.dataset.previewHtml, scripts: true}, '*');+}+frame.addEventListener('load', send);+send();+"""+++def mount_preview_assets(application: FastAPI) -> None:+ """Public Webapp assets receive authorized content only via parent messages."""+ dependencies = [Depends(route_on("browser_files"))]++ @application.get("/assets/webapp-preview.html", dependencies=dependencies)+ async def preview_document():+ return HTMLResponse(PREVIEW_HTML, headers={+ "Content-Security-Policy": PREVIEW_POLICY,+ "Cache-Control": "no-store",+ "Referrer-Policy": "no-referrer",+ "X-Content-Type-Options": "nosniff",+ })++ @application.get("/assets/webapp-preview.js", dependencies=dependencies)+ async def preview_loader():+ return Response(PREVIEW_LOADER, media_type="text/javascript", headers={+ "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",+ })diff --git a/tests/hermes_cli/test_webapp_page_previews.py b/tests/hermes_cli/test_webapp_page_previews.pyindex 97110876d97..534041031d5 100644--- a/tests/hermes_cli/test_webapp_page_previews.py+++ b/tests/hermes_cli/test_webapp_page_previews.py@@ -1,12 +1,4 @@-"""Live HTML previews on the gateway's Webapp page (``::preview`` widgets and artifacts).--They render in sandboxed ``srcdoc`` frames, which inherit the Content-Security-Policy of the page that-embeds them, and they load their libraries from a public CDN: the agent is told to pin each one as-``https://cdn.jsdelivr.net/npm/<package>@<version>/<file>`` (``agent/onboarding_text.py``). A policy on-the Webapp page that keeps scripts or stylesheets to its own origin blocks them, and the widget renders-nothing (headless Chromium: ``script-src-elem`` violation, the CDN never asked). Until previews move to-documents served with a policy of their own, whatever the page sends must let those loads through.-"""+"""Preview CDN loads use the isolated document policy, never the app policy."""from urllib.parse import urlsplitimport pytest@@ -24,6 +16,7 @@ def _page(monkeypatch, tmp_path):from hermes_cli import web_server as serverfrom hermes_cli.web_server_dashboard import mount_spa+ (tmp_path / "assets").mkdir()(tmp_path / "index.html").write_text("<html><head></head><body></body></html>")application = FastAPI()application.state.ui_surface = "webapp"@@ -52,11 +45,10 @@ def _allows(policy: str, directives: tuple[str, ...], url: str) -> bool:for source in sources)[email protected]("path", ["/", "/chat"])@pytest.mark.parametrize(("directives", "url"), PREVIEW_LOADS, ids=[d[0] for d, _ in PREVIEW_LOADS])-def test_a_live_preview_can_load_its_cdn_libraries_under_the_webapp_pages_policy(- monkeypatch, tmp_path, path, directives, url):- response = _page(monkeypatch, tmp_path).get(path)+def test_a_live_preview_can_load_its_cdn_libraries_under_its_own_policy(+ monkeypatch, tmp_path, directives, url):+ response = _page(monkeypatch, tmp_path).get("/assets/webapp-preview.html")assert response.status_code == 200for policy in response.headers.get_list("content-security-policy"):assert _allows(policy, directives, url), f"{directives[0]} blocks {url}: {policy}"diff --git a/tests/hermes_cli/test_webapp_preview_documents.py b/tests/hermes_cli/test_webapp_preview_documents.pynew file mode 100644index 00000000000..e90c61175b1--- /dev/null+++ b/tests/hermes_cli/test_webapp_preview_documents.py@@ -0,0 +1,44 @@+"""Preview policy is independent of the app, without a new private-content endpoint."""+import pytest+from fastapi.testclient import TestClient+++def client(monkeypatch, tmp_path):+ from hermes_cli import web_server as server++ monkeypatch.setattr(server.app.state, "ui_surface", "webapp", raising=False)+ monkeypatch.setattr(server.app.state, "auth_required", False, raising=False)+ (tmp_path / "assets").mkdir()+ monkeypatch.setattr(server.app.state, "web_dist", tmp_path, raising=False)+ return TestClient(server.app)+++def test_preview_assets_expose_only_a_sandboxed_empty_shell(client):+ from hermes_cli import web_server as server++ response = client.get("/assets/webapp-preview.html", params={"html": "private-content", "profile": "other"})+ assert response.status_code == 200+ assert "sandbox allow-scripts" in response.headers["content-security-policy"]+ assert "allow-same-origin" not in response.headers["content-security-policy"]+ assert "frame-ancestors 'self'" in response.headers["content-security-policy"]+ # Widgets keep main's reach: plain-http images and APIs, workers and embeds.+ policy = dict(part.strip().split(" ", 1) for part in response.headers["content-security-policy"].split(";"))+ for directive in ("script-src", "img-src", "connect-src", "worker-src", "frame-src"):+ assert "*" in policy[directive].split(), directive+ assert response.headers["cache-control"] == "no-store"+ assert response.headers["referrer-policy"] == "no-referrer"+ assert "private-content" not in response.text+ assert server._SESSION_TOKEN not in response.text+ loader = client.get("/assets/webapp-preview.js")+ assert loader.status_code == 200+ assert loader.headers["content-type"].startswith("text/javascript")+ assert server._SESSION_TOKEN not in loader.text+ assert client.get("/api/fs/read-text", params={"path": "/secret", "profile": "other"}).status_code == 401++[email protected]("surface", ["gateway", "serve", "dashboard"])+def test_preview_assets_are_webapp_only(client, monkeypatch, surface):+ monkeypatch.setattr(client.app.state, "ui_surface", surface)+ for path in ("/assets/webapp-preview.html", "/assets/webapp-preview.js"):+ assert client.get(path).status_code == 404