The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): open browser sockets with one-use tickets and close them on sign-out
emozillab7a97cea05a0
diff --git a/apps/desktop/src/api/plugins.ts b/apps/desktop/src/api/plugins.tsindex 5fba448d990..e781e663c93 100644--- a/apps/desktop/src/api/plugins.ts+++ b/apps/desktop/src/api/plugins.ts@@ -1,6 +1,7 @@import { isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'import type { HermesConnection } from '@/global'+import { isBrowserHostedDesktop } from '@/lib/platform'import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'import { $apiRequestScope, getApiRequestConnection, getApiRequestProfile, hermesApi, profileScoped } from './client'@@ -188,9 +189,10 @@ export function pluginSocket(pluginId: string, path: string, onMessage: (data: ureturn retry(dial, false)}- // OAuth cookie auth (WS tickets are single-use, core-managed): stay on the- // polling fallback rather than half-working.- if (stale() || connection.authMode === 'oauth') {+ // OAuth cookie auth (WS tickets are single-use, core-managed) and the browser-hosted+ // Desktop (its session token never rides a URL): stay on the polling fallback rather than+ // half-working.+ if (stale() || connection.authMode === 'oauth' || isBrowserHostedDesktop()) {return}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 bc854c2bd0d..2e4d51380ca 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@@ -137,6 +137,18 @@ function Harness({ id }: { id: string }) {beforeEach(() => {window.dispatchEvent(new PageTransitionEvent('pageshow'))localStorage.clear()+ // A Webapp tab dials each host terminal with a one-use ticket from the ticket route.+ const realFetch = globalThis.fetch+ let minted = 0+ vi.stubGlobal('fetch', vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ if (new URL(String(input), window.location.href).pathname.endsWith('/api/webapp/terminal-ticket')) {+ minted += 1++ return new Response(JSON.stringify({ ticket: `shell-ticket-${minted}` }), { status: 200 })+ }++ return realFetch(input, init)+ }))})afterEach(() => {diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsindex ffca13a99a1..5c9244de5cd 100644--- a/apps/desktop/src/lib/browser-desktop-bridge.test.ts+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -843,7 +843,8 @@ describe('browser-hosted Desktop bridge', () => {seedWebappSession('served-token')$connection.set({ profile: 'active-terminal' } as never)- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 })))+ const fetchMock = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ ticket: 'shell-ticket' })))+ vi.stubGlobal('fetch', fetchMock)class FakeWebSocket {static readonly CONNECTING = 0@@ -900,7 +901,9 @@ describe('browser-hosted Desktop bridge', () => {await expect(win.hermesDesktop!.terminal.attach(session.id)).resolves.toBe(true)await expect(win.hermesDesktop!.terminal.attach('missing-terminal')).resolves.toBe(false)expect(url.pathname).toBe('/hermes/api/host-terminal')- expect(url.searchParams.get('token')).toBe('served-token')+ 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(url.searchParams.get('profile')).toBe('active-terminal')expect(url.searchParams.get('cwd')).toBe('/work')expect(url.searchParams.get('cols')).toBe('42')@@ -932,10 +935,50 @@ describe('browser-hosted Desktop bridge', () => {await expect(win.hermesDesktop!.terminal.dispose(session.id)).resolves.toBe(true)})+ it('opens the host shell of a signed-in browser with a terminal ticket from its cookie session', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ const fetchMock = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ ticket: 'shell-ticket' })))+ vi.stubGlobal('fetch', fetchMock)+ const dialed: string[] = []++ class SignedInSocket {+ binaryType = ''+ onclose: ((event: CloseEvent) => void) | null = null+ onerror: (() => void) | null = null+ onmessage: ((event: MessageEvent) => void) | null = null+ onopen: (() => void) | null = null+ readyState = 0++ constructor(url: string | URL) {+ dialed.push(String(url))+ queueMicrotask(() => {+ this.readyState = 1+ this.onopen?.()+ this.onmessage?.({ data: '\u0000HERMES_TERMINAL_META:{"shell":"sh"}' } as MessageEvent)+ })+ }++ close() {}+ send() {}+ }++ vi.stubGlobal('WebSocket', SignedInSocket)+ expect(installBrowserDesktopBridge()).toBe(true)+ 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(init.method).toBe('POST')+ expect(init.credentials).toBe('same-origin')+ expect(new Headers(init.headers).has('X-Hermes-Session-Token')).toBe(false)+ expect(new URL(dialed[0]).searchParams.get('ticket')).toBe('shell-ticket')+ })+it('buffers early host-shell output until Desktop registers its terminal data listener', async () => {const win = mutableWindow()seedWebappSession('served-token')- vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 })))+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => new Response(JSON.stringify({ ticket: 'shell-ticket' }))))class PromptWebSocket {static readonly OPEN = 1diff --git a/apps/desktop/src/lib/browser-launch-session.test.ts b/apps/desktop/src/lib/browser-launch-session.test.tsindex 26f8c580a92..f32078c1bfe 100644--- a/apps/desktop/src/lib/browser-launch-session.test.ts+++ b/apps/desktop/src/lib/browser-launch-session.test.ts@@ -1,5 +1,7 @@import { afterEach, expect, it, vi } from 'vitest'+import { pluginSocket } from '@/api/plugins'+import { installBrowserDesktopBridge } from './browser-desktop-bridge'import { consumeWebappSession, watchWebappLaunchLink } from './browser-launch-session'@@ -40,9 +42,13 @@ it('uses one private session for REST, RPC and terminal across reload without lovi.stubGlobal('WebSocket', Socket)- const fetchMock = vi.fn().mockImplementation(async (url: URL) =>- new Response(url.pathname.endsWith('/api/webapp/gateway-ticket') ? '{"ticket":"rpc-ticket"}' : '{"ok":true}', { status: 200 })- )+ const minted: Record<string, string> = { 'gateway-ticket': 'rpc-ticket', 'terminal-ticket': 'shell-ticket' }++ const fetchMock = vi.fn().mockImplementation(async (url: URL) => {+ const ticket = minted[url.pathname.split('/api/webapp/')[1] ?? '']++ return new Response(ticket ? JSON.stringify({ ticket }) : '{"ok":true}', { status: 200 })+ })vi.stubGlobal('fetch', fetchMock)expect(installBrowserDesktopBridge()).toBe(true)@@ -62,9 +68,21 @@ it('uses one private session for REST, RPC and terminal across reload without loexpect(rpcUrl.searchParams.get('profile')).toBe('coder')const mint = fetchMock.mock.calls.find(([url]) => (url as URL).pathname === '/one/api/webapp/gateway-ticket')!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('token')).toBe(token)+ 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')!+ 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.+ const stopPluginSocket = pluginSocket('kanban', '/events', () => undefined)+ await new Promise(resolve => setTimeout(resolve, 20))+ stopPluginSocket()+ // No URL this tab requested or dialed carries the session token: it rides only the request header.+ const requested = [...fetchMock.mock.calls.map(([url]) => String(url)), ...urls.map(String), rpcUrl.href]+ expect(requested.filter(url => url.includes(token))).toEqual([])+ expect(urls).toHaveLength(1)window.dispatchEvent(new Event('beforeunload'))Reflect.deleteProperty(window, 'hermesDesktop')window.history.replaceState(null, '', '/one/?profile=coder#/settings')diff --git a/apps/desktop/src/lib/browser-transport.ts b/apps/desktop/src/lib/browser-transport.tsindex d14b5c7ea76..5784afea4f2 100644--- a/apps/desktop/src/lib/browser-transport.ts+++ b/apps/desktop/src/lib/browser-transport.ts@@ -68,20 +68,15 @@ export function endpointUrl(path: string, basePath: string, profile?: null | strreturn url}+/** A socket URL on this origin; its only credential is a one-use ticket, never the session token. */export function websocketUrl(basePath: string,path: string,- credential: { ticket?: string; token?: string },+ credential: { ticket?: string },profile?: null | string): string {- const authParam = credential.ticket- ? (['ticket', credential.ticket] as const)- : credential.token- ? (['token', credential.token] as const)- : undefined-return buildHermesWebSocketUrl({- authParam,+ authParam: credential.ticket ? ['ticket', credential.ticket] : undefined,basePath,params: profile ? { profile } : undefined,path@@ -295,25 +290,25 @@ 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> {- if (!bootstrap.authRequired) {- if (!bootstrap.token) {throw new Error(WEBAPP_LAUNCH_REQUIRED)}-- return websocketUrl(bootstrap.basePath, path, { token: bootstrap.token }, profile)- }-- const result = await browserApi<{ ticket?: string }>(bootstrap, {+ const result = await browserApi<null | { ticket?: string }>(bootstrap, {method: 'POST',- path: '/api/auth/ws-ticket'+ path: '/api/webapp/terminal-ticket'})- const ticket = String(result.ticket || '').trim()+ const ticket = String(result?.ticket || '').trim()- if (!ticket) {throw new Error('Hermes did not return a WebSocket ticket')}+ if (!ticket) {throw new Error('Hermes did not return a terminal ticket')}return websocketUrl(bootstrap.basePath, path, { ticket }, profile)}diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.pyindex 9567ce3746a..bead1d3193f 100644--- a/gateway/webapp_listener.py+++ b/gateway/webapp_listener.py@@ -164,7 +164,7 @@ def register_control_verbs(runner, home) -> None:reaches them. ``webapp-launch`` returns a one-use launch link, so the credential crosses neitherthe socket nor a browser's argv; where such a link cannot be redeemed (macOS) it returns theprivate credential link instead, for the user to open by hand. ``webapp-sign-out`` replaces the- browser credential."""+ browser credential and closes the browser sockets it opened."""server = getattr(runner, "session_control_server", None)if server is None:return@@ -201,8 +201,13 @@ def register_control_verbs(runner, home) -> None:"expires_in_seconds": LAUNCH_TICKET_TTL_SECONDS}def webapp_sign_out(_params, _peer):+ from hermes_cli import web_server_file_tickets, web_session_sockets_, web = serving()web._SESSION_TOKEN = browser_session_token(home, rotate=True)+ # Every tab loses access at once: the sockets and media links the old credential opened end+ # now, not when each tab next reconnects. Native clients never held it and stay connected.+ web_session_sockets.close_all()+ web_server_file_tickets.revoke_all()return {"signed_out": True}server.private_handlers.update({diff --git a/hermes_cli/web_host_terminal_sessions.py b/hermes_cli/web_host_terminal_sessions.pyindex 24a3f5c4058..04d951d7dfe 100644--- a/hermes_cli/web_host_terminal_sessions.py+++ b/hermes_cli/web_host_terminal_sessions.py@@ -74,17 +74,13 @@ class HostOwner:def _request_identity(ws: WebSocket) -> tuple[str, str]:- identity = getattr(ws, "_hermes_auth_identity", None)- if identity:- user, provider = identity.get("user_id"), identity.get("provider")- if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider:- raise TerminalDenied()- return provider, user- from hermes_cli.web_server import app- if getattr(app.state, "auth_required", False):+ """``(provider, user)`` of the terminal ticket that admitted *ws*; ``_ws_gate`` admits no other+ credential to the host terminal."""+ identity = getattr(ws, "_hermes_auth_identity", None) or {}+ user, provider = identity.get("user_id"), identity.get("provider")+ if not isinstance(user, str) or not user or not isinstance(provider, str) or not provider:raise TerminalDenied()- # _ws_gate already validated the process's loopback credential.- return "loopback", "session-token"+ return provider, userdef _request_home(profile: str | None) -> Path:diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 13553ddc436..4261981e078 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -23,6 +23,7 @@ from hermes_cli.web_server_chat import (_build_sidecar_url, _close_stalled_pty_input, _get_console_executor, _legacy_pump, _pty_fail, _ws_auth_ok,_ws_close_reason, _ws_gate, _ws_request_is_allowed,)+from hermes_cli.web_session_sockets import GATEWAY_SOCKET_log = logging.getLogger("hermes_cli.web_server")router = APIRouter()@@ -98,13 +99,14 @@ def _read_active_session_file(path: Path) -> Optional[str]:return str(data.get("session_id") or "").strip() or None-async def _close_unless_sidecar_allowed(ws: WebSocket, *, allow_internal: bool = False) -> bool:+async def _close_unless_sidecar_allowed(ws: WebSocket, *, allow_internal: bool = False,+ socket: Optional[str] = None) -> bool:"""Pre-accept gates for the /api/ws, /api/pub and /api/events sidecars:4403 when chat is disabled or the request isn't allowed, 4401 on bad auth."""if not _DASHBOARD_EMBEDDED_CHAT_ENABLED:await ws.close(code=4403)return False- if not _ws_auth_ok(ws, allow_internal=allow_internal):+ if not _ws_auth_ok(ws, allow_internal=allow_internal, socket=socket):await ws.close(code=4401)return Falseif not _ws_request_is_allowed(ws):@@ -630,7 +632,7 @@ async def pty_ws(ws: WebSocket) -> None:@router.websocket("/api/ws")async def gateway_ws(ws: WebSocket) -> None:- if not await _close_unless_sidecar_allowed(ws, allow_internal=True):+ if not await _close_unless_sidecar_allowed(ws, allow_internal=True, socket=GATEWAY_SOCKET):returnfrom hermes_cli.mcp_startup import start_deferred_mcp_discovery_nowfrom tui_gateway.ws import handle_wsdiff --git a/hermes_cli/web_routers/webapp.py b/hermes_cli/web_routers/webapp.pyindex 4ee1c0ca512..7f653ad289a 100644--- a/hermes_cli/web_routers/webapp.py+++ b/hermes_cli/web_routers/webapp.py@@ -1,7 +1,8 @@"""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), 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/gateway-ticket`` for+``/api/ws`` on this same origin, ``/api/webapp/terminal-ticket`` for the host terminal),+and the one-use handoffs (child window, auto-opened launch tab) for the private, loopback+Webapp session."""from __future__ import annotationsimport ipaddress@@ -18,6 +19,7 @@ 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 GATEWAY_SOCKET, HOST_TERMINAL_SOCKET_log = logging.getLogger("hermes_cli.web_server")router = APIRouter()@@ -26,6 +28,9 @@ WINDOW_TICKET_TTL_SECONDS = 30LAUNCH_TICKET_TTL_SECONDS = 60_MAX_WINDOW_TICKETS = 128_ticket_lock = threading.Lock()+#: Who a socket opened with the loopback session token is (``chat_ws.gateway_ws`` gives a+#: ``?token=`` socket the same identity, and REST mutations are forwarded as it).+SESSION_TOKEN_OWNER = {"user_id": "legacy-token-owner", "provider": "session-token", "issuer": ""}def _require_private_webapp(request: Request) -> None:@@ -39,7 +44,7 @@ async def host_terminal_ws(ws: WebSocket) -> None:from hermes_cli.web_host_terminal_sessions import host_terminalfrom hermes_cli.web_server_chat import _PTY_BRIDGE_AVAILABLE, PtyUnavailableError, _pty_fail, _ws_gate- gate = await _ws_gate(ws, "host-terminal")+ gate = await _ws_gate(ws, HOST_TERMINAL_SOCKET)if gate is None:returnpeer, mode, cred = gate@@ -143,37 +148,69 @@ async def issue_window_ticket(request: Request):return JSONResponse({"ticket": ticket}, headers={"Cache-Control": "no-store"})-def _ticket_principal(request: Request) -> dict:- """``{user_id, provider, issuer}`` of the caller: its verified login, or on an unauthenticated- loopback bind the session-token owner, the identity ``chat_ws.gateway_ws`` gives a ``?token=``- socket (and REST mutations are forwarded as)."""+def _ticket_principal(request: Request) -> tuple[dict, str | None]:+ """``({user_id, provider, issuer}, session_token)`` of the caller: its verified login (no+ token), or on an unauthenticated loopback bind ``SESSION_TOKEN_OWNER`` and the session token+ it presented."""session = getattr(request.state, "session", None)if session is not None:return {"user_id": session.user_id, "provider": session.provider,- "issuer": getattr(session, "issuer", "") or ""}+ "issuer": getattr(session, "issuer", "") or ""}, Noneif not getattr(request.app.state, "auth_required", False):- from hermes_cli.web_server import _has_valid_session_token+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _has_valid_session_token+ presented = (request.headers.get(_SESSION_HEADER_NAME)+ or request.headers.get("authorization", "").removeprefix("Bearer "))if _has_valid_session_token(request):- return {"user_id": "legacy-token-owner", "provider": "session-token", "issuer": ""}+ return dict(SESSION_TOKEN_OWNER), presentedraise HTTPException(status_code=401, detail="Unauthorized")+def mint_socket_ticket(identity: dict, socket: str, *, session_token: str | None = None) -> str:+ """A one-use ticket that opens only *socket* (``web_session_sockets.GATEWAY_SOCKET`` or+ ``HOST_TERMINAL_SOCKET``) as *identity*. Minted with *session_token*, it opens nothing once that+ token is replaced, and the socket it opens closes when the browser signs out."""+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket+ from hermes_cli.web_session_sockets import token_digest++ extra = {"socket": socket}+ if session_token is not None:+ extra["session_token"] = token_digest(session_token)+ return mint_ticket(user_id=identity["user_id"], provider=identity["provider"],+ issuer=identity.get("issuer", ""), extra=extra)+++def _socket_ticket_response(identity: dict, socket: str, session_token: str | None) -> JSONResponse:+ from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS++ ticket = mint_socket_ticket(identity, socket, session_token=session_token)+ return JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})++@router.post("/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, offeredas the ``hermes-gateway-ticket.`` subprotocol and redeemed by the upgrade gate- (``web_server_chat._consume_ws_ticket``) as this caller's login. 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."""- from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS, mint_ticket+ (``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."""from hermes_cli.web_server_cron import _cron_profile_homeif not policy(request.app.state).gateway_ticket:raise HTTPException(404, "Webapp gateway tickets are unavailable on this surface")- identity = _ticket_principal(request)+ identity, session_token = _ticket_principal(request)_cron_profile_home(profile)- ticket = mint_ticket(user_id=identity["user_id"], provider=identity["provider"], issuer=identity["issuer"])- return JSONResponse({"ticket": ticket, "ttl_seconds": TTL_SECONDS}, headers={"Cache-Control": "no-store"})+ return _socket_ticket_response(identity, GATEWAY_SOCKET, session_token)++[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(identity, HOST_TERMINAL_SOCKET, session_token)@router.post("/webapp/window-session")diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 37137d9683a..2e7e3684ac7 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -7,6 +7,7 @@ import asyncioimport atexitimport concurrent.futuresimport contextlib+import functoolsimport hmacimport osimport re@@ -199,12 +200,16 @@ def _ws_request_view(ws: WebSocket) -> Request:})-def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False) -> tuple[Optional[str], str]:+def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False,+ socket: Optional[str] = None) -> tuple[Optional[str], str]:"""Validate WS-upgrade auth; return ``(reason, credential)``.``reason`` is None when accepted, else a short token (``no_credential``,``token_mismatch``, ``ticket_invalid``, ``internal_invalid``);``credential`` names what was presented so the accept path can log *how*.+ *socket* names the route's socket for its own tickets+ (``web_session_sockets.GATEWAY_SOCKET`` / ``HOST_TERMINAL_SOCKET``): a ticket minted for+ one socket opens no other, and the host terminal opens only with its own ticket.Loopback / ``--insecure``: legacy ``?token=`` (constant-time compared).Gated: ``?ticket=`` (browser-minted, single-use, 30s TTL) or ``?internal=``@@ -225,23 +230,25 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False) -> tuple[Opt"""from hermes_cli.dashboard_auth.native_http import HEADER, authenticate_native_wsfrom hermes_cli.web_server import _SESSION_TOKEN, app+ from hermes_cli.web_session_sockets import OWN_TICKET_SOCKETS, token_digest, track+ auth_required = bool(getattr(app.state, "auth_required", False))+ if socket in OWN_TICKET_SOCKETS:+ # No standing credential (the session token, a native grant, a login's access token) opens it.+ reject = functools.partial(_audit_ws_rejection, ws) if auth_required else _ignore_rejection+ return _consume_ws_ticket(ws, reject, socket, auth_required=auth_required) or ("no_credential", "none")if HEADER in ws.headers:grant = authenticate_native_ws(ws)if grant is None:return "native_invalid", "native"ws._hermes_auth_identity = {"user_id": grant["subject"], "provider": "local"}return None, "native"- auth_required = bool(getattr(app.state, "auth_required", False))if auth_required:# Lazy import — keeps this function importable in test harnesses# that don't bring in the dashboard_auth layer.from hermes_cli.dashboard_auth.audit import AuditEvent, audit_logfrom hermes_cli.dashboard_auth.ws_tickets import TicketInvalid, consume_internal_credential- def _reject(reason: str) -> None:- audit_log(- AuditEvent.WS_TICKET_REJECTED, reason=reason,- ip=(ws.client.host if ws.client else ""), path=ws.url.path)+ _reject = functools.partial(_audit_ws_rejection, ws)def _stamp_identity(info) -> None:# Server-minted {user_id, provider} stamped onto the WS object is the@@ -266,7 +273,7 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False) -> tuple[Opt_reject(f"internal: {exc}")return "internal_invalid", "internal"- consumed = _consume_ws_ticket(ws, _reject)+ consumed = _consume_ws_ticket(ws, _reject, socket, auth_required=True)if consumed is not None:return consumed@@ -319,23 +326,38 @@ def _ws_auth_reason(ws: WebSocket, *, allow_internal: bool = False) -> tuple[Opt# Loopback: a one-use ticket ``/api/webapp/gateway-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, lambda reason: None)+ consumed = _consume_ws_ticket(ws, _ignore_rejection, socket)if consumed is not None:return consumedtoken = ws.query_params.get("token", "")if not token:return "no_credential", "none"if hmac.compare_digest(token.encode(), _SESSION_TOKEN.encode()):+ track(ws, token_digest(token))return None, "token"return "token_mismatch", "token"-def _consume_ws_ticket(ws: WebSocket, reject) -> Optional[tuple[Optional[str], str]]:+def _ignore_rejection(reason: str) -> None:+ """The loopback gate keeps no audit record of a refused credential."""+++def _audit_ws_rejection(ws: WebSocket, reason: str) -> None:+ """The gated gate's audit record of a refused upgrade credential."""+ from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log+ audit_log(AuditEvent.WS_TICKET_REJECTED, reason=reason, ip=(ws.client.host if ws.client else ""),+ path=ws.url.path)+++def _consume_ws_ticket(ws: WebSocket, reject, socket: Optional[str] = None, *,+ auth_required: bool = False) -> Optional[tuple[Optional[str], str]]:"""A one-use ticket offered as the ``hermes-gateway-ticket.`` subprotocol or ``?ticket=``:``(reason, credential)`` once judged, or None when the upgrade presents none. An accepted ticketstamps the server-minted identity onto the socket; the client never supplies it through RPC- params."""+ params. *socket* is the route's socket (``web_session_sockets.ticket_refusal``); a socket a+ session-token ticket opens is tracked so signing out closes it."""from hermes_cli.dashboard_auth.ws_tickets import TicketInvalid, consume_ticket+ from hermes_cli.web_session_sockets import ticket_refusal, trackprotocol_ticket, protocol_reason = _gateway_ws_ticket_from_subprotocol(ws)if protocol_reason == "invalid":return "ticket_invalid", "ticket-subprotocol"@@ -347,6 +369,10 @@ def _consume_ws_ticket(ws: WebSocket, reject) -> Optional[tuple[Optional[str], sexcept TicketInvalid as exc:reject(str(exc))return "ticket_invalid", "ticket"+ refusal = ticket_refusal(info, socket, auth_required=auth_required)+ if refusal is not None:+ reject(refusal)+ return "ticket_invalid", "ticket"if info.get("provider") == "bot-desktop":# A display ticket admits one RFB bridge on /api/display/ws (a watch-only capability handed# to a screen viewer); it must not double as a login here.@@ -356,6 +382,8 @@ def _consume_ws_ticket(ws: WebSocket, reject) -> Optional[tuple[Optional[str], sws._hermes_auth_identity = {"user_id": info.get("user_id"), "provider": info.get("provider")}if info.get("issuer"):ws._hermes_auth_identity["issuer"] = info["issuer"]+ if "session_token" in info:+ track(ws, info["session_token"])if not protocol_ticket:return None, "ticket"# Select only the stable public protocol during accept. The ticket-bearing protocol is a@@ -364,9 +392,9 @@ def _consume_ws_ticket(ws: WebSocket, reject) -> Optional[tuple[Optional[str], sreturn None, "ticket-subprotocol"-def _ws_auth_ok(ws: WebSocket, *, allow_internal: bool = False) -> bool:+def _ws_auth_ok(ws: WebSocket, *, allow_internal: bool = False, socket: Optional[str] = None) -> bool:"""True when the WS-upgrade credential is accepted. See _ws_auth_reason."""- return _ws_auth_reason(ws, allow_internal=allow_internal)[0] is None+ return _ws_auth_reason(ws, allow_internal=allow_internal, socket=socket)[0] is Nonedef _ws_auth_mode() -> str:@@ -404,7 +432,7 @@ async def _ws_gate(ws: WebSocket, kind: str) -> Optional[tuple[str, str, str]]:await ws.close(code=4404, reason="embedded chat disabled")return None- auth_reason, cred = _ws_auth_reason(ws)+ auth_reason, cred = _ws_auth_reason(ws, socket=kind)mode = _ws_auth_mode()if auth_reason is not None:_log.warning("%s auth rejected reason=%s mode=%s cred=%s peer=%s", kind, auth_reason, mode, cred, peer)diff --git a/hermes_cli/web_server_file_tickets.py b/hermes_cli/web_server_file_tickets.pyindex acd3580054f..31d39abae27 100644--- a/hermes_cli/web_server_file_tickets.py+++ b/hermes_cli/web_server_file_tickets.py@@ -87,6 +87,12 @@ def mint(route: str, query: Mapping[str, str], *, authority: FileAuthority) -> sreturn ticket+def revoke_all() -> None:+ """Drop every ticket: the session token that authorized them was replaced (sign-out)."""+ with _lock:+ _tickets.clear()++def redeem(request: Request) -> bool:"""True when ``?ticket=`` authorizes this exact request; consumes a download ticket."""ticket = request.query_params.get("ticket", "")diff --git a/hermes_cli/web_session_sockets.py b/hermes_cli/web_session_sockets.pynew file mode 100644index 00000000000..dbd0249042f--- /dev/null+++ b/hermes_cli/web_session_sockets.py@@ -0,0 +1,106 @@+"""Browser sockets the dashboard session token opens, and how they end when it is replaced.++A browser on the loopback Webapp never puts the session token in a socket URL. An authenticated+request mints a one-use ticket for one socket instead: ``GATEWAY_SOCKET`` (``/api/ws``) or+``HOST_TERMINAL_SOCKET`` (``/api/host-terminal``). A ticket named for one socket opens no other, and+the host terminal opens only with its own ticket. A ticket minted with the session token records that+token's digest and opens nothing once the token is replaced.++Every socket the session token admits, directly or through such a ticket, is tracked here until it+ends, so ``close_all`` (run when ``hermes webapp --sign-out`` replaces the token) closes them all at+once. Sockets admitted on any other credential (a signed-in login, a native client's grant) are never+tracked.+"""+from __future__ import annotations++import asyncio+import contextlib+import hashlib+import hmac+import logging+import threading+import weakref+from typing import Any, Optional++from starlette.websockets import WebSocketDisconnect++_log = logging.getLogger(__name__)++GATEWAY_SOCKET = "gateway"+HOST_TERMINAL_SOCKET = "host-terminal"+#: Sockets that open only with a ticket minted for them, never with a standing credential.+OWN_TICKET_SOCKETS = frozenset({HOST_TERMINAL_SOCKET})+#: What a signed-out tab's sockets are closed with: the same code a refused credential gets.+SIGNED_OUT_CODE = 4401++_lock = threading.Lock()+_live: dict[int, tuple[weakref.ref, asyncio.AbstractEventLoop]] = {}+++def token_digest(token: str) -> str:+ return hashlib.sha256(token.encode()).hexdigest()+++def _current_digest() -> str:+ from hermes_cli.web_server import _SESSION_TOKEN+ return token_digest(_SESSION_TOKEN)+++def ticket_refusal(info: dict[str, Any], socket: Optional[str], *, auth_required: bool) -> Optional[str]:+ """Why a redeemed ticket may not open *socket*, or None when it may.++ A ticket named for a socket opens only that socket; an unnamed ticket opens any socket except+ one that takes only its own ticket. A ticket minted with the session token opens nothing behind+ the sign-in gate, nor once that token is replaced.+ """+ named = info.get("socket")+ if named != socket and (named is not None or socket in OWN_TICKET_SOCKETS):+ return f"ticket for {named or 'any socket'} presented to {socket or 'an unnamed socket'}"+ minted_with = info.get("session_token")+ if minted_with is not None and (auth_required or not hmac.compare_digest(minted_with, _current_digest())):+ return "ticket minted with a replaced session token"+ return None+++def track(ws, admitted_with: str) -> None:+ """Keep *ws*, admitted on the session token whose digest is *admitted_with*, until it ends.++ A socket admitted while that token was being replaced closes at once, so ``close_all`` never+ misses one.+ """+ try:+ loop = asyncio.get_running_loop()+ except RuntimeError: # judged outside a server loop: no live socket to close later+ return+ with _lock:+ # Ended sockets are dropped here rather than from a weakref callback, which garbage+ # collection could run while this thread already holds the lock.+ for key in [key for key, (ref, _loop) in _live.items() if ref() is None]:+ del _live[key]+ _live[id(ws)] = (weakref.ref(ws), loop)+ if not hmac.compare_digest(admitted_with, _current_digest()):+ _close_on(ws, loop)+++async def _close(ws) -> None:+ # The socket may already be closing or gone; it ends either way.+ with contextlib.suppress(RuntimeError, OSError, WebSocketDisconnect):+ await ws.close(code=SIGNED_OUT_CODE, reason="Signed out")+++def _close_on(ws, loop: asyncio.AbstractEventLoop) -> bool:+ if loop.is_closed():+ return False+ asyncio.run_coroutine_threadsafe(_close(ws), loop)+ return True+++def close_all() -> int:+ """Close every live socket the session token admitted, each on its own event loop. Safe from any+ thread; returns how many were asked to close."""+ with _lock:+ live = list(_live.values())+ _live.clear()+ closing = sum(_close_on(ws, loop) for ref, loop in live if (ws := ref()) is not None)+ _log.info("Closing %d browser sockets opened with the replaced session token", closing)+ return closingdiff --git a/tests/gateway/fixtures/webapp_listener_peer.py b/tests/gateway/fixtures/webapp_listener_peer.pyindex 82d4796052a..ab08ecc2d80 100644--- a/tests/gateway/fixtures/webapp_listener_peer.py+++ b/tests/gateway/fixtures/webapp_listener_peer.py@@ -14,6 +14,78 @@ import tracebackSEEDED_TOKEN = "seeded-browser-credential-from-an-earlier-0" # 43 URL-safe characters+async def _upgrade_refusal(url, **kwargs):+ """The HTTP status a refused upgrade answers, or ``"accepted"``."""+ from websockets.asyncio.client import connect+ from websockets.exceptions import InvalidStatus++ try:+ async with connect(url, **kwargs):+ return "accepted"+ except InvalidStatus as exc:+ return exc.response.status_code+++async def _close_code(ws, seconds=10):+ """The code the server closed *ws* with, reading past any frames it sends first."""+ from websockets.exceptions import ConnectionClosed++ try:+ async with asyncio.timeout(seconds):+ while True:+ await ws.recv()+ except ConnectionClosed as exc:+ return exc.rcvd.code if exc.rcvd else None+ except TimeoutError:+ return "open"+++async def sockets_across_sign_out(runner, client, origin, ask):+ """A tab's chat socket and host terminal and a native client's session socket, open across a+ sign-out; also what each browser socket ticket refuses to open."""+ from websockets.asyncio.client import connect++ from gateway.runtime_bootstrap import TicketStore+ from hermes_cli import web_host_terminal, web_server+ from tests.gateway.fixtures.local_recovery_probe import rpc++ # A harmless program stands in for the user's login shell.+ web_host_terminal.shell_spec = lambda: ([sys.executable, "-c", "import time; time.sleep(120)"], "python")+ 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"]++ def chat_protocols(value):+ return ["hermes-gateway-v1", f"hermes-gateway-ticket.{value}"]++ report = {+ "terminal_refuses_session_token": await _upgrade_refusal(+ f"{sockets}/api/host-terminal?token={web_server._SESSION_TOKEN}", origin=origin),+ "terminal_refuses_chat_ticket": await _upgrade_refusal(+ 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"))),+ }+ authority = runner.session_authority+ runner.session_ticket_store = TicketStore("webapp-listener", frozenset({authority.profile_id}))+ native_ticket = runner.session_ticket_store.mint(+ 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/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")+ report["sign_out_ok"] = ask("webapp-sign-out")["ok"]+ report["chat_close_after_sign_out"] = await _close_code(chat)+ report["terminal_close_after_sign_out"] = await _close_code(terminal)+ report["native_answers_after_sign_out"] = "result" in await rpc(native, "session.list")+ return report++async def probe(mode, port, dist):import httpxfrom websockets.asyncio.client import connect@@ -87,7 +159,7 @@ async def probe(mode, port, dist):redeemed.json()["token"] == SEEDED_TOKEN)report["handoff_reuse_status"] = (await client.post("/webapp/window-session", headers=handoff)).status_code- report["sign_out_ok"] = ask("webapp-sign-out")["ok"]+ report.update(await sockets_across_sign_out(runner, client, origin, ask))stale = await client.post("/api/webapp/gateway-ticket",headers={"X-Hermes-Session-Token": SEEDED_TOKEN})report["old_credential_status"] = stale.status_codediff --git a/tests/gateway/test_gateway_serves_webapp.py b/tests/gateway/test_gateway_serves_webapp.pyindex 04c0b97b563..c02959fdf90 100644--- a/tests/gateway/test_gateway_serves_webapp.py+++ b/tests/gateway/test_gateway_serves_webapp.py@@ -4,8 +4,9 @@ With it on, the dashboard mount serves the Webapp bundle without the session tokbrowser credential is the one kept in the gateway home (so it survives a restart), the host terminalregistry runs, and a browser holding that credential gets a socket ticket and opens a gateway sessionon the same origin. The launcher's link comes over the control socket and spends once; signing out-replaces the credential. With it off, the listener is main's private one: no Webapp surface, no ticket-route, no credential file, no launch link.+replaces the credential and closes the browser sockets it opened, while native clients stay+connected. Each browser socket ticket opens only its own socket. With it off, the listener is main's+private one: no Webapp surface, no ticket route, no credential file, no launch link."""import jsonfrom pathlib import Path@@ -96,6 +97,22 @@ def test_signing_out_cuts_off_the_old_browser_credential(webapp_on):assert report["token_file_rotated"] is True+def test_each_browser_socket_ticket_opens_only_its_own_socket(webapp_on):+ _, report = webapp_on+ assert report["terminal_opens_with_its_ticket"] is True+ assert report["chat_opens_before_sign_out"] is True+ assert report["terminal_refuses_session_token"] == 403+ assert report["terminal_refuses_chat_ticket"] == 403+ assert report["chat_refuses_terminal_ticket"] == 403+++def test_signing_out_closes_the_browser_sockets_and_keeps_native_clients(webapp_on):+ _, report = webapp_on+ assert report["chat_close_after_sign_out"] == 4401+ assert report["terminal_close_after_sign_out"] == 4401+ assert report["native_answers_after_sign_out"] is True++def test_without_the_webapp_the_listener_stays_mains_private_one(webapp_off):_, report = webapp_offassert report["index_is_webapp"] is Falsediff --git a/tests/hermes_cli/test_pty_keepalive_ws.py b/tests/hermes_cli/test_pty_keepalive_ws.pyindex a881af42667..1a09abaa0d2 100644--- a/tests/hermes_cli/test_pty_keepalive_ws.py+++ b/tests/hermes_cli/test_pty_keepalive_ws.py@@ -47,7 +47,7 @@ def pty_keepalive_harness(monkeypatch):return bmonkeypatch.setattr(_web_server_chat.PtyBridge, "spawn", staticmethod(fake_spawn))- monkeypatch.setattr(_web_server_chat, "_ws_auth_reason", lambda ws: (None, "test"))+ monkeypatch.setattr(_web_server_chat, "_ws_auth_reason", lambda ws, **_kwargs: (None, "test"))monkeypatch.setattr(_web_server_chat, "_ws_host_origin_reason", lambda ws: None)monkeypatch.setattr(_web_server_chat, "_ws_client_reason", lambda ws: None)diff --git a/tests/hermes_cli/test_serve_mcp_discovery_after_bind.py b/tests/hermes_cli/test_serve_mcp_discovery_after_bind.pyindex 31c2237e3c8..b7f256e79be 100644--- a/tests/hermes_cli/test_serve_mcp_discovery_after_bind.py+++ b/tests/hermes_cli/test_serve_mcp_discovery_after_bind.py@@ -113,6 +113,7 @@ def test_first_gateway_ws_client_starts_the_armed_discovery_once(monkeypatch):import asynciofrom hermes_cli.web_routers import chat_ws+ from hermes_cli.web_session_sockets import GATEWAY_SOCKET_reset_discovery_state(monkeypatch)calls: list[str] = []@@ -124,8 +125,9 @@ def test_first_gateway_ws_client_starts_the_armed_discovery_once(monkeypatch):)assert calls == []- async def _allowed(ws, *, allow_internal=False):+ async def _allowed(ws, *, allow_internal=False, socket=None):assert allow_internal is True+ assert socket == GATEWAY_SOCKET # /api/ws accepts only tickets minted for itreturn Trueasync def _handle_ws(ws, **kwargs):diff --git a/tests/hermes_cli/test_web_host_terminal.py b/tests/hermes_cli/test_web_host_terminal.pyindex 7c56b82b233..e4b8e285545 100644--- a/tests/hermes_cli/test_web_host_terminal.py+++ b/tests/hermes_cli/test_web_host_terminal.py@@ -34,13 +34,18 @@ def test_host_terminal_rejection_runs_through_websocket_route(from starlette.testclient import TestClientfrom starlette.websockets import WebSocketDisconnect+ from hermes_cli.web_routers.webapp import SESSION_TOKEN_OWNER, mint_socket_ticket+ from hermes_cli.web_session_sockets import HOST_TERMINAL_SOCKET+monkeypatch.setattr(web_server.app.state, "ui_surface", surface, raising=False)monkeypatch.setattr(web_server.app.state, "bound_host", bound_host, raising=False)monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)with pytest.raises(WebSocketDisconnect) as exc:with TestClient(web_server.app).websocket_connect(- f"/api/host-terminal?token={web_server._SESSION_TOKEN}", headers=headers+ "/api/host-terminal?ticket=" + mint_socket_ticket(+ SESSION_TOKEN_OWNER, HOST_TERMINAL_SOCKET, session_token=web_server._SESSION_TOKEN),+ headers=headers,):passdiff --git a/tests/hermes_cli/test_web_host_terminal_lifespan.py b/tests/hermes_cli/test_web_host_terminal_lifespan.pyindex 9eca0c882f6..9fa3767d9ca 100644--- a/tests/hermes_cli/test_web_host_terminal_lifespan.py+++ b/tests/hermes_cli/test_web_host_terminal_lifespan.py@@ -61,7 +61,8 @@ def test_real_shells_remain_owned_after_overlapping_lifespan_exit(tmp_path, monkimport psutilfrom hermes_cli import web_host_terminal, web_server- from hermes_cli.web_routers.webapp import router+ from hermes_cli.web_routers.webapp import SESSION_TOKEN_OWNER, mint_socket_ticket, router+ from hermes_cli.web_session_sockets import HOST_TERMINAL_SOCKEThome = tmp_path / ".hermes"home.mkdir()@@ -75,12 +76,14 @@ def test_real_shells_remain_owned_after_overlapping_lifespan_exit(tmp_path, monkmonkeypatch.setattr(web_host_terminal, "shell_spec", lambda: (["/bin/sh", "-i"], "sh"))app = FastAPI(lifespan=host_terminal_lifespan)app.include_router(router)- url = f"ws://localhost/api/host-terminal?token={web_server._SESSION_TOKEN}"+ def url():+ ticket = mint_socket_ticket(SESSION_TOKEN_OWNER, HOST_TERMINAL_SOCKET, session_token=web_server._SESSION_TOKEN)+ return f"ws://localhost/api/host-terminal?ticket={ticket}"bridges = []processes = []def open_shell(client):- with client.websocket_connect(url) as ws:+ with client.websocket_connect(url()) as ws:metadata = json.loads(ws.receive_text().removeprefix(web_host_terminal.META_PREFIX))session = get_host_terminals(app)._sessions[metadata["terminalId"]]bridges.append(session.bridge)@@ -111,7 +114,7 @@ def test_real_shells_remain_owned_after_overlapping_lifespan_exit(tmp_path, monk# An accepted request outside a lifespan must fail, not spawn a shell.# TestClient without a context deliberately does not run startup.- with TestClient(app).websocket_connect(url) as ws:+ with TestClient(app).websocket_connect(url()) as ws:assert "terminalId" not in ws.receive_text()with pytest.raises(WebSocketDisconnect) as error:ws.receive_bytes()diff --git a/tests/hermes_cli/test_web_host_terminal_persistence.py b/tests/hermes_cli/test_web_host_terminal_persistence.pyindex 6051e551ea2..da0ee4c5d3d 100644--- a/tests/hermes_cli/test_web_host_terminal_persistence.py+++ b/tests/hermes_cli/test_web_host_terminal_persistence.py@@ -10,6 +10,7 @@ from starlette.websockets import WebSocketDisconnectfrom hermes_cli import web_host_terminal, web_server, web_server_chatfrom hermes_cli.web_routers.webapp import router+from hermes_cli.web_session_sockets import HOST_TERMINAL_SOCKETfrom tests.waiting import async_wait_until@@ -35,7 +36,10 @@ def host_app(tmp_path, monkeypatch):def url(extra=""):- return f"ws://localhost/api/host-terminal?token={web_server._SESSION_TOKEN}{extra}"+ """A host-terminal URL with a fresh terminal ticket minted with this process's session token."""+ from hermes_cli.web_routers.webapp import SESSION_TOKEN_OWNER, mint_socket_ticket+ ticket = mint_socket_ticket(SESSION_TOKEN_OWNER, HOST_TERMINAL_SOCKET, session_token=web_server._SESSION_TOKEN)+ return f"ws://localhost/api/host-terminal?ticket={ticket}{extra}"def metadata(ws):@@ -317,8 +321,9 @@ def rejection(client, request, expected):def ticket_url(user="owner", extra=""):- from hermes_cli.dashboard_auth.ws_tickets import mint_ticket- ticket = mint_ticket(user_id=user, provider="test-provider")+ """A host-terminal URL with a fresh terminal ticket for a signed-in *user*."""+ from hermes_cli.web_routers.webapp import mint_socket_ticket+ ticket = mint_socket_ticket({"user_id": user, "provider": "test-provider"}, HOST_TERMINAL_SOCKET)return f"ws://localhost/api/host-terminal?ticket={ticket}{extra}"diff --git a/tests/hermes_cli/test_webapp_gateway_ticket.py b/tests/hermes_cli/test_webapp_gateway_ticket.pyindex 09be05f1aab..5811ba01376 100644--- a/tests/hermes_cli/test_webapp_gateway_ticket.py+++ b/tests/hermes_cli/test_webapp_gateway_ticket.py@@ -9,6 +9,8 @@ from types import SimpleNamespaceimport pytestfrom fastapi.testclient import TestClient+from hermes_cli.web_session_sockets import GATEWAY_SOCKET+_TOKEN = "a" * 43@@ -48,12 +50,12 @@ def test_loopback_ticket_names_the_session_token_owner_and_is_spent_once(webapp)body = minted.json()assert set(body) == {"ticket", "ttl_seconds"} and body["ttl_seconds"] > 0first = _socket(body["ticket"])- assert chat._ws_auth_ok(first) is True+ assert chat._ws_auth_ok(first, socket=GATEWAY_SOCKET) is True# The same identity ``chat_ws.gateway_ws`` gives a ``?token=`` socket, and only the public protocol.assert first._hermes_auth_identity == {"user_id": "legacy-token-owner", "provider": "session-token"}assert first._hermes_ws_subprotocol == chat._GATEWAY_WS_PROTOCOLassert not hasattr(first, "_hermes_gateway_home")- assert chat._ws_auth_ok(_socket(body["ticket"])) is False+ assert chat._ws_auth_ok(_socket(body["ticket"]), socket=GATEWAY_SOCKET) is Falsedef test_a_missing_profile_is_refused_before_a_ticket_exists(webapp):diff --git a/tests/hermes_cli/test_webapp_sign_out_sockets.py b/tests/hermes_cli/test_webapp_sign_out_sockets.pynew file mode 100644index 00000000000..8b7cdc11995--- /dev/null+++ b/tests/hermes_cli/test_webapp_sign_out_sockets.py@@ -0,0 +1,130 @@+"""Signing the Webapp out closes every socket the old browser credential opened.++``hermes webapp --sign-out`` (control verb ``webapp-sign-out``) replaces the session token and closes+the live sockets that token authenticated, directly or through a ticket minted with it: each tab's+host terminal and event stream close at once with code 4401, and the media links it minted stop+streaming. A socket opened with another credential stays connected. The verb runs on a+control-socket worker thread, not on the sockets' event loops.+"""+import json+from types import SimpleNamespace++import anyio+import pytest+from starlette.testclient import TestClient++from tests.hermes_cli.test_web_host_terminal_persistence import metadata+from tests.hermes_cli.test_webapp_socket_tickets import _TOKEN, _mint, serve_webapp+++def _next_message(ws, seconds=5.0):+ """The next frame the server sent *ws*, or None when none arrives within *seconds*."""+ async def receive():+ with anyio.move_on_after(seconds):+ return await ws._send_rx.receive()+ return None+ return ws.portal.call(receive)+++def _close_code(ws, seconds=5.0):+ """The code the server closed *ws* with, or None while it stays open."""+ while (message := _next_message(ws, seconds)) is not None:+ if message["type"] == "websocket.close":+ return message["code"]+ return None+++def webapp(tmp_path, monkeypatch):+ return serve_webapp(tmp_path, monkeypatch)+++def sign_out(webapp, tmp_path):+ """The ``webapp-sign-out`` verb of a gateway serving *webapp*, asked over its control socket."""+ from gateway.control_socket import GatewayControlServer+ from gateway.webapp_listener import TOKEN_PATH, register_control_verbs++ server = webapp.server+ home = tmp_path / ".hermes"+ runner = SimpleNamespace(+ session_control_server=GatewayControlServer(home),+ webapp_status={"state": "serving", "url": "http://localhost:9120", "reason": None},+ session_api=SimpleNamespace(app=SimpleNamespace(web=server)))+ register_control_verbs(runner, home)++ def ask():+ raw = json.dumps({"protocol": 1, "verb": "webapp-sign-out", "id": 1, "params": {}}).encode()+ answer = json.loads(runner.session_control_server.handle_request_line(raw, "same-user"))+ assert answer["ok"], answer+ assert (home / TOKEN_PATH).read_text(encoding="utf-8").strip() == server._SESSION_TOKEN != _TOKEN+ return answer["result"]+ return ask+++def test_signing_out_closes_the_terminal_and_streams_the_session_token_opened(webapp, sign_out):+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket++ client, host = webapp.client, webapp.host+ other = 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, \+ 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)+ assert _close_code(shell, 0.2) is None and _close_code(events, 0.2) is None+ assert sign_out() == {"signed_out": True}+ assert _close_code(shell) == 4401+ assert _close_code(events) == 4401+ assert _close_code(kept, 0.5) is None+ # The shell itself outlives its viewer, as after any disconnect, until its retention ends.+ assert len(webapp.shells) == 1 and webapp.shells[0].is_alive()+++def test_signing_out_with_no_open_tabs_still_replaces_the_credential(webapp, sign_out):+ client = webapp.client+ assert sign_out() == {"signed_out": True}+ assert client.post("/api/webapp/gateway-ticket", headers={"X-Hermes-Session-Token": _TOKEN}).status_code == 401+++def test_signing_out_ends_the_media_links_the_session_token_minted(webapp, sign_out, tmp_path, monkeypatch):+ """A media element's stream link is reusable for an hour; after sign-out it streams nothing."""+ client = webapp.client+ root = tmp_path / "files"+ root.mkdir()+ (root / "clip.mp4").write_bytes(b"hello")+ monkeypatch.setenv("HERMES_DASHBOARD_FILES_ROOT", str(root))+ minted = client.post("/api/files/ticket", json={"route": "stream", "path": str(root / "clip.mp4")},+ headers={"X-Hermes-Session-Token": _TOKEN})+ assert minted.status_code == 200, minted.text+ stream = {"path": str(root / "clip.mp4"), "ticket": minted.json()["ticket"]}+ assert client.get("/api/files/stream", params=stream).content == b"hello"+ sign_out()+ assert client.get("/api/files/stream", params=stream).status_code == 401+++def test_a_socket_admitted_while_the_token_is_replaced_closes_at_once(monkeypatch):+ """The gate checked the old token, then sign-out replaced it and closed the sockets it knew of+ before this one was tracked: tracking it closes it."""+ import asyncio++ from hermes_cli import web_server, web_session_sockets++ closed = []++ class Socket:+ def __init__(self):+ self.ended = asyncio.Event()++ async def close(self, code, reason):+ closed.append((code, reason))+ self.ended.set()++ async def admit():+ socket = Socket()+ web_session_sockets.track(socket, web_session_sockets.token_digest(_TOKEN))+ await asyncio.wait_for(socket.ended.wait(), timeout=5)++ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)+ asyncio.run(admit())+ assert closed == [(4401, "Signed out")]diff --git a/tests/hermes_cli/test_webapp_socket_tickets.py b/tests/hermes_cli/test_webapp_socket_tickets.pynew file mode 100644index 00000000000..168a56fedd4--- /dev/null+++ b/tests/hermes_cli/test_webapp_socket_tickets.py@@ -0,0 +1,156 @@+"""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``) and+``POST /api/webapp/terminal-ticket`` for the host terminal (``/api/host-terminal``). A host shell opens+only with a terminal ticket, a chat ticket opens no host shell, a terminal ticket opens no chat socket,+and a ticket minted with a session token that has since been replaced opens nothing.+"""+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from starlette.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from tests.hermes_cli.test_web_host_terminal_persistence import IdleBridge, metadata++_TOKEN = "a" * 43+_SESSION = {"X-Hermes-Session-Token": _TOKEN}+++def serve_webapp(tmp_path, monkeypatch):+ """The loopback Webapp: ``web_server.app`` mints tickets, a small app serves the host terminal,+ and ``shells`` lists the idle stand-ins it spawns for host shells."""+ from hermes_cli import web_host_terminal, web_server, web_server_chat+ from hermes_cli.web_host_terminal_sessions import host_terminal_lifespan+ from hermes_cli.web_routers.webapp import router++ home = tmp_path / ".hermes"+ home.mkdir()+ (home / "config.yaml").write_text("{}", encoding="utf-8")+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)+ monkeypatch.setattr(web_server.app.state, "bound_host", "localhost", raising=False)+ monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", _TOKEN)+ monkeypatch.setattr(web_server, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True)+ monkeypatch.setattr(web_host_terminal, "shell_spec", lambda: (["/bin/sh", "-i"], "sh"))+ shells = []++ def spawn(*_args, **_kwargs):+ shells.append(IdleBridge())+ return shells[-1]++ monkeypatch.setattr(web_server_chat.PtyBridge, "spawn", spawn)+ host = FastAPI(lifespan=host_terminal_lifespan)+ host.include_router(router)+ return SimpleNamespace(server=web_server, client=TestClient(web_server.app, base_url="http://localhost"),+ host=host, shells=shells)+++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)+ 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"]+++def _refused(client, url, code=4401, **kwargs):+ with pytest.raises(WebSocketDisconnect) as closed:+ with client.websocket_connect(url, **kwargs) as ws:+ ws.receive_text()+ assert closed.value.code == code+++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")+ with TestClient(host) as shells:+ with shells.websocket_connect(f"ws://localhost/api/host-terminal?ticket={ticket}") as ws:+ assert metadata(ws)["terminalId"]+ _refused(shells, f"ws://localhost/api/host-terminal?ticket={ticket}")+ assert len(webapp.shells) == 1+++def test_the_host_terminal_refuses_the_session_token_and_every_other_ticket(webapp):+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket++ client, host = webapp.client, webapp.host+ others = [_mint(client, "gateway"), mint_ticket(user_id="legacy-token-owner", provider="session-token")]+ with TestClient(host) as shells:+ _refused(shells, f"ws://localhost/api/host-terminal?token={_TOKEN}")+ for ticket in others:+ _refused(shells, f"ws://localhost/api/host-terminal?ticket={ticket}")+ protocols = ["hermes-gateway-v1", f"hermes-gateway-ticket.{_mint(client, 'gateway')}"]+ _refused(shells, "ws://localhost/api/host-terminal", subprotocols=protocols)+ assert webapp.shells == []+++def 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')}"]+ _refused(client, "ws://localhost/api/ws?native_dial=browser", subprotocols=protocols)+ _refused(client, f"ws://localhost/api/ws?ticket={_mint(client, '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")+ monkeypatch.setattr(server, "_SESSION_TOKEN", "b" * 43)+ with TestClient(host) as shells:+ _refused(shells, f"ws://localhost/api/host-terminal?ticket={terminal}")+ _refused(client, f"ws://localhost/api/ws?ticket={chat}")+ assert webapp.shells == []++[email protected]("surface", ["dashboard", "serve"])+def test_other_surfaces_do_not_mint_terminal_tickets(webapp, monkeypatch, surface):+ server, client = webapp.server, webapp.client+ monkeypatch.setattr(server.app.state, "ui_surface", surface)+ assert client.post("/api/webapp/terminal-ticket", headers=_SESSION).status_code == 404+++def test_a_signed_in_browser_opens_its_host_shell_with_a_terminal_ticket(webapp, monkeypatch):+ """Wildcard host: the dashboard's cookie sign-in mints the ticket, and the shell is that login's."""+ from hermes_cli.dashboard_auth import clear_providers, register_provider+ from hermes_cli.dashboard_auth.ws_tickets import _reset_for_tests+ from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+ from tests.hermes_cli.test_dashboard_auth_ws_auth import _logged_in++ server, host = webapp.server, webapp.host+ _reset_for_tests()+ clear_providers()+ register_provider(StubAuthProvider())+ monkeypatch.setattr(server.app.state, "bound_host", "fly-app.fly.dev")+ monkeypatch.setattr(server.app.state, "bound_port", 443, raising=False)+ 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,+ 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={})+ 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="+ with shells.websocket_connect(url + ticket) as ws:+ shell = metadata(ws)["terminalId"]+ assert host.state.host_terminals.owners[shell].identity[0] == "stub"+ _refused(shells, url + generic)+ assert len(webapp.shells) == 1+ finally:+ clear_providers()+ _reset_for_tests()