The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): keep noopener and detect a blocked pop-out by handshake
Adolaniumb94a130355f8
diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex a5aaba6715d..1f5c65f164f 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { reconnectMovedCloudAgent } from '@/app/settings/cloud-team-change'import { $connection } from '@/store/session'import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'+import { browserOpensWebappWindows } from '@/test/webapp-windows'import { installBrowserDesktopBridge } from './browser-desktop-bridge'import { desktopGit } from './desktop-git'@@ -329,7 +330,7 @@ describe('browser-hosted Desktop bridge', () => {// A gated host opens the window directly; a launch-link tab hands it a session first.win.__HERMES_AUTH_REQUIRED__ = truewindow.history.replaceState(null, '', '/?profile=work#/existing')- const open = vi.spyOn(window, 'open').mockImplementation(() => ({}) as Window)+ const { open } = browserOpensWebappWindows()expect(installBrowserDesktopBridge()).toBe(true)await expect(@@ -343,7 +344,7 @@ describe('browser-hosted Desktop bridge', () => {expect(url.searchParams.get('watch')).toBe('1')expect(url.hash).toBe('#/session%20%2F%201')expect(target).toBe('_blank')- expect(features).toBeUndefined()+ expect(features).toBe('noopener,noreferrer')})it('hands only the schemes Electron opens externally to window.open', async () => {@@ -395,7 +396,7 @@ describe('browser-hosted Desktop bridge', () => {// A gated host opens the window directly; a launch-link tab hands it a session first.win.__HERMES_AUTH_REQUIRED__ = truewindow.history.replaceState(null, '', '/?profile=work#/existing')- const open = vi.spyOn(window, 'open').mockImplementation(() => ({}) as Window)+ const { open } = browserOpensWebappWindows()expect(installBrowserDesktopBridge()).toBe(true)await expect(win.hermesDesktop!.openSessionWindow('session-1', opts)).resolves.toEqual({ ok: true })diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.tsindex ac4c0515625..31d8eda9d36 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts@@ -11,7 +11,7 @@ import { createBrowserSettings } from '@/lib/browser-settings'import { createBrowserTerminal } from '@/lib/browser-terminal'import { browserApi, browserBootstrap, ticketedWebsocketUrl } from '@/lib/browser-transport'import { createBrowserUploadsBridge } from '@/lib/browser-uploads'-import { createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'+import { announceWebappWindow, createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'import { createBrowserZoom } from '@/lib/browser-zoom'import { failDesktopBoot } from '@/store/boot'import { $connection } from '@/store/session'@@ -36,6 +36,9 @@ export function installBrowserDesktopBridge(): boolean {if (!bootstrap) {return false}+ // A gated host's opener waits for this window to say it booted (createBrowserWindowOpener).+ if (!bootstrap.privateSession) {announceWebappWindow()}+const api = <T>(request: HermesApiRequest) => browserApi<T>(bootstrap, request)const currentProfile = () => $connection.get()?.profile?.trim() || windowProfileOverride()diff --git a/apps/desktop/src/lib/browser-launch-session.test.ts b/apps/desktop/src/lib/browser-launch-session.test.tsindex 8e2176ca43f..602f44095fc 100644--- a/apps/desktop/src/lib/browser-launch-session.test.ts+++ b/apps/desktop/src/lib/browser-launch-session.test.ts@@ -152,7 +152,7 @@ it.each(['window', 'session'] as const)('hands off a private %s through a one-usclose = vi.fn()}vi.stubGlobal('BroadcastChannel', Channel)- const open = vi.spyOn(window, 'open').mockReturnValue({} as Window)+ const open = vi.spyOn(window, 'open').mockReturnValue(null)expect(installBrowserDesktopBridge()).toBe(true)const pending = kind === 'window'@@ -183,8 +183,7 @@ it.each(['window', 'session'] as const)('hands off a private %s through a one-usexpect(handoff.get('query')).toContain('profile=research')expect(handoff.get('route')).toBe(kind === 'window' ? '/' : '/session%20%2F%201')expect(handoff.get('query')?.includes('watch=1')).toBe(kind === 'session')- expect(target).toBe('_blank')- expect(features).toBeUndefined()+ expect([target, features]).toEqual(['_blank', 'noopener,noreferrer'])expect(String(opened)).not.toContain(token)expect(String(opened)).not.toContain(ticket)expect(window.location.search).toBe('?profile=coder')diff --git a/apps/desktop/src/lib/browser-profile.test.ts b/apps/desktop/src/lib/browser-profile.test.tsindex d3fd146d64a..66ec8cf91fb 100644--- a/apps/desktop/src/lib/browser-profile.test.ts+++ b/apps/desktop/src/lib/browser-profile.test.ts@@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { $connection } from '@/store/session'import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'+import { browserOpensWebappWindows } from '@/test/webapp-windows'import { installBrowserDesktopBridge } from './browser-desktop-bridge'@@ -80,7 +81,7 @@ it('opens the requested profile on this host without carrying another session or// A gated host opens the window directly; a launch-link tab hands it a session first.bootstrap.__HERMES_AUTH_REQUIRED__ = truewindow.history.replaceState(null, '', '/hermes?profile=active&win=secondary&watch=1#/session-1')- const open = vi.spyOn(window, 'open').mockImplementation(() => ({}) as Window)+ const { open } = browserOpensWebappWindows()expect(installBrowserDesktopBridge()).toBe(true)const originalUrl = window.location.hrefdiff --git a/apps/desktop/src/lib/browser-window.test.ts b/apps/desktop/src/lib/browser-window.test.tsindex 479ec211c24..bf33380099a 100644--- a/apps/desktop/src/lib/browser-window.test.ts+++ b/apps/desktop/src/lib/browser-window.test.ts@@ -1,12 +1,21 @@import { afterEach, describe, expect, it, vi } from 'vitest'+import { browserOpensWebappWindows, stubBroadcastChannels } from '@/test/webapp-windows'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'import { createBrowserWindowOpener } from './browser-window'const POPUP_BLOCKED = 'Webapp window did not open. Allow popups for this site and try again.'+const bootstrap = window as Window & { __HERMES_AUTH_REQUIRED__?: boolean }afterEach(() => {- vi.restoreAllMocks()+ vi.useRealTimers()+ Reflect.deleteProperty(window, 'hermesDesktop')+ delete bootstrap.__HERMES_AUTH_REQUIRED__+ window.document.documentElement.removeAttribute('data-hermes-desktop-host')+ window.history.replaceState(null, '', '/')vi.unstubAllGlobals()+ vi.restoreAllMocks()})function opener(privateSession: boolean, api = vi.fn()) {@@ -14,46 +23,114 @@ function opener(privateSession: boolean, api = vi.fn()) {}function target(): URL {- return new URL('/?win=secondary#/session-1', window.location.origin)+ return new URL('/one/?profile=coder&win=secondary#/session-1', window.location.origin)}-// The browser's side of window.open: `child` is null when the popup blocker stops the window, and a-// `noopener` or `noreferrer` open returns null even when the window opens (HTML window open steps).-function browserOpens(child: Window | null) {- return vi.spyOn(window, 'open').mockImplementation((_url, _target, features) =>- /noopener|noreferrer/.test(features ?? '') ? null : child- )+/** 'opened' or the rejection message once the pop-out settles, so a test can look while it is pending. */+function outcome(pending: Promise<unknown>): () => string | undefined {+ let result: string | undefined+ pending.then(() => { result = 'opened' }, (error: Error) => { result = error.message })++ return () => result+}++/** `/webapp/window` as the gateway serves it: says ready on the channel its fragment names, done once it has a ticket. */+function handoffPage(href: string): unknown[] {+ const id = new URLSearchParams(new URL(href).hash.slice(1)).get('channel')+ const channel = new BroadcastChannel(`hermes.webapp.window:${id}`)+ const received: unknown[] = []++ channel.onmessage = event => {+ received.push(event.data)++ if (event.data?.ticket) {+ channel.postMessage({ type: 'done' })+ channel.close()+ }+ }++ channel.postMessage({ type: 'ready' })++ return received}-describe('browser pop-out', () => {- it('reports a blocked popup instead of success', async () => {- browserOpens(null)+describe('gated host pop-out', () => {+ it('reports a window the browser blocked within seconds', async () => {+ vi.useFakeTimers()+ const { channels, open } = browserOpensWebappWindows({ blocked: true })+ const result = outcome(opener(false)(target()))- await expect(opener(false)(target())).rejects.toThrow(POPUP_BLOCKED)+ await vi.advanceTimersByTimeAsync(0)+ expect(result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(5_000)+ expect(result()).toBe(POPUP_BLOCKED)+ expect(open.mock.calls[0]?.[2]).toBe('noopener,noreferrer')+ expect(channels.size).toBe(0)})- it('resolves when the browser opens the window and severs its opener', async () => {- const child = { opener: window } as Window- const open = browserOpens(child)- const href = target().href+ it('resolves once the window boots, which drops the hello from its address', async () => {+ vi.useFakeTimers()+ // A gated host may be served over plain HTTP, where crypto.randomUUID does not exist.+ const { getRandomValues } = crypto+ vi.stubGlobal('crypto', { getRandomValues: getRandomValues.bind(crypto) })+ const channels = stubBroadcastChannels()+ const open = vi.spyOn(window, 'open').mockReturnValue(null)+ const result = outcome(opener(false)(target()))+ const [href, name, features] = open.mock.calls[0]+ expect([name, features]).toEqual(['_blank', 'noopener,noreferrer'])++ // The window loads that address and boots the Webapp.+ bootstrap.__HERMES_AUTH_REQUIRED__ = true+ window.history.replaceState(null, '', String(href))+ expect(installBrowserDesktopBridge()).toBe(true)+ await vi.advanceTimersByTimeAsync(5_000)- await expect(opener(false)(new URL(href))).resolves.toEqual({ ok: true })- expect(open.mock.calls[0]?.[0]).toBe(href)- expect(child.opener).toBeNull()+ expect(result()).toBe('opened')+ const booted = new URL(window.location.href)+ expect([...booted.searchParams.keys()].sort()).toEqual(['profile', 'win'])+ expect(booted.hash).toBe('#/session-1')+ expect(channels.size).toBe(0)})+})- it('reports a blocked private-session popup without waiting for the handoff', async () => {- browserOpens(null)- vi.stubGlobal(- 'BroadcastChannel',- class {- onmessage: ((event: { data: unknown }) => void) | null = null- close() {}- }- )+describe('launch-link pop-out', () => {+ it('reports a window that has not said ready within seconds and stops listening when the handoff expires', async () => {+ vi.useFakeTimers()+ const { channels, open } = browserOpensWebappWindows({ blocked: true })const api = vi.fn()+ const result = outcome(opener(true, api)(target()))- await expect(opener(true, api)(target())).rejects.toThrow(POPUP_BLOCKED)+ await vi.advanceTimersByTimeAsync(0)+ expect(result()).toBeUndefined()+ await vi.advanceTimersByTimeAsync(5_000)+ expect(result()).toBe(POPUP_BLOCKED)+ // Still listening: a late window could yet say ready.+ expect(channels.size).toBe(1)+ await vi.advanceTimersByTimeAsync(25_000)+ expect(channels.size).toBe(0)expect(api).not.toHaveBeenCalled()+ expect(open.mock.calls[0]?.[2]).toBe('noopener,noreferrer')+ })++ it('signs in a blocked window the user opens from the blocked-popup prompt before the handoff expires', async () => {+ vi.useFakeTimers()+ const ticket = 'b'.repeat(43)+ const { channels, open } = browserOpensWebappWindows({ blocked: true })+ const api = vi.fn().mockResolvedValue({ ticket })+ const result = outcome(opener(true, api)(target()))++ await vi.advanceTimersByTimeAsync(5_000)+ expect(result()).toBe(POPUP_BLOCKED)+ expect(api).not.toHaveBeenCalled()++ // The browser's "Pop-ups blocked" prompt opens the address it stopped.+ await vi.advanceTimersByTimeAsync(10_000)+ const received = handoffPage(String(open.mock.calls[0]?.[0]))+ await vi.advanceTimersByTimeAsync(0)++ expect(api).toHaveBeenCalledOnce()+ expect(received).toEqual([{ ticket }])+ expect(channels.size).toBe(0)+ expect(result()).toBe(POPUP_BLOCKED)})})diff --git a/apps/desktop/src/lib/browser-window.ts b/apps/desktop/src/lib/browser-window.tsindex 661bc1ae107..10348463cfc 100644--- a/apps/desktop/src/lib/browser-window.ts+++ b/apps/desktop/src/lib/browser-window.ts@@ -10,85 +10,147 @@ interface BrowserWindowOptions {const POPUP_BLOCKED = 'Webapp window did not open. Allow popups for this site and try again.'-// No `noopener`: with it, window.open returns null even when the window opens (HTML "window-// open steps"), so a blocked popup cannot be told from an open one. Severing `opener` on the-// handle keeps the window from reaching this one. The rest of what noopener prevented now-// happens: the browser copies this tab's sessionStorage into the window and sends this URL as a-// same-origin Referer. The only credential in that copy is the launch-link one, which the window-// ticket below hands over anyway.-function openWebappWindow(href: string): Window | null {- const opened = window.open(href, '_blank')+// The new window gets its own browsing context group: it does not share this tab's event loop,+// starts with empty sessionStorage and gets no Referer. The cost: window.open returns null whether+// or not the window opened (HTML "window open steps"), so each window says `ready` on a+// BroadcastChannel instead.+const WINDOW_FEATURES = 'noopener,noreferrer'- if (!opened) {return null}+// A window that has not said `ready` by then is reported as blocked. In Chrome, Edge and WebKit a+// window that opened said it within 0.4 s (the launch-link handoff page) and about 1.3 s (the+// whole app on a gated host), even with the browser held to one CPU. A slower window still opens+// after the toast, and on a launch-link tab it still signs in.+const READY_DEADLINE_MS = 3_000- opened.opener = null+// A gated host's window is the app itself, which says `ready` at boot on the channel this+// parameter names (`announceWebappWindow`).+const HELLO_PARAM = 'hello'- return opened+const helloChannel = (id: string) => `hermes.webapp.hello:${id}`++// Not crypto.randomUUID: it exists only in secure contexts, and a gated host may be served over+// plain HTTP from another machine.+const helloId = () => Array.from(crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('')++const asError = (error: unknown) => (error instanceof Error ? error : new Error(String(error)))++/** Open synchronously in the user gesture; never rely on an opener/storage copy. */+export function createBrowserWindowOpener({ api, basePath, privateSession }: BrowserWindowOptions) {+ return (target: URL): Promise<{ ok: true }> =>+ privateSession ? openLaunchLinkWindow(target, api, basePath) : openGatedWindow(target)+}++function openGatedWindow(target: URL): Promise<{ ok: true }> {+ const id = helloId()+ const channel = new BroadcastChannel(helloChannel(id))+ const href = new URL(target)+ href.searchParams.set(HELLO_PARAM, id)++ return new Promise((resolve, reject) => {+ const finish = (error?: Error) => {+ window.clearTimeout(deadline)+ channel.close()++ if (error) {reject(error)} else {resolve({ ok: true })}+ }++ const deadline = window.setTimeout(() => finish(new Error(POPUP_BLOCKED)), READY_DEADLINE_MS)++ channel.onmessage = event => {+ if (event.data?.type === 'ready') {finish()}+ }++ try {+ window.open(href.href, '_blank', WINDOW_FEATURES)+ } catch (error) {+ finish(asError(error))+ }+ })}/**- * Open synchronously in the user gesture. A launch-link tab's window signs in with a one-use ticket- * and does not rely on the opener or on the sessionStorage copy.+ * The window opens on the handoff page, which says `ready` and signs in with a one-use ticket this+ * tab mints for it. Past the deadline the promise rejects as blocked, but the channel stays open+ * until the handoff expires: a window that starts late, or one the user opens from the browser's+ * blocked-popup prompt, still signs in.*/-export function createBrowserWindowOpener({ api, basePath, privateSession }: BrowserWindowOptions) {- return (target: URL): Promise<{ ok: true }> => {- if (!privateSession) {- if (!openWebappWindow(target.href)) {- return Promise.reject(new Error(POPUP_BLOCKED))- }+function openLaunchLinkWindow(+ target: URL,+ api: BrowserWindowOptions['api'],+ basePath: string+): Promise<{ ok: true }> {+ const id = randomUuid()+ const channel = new BroadcastChannel(`hermes.webapp.window:${id}`)+ const launch = new URL(`${basePath}/webapp/window`, window.location.origin)+ launch.hash = new URLSearchParams({ channel: id, query: target.search, route: target.hash.slice(1) }).toString()- return Promise.resolve({ ok: true })- }+ return new Promise((resolve, reject) => {+ let minting = false+ let closed = false- const id = randomUuid()- const channel = new BroadcastChannel(`hermes.webapp.window:${id}`)- const launch = new URL(`${basePath}/webapp/window`, window.location.origin)- launch.hash = new URLSearchParams({ channel: id, query: target.search, route: target.hash.slice(1) }).toString()+ // Once the deadline has rejected the promise, a later done or error only closes the channel.+ const settle = (error?: Error) => {+ window.clearTimeout(deadline)- return new Promise((resolve, reject) => {- let minting = false- let settled = false+ if (error) {reject(error)} else {resolve({ ok: true })}+ }- const finish = (error?: Error) => {- if (settled) {return}- settled = true- window.clearTimeout(timeout)- channel.close()+ const close = (error?: Error) => {+ closed = true+ window.clearTimeout(expiry)+ channel.close()+ settle(error)+ }- if (error) {reject(error)} else {resolve({ ok: true })}+ const deadline = window.setTimeout(() => settle(new Error(POPUP_BLOCKED)), READY_DEADLINE_MS)+ const expiry = window.setTimeout(() => close(new Error(POPUP_BLOCKED)), 30_000)++ channel.onmessage = event => {+ if (closed) {return}++ if (event.data?.type === 'ready' && !minting) {+ minting = true+ window.clearTimeout(deadline)+ void api<{ ticket: string }>({ method: 'POST', path: '/api/webapp/window-ticket' }).then(({ ticket }) => {+ if (closed) {return}+ channel.postMessage({ ticket })+ }).catch(error => {+ if (closed) {return}+ channel.postMessage({ error: 'Could not authorize this window. Try opening it again from the original tab.' })+ close(asError(error))+ })+ } else if (event.data?.type === 'done') {+ close()+ } else if (event.data?.type === 'error') {+ close(new Error('Could not authorize the Webapp window. Try opening it again.'))}+ }- const timeout = window.setTimeout(() => finish(new Error(POPUP_BLOCKED)), 30_000)-- channel.onmessage = event => {- if (settled) {return}-- if (event.data?.type === 'ready' && !minting) {- minting = true- void api<{ ticket: string }>({ method: 'POST', path: '/api/webapp/window-ticket' }).then(({ ticket }) => {- if (settled) {return}- channel.postMessage({ ticket })- }).catch(error => {- if (settled) {return}- channel.postMessage({ error: 'Could not authorize this window. Try opening it again from the original tab.' })- finish(error instanceof Error ? error : new Error(String(error)))- })- } else if (event.data?.type === 'done') {- finish()- } else if (event.data?.type === 'error') {- finish(new Error('Could not authorize the Webapp window. Try opening it again.'))- }- }+ try {+ window.open(launch.href, '_blank', WINDOW_FEATURES)+ } catch (error) {+ close(asError(error))+ }+ })+}- try {- if (!openWebappWindow(launch.href)) {- finish(new Error(POPUP_BLOCKED))- }- } catch (error) {- finish(error instanceof Error ? error : new Error(String(error)))- }- })- }+/**+ * In a window a gated host opened: say `ready` on the channel its address names, then drop the+ * name from the address. The message carries nothing, so a same-origin page that guessed the+ * name could at most spare the opener its blocked-popup toast.+ */+export function announceWebappWindow(): void {+ const url = new URL(window.location.href)+ const id = url.searchParams.get(HELLO_PARAM)++ if (id === null) {return}+ url.searchParams.delete(HELLO_PARAM)+ window.history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`)++ if (!/^[a-f0-9]{32}$/.test(id)) {return}+ const channel = new BroadcastChannel(helloChannel(id))+ channel.postMessage({ type: 'ready' })+ channel.close()}/** The secondary-window URL showing one session, or null for an empty session id. */diff --git a/apps/desktop/src/test/webapp-windows.ts b/apps/desktop/src/test/webapp-windows.tsnew file mode 100644index 00000000000..6436e172b6b--- /dev/null+++ b/apps/desktop/src/test/webapp-windows.ts@@ -0,0 +1,66 @@+import { vi } from 'vitest'++import { announceWebappWindow } from '@/lib/browser-window'++/**+ * BroadcastChannel as a browser delivers it within one origin: asynchronously, to every other open+ * channel with the same name, never to the sender, and never after either side closes.+ */+class Channel {+ static open = new Set<Channel>()+ onmessage: ((event: MessageEvent) => void) | null = null++ constructor(readonly name: string) {+ Channel.open.add(this)+ }++ postMessage(data: unknown) {+ if (!Channel.open.has(this)) {throw new DOMException('BroadcastChannel is closed', 'InvalidStateError')}++ for (const peer of Channel.open) {+ if (peer !== this && peer.name === this.name) {+ queueMicrotask(() => {+ if (Channel.open.has(peer)) {peer.onmessage?.(new MessageEvent('message', { data }))}+ })+ }+ }+ }++ close() {+ Channel.open.delete(this)+ }+}++/** Every open channel, for asserting what is still listening. */+export function stubBroadcastChannels(): ReadonlySet<Channel> {+ Channel.open.clear()+ vi.stubGlobal('BroadcastChannel', Channel)++ return Channel.open+}++/**+ * The browser's side of a Webapp pop-out. As in a browser, `window.open` returns null when the+ * popup blocker stops the window, and for a `noopener` or `noreferrer` open even when the window+ * opens. Unless `blocked`, each window opens and boots the Webapp at its address, which runs the+ * boot hello (`announceWebappWindow`). This test has one jsdom window, so the boot borrows its+ * address and puts it back.+ */+export function browserOpensWebappWindows({ blocked = false } = {}) {+ const channels = stubBroadcastChannels()++ const open = vi.spyOn(window, 'open').mockImplementation((url, _target, features) => {+ if (blocked) {return null}++ queueMicrotask(() => {+ const opener = window.location.href+ window.history.replaceState(null, '', String(url))+ announceWebappWindow()+ window.history.replaceState(null, '', opener)+ })++ return /noopener|noreferrer/.test(features ?? '') ? null : ({ opener: window } as Window)+ })++ return { channels, open }+}