fix(serve): serve Desktop token page at / in headless mode (#94227)

The Electron shell boots by fetching / and extracting
window.__HERMES_SESSION_TOKEN__ to authenticate /api/ws
(dashboard-token.ts adoptServedDashboardToken). Headless serve 404'd
every path, so when the renderer's spawn token drifted from the
backend's live token — e.g. hermes update replaced the backend and the
env pin no longer matched — the renderer had no way to adopt the served
token, the WebSocket handshake failed, and the primary window
white-screened (#95575).

Serve a minimal token-only HTML page at the exact root path in
mount_spa()'s headless branch, matching the renderer's extraction regex.
Gate it on app.state.auth_required read at request time: a gated
(non-loopback / remote public_url) serve keeps returning the 404 JSON so
the session token never leaks past the loopback boundary. Every other
path stays 404 JSON — the SPA remains unserved.

Regression tests: TestHeadlessServeTokenPage (3 cases) — verified to
fail against the pre-fix headless branch.
This commit is contained in:
Teknium
2026-08-26 15:23:02 -07:00
parent de34c746cc
commit 39a5aa91ed
2 changed files with 86 additions and 0 deletions
+26
View File
@@ -17908,6 +17908,32 @@ def mount_spa(application: FastAPI):
@application.get("/{full_path:path}")
async def no_frontend(full_path: str):
# Desktop token handshake (#94227): the Electron shell boots by
# fetching `/` and extracting ``window.__HERMES_SESSION_TOKEN__``
# for /api/ws auth (apps/desktop/electron/dashboard-token.ts).
# When headless serve 404'd every path, a renderer whose spawn
# token no longer matched the backend's live token (e.g. after
# `hermes update` replaced the backend) had no way to adopt the
# served token — the WS handshake failed and the window
# white-screened (#95575). Serve a minimal token-only page at the
# exact root, but ONLY when the dashboard auth gate is off: on a
# gated (non-loopback/remote) serve the token must never be
# readable without auth, so the 404 JSON stays.
gated = bool(getattr(application.state, "auth_required", False))
if full_path == "" and not gated:
token_js = json.dumps(_SESSION_TOKEN)
return HTMLResponse(
"<!doctype html><html><head><script>"
f"window.__HERMES_SESSION_TOKEN__={token_js};"
"window.__HERMES_AUTH_REQUIRED__=false;"
"</script></head><body>"
"Headless backend (hermes serve): web UI disabled — use "
"`hermes dashboard` for the browser UI."
"</body></html>",
headers={
"Cache-Control": "no-store, no-cache, must-revalidate"
},
)
return JSONResponse({"error": _msg}, status_code=404)
return
+60
View File
@@ -4859,6 +4859,66 @@ class TestServeIndexMissingIndex:
assert "SPA-rebuilt" in resp.text
class TestHeadlessServeTokenPage:
"""Headless `hermes serve` must serve the Desktop token handshake page
at `/` when the dashboard auth gate is off (#94227).
The Electron renderer boots by fetching `/` and extracting
``window.__HERMES_SESSION_TOKEN__`` for WebSocket auth. Headless serve
used to 404 every path, so after an update replaced the backend (and
the spawn-token env pin no longer matched the token the new backend
generated) the renderer was stuck with a stale token, /api/ws rejected
it, and the window white-screened (#95575).
"""
@staticmethod
def _headless_client(monkeypatch, *, gated: bool):
from fastapi import FastAPI
from starlette.testclient import TestClient
import hermes_cli.web_server as ws
monkeypatch.setenv("HERMES_SERVE_HEADLESS", "1")
spa_app = FastAPI()
spa_app.state.auth_required = gated
ws.mount_spa(spa_app)
return TestClient(spa_app), ws
def test_root_serves_token_page_when_not_gated(self, monkeypatch):
import re
client, ws = self._headless_client(monkeypatch, gated=False)
resp = client.get("/")
assert resp.status_code == 200
assert resp.headers["content-type"].startswith("text/html")
assert "no-store" in resp.headers.get("cache-control", "")
# Must match the desktop's extraction regex exactly
# (apps/desktop/electron/dashboard-token.ts).
match = re.search(
r'window\.__HERMES_SESSION_TOKEN__\s*=\s*("(?:\\.|[^"\\])*")',
resp.text,
)
assert match, resp.text
import json as _json
assert _json.loads(match.group(1)) == ws._SESSION_TOKEN
assert "window.__HERMES_AUTH_REQUIRED__=false" in resp.text
def test_root_stays_404_json_when_auth_gated(self, monkeypatch):
client, ws = self._headless_client(monkeypatch, gated=True)
resp = client.get("/")
assert resp.status_code == 404
assert "web UI disabled" in resp.json()["error"]
assert ws._SESSION_TOKEN not in resp.text
def test_non_root_paths_stay_404_json(self, monkeypatch):
client, ws = self._headless_client(monkeypatch, gated=False)
for route in ("/chat", "/api/status-page", "/assets/index-abc.js"):
resp = client.get(route)
assert resp.status_code == 404
assert "web UI disabled" in resp.json()["error"]
assert ws._SESSION_TOKEN not in resp.text
class TestHashedAssetCacheHeaders:
"""Hashed /assets/* responses must be immutable-cacheable; index.html
must stay no-store so it always references the current hashes