The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): keep scripted SandboxedFrame data: HTML running under the page CSP
Teknium764fa746ae27
diff --git a/apps/desktop/src/components/ui/sandboxed-frame.test.tsx b/apps/desktop/src/components/ui/sandboxed-frame.test.tsxindex 22e6b6d53f9..35febadaecd 100644--- a/apps/desktop/src/components/ui/sandboxed-frame.test.tsx+++ b/apps/desktop/src/components/ui/sandboxed-frame.test.tsx@@ -1,10 +1,15 @@// @vitest-environment jsdom-import { cleanup, render } from '@testing-library/react'+import { act, cleanup, fireEvent, render } from '@testing-library/react'+import { createRef } from 'react'import { afterEach, describe, expect, it, vi } from 'vitest'import { SANDBOXED_FRAME_DEFAULT_SANDBOX, SandboxedFrame, sanitizeFrameSandbox } from './sandboxed-frame'-afterEach(cleanup)+afterEach(() => {+ cleanup()+ window.document.documentElement.removeAttribute('data-hermes-desktop-host')+ vi.unstubAllGlobals()+})describe('sanitizeFrameSandbox', () => {it('strips every realm-escaping or unknown token, case-insensitively, and never emits an empty attribute', () => {@@ -97,3 +102,81 @@ describe('SandboxedFrame', () => {warn.mockRestore()})})++describe('SandboxedFrame in the Webapp', () => {+ const guest = `data:text/html;charset=utf-8,${encodeURIComponent('<script>parent.postMessage("ready", "*")</script>')}`++ function browserHost() {+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('__HERMES_BASE_PATH__', '/hermes')+ vi.stubGlobal('__HERMES_UI_SURFACE__', 'webapp')+ }++ it('serves data: HTML through the guest shell with the caller tokens, and fires onLoad for the guest', () => {+ browserHost()+ const onLoad = vi.fn()+ const ref = createRef<HTMLIFrameElement>()++ const { container } = render(+ <SandboxedFrame+ onLoad={onLoad}+ ref={ref}+ sandbox="allow-forms ALLOW-SAME-ORIGIN allow-popups"+ src={guest}+ title="Widget"+ />+ )++ const frame = container.querySelector('iframe')!++ expect(ref.current).toBe(frame)+ expect(frame.getAttribute('srcdoc')).toBeNull()+ expect(frame.src).toBe(`${window.location.origin}/hermes/assets/webapp-guest.html`)+ expect(frame.getAttribute('sandbox')).toBe('allow-forms allow-scripts')+ expect(frame.getAttribute('referrerpolicy')).toBe('no-referrer')++ const send = vi.spyOn(frame.contentWindow!, 'postMessage')+ fireEvent.load(frame)+ expect(send).toHaveBeenLastCalledWith(+ {+ type: 'hermes-preview-document',+ html: '<script>parent.postMessage("ready", "*")</script>',+ sandbox: 'allow-forms'+ },+ '*'+ )+ // The shell loading is not the guest loading.+ expect(onLoad).not.toHaveBeenCalled()++ act(() => {+ window.dispatchEvent(new MessageEvent('message', { data: { type: 'hermes-guest-loaded' }, source: window }))+ })+ expect(onLoad).not.toHaveBeenCalled()++ act(() => {+ window.dispatchEvent(+ new MessageEvent('message', { data: { type: 'hermes-guest-loaded' }, source: frame.contentWindow })+ )+ })+ expect(onLoad).toHaveBeenCalledTimes(1)+ })++ it('keeps http(s) and non-HTML data: embeds on the direct frame', () => {+ browserHost()++ for (const src of ['https://example.com/feed', 'data:image/svg+xml,%3Csvg%2F%3E', 'data:,plain']) {+ const { container, unmount } = render(<SandboxedFrame src={src} title="Feed" />)++ expect(container.querySelector('iframe')!.getAttribute('src'), src).toBe(src)+ unmount()+ }+ })++ it('leaves native Desktop on the direct data: frame', () => {+ const { container } = render(<SandboxedFrame src={guest} title="Widget" />)+ const frame = container.querySelector('iframe')!++ expect(frame.getAttribute('src')).toBe(guest)+ expect(frame.getAttribute('sandbox')).toBe(SANDBOXED_FRAME_DEFAULT_SANDBOX)+ })+})diff --git a/apps/desktop/src/components/ui/sandboxed-frame.tsx b/apps/desktop/src/components/ui/sandboxed-frame.tsxindex e391f6224e1..15ae4676206 100644--- a/apps/desktop/src/components/ui/sandboxed-frame.tsx+++ b/apps/desktop/src/components/ui/sandboxed-frame.tsx@@ -1,5 +1,9 @@import type * as React from 'react'+import { useCallback, useEffect, useRef } from 'react'+import { htmlFromDataUrl } from '@/lib/browser-guest-document'+import { browserBootstrap, endpointUrl } from '@/lib/browser-transport'+import { isBrowserHostedDesktop } from '@/lib/platform'import { cn } from '@/lib/utils'/** The sandbox posture guest content gets by default: scripts run, the frame@@ -93,6 +97,23 @@ export function SandboxedFrame({ className, onError, onLoad, ref, sandbox, src,return null}+ const html = isBrowserHostedDesktop() ? htmlFromDataUrl(src) : null++ if (html !== null) {+ return (+ <BrowserGuestFrame+ className={className}+ html={html}+ onError={onError}+ onLoad={onLoad}+ ref={ref}+ sandbox={sandbox}+ style={style}+ title={title}+ />+ )+ }+return (<iframeclassName={cn('size-full border-0 bg-transparent', className)}@@ -109,6 +130,88 @@ export function SandboxedFrame({ className, onError, onLoad, ref, sandbox, src,)}+interface BrowserGuestFrameProps extends Omit<SandboxedFrameProps, 'src'> {+ html: string+}++/** Webapp only: a `data:text/html` document would inherit the page CSP, which+ * never runs guest inline scripts. The gateway's guest shell is served with+ * its own policy and the SDK allowlist as its sandbox ceiling; this frame's+ * sandbox narrows it to the caller's tokens (plus `allow-scripts`, which the+ * shell itself needs), and the guest document nested in the shell gets the+ * caller's tokens exactly. The shell relays messages both ways, so+ * `ref.current.contentWindow.postMessage` and `event.source ===+ * ref.current.contentWindow` keep working, and `onLoad` fires once the guest+ * document (not the shell) has loaded. */+function BrowserGuestFrame({ className, html, onError, onLoad, ref, sandbox, style, title }: BrowserGuestFrameProps) {+ const frame = useRef<HTMLIFrameElement | null>(null)+ const shellLoad = useRef<React.SyntheticEvent<HTMLIFrameElement> | null>(null)+ const guestSandbox = sanitizeFrameSandbox(sandbox)+ const src = endpointUrl('/assets/webapp-guest.html', browserBootstrap()?.basePath || '').href++ const send = useCallback(() => {+ frame.current?.contentWindow?.postMessage({ type: 'hermes-preview-document', html, sandbox: guestSandbox }, '*')+ }, [html, guestSandbox])++ useEffect(send, [send])++ useEffect(() => {+ const guestLoaded = (event: MessageEvent) => {+ const loaded = shellLoad.current++ if (loaded && event.source === frame.current?.contentWindow && event.data?.type === 'hermes-guest-loaded') {+ onLoad?.(loaded)+ }+ }++ window.addEventListener('message', guestLoaded)++ return () => window.removeEventListener('message', guestLoaded)+ }, [onLoad])++ const attach = useCallback(+ (node: HTMLIFrameElement | null) => {+ frame.current = node+ const cleanup = typeof ref === 'function' ? ref(node) : undefined++ if (ref && typeof ref !== 'function') {+ ref.current = node+ }++ return () => {+ frame.current = null++ if (typeof cleanup === 'function') {+ cleanup()+ } else if (typeof ref === 'function') {+ ref(null)+ } else if (ref) {+ ref.current = null+ }+ }+ },+ [ref]+ )++ return (+ <iframe+ className={cn('size-full border-0 bg-transparent', className)}+ loading="lazy"+ onError={onError}+ onLoad={event => {+ shellLoad.current = event+ send()+ }}+ ref={attach}+ referrerPolicy="no-referrer"+ sandbox={sanitizeFrameSandbox(`${guestSandbox} allow-scripts`)}+ src={src}+ style={style}+ title={title}+ />+ )+}+function hasAllowedScheme(src: string): boolean {try {return ALLOWED_SRC_SCHEMES.has(new URL(src).protocol)diff --git a/apps/desktop/src/lib/browser-guest-document.test.ts b/apps/desktop/src/lib/browser-guest-document.test.tsnew file mode 100644index 00000000000..83de4984b27--- /dev/null+++ b/apps/desktop/src/lib/browser-guest-document.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest'++import { htmlFromDataUrl } from './browser-guest-document'++describe('htmlFromDataUrl', () => {+ it('decodes percent-encoded, base64 and charset-labelled HTML like the browser would', () => {+ expect(htmlFromDataUrl('data:text/html,<p>caf%C3%A9 & %3Cb%3E</p>')).toBe('<p>café & <b></p>')+ expect(htmlFromDataUrl(`data:text/html;base64,${btoa('<h1>hi</h1>')}`)).toBe('<h1>hi</h1>')+ expect(htmlFromDataUrl('data:TEXT/HTML ; charset=ISO-8859-1,caf%E9')).toBe('café')+ // The fragment is not part of the document.+ expect(htmlFromDataUrl('data:text/html,<a>x</a>#section')).toBe('<a>x</a>')+ })++ it('returns null for anything that is not a data: HTML document', () => {+ for (const src of [+ 'https://example.com/a.html',+ 'data:,plain',+ 'data:text/plain,<script>1</script>',+ 'data:image/svg+xml,%3Csvg%2F%3E',+ 'data:text/html',+ 'data:text/html;base64,***',+ 'not a url'+ ]) {+ expect(htmlFromDataUrl(src), src).toBeNull()+ }+ })+})diff --git a/apps/desktop/src/lib/browser-guest-document.ts b/apps/desktop/src/lib/browser-guest-document.tsnew file mode 100644index 00000000000..25cba8593b9--- /dev/null+++ b/apps/desktop/src/lib/browser-guest-document.ts@@ -0,0 +1,78 @@+/** The markup of a `data:text/html` URL, or null for any other src.+ *+ * The Webapp page CSP has no room for guest inline scripts, and a `data:`+ * document inherits it, so the browser host re-serves this markup through+ * the gateway's guest shell instead of navigating to the URL. Decoding+ * follows the URL standard's data: processor: the fragment is not content,+ * the body is percent-decoded bytes (or base64), and `charset=` picks the+ * decoder. */+export function htmlFromDataUrl(src: string): null | string {+ let url: URL++ try {+ url = new URL(src)+ } catch {+ return null+ }++ if (url.protocol !== 'data:') {+ return null+ }++ url.hash = ''+ const raw = url.href.slice('data:'.length)+ const comma = raw.indexOf(',')++ if (comma < 0) {+ return null+ }++ const [type = '', ...params] = raw+ .slice(0, comma)+ .split(';')+ .map(part => part.trim().toLowerCase())++ if (type !== 'text/html') {+ return null+ }++ const bytes = params.includes('base64') ? base64Bytes(raw.slice(comma + 1)) : percentBytes(raw.slice(comma + 1))++ if (!bytes) {+ return null+ }++ const charset = params.find(param => param.startsWith('charset='))?.slice('charset='.length) || 'utf-8'++ try {+ return new TextDecoder(charset).decode(bytes)+ } catch {+ return new TextDecoder().decode(bytes)+ }+}++function base64Bytes(body: string): null | Uint8Array {+ try {+ return Uint8Array.from(atob(decodeURIComponent(body).replace(/\s/g, '')), char => char.charCodeAt(0))+ } catch {+ return null+ }+}++function percentBytes(body: string): Uint8Array {+ const input = new TextEncoder().encode(body)+ const output: number[] = []++ for (let index = 0; index < input.length; index += 1) {+ const hex = input[index] === 0x25 ? String.fromCharCode(input[index + 1] ?? 0, input[index + 2] ?? 0) : ''++ if (/^[\da-f]{2}$/i.test(hex)) {+ output.push(parseInt(hex, 16))+ index += 2+ } else {+ output.push(input[index])+ }+ }++ return Uint8Array.from(output)+}diff --git a/hermes_cli/webapp_previews.py b/hermes_cli/webapp_previews.pyindex daa8d2aafa6..ab8b6d218fc 100644--- a/hermes_cli/webapp_previews.py+++ b/hermes_cli/webapp_previews.py@@ -7,14 +7,23 @@ 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; "+_GUEST_SOURCES = (+ "default-src 'none'; ""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-src * data: blob: about:; object-src 'none'; base-uri * about:; ""frame-ancestors 'self'")+PREVIEW_POLICY = f"{_GUEST_SOURCES}; sandbox allow-scripts; form-action 'none'"++# Plugin `SandboxedFrame` data: HTML (the SDK's allowlist, never allow-same-origin): the+# outer iframe's own sandbox attribute narrows this ceiling to what the plugin asked for,+# and a nested frame can never hold a flag its parent lacks.+GUEST_SANDBOX = (+ "allow-downloads allow-forms allow-orientation-lock allow-pointer-lock allow-presentation allow-scripts"+)+GUEST_POLICY = f"{_GUEST_SOURCES}; sandbox {GUEST_SANDBOX}; form-action *"# 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.@@ -28,7 +37,10 @@ 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' : '');+ const guest = typeof event.data.sandbox === 'string';+ frame.setAttribute('sandbox', guest ? event.data.sandbox : event.data.scripts === true ? 'allow-scripts' : '');+ // A plugin's onLoad means its guest document loaded, not this shell.+ frame.onload = guest ? () => parent.postMessage({type: 'hermes-guest-loaded'}, '*') : null;frame.srcdoc = event.data.html;document.body.append(frame);} else if (event.source === parent && event.origin === new URL(location.href).origin) {@@ -63,6 +75,15 @@ def mount_preview_assets(application: FastAPI) -> None:"X-Content-Type-Options": "nosniff",})+ @application.get("/assets/webapp-guest.html", dependencies=dependencies)+ async def guest_document():+ return HTMLResponse(PREVIEW_HTML, headers={+ "Content-Security-Policy": GUEST_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={diff --git a/tests/hermes_cli/test_webapp_preview_documents.py b/tests/hermes_cli/test_webapp_preview_documents.pyindex e90c61175b1..4f83a5cdafe 100644--- a/tests/hermes_cli/test_webapp_preview_documents.py+++ b/tests/hermes_cli/test_webapp_preview_documents.py@@ -40,5 +40,30 @@ def test_preview_assets_expose_only_a_sandboxed_empty_shell(client):@pytest.mark.parametrize("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"):+ for path in ("/assets/webapp-preview.html", "/assets/webapp-guest.html", "/assets/webapp-preview.js"):assert client.get(path).status_code == 404+++def _policy(response):+ return dict(part.strip().split(" ", 1) for part in response.headers["content-security-policy"].split(";"))+++def test_plugin_guest_shell_caps_at_the_sdk_sandbox_allowlist(client):+ """SandboxedFrame data: HTML runs here, never with same-origin or navigation tokens."""+ from hermes_cli import web_server as server++ response = client.get("/assets/webapp-guest.html", params={"html": "private-content"})+ assert response.status_code == 200+ policy = _policy(response)+ assert set(policy["sandbox"].split()) == {+ "allow-downloads", "allow-forms", "allow-orientation-lock",+ "allow-pointer-lock", "allow-presentation", "allow-scripts",+ }+ assert "'unsafe-inline'" in policy["script-src"].split()+ assert policy["frame-ancestors"] == "'self'"+ 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+ # File previews keep their own, narrower ceiling.+ assert _policy(client.get("/assets/webapp-preview.html"))["sandbox"] == "allow-scripts"diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.mdindex 42ce5c71bad..701ca99b1dc 100644--- a/website/docs/developer-guide/desktop-plugin-sdk.md+++ b/website/docs/developer-guide/desktop-plugin-sdk.md@@ -1072,6 +1072,17 @@ attribute is fully privileged. `loading="lazy"` andcontainment: guest content cannot reach the app, its storage, or the preloadbridge.+*Webapp (browser tab):* the page's Content-Security-Policy would also bind a+`data:` document, so a `data:text/html` src is rendered through the gateway's+guest shell (`/assets/webapp-guest.html`, its own policy, same opaque origin+and sandbox tokens) instead of being navigated to directly. Scripts run as on+native Desktop; messages the guest posts to `parent` arrive with+`event.source === ref.current.contentWindow`, messages posted to that window+reach the guest, and `onLoad` fires when the guest document has loaded (the+shell announces that with one `{type: 'hermes-guest-loaded'}` message from the+same window, so filter guest messages by type). Post+to `parent`, not `top`: the shell sits between them.+*Teardown:* it is a plain React element — unmounting your pane/page removes theframe and its realm; nothing is registered app-side.