The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): gate the preview guest bridge on a trusted click; trim salvage
teknium1408f5b78024b
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 69d99240d76..eac0d0f4a68 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -140,6 +140,35 @@ Two auth-flavored corollaries worth naming because they are easy to get wrong:nor write, so the session silently never persists. `electron/oauth-partition.ts`pins the invariant; renaming a partition signs its users out once — say so.+## Guest content never opens anything by itself++Untrusted HTML runs in two places: sandboxed `allow-scripts` iframes (artifact+previews) and the preview pane's `<webview>` (`persist:hermes-preview`). Neither+may drive the OS browser without the user's hand on it (GHSA-9f4c-93c8-jc8g):+`setWindowOpenHandler` denies everything and never opens a URL as a side+effect (`electron/window-open-policy.ts`), and the webview has no+`allowpopups` — do not add it.++A guest page's `target="_blank"` links (Streamlit's "Ask Google" traceback+button) reach the OS browser through one explicit bridge instead:++- `main.ts` installs `electron/preview-guest-preload-entry.ts` via+ `will-attach-webview`, keyed on the `persist:hermes-preview` partition only.+ It is the app's only guest preload; a new webview does not inherit it unless+ it opts into that partition.+- The preload runs in the isolated world, exposes nothing to the page, and+ forwards only a **trusted** (`event.isTrusted`) primary-button click on an+ `a[target="_blank"]` to the host via `ipcRenderer.sendToHost`. A synthetic+ `dispatchEvent(click)` from page script is dropped there; page `window.open`+ stays blocked.+- `PreviewPane` admits `http:`/`https:` only (`src/lib/preview-external.ts`)+ and hands the URL to the existing `hermes:openExternal` IPC, which applies+ main's URL policy. `file:` is excluded on purpose: a guest must never reach+ `shell.openPath`.++Widening any of those three (partition key, trusted-click gate, scheme set)+reopens the gesture-less forced-navigation class the advisory closed.+## Compatibility without carrying the past foreverDesktop and its runtime update on separate clocks, so a change can meet an olderdiff --git a/apps/desktop/electron/preview-guest-preload-entry.ts b/apps/desktop/electron/preview-guest-preload-entry.tsindex ddeb1203503..7a3daa2b990 100644--- a/apps/desktop/electron/preview-guest-preload-entry.ts+++ b/apps/desktop/electron/preview-guest-preload-entry.ts@@ -10,9 +10,10 @@// URL through the audited `hermes:openExternal` channel. A guest URL never// becomes an Electron popup and this side never opens anything by itself.//-// Deliberate scope: only anchor clicks are forwarded. A page's direct-// `window.open` calls stay blocked (the webview has no `allowpopups`), which-// keeps the pre-fix default for script-driven popups.+// Deliberate scope: only trusted anchor clicks are forwarded. A page's direct+// `window.open` calls stay blocked (the webview has no `allowpopups`): hooking+// them would mean reaching into the guest's JS world, and this preload exposes+// nothing there.import { installGuestExternalHandoff } from './preview-guest-preload'@@ -21,6 +22,6 @@ const electron = require('electron') as {}installGuestExternalHandoff({- addEventListener: (type, listener, capture) => document.addEventListener(type, listener as EventListener, capture),+ addEventListener: (type, listener, capture) => document.addEventListener(type, listener, capture),sendToHost: (channel, ...args) => electron.ipcRenderer.sendToHost(channel, ...args)})diff --git a/apps/desktop/electron/preview-guest-preload.test.ts b/apps/desktop/electron/preview-guest-preload.test.tsindex 136e9c3e5cf..6e4a034eb26 100644--- a/apps/desktop/electron/preview-guest-preload.test.ts+++ b/apps/desktop/electron/preview-guest-preload.test.ts@@ -2,62 +2,49 @@ import assert from 'node:assert/strict'import { describe, test } from 'vitest'-import { GUEST_EXTERNAL_CHANNEL, installGuestExternalHandoff } from './preview-guest-preload'+import { GUEST_EXTERNAL_CHANNEL, type GuestClickEvent, installGuestExternalHandoff } from './preview-guest-preload'+// Preview-pane guest bridge (#112941): the preload forwards a user's click on a+// `_blank` anchor to the host and nothing else.function rig() {const sent: { channel: string; args: unknown[] }[] = []- const listeners: { type: string; listener: (event: unknown) => void; capture?: boolean }[] = []+ const listeners: { type: string; listener: (event: GuestClickEvent) => void; capture?: boolean }[] = []- const host = {- addEventListener: (type: 'click', listener: (event: unknown) => void, capture?: boolean) =>- listeners.push({ type, listener, capture }),- sendToHost: (channel: string, ...args: unknown[]) => sent.push({ args, channel })- }-- installGuestExternalHandoff(host)+ installGuestExternalHandoff({+ addEventListener: (type, listener, capture) => listeners.push({ capture, listener, type }),+ sendToHost: (channel, ...args) => sent.push({ args, channel })+ })- return { click: (target: unknown) => listeners[0].listener({ target }), listeners, sent }+ return { click: (event: GuestClickEvent) => listeners[0].listener(event), listeners, sent }}-describe('installGuestExternalHandoff', () => {- test('registers one capture-phase click listener', () => {- const { listeners } = rig()+const blankAnchor = (href: string) => ({+ closest: (selector: string) => (selector === 'a[target="_blank"]' ? { href } : null)+})- assert.equal(listeners.length, 1)- assert.equal(listeners[0].type, 'click')- assert.equal(listeners[0].capture, true)- })+describe('installGuestExternalHandoff', () => {+ test('a trusted click inside a _blank anchor is forwarded once, in the capture phase', () => {+ const { click, listeners, sent } = rig()- test('forwards a clicked _blank anchor as the channel message', () => {- const { click, sent } = rig()+ assert.deepEqual(+ listeners.map(entry => [entry.type, entry.capture]),+ [['click', true]]+ )- click({- closest: (selector: string) =>- selector === 'a[target="_blank"]' ? { href: 'https://www.google.com/search?q=traceback' } : null- })+ click({ button: 0, isTrusted: true, target: blankAnchor('https://www.google.com/search?q=traceback') })assert.deepEqual(sent, [{ args: ['https://www.google.com/search?q=traceback'], channel: GUEST_EXTERNAL_CHANNEL }])})- test('climbs from an inner element through the shared DOM', () => {- const { click, sent } = rig()-- // The listener resolves the enclosing anchor itself via `closest`.- click({- closest: (selector: string) => (selector === 'a[target="_blank"]' ? { href: 'https://chatgpt.com/?q=why' } : null)- })-- assert.equal(sent.length, 1)- assert.equal(sent[0].args[0], 'https://chatgpt.com/?q=why')- })-- test('ignores clicks that resolve to no _blank anchor', () => {+ test('synthetic clicks, non-primary buttons and non-_blank targets are dropped', () => {const { click, sent } = rig()- click({ closest: () => null })- click({ closest: (selector: string) => (selector === 'a[target="_blank"]' ? { href: '' } : null) })- click(null)- click({})+ // Page script dispatching its own click event must not reach the OS browser.+ click({ button: 0, isTrusted: false, target: blankAnchor('https://evil.example/') })+ click({ button: 1, isTrusted: true, target: blankAnchor('https://evil.example/') })+ click({ button: 0, isTrusted: true, target: { closest: () => null } })+ click({ button: 0, isTrusted: true, target: blankAnchor('') })+ click({ button: 0, isTrusted: true, target: null })assert.deepEqual(sent, [])})diff --git a/apps/desktop/electron/preview-guest-preload.ts b/apps/desktop/electron/preview-guest-preload.tsindex 672ac25e7a2..cee6f55f157 100644--- a/apps/desktop/electron/preview-guest-preload.ts+++ b/apps/desktop/electron/preview-guest-preload.ts@@ -1,15 +1,23 @@// Logic half of the preview pane's guest preload. The wiring half lives in// `preview-guest-preload-entry.ts` (the bundled preload itself); this split// keeps the handoff rules unit-testable in a plain Node environment.-+//+// Mirrored by `PREVIEW_EXTERNAL_CHANNEL` in src/lib/preview-external.ts — the+// renderer tsconfig cannot import from electron/.export const GUEST_EXTERNAL_CHANNEL = 'preview-open-external'interface GuestEventTarget {closest(selector: string): { href: string } | null}+export interface GuestClickEvent {+ button?: number+ isTrusted?: boolean+ target?: unknown+}+export interface GuestHandoffHost {- addEventListener(type: 'click', listener: (event: unknown) => void, capture?: boolean): void+ addEventListener(type: 'click', listener: (event: GuestClickEvent) => void, capture?: boolean): voidsendToHost(channel: string, ...args: unknown[]): void}@@ -18,12 +26,21 @@ export interface GuestHandoffHost {* absolute URL to the host. `host` is injected so the entry can pass the* guest's `document` and `ipcRenderer`, and tests can drive the same rules* without Electron or a DOM.+ *+ * Only a trusted primary-button click qualifies. `isTrusted` is what keeps+ * this bridge out of the gesture-less forced-navigation class+ * (GHSA-9f4c-93c8-jc8g): page script can `dispatchEvent` a synthetic click+ * on an anchor, but it cannot forge `isTrusted`.*/export function installGuestExternalHandoff(host: GuestHandoffHost): void {host.addEventListener('click',event => {- const target = (event as { target?: unknown }).target as GuestEventTarget | null+ if (event.isTrusted !== true || (event.button ?? 0) !== 0) {+ return+ }++ const target = event.target as GuestEventTarget | nullif (!target || typeof target.closest !== 'function') {returndiff --git a/apps/desktop/electron/window-open-policy.test.ts b/apps/desktop/electron/window-open-policy.test.tsdeleted file mode 100644index 0edbd54b0d9..00000000000--- a/apps/desktop/electron/window-open-policy.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import assert from 'node:assert/strict'--import { test } from 'vitest'--import { createWindowOpenHandler, describeDeniedUrl } from './window-open-policy'--test('host handler denies every request and reports the origin only', () => {- const seen: string[] = []- const handler = createWindowOpenHandler(origin => seen.push(origin))-- assert.deepEqual(handler({ url: 'https://evil.example/path?token=x' }), { action: 'deny' })- assert.deepEqual(handler({ url: 'file:///etc/passwd' }), { action: 'deny' })- // Full URLs (query credentials, paths) never reach the observer.- assert.deepEqual(seen, ['https://evil.example', 'file:'])-})--test('host handler keeps denying when the observer throws', () => {- const handler = createWindowOpenHandler(() => {- throw new Error('observer blew up')- })-- assert.deepEqual(handler({ url: 'https://evil.example/' }), { action: 'deny' })-})--test('describeDeniedUrl sanitizes unparseable and opaque origins', () => {- assert.equal(describeDeniedUrl('https://example.com/x?y=1'), 'https://example.com')- assert.equal(describeDeniedUrl('data:text/html,hi'), 'data:')- assert.equal(describeDeniedUrl('not a url'), '<unparseable>')-})diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsxindex cc222db5f8a..5eb5e86169a 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx@@ -673,6 +673,8 @@ describe('PreviewPane console state', () => {})describe('PreviewPane guest external handoff', () => {+ // #112941: a guest page's `_blank` anchor (Streamlit's "Ask Google" button)+ // reaches the OS browser only through the audited `hermes:openExternal` IPC.const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }const initialHermesDesktop = desktopWindow.hermesDesktop@@ -685,6 +687,9 @@ describe('PreviewPane guest external handoff', () => {})async function renderWebview() {+ const openExternal = vi.fn(async () => undefined)+ desktopWindow.hermesDesktop = { openExternal } as unknown as Window['hermesDesktop']+let rendered!: ReturnType<typeof render>await act(async () => {@@ -700,49 +705,30 @@ describe('PreviewPane guest external handoff', () => {)})- return rendered.container.querySelector('webview') as HTMLElement+ return { openExternal, webview: rendered.container.querySelector('webview') as HTMLElement }}- function guestHandoff(webview: HTMLElement, url: string) {+ function guestMessage(webview: HTMLElement, url: string, channel = 'preview-open-external') {act(() => {- webview.dispatchEvent(Object.assign(new Event('ipc-message'), { args: [url], channel: 'preview-open-external' }))+ webview.dispatchEvent(Object.assign(new Event('ipc-message'), { args: [url], channel }))})}it('opens an admitted guest anchor URL through the audited OS-browser channel', async () => {- const openExternal = vi.fn(async () => undefined)- desktopWindow.hermesDesktop = { openExternal } as unknown as Window['hermesDesktop']-- const webview = await renderWebview()+ const { openExternal, webview } = await renderWebview()- guestHandoff(webview, 'https://www.google.com/search?q=traceback')+ guestMessage(webview, 'https://www.google.com/search?q=traceback')expect(openExternal).toHaveBeenCalledExactlyOnceWith('https://www.google.com/search?q=traceback')})- it('rejects file: and javascript: guest URLs without any OS open', async () => {- const openExternal = vi.fn(async () => undefined)- desktopWindow.hermesDesktop = { openExternal } as unknown as Window['hermesDesktop']-- const webview = await renderWebview()+ it('never opens non-web schemes or messages from a channel the preload does not own', async () => {+ const { openExternal, webview } = await renderWebview()- guestHandoff(webview, 'file:///etc/passwd')- guestHandoff(webview, 'javascript:alert(1)')-- expect(openExternal).not.toHaveBeenCalled()- })-- it('ignores channels the guest preload does not own', async () => {- const openExternal = vi.fn(async () => undefined)- desktopWindow.hermesDesktop = { openExternal } as unknown as Window['hermesDesktop']-- const webview = await renderWebview()-- act(() => {- webview.dispatchEvent(- Object.assign(new Event('ipc-message'), { args: ['https://example.com'], channel: 'something-else' })- )- })+ guestMessage(webview, 'file:///etc/passwd')+ guestMessage(webview, 'javascript:alert(1)')+ guestMessage(webview, 'mailto:[email protected]')+ guestMessage(webview, 'https://example.com', 'something-else')expect(openExternal).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex a3d6fb75118..6ee1715da5f 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -1029,7 +1029,7 @@ export function PreviewPane({ embedded = false, onRestartServer, reloadRequest =// The guest preload (main.ts installs it on this partition) forwards a// clicked `_blank` anchor here. Admission is our side of the contract —- // web/mail schemes only, so a guest page can never reach the local-file+ // http/https only, so a guest page can never reach the local-file// opener — and the open itself goes through the audited// `hermes:openExternal` channel, never a popup side effect.const onGuestExternal = (event: Event) => {diff --git a/apps/desktop/src/lib/preview-external.test.ts b/apps/desktop/src/lib/preview-external.test.tsdeleted file mode 100644index 6a87e6b652c..00000000000--- a/apps/desktop/src/lib/preview-external.test.ts+++ /dev/null@@ -1,34 +0,0 @@-import { describe, expect, it } from 'vitest'--import { admitPreviewExternalUrl, PREVIEW_EXTERNAL_CHANNEL } from './preview-external'--describe('admitPreviewExternalUrl', () => {- it('admits the web and mail schemes the guest handoff exists for', () => {- expect(admitPreviewExternalUrl('https://www.google.com/search?q=traceback')).toBe(true)- expect(admitPreviewExternalUrl('http://localhost:8501/')).toBe(true)- expect(admitPreviewExternalUrl('mailto:[email protected]')).toBe(true)- })-- it('rejects file: — a guest page must not reach the local-file opener', () => {- expect(admitPreviewExternalUrl('file:///etc/passwd')).toBe(false)- expect(admitPreviewExternalUrl('FILE:///Users/me/secret.txt')).toBe(false)- })-- it('rejects script-capable and opaque schemes', () => {- expect(admitPreviewExternalUrl('javascript:alert(1)')).toBe(false)- expect(admitPreviewExternalUrl('data:text/html,hi')).toBe(false)- expect(admitPreviewExternalUrl('blob:https://example.com/uuid')).toBe(false)- expect(admitPreviewExternalUrl('chrome://settings')).toBe(false)- })-- it('rejects unparseable and empty input', () => {- expect(admitPreviewExternalUrl('')).toBe(false)- expect(admitPreviewExternalUrl(' ')).toBe(false)- expect(admitPreviewExternalUrl('not a url')).toBe(false)- expect(admitPreviewExternalUrl('localhost:8501')).toBe(false)- })-- it('uses the channel the guest preload sends on', () => {- expect(PREVIEW_EXTERNAL_CHANNEL).toBe('preview-open-external')- })-})diff --git a/apps/desktop/src/lib/preview-external.ts b/apps/desktop/src/lib/preview-external.tsindex 393f1892652..1d8b4f7a724 100644--- a/apps/desktop/src/lib/preview-external.ts+++ b/apps/desktop/src/lib/preview-external.ts@@ -2,8 +2,8 @@// (electron/preview-guest-preload.ts, `preview-open-external` channel).//// A guest page chose this URL, not the user typing it, so the scheme set is-// strictly the web/mail subset of what main's `openExternalUrl` accepts.-// `file:` stays out on purpose: main's opener does open local files, but that+// strictly the web subset of what main's `openExternalUrl` accepts. `file:`+// stays out on purpose: main's opener does open local files, but that// capability belongs to host-driven surfaces (the artifacts panel), and an// untrusted preview page must never reach `shell.openPath` through us.@@ -19,7 +19,7 @@ export function admitPreviewExternalUrl(rawUrl: string): boolean {try {const { protocol } = new URL(raw)- return protocol === 'https:' || protocol === 'http:' || protocol === 'mailto:'+ return protocol === 'https:' || protocol === 'http:'} catch {return false}