Skip to content

[Bug]: Desktop "Remote gateway" can't connect over WebSocket — /api/ws always rejected (4403) for packaged Electron client #38412

Closed

Description

@bscott

Bug Description

Summary

Hermes Desktop in Remote gateway mode connects to the remote backend's REST layer but the WebSocket leg (/api/ws) is always rejected, so the UI sits
on "Could not connect to Hermes gateway." As far as I can tell, there is no bind configuration where a packaged Electron desktop on machine B can
satisfy the WS admission gates on a gateway running on machine A.

Environment

  • Desktop (client): macOS, Hermes 0.15.1
  • Gateway (remote): Linux, Hermes 0.15.1 (release 2026.5.29), reached over Tailscale at http://:9119
  • HERMES_AUTH_REQUIRED=false on the gateway

Suggested fix

Allow the Desktop's remote WS handshake to authenticate on the session token alone for non-loopback binds, or explicitly permit the Electron desktop's
non-web Origin when the request carries a valid _SESSION_TOKEN (decouple the Origin/peer DNS-rebinding guards from the token-authenticated desktop
path).

Steps to Reproduce

Repro

  1. On machine A, run the dashboard/gateway and expose port 9119 to machine B.
  2. On machine B, set Desktop → Remote gateway, URL http://:9119, token = the dashboard session token.
  3. Launch Desktop.

Expected Behavior

Expected

Desktop connects and the chat UI loads against the remote gateway.

Actual

  • desktop.log: Connecting to remote Hermes backend at http://:9119 → Remote Hermes backend is ready (the /api/status boot probe passes).
  • UI then shows "Hermes couldn't start / Could not connect to Hermes gateway."
  • A direct handshake to ws://:9119/api/ws?token=<session_token> returns HTTP 403 regardless of token or Origin.

Analysis

