The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-screen): server-minted viewer ids; lease snapshots carry a hash, not the id
teknium1a558536e2163
diff --git a/tests/tui_gateway/test_display_methods.py b/tests/tui_gateway/test_display_methods.pyindex e6aa3287e86..67a6f207f08 100644--- a/tests/tui_gateway/test_display_methods.py+++ b/tests/tui_gateway/test_display_methods.py@@ -1,11 +1,15 @@-"""display.install runs its worker inside the caller's profile scope."""+"""display.install runs its worker inside the caller's profile scope; display.observe mints the viewer identity."""from __future__ import annotations+import hashlib+import jsonimport threadingimport pytest+from hermes_cli.dashboard_auth import ws_tickets+def test_install_worker_keeps_the_requested_profile_scope(tmp_path, monkeypatch):from hermes_constants import get_hermes_home@@ -73,3 +77,49 @@ def test_release_without_viewer_id_cannot_yank_another_viewers_lease(_fresh_leasassert _call(server, "display.lease.release", {"viewer_id": "viewer-1"})["result"]["lease"]["holder"] == _fresh_lease.AGENT_fresh_lease.acquire("viewer-2")assert _call(server, "display.lease.release", {"force": True})["result"]["lease"]["holder"] == _fresh_lease.AGENT++def _rpc(server, method, params):+ return server.handle_request({"jsonrpc": "2.0", "id": 7, "method": method, "params": params})+++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+ itself can match."""+ from tools.bot_desktop import lease, runtime+ import tui_gateway.server as server++ monkeypatch.setattr(runtime, "rfb_socket_path", lambda: tmp_path / "rfb.sock")+ lease._reset_for_tests()+ broadcasts = []+ monkeypatch.setattr(server, "_broadcast_global_event", lambda ev, payload=None: broadcasts.append((ev, payload)))+ try:+ observed = _rpc(server, "display.observe", {"viewer_id": "victim"})["result"]+ assert observed["viewer_id"] != "victim"+ assert observed["viewer_id"] and len(observed["viewer_id"]) >= 16+ assert ws_tickets.consume_ticket(observed["ticket"])["viewer_id"] == observed["viewer_id"]+ holder = observed["viewer_id"]++ # Only the connection that minted an id may reuse it (a reconnecting pane keeps its lease).+ class _Peer:+ def write(self, obj):+ return True+ mine, other = _Peer(), _Peer()+ with_mine = server.dispatch({"jsonrpc": "2.0", "id": 8, "method": "display.observe", "params": {}}, mine)["result"]+ again = server.dispatch({"jsonrpc": "2.0", "id": 9, "method": "display.observe",+ "params": {"viewer_id": with_mine["viewer_id"]}}, mine)["result"]+ assert again["viewer_id"] == with_mine["viewer_id"]+ stolen = server.dispatch({"jsonrpc": "2.0", "id": 10, "method": "display.observe",+ "params": {"viewer_id": with_mine["viewer_id"]}}, other)["result"]+ assert stolen["viewer_id"] != with_mine["viewer_id"]++ _rpc(server, "display.status", {}) # installs the broadcast listener+ lease.acquire(holder)+ status = _rpc(server, "display.status", {})["result"]+ assert status["lease"]["holder"] == lease.HUMAN+ assert holder not in json.dumps(status)+ assert status["lease"]["viewer_hash"] == hashlib.sha256(holder.encode()).hexdigest()[:12]+ lease_events = [p for ev, p in broadcasts if ev == "display.lease"]+ assert lease_events and all(holder not in json.dumps(p) for p in lease_events)+ finally:+ lease._reset_for_tests()diff --git a/tui_gateway/methods_display.py b/tui_gateway/methods_display.pyindex 37d0248dd37..38e4fba6976 100644--- a/tui_gateway/methods_display.py+++ b/tui_gateway/methods_display.py@@ -15,6 +15,7 @@ Bodies are rebound onto server.py's globals (method_ctx.bind_module) and referenimport loggingimport threading+import weakreffrom .method_ctx import HandlerRegistry, bind_module@@ -27,11 +28,23 @@ _DISPLAY_ERR = 5300_lease_listener_installed = threading.Event()+def _lease_view(lease) -> dict:+ """The lease as clients may see it: the holder's viewer id is a capability (whoever presents it+ co-drives or releases the lease), so it is replaced by a short hash the holder can match against+ its own id to know it is the one in control."""+ import hashlib+ d = lease.as_dict()+ vid = d.pop("viewer_id")+ d["viewer_id"] = None+ d["viewer_hash"] = hashlib.sha256(vid.encode()).hexdigest()[:12] if vid else None+ return d++def _display_snapshot() -> dict:from hermes_constants import hermes_home_keyfrom tools.bot_desktop import lease as _bd_lease, runtime as _bd_runtimest = _bd_runtime.status()- return {**st.as_dict(), "lease": _bd_lease.get().as_dict(), "profile_key": hermes_home_key()}+ return {**st.as_dict(), "lease": _lease_view(_bd_lease.get()), "profile_key": hermes_home_key()}def _install_lease_listener() -> None:@@ -41,7 +54,7 @@ def _install_lease_listener() -> None:from tools.bot_desktop import lease as _bd_leasedef _on_change(profile_key: str, lease) -> None:- _broadcast_global_event("display.lease", {"profile_key": profile_key, "lease": lease.as_dict()})+ _broadcast_global_event("display.lease", {"profile_key": profile_key, "lease": _lease_view(lease)})_bd_lease.on_change(_on_change)_lease_listener_installed.set() # only once the subscription exists, or a failed import would silence every client@@ -95,18 +108,39 @@ def _(rid, params: dict) -> dict:return _err(rid, _DISPLAY_ERR, str(e))+# viewer ids minted per connection (keyed by the transport that asked), so a reconnecting pane can+# keep its identity — and its lease — while nobody can claim an id minted for another connection.+_minted_viewer_ids: "weakref.WeakKeyDictionary[object, set[str]]" = weakref.WeakKeyDictionary()+++def _mint_viewer_id(requested: str) -> str:+ """Server-minted viewer identity. ``requested`` is honoured only when THIS connection minted it+ earlier; anything else (including a holder id read off display.status) gets a fresh id."""+ import secrets+ try:+ mine = _minted_viewer_ids.setdefault(current_transport(), set())+ except TypeError: # stdio / slotted transports cannot be weakly referenced: always mint+ mine = set()+ if requested in mine:+ return requested+ viewer_id = secrets.token_urlsafe(16)+ mine.add(viewer_id)+ return viewer_id++@method("display.observe")@_profile_scopeddef _(rid, params: dict) -> dict:"""Mint a single-use, 30 s ticket for ``/api/display/ws``. The ticket carries the profile home so- the bridge dials THIS profile's RFB socket, and the viewer id so the lease can name the holder."""+ the bridge dials THIS profile's RFB socket, and a server-minted viewer id (returned to the caller,+ who passes it to ``display.lease.acquire`` / ``release``) so the lease can name the holder."""from hermes_constants import get_hermes_homefrom hermes_cli.dashboard_auth.ws_tickets import mint_ticketfrom tools.bot_desktop import runtime as _bd_runtimetry:if _bd_runtime.rfb_socket_path() is None:return _err(rid, _DISPLAY_ERR, "this profile's Bot Desktop is not running; call display.start first")- viewer_id = str(params.get("viewer_id") or "").strip() or f"viewer-{rid}"+ 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})return _ok(rid, {"ticket": ticket, "path": "/api/display/ws", "viewer_id": viewer_id,