The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(gateway): the session listener serves local clients without importing the dashboard app
Teknium276da15e93ca
diff --git a/gateway/run_api.py b/gateway/run_api.pyindex ffdd9566123..5d1f9bf955e 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -1,15 +1,30 @@-"""Compose the existing complete HTTP/WS surface into the gateway event loop.+"""The gateway's local HTTP/WS listener: the native session WebSocket plus the dashboard API.The caller initializes session authority before starting this listener and ownsall runtime services and signals. This module owns only HTTP resources; it doesnot bootstrap an agent, scheduler, hosted room, or a second gateway.++The native session WebSocket (ticketed ``/api/ws`` — every local CLI/TUI/Desktop session) is served+without the dashboard app: importing ``hermes_cli.web_server`` (about 690 routes, ~0.6 s) before the+listener bound stalled every cold start and the control socket's identify. The dashboard is mounted+on its first request (imported off the event loop) or warmed after READY for a supervised gateway+(``warm_gateway_dashboard``); a gated listener (non-loopback bind or ``dashboard.public_url``) and a+process that already imported it mount it before the listener starts, exactly as before."""import asynciofrom dataclasses import dataclass+import loggingimport socket+import sys+import typesfrom typing import Any+logger = logging.getLogger(__name__)++# One listener per process: the dashboard routers share one process-local app.+_ACTIVE_RUNNER: Any = None+@dataclassclass GatewayAPIHandle:@@ -20,56 +35,152 @@ class GatewayAPIHandle:socket: socket.socket+class GatewayDashboardMount:+ """ASGI app that imports and mounts the dashboard (``hermes_cli.web_server.app``) on first use.++ ``state`` is the listener's boundary state (``bound_host``, ``bound_port``, ``auth_required``,+ ``trusted_public_hosts``, ``gateway_runner``, ``session_authority``) — what the native WebSocket+ path checks, mirrored onto the dashboard app state once it is mounted.+ """++ def __init__(self, runner, state):+ self.runner, self._state = runner, state+ self.web = None+ self._lock: asyncio.Lock | None = None+ self._lifespan = None+ self._closed = False++ @property+ def loaded(self) -> bool:+ return self.web is not None++ @property+ def state(self):+ """Boundary state: the dashboard app's own state once mounted (operators and tests may+ change it there), the listener's pre-mount snapshot before."""+ return self.web.app.state if self.web is not None else self._state++ def _bind_state(self, web) -> None:+ # Local clients authenticate with tickets minted on the owner-only control socket. The SPA+ # session token is a bearer credential any loopback peer (any OS user) could read from+ # GET /, so the gateway-hosted listener never publishes it.+ web.app.state.withhold_session_token = True+ web._configure_auth_gate(self._state.bound_host, False, None, None)+ web.app.state.gateway_runner = self.runner+ web.app.state.session_authority = getattr(self.runner, "session_authority", None)+ web.app.state.bound_host = self._state.bound_host+ web.app.state.bound_port = self._state.bound_port++ def _unbind_state(self) -> None:+ if self.web is not None:+ self.web.app.state.gateway_runner = None+ self.web.app.state.session_authority = None+ self.web.app.state.withhold_session_token = False++ async def ensure(self):+ """Import (off the loop), bind and start the dashboard app once; returns ``web_server``."""+ if self.web is not None:+ return self.web+ if self._lock is None:+ self._lock = asyncio.Lock()+ async with self._lock:+ if self.web is not None:+ return self.web+ if self._closed:+ raise RuntimeError("gateway API stopped")+ import importlib+ web = sys.modules.get("hermes_cli.web_server") or await asyncio.to_thread(+ importlib.import_module, "hermes_cli.web_server")+ if self._closed: # the listener stopped while the import ran+ raise RuntimeError("gateway API stopped")+ if getattr(web.app.state, "gateway_runner", None) not in (None, self.runner):+ raise RuntimeError("gateway API already started")+ self._bind_state(web)+ lifespan = web.app.router.lifespan_context(web.app)+ try:+ await lifespan.__aenter__()+ except BaseException:+ self.web = web+ self._unbind_state()+ self.web = None+ raise+ self.web, self._lifespan = web, lifespan+ return web++ async def close(self) -> None:+ self._closed = True+ lifespan, self._lifespan = self._lifespan, None+ try:+ if lifespan is not None:+ await lifespan.__aexit__(None, None, None)+ finally:+ self._unbind_state()++ async def __call__(self, scope, receive, send):+ if scope["type"] not in {"http", "websocket"}:+ return+ try:+ web = await self.ensure()+ except Exception:+ logger.exception("Gateway dashboard API failed to load")+ if scope["type"] == "websocket":+ await send({"type": "websocket.close", "code": 1011})+ else:+ from starlette.responses import JSONResponse+ await JSONResponse({"error": "dashboard_unavailable"}, status_code=500)(scope, receive, send)+ return+ await web.app(scope, receive, send)++async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -> GatewayAPIHandle:- from hermes_cli import web_server as web+ global _ACTIVE_RUNNER+ from hermes_cli.web_server_boundary import _dashboard_public_hosts, listener_auth_required+ from hermes_cli.web_server_lifecycle import build_listener_server# Existing routers/auth helpers share one process-local app. Never rebind it# underneath another listener. Each authority is bound to its own profile DB.- if getattr(web.app.state, "gateway_runner", None) is not None:+ loaded_web = sys.modules.get("hermes_cli.web_server")+ if _ACTIVE_RUNNER is not None or (+ loaded_web is not None and getattr(loaded_web.app.state, "gateway_runner", None) is not None):raise RuntimeError("gateway API already started")- web._configure_auth_gate(host, False, None, None)- # Local clients authenticate with tickets minted on the owner-only control socket. The SPA- # session token is a bearer credential any loopback peer (any OS user) could read from- # GET /, so the gateway-hosted listener never publishes it.- web.app.state.withhold_session_token = True- config, server = web._build_uvicorn_server(host, port)- config.timeout_graceful_shutdown = 5+ trusted = _dashboard_public_hosts()+ state = types.SimpleNamespace(+ bound_host=host, bound_port=None, auth_required=listener_auth_required(host, trusted),+ trusted_public_hosts=trusted, gateway_runner=runner,+ session_authority=getattr(runner, "session_authority", None))+ mount = GatewayDashboardMount(runner, state)+ # Lifespan off: the dashboard's own lifespan runs when it is mounted (GatewayDashboardMount).+ config, server = build_listener_server(mount, host, port, auth_required=state.auth_required,+ timeout_graceful_shutdown=5, lifespan="off")family, kind, proto, _, address = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM,)[0]listener = socket.socket(family, kind, proto)+ _ACTIVE_RUNNER = runnertry:listener.bind(address)listener.setblocking(False)+ state.bound_port = listener.getsockname()[1]# Loading the ASGI graph may fail too; it owns the same bound socket.if not config.loaded:config.load()- config.loaded_app = GatewayRuntimeAPI(config.loaded_app, runner, web.app)- except BaseException:- listener.close()- raise-- web.app.state.gateway_runner = runner- web.app.state.session_authority = getattr(runner, "session_authority", None)- web.app.state.bound_host = host- web.app.state.bound_port = listener.getsockname()[1]- try:- if not config.loaded:- config.load()+ config.loaded_app = GatewayRuntimeAPI(config.loaded_app, runner, mount)+ # A gated listener needs the dashboard's auth providers (and refuses to start without one);+ # an already-imported dashboard costs nothing to mount now.+ if state.auth_required or loaded_web is not None:+ await mount.ensure()server.lifespan = config.lifespan_class(config)await server.startup(sockets=[listener])if not server.started or server.should_exit:raise RuntimeError("gateway API lifespan startup failed")except BaseException:listener.close()- web.app.state.gateway_runner = None- web.app.state.session_authority = None- web.app.state.withhold_session_token = False- if hasattr(server, "lifespan") and not server.lifespan.should_exit:- await server.lifespan.shutdown()+ _ACTIVE_RUNNER = None+ await mount.close()raiseasync def serve():+ global _ACTIVE_RUNNERtry:await server.main_loop()finally:@@ -77,18 +188,38 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -await server.shutdown(sockets=[listener])finally:listener.close()- web.app.state.gateway_runner = None- web.app.state.session_authority = None- web.app.state.withhold_session_token = False+ try:+ await mount.close()+ finally:+ _ACTIVE_RUNNER = Nonetask = asyncio.create_task(serve(), name="gateway-api")origin_host = f"[{host}]" if ":" in host else hostreturn GatewayAPIHandle(- api_origin=f"http://{origin_host}:{web.app.state.bound_port}",- server=server, task=task, app=web.app, socket=listener,+ api_origin=f"http://{origin_host}:{state.bound_port}",+ server=server, task=task, app=mount, socket=listener,)+def warm_gateway_dashboard(runner) -> None:+ """Mount the dashboard in the background once the gateway is READY (supervised gateways, whose+ clients — Desktop, the dashboard SPA — call its routes right away). Never raises."""+ handle = getattr(runner, "session_api", None)+ mount = getattr(handle, "app", None)+ if not isinstance(mount, GatewayDashboardMount) or mount.loaded:+ return++ async def _warm():+ try:+ await mount.ensure()+ except Exception:+ if not mount._closed:+ logger.warning("Gateway dashboard API warm-up failed; it loads on first request", exc_info=True)++ runner._gateway_dashboard_warmup = asyncio.get_running_loop().create_task(+ _warm(), name="gateway-dashboard-warmup")++async def stop_gateway_api(handle: GatewayAPIHandle) -> None:"""Drain sockets without stopping the session authority or taking signals."""handle.server.should_exit = True@@ -97,11 +228,20 @@ async def stop_gateway_api(handle: GatewayAPIHandle) -> None:await asyncio.shield(asyncio.gather(handle.task, return_exceptions=True))+def _embedded_chat_enabled() -> bool:+ """``web_server._DASHBOARD_EMBEDDED_CHAT_ENABLED`` without importing the dashboard (always True+ unless a loaded dashboard says otherwise)."""+ web = sys.modules.get("hermes_cli.web_server")+ return True if web is None else bool(getattr(web, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True))++class GatewayRuntimeAPI:"""Redeem private local tickets at the existing WS subprotocol boundary.Other credentials and HTTP routes retain the complete dashboard gate. Localbootstrap never grants an exposure/worker ticket interactive permissions.+ *web_app* is the dashboard mount (or any object whose ``state`` carries the listener's+ ``bound_host`` / ``auth_required`` / ``trusted_public_hosts``)."""def __init__(self, app, runner, web_app):self.app, self.runner, self.web_app = app, runner, web_app@@ -139,9 +279,10 @@ class GatewayRuntimeAPI:receive = receive_admittedfrom starlette.websockets import WebSocket- from hermes_cli.web_server_chat import (- _gateway_ws_ticket_from_subprotocol, _ws_request_is_allowed,+ from hermes_cli.web_server_boundary import (+ _gateway_ws_ticket_from_subprotocol, ws_client_reason, ws_host_origin_reason,)+ state = getattr(self.web_app, 'state', None)scope['app'] = self.web_appws = WebSocket(scope, receive, send)ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)@@ -150,9 +291,9 @@ class GatewayRuntimeAPI:await ws.close(code=1013)returnreturn await self.app(scope, receive, send)- from hermes_cli import web_server as web- if (reason != 'ok' or not web._DASHBOARD_EMBEDDED_CHAT_ENABLED- or not _ws_request_is_allowed(ws) or ws.headers.get('origin')+ if (reason != 'ok' or not _embedded_chat_enabled()+ or ws_host_origin_reason(ws, state) is not None or ws_client_reason(ws, state) is not None+ or ws.headers.get('origin')or not ws.client or ws.client.host not in {'127.0.0.1', '::1'}):await ws.close(code=4403)returndiff --git a/gateway/run_bootstrap.py b/gateway/run_bootstrap.pyindex 7d245b15223..9487af7cf5b 100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@ -798,6 +798,12 @@ async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool =if idle_exit:from gateway.run_idle_exit import arm_unmanaged_idle_exitarm_unmanaged_idle_exit(runner)+ else:+ # A supervised/explicit gateway serves Desktop and the dashboard SPA, which call the+ # dashboard routes right away: mount them now, after READY. A client's own idle-exit+ # gateway (chat -q, TUI) only uses the native WebSocket; it mounts on first request.+ from gateway.run_api import warm_gateway_dashboard+ warm_gateway_dashboard(runner)from gateway.run_runtime import wait_gateway_runtimetry:diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex f30b4a6a756..f4303048ee5 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -282,10 +282,6 @@ def _ssh_runtime_intact() -> bool:# share one testable seam._DASHBOARD_EMBEDDED_CHAT_ENABLED = True-# Desktop file.attach sends a whole base64 data URL in one JSON-RPC frame;-# uvicorn's 16 MiB default rejects files under the 256 MiB raw attach cap.-_DESKTOP_ATTACHMENT_WS_MAX_BYTES = 384 * 1024 * 1024-# Endpoints that do NOT require the session token; everything else under /api/# is gated below. Shared with the OAuth gate so the two allowlists cannot# drift (/api/status once 401'd under the OAuth gate, breaking the portal probe).@@ -340,36 +336,16 @@ def _require_token(request: Request) -> None:raise HTTPException(status_code=401, detail="Unauthorized")-# Accepted Host values for loopback binds. DNS rebinding TTL-flips an attacker-# hostname to 127.0.0.1 so the browser treats it as same-origin; validating Host-# at the app layer rejects it. See GHSA-ppp5-vxwm-4cf7.-_LOOPBACK_HOST_VALUES: frozenset = frozenset({"localhost", "127.0.0.1", "::1"})---def _dashboard_public_hosts() -> frozenset[str]:- """Return the exact hostname declared by ``dashboard.public_url``.-- One source of truth for OAuth redirects, Host and WS Origin validation.- Malformed or unset values fail closed as an empty set.- """- from hermes_cli.dashboard_auth.prefix import resolve_public_url-- public_url = resolve_public_url()- try:- hostname = urllib.parse.urlparse(public_url).hostname if public_url else None- except ValueError:- hostname = None- return frozenset({hostname.lower()}) if hostname else frozenset()---def should_require_auth(host: str, allow_public: bool = False) -> bool:- """True iff the auth gate must be active: any non-loopback bind.-- RFC1918 / CGNAT / link-local are deliberately PUBLIC — a hostile LAN device- is the threat model. ``allow_public`` (legacy ``--insecure``) is accepted for- old launch scripts but IGNORED since the June 2026 hermes-0day campaign.- """- return host not in _LOOPBACK_HOST_VALUES+from hermes_cli.web_server_boundary import ( # re-exported: web_server.<name> stays the public seam+ _DESKTOP_ATTACHMENT_WS_MAX_BYTES,+ _LOOPBACK_HOST_VALUES,+ _dashboard_public_hosts,+ _desktop_loopback_auth_exempt,+ _host_header_hostname,+ _is_accepted_host,+ public_hosts_engage_gate,+ should_require_auth,+)def should_require_dashboard_auth(@@ -383,90 +359,7 @@ def should_require_dashboard_auth("""if trusted_public_hosts is None:trusted_public_hosts = _dashboard_public_hosts()- return should_require_auth(host) or any(h not in _LOOPBACK_HOST_VALUES for h in trusted_public_hosts)---def _desktop_loopback_auth_exempt(- host: str,- ssh_session_token: Optional[str] = None,- ssh_owner_nonce: Optional[str] = None,-) -> bool:- """True for a Desktop-owned loopback backend (#96490).-- A non-loopback ``dashboard.public_url`` would otherwise engage the- ticket-only gate for the private loopback backends Desktop spawns, whose- per-spawn session token the gate's WS path refuses — Desktop could not boot.- The public dashboard is a separate non-loopback process that stays gated, so- this never opens the public surface. Requires ALL of: loopback bind,- ``HERMES_DESKTOP=1``, and an operator-minted credential (env token, SSH- session token, or owner nonce).- """- return (- host in _LOOPBACK_HOST_VALUES- and os.environ.get("HERMES_DESKTOP") == "1"- and bool(os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN") or ssh_session_token or ssh_owner_nonce)- )---def _host_header_hostname(host_header: str) -> str:- """Return a normalized hostname from a valid HTTP Host authority.-- Host headers are authorities, not full URLs. Reject ambiguous ports,- malformed IPv6 brackets, and URL syntax so validation always fails closed.- """- value = (host_header or "").strip()- if not value or "://" in value or any(c in value for c in '"\'<> \n\r\t/?#@'):- return ""-- if value.startswith("["):- close = value.find("]")- if close == -1:- return ""- hostname = value[1:close]- # Bracket notation is reserved for IPv6 literals.- if ":" not in hostname:- return ""- suffix = value[close + 1:]- if suffix and not re.fullmatch(r":\d+", suffix):- return ""- return hostname.lower()-- # Unbracketed IPv6 authorities are ambiguous with a port separator.- if value.count(":") > 1:- return ""- if ":" in value:- hostname, port = value.rsplit(":", 1)- if not hostname or not port.isdigit():- return ""- return hostname.lower()- return value.lower()---def _is_accepted_host(- host_header: str,- bound_host: str,- trusted_public_hosts: frozenset[str] = frozenset(),-) -> bool:- """True if the Host header targets the interface we bound to.-- Accepts:- - Exact bound host (with or without port suffix)- - Loopback aliases when bound to loopback- - Exact operator-declared public hosts (with or without port suffix)- - Any host when bound to 0.0.0.0 (explicit opt-in to non-loopback,- no protection possible at this layer)- """- host_only = _host_header_hostname(host_header)- if not host_only:- return False- # All-interfaces bind: no Host-layer defence is possible; rely on operator- # network controls.- if host_only in trusted_public_hosts or bound_host in {"0.0.0.0", "::"}:- return True- bound_lc = bound_host.lower()- if bound_lc in _LOOPBACK_HOST_VALUES:- return host_only in _LOOPBACK_HOST_VALUES- return host_only == bound_lc+ return should_require_auth(host) or public_hosts_engage_gate(trusted_public_hosts)@app.middleware("http")diff --git a/hermes_cli/web_server_boundary.py b/hermes_cli/web_server_boundary.pynew file mode 100644index 00000000000..80a1eea39e4--- /dev/null+++ b/hermes_cli/web_server_boundary.py@@ -0,0 +1,218 @@+"""Listener boundary primitives shared by the dashboard app and the gateway's session listener:+Host validation, the auth-gate decision and the native WebSocket ticket subprotocol.++Import-light on purpose (no FastAPI): ``gateway.run_api`` serves the native session WebSocket+without importing the dashboard app (about 690 routes, ~0.6 s), and must apply the same+DNS-rebinding Host check and gate decision. ``hermes_cli.web_server`` and+``hermes_cli.web_server_chat`` re-export these names, so ``web_server.<name>`` keeps working.+"""++import os+import re+import urllib.parse+from typing import Optional++# Accepted Host values for loopback binds. DNS rebinding TTL-flips an attacker+# hostname to 127.0.0.1 so the browser treats it as same-origin; validating Host+# at the app layer rejects it. See GHSA-ppp5-vxwm-4cf7.+_LOOPBACK_HOST_VALUES: frozenset = frozenset({"localhost", "127.0.0.1", "::1"})++# Starlette's TestClient reports the peer as "testclient"; treat it as+# loopback so tests don't need to rewrite request scope.+_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost", "testclient"})++# Desktop file.attach sends a whole base64 data URL in one JSON-RPC frame;+# uvicorn's 16 MiB default rejects files under the 256 MiB raw attach cap.+_DESKTOP_ATTACHMENT_WS_MAX_BYTES = 384 * 1024 * 1024+++def _dashboard_public_hosts() -> frozenset[str]:+ """Return the exact hostname declared by ``dashboard.public_url``.++ One source of truth for OAuth redirects, Host and WS Origin validation.+ Malformed or unset values fail closed as an empty set.+ """+ from hermes_cli.dashboard_auth.prefix import resolve_public_url++ public_url = resolve_public_url()+ try:+ hostname = urllib.parse.urlparse(public_url).hostname if public_url else None+ except ValueError:+ hostname = None+ return frozenset({hostname.lower()}) if hostname else frozenset()+++def _host_header_hostname(host_header: str) -> str:+ """Return a normalized hostname from a valid HTTP Host authority.++ Host headers are authorities, not full URLs. Reject ambiguous ports,+ malformed IPv6 brackets, and URL syntax so validation always fails closed.+ """+ value = (host_header or "").strip()+ if not value or "://" in value or any(c in value for c in '"\'<> \n\r\t/?#@'):+ return ""++ if value.startswith("["):+ close = value.find("]")+ if close == -1:+ return ""+ hostname = value[1:close]+ # Bracket notation is reserved for IPv6 literals.+ if ":" not in hostname:+ return ""+ suffix = value[close + 1:]+ if suffix and not re.fullmatch(r":\d+", suffix):+ return ""+ return hostname.lower()++ # Unbracketed IPv6 authorities are ambiguous with a port separator.+ if value.count(":") > 1:+ return ""+ if ":" in value:+ hostname, port = value.rsplit(":", 1)+ if not hostname or not port.isdigit():+ return ""+ return hostname.lower()+ return value.lower()+++def _is_accepted_host(+ host_header: str,+ bound_host: str,+ trusted_public_hosts: frozenset[str] = frozenset(),+) -> bool:+ """True if the Host header targets the interface we bound to.++ Accepts:+ - Exact bound host (with or without port suffix)+ - Loopback aliases when bound to loopback+ - Exact operator-declared public hosts (with or without port suffix)+ - Any host when bound to 0.0.0.0 (explicit opt-in to non-loopback,+ no protection possible at this layer)+ """+ host_only = _host_header_hostname(host_header)+ if not host_only:+ return False+ # All-interfaces bind: no Host-layer defence is possible; rely on operator+ # network controls.+ if host_only in trusted_public_hosts or bound_host in {"0.0.0.0", "::"}:+ return True+ bound_lc = bound_host.lower()+ if bound_lc in _LOOPBACK_HOST_VALUES:+ return host_only in _LOOPBACK_HOST_VALUES+ return host_only == bound_lc+++def should_require_auth(host: str, allow_public: bool = False) -> bool:+ """True iff the auth gate must be active: any non-loopback bind.++ RFC1918 / CGNAT / link-local are deliberately PUBLIC — a hostile LAN device+ is the threat model. ``allow_public`` (legacy ``--insecure``) is accepted for+ old launch scripts but IGNORED since the June 2026 hermes-0day campaign.+ """+ return host not in _LOOPBACK_HOST_VALUES+++def public_hosts_engage_gate(trusted_public_hosts: frozenset[str]) -> bool:+ """A non-loopback ``dashboard.public_url`` host engages the auth gate even on a loopback bind."""+ return any(h not in _LOOPBACK_HOST_VALUES for h in trusted_public_hosts)+++def _desktop_loopback_auth_exempt(+ host: str,+ ssh_session_token: Optional[str] = None,+ ssh_owner_nonce: Optional[str] = None,+) -> bool:+ """True for a Desktop-owned loopback backend (#96490).++ A non-loopback ``dashboard.public_url`` would otherwise engage the+ ticket-only gate for the private loopback backends Desktop spawns, whose+ per-spawn session token the gate's WS path refuses — Desktop could not boot.+ The public dashboard is a separate non-loopback process that stays gated, so+ this never opens the public surface. Requires ALL of: loopback bind,+ ``HERMES_DESKTOP=1``, and an operator-minted credential (env token, SSH+ session token, or owner nonce).+ """+ return (+ host in _LOOPBACK_HOST_VALUES+ and os.environ.get("HERMES_DESKTOP") == "1"+ and bool(os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN") or ssh_session_token or ssh_owner_nonce)+ )+++def listener_auth_required(host: str, trusted_public_hosts: frozenset[str]) -> bool:+ """The ``app.state.auth_required`` value ``web_server._configure_auth_gate(host, False, None,+ None)`` resolves for a listener with no SSH credentials (the gateway's session listener)."""+ if _desktop_loopback_auth_exempt(host):+ return should_require_auth(host)+ return should_require_auth(host) or public_hosts_engage_gate(trusted_public_hosts)+++_GATEWAY_WS_PROTOCOL = "hermes-gateway-v1"+_GATEWAY_WS_TICKET_PROTOCOL_PREFIX = "hermes-gateway-ticket."+++def _gateway_ws_ticket_from_subprotocol(ws) -> tuple[str, str]:+ """Return ``(ticket, reason)`` from an unambiguous gateway protocol set."""+ raw = str(ws.headers.get("sec-websocket-protocol", "") or "")+ protocols = [value.strip() for value in raw.split(",") if value.strip()]+ ticket_protocols = [+ value for value in protocols if value.startswith(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX)]+ if not ticket_protocols:+ return "", "none"+ if _GATEWAY_WS_PROTOCOL not in protocols or len(ticket_protocols) != 1:+ return "", "invalid"+ ticket = ticket_protocols[0][len(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX):]+ return (ticket, "ok") if ticket else ("", "invalid")+++def ws_client_reason(ws, state) -> Optional[str]:+ """Rejection reason token for the WebSocket peer IP under listener *state*+ (``auth_required`` / ``bound_host``), or None when allowed.++ Loopback bind: only loopback peers (the legacy ``?token=`` is the only auth,+ LAN hosts must not get to guess it); an empty peer fails closed. Explicit+ non-loopback bind (``--insecure``) or gated mode: any peer — DNS-rebinding is+ blocked by :func:`ws_host_origin_reason`, and in gated mode+ ``ws.client.host`` is the X-Forwarded-For value anyway.+ """+ if getattr(state, "auth_required", False):+ return None+ bound_host = (getattr(state, "bound_host", "") or "").strip().lower()+ if bound_host and bound_host not in _LOOPBACK_HOSTS:+ return None+ client_host = ws.client.host if ws.client else ""+ if not client_host:+ return f"missing_or_empty_peer bound={bound_host or '?'}"+ if client_host in _LOOPBACK_HOSTS:+ return None+ return f"peer_not_loopback peer={client_host} bound={bound_host or '?'}"+++def ws_host_origin_reason(ws, state) -> Optional[str]:+ """``host_mismatch …`` / ``origin_mismatch …`` under listener *state*, or None when allowed.++ HTTP middleware does not run for WebSocket routes, so the DNS-rebinding+ Host check is repeated here; an Origin header, when present, must target the+ bound host. Non-web origins (packaged Electron: file://, null, app://) are+ trusted — the credential check is the real auth boundary there.+ """+ bound_host = getattr(state, "bound_host", None)+ if not bound_host:+ return None+ trusted_public_hosts = getattr(state, "trusted_public_hosts", frozenset())+ host_header = ws.headers.get("host", "")+ if not _is_accepted_host(host_header, bound_host, trusted_public_hosts):+ return f"host_mismatch host={host_header or '?'} bound={bound_host}"+ origin = ws.headers.get("origin", "")+ if not origin:+ return None+ try:+ parsed = urllib.parse.urlparse(origin)+ except ValueError: # malformed authority, e.g. "http://[::1" — fail closed+ parsed = None+ if parsed is not None and parsed.scheme not in {"http", "https"}:+ return None+ if parsed is None or not parsed.netloc or not _is_accepted_host(parsed.netloc, bound_host, trusted_public_hosts):+ return f"origin_mismatch origin={origin} bound={bound_host}"+ return Nonediff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex e6e32c0d756..b6a891d9bc3 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -131,32 +131,15 @@ async def _legacy_pump(ws: "WebSocket", bridge) -> None:await asyncio.to_thread(bridge.close)-# Starlette's TestClient reports the peer as "testclient"; treat it as-# loopback so tests don't need to rewrite request scope.-_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost", "testclient"})+from hermes_cli.web_server_boundary import _LOOPBACK_HOSTSdef _ws_client_reason(ws: "WebSocket") -> Optional[str]:- """Return a rejection reason token for the peer IP, or None when allowed.-- Loopback bind: only loopback peers (the legacy ``?token=`` is the only auth,- LAN hosts must not get to guess it); an empty peer fails closed. Explicit- non-loopback bind (``--insecure``) or gated mode: any peer — DNS-rebinding is- blocked by :func:`_ws_host_origin_reason`, and in gated mode- ``ws.client.host`` is the X-Forwarded-For value anyway.- """+ """Return a rejection reason token for the peer IP, or None when allowed+ (:func:`hermes_cli.web_server_boundary.ws_client_reason` on the dashboard app state)."""from hermes_cli.web_server import app- if getattr(app.state, "auth_required", False):- return None- bound_host = (getattr(app.state, "bound_host", "") or "").strip().lower()- if bound_host and bound_host not in _LOOPBACK_HOSTS:- return None- client_host = ws.client.host if ws.client else ""- if not client_host:- return f"missing_or_empty_peer bound={bound_host or '?'}"- if client_host in _LOOPBACK_HOSTS:- return None- return f"peer_not_loopback peer={client_host} bound={bound_host or '?'}"+ from hermes_cli.web_server_boundary import ws_client_reason+ return ws_client_reason(ws, app.state)def _ws_client_is_allowed(ws: "WebSocket") -> bool:@@ -165,33 +148,11 @@ def _ws_client_is_allowed(ws: "WebSocket") -> bool:def _ws_host_origin_reason(ws: "WebSocket") -> Optional[str]:- """Return ``host_mismatch …`` / ``origin_mismatch …``, or None when allowed.-- HTTP middleware does not run for WebSocket routes, so the DNS-rebinding- Host check is repeated here; an Origin header, when present, must target the- bound host. Non-web origins (packaged Electron: file://, null, app://) are- trusted — the credential check is the real auth boundary there.- """- from hermes_cli.web_server import _is_accepted_host, app- bound_host = getattr(app.state, "bound_host", None)- if not bound_host:- return None- trusted_public_hosts = getattr(app.state, "trusted_public_hosts", frozenset())- host_header = ws.headers.get("host", "")- if not _is_accepted_host(host_header, bound_host, trusted_public_hosts):- return f"host_mismatch host={host_header or '?'} bound={bound_host}"- origin = ws.headers.get("origin", "")- if not origin:- return None- try:- parsed = urllib.parse.urlparse(origin)- except ValueError: # malformed authority, e.g. "http://[::1" — fail closed- parsed = None- if parsed is not None and parsed.scheme not in {"http", "https"}:- return None- if parsed is None or not parsed.netloc or not _is_accepted_host(parsed.netloc, bound_host, trusted_public_hosts):- return f"origin_mismatch origin={origin} bound={bound_host}"- return None+ """Return ``host_mismatch …`` / ``origin_mismatch …``, or None when allowed+ (:func:`hermes_cli.web_server_boundary.ws_host_origin_reason` on the dashboard app state)."""+ from hermes_cli.web_server import app+ from hermes_cli.web_server_boundary import ws_host_origin_reason+ return ws_host_origin_reason(ws, app.state)def _ws_host_origin_is_allowed(ws: "WebSocket") -> bool:@@ -204,22 +165,11 @@ def _ws_request_is_allowed(ws: "WebSocket") -> bool:return _ws_host_origin_is_allowed(ws) and _ws_client_is_allowed(ws)-_GATEWAY_WS_PROTOCOL = "hermes-gateway-v1"-_GATEWAY_WS_TICKET_PROTOCOL_PREFIX = "hermes-gateway-ticket."---def _gateway_ws_ticket_from_subprotocol(ws: "WebSocket") -> tuple[str, str]:- """Return ``(ticket, reason)`` from an unambiguous gateway protocol set."""- raw = str(ws.headers.get("sec-websocket-protocol", "") or "")- protocols = [value.strip() for value in raw.split(",") if value.strip()]- ticket_protocols = [- value for value in protocols if value.startswith(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX)]- if not ticket_protocols:- return "", "none"- if _GATEWAY_WS_PROTOCOL not in protocols or len(ticket_protocols) != 1:- return "", "invalid"- ticket = ticket_protocols[0][len(_GATEWAY_WS_TICKET_PROTOCOL_PREFIX):]- return (ticket, "ok") if ticket else ("", "invalid")+from hermes_cli.web_server_boundary import (+ _GATEWAY_WS_PROTOCOL,+ _GATEWAY_WS_TICKET_PROTOCOL_PREFIX,+ _gateway_ws_ticket_from_subprotocol,+)def _ws_request_view(ws: "WebSocket") -> "Request":diff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex 12f9b19871a..d3b076593f5 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -517,3 +517,57 @@ def _dashboard_forwarded_allow_ips(dashboard_config: dict[str, Any]) -> list[str_log.info("Dashboard trusted proxies: %s", ", ".join(trusted))return trusted+++def build_listener_server(served_app, host: str, port: int, *, auth_required: bool,+ ws_ping: Optional[tuple[float, float]] = None,+ timeout_graceful_shutdown: Optional[float] = 3, lifespan: str = "auto"):+ """uvicorn ``Config`` + ``Server`` for a dashboard or gateway-session listener (FastAPI-free, so+ the gateway can build its session listener without importing the dashboard app).++ WS keepalive ping runs ON the agent event loop; a GIL-holding worker call can starve it for+ minutes, so uvicorn misses the pong and drops a healthy local socket (#53773/#48445/#50005).+ The ping only detects half-open connections (proxy 524, dropped tunnels), impossible on+ loopback where a dead client sends a real FIN/RST -> WebSocketDisconnect. So: no ping on+ loopback; non-loopback sits behind a Cloudflare Tunnel (~100s idle) and keeps a config-driven+ cadence (dashboard.ws_ping_interval/_timeout, #79635) defaulting to 20/20. *ws_ping* overrides+ both (SSH-isolated Desktop backends).+ """+ import uvicorn+ from hermes_cli.config import load_config+ from hermes_cli.web_server_boundary import _DESKTOP_ATTACHMENT_WS_MAX_BYTES, _LOOPBACK_HOST_VALUES++ try:+ dash_cfg = load_config().get("dashboard") or {}+ except Exception: # health: allow BLE001 -- same fail-open read as web_server._build_uvicorn_server: a broken config.yaml must not stop the listener+ dash_cfg = {}++ def _ws_ping_setting(key: str, default: float = 20.0) -> float:+ try:+ return float(dash_cfg.get(key, default))+ except (TypeError, ValueError):+ return default++ if ws_ping is None:+ ws_ping = (None, None) if host in _LOOPBACK_HOST_VALUES else (+ _ws_ping_setting("ws_ping_interval"), _ws_ping_setting("ws_ping_timeout"))+ config = uvicorn.Config(+ served_app, host=host, port=port, log_level="warning",+ # Off by default so _ws_client_is_allowed sees the real peer, not+ # X-Forwarded-For. Gated mode runs behind a TLS terminator and needs+ # X-Forwarded-Proto for cookie Secure flags.+ proxy_headers=auth_required,+ # Loopback-only unless the operator trusts a bounded upstream proxy, so+ # spoofed X-Forwarded-* from arbitrary callers is never honoured.+ forwarded_allow_ips=_dashboard_forwarded_allow_ips(dash_cfg),+ ws_ping_interval=ws_ping[0],+ ws_ping_timeout=ws_ping[1],+ ws_max_size=_DESKTOP_ATTACHMENT_WS_MAX_BYTES,+ # Desktop sends a single SIGTERM and escalates to SIGKILL ~5s later;+ # uvicorn's default (None) waits on lingering ASGI tasks forever, so a+ # mid-turn request orphans the backend past that budget (#76244). 3s+ # leaves room for lifespan shutdown + cron_stop before the kill.+ timeout_graceful_shutdown=timeout_graceful_shutdown,+ lifespan=lifespan,+ )+ return config, uvicorn.Server(config)diff --git a/tests/gateway/test_session_listener_lazy_dashboard.py b/tests/gateway/test_session_listener_lazy_dashboard.pynew file mode 100644index 00000000000..1c7a2d0f305--- /dev/null+++ b/tests/gateway/test_session_listener_lazy_dashboard.py@@ -0,0 +1,95 @@+"""The gateway's session listener serves local sessions without importing the dashboard app.++``start_gateway_api`` imported ``hermes_cli.web_server`` (about 690 routes, ~0.6 s on the event loop)+before the listener bound, stalling every cold start and the control socket's identify. The native+ticketed ``/api/ws`` must be served — with the same Host and peer boundary — before the dashboard is+imported, and the dashboard routes must still answer on the same origin (mounted on first request).+"""++import json+import os+import subprocess+import sys+import textwrap+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]++_PROBE = textwrap.dedent("""+ import asyncio, json, sys, types+ import httpx+ from websockets.asyncio.client import connect++ async def main():+ from gateway.run_api import start_gateway_api, stop_gateway_api+ from gateway.runtime_bootstrap import TicketStore+ import tui_gateway.ws++ async def fake_handle_ws(ws, **kwargs):+ await ws.accept(subprotocol="hermes-gateway-v1")+ await ws.send_json({"native": True, "dashboard_loaded": "hermes_cli.web_server" in sys.modules})+ await ws.close()+ tui_gateway.ws.handle_ws = fake_handle_ws++ home = sys.argv[1]+ tickets = TicketStore("owner", [home])+ authority = types.SimpleNamespace(db=types.SimpleNamespace(db_path=home + "/state.db"), profile_id=home)+ runner = types.SimpleNamespace(_draining=False, session_runtime_descriptor={"state": "ready"},+ session_authority=authority, session_ticket_store=tickets)+ out = {}+ handle = await start_gateway_api(runner)+ try:+ out["after_bind"] = sorted(m for m in ("hermes_cli.web_server", "fastapi") if m in sys.modules)+ url = handle.api_origin.replace("http:", "ws:") + "/api/ws"+ def protocols():+ return ["hermes-gateway-v1", "hermes-gateway-ticket." + tickets.mint(+ profile_id=home, subject="human", purpose="interactive")]+ async with connect(url, subprotocols=protocols()) as ws:+ out["native"] = json.loads(await ws.recv())+ # DNS-rebinding guard applies before the dashboard is loaded: a raw upgrade carrying a+ # valid ticket but a foreign Host is refused (403) at the handshake.+ port = int(handle.api_origin.rsplit(":", 1)[1])+ reader, writer = await asyncio.open_connection("127.0.0.1", port)+ writer.write((+ "GET /api/ws HTTP/1.1\\r\\nHost: attacker.invalid\\r\\nUpgrade: websocket\\r\\n"+ "Connection: Upgrade\\r\\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\\r\\n"+ "Sec-WebSocket-Version: 13\\r\\nSec-WebSocket-Protocol: " + ", ".join(protocols()) + "\\r\\n\\r\\n"+ ).encode())+ await writer.drain()+ out["rebind"] = int((await asyncio.wait_for(reader.readline(), 10)).split()[1])+ writer.close()+ out["before_http"] = "hermes_cli.web_server" in sys.modules+ async with httpx.AsyncClient(base_url=handle.api_origin, trust_env=False) as client:+ out["status"] = (await client.get("/api/status")).status_code+ out["rebind_http"] = (await client.get("/api/status", headers={"Host": "attacker.invalid"})).status_code+ out["after_http"] = "hermes_cli.web_server" in sys.modules+ from hermes_cli import web_server+ out["runner_bound"] = web_server.app.state.gateway_runner is runner+ out["token_withheld"] = bool(web_server.app.state.withhold_session_token)+ finally:+ await stop_gateway_api(handle)+ from hermes_cli import web_server+ out["unbound"] = web_server.app.state.gateway_runner is None+ print("RESULT " + json.dumps(out), file=sys.stderr, flush=True)++ asyncio.run(main())+""")+++def test_session_listener_serves_native_ws_before_importing_the_dashboard(tmp_path):+ home = tmp_path / ".hermes"+ home.mkdir()+ env = {k: v for k, v in os.environ.items() if k in {"PATH", "LANG", "TZ", "HERMES_RUNTIME_DIR", "TMPDIR"}}+ env.update(HOME=str(tmp_path), HERMES_HOME=str(home), PYTHONPATH=str(REPO))+ proc = subprocess.run([sys.executable, "-c", _PROBE, str(home)], cwd=str(REPO), env=env,+ capture_output=True, text=True, timeout=120)+ lines = [ln for ln in (proc.stdout + proc.stderr).splitlines() if ln.startswith("RESULT ")]+ assert proc.returncode == 0 and lines, proc.stderr[-3000:]+ out = json.loads(lines[-1][len("RESULT "):])+ assert out["after_bind"] == [], f"listener start imported {out['after_bind']}"+ assert out["native"] == {"native": True, "dashboard_loaded": False}+ assert out["rebind"] == 403+ assert out["before_http"] is False+ # Dashboard routes still answer on the same origin, behind the same Host guard.+ assert out["status"] == 200 and out["rebind_http"] == 400+ assert out["after_http"] and out["runner_bound"] and out["token_withheld"] and out["unbound"]