The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(ws-only): address review blockers — opt-in gating, loopback fail-close, real v15 handshake tests
kshitijk4poor49442c7b70ad
diff --git a/apps/desktop/electron/backend-command.test.ts b/apps/desktop/electron/backend-command.test.tsindex 6422bb647ae..2e49160d268 100644--- a/apps/desktop/electron/backend-command.test.ts+++ b/apps/desktop/electron/backend-command.test.ts@@ -9,15 +9,18 @@ import {sourceDeclaresWsOnly} from './backend-command'-test('serveBackendArgs builds a headless serve invocation with --ws-only by default', () => {- assert.deepEqual(serveBackendArgs(), ['serve', '--host', '127.0.0.1', '--port', '0', '--ws-only'])+test('serveBackendArgs builds a headless serve invocation WITHOUT --ws-only by default', () => {+ // Opt-in until the desktop REST plane migrates to JSON-RPC (#94484 ph.3):+ // the WS-only server has no HTTP routes and would break hermes:api.+ assert.deepEqual(serveBackendArgs(), ['serve', '--host', '127.0.0.1', '--port', '0'])})test('serveBackendArgs pins a profile when provided', () => {- assert.deepEqual(serveBackendArgs('worker'), ['--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0', '--ws-only'])+ assert.deepEqual(serveBackendArgs('worker'), ['--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0'])})-test('serveBackendArgs omits --ws-only when wsOnly=false', () => {+test('serveBackendArgs emits --ws-only only on explicit opt-in', () => {+ assert.deepEqual(serveBackendArgs(undefined, { wsOnly: true }), ['serve', '--host', '127.0.0.1', '--port', '0', '--ws-only'])assert.deepEqual(serveBackendArgs(undefined, { wsOnly: false }), ['serve', '--host', '127.0.0.1', '--port', '0'])})diff --git a/apps/desktop/electron/backend-command.ts b/apps/desktop/electron/backend-command.tsindex 233627a53f9..7de0ea369a3 100644--- a/apps/desktop/electron/backend-command.ts+++ b/apps/desktop/electron/backend-command.ts@@ -22,12 +22,15 @@* Build the canonical headless backend argv (always `serve`).* @param {string} [profile] optional Hermes profile to pin via `--profile`.* @param {object} [opts] runtime capability flags.- * @param {boolean} [opts.wsOnly=true] emit `--ws-only` (the slim WS server)- * when true. Set to false for a runtime that doesn't understand the flag.+ * @param {boolean} [opts.wsOnly=false] emit `--ws-only` (the slim WS server).+ * OPT-IN: the WS-only server has no HTTP routes, and the desktop's+ * `hermes:api` REST plane still speaks http — flipping this on by default+ * would break every REST consumer (see PR #94245 review F1). Stays off+ * until the REST consumers migrate to JSON-RPC (#94484 phase 3).*/export function serveBackendArgs(profile?: string, opts?: { wsOnly?: boolean }) {const head = profile ? ['--profile', profile] : []- const wsOnly = opts?.wsOnly !== false // default true+ const wsOnly = opts?.wsOnly === true // default false — see docstringconst tail = wsOnly ? ['--ws-only'] : []return [...head, 'serve', '--host', '127.0.0.1', '--port', '0', ...tail]diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex fdb6cd2244a..b7a3e4b08a2 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -10542,7 +10542,14 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po// --profile wins over the inherited HERMES_HOME env (see _apply_profile_override// step 3 in hermes_cli/main.py), so the child re-homes to this profile.// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.- const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0', '--ws-only']+ // `--ws-only` is OPT-IN (HERMES_DESKTOP_WS_ONLY=1): the slim server has no+ // HTTP routes, and the desktop's `hermes:api` REST plane still requires+ // http — enabling it by default breaks every REST consumer (review F1 on+ // PR #94245). Flips to default once the REST plane migrates (#94484 ph.3).+ const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']+ if (process.env.HERMES_DESKTOP_WS_ONLY === '1') {+ backendArgs.push('--ws-only')+ }const backend = await ensureRuntime(resolveHermesBackend(backendArgs))// Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.backend.args = getBackendArgsForRuntime(backend)@@ -10688,7 +10695,11 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; po)}- const baseUrl = announcedToken ? `ws://127.0.0.1:${port}` : `http://127.0.0.1:${port}`+ // baseUrl feeds the `hermes:api` REST plane (fetchJson rejects non-http).+ // A WS-only backend has no HTTP routes; expose the WS transport via wsUrl+ // and mark it on the descriptor instead of overloading baseUrl (F1).+ const baseUrl = `http://127.0.0.1:${port}`+ const wsOnlyTransport = Boolean(announcedToken)return {baseUrl,@@ -10698,6 +10709,7 @@ async function spawnPoolBackend(profile, entry, opts: { forceLocal?: boolean; potoken: authToken,profile,wsUrl,+ wsOnlyTransport,logs: hermesLog.slice(-80),...getWindowState()}@@ -10909,7 +10921,11 @@ async function startHermes() {const token = crypto.randomBytes(32).toString('base64url')// --port 0: the OS assigns an ephemeral port; the child announces it on stdout.- const backendArgs = ['serve', '--host', '127.0.0.1', '--port', '0', '--ws-only']+ // `--ws-only` opt-in — same gate as the pool spawn site above (F1).+ const backendArgs = ['serve', '--host', '127.0.0.1', '--port', '0']+ if (process.env.HERMES_DESKTOP_WS_ONLY === '1') {+ backendArgs.push('--ws-only')+ }// Pin the desktop's chosen profile via the global --profile flag. This is// deterministic (it wins over the sticky ~/.hermes/active_profile file) and// resolves HERMES_HOME the same way `hermes -p <name>` does on the CLI. An@@ -11157,7 +11173,10 @@ async function startHermes() {// accumulated count of the resolved episode.bootstrapRepairAttempt = 0- const baseUrl = announcedToken ? `ws://127.0.0.1:${port}` : `http://127.0.0.1:${port}`+ // Same descriptor rule as spawnPoolBackend: baseUrl stays http for the+ // REST plane; WS-only mode is flagged separately (F1).+ const baseUrl = `http://127.0.0.1:${port}`+ const wsOnlyTransport = Boolean(announcedToken)return {baseUrl,@@ -11166,6 +11185,7 @@ async function startHermes() {authMode: 'token',token: authToken,wsUrl,+ wsOnlyTransport,logs: hermesLog.slice(-80),...getWindowState()}diff --git a/tests/test_tui_gateway_entry_ws.py b/tests/test_tui_gateway_entry_ws.pynew file mode 100644index 00000000000..d139a452869--- /dev/null+++ b/tests/test_tui_gateway_entry_ws.py@@ -0,0 +1,118 @@+"""Tests for tui_gateway.entry_ws — the slim WS-only gateway server.++The auth/path handling MUST be exercised against the real, repo-pinned+``websockets`` package (15.x): its asyncio server passes a single+``ServerConnection`` to the handler (no second ``path`` argument), and the+request path lives on ``connection.request.path``. A fake adapter would have+masked exactly the signature mismatch that review F2 on PR #94245 flagged.+"""++from __future__ import annotations++import asyncio+import contextlib+import threading++import pytest++websockets = pytest.importorskip("websockets")++from tui_gateway import entry_ws+++def ws_server():+ """Real websockets server running entry_ws._handle_connection on loopback.++ Runs in a dedicated event-loop thread so tests can drive real client+ connections with the synchronous websockets client API.+ """+ loop = asyncio.new_event_loop()+ started = threading.Event()+ state: dict = {}++ async def _serve():+ server = await websockets.serve(+ entry_ws._handle_connection, "127.0.0.1", 0+ )+ state["port"] = server.sockets[0].getsockname()[1]+ state["server"] = server+ started.set()+ await asyncio.Event().wait()++ def _run():+ asyncio.set_event_loop(loop)+ with contextlib.suppress(asyncio.CancelledError):+ loop.run_until_complete(_serve())++ thread = threading.Thread(target=_run, daemon=True)+ thread.start()+ assert started.wait(timeout=10), "ws server failed to start"+ yield state+ loop.call_soon_threadsafe(loop.stop)+ thread.join(timeout=5)+++def _connect(port: int, query: str):+ """Open a real client connection; returns (ok, close_code).++ Deterministic accept/reject probe: an ACCEPTED connection is handed to+ handle_ws, which emits the ``gateway.ready`` event; a REJECTED one is+ closed with 4401. Waiting on recv() observes whichever happens — no race+ against the close frame (a ping can win that race and false-pass).+ """+ from websockets.sync.client import connect as sync_connect++ uri = f"ws://127.0.0.1:{port}/{query}"+ try:+ with sync_connect(uri, open_timeout=5, close_timeout=5) as client:+ first = client.recv(timeout=10)+ return "gateway.ready" in str(first), None+ except Exception as exc: # ConnectionClosed carries the close code+ code = getattr(getattr(exc, "rcvd", None), "code", None)+ return False, code+++def test_handshake_rejects_missing_token(ws_server):+ ok, code = _connect(ws_server["port"], "")+ assert not ok+ assert code == 4401+++def test_handshake_rejects_wrong_token(ws_server):+ ok, code = _connect(ws_server["port"], "?token=definitely-wrong")+ assert not ok+ assert code == 4401+++def test_handshake_accepts_valid_token_reading_path_from_v15_connection(ws_server):+ """The regression F2 guards against: under websockets 15.x the handler+ receives only a ServerConnection — the ?token= query MUST still be read+ (from ws.request.path). If the handler fell back to path='/', this valid+ token would be rejected exactly like the missing-token case above."""+ token = entry_ws.get_session_token()+ ok, code = _connect(ws_server["port"], f"?token={token}")+ assert ok, f"valid token rejected (close code {code}) — path not read from v15 connection"+++def test_run_refuses_non_loopback_host():+ """F3: --ws-only uses static-token auth and must fail closed off-loopback."""+ with pytest.raises(SystemExit, match="loopback"):+ entry_ws.run(host="0.0.0.0", port=0)+ with pytest.raises(SystemExit, match="loopback"):+ entry_ws.run(host="192.168.1.10", port=0)+++def test_run_allows_loopback_hosts_past_the_guard(monkeypatch):+ """Loopback names/addresses pass the guard (asyncio.run is stubbed so the+ server itself never starts)."""+ sentinel = RuntimeError("guard passed — reached server start")++ def _boom(_coro):+ _coro.close()+ raise sentinel++ monkeypatch.setattr(entry_ws.asyncio, "run", _boom)+ for host in ("127.0.0.1", "::1", "localhost"):+ with pytest.raises(RuntimeError, match="guard passed"):+ entry_ws.run(host=host, port=0)diff --git a/tui_gateway/entry_ws.py b/tui_gateway/entry_ws.pyindex 1ab2c2835e7..d3232068a3c 100644--- a/tui_gateway/entry_ws.py+++ b/tui_gateway/entry_ws.py@@ -179,9 +179,31 @@ def run(host: str = "127.0.0.1", port: int = 0) -> None:the desktop's Electron main process can discover the port (when``--port 0``) and the token (when auto-generated), identical to how itparses the dashboard's ready sentinel.++ Loopback-only: this server authenticates with a static per-process+ session token — the loopback shortcut the desktop uses. It deliberately+ does NOT implement the dashboard's gated one-time-ticket auth+ (``should_require_dashboard_auth``), so binding it to a non-loopback+ interface would expose a weaker auth posture than every other Hermes+ surface. Fail closed instead of serving."""+ import ipaddressimport signal+ try:+ addr = ipaddress.ip_address(host)+ is_loopback = addr.is_loopback+ except ValueError:+ # Hostnames: allow the conventional loopback name only.+ is_loopback = host == "localhost"+ if not is_loopback:+ raise SystemExit(+ f"--ws-only only binds loopback interfaces (got {host!r}). "+ "It uses the desktop's static session-token auth, which is not "+ "hardened for network exposure. Use `hermes serve` (the full "+ "dashboard server with gated auth) for non-loopback hosts."+ )+# Capture the real stdout BEFORE importing tui_gateway.server —# server.py redirects sys.stdout → sys.stderr at module level# (line 392: `sys.stdout = sys.stderr`) to keep JSON-RPC over stdio