The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(webapp): one route mints every Webapp socket ticket
emozillac7bab35d0800
diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsxindex 19e889218a9..1d0439f9cc1 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx@@ -143,7 +143,9 @@ beforeEach(() => {const realFetch = globalThis.fetchlet minted = 0vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {- if (new URL(String(input), window.location.href).pathname.endsWith('/api/webapp/terminal-ticket')) {+ const mint = new URL(String(input), window.location.href)++ if (mint.pathname.endsWith('/api/webapp/socket-ticket') && mint.searchParams.get('socket') === 'host-terminal') {minted += 1return new Response(JSON.stringify({ ticket: `shell-ticket-${minted}` }), { status: 200 })diff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.tsindex 1c02189d1ed..a12d0994773 100644--- a/apps/desktop/src/lib/browser-connection.ts+++ b/apps/desktop/src/lib/browser-connection.ts@@ -4,13 +4,12 @@ import type { HermesApiRequest, HermesConnection } from '@/global'import { webappSignInRequired } from '@/lib/browser-launch-session'import {type AudioSocketPath,- audioWebsocketUrl,type BrowserBootstrap,BrowserReauthRequiredError,endpointUrl,gatewaySocketUrl,- gatewayWebsocketUrl,- navigateToBrowserLogin+ navigateToBrowserLogin,+ ticketedWebsocketUrl} from '@/lib/browser-transport'import { windowProfileOverride } from '@/store/windows'@@ -99,7 +98,7 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnecttry {return {ok: true as const,- wsUrl: await gatewayWebsocketUrl(bootstrap, profile)+ wsUrl: await ticketedWebsocketUrl(bootstrap, '/api/ws', profile)}} catch (error) {if (error instanceof BrowserReauthRequiredError) {@@ -151,7 +150,7 @@ export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnect}) => {requireBrowserConnection(payload.connectionId)- return audioWebsocketUrl(bootstrap, payload.path, payload.profile)+ return ticketedWebsocketUrl(bootstrap, payload.path, payload.profile)},// Reconnect belongs to the window, not whichever secondary profile is active.// Explicit null still selects the default backend.diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex 7c86a3f56e9..50e77cd9ca8 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -170,7 +170,8 @@ describe('browser-hosted Desktop bridge', () => {expect(secondUrl.searchParams.get('ticket')).toBe('ticket-two')expect(fetchMock).toHaveBeenCalledTimes(2)const minted = fetchMock.mock.calls.map(([url]) => url as URL)- expect(minted.every(url => url.pathname === '/hermes/api/webapp/gateway-ticket')).toBe(true)+ expect(minted.every(url => url.pathname === '/hermes/api/webapp/socket-ticket')).toBe(true)+ expect(minted.every(url => url.searchParams.get('socket') === 'gateway')).toBe(true)expect(minted.every(url => url.searchParams.get('profile') === 'worker-a')).toBe(true)expect(fetchMock.mock.calls.every(([, init]) => init?.method === 'POST')).toBe(true)expect(fetchMock.mock.calls.every(([, init]) => init?.credentials === 'same-origin')).toBe(true)@@ -410,7 +411,7 @@ describe('browser-hosted Desktop bridge', () => {vi.fn().mockImplementation(async (url: URL) =>new Response(JSON.stringify(- url.pathname.endsWith('/api/webapp/gateway-ticket')+ url.pathname.endsWith('/api/webapp/socket-ticket')? { ticket: 'research-ticket' }: { profiles: [{ name: 'default' }, { name: 'research' }] }),@@ -908,7 +909,8 @@ describe('browser-hosted Desktop bridge', () => {expect(url.pathname).toBe('/hermes/api/host-terminal')expect(url.searchParams.get('ticket')).toBe('shell-ticket')expect(socket.url).not.toContain('served-token')- expect((fetchMock.mock.calls[0][0] as URL).pathname).toBe('/hermes/api/webapp/terminal-ticket')+ expect((fetchMock.mock.calls[0][0] as URL).pathname).toBe('/hermes/api/webapp/socket-ticket')+ expect((fetchMock.mock.calls[0][0] as URL).searchParams.get('socket')).toBe('host-terminal')expect(url.searchParams.get('profile')).toBe('active-terminal')expect(url.searchParams.get('cwd')).toBe('/work')expect(url.searchParams.get('cols')).toBe('42')@@ -973,7 +975,8 @@ describe('browser-hosted Desktop bridge', () => {await win.hermesDesktop!.terminal.start({ cwd: '/work' })const [mint, init] = fetchMock.mock.calls[0] as [URL, RequestInit]- expect(mint.pathname).toBe('/api/webapp/terminal-ticket')+ expect(mint.pathname).toBe('/api/webapp/socket-ticket')+ expect(mint.searchParams.get('socket')).toBe('host-terminal')expect(init.method).toBe('POST')expect(init.credentials).toBe('same-origin')expect(new Headers(init.headers).has('X-Hermes-Session-Token')).toBe(false)diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.tsindex dfb1286441c..114a2714279 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts@@ -9,7 +9,7 @@ import { watchWebappLaunchLink, WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-lauimport { createBrowserProfileBridge } from '@/lib/browser-profile'import { createBrowserSettings } from '@/lib/browser-settings'import { createBrowserTerminal } from '@/lib/browser-terminal'-import { authenticatedWebsocketUrl, browserApi, browserBootstrap } from '@/lib/browser-transport'+import { browserApi, browserBootstrap, ticketedWebsocketUrl } from '@/lib/browser-transport'import { createBrowserUploadsBridge } from '@/lib/browser-uploads'import { createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'import { createBrowserZoom } from '@/lib/browser-zoom'@@ -130,7 +130,7 @@ export function installBrowserDesktopBridge(): boolean {terminal: createBrowserTerminal({basePath: bootstrap.basePath,currentProfile,- websocketUrl: profile => authenticatedWebsocketUrl(bootstrap, '/api/host-terminal', profile),+ websocketUrl: profile => ticketedWebsocketUrl(bootstrap, '/api/host-terminal', profile),defaultCwd: async profile => (await api<{ cwd?: string }>({ path: '/api/fs/default-cwd', profile })).cwd || '',// The chat's sign-in view for a launch-link tab. Behind the sign-in gate the next ticket// request already takes the tab to the login page.diff --git a/apps/desktop/src/lib/browser-launch-session.test.ts b/apps/desktop/src/lib/browser-launch-session.test.tsindex 096783810e8..36388bbba94 100644--- a/apps/desktop/src/lib/browser-launch-session.test.ts+++ b/apps/desktop/src/lib/browser-launch-session.test.ts@@ -43,10 +43,10 @@ it('uses one private session for REST, RPC and terminal across reload without lovi.stubGlobal('WebSocket', Socket)- const minted: Record<string, string> = { 'gateway-ticket': 'rpc-ticket', 'terminal-ticket': 'shell-ticket' }+ const minted: Record<string, string> = { gateway: 'rpc-ticket', 'host-terminal': 'shell-ticket' }const fetchMock = vi.fn().mockImplementation(async (url: URL) => {- const ticket = minted[url.pathname.split('/api/webapp/')[1] ?? '']+ const ticket = url.pathname.endsWith('/api/webapp/socket-ticket') ? minted[url.searchParams.get('socket') ?? ''] : ''return new Response(ticket ? JSON.stringify({ ticket }) : '{"ok":true}', { status: 200 })})@@ -67,13 +67,19 @@ it('uses one private session for REST, RPC and terminal across reload without loconst rpcUrl = new URL(typeof rpc === 'string' ? rpc : rpc.ok ? rpc.wsUrl : '')expect(rpcUrl.searchParams.get('ticket')).toBe('rpc-ticket')expect(rpcUrl.searchParams.get('profile')).toBe('coder')- const mint = fetchMock.mock.calls.find(([url]) => (url as URL).pathname === '/one/api/webapp/gateway-ticket')!++ const mintFor = (socket: string) =>+ fetchMock.mock.calls.find(+ ([url]) => (url as URL).pathname === '/one/api/webapp/socket-ticket' && (url as URL).searchParams.get('socket') === socket+ )!++ const mint = mintFor('gateway')expect(new Headers(mint[1].headers).get('X-Hermes-Session-Token')).toBe(token)// Terminal: each dial mints its own one-use ticket the same way.await desktop.terminal.start({ cwd: '/work' })expect(urls[0].pathname).toBe('/one/api/host-terminal')expect(urls[0].searchParams.get('ticket')).toBe('shell-ticket')- const shellMint = fetchMock.mock.calls.find(([url]) => (url as URL).pathname === '/one/api/webapp/terminal-ticket')!+ const shellMint = mintFor('host-terminal')expect(shellMint[1].method).toBe('POST')expect(new Headers(shellMint[1].headers).get('X-Hermes-Session-Token')).toBe(token)// A plugin's live socket cannot carry a ticket here; it stays on its polling fallback.diff --git a/apps/desktop/src/lib/browser-transport.ts b/apps/desktop/src/lib/browser-transport.tsindex f23ec671d86..8b523b64ce8 100644--- a/apps/desktop/src/lib/browser-transport.ts+++ b/apps/desktop/src/lib/browser-transport.ts@@ -266,22 +266,44 @@ export async function fileEndpointUrl(}/**- * The live socket to the gateway serving this page. Every dial mints its own one-use ticket on the- * same origin; a failed mint is the reason to show. `native_dial` makes the client speak the- * gateway's canonical contract and move the ticket into the socket's subprotocol.+ * The sockets a Webapp page dials, each with a one-use ticket minted for that socket alone by an+ * authenticated request on this same origin (the session header on a loopback Webapp, the sign-in+ * cookie on a gated host), so the session token never rides a socket URL that logs, history and+ * proxies keep. Each maps to its name in `POST /api/webapp/socket-ticket?socket=`.*/-export async function gatewayWebsocketUrl(bootstrap: BrowserBootstrap, profile?: null | string): Promise<string> {+const TICKET_SOCKETS = {+ '/api/audio/speak-stream': 'speak-stream',+ '/api/audio/transcribe-stream': 'transcribe-stream',+ '/api/host-terminal': 'host-terminal',+ '/api/ws': 'gateway'+} as const++export type TicketSocketPath = keyof typeof TICKET_SOCKETS+export type AudioSocketPath = '/api/audio/speak-stream' | '/api/audio/transcribe-stream'++/**+ * Socket *path*'s URL for one dial, carrying a ticket minted for it alone; a failed mint is the+ * reason to show. The gateway socket's mint also checks *profile*, and its `native_dial` makes the+ * client speak the gateway's canonical contract and move the ticket into the socket's subprotocol.+ */+export async function ticketedWebsocketUrl(+ bootstrap: BrowserBootstrap,+ path: TicketSocketPath,+ profile?: null | string+): Promise<string> {+ const gateway = path === '/api/ws'+const result = await browserApi<null | { ticket?: string }>(bootstrap, {method: 'POST',- path: '/api/webapp/gateway-ticket',- profile+ path: `/api/webapp/socket-ticket?socket=${TICKET_SOCKETS[path]}`,+ profile: gateway ? profile : undefined})const ticket = String(result?.ticket || '').trim()- if (!ticket) {- throw new Error('Hermes did not return a gateway ticket')- }+ if (!ticket) {throw new Error(`Hermes did not return a ticket for ${path}`)}++ if (!gateway) {return websocketUrl(bootstrap.basePath, path, { ticket }, profile)}const url = new URL(gatewaySocketUrl(bootstrap, profile))url.searchParams.set('ticket', ticket)@@ -296,55 +318,3 @@ export function gatewaySocketUrl(bootstrap: BrowserBootstrap, profile?: null | sreturn url.toString()}--/**- * The host terminal's socket URL for one dial. Its one-use ticket is minted by an authenticated- * request (the session header on a loopback Webapp, the sign-in cookie on a gated host) and opens- * only the host terminal, so the session token never rides a socket URL that logs, history and- * proxies keep.- */-export async function authenticatedWebsocketUrl(- bootstrap: BrowserBootstrap,- path: '/api/host-terminal',- profile?: null | string-): Promise<string> {- const result = await browserApi<null | { ticket?: string }>(bootstrap, {- method: 'POST',- path: '/api/webapp/terminal-ticket'- })-- const ticket = String(result?.ticket || '').trim()-- if (!ticket) {throw new Error('Hermes did not return a terminal ticket')}-- return websocketUrl(bootstrap.basePath, path, { ticket }, profile)-}--/** The voice streams beside `/api/ws`, each opened only by a ticket minted under its socket name. */-const AUDIO_SOCKETS = {- '/api/audio/speak-stream': 'speak-stream',- '/api/audio/transcribe-stream': 'transcribe-stream'-} as const--export type AudioSocketPath = keyof typeof AUDIO_SOCKETS--/**- * A voice stream's socket URL for one dial. Its one-use ticket is minted for that stream alone: the- * gateway's ticket opens only `/api/ws`, so the stream cannot reuse it.- */-export async function audioWebsocketUrl(- bootstrap: BrowserBootstrap,- path: AudioSocketPath,- profile?: null | string-): Promise<string> {- const result = await browserApi<null | { ticket?: string }>(bootstrap, {- method: 'POST',- path: `/api/webapp/audio-ticket?socket=${AUDIO_SOCKETS[path]}`- })-- const ticket = String(result?.ticket || '').trim()-- if (!ticket) {throw new Error('Hermes did not return a voice stream ticket')}-- return websocketUrl(bootstrap.basePath, path, { ticket }, profile)-}diff --git a/apps/desktop/src/lib/browser-voice-sockets.test.ts b/apps/desktop/src/lib/browser-voice-sockets.test.tsindex 6a3c288e054..07ed2a038c5 100644--- a/apps/desktop/src/lib/browser-voice-sockets.test.ts+++ b/apps/desktop/src/lib/browser-voice-sockets.test.ts@@ -24,11 +24,7 @@ function serveTickets() {const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => {const url = new URL(String(input))- const ticket = url.pathname.endsWith('/api/webapp/audio-ticket')- ? `${url.searchParams.get('socket')}-ticket`- : url.pathname.endsWith('/api/webapp/gateway-ticket')- ? 'gateway-ticket'- : ''+ const ticket = url.pathname.endsWith('/api/webapp/socket-ticket') ? `${url.searchParams.get('socket')}-ticket` : ''return new Response(JSON.stringify(ticket ? { ticket, ttl_seconds: 60 } : {}), {headers: { 'content-type': 'application/json' },@@ -75,7 +71,7 @@ describe('browser-hosted Desktop voice streams', () => {const [mint, ...others] = minted(fetchMock)expect(others).toEqual([])- expect(mint.url.pathname).toBe('/hermes/api/webapp/audio-ticket')+ expect(mint.url.pathname).toBe('/hermes/api/webapp/socket-ticket')expect(mint.url.searchParams.get('socket')).toBe('speak-stream')expect(mint.init?.method).toBe('POST')expect(mint.init?.credentials).toBe('same-origin')@@ -95,7 +91,7 @@ describe('browser-hosted Desktop voice streams', () => {const [mint, ...others] = minted(fetchMock)expect(others).toEqual([])- expect(mint.url.pathname).toBe('/api/webapp/audio-ticket')+ expect(mint.url.pathname).toBe('/api/webapp/socket-ticket')expect(mint.url.searchParams.get('socket')).toBe('transcribe-stream')expect(new Headers(mint.init?.headers).get('X-Hermes-Session-Token')).toBe('served-token')})@@ -111,6 +107,8 @@ describe('browser-hosted Desktop voice streams', () => {expect(url.pathname).toBe('/api/ws')expect(url.searchParams.get('ticket')).toBe('gateway-ticket')- expect(minted(fetchMock).map(({ url }) => url.pathname)).toEqual(['/api/webapp/gateway-ticket'])+ expect(minted(fetchMock).map(({ url }) => [url.pathname, url.searchParams.get('socket')])).toEqual([+ ['/api/webapp/socket-ticket', 'gateway']+ ])})})diff --git a/hermes_cli/web_routers/audio.py b/hermes_cli/web_routers/audio.pyindex 2d38b738762..51a255c5c1d 100644--- a/hermes_cli/web_routers/audio.py+++ b/hermes_cli/web_routers/audio.py@@ -526,7 +526,7 @@ async def transcribe_stream_ws(ws: WebSocket) -> None:``{"type": "error", "message": ...}`` — also when no live STT is available, so theclient falls back to ``POST /api/audio/transcribe`` with its recorded blob."""- # A socket ticket opens this stream only when minted for it (``/api/webapp/audio-ticket``).+ # A socket ticket opens this stream only when minted for it (``/api/webapp/socket-ticket``).if not _ws_auth_ok(ws, socket=TRANSCRIBE_STREAM_SOCKET):await ws.close(code=4401)return@@ -613,7 +613,7 @@ async def speak_stream_ws(ws: WebSocket) -> None:still speak per sentence via ``text_to_speech_tool`` and streamthat PCM — the client POST is the last resort, not the Edge path."""- # A socket ticket opens this stream only when minted for it (``/api/webapp/audio-ticket``).+ # A socket ticket opens this stream only when minted for it (``/api/webapp/socket-ticket``).if not _ws_auth_ok(ws, socket=SPEAK_STREAM_SOCKET):await ws.close(code=4401)returndiff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.pyindex 39dd3b8bfc3..32fe3e9d746 100644--- a/hermes_cli/web_routers/webapp.py+++ b/hermes_cli/web_routers/webapp.py@@ -1,8 +1,7 @@"""Webapp-only routes: the host terminal (loopback or authenticated binds), the-one-use ticket each browser socket dial mints (``/api/webapp/gateway-ticket`` for-``/api/ws`` on this same origin, ``/api/webapp/terminal-ticket`` for the host terminal,-``/api/webapp/audio-ticket`` for each voice stream), and the one-use handoffs (child window,-auto-opened launch tab) for the private, loopback Webapp session."""+one-use ticket each browser socket dial mints (``/api/webapp/socket-ticket?socket=`` for+``/api/ws`` on this same origin, the host terminal and each voice stream), and the one-use+handoffs (child window, auto-opened launch tab) for the private, loopback Webapp session."""from __future__ import annotationsimport ipaddress@@ -19,7 +18,8 @@ from fastapi.responses import HTMLResponse, JSONResponsefrom hermes_cli.dashboard_auth.request_utils import _http_originfrom hermes_cli.web_server_surface import policy, private_launch-from hermes_cli.web_session_sockets import AUDIO_SOCKETS, GATEWAY_SOCKET, HOST_TERMINAL_SOCKET+from hermes_cli.web_session_sockets import (+ GATEWAY_SOCKET, HOST_TERMINAL_SOCKET, SPEAK_STREAM_SOCKET, TRANSCRIBE_STREAM_SOCKET)_log = logging.getLogger("hermes_cli.web_server")router = APIRouter()@@ -209,47 +209,42 @@ def _socket_ticket_response(request: Request, identity: dict, socket: str, sessireturn JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})[email protected]("/api/webapp/gateway-ticket")-async def issue_gateway_ticket(request: Request, profile: str | None = None):- """The browser's one-use ticket for its live socket: ``/api/ws`` on this same origin, offered- as the ``hermes-gateway-ticket.`` subprotocol and redeemed by the upgrade gate- (``web_server_chat._consume_ws_ticket``) as this caller's login. It opens no other socket.- Minted locally: the server that serves this page runs the socket's sessions. *profile* is- validated (400/404) so a stale tab learns its profile is gone here rather than from a socket- that keeps closing, and the ticket names it: the socket answers a request that names no profile- for the tab's profile, as a native ticket does, never for the gateway's launch profile."""- from hermes_cli.web_server_cron import _cron_profile_home-- if not policy(request.app.state).gateway_ticket:- raise HTTPException(404, "Webapp gateway tickets are unavailable on this surface")- identity, session_token = _ticket_principal(request)- _name, home = _cron_profile_home(profile)- return _socket_ticket_response(request, identity, GATEWAY_SOCKET, session_token,- profile_home=str(home) if profile else None)-+#: Every socket a Webapp page dials with a one-use ticket from ``POST /api/webapp/socket-ticket``, by+#: its ``web_session_sockets`` name: the ``web_server_surface.SurfacePolicy`` field that lets a surface+#: mint it, and whether the mint checks the profile the page will dial (400/404), so a stale tab learns+#: its profile is gone there rather than from a socket that keeps closing.+SOCKET_TICKETS: dict[str, tuple[str, bool]] = {+ GATEWAY_SOCKET: ("gateway_ticket", True),+ HOST_TERMINAL_SOCKET: ("host_terminal", False),+ SPEAK_STREAM_SOCKET: ("gateway_ticket", False),+ TRANSCRIBE_STREAM_SOCKET: ("gateway_ticket", False),+}[email protected]("/api/webapp/terminal-ticket")-async def issue_terminal_ticket(request: Request):- """The browser's one-use ticket for one host-terminal dial (``/api/host-terminal?ticket=``).- The host terminal opens with nothing else, and this ticket opens nothing else."""- if not policy(request.app.state).host_terminal:- raise HTTPException(404, "The host terminal is unavailable on this surface")- identity, session_token = _ticket_principal(request)- return _socket_ticket_response(request, identity, HOST_TERMINAL_SOCKET, session_token)[email protected]("/api/webapp/socket-ticket")+async def issue_socket_ticket(request: Request, socket: str = "", profile: str | None = None):+ """The browser's one-use ticket for one dial of *socket* on this same origin: ``gateway`` for+ ``/api/ws`` (also offered as the ``hermes-gateway-ticket.`` subprotocol), ``host-terminal`` for+ ``/api/host-terminal``, ``speak-stream`` and ``transcribe-stream`` for ``/api/audio/<name>``. The+ upgrade gate (``web_server_chat._consume_ws_ticket``) redeems it as this caller's login; it opens+ that socket and nothing else, so the browser mints one per dial. Minted locally: the server that+ serves this page runs the socket's sessions. A ``gateway`` ticket minted with *profile* names+ it: that socket answers a request that names no profile for *profile*, as a native ticket does+ (``chat_ws.gateway_ws``), never for the gateway's launch profile."""+ from hermes_cli.web_server_cron import _cron_profile_home[email protected]("/api/webapp/audio-ticket")-async def issue_audio_ticket(request: Request, socket: str = ""):- """The browser's one-use ticket for one voice stream dial, named by *socket*:- ``speak-stream`` for ``/api/audio/speak-stream``, ``transcribe-stream`` for- ``/api/audio/transcribe-stream``. It opens that stream and nothing else, and the gateway ticket- opens neither stream, so the browser mints one per dial beside the gateway's."""- if not policy(request.app.state).gateway_ticket:- raise HTTPException(404, "Webapp voice tickets are unavailable on this surface")+ if socket not in SOCKET_TICKETS:+ raise HTTPException(400, "Unknown socket")+ surface, checks_profile = SOCKET_TICKETS[socket]+ if not getattr(policy(request.app.state), surface):+ raise HTTPException(404, f"Webapp {socket} tickets are unavailable on this surface")identity, session_token = _ticket_principal(request)- if socket not in AUDIO_SOCKETS:- raise HTTPException(400, "Unknown voice stream")- return _socket_ticket_response(request, identity, socket, session_token)+ profile_home = None+ if checks_profile:+ _name, home = _cron_profile_home(profile)+ if socket == GATEWAY_SOCKET and profile:+ profile_home = str(home)+ return _socket_ticket_response(request, identity, socket, session_token, profile_home=profile_home)@router.post("/webapp/window-session")diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex a81db2c5f6e..beb01b6bef4 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -337,7 +337,7 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,return "no_credential", "none"- # Loopback: a one-use ticket ``/api/webapp/gateway-ticket`` minted for the session-token owner+ # Loopback: a one-use ticket ``/api/webapp/socket-ticket`` minted for the session-token owner# (the Webapp's live socket on this same origin), else the legacy ``?token=``.consumed = _consume_ws_ticket(ws, _ignore_rejection, socket)if consumed is not None:diff --git a/hermes_cli/web_server_surface.py b/hermes_cli/web_server_surface.pyindex b09f0d0aaf2..740d4bd29fd 100644--- a/hermes_cli/web_server_surface.py+++ b/hermes_cli/web_server_surface.py@@ -23,8 +23,8 @@ class SurfacePolicy:host_terminal: bool#: An unauthenticated start hands the operator a private launch link.launch_link: bool- #: ``/api/webapp/gateway-ticket`` mints the browser's one-use ticket for ``/api/ws`` on this- #: same origin (accepted by the loopback and gated upgrade gates alike).+ #: ``/api/webapp/socket-ticket`` mints the browser's one-use tickets for ``/api/ws`` and the voice+ #: streams on this same origin (accepted by the loopback and gated upgrade gates alike).gateway_ticket: booldiff --git a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py b/tests/gateway/fixtures/webapp_gated_sign_out_peer.pyindex 441bd94799e..79b7a81212d 100644--- a/tests/gateway/fixtures/webapp_gated_sign_out_peer.py+++ b/tests/gateway/fixtures/webapp_gated_sign_out_peer.py@@ -95,8 +95,8 @@ async def across_sign_out(runner, origin, ask):json={"provider": "basic", "username": USER, "password": PASSWORD})return signed_in.status_code- async def ticket(browser, kind):- minted = await browser.post(f"/api/webapp/{kind}-ticket", headers=page)+ async def ticket(browser, socket):+ minted = await browser.post(f"/api/webapp/socket-ticket?socket={socket}", headers=page)return minted.json()["ticket"] if minted.status_code == 200 else Noneauthority = runner.session_authority@@ -109,10 +109,10 @@ async def across_sign_out(runner, origin, ask):report["sessions_before"] = (await browser.get("/api/sessions")).status_codereport["me_before"] = (await browser.get("/api/auth/me")).status_codestolen = dict(browser.cookies.items())- unused_terminal_ticket = await ticket(browser, "terminal")+ unused_terminal_ticket = await ticket(browser, "host-terminal")async with connect(f"{sockets}/api/ws?native_dial=browser", origin=origin,subprotocols=chat_protocols(await ticket(browser, "gateway"))) as chat, \- connect(f"{sockets}/api/host-terminal?ticket={await ticket(browser, 'terminal')}",+ connect(f"{sockets}/api/host-terminal?ticket={await ticket(browser, 'host-terminal')}",origin=origin) as terminal, \connect(f"{sockets}/api/ws", subprotocols=chat_protocols(native_ticket)) as native:report["terminal_open"] = (await terminal.recv()).startswith(web_host_terminal.META_PREFIX)@@ -126,7 +126,8 @@ async def across_sign_out(runner, origin, ask):report["sessions_after"] = _refusal(await browser.get("/api/sessions"))report["me_after"] = _refusal(await browser.get("/api/auth/me"))report["page_after"] = _refusal(await browser.get("/", follow_redirects=False))- report["terminal_ticket_after"] = _refusal(await browser.post("/api/webapp/terminal-ticket", headers=page))+ report["terminal_ticket_after"] = _refusal(+ await browser.post("/api/webapp/socket-ticket?socket=host-terminal", headers=page))report["old_terminal_ticket_after"] = await _upgrade(f"{sockets}/api/host-terminal?ticket={unused_terminal_ticket}", origin=origin)async with httpx.AsyncClient(base_url=origin, timeout=20, cookies=stolen) as replay:diff --git a/tests/gateway/fixtures/webapp_listener_peer.py b/tests/gateway/fixtures/webapp_listener_peer.pyindex 52d6b607323..9484cfcdc87 100644--- a/tests/gateway/fixtures/webapp_listener_peer.py+++ b/tests/gateway/fixtures/webapp_listener_peer.py@@ -66,8 +66,8 @@ async def sockets_across_sign_out(runner, client, origin, ask):sockets = origin.replace("http:", "ws:")session = {"X-Hermes-Session-Token": web_server._SESSION_TOKEN}- async def ticket(kind):- return (await client.post(f"/api/webapp/{kind}-ticket", headers=session)).json()["ticket"]+ async def ticket(socket):+ return (await client.post(f"/api/webapp/socket-ticket?socket={socket}", headers=session)).json()["ticket"]def chat_protocols(value):return ["hermes-gateway-v1", f"hermes-gateway-ticket.{value}"]@@ -79,7 +79,7 @@ async def sockets_across_sign_out(runner, client, origin, ask):f"{sockets}/api/host-terminal?ticket={await ticket('gateway')}", origin=origin),"chat_refuses_terminal_ticket": await _upgrade_refusal(f"{sockets}/api/ws?native_dial=browser", origin=origin,- subprotocols=chat_protocols(await ticket("terminal"))),+ subprotocols=chat_protocols(await ticket("host-terminal"))),}authority = runner.session_authorityrunner.session_ticket_store = TicketStore("webapp-listener", frozenset({authority.profile_id}))@@ -87,7 +87,7 @@ async def sockets_across_sign_out(runner, client, origin, ask):profile_id=authority.profile_id, subject="fixture-same-user", purpose="interactive")async with connect(f"{sockets}/api/ws?native_dial=browser", origin=origin,subprotocols=chat_protocols(await ticket("gateway"))) as chat, \- connect(f"{sockets}/api/host-terminal?ticket={await ticket('terminal')}", origin=origin) as terminal, \+ connect(f"{sockets}/api/host-terminal?ticket={await ticket('host-terminal')}", origin=origin) as terminal, \connect(f"{sockets}/api/ws", subprotocols=chat_protocols(native_ticket)) as native:report["terminal_opens_with_its_ticket"] = (await terminal.recv()).startswith(web_host_terminal.META_PREFIX)report["chat_opens_before_sign_out"] = "result" in await rpc(chat, "session.list")@@ -150,7 +150,7 @@ async def probe(mode, port, dist, platform):report["host_terminals"] = hasattr(web_server.app.state, "host_terminals")report["session_token_is_seeded"] = web_server._SESSION_TOKEN == SEEDED_TOKENreport["token_file"] = (home / TOKEN_PATH).exists()- minted = await client.post("/api/webapp/gateway-ticket",+ minted = await client.post("/api/webapp/socket-ticket?socket=gateway",headers={"X-Hermes-Session-Token": web_server._SESSION_TOKEN})report["ticket_status"] = minted.status_codeif minted.status_code == 200:@@ -177,7 +177,7 @@ async def probe(mode, port, dist, platform):report["handoff_reuse_status"] = (await client.post("/webapp/window-session", headers=handoff)).status_codereport.update(await sockets_across_sign_out(runner, client, origin, ask))- stale = await client.post("/api/webapp/gateway-ticket",+ stale = await client.post("/api/webapp/socket-ticket?socket=gateway",headers={"X-Hermes-Session-Token": SEEDED_TOKEN})report["old_credential_status"] = stale.status_codereport["token_file_rotated"] = (home / TOKEN_PATH).read_text().strip() not in {"", SEEDED_TOKEN}diff --git a/tests/gateway/test_webapp_cookie_writes.py b/tests/gateway/test_webapp_cookie_writes.pyindex 14289843450..543a510954f 100644--- a/tests/gateway/test_webapp_cookie_writes.py+++ b/tests/gateway/test_webapp_cookie_writes.py@@ -30,7 +30,7 @@ FOREIGN_PAGES = (async def _write_statuses(client: httpx.AsyncClient, headers: dict) -> tuple[int, int, int]:"""Status codes of a POST (socket ticket), a PUT (config) and a DELETE (cron job) sent with *headers*."""- ticket = await client.post("/api/webapp/gateway-ticket", headers=headers)+ ticket = await client.post("/api/webapp/socket-ticket?socket=gateway", headers=headers)config = await client.put("/api/config", headers=headers, json=SKIN)job = await client.delete("/api/cron/jobs/no-such-job", headers=headers)return ticket.status_code, config.status_code, job.status_code@@ -85,7 +85,7 @@ def test_a_wildcard_webapp_takes_cookie_writes_only_from_its_own_page(tmp_path,assert read_raw_config()["display"]["skin"] == "mono"# Electron's net.request sends the cookie with no Origin and no page Fetch Metadata.for native in ({}, {"Sec-Fetch-Site": "none"}):- native_ticket = await browser.post("/api/webapp/gateway-ticket", headers=native)+ native_ticket = await browser.post("/api/webapp/socket-ticket?socket=gateway", headers=native)assert native_ticket.status_code == 200, native_ticket.textasync with httpx.AsyncClient(transport=transport, base_url=WEBAPP) as native_app:bearer = {"Authorization": f"Bearer {await _native_app_token(native_app)}", "Origin": "null"}diff --git a/tests/hermes_cli/test_dashboard_auth_ws_auth.py b/tests/hermes_cli/test_dashboard_auth_ws_auth.pyindex b0577d7baed..bfbdc336656 100644--- a/tests/hermes_cli/test_dashboard_auth_ws_auth.py+++ b/tests/hermes_cli/test_dashboard_auth_ws_auth.py@@ -236,7 +236,7 @@ class TestWsAuthOkLoopback:def test_webapp_socket_ticket_is_accepted_once(self, loopback_app):"""The Webapp on a loopback bind mints the browser's one-use socket ticket- (``POST /api/webapp/gateway-ticket``) for the session-token owner: the gate takes it once+ (``POST /api/webapp/socket-ticket?socket=gateway``) for the session-token owner: the gate takes it onceand selects only the public protocol. A Bot Desktop screen ticket is never a login hereeither."""ticket = mint_ticket(user_id="legacy-token-owner", provider="session-token")diff --git a/tests/hermes_cli/test_webapp_gated_sign_out.py b/tests/hermes_cli/test_webapp_gated_sign_out.pyindex 71d69ab2792..f361024477d 100644--- a/tests/hermes_cli/test_webapp_gated_sign_out.py+++ b/tests/hermes_cli/test_webapp_gated_sign_out.py@@ -107,7 +107,7 @@ def test_signing_out_ends_every_login_behind_the_gate(gated, sign_out, sign_in):assert browser.get("/api/auth/me").status_code == 200sign_out()_signed_out(browser.get("/api/auth/me"))- _signed_out(browser.post("/api/webapp/terminal-ticket"))+ _signed_out(browser.post("/api/webapp/socket-ticket?socket=host-terminal"))_signed_out(browser.post("/api/auth/ws-ticket"))page = browser.get("/", follow_redirects=False)assert page.status_code == 302 and page.headers["location"].startswith("/login")@@ -130,7 +130,7 @@ def test_signing_in_again_after_sign_out_works(gated, sign_out):_signed_out(browser.get("/api/auth/me"))_sign_in_with_password(browser)assert browser.get("/api/auth/me").status_code == 200- assert browser.post("/api/webapp/terminal-ticket").status_code == 200+ assert browser.post("/api/webapp/socket-ticket?socket=host-terminal").status_code == 200def test_a_credential_replaced_while_the_gateway_was_down_signs_logins_out(gated, monkeypatch):@@ -147,7 +147,7 @@ def test_signing_out_closes_the_sockets_and_host_terminal_a_login_opened(gated,browser = gated.browser()_sign_in_with_password(browser)- terminal = browser.post("/api/webapp/terminal-ticket").json()["ticket"]+ terminal = browser.post("/api/webapp/socket-ticket?socket=host-terminal").json()["ticket"]events = browser.post("/api/auth/ws-ticket").json()["ticket"]other = mint_ticket(user_id="someone-else", provider="stub")with TestClient(gated.host, base_url=WEBAPP) as shells, \@@ -167,7 +167,7 @@ def test_signing_out_closes_the_sockets_and_host_terminal_a_login_opened(gated,def test_tickets_a_login_minted_before_sign_out_open_nothing_after(gated, sign_out):browser = gated.browser()_sign_in_with_password(browser)- terminal = browser.post("/api/webapp/terminal-ticket").json()["ticket"]+ terminal = browser.post("/api/webapp/socket-ticket?socket=host-terminal").json()["ticket"]events = browser.post("/api/auth/ws-ticket").json()["ticket"]sign_out()with TestClient(gated.host, base_url=WEBAPP) as shells:@@ -260,7 +260,7 @@ def _refused_alone(gated, access, refresh):refresh route."""stolen = gated.browser()_refused(stolen.get("/api/auth/me", headers=_bearer(access)))- _refused(stolen.post("/api/webapp/terminal-ticket", headers=_bearer(access)))+ _refused(stolen.post("/api/webapp/socket-ticket?socket=host-terminal", headers=_bearer(access)))_refused(stolen.post("/api/auth/ws-ticket", headers=_bearer(access)))_refused(_renew(gated, refresh))@@ -341,7 +341,7 @@ def test_a_login_after_sign_out_works(gated, sign_out, clock):clock()_sign_in_with_password(browser)assert browser.get("/api/auth/me").status_code == 200- assert browser.post("/api/webapp/terminal-ticket").status_code == 200+ assert browser.post("/api/webapp/socket-ticket?socket=host-terminal").status_code == 200def _native_app_sign_in(gated):diff --git a/tests/hermes_cli/test_webapp_gateway_ticket.py b/tests/hermes_cli/test_webapp_gateway_ticket.pyindex 60752ad9796..eaaaf087368 100644--- a/tests/hermes_cli/test_webapp_gateway_ticket.py+++ b/tests/hermes_cli/test_webapp_gateway_ticket.py@@ -1,6 +1,6 @@"""The Webapp's live socket ticket is minted by the server that serves the page.-``POST /api/webapp/gateway-ticket?profile=<name>`` hands the browser a one-use ticket for+``POST /api/webapp/socket-ticket?socket=gateway&profile=<name>`` hands the browser a one-use ticket for``/api/ws`` on the same origin (offered as the ``hermes-gateway-ticket.`` subprotocol). It names thecaller's login (and the profile it names, ``test_webapp_ticket_profile.py``), and the upgrade gateredeems it exactly once.@@ -12,6 +12,8 @@ from fastapi.testclient import TestClientfrom hermes_cli.web_session_sockets import GATEWAY_SOCKET+_MINT = "/api/webapp/socket-ticket?socket=gateway"+_TOKEN = "a" * 43@@ -44,8 +46,8 @@ def test_loopback_ticket_names_the_session_token_owner_and_is_spent_once(webapp)from hermes_cli import web_server_chat as chat_server, client = webapp- assert client.post("/api/webapp/gateway-ticket").status_code == 401- minted = client.post("/api/webapp/gateway-ticket", headers={"X-Hermes-Session-Token": _TOKEN})+ assert client.post(_MINT).status_code == 401+ minted = client.post(_MINT, headers={"X-Hermes-Session-Token": _TOKEN})assert minted.status_code == 200, minted.textassert minted.headers["cache-control"] == "no-store"body = minted.json()@@ -61,7 +63,7 @@ def test_loopback_ticket_names_the_session_token_owner_and_is_spent_once(webapp)def test_a_missing_profile_is_refused_before_a_ticket_exists(webapp):_server, client = webapp- refused = client.post("/api/webapp/gateway-ticket?profile=missing", headers={"X-Hermes-Session-Token": _TOKEN})+ refused = client.post(_MINT + "&profile=missing", headers={"X-Hermes-Session-Token": _TOKEN})assert refused.status_code == 404@@ -69,5 +71,5 @@ def test_a_missing_profile_is_refused_before_a_ticket_exists(webapp):def test_other_surfaces_do_not_mint_webapp_socket_tickets(webapp, monkeypatch, surface):server, client = webappmonkeypatch.setattr(server.app.state, "ui_surface", surface)- refused = client.post("/api/webapp/gateway-ticket", headers={"X-Hermes-Session-Token": _TOKEN})+ refused = client.post(_MINT, headers={"X-Hermes-Session-Token": _TOKEN})assert refused.status_code == 404diff --git a/tests/hermes_cli/test_webapp_sign_out_sockets.py b/tests/hermes_cli/test_webapp_sign_out_sockets.pyindex 5a41f608814..11ca0be7829 100644--- a/tests/hermes_cli/test_webapp_sign_out_sockets.py+++ b/tests/hermes_cli/test_webapp_sign_out_sockets.py@@ -68,7 +68,7 @@ def test_signing_out_closes_the_terminal_and_streams_the_session_token_opened(weclient, host = webapp.client, webapp.hostother = mint_ticket(user_id="someone-else", provider="stub")with TestClient(host) as shells, \- shells.websocket_connect(f"ws://localhost/api/host-terminal?ticket={_mint(client, 'terminal')}") as shell, \+ shells.websocket_connect(f"ws://localhost/api/host-terminal?ticket={_mint(client, 'host-terminal')}") as shell, \client.websocket_connect(f"ws://localhost/api/events?channel=tab-1&token={_TOKEN}") as events, \client.websocket_connect(f"ws://localhost/api/events?channel=kept&ticket={other}") as kept:metadata(shell)@@ -84,7 +84,7 @@ def test_signing_out_closes_the_terminal_and_streams_the_session_token_opened(wedef test_signing_out_with_no_open_tabs_still_replaces_the_credential(webapp, sign_out):client = webapp.clientassert sign_out() == {"signed_out": True, "serving": True, "sign_in_gate": False, "connections_closed": 0}- assert client.post("/api/webapp/gateway-ticket", headers={"X-Hermes-Session-Token": _TOKEN}).status_code == 401+ assert client.post("/api/webapp/socket-ticket?socket=gateway", headers={"X-Hermes-Session-Token": _TOKEN}).status_code == 401def test_signing_out_ends_the_media_links_the_session_token_minted(webapp, sign_out, tmp_path, monkeypatch):diff --git a/tests/hermes_cli/test_webapp_socket_tickets.py b/tests/hermes_cli/test_webapp_socket_tickets.pyindex 58aedcc2aa7..3f517358aa2 100644--- a/tests/hermes_cli/test_webapp_socket_tickets.py+++ b/tests/hermes_cli/test_webapp_socket_tickets.py@@ -1,9 +1,9 @@"""Each Webapp socket ticket opens only the socket it was minted for.The browser never puts its session token in a socket URL. An authenticated request mints a one-use,-short-lived ticket instead: ``POST /api/webapp/gateway-ticket`` for the chat socket (``/api/ws``),-``POST /api/webapp/terminal-ticket`` for the host terminal (``/api/host-terminal``) and-``POST /api/webapp/audio-ticket?socket=`` for each voice stream (``/api/audio/speak-stream``,+short-lived ticket instead, from one route, ``POST /api/webapp/socket-ticket?socket=``: ``gateway`` for+the chat socket (``/api/ws``), ``host-terminal`` for the host terminal (``/api/host-terminal``),+``speak-stream`` and ``transcribe-stream`` for the voice streams (``/api/audio/speak-stream``,``/api/audio/transcribe-stream``). A host shell opens only with a terminal ticket, a chat ticket opensno host shell, a terminal ticket opens no chat socket, a voice stream opens with a ticket minted forthat stream and no other, and a ticket minted with a session token that has since been replaced opens@@ -61,8 +61,8 @@ def webapp(tmp_path, monkeypatch):return serve_webapp(tmp_path, monkeypatch)-def _mint(client, kind, headers=_SESSION):- response = client.post(f"/api/webapp/{kind}-ticket", headers=headers)+def _mint(client, socket, headers=_SESSION):+ response = client.post("/api/webapp/socket-ticket", params={"socket": socket}, headers=headers)assert response.status_code == 200, response.textassert response.headers["cache-control"] == "no-store"body = response.json()@@ -79,8 +79,8 @@ def _refused(client, url, code=4401, **kwargs):def test_a_terminal_ticket_opens_one_host_shell_once(webapp):client, host = webapp.client, webapp.host- assert client.post("/api/webapp/terminal-ticket").status_code == 401- ticket = _mint(client, "terminal")+ assert client.post("/api/webapp/socket-ticket", params={"socket": "host-terminal"}).status_code == 401+ ticket = _mint(client, "host-terminal")with TestClient(host) as shells:with shells.websocket_connect(f"ws://localhost/api/host-terminal?ticket={ticket}") as ws:assert metadata(ws)["terminalId"]@@ -104,14 +104,14 @@ def test_the_host_terminal_refuses_the_session_token_and_every_other_ticket(webadef test_a_terminal_ticket_does_not_open_the_chat_socket(webapp):client = webapp.client- protocols = ["hermes-gateway-v1", f"hermes-gateway-ticket.{_mint(client, 'terminal')}"]+ protocols = ["hermes-gateway-v1", f"hermes-gateway-ticket.{_mint(client, 'host-terminal')}"]_refused(client, "ws://localhost/api/ws?native_dial=browser", subprotocols=protocols)- _refused(client, f"ws://localhost/api/ws?ticket={_mint(client, 'terminal')}")+ _refused(client, f"ws://localhost/api/ws?ticket={_mint(client, 'host-terminal')}")def test_tickets_minted_before_the_session_token_changed_open_nothing(webapp, monkeypatch):server, client, host = webapp.server, webapp.client, webapp.host- terminal, chat = _mint(client, "terminal"), _mint(client, "gateway")+ terminal, chat = _mint(client, "host-terminal"), _mint(client, "gateway")monkeypatch.setattr(server, "_SESSION_TOKEN", "b" * 43)with TestClient(host) as shells:_refused(shells, f"ws://localhost/api/host-terminal?ticket={terminal}")@@ -123,7 +123,8 @@ def test_tickets_minted_before_the_session_token_changed_open_nothing(webapp, modef test_other_surfaces_do_not_mint_terminal_tickets(webapp, monkeypatch, surface):server, client = webapp.server, webapp.clientmonkeypatch.setattr(server.app.state, "ui_surface", surface)- assert client.post("/api/webapp/terminal-ticket", headers=_SESSION).status_code == 404+ minted = client.post("/api/webapp/socket-ticket", params={"socket": "host-terminal"}, headers=_SESSION)+ assert minted.status_code == 404def test_a_signed_in_browser_opens_its_host_shell_with_a_terminal_ticket(webapp, monkeypatch):@@ -142,11 +143,11 @@ def test_a_signed_in_browser_opens_its_host_shell_with_a_terminal_ticket(webapp,monkeypatch.setattr(server.app.state, "auth_required", True)try:anonymous = TestClient(server.app, base_url="https://fly-app.fly.dev")- assert anonymous.post("/api/webapp/terminal-ticket", headers=_SESSION,+ assert anonymous.post("/api/webapp/socket-ticket", params={"socket": "host-terminal"}, headers=_SESSION,follow_redirects=False).status_code in (302, 401)gated = TestClient(server.app, base_url="https://fly-app.fly.dev")_logged_in(gated)- ticket = _mint(gated, "terminal", headers={})+ ticket = _mint(gated, "host-terminal", headers={})generic = gated.post("/api/auth/ws-ticket").json()["ticket"]with TestClient(host, base_url="https://fly-app.fly.dev") as shells:url = "wss://fly-app.fly.dev/api/host-terminal?ticket="@@ -164,15 +165,6 @@ _SPEAK = "/api/audio/speak-stream"_TRANSCRIBE = "/api/audio/transcribe-stream"-def _mint_audio(client, socket, headers=_SESSION):- response = client.post("/api/webapp/audio-ticket", params={"socket": socket}, headers=headers)- assert response.status_code == 200, response.text- assert response.headers["cache-control"] == "no-store"- body = response.json()- assert set(body) == {"ticket", "ttl_seconds"} and 0 < body["ttl_seconds"] <= 60- return body["ticket"]--@pytest.fixturedef voice(monkeypatch):"""Voice streams that answer once they admit a socket: speech yields one PCM frame, and live@@ -205,11 +197,11 @@ def _transcribes(client, url):def test_each_voice_stream_opens_once_with_a_ticket_minted_for_it(webapp, voice):client = webapp.client- assert client.post("/api/webapp/audio-ticket", params={"socket": "speak-stream"}).status_code == 401- speak = _mint_audio(client, "speak-stream")+ assert client.post("/api/webapp/socket-ticket", params={"socket": "speak-stream"}).status_code == 401+ speak = _mint(client, "speak-stream")_speaks(client, f"ws://localhost{_SPEAK}?ticket={speak}")_refused(client, f"ws://localhost{_SPEAK}?ticket={speak}")- transcribe = _mint_audio(client, "transcribe-stream")+ transcribe = _mint(client, "transcribe-stream")_transcribes(client, f"ws://localhost{_TRANSCRIBE}?ticket={transcribe}")_refused(client, f"ws://localhost{_TRANSCRIBE}?ticket={transcribe}")@@ -219,33 +211,36 @@ def test_a_voice_stream_refuses_a_ticket_minted_for_another_socket(webapp, voicestream; a voice stream's ticket opens no chat socket and no host shell."""client, host = webapp.client, webapp.hostfor url, other in ((_SPEAK, "transcribe-stream"), (_TRANSCRIBE, "speak-stream")):- for ticket in (_mint(client, "gateway"), _mint(client, "terminal"), _mint_audio(client, other)):+ for ticket in (_mint(client, "gateway"), _mint(client, "host-terminal"), _mint(client, other)):_refused(client, f"ws://localhost{url}?ticket={ticket}")- _refused(client, f"ws://localhost/api/ws?ticket={_mint_audio(client, 'speak-stream')}")- protocols = ["hermes-gateway-v1", f"hermes-gateway-ticket.{_mint_audio(client, 'transcribe-stream')}"]+ _refused(client, f"ws://localhost/api/ws?ticket={_mint(client, 'speak-stream')}")+ protocols = ["hermes-gateway-v1", f"hermes-gateway-ticket.{_mint(client, 'transcribe-stream')}"]_refused(client, "ws://localhost/api/ws?native_dial=browser", subprotocols=protocols)with TestClient(host) as shells:- _refused(shells, f"ws://localhost/api/host-terminal?ticket={_mint_audio(client, 'speak-stream')}")+ _refused(shells, f"ws://localhost/api/host-terminal?ticket={_mint(client, 'speak-stream')}")assert webapp.shells == []def test_voice_tickets_minted_before_the_session_token_changed_open_nothing(webapp, voice, monkeypatch):server, client = webapp.server, webapp.client- speak, transcribe = _mint_audio(client, "speak-stream"), _mint_audio(client, "transcribe-stream")+ speak, transcribe = _mint(client, "speak-stream"), _mint(client, "transcribe-stream")monkeypatch.setattr(server, "_SESSION_TOKEN", "b" * 43)_refused(client, f"ws://localhost{_SPEAK}?ticket={speak}")_refused(client, f"ws://localhost{_TRANSCRIBE}?ticket={transcribe}")-def test_audio_tickets_are_minted_only_for_voice_streams_on_the_webapp(webapp, monkeypatch):+def test_socket_tickets_are_minted_only_for_the_webapps_sockets_on_the_webapp(webapp, monkeypatch):+ """One route mints every socket ticket; it knows only the Webapp's four sockets, and the+ standalone dashboard and ``hermes serve`` mint none."""server, client = webapp.server, webapp.client- for socket in ("gateway", "host-terminal", "display", ""):- response = client.post("/api/webapp/audio-ticket", params={"socket": socket}, headers=_SESSION)+ for socket in ("display", "events", "speak", ""):+ response = client.post("/api/webapp/socket-ticket", params={"socket": socket}, headers=_SESSION)assert response.status_code == 400, socketfor surface in ("dashboard", "serve"):monkeypatch.setattr(server.app.state, "ui_surface", surface)- response = client.post("/api/webapp/audio-ticket", params={"socket": "speak-stream"}, headers=_SESSION)- assert response.status_code == 404, surface+ for socket in ("gateway", "host-terminal", "speak-stream", "transcribe-stream"):+ response = client.post("/api/webapp/socket-ticket", params={"socket": socket}, headers=_SESSION)+ assert response.status_code == 404, (surface, socket)def test_a_native_clients_unnamed_ticket_still_opens_a_voice_stream(webapp, voice):@@ -275,13 +270,13 @@ def test_a_signed_in_browser_opens_its_voice_streams_with_their_own_tickets(webamonkeypatch.setattr(server.app.state, "auth_required", True)try:anonymous = TestClient(server.app, base_url="https://fly-app.fly.dev")- assert anonymous.post("/api/webapp/audio-ticket", params={"socket": "speak-stream"},+ assert anonymous.post("/api/webapp/socket-ticket", params={"socket": "speak-stream"},follow_redirects=False).status_code in (302, 401)gated = TestClient(server.app, base_url="https://fly-app.fly.dev")_logged_in(gated)- _speaks(gated, f"wss://fly-app.fly.dev{_SPEAK}?ticket={_mint_audio(gated, 'speak-stream', headers={})}")+ _speaks(gated, f"wss://fly-app.fly.dev{_SPEAK}?ticket={_mint(gated, 'speak-stream', headers={})}")_transcribes(- gated, f"wss://fly-app.fly.dev{_TRANSCRIBE}?ticket={_mint_audio(gated, 'transcribe-stream', headers={})}")+ gated, f"wss://fly-app.fly.dev{_TRANSCRIBE}?ticket={_mint(gated, 'transcribe-stream', headers={})}")_refused(gated, f"wss://fly-app.fly.dev{_SPEAK}?ticket={_mint(gated, 'gateway', headers={})}")finally:clear_providers()diff --git a/tests/hermes_cli/test_webapp_ticket_profile.py b/tests/hermes_cli/test_webapp_ticket_profile.pyindex 8394721a5c7..9175e3707d3 100644--- a/tests/hermes_cli/test_webapp_ticket_profile.py+++ b/tests/hermes_cli/test_webapp_ticket_profile.py@@ -54,8 +54,8 @@ def two_profiles(monkeypatch, tmp_path):def _ask(client, method, params, profile=None):"""*method*'s reply on a tab socket opened for *profile* (``?profile=`` on the page)."""- query = f"?profile={profile}" if profile else ""- minted = client.post(f"/api/webapp/gateway-ticket{query}", headers={"X-Hermes-Session-Token": _TOKEN})+ query = f"&profile={profile}" if profile else ""+ minted = client.post(f"/api/webapp/socket-ticket?socket=gateway{query}", headers={"X-Hermes-Session-Token": _TOKEN})assert minted.status_code == 200, minted.textticket = minted.json()["ticket"]socket_query = f"&profile={profile}" if profile else ""