REST works (_is_accepted_host passes by hostname) and auth is fine (verified the ?token= value equals the server's _SESSION_TOKEN injected into the
HTML). The 403 comes from _ws_request_is_allowed in hermes_cli/web_server.py, and the two sub-checks appear mutually exclusive for a remote Electron
client:

  • _ws_client_is_allowed — with a loopback bind, only loopback peers are allowed, so a remote desktop peer is rejected.
  • _ws_host_origin_is_allowed — the packaged Electron renderer sends a non-web Origin (file:///null), which is only accepted when the bind is loopback
    (bound_host in _LOOPBACK_HOST_VALUES). With a non-loopback bind it's rejected.

So binding loopback fails the client/peer check, and binding non-loopback fails the origin check — leaving no configuration where a remote
packaged-Electron desktop passes both. This makes the documented "Remote gateway" feature unusable for the intended cross-machine case (it only works
when the client is effectively loopback to the gateway).

Actual Behavior

Hermes Desktop in Remote gateway mode connects to the remote backend's REST layer but the WebSocket leg (/api/ws) is always rejected, so the UI sits
on "Could not connect to Hermes gateway." As far as I can tell, there is no bind configuration where a packaged Electron desktop on machine B can
satisfy the WS admission gates on a gateway running on machine A.

Environment

  • Desktop (client): macOS, Hermes 0.15.1
  • Gateway (remote): Linux, Hermes 0.15.1 (release 2026.5.29), reached over Tailscale at http://:9119
  • HERMES_AUTH_REQUIRED=false on the gateway

Affected Component

Other

Messaging Platform (if gateway-related)

N/A (CLI only)

Debug Report

Already attached

Operating System

Mac

Python Version

No response

Hermes Version

No response

Additional Logs / Traceback (optional)

Root Cause Analysis (optional)

No response

Proposed Fix (optional)

No response

Are you willing to submit a PR for this?

  • I'd like to fix this myself and submit a PR

Activity

  1. added
    type/bugSomething isn't working
    P2Medium — degraded but workaround exists
    comp/gatewayGateway runner, session dispatch, delivery
    area/authAuthentication, OAuth, credential pools
    on Jun 3, 2026
  2. katiL-UI commented on Jun 5, 2026

    @katiL-UI

    Approach: API Server as WebSocket/REST proxy to Dashboard

    We hit the same problem (Desktop remote gateway unusable) and worked around it with a different architectural approach: instead of having the Desktop connect directly to the Dashboard (port 9119), we route through the API Server (port 8642), which proxies both WebSocket and REST /api/* traffic to the Dashboard internally on loopback.

    This sidesteps the file:///null origin check entirely — the API server talks to the Dashboard on 127.0.0.1, where loopback origin checks pass. The Desktop only ever talks to the API server.

    What we added to api_server.py

    1. Import additions (line ~49)

    from aiohttp import web, ClientSession, WSMsgType

    2. Auth: accept X-Hermes-Session-Token header (in _check_auth)
    The Desktop sends X-Hermes-Session-Token instead of Authorization: Bearer. Added a second check after the Bearer block:

    session_token = request.headers.get("X-Hermes-Session-Token", "")
    if session_token and hmac.compare_digest(session_token, self._api_key):
        return None  # Auth OK

    3. /api/status endpoint
    The Desktop probes this to detect auth mode. Simple public endpoint:

    async def _handle_api_status(self, request):
        return web.json_response({
            "status": "ok", "platform": "hermes-agent",
            "version": "0.15.1", "auth_required": False, "auth_providers": [],
        })

    Route: self._app.router.add_get("/api/status", self._handle_api_status)

    4. Dashboard token helper
    Fetches and caches the dashboard session token from the dashboard root HTML:

    async def _get_dashboard_token(self):
        if self._dashboard_token:
            return self._dashboard_token
        async with aiohttp.ClientSession() as session:
            async with session.get("http://127.0.0.1:9119/") as resp:
                html = await resp.text()
                match = re.search(r'__HERMES_SESSION_TOKEN__\s*=\s*"([^"]+)"', html)
                if match:
                    self._dashboard_token = match.group(1)
                    return self._dashboard_token
        return None

    5. WebSocket proxy (/api/ws)
    Validates ?token= against API_SERVER_KEY, fetches dashboard token, opens client WS to ws://127.0.0.1:9119/api/ws?token=<dash_token>, bidirectionally proxies messages.

    6. Catch-all REST proxy (/api/{tail:.*})
    Forwards unmatched /api/* requests to http://127.0.0.1:9119/api/{tail}, translating X-Hermes-Session-Token → Authorization: Bearer <dash_token>.

    7. CORS

    API_SERVER_CORS_ORIGINS=*

    Why this works

    The Desktop connects to http://<host>:8642 (API server). All requests go through the API server's aiohttp stack, where the file:///null origin from Electron is handled by the CORS middleware (not the WebSocket admission gates in web_server.py). The actual Dashboard WebSocket connection happens on loopback, where origin checks pass normally.

    Trade-offs vs. fixing _ws_request_is_allowed directly

    • Pro: No changes to Dashboard code. Works today without waiting for upstream WebSocket gate changes.
    • Pro: Single port exposure (8642). Dashboard (9119) stays internal.
    • Con: Adds latency (extra hop). Token extraction from HTML is fragile (but the session token pattern __HERMES_SESSION_TOKEN__ appears stable).
    • Con: Requires aiohttp on the API server side (already a gateway dependency).

    Happy to turn this into a PR if there's interest. The code is tested and working with Hermes Desktop 0.15.1 against a remote Linux gateway.

  3. govtech42 commented on Jun 6, 2026

    @govtech42

    Hit the same failure on macOS 0.15.1, and after digging through the WebSocket admission gates I think the most common cause for "the desktop reaches the backend but the WS always 403s" is token mismatch, not the loopback/origin conflict described above. Two distinct failure modes, two distinct fixes, easy to confuse.

    My repro (macOS 0.15.1, both ends on the same LAN, no proxy):

    • Gateway: standalone hermes dashboard running under a launchd LaunchAgent (~/Library/LaunchAgents/ai.hermes.dashboard.plist) with --host 0.0.0.0 --port 9119 --insecure.
    • Client: Hermes Desktop on a second Mac, Remote Gateway set to http://<lan-ip>:9119 with a static token pasted into connection.json.

    Symptom (identical to this issue):

    • "Test remote" reports the HTTP check passing.
    • Desktop log cycles Remote Hermes backend is ready → WebSocket connection failed → restart loop, exactly as the reporter describes.
    • probeGatewayWebSocket returns "WebSocket connection failed" with the generic fallback reason.

    Where the 403 actually comes from (in my case):

    The reporter's analysis attributes the rejection to _ws_request_is_allowed in hermes_cli/web_server.py (host/origin/peer-IP gates). For a remote Electron desktop over a non-loopback bind with --insecure, the _ws_host_origin_is_allowed short-circuits via the bound_host in {"0.0.0.0", "::"} branch (line ~270) and _ws_client_is_allowed short-circuits via the non-loopback-bind branch (line ~7642) — both should let the upgrade through. So the 403 is not from those gates in my repro.

    In my case the rejection is in gateway_ws (line ~8121) calling _ws_auth_ok, which fails hmac.compare_digest because the ?token= value carried by the Desktop doesn't match the server's _SESSION_TOKEN. With a --insecure launchd service and no HERMES_DASHBOARD_SESSION_TOKEN in the env, web_server.py:139 falls back to secrets.token_urlsafe(32) at process start, generating a fresh per-process random token that's only injected into the SPA <script>window.__HERMES_SESSION_TOKEN__="..."</script> block. The Desktop never scrapes the SPA, so any value the user types in connection.json is a guess and will never match — the server returns 403 on the upgrade, Node's WebSocket fires onerror (not onopen + early onclose), and the probe reports the generic "WebSocket connection failed" instead of a useful "credential rejected" reason.

    Verified empirically with a raw socket:

    • GET /api/ws (no token) → HTTP/1.1 403 Forbidden (closes connection)
    • GET /api/ws?token=WRONG → HTTP/1.1 403 Forbidden (closes connection)
    • GET /api/ws?token=<token scraped from /__session__ HTML> → HTTP/1.1 101 Switching Protocols ✓

    The 403 is sent before the 101, which is why the probe's grace window never engages.

    Two working fixes:

    1. Pin the server-side token (smallest change, no client work). Set HERMES_DASHBOARD_SESSION_TOKEN=<a-token-you-also-paste-into-connection.json> in the LaunchAgent's EnvironmentVariables, reload, paste the same value into the Desktop's connection.json remote.token. Works for --insecure and for OAuth-gated mode alike (loopback binds ignore the token, non-loopback binds still verify it). Confirmed working on my setup.

    2. Use the OAuth gate (the path the Hermes team has been steering users toward). Drop --insecure, configure BasicAuthProvider (or the Nous OAuth provider) via HERMES_DASHBOARD_BASIC_AUTH_USERNAME / _PASSWORD / _SECRET, the login page renders a credential form, the Desktop's existing OAuth flow mints a single-use ?ticket= via POST /api/auth/ws-ticket, the WS upgrade accepts it. No static token to keep in sync. End-to-end verified on my setup (login → cookies → ws-ticket → 101 Switching Protocols).

    Two small follow-ups I think would help everyone:

    • probeGatewayWebSocket in apps/desktop/electron/gateway-ws-probe.cjs doesn't distinguish "server rejected the upgrade" (e.g. 401/403 with a body) from "TCP RST / no response". The current generic "WebSocket connection failed" string is what hides the token-mismatch case from testDesktopConnectionConfig users. Surfacing the HTTP status + body when the upgrade is rejected pre-101 would unblock a lot of debugging.
    • testDesktopConnectionConfig in apps/desktop/electron/main.cjs validates only the HTTP leg against the documented "ws-ticket/token auth" path. If the authMode === 'oauth' branch were actually exercised in the test, users on --insecure would get a clear "this remote is using legacy token auth, not OAuth — your token does not match the server's _SESSION_TOKEN" message instead of a generic failure.

    Happy to file either as a separate PR if there's interest, or to bundle the workaround in a skill so other LAN setups can find it. Filing as a tracking comment here first so the duplicate-issues pile (#38115, #38332, #40083) can be linked.

  4. logancyang commented on Jun 6, 2026

    @logancyang

    Confirming this over an SSH tunnel (ssh -L 9119:localhost:9119), which isolates the root cause more cleanly than the Tailscale/LAN repros above — and a no-code-change workaround.

    SSH-tunnel case removes the peer-IP variable. Over ssh -L, the dashboard sees the peer as 127.0.0.1, so _ws_client_is_allowed passes and the bind stays loopback. It still 403s — purely because the packaged Electron renderer (loaded from file://) sends Origin: null, which trips _ws_host_origin_is_allowed (scheme not in {http,https} → reject). So the Origin guard alone is sufficient to break it, independent of the peer/host checks. Empirically, against a loopback-bound --tui dashboard with a valid ?token=:

    • Origin: null → 403
    • Origin: file:// → 403
    • no Origin header → 101 Switching Protocols

    This also explains the "ready, then connecting forever" split. The boot probe (apps/desktop/electron/gateway-ws-probe.cjs) runs in the Node main process via globalThis.WebSocket, which sends no Origin → 101 → "Remote backend is ready". The real chat socket (HermesGateway in apps/desktop/src/store/gateway.ts) runs in the file:// renderer → Origin: null → 403. Same URL+token, different Origin, opposite outcomes.

    Prerequisite worth flagging: /api/ws also 4403s for everyone (even loopback/no-origin) unless the dashboard runs with --tui / HERMES_DASHBOARD_TUI=1 — the if not _DASHBOARD_EMBEDDED_CHAT_ENABLED guard at the top of gateway_ws. Easy to mistake for the Origin bug.

    Workaround (no code changes to app or server): a tiny localhost TCP proxy that strips the Origin header from the upgrade request, in front of the tunnel — desktop → proxy:9119 (strip Origin) → ssh -L :9129 → dashboard :9119. The dashboard then hits if not origin: return True and accepts; Origin: null/file:// → 101 confirmed end-to-end, chat works. Core of it:

    head, sep, rest = buf.partition(b"\r\n\r\n")
    lines = [ln for ln in head.split(b"\r\n") if not ln.lower().startswith(b"origin:")]
    upstream.write(b"\r\n".join(lines) + sep + rest)  # then bidirectional byte-pipe

    This validates the suggested fix direction: in loopback/token mode the _SESSION_TOKEN + loopback bind are already the trust boundary, so the Origin/DNS-rebinding guard could be decoupled from the token-authenticated desktop path (accept opaque/null/file:// origins when a valid _SESSION_TOKEN is presented). Env: desktop 0.15.1, gateway 0.16.0.

  5. Gmatrix2022 commented on Jun 7, 2026

    @Gmatrix2022

    复测确认 — Hermes 0.16.0 (release_date 2026.6.5) 仍未修复

    环境:

    • MacBook Air M5 24GB
    • Hermes Desktop (packaged Electron) + 远端 gateway 走 Tailscale (100.91.207.5:9800)
    • Token 走 env HERMES_DASHBOARD_SESSION_TOKEN 注入容器(Mac keychain 不可用,旧版 token 输入框已禁用)

    服务端实测(0.16.0)

    同一 token vKCsw4jBPR0QuU6rDHS5dfzwPsTigufpxUUe9ihVFHE(43 字符):

    端点 鉴权 结果
    GET /api/status 带 X-Hermes-Session-Token header header 200 OK ✅
    GET /api/ws?token=... 带 query 升级 WS query 101 Switching Protocols ✅,收到 gateway.ready 事件
    GET /api/ws 无 query 升级 WS — 403 Forbidden ❌

    compare_digest 两边一致。

    关键观察

    • 服务端鉴权逻辑本身正常:带 ?token= 立刻 101 + 正常推送 gateway.ready 事件;不带才 403。
    • 客户端 bug:Desktop 拼 WS URL 时 没 append ?token=(只走 header 走不通 WS,HTTP /api/status 和 WS /api/ws 的鉴权通道不是同一套)。
    • 0.16 release notes 提到 "OAuth-gated binds" 修复(PR fix(dashboard): trust non-web WS origins on OAuth-gated binds after ticket auth #37870),但 token env 注入 → WS URL 拼接这条路径仍然断。

    期望修复

    Desktop 客户端在拼 ws://gateway/api/ws URL 时,如果用户配置了 token(env 或 keystore),应自动 append ?token=<value>。当前 macOS keychain 不可用、env 是唯一注入通道,这条路径不能断。

    相关 issue

  6. d3faulter commented on Jun 7, 2026

    @d3faulter

    Same here on windows. Backend seems to be fine.

  7. 0xTimepunk commented on Jun 26, 2026

    @0xTimepunk

    Confirming this on macOS (Apple Silicon) with the official nousresearch/hermes-agent:latest image under OrbStack — and I think there are two distinct root causes here, plus a docs bug. Source refs are from the published image.

    Setup

    • Hermes Desktop (packaged Electron), gateway = official Docker image, bridge networking, ports published on 127.0.0.1 only (9119 dashboard, 8642 API).
    • Model on host Ollama via host.docker.internal:11434 (fine).
    • Launched with HERMES_DESKTOP_REMOTE_URL=http://127.0.0.1:9119 + HERMES_DESKTOP_REMOTE_TOKEN=….
    • Symptom: REST TCP connects, then "Could not connect to Hermes gateway."

    Root cause 1 — token-mode auth is structurally impossible once the gate engages

    Desktop token mode (buildRemoteConnection(..., 'token', token) in apps/desktop/electron/main.cjs) sends the token as X-Hermes-Session-Token (REST) and ?token= (WS). Both are validated against _SESSION_TOKEN in hermes_cli/web_server.py:

    _SESSION_TOKEN = os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN") or secrets.token_urlsafe(32)

    …but the comments state _SESSION_TOKEN is loopback-only and disabled once the gate engages (web_server.py ~486 and ~11390: "_SESSION_TOKEN must not grant WS access once the gate is engaged"). A Docker port-publish requires a non-loopback bind, which mandates the auth gate — so token-mode auth can never succeed. Verified: both user:password and a freshly minted hermes_session_at return 401 via X-Hermes-Session-Token.

    Root cause 2 — WS gate rejects the packaged-Electron origin (this issue)

    _ws_request_is_allowed → _ws_host_origin_is_allowed, with a hardcoded policy:

    allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$"   # web_server.py ~274

    The packaged Electron renderer sends Origin: file:///null → fails the regex → /api/ws 4403. No env var allowlists it, so even OAuth mode hits this.

    Docs bug

    docs/user-guide/docker recommends HERMES_DESKTOP_REMOTE_TOKEN=admin:yourpassword with basic auth. Per #1 this cannot work — the token routes to the gate-disabled _SESSION_TOKEN path. The example should be corrected.

    Net

    With the official image + a non-loopback bind (required to publish the port), the native Desktop cannot connect via token mode at all, and the WS leg is blocked by the origin gate regardless of auth mode. The API-server-proxy approach proposed above sidesteps both gates (auth via API_SERVER_KEY, dashboard reached on loopback) and is the most practical fix today. Happy to test a patch against this exact setup (official image + OrbStack + host Ollama).

  8. added
    comp/cliCLI entry point, hermes_cli/, setup wizard
    sweeper:risk-security-boundarySweeper risk: may affect sandboxing, auth, credentials, or sensitive data
    P1High — major feature broken, no workaround
    comp/desktopElectron desktop app (apps/desktop/*)
    and removed
    P2Medium — degraded but workaround exists
    on Jun 26, 2026
  9. kshitijk4poor commented on Jun 28, 2026

    @kshitijk4poor

    Verified fixed on current main — closing.

    The non-web WebSocket Origin rejection (packaged Electron desktop connecting to /api/ws in remote-gateway mode getting 4403/403 despite a valid session token) was introduced by 2e66eefbc and fixed by the desktop-remote work:

    • 6ed9a2de8 — allow desktop websocket origins on remote binds
    • dd28f2ac9 — trust non-web WS origins on OAuth-gated binds after ticket auth

    On current main, _ws_host_origin_reason in hermes_cli/web_server.py (≈L11407–11415) returns None (allowed) for empty or non-http(s) origins (file://, null, app://), deferring to the real credential check (_ws_auth_reason, hmac.compare_digest against the session token). A valid-token desktop client with a non-web Origin now completes the WS upgrade (101) instead of being rejected.

    This issue never auto-closed only because the fixing commits didn't reference #38412 in their messages — the bug class itself is resolved. (Open PR #40408, which does name #38412, is a now-redundant re-fix of an already-fixed path.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1High — major feature broken, no workaroundarea/authAuthentication, OAuth, credential poolscomp/cliCLI entry point, hermes_cli/, setup wizardcomp/desktopElectron desktop app (apps/desktop/*)comp/gatewayGateway runner, session dispatch, deliverysweeper:risk-security-boundarySweeper risk: may affect sandboxing, auth, credentials, or sensitive datatype/bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions