Skip to content

The agent that grows with you

fix(webapp): the launch link leaves the browser credential out of the browser's history

emozillababc763a0fa1
diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.ts
index 114a2714279..ac4c0515625 100644
--- a/apps/desktop/src/lib/browser-desktop-bridge.ts
+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts
@@ -5,7 +5,7 @@ import { BROWSER_BRIDGE_STUBS } from '@/lib/browser-bridge-stubs'
import { createBrowserClipboardBridge } from '@/lib/browser-clipboard'
import { createBrowserConnectionBridge } from '@/lib/browser-connection'
import { createBrowserFilesBridge } from '@/lib/browser-files'
-import { watchWebappLaunchLink, WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'
+import { WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'
import { createBrowserProfileBridge } from '@/lib/browser-profile'
import { createBrowserSettings } from '@/lib/browser-settings'
import { createBrowserTerminal } from '@/lib/browser-terminal'
@@ -36,10 +36,6 @@ export function installBrowserDesktopBridge(): boolean {
if (!bootstrap) {return false}
- if (bootstrap.privateSession) {
- watchWebappLaunchLink(() => window.location.reload())
- }
-
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.ts
index 36388bbba94..410be652f1e 100644
--- a/apps/desktop/src/lib/browser-launch-session.test.ts
+++ b/apps/desktop/src/lib/browser-launch-session.test.ts
@@ -4,7 +4,7 @@ import { afterEach, expect, it, vi } from 'vitest'
import { pluginSocket } from '@/api/plugins'
import { installBrowserDesktopBridge } from './browser-desktop-bridge'
-import { consumeWebappSession, watchWebappLaunchLink, WEBAPP_LAUNCH_REQUIRED } from './browser-launch-session'
+import { readWebappSession, WEBAPP_LAUNCH_REQUIRED, webappSessionKey } from './browser-launch-session'
const win = window as Window & {
__HERMES_UI_SURFACE__?: string
@@ -29,7 +29,9 @@ it('uses one private session for REST, RPC and terminal across reload without lo
const token = 'a'.repeat(43)
win.__HERMES_UI_SURFACE__ = 'webapp'
win.__HERMES_BASE_PATH__ = '/one'
- window.history.replaceState(null, '', `/one/?profile=coder#hermes-session=${token}`)
+ // Where /webapp/launch leaves the credential before it opens /one/?profile=coder.
+ sessionStorage.setItem(webappSessionKey('/one'), token)
+ window.history.replaceState(null, '', '/one/?profile=coder')
const urls: URL[] = []
class Socket {
@@ -96,7 +98,7 @@ it('uses one private session for REST, RPC and terminal across reload without lo
expect(installBrowserDesktopBridge()).toBe(true)
expect((await window.hermesDesktop!.getConnection()).token).toBe(token)
expect(window.location.hash).toBe('#/settings')
- expect(consumeWebappSession('/other')).toBe('')
+ expect(readWebappSession('/other')).toBe('')
expect(Object.values(localStorage)).not.toContain(token)
})
@@ -110,31 +112,25 @@ it('fails closed with actionable launch instructions in a fresh tab and ignores
expect(fetchMock).not.toHaveBeenCalled()
window.dispatchEvent(new Event('beforeunload'))
Reflect.deleteProperty(window, 'hermesDesktop')
- window.history.replaceState(null, '', `/#hermes-session=${'b'.repeat(43)}`)
- expect(consumeWebappSession('')).toHaveLength(43)
- window.history.replaceState(null, '', '/#hermes-session=invalid')
- expect(consumeWebappSession('')).toBe('')
- expect(consumeWebappSession('')).toBe('')
+ sessionStorage.setItem(webappSessionKey(''), 'b'.repeat(43))
+ expect(readWebappSession('')).toHaveLength(43)
+ sessionStorage.clear()
+ expect(readWebappSession('')).toBe('')
win.__HERMES_AUTH_REQUIRED__ = true
expect(installBrowserDesktopBridge()).toBe(true)
expect((await window.hermesDesktop!.getConnection()).authMode).toBe('oauth')
expect((await window.hermesDesktop!.getConnection()).token).toBe('')
})
-it('reloads for a pasted launch fragment but not HashRouter navigation', () => {
- const reload = vi.fn()
- watchWebappLaunchLink(reload)
- window.history.replaceState(null, '', '/#/settings')
- window.dispatchEvent(new HashChangeEvent('hashchange'))
- expect(reload).not.toHaveBeenCalled()
- const fragment = `#hermes-session=${'c'.repeat(43)}`
- window.history.replaceState(null, '', `/${fragment}`)
- window.dispatchEvent(new HashChangeEvent('hashchange'))
- expect(reload).toHaveBeenCalledOnce()
- expect(window.location.hash).toBe(fragment)
- window.dispatchEvent(new Event('beforeunload'))
- window.dispatchEvent(new HashChangeEvent('hashchange'))
- expect(reload).toHaveBeenCalledOnce()
+it('takes the credential only from the tab storage the launch page fills, never from the address', () => {
+ // The browser records every address in its history, where a credential would outlive the tab.
+ win.__HERMES_UI_SURFACE__ = 'webapp'
+ window.history.replaceState(null, '', `/?profile=coder#hermes-session=${'c'.repeat(43)}`)
+ expect(readWebappSession('')).toBe('')
+ expect(installBrowserDesktopBridge()).toBe(true)
+ expect(sessionStorage.length).toBe(0)
+ sessionStorage.setItem(webappSessionKey(''), 'd'.repeat(43))
+ expect(readWebappSession('')).toBe('d'.repeat(43))
})
it.each(['window', 'session'] as const)('hands off a private %s through a one-use ticket without sharing its session token', async kind => {
@@ -142,7 +138,8 @@ it.each(['window', 'session'] as const)('hands off a private %s through a one-us
const ticket = 'b'.repeat(43)
win.__HERMES_UI_SURFACE__ = 'webapp'
win.__HERMES_BASE_PATH__ = '/one'
- window.history.replaceState(null, '', `/one/?profile=coder#hermes-session=${token}`)
+ sessionStorage.setItem(webappSessionKey('/one'), token)
+ window.history.replaceState(null, '', '/one/?profile=coder')
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ticket })))
vi.stubGlobal('fetch', fetchMock)
@@ -219,7 +216,7 @@ it('asks a tab without a working credential to sign in, so reconnecting stops',
// hermes webapp --sign-out replaced the credential this tab holds.
window.dispatchEvent(new Event('beforeunload'))
Reflect.deleteProperty(window, 'hermesDesktop')
- window.history.replaceState(null, '', `/#hermes-session=${'d'.repeat(43)}`)
+ sessionStorage.setItem(webappSessionKey(''), 'd'.repeat(43))
expect(installBrowserDesktopBridge()).toBe(true)
const signedOut = await failure(window.hermesDesktop!.api({ path: '/api/status' }))
diff --git a/apps/desktop/src/lib/browser-launch-session.ts b/apps/desktop/src/lib/browser-launch-session.ts
index 0d9509e10e2..71055675f6f 100644
--- a/apps/desktop/src/lib/browser-launch-session.ts
+++ b/apps/desktop/src/lib/browser-launch-session.ts
@@ -1,7 +1,5 @@
import { GatewayReauthRequiredError } from '@hermes/shared'
-const FRAGMENT_KEY = 'hermes-session'
-
export const WEBAPP_LAUNCH_REQUIRED = 'Run hermes webapp on this computer to sign this browser in.'
/**
@@ -12,38 +10,16 @@ export function webappSignInRequired(): GatewayReauthRequiredError {
return new GatewayReauthRequiredError(WEBAPP_LAUNCH_REQUIRED)
}
-/** Pasting the launch link over a bare URL is a same-document navigation. */
-export function watchWebappLaunchLink(reload: () => void): void {
- const onHash = () => {
- // Leave the fragment intact: startup consumes it even if storage is disabled.
- if (window.location.hash.startsWith(`#${FRAGMENT_KEY}=`)) {reload()}
- }
-
- window.addEventListener('hashchange', onHash)
- window.addEventListener('beforeunload', () => window.removeEventListener('hashchange', onHash), { once: true })
-}
-
/** Where this tab keeps its launch-link grant for the Webapp at ``basePath`` on this origin. */
export function webappSessionKey(basePath: string): string {
return `hermes.webapp.session.v1:${JSON.stringify([window.location.origin, basePath])}`
}
-/** HTTP never supplies this credential; reloads keep only this tab's grant. */
-export function consumeWebappSession(basePath: string): string {
- const key = webappSessionKey(basePath)
-
- // HashRouter owns other fragments; don't parse/rewrite its route on reload.
- if (window.location.hash.startsWith(`#${FRAGMENT_KEY}=`)) {
- const supplied = new URLSearchParams(window.location.hash.slice(1)).getAll(FRAGMENT_KEY)
- window.history.replaceState(window.history.state, '', `${window.location.pathname}${window.location.search}`)
- const token = supplied.length === 1 && /^[A-Za-z0-9_-]{43}$/.test(supplied[0]) ? supplied[0] : ''
-
- try {
- if (token) {sessionStorage.setItem(key, token)} else {sessionStorage.removeItem(key)}
- } catch { /* Storage may be disabled; the current page can still use its link. */ }
-
- return token
- }
-
- try { return sessionStorage.getItem(key) || '' } catch { return '' }
+/**
+ * This tab's credential, which the launch and child-window pages (``/webapp/launch``,
+ * ``/webapp/window``) leave in its sessionStorage. It never travels in a URL: the browser would keep
+ * that in its history. Reloads keep only this tab's grant.
+ */
+export function readWebappSession(basePath: string): string {
+ try { return sessionStorage.getItem(webappSessionKey(basePath)) || '' } catch { return '' }
}
diff --git a/apps/desktop/src/lib/browser-transport.ts b/apps/desktop/src/lib/browser-transport.ts
index 8b523b64ce8..d8f73923694 100644
--- a/apps/desktop/src/lib/browser-transport.ts
+++ b/apps/desktop/src/lib/browser-transport.ts
@@ -1,7 +1,7 @@
import { BROWSER_NATIVE_DIAL, buildHermesWebSocketUrl, normalizeBasePath } from '@hermes/shared'
import type { HermesApiRequest } from '@/global'
-import { consumeWebappSession, webappSignInRequired } from '@/lib/browser-launch-session'
+import { readWebappSession, webappSignInRequired } from '@/lib/browser-launch-session'
import { type BrowserHostGlobals, hasBrowserHostBootstrap } from '@/lib/platform'
export interface BrowserBootstrap {
@@ -34,7 +34,7 @@ export function browserBootstrap(): BrowserBootstrap | null {
const authRequired = win.__HERMES_AUTH_REQUIRED__ === true
const basePath = normalizeBasePath(win.__HERMES_BASE_PATH__)
const privateSession = !authRequired && win.__HERMES_UI_SURFACE__ === 'webapp'
- const token = privateSession ? consumeWebappSession(basePath) : ''
+ const token = privateSession ? readWebappSession(basePath) : ''
return {
authRequired,
diff --git a/apps/desktop/src/test/webapp-session.ts b/apps/desktop/src/test/webapp-session.ts
index 5b136d98eef..34f6cb7f170 100644
--- a/apps/desktop/src/test/webapp-session.ts
+++ b/apps/desktop/src/test/webapp-session.ts
@@ -6,7 +6,7 @@ type WebappWindow = Window & { __HERMES_BASE_PATH__?: string; __HERMES_UI_SURFAC
/**
* A Webapp tab after its private launch link, on an unauthenticated bind: the browser host's only
- * credential, as `consumeWebappSession` reads it back. Seeds the grant for the base path the window
+ * credential, as `readWebappSession` reads it back. Seeds the grant for the base path the window
* carries at call time, so set `__HERMES_BASE_PATH__` first.
*/
export function seedWebappSession(token: string): void {
diff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.py
index 32fe3e9d746..cccab773a76 100644
--- a/hermes_cli/web_routers/webapp.py
+++ b/hermes_cli/web_routers/webapp.py
@@ -281,15 +281,15 @@ async def redeem_window_ticket(request: Request):
return JSONResponse({"token": token}, headers={"Cache-Control": "no-store"})
+# The credential goes to this tab's sessionStorage, where the Webapp reads it at boot
+# (browser-launch-session.ts), never into a URL: the browser keeps every address it opens in its history.
_LAUNCH_SCRIPT = r"""
const basePath = __BASE_PATH__;
const params = new URLSearchParams(location.hash.slice(1));
history.replaceState(null, '', location.pathname);
const ticket = params.get('ticket') || '';
-const fail = () => {
- document.getElementById('status').textContent = 'This launch link was already used or has expired. '
- + 'Run hermes webapp again for a new one.';
-};
+const show = message => { document.getElementById('status').textContent = message; };
+const fail = () => show('This launch link was already used or has expired. Run hermes webapp again for a new one.');
if (!/^[A-Za-z0-9_-]{43}$/.test(ticket)) {
fail();
} else {
@@ -297,10 +297,15 @@ if (!/^[A-Za-z0-9_-]{43}$/.test(ticket)) {
method: 'POST', credentials: 'same-origin', headers: {'X-Hermes-Window-Ticket': ticket}
}).then(response => response.ok ? response.json() : Promise.reject()).then(({token}) => {
if (typeof token !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(token)) throw new Error();
- // The SPA consumes and strips this fragment exactly as it does for the printed link.
+ try {
+ sessionStorage.setItem(`hermes.webapp.session.v1:${JSON.stringify([location.origin, basePath])}`, token);
+ } catch {
+ show('This browser does not let the Webapp keep its sign-in in this tab. Allow site data for this '
+ + 'address, then run hermes webapp again.');
+ return;
+ }
const target = new URL(`${basePath}/`, location.origin);
target.search = params.get('query') || '';
- target.hash = `hermes-session=${token}`;
location.replace(target.href);
}).catch(fail);
}
@@ -329,7 +334,8 @@ def _handoff_page(request: Request, title: str, status: str, script: str) -> HTM
@router.get("/webapp/launch")
async def launch_page(request: Request):
"""Where the server's own browser-open lands: spends the one-use launch ticket from the
- fragment (never sent to the server or kept in history) and enters the Webapp."""
+ fragment (never sent to the server), keeps the credential it receives in this tab's
+ sessionStorage and enters the Webapp at an address that carries neither."""
_require_private_webapp(request)
return _handoff_page(request, "Opening Hermes", "Opening Hermes Webapp…", _LAUNCH_SCRIPT)
diff --git a/tests/hermes_cli/test_webapp_launch.py b/tests/hermes_cli/test_webapp_launch.py
index d3b33fc896d..5f79ae56a92 100644
--- a/tests/hermes_cli/test_webapp_launch.py
+++ b/tests/hermes_cli/test_webapp_launch.py
@@ -132,3 +132,27 @@ def test_windows_spends_a_launch_ticket_without_a_peer_check():
assert webapp._peer_is_server_user(_loopback_request(), platform="win32") is True
assert webapp_listener._one_use_links_work(platform="win32") is True
+
+
[email protected]("page", ["/webapp/launch", "/webapp/window"])
+def test_a_handoff_page_keeps_the_credential_out_of_every_url(monkeypatch, page):
+ """The browser records every address a tab navigates to in its history (and syncs it), and the
+ credential a handoff page receives lasts until ``hermes webapp --sign-out``. So the launch and
+ child-window pages put it in this tab's sessionStorage, under the key the Webapp reads at boot,
+ and then replace themselves with the Webapp's own address: no URL they navigate to carries it.
+ Each page is uncached and sends no Referer."""
+ from fastapi.testclient import TestClient
+ 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)
+ monkeypatch.setattr(server.app.state, "bound_host", "127.0.0.1", raising=False)
+ monkeypatch.setattr(server, "_SESSION_TOKEN", "a" * 43)
+ served = TestClient(server.app, base_url="http://127.0.0.1").get(page)
+ assert served.status_code == 200
+ assert "hermes-session" not in served.text, "the page navigates with the credential in the URL"
+ assert "sessionStorage.setItem(`hermes.webapp.session.v1:${JSON.stringify([location.origin, basePath])}`, token)" \
+ in served.text
+ assert "a" * 43 not in served.text
+ assert served.headers["cache-control"] == "no-store"
+ assert served.headers["referrer-policy"] == "no-referrer"