Skip to content

The agent that grows with you

fix(webapp): signing out closes the screen viewers a browser tab opened

emozillab884a6a72273
diff --git a/hermes_cli/web_routers/display.py b/hermes_cli/web_routers/display.py
index 76193c06454..9d29cfffbcd 100644
--- a/hermes_cli/web_routers/display.py
+++ b/hermes_cli/web_routers/display.py
@@ -8,7 +8,8 @@ into the WebSocket as binary frames with backpressure both ways, and runs the cl
only from the viewer that currently holds the lease. noVNC's ``viewOnly`` is UX; this is the gate.
A lease change closes the evicted viewer's socket with 4000 ``control-taken`` so its UI drops back to
-Watch mode and reconnects.
+Watch mode and reconnects. A viewer a browser tab asked for signs out with that tab: ``hermes webapp
+--sign-out`` closes it with 4401, and its ticket opens nothing afterwards.
Design notes. The ticket rides in the query string on purpose: noVNC's Websock owns the socket and
cannot negotiate a subprotocol or add a header, and the ticket is single-use and expires in 30 s, so
@@ -87,9 +88,28 @@ async def display_ws(ws: WebSocket) -> None:
if info is None:
await ws.close(code=_CLOSE_BAD_TICKET, reason="display ticket missing, expired or used")
return
+ if _signed_out(ws, info):
+ await ws.close(code=_CLOSE_BAD_TICKET, reason="Signed out")
+ return
await _bridge(ws, info)
+def _signed_out(ws: WebSocket, info: dict) -> bool:
+ """True when the browser tab that asked for this viewer has signed out since; otherwise the
+ viewer is tracked with that tab's sockets, so signing out closes it too. A ticket a native
+ client minted carries no browser credential and is left alone."""
+ import hmac
+
+ from hermes_cli.web_session_sockets import current_digest, track
+ admitted = info.get("admitted_with")
+ if admitted is None:
+ return False
+ if not hmac.compare_digest(admitted, current_digest()):
+ return True
+ track(ws, admitted)
+ return False
+
+
async def _open_rfb(profile_home: Path):
"""``(reader, writer, relay)`` for THIS profile's Xvnc. Gateway-hosted screen: its unix socket. Screen inside
the terminal backend: a ``docker exec`` / ``ssh`` relay whose stdio IS the RFB stream (``relay`` is that
diff --git a/hermes_cli/web_session_sockets.py b/hermes_cli/web_session_sockets.py
index fb6f397b6c7..2c9c650b71b 100644
--- a/hermes_cli/web_session_sockets.py
+++ b/hermes_cli/web_session_sockets.py
@@ -38,7 +38,7 @@ OWN_TICKET_SOCKETS = frozenset({HOST_TERMINAL_SOCKET})
SIGNED_OUT_CODE = 4401
_lock = threading.Lock()
-_live: dict[int, tuple[weakref.ref, asyncio.AbstractEventLoop]] = {}
+_live: dict[int, tuple[weakref.ref, asyncio.AbstractEventLoop, str]] = {}
def token_digest(token: str) -> str:
@@ -90,13 +90,21 @@ def track(ws, admitted_with: str) -> None:
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]:
+ for key in [key for key, (ref, *_rest) in _live.items() if ref() is None]:
del _live[key]
- _live[id(ws)] = (weakref.ref(ws), loop)
+ _live[id(ws)] = (weakref.ref(ws), loop, admitted_with)
if not hmac.compare_digest(admitted_with, current_digest()):
_close_on(ws, loop)
+def admission_of(ws) -> Optional[str]:
+ """The digest live socket *ws* was tracked under, or None when signing out does not close it.
+ A socket it opens on the browser's behalf (a screen viewer) is tracked under the same one."""
+ with _lock:
+ entry = _live.get(id(ws))
+ return entry[2] if entry is not None and entry[0]() is ws else None
+
+
async def _close(ws) -> None:
# The socket may already be closing or gone; it ends either way.
with contextlib.suppress(RuntimeError, OSError, WebSocketDisconnect):
@@ -117,6 +125,6 @@ def close_all() -> int:
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)
+ closing = sum(_close_on(ws, loop) for ref, loop, _digest in live if (ws := ref()) is not None)
_log.info("Closing %d browser sockets opened with the replaced session token", closing)
return closing
diff --git a/tests/hermes_cli/test_display_ws_ticket.py b/tests/hermes_cli/test_display_ws_ticket.py
index 6cb2dd0613b..e055b7ef5b9 100644
--- a/tests/hermes_cli/test_display_ws_ticket.py
+++ b/tests/hermes_cli/test_display_ws_ticket.py
@@ -60,3 +60,61 @@ def test_a_bad_ticket_is_refused_with_a_close_frame_the_renderer_can_read(monkey
delattr(web_server.app.state, k)
else:
setattr(web_server.app.state, k, v)
+
+
+def _viewer_app(monkeypatch):
+ """The display route on the loopback Webapp; the RFB bridge stands in as a viewer that stays
+ connected until the server closes it."""
+ from fastapi import FastAPI
+ from starlette.testclient import TestClient
+
+ from hermes_cli import web_server
+
+ async def watch(ws, _info):
+ while (await ws.receive())["type"] != "websocket.disconnect":
+ pass
+
+ monkeypatch.setattr(display, "_bridge", watch)
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "a" * 43)
+ monkeypatch.setattr(web_server.app.state, "auth_required", False, raising=False)
+ monkeypatch.setattr(web_server.app.state, "bound_host", None, raising=False)
+ app = FastAPI()
+ app.include_router(display.router)
+ return TestClient(app)
+
+
+def _viewer_ticket(**extra):
+ return ws_tickets.mint_ticket(user_id="display:v", provider="bot-desktop",
+ extra={"hermes_home": "/srv/hermes/bot-a", "viewer_id": "v", **extra})
+
+
+def test_signing_out_closes_a_screen_viewer_a_browser_tab_opened(monkeypatch):
+ """A viewer opened from a signed-in tab watches, and while it holds the lease drives, the agent's
+ screen: it closes with the tab's other sockets when the browser signs out. A viewer a native
+ client opened (no browser credential on its ticket) stays."""
+ from hermes_cli import web_server, web_session_sockets
+ from tests.hermes_cli.test_webapp_sign_out_sockets import _close_code
+
+ ws_tickets._reset_for_tests()
+ client = _viewer_app(monkeypatch)
+ tab = _viewer_ticket(admitted_with=web_session_sockets.token_digest("a" * 43))
+ native = _viewer_ticket()
+ with client.websocket_connect(f"/api/display/ws?display_ticket={tab}") as from_tab, \
+ client.websocket_connect(f"/api/display/ws?display_ticket={native}") as from_native:
+ assert _close_code(from_tab, 0.2) is None
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)
+ web_session_sockets.close_all()
+ assert _close_code(from_tab) == 4401
+ assert _close_code(from_native, 0.5) is None
+
+
+def test_a_screen_viewer_ticket_from_a_signed_out_tab_opens_nothing(monkeypatch):
+ from hermes_cli import web_server, web_session_sockets
+ from tests.hermes_cli.test_webapp_sign_out_sockets import _close_code
+
+ ws_tickets._reset_for_tests()
+ client = _viewer_app(monkeypatch)
+ stale = _viewer_ticket(admitted_with=web_session_sockets.token_digest("a" * 43))
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "b" * 43)
+ with client.websocket_connect(f"/api/display/ws?display_ticket={stale}") as conn:
+ assert _close_code(conn, 2.0) == 4401
diff --git a/tests/tui_gateway/test_display_methods.py b/tests/tui_gateway/test_display_methods.py
index 86bf0380382..467327e6f25 100644
--- a/tests/tui_gateway/test_display_methods.py
+++ b/tests/tui_gateway/test_display_methods.py
@@ -85,6 +85,46 @@ def _rpc(server, method, params):
return server.handle_request({"jsonrpc": "2.0", "id": 7, "method": method, "params": params})
+def test_a_viewer_opened_from_a_browser_tab_signs_out_with_that_tab(monkeypatch, tmp_path):
+ """The viewer ticket carries the credential digest the asking browser socket was admitted with,
+ so /api/display/ws closes the viewer when that browser signs out; a native client's carries none."""
+ import asyncio
+
+ from hermes_cli import web_server, web_session_sockets
+ from tools.bot_desktop import runtime
+ from tui_gateway import server
+
+ monkeypatch.setattr(runtime, "rfb_socket_path", lambda: tmp_path / "rfb.sock")
+ monkeypatch.setattr(web_server, "_SESSION_TOKEN", "a" * 43)
+ signed_in = web_session_sockets.token_digest("a" * 43)
+
+ class _Socket:
+ async def close(self, code=1000, reason=""):
+ pass
+
+ class _Peer:
+ def __init__(self, ws=None):
+ self.ws = ws
+
+ def write(self, obj):
+ return True
+
+ tab = _Peer(_Socket())
+
+ async def admit(): # sockets are tracked from the server's loop
+ web_session_sockets.track(tab.ws, signed_in)
+
+ asyncio.run(admit())
+
+ def ticket(peer):
+ observed = server.dispatch({"jsonrpc": "2.0", "id": 11, "method": "display.observe", "params": {}}, peer)
+ return ws_tickets.consume_ticket(observed["result"]["ticket"])
+
+ assert ticket(tab)["admitted_with"] == signed_in
+ assert "admitted_with" not in ticket(_Peer())
+ assert "admitted_with" not in ticket(_Peer(_Socket())) # a socket sign-out does not cover
+
+
def test_observe_mints_the_viewer_id_and_status_never_discloses_the_holder(monkeypatch, tmp_path):
"""A client cannot choose its viewer id (it would impersonate the holder and co-drive or release
their lease), and no snapshot or broadcast carries the raw holder id — only a hash the holder
diff --git a/tui_gateway/methods_display.py b/tui_gateway/methods_display.py
index 7cca148ee32..1f30d87b326 100644
--- a/tui_gateway/methods_display.py
+++ b/tui_gateway/methods_display.py
@@ -154,14 +154,19 @@ def _(rid, params: dict) -> dict:
who passes it to ``display.lease.acquire`` / ``release``) so the lease can name the holder."""
from hermes_constants import get_hermes_home
from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ from hermes_cli.web_session_sockets import admission_of
from tools.bot_desktop import runtime as _bd_runtime
try:
# The bridge dials either the host RFB socket or the sandbox relay; neither exists before start.
if _bd_runtime.rfb_socket_path() is None and not _bd_runtime.sandbox_screen_running():
return _err(rid, _DISPLAY_ERR, "this profile's Bot Desktop is not running; call display.start first")
viewer_id = _mint_viewer_id(str(params.get("viewer_id") or "").strip())
- ticket = mint_ticket(user_id=f"display:{viewer_id}", provider="bot-desktop",
- extra={"hermes_home": str(get_hermes_home()), "viewer_id": viewer_id})
+ extra = {"hermes_home": str(get_hermes_home()), "viewer_id": viewer_id}
+ # A viewer a browser tab opens watches and can drive this screen: it signs out with that tab,
+ # so the ticket carries the credential digest the tab's socket was admitted with.
+ if (admitted := admission_of(getattr(current_transport(), "ws", None))) is not None:
+ extra["admitted_with"] = admitted
+ ticket = mint_ticket(user_id=f"display:{viewer_id}", provider="bot-desktop", extra=extra)
return _ok(rid, {"ticket": ticket, "path": "/api/display/ws", "viewer_id": viewer_id,
**_display_snapshot()})
except Exception as e:
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 769ac943e76..527e88cec00 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -224,6 +224,11 @@ class WSTransport:
def closed(self) -> bool:
return self._closed
+ @property
+ def ws(self) -> Any:
+ """The WebSocket this transport writes to (what sign-out tracks a browser tab by)."""
+ return self._ws
+
async def write_async(self, obj: dict) -> bool:
"""Send from the owning loop; awaits until the frame is on the wire. Buffered tokens are flushed
ahead of it in the SAME batch so nothing slips between."""