The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): serve the Webapp from the gateway's own listener
emozillafff24cff13cb
diff --git a/gateway/run_api.py b/gateway/run_api.pyindex cbb599dcacc..a8f9e4156cd 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -40,7 +40,8 @@ class GatewayDashboardMount:``state`` is the listener's boundary state (``bound_host``, ``bound_port``, ``auth_required``,``trusted_public_hosts``, ``gateway_runner``, ``session_authority``) — what the native WebSocket- path checks, mirrored onto the dashboard app state once it is mounted.+ path checks, mirrored onto the dashboard app state once it is mounted. ``state.webapp`` (a+ ``gateway.webapp_listener.WebappMount``) makes the mount serve the browser-hosted Desktop."""def __init__(self, runner, state):@@ -49,6 +50,7 @@ class GatewayDashboardMount:self._lock: asyncio.Lock | None = Noneself._lifespan = Noneself._closed = False+ self._replaced_session_token = None@propertydef loaded(self) -> bool:@@ -70,12 +72,26 @@ class GatewayDashboardMount:web.app.state.session_authority = getattr(self.runner, "session_authority", None)web.app.state.bound_host = self._state.bound_hostweb.app.state.bound_port = self._state.bound_port+ webapp = getattr(self._state, "webapp", None)+ if webapp is not None:+ # The browser-hosted Desktop: its bundle at /, its routes (launch handoff, socket tickets,+ # host terminal) on, and the browser credential kept in the home so tabs survive a restart.+ # The page itself still never carries the credential (the webapp surface withholds it).+ from gateway.webapp_listener import browser_session_token+ web.app.state.ui_surface = "webapp"+ web.app.state.web_dist = webapp.dist+ self._replaced_session_token = web._SESSION_TOKEN+ web._SESSION_TOKEN = browser_session_token(webapp.home)def _unbind_state(self) -> None:if self.web is not None:self.web.app.state.gateway_runner = Noneself.web.app.state.session_authority = Noneself.web.app.state.withhold_session_token = False+ if self._replaced_session_token is not None:+ self.web.app.state.ui_surface = None+ self.web.app.state.web_dist = None+ self.web._SESSION_TOKEN, self._replaced_session_token = self._replaced_session_token, Noneasync def ensure(self):"""Import (off the loop), bind and start the dashboard app once; returns ``web_server``."""@@ -135,8 +151,9 @@ class GatewayDashboardMount:await web.app(scope, receive, send)-async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -> GatewayAPIHandle:+async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0, webapp=None) -> GatewayAPIHandle:global _ACTIVE_RUNNER+ from gateway.webapp_listener import dial_originfrom hermes_cli.web_server_boundary import _dashboard_public_hosts, listener_auth_requiredfrom hermes_cli.web_server_lifecycle import build_listener_server@@ -150,7 +167,7 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -state = types.SimpleNamespace(bound_host=host, bound_port=None, auth_required=listener_auth_required(host, trusted),trusted_public_hosts=trusted, gateway_runner=runner,- session_authority=getattr(runner, "session_authority", None))+ session_authority=getattr(runner, "session_authority", None), webapp=webapp)mount = GatewayDashboardMount(runner, state)# Lifespan off: the dashboard's own lifespan runs when it is mounted (GatewayDashboardMount).config, server = build_listener_server(mount, host, port, auth_required=state.auth_required,@@ -169,8 +186,9 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -config.load()config.loaded_app = GatewayRuntimeAPI(config.loaded_app, runner, mount)# A gated listener needs the dashboard's auth providers (and refuses to start without one);- # an already-imported dashboard costs nothing to mount now.- if state.auth_required or loaded_web is not None:+ # an already-imported dashboard costs nothing to mount now; the Webapp serves its page and+ # mints launch links from the start.+ if state.auth_required or loaded_web is not None or webapp is not None:await mount.ensure()server.lifespan = config.lifespan_class(config)await server.startup(sockets=[listener])@@ -197,9 +215,8 @@ async def start_gateway_api(runner, *, host: str = "127.0.0.1", port: int = 0) -_ACTIVE_RUNNER = Nonetask = asyncio.create_task(serve(), name="gateway-api")- origin_host = f"[{host}]" if ":" in host else hostreturn GatewayAPIHandle(- api_origin=f"http://{origin_host}:{state.bound_port}",+ api_origin=dial_origin(host, state.bound_port),server=server, task=task, app=mount, socket=listener,)diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 49f4233a47c..d2c3cb74691 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -495,8 +495,31 @@ async def recover_bot_mailbox(authority):async def start_gateway_runtime_api(runner):- from gateway.run_api import start_gateway_api- runner.session_api = await start_gateway_api(runner)+ from gateway import run_api+ from gateway.webapp_listener import dial_origin, listener_plan, register_control_verbs+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ host, port, webapp = listener_plan(home)+ runner.webapp_status = {"state": "off", "url": None, "reason": None}+ try:+ # Without the Webapp the listener is main's: the same call, a private ephemeral port.+ runner.session_api = await (run_api.start_gateway_api(runner, host=host, port=port, webapp=webapp)+ if webapp is not None else run_api.start_gateway_api(runner))+ except Exception as exc:+ if webapp is None:+ raise+ # The Webapp's listener could not start (port taken, address unavailable, a wildcard bind+ # with no dashboard sign-in provider): native clients still need this gateway, so it keeps+ # main's private listener and reports why the Webapp is not served.+ cause = (exc.strerror or exc) if isinstance(exc, OSError) else exc+ reason = f"could not listen on {host}:{port} ({cause})"+ logger.error("Webapp unavailable: %s", reason)+ runner.webapp_status = {"state": "unavailable", "url": None, "reason": reason}+ runner.session_api = await run_api.start_gateway_api(runner)+ else:+ if webapp is not None:+ runner.webapp_status = {"state": "serving", "url": dial_origin(host, port), "reason": None}+ register_control_verbs(runner, home)runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_originfor authority in _authorities(runner):await _recover_profile_bot_mailbox(runner, authority)diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.pynew file mode 100644index 00000000000..9567ce3746a--- /dev/null+++ b/gateway/webapp_listener.py@@ -0,0 +1,209 @@+"""The browser-hosted Desktop (Webapp) on the gateway's own HTTP listener.++``webapp.enabled`` in the gateway home's ``config.yaml`` turns it on. The gateway then binds its one+listener to ``webapp.host``/``webapp.port`` (a stable port, so the browser's URL survives restarts) and+its dashboard mount serves the Webapp bundle. ``webapp.host`` is a loopback address or a wildcard+(``0.0.0.0``/``::``), and a wildcard bind is gated by dashboard sign-in like any non-loopback listener.+Native clients (Desktop, the CLI, Ink) dial the loopback address this module derives from the bind.++The browser's credential is the dashboard session token. With the Webapp on, the gateway keeps that+token in a user-only file in its home, so open tabs keep working across a gateway restart; signing out+replaces the file.+"""+from __future__ import annotations++import ipaddress+import logging+import re+import secrets+import sys+from dataclasses import dataclass+from pathlib import Path++logger = logging.getLogger(__name__)++DEFAULT_HOST = "127.0.0.1"+DEFAULT_PORT = 9120+TOKEN_PATH = Path("webapp") / "session-token"+# secrets.token_urlsafe(32); the launch page refuses any other shape.+_TOKEN_FORMAT = re.compile(r"[A-Za-z0-9_-]{43}")+++@dataclass(frozen=True)+class WebappSettings:+ enabled: bool = False+ host: str = DEFAULT_HOST+ port: int = DEFAULT_PORT++ @property+ def bind(self) -> tuple[str, int]:+ """The listener's bind address: the configured one with the Webapp on, else a private+ loopback listener on an ephemeral port (main's default)."""+ return (self.host, self.port) if self.enabled else (DEFAULT_HOST, 0)+++@dataclass(frozen=True)+class WebappMount:+ """What the gateway's dashboard mount needs to serve the Webapp: the built bundle and the home+ whose browser credential it uses."""+ dist: Path+ home: Path+++def _config_document(home: Path) -> dict:+ """*home*'s config: the merged one (managed overlay, ``${ENV}`` expansion) for this process's own+ home, which is always the case in the gateway; otherwise that home's file as written, which only+ ``hermes webapp`` reads, about the gateway it targets, before asking that gateway itself."""+ from hermes_cli.config import load_config_readonly, read_user_config_raw+ from hermes_constants import get_hermes_home+ try:+ own = home.resolve() == Path(get_hermes_home()).resolve()+ except OSError:+ own = False+ return load_config_readonly() if own else read_user_config_raw(home / "config.yaml")+++def webapp_settings(home) -> WebappSettings:+ """``webapp:`` from *home*'s config. A missing, unreadable or malformed block reads as off, so a+ typo never exposes the listener."""+ path = Path(home) / "config.yaml"+ from ruamel.yaml.error import YAMLError+ try:+ document = _config_document(Path(home))+ except (OSError, ValueError, YAMLError) as exc: # the gateway's own config load reports it+ logger.warning("Webapp stays off: %s could not be read (%s)", path, exc)+ return WebappSettings()+ block = document.get("webapp") if isinstance(document, dict) else None+ if block is None:+ return WebappSettings()+ if not isinstance(block, dict):+ logger.warning("Webapp stays off: webapp in %s must be a mapping", path)+ return WebappSettings()+ enabled = block.get("enabled", False)+ if enabled is False:+ return WebappSettings()+ if enabled is not True:+ logger.warning("Webapp stays off: webapp.enabled must be true or false in %s", path)+ return WebappSettings()+ host = block.get("host", DEFAULT_HOST)+ port = block.get("port", DEFAULT_PORT)+ if not isinstance(host, str) or not (_is_loopback(host.strip()) or _is_wildcard(host.strip())):+ logger.warning("Webapp stays off: webapp.host must be a loopback address, 0.0.0.0 or :: in %s", path)+ return WebappSettings()+ if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535:+ logger.warning("Webapp stays off: webapp.port must be a port number (1-65535) in %s", path)+ return WebappSettings()+ return WebappSettings(enabled=True, host=host.strip(), port=port)+++def _is_loopback(host: str) -> bool:+ if host == "localhost":+ return True+ try:+ return ipaddress.ip_address(host.strip("[]")).is_loopback+ except ValueError:+ return False+++def _is_wildcard(host: str) -> bool:+ return host in {"0.0.0.0", "::"}+++def dial_host(bind_host: str) -> str:+ """The loopback address native clients dial for a listener bound to *bind_host*."""+ if _is_loopback(bind_host):+ return bind_host+ return "::1" if bind_host == "::" else "127.0.0.1"+++def dial_origin(bind_host: str, port: int) -> str:+ """The ``api_origin`` native clients get for a listener bound to *bind_host*."""+ host = dial_host(bind_host)+ return f"http://[{host}]:{port}" if ":" in host else f"http://{host}:{port}"+++def listener_plan(home) -> tuple[str, int, WebappMount | None]:+ """The gateway listener's ``(host, port, webapp)`` for the gateway serving *home*."""+ settings = webapp_settings(home)+ if not settings.enabled:+ return (*settings.bind, None)+ from hermes_cli.config import get_project_root+ from hermes_cli.webapp import webapp_dist_dir+ return (*settings.bind, WebappMount(dist=webapp_dist_dir(get_project_root()), home=Path(home)))+++def browser_session_token(home, *, rotate: bool = False) -> str:+ """The dashboard session token a Webapp browser holds, kept user-only in *home*.++ Created on first use; *rotate* replaces it, which signs every open tab out."""+ from utils import atomic_write_text++ path = Path(home) / TOKEN_PATH+ if not rotate:+ try:+ token = path.read_text(encoding="utf-8-sig").strip()+ except OSError:+ token = ""+ if _TOKEN_FORMAT.fullmatch(token):+ return token+ token = secrets.token_urlsafe(32)+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)+ atomic_write_text(path, token + "\n", mode=0o600)+ return token+++def _one_use_links_work() -> bool:+ """Whether a browser can redeem a one-use launch link here. Redemption needs proof that the+ browser's connection belongs to the gateway's OS user (``web_routers.webapp._peer_is_server_user``),+ which macOS cannot give, and a browser launcher's arguments are not private to the user there."""+ return sys.platform != "darwin"+++def register_control_verbs(runner, home) -> None:+ """The private control-socket verbs ``hermes webapp`` uses; only an authenticated same-user peer+ reaches them. ``webapp-launch`` returns a one-use launch link, so the credential crosses neither+ the socket nor a browser's argv; where such a link cannot be redeemed (macOS) it returns the+ private credential link instead, for the user to open by hand. ``webapp-sign-out`` replaces the+ browser credential."""+ server = getattr(runner, "session_control_server", None)+ if server is None:+ return++ def serving():+ status = runner.webapp_status+ if status["state"] == "off":+ raise RuntimeError("The Webapp is off. Set webapp.enabled: true in config.yaml and restart the gateway.")+ if status["state"] != "serving":+ raise RuntimeError(f"The Webapp is unavailable: {status['reason']}")+ web = getattr(getattr(getattr(runner, "session_api", None), "app", None), "web", None)+ if web is None:+ raise RuntimeError("The Webapp is still starting; try again.")+ return status, web++ def webapp_status(_params, _peer):+ return dict(runner.webapp_status)++ def webapp_launch(params, _peer):+ from urllib.parse import urlencode++ from hermes_cli.web_routers.webapp import LAUNCH_TICKET_TTL_SECONDS, mint_launch_ticket+ from hermes_constants import PROFILE_ID_RE+ profile = params.get("profile")+ if profile is not None and not (isinstance(profile, str) and PROFILE_ID_RE.match(profile)):+ raise ValueError("profile must be a profile name")+ query = f"?profile={profile}" if profile else "" # the page opens on that profile+ status, web = serving()+ if not _one_use_links_work():+ return {"url": f"{status['url']}/{query}#hermes-session={web._SESSION_TOKEN}", "private": True,+ "expires_in_seconds": None}+ fragment = urlencode({"ticket": mint_launch_ticket(web.app.state), **({"query": query} if query else {})})+ return {"url": f"{status['url']}/webapp/launch#{fragment}", "private": False,+ "expires_in_seconds": LAUNCH_TICKET_TTL_SECONDS}++ def webapp_sign_out(_params, _peer):+ _, web = serving()+ web._SESSION_TOKEN = browser_session_token(home, rotate=True)+ return {"signed_out": True}++ server.private_handlers.update({+ "webapp-status": webapp_status, "webapp-launch": webapp_launch, "webapp-sign-out": webapp_sign_out})diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 0a881fae506..3c9ec7b758f 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -995,7 +995,7 @@ DEFAULT_CONFIG = {"unicode_cols": 0, # Hard override for terminal column width; 0 = derive from scale.},},-+ "webapp": {"enabled": False, "host": "127.0.0.1", "port": 9120}, # gateway/webapp_listener.py"dashboard": {# Visual theme: "default" | "midnight" | "ember" | "mono" | "cyberpunk" | "rose""theme": "default",diff --git a/hermes_cli/web_server_app.py b/hermes_cli/web_server_app.pyindex 590b62407d9..e87cb3207c6 100644--- a/hermes_cli/web_server_app.py+++ b/hermes_cli/web_server_app.py@@ -200,8 +200,11 @@ async def standalone_lifespan(app: "FastAPI"):@asynccontextmanagerasync def http_lifespan(app: FastAPI):"""The gateway already owns schema, rooms, scheduler and model services."""+ from contextlib import AsyncExitStack+from hermes_cli.web_server import _dashboard_selftest_loopfrom hermes_cli.web_server_chat import PTY_REGISTRY+ from hermes_cli.web_server_surface import policyapp.state.event_channels = {}app.state.event_lock = asyncio.Lock()@@ -213,7 +216,11 @@ async def http_lifespan(app: FastAPI):asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),]try:- yield+ async with AsyncExitStack() as surface:+ if policy(app.state).host_terminal:+ from hermes_cli.web_host_terminal_sessions import host_terminal_lifespan+ await surface.enter_async_context(host_terminal_lifespan(app))+ yieldfinally:for task in tasks:task.cancel()diff --git a/tests/gateway/fixtures/webapp_listener_peer.py b/tests/gateway/fixtures/webapp_listener_peer.pynew file mode 100644index 00000000000..82d4796052a--- /dev/null+++ b/tests/gateway/fixtures/webapp_listener_peer.py@@ -0,0 +1,111 @@+"""Start the gateway listener with the Webapp on or off; report what a browser and a native client get.++Run as ``python webapp_listener_peer.py on|off <port> <dist>`` with an isolated ``HERMES_HOME``. Writes+``receipt.json`` there (the gateway redirects stdout). No external inference: the model points at a closed+port and no turn is submitted.+"""+import asyncio+import json+import os+from pathlib import Path+import sys+import traceback++SEEDED_TOKEN = "seeded-browser-credential-from-an-earlier-0" # 43 URL-safe characters+++async def probe(mode, port, dist):+ import httpx+ from websockets.asyncio.client import connect++ from gateway.control_socket import GatewayControlServer+ from gateway.run import GatewayRunner+ from gateway.run_api import stop_gateway_api+ from gateway.run_runtime import start_gateway_runtime_api+ from gateway.session_authority import initialize_session_authority+ from gateway.webapp_listener import TOKEN_PATH+ import hermes_cli.webapp+ from tests.gateway.fixtures.local_recovery_probe import rpc++ home = Path(os.environ["HERMES_HOME"])+ webapp_block = f"webapp:\n enabled: true\n port: {port}\n" if mode == "on" else ""+ (home / "config.yaml").write_text(+ "gateway:\n multiplex_profiles: false\nmodel:\n provider: custom\n default: no-inference\n"+ " base_url: http://127.0.0.1:1/v1\nauxiliary:\n title_generation:\n enabled: false\n" + webapp_block)+ if mode == "on":+ (home / TOKEN_PATH).parent.mkdir(parents=True, exist_ok=True)+ (home / TOKEN_PATH).write_text(SEEDED_TOKEN + "\n", encoding="utf-8")+ hermes_cli.webapp.webapp_dist_dir = lambda _root: Path(dist) # the built bundle, without a build+ runner = GatewayRunner()+ runner.session_control_server = GatewayControlServer(home) # verbs only; not listening+ # Set by the gateway bootstrap, which this fixture skips; the gateway is up.+ runner.session_runtime_descriptor = {"runtime_protocol": 1, "state": "ready", "capabilities": [],+ "served_profiles": []}+ await initialize_session_authority(runner, profile_id=str(home), instance_id="webapp-listener")+ await start_gateway_runtime_api(runner)+ api = runner.session_api+ from hermes_cli import web_server++ def ask(verb):+ raw = json.dumps({"protocol": 1, "verb": verb, "id": 1, "params": {}}).encode()+ return json.loads(runner.session_control_server.handle_request_line(raw, "fixture-same-user"))++ report = {"api_origin": api.api_origin, "status": ask("webapp-status").get("result")}+ origin = api.api_origin+ try:+ async with httpx.AsyncClient(base_url=origin, timeout=20) as client:+ index = await client.get("/")+ report["index_status"] = index.status_code+ report["index_is_webapp"] = "WEBAPP_BUNDLE" in index.text+ report["index_carries_token"] = web_server._SESSION_TOKEN in index.text+ report["surface"] = getattr(web_server.app.state, "ui_surface", None)+ report["host_terminals"] = hasattr(web_server.app.state, "host_terminals")+ report["session_token_is_seeded"] = web_server._SESSION_TOKEN == SEEDED_TOKEN+ report["token_file"] = (home / TOKEN_PATH).exists()+ minted = await client.post("/api/webapp/gateway-ticket",+ headers={"X-Hermes-Session-Token": web_server._SESSION_TOKEN})+ report["ticket_status"] = minted.status_code+ if minted.status_code == 200:+ ticket = minted.json()["ticket"]+ url = origin.replace("http:", "ws:") + "/api/ws?native_dial=browser"+ async with connect(url, origin=origin,+ subprotocols=["hermes-gateway-v1", f"hermes-gateway-ticket.{ticket}"]) as ws:+ created = await rpc(ws, "session.create", request_id="browser-create", source="gui",+ toolsets=[])+ report["browser_session"] = "result" in created+ launched = ask("webapp-launch")+ report["launch_ok"] = launched["ok"]+ if launched["ok"]:+ url = launched["result"]["url"]+ report["launch_page"] = url.split("#", 1)[0] == origin + "/webapp/launch"+ report["launch_private"] = launched["result"]["private"]+ ticket = url.split("#ticket=", 1)[1]+ handoff = {"X-Hermes-Window-Ticket": ticket, "Origin": origin}+ redeemed = await client.post("/webapp/window-session", headers=handoff)+ report["handoff_status"] = redeemed.status_code+ report["handoff_gives_credential"] = redeemed.status_code == 200 and (+ redeemed.json()["token"] == SEEDED_TOKEN)+ report["handoff_reuse_status"] = (+ await client.post("/webapp/window-session", headers=handoff)).status_code+ report["sign_out_ok"] = ask("webapp-sign-out")["ok"]+ stale = await client.post("/api/webapp/gateway-ticket",+ headers={"X-Hermes-Session-Token": SEEDED_TOKEN})+ report["old_credential_status"] = stale.status_code+ report["token_file_rotated"] = (home / TOKEN_PATH).read_text().strip() not in {"", SEEDED_TOKEN}+ finally:+ await stop_gateway_api(api)+ report["host_terminals_after_stop"] = hasattr(web_server.app.state, "host_terminals")+ return report+++def main():+ receipt = Path(os.environ["HERMES_HOME"]) / "receipt.json"+ try:+ receipt.write_text(json.dumps(asyncio.run(probe(sys.argv[1], int(sys.argv[2]), sys.argv[3]))))+ except BaseException:+ receipt.write_text(json.dumps({"error": traceback.format_exc()}))+ raise SystemExit(1)+++if __name__ == "__main__":+ main()diff --git a/tests/gateway/test_gateway_serves_webapp.py b/tests/gateway/test_gateway_serves_webapp.pynew file mode 100644index 00000000000..04c0b97b563--- /dev/null+++ b/tests/gateway/test_gateway_serves_webapp.py@@ -0,0 +1,106 @@+"""The gateway's own listener serves the browser-hosted Desktop when ``webapp.enabled`` is on.++With it on, the dashboard mount serves the Webapp bundle without the session token in the page, the+browser credential is the one kept in the gateway home (so it survives a restart), the host terminal+registry runs, and a browser holding that credential gets a socket ticket and opens a gateway session+on the same origin. The launcher's link comes over the control socket and spends once; signing out+replaces the credential. With it off, the listener is main's private one: no Webapp surface, no ticket+route, no credential file, no launch link.+"""+import json+from pathlib import Path+import socket+import subprocess+import sys++import pytest++from tests.gateway.fixtures.local_recovery_probe import child_env+++def _free_port() -> int:+ with socket.socket() as probe:+ probe.bind(("127.0.0.1", 0))+ return probe.getsockname()[1]+++def _run(tmp_path, mode):+ root = Path(__file__).resolve().parents[2]+ home, user, dist = tmp_path / "state", tmp_path / "user", tmp_path / "dist-webapp"+ for path in (home, user, dist):+ path.mkdir()+ (dist / "index.html").write_text("<!doctype html><html><body>WEBAPP_BUNDLE</body></html>", encoding="utf-8")+ port = _free_port()+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ PYTHONUNBUFFERED="1")+ result = subprocess.run(+ [sys.executable, str(root / "tests/gateway/fixtures/webapp_listener_peer.py"), mode, str(port), str(dist)],+ cwd=root, env=env, capture_output=True, text=True, timeout=120, check=False)+ receipt = home / "receipt.json"+ assert result.returncode == 0, result.stdout + result.stderr + (receipt.read_text() if receipt.exists() else "")+ return port, json.loads(receipt.read_text())++[email protected](scope="module")+def webapp_on(tmp_path_factory):+ return _run(tmp_path_factory.mktemp("webapp-on"), "on")++[email protected](scope="module")+def webapp_off(tmp_path_factory):+ return _run(tmp_path_factory.mktemp("webapp-off"), "off")+++def test_the_listener_binds_the_configured_port_and_native_clients_dial_it(webapp_on):+ port, report = webapp_on+ assert report["api_origin"] == f"http://127.0.0.1:{port}"+++def test_the_listener_serves_the_webapp_bundle_without_the_credential(webapp_on):+ _, report = webapp_on+ assert (report["index_status"], report["index_is_webapp"]) == (200, True)+ assert report["index_carries_token"] is False+ assert report["surface"] == "webapp"+++def test_the_browser_credential_survives_a_gateway_restart(webapp_on):+ _, report = webapp_on+ assert report["session_token_is_seeded"] is True+++def test_the_host_terminal_runs_with_the_listener(webapp_on):+ _, report = webapp_on+ assert report["host_terminals"] is True+ assert report["host_terminals_after_stop"] is False+++def test_a_browser_with_the_credential_opens_a_gateway_session(webapp_on):+ _, report = webapp_on+ assert report["ticket_status"] == 200+ assert report["browser_session"] is True+++def test_the_launch_link_from_the_control_socket_hands_over_the_credential_once(webapp_on):+ port, report = webapp_on+ assert report["status"] == {"state": "serving", "url": f"http://127.0.0.1:{port}", "reason": None}+ assert (report["launch_ok"], report["launch_page"], report["launch_private"]) == (True, True, False)+ assert (report["handoff_status"], report["handoff_gives_credential"]) == (200, True)+ assert report["handoff_reuse_status"] == 403+++def test_signing_out_cuts_off_the_old_browser_credential(webapp_on):+ _, report = webapp_on+ assert report["sign_out_ok"] is True+ assert report["old_credential_status"] == 401+ assert report["token_file_rotated"] is True+++def test_without_the_webapp_the_listener_stays_mains_private_one(webapp_off):+ _, report = webapp_off+ assert report["index_is_webapp"] is False+ assert report["surface"] != "webapp"+ assert report["host_terminals"] is False+ assert report["token_file"] is False+ assert report["ticket_status"] in {403, 404}+ assert report["status"] == {"state": "off", "url": None, "reason": None}diff --git a/tests/gateway/test_webapp_listener.py b/tests/gateway/test_webapp_listener.pynew file mode 100644index 00000000000..47f1bd332fa--- /dev/null+++ b/tests/gateway/test_webapp_listener.py@@ -0,0 +1,223 @@+"""The browser-hosted Desktop on the gateway's own listener: config, bind address and browser credential.++``webapp.enabled`` in the gateway home's ``config.yaml`` turns it on; the gateway then binds its one HTTP+listener to ``webapp.port`` on a loopback or wildcard ``webapp.host``, and native clients keep dialling a+loopback address.+"""+import asyncio+import errno+import json+import os+import re+import stat+from types import SimpleNamespace++import pytest++from gateway import webapp_listener as webapp+++def _home(tmp_path, config=None):+ home = tmp_path / "home"+ home.mkdir(parents=True)+ if config is not None:+ (home / "config.yaml").write_text(config, encoding="utf-8")+ return home+++def test_the_webapp_stays_off_until_config_turns_it_on(tmp_path):+ off = webapp.webapp_settings(_home(tmp_path))+ assert (off.enabled, off.bind) == (False, ("127.0.0.1", 0))+++def test_an_enabled_webapp_binds_its_configured_address(tmp_path):+ on = webapp.webapp_settings(_home(tmp_path, "webapp:\n enabled: true\n host: 0.0.0.0\n port: 9555\n"))+ assert (on.enabled, on.bind) == (True, ("0.0.0.0", 9555))+ default = webapp.webapp_settings(_home(tmp_path / "d", "webapp:\n enabled: true\n"))+ assert default.bind == ("127.0.0.1", webapp.DEFAULT_PORT)++[email protected]("block", [+ "webapp: yes\n",+ "webapp:\n enabled: true\n port: 70000\n",+ "webapp:\n enabled: true\n port: http\n",+ "webapp:\n enabled: true\n host: ''\n",+ "webapp:\n enabled: 'true'\n",+ "webapp:\n enabled: true\n host: 192.168.1.20\n",+ "webapp:\n enabled: true\n host: hermes.example.net\n",+])+def test_a_malformed_webapp_block_keeps_the_listener_private(tmp_path, block):+ settings = webapp.webapp_settings(_home(tmp_path, block))+ assert settings.bind == ("127.0.0.1", 0)++[email protected](("bind", "dial"), [+ ("127.0.0.1", "127.0.0.1"),+ ("localhost", "localhost"),+ ("::1", "::1"),+ ("0.0.0.0", "127.0.0.1"),+ ("::", "::1"),+])+def test_native_clients_dial_loopback_whatever_the_browser_bind(bind, dial):+ assert webapp.dial_host(bind) == dial++[email protected](("bind", "origin"), [+ ("127.0.0.1", "http://127.0.0.1:9120"),+ ("0.0.0.0", "http://127.0.0.1:9120"),+ ("::", "http://[::1]:9120"),+ ("::1", "http://[::1]:9120"),+])+def test_the_advertised_api_origin_is_the_loopback_dial_address(bind, origin):+ assert webapp.dial_origin(bind, 9120) == origin+++def test_a_gateway_restart_keeps_the_browser_credential(tmp_path):+ home = _home(tmp_path)+ first = webapp.browser_session_token(home)+ assert len(first) >= 43+ assert webapp.browser_session_token(home) == first+ if os.name != "nt":+ assert stat.S_IMODE((home / webapp.TOKEN_PATH).stat().st_mode) == 0o600+++def test_signing_out_replaces_the_browser_credential(tmp_path):+ home = _home(tmp_path)+ first = webapp.browser_session_token(home)+ second = webapp.browser_session_token(home, rotate=True)+ assert second != first+ assert webapp.browser_session_token(home) == second++[email protected]("stored", ["short", "x" * 60, "not/url+safe" + "a" * 31])+def test_a_credential_the_browser_would_refuse_is_replaced(tmp_path, stored):+ home = _home(tmp_path)+ (home / webapp.TOKEN_PATH).parent.mkdir(parents=True)+ (home / webapp.TOKEN_PATH).write_text(stored + "\n", encoding="utf-8")+ token = webapp.browser_session_token(home)+ assert token != stored+ assert re.fullmatch(r"[A-Za-z0-9_-]{43}", token)+++def _start_runtime_api(monkeypatch, tmp_path, config, *, busy=False, refuse=None):+ from gateway import run_api, run_runtime+ home = _home(tmp_path, config)+ monkeypatch.setenv("HERMES_HOME", str(home))+ calls = []++ async def start(runner, *, host="127.0.0.1", port=0, webapp=None):+ calls.append((host, port, webapp))+ if busy and port:+ raise OSError(errno.EADDRINUSE, "Address already in use")+ if refuse is not None and webapp is not None:+ raise refuse+ return SimpleNamespace(api_origin=f"http://127.0.0.1:{port or 50001}")++ monkeypatch.setattr(run_api, "start_gateway_api", start)+ from gateway.control_socket import GatewayControlServer+ runner = SimpleNamespace(session_runtime_descriptor={}, session_authorities=[],+ session_control_server=GatewayControlServer(home))+ asyncio.run(run_runtime.start_gateway_runtime_api(runner))+ return runner, calls, home+++def _ask(runner, verb, peer="same-user-peer", params=None):+ raw = json.dumps({"protocol": 1, "verb": verb, "id": 1, "params": params or {}}).encode()+ return json.loads(runner.session_control_server.handle_request_line(raw, peer))+++def test_the_gateway_listens_on_the_webapp_port_when_enabled(monkeypatch, tmp_path):+ runner, calls, home = _start_runtime_api(monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n")+ [(host, port, mount)] = calls+ assert (host, port) == ("127.0.0.1", 9555)+ assert (mount.home, mount.dist.name) == (home, "dist-webapp")+ assert runner.webapp_status == {"state": "serving", "url": "http://127.0.0.1:9555", "reason": None}+++def test_a_busy_webapp_port_still_leaves_native_clients_a_listener(monkeypatch, tmp_path):+ runner, calls, _ = _start_runtime_api(+ monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n", busy=True)+ assert [(host, port) for host, port, _ in calls] == [("127.0.0.1", 9555), ("127.0.0.1", 0)]+ assert calls[1][2] is None+ assert runner.session_runtime_descriptor["api_origin"] == "http://127.0.0.1:50001"+ assert runner.webapp_status["state"] == "unavailable"+ assert "127.0.0.1:9555" in runner.webapp_status["reason"]+++def test_a_gateway_without_the_webapp_starts_mains_private_listener(monkeypatch, tmp_path):+ runner, calls, _ = _start_runtime_api(monkeypatch, tmp_path, None)+ assert calls == [("127.0.0.1", 0, None)]+ assert runner.webapp_status == {"state": "off", "url": None, "reason": None}+++def test_the_launcher_reads_the_webapp_state_from_its_gateway(monkeypatch, tmp_path):+ off, _, _ = _start_runtime_api(monkeypatch, tmp_path / "off", None)+ assert _ask(off, "webapp-status")["result"] == {"state": "off", "url": None, "reason": None}+ busy, _, _ = _start_runtime_api(+ monkeypatch, tmp_path / "busy", "webapp:\n enabled: true\n port: 9555\n", busy=True)+ status = _ask(busy, "webapp-status")["result"]+ assert status["state"] == "unavailable" and "127.0.0.1:9555" in status["reason"]+++def test_a_gateway_not_serving_the_webapp_mints_no_launch_link(monkeypatch, tmp_path):+ off, _, _ = _start_runtime_api(monkeypatch, tmp_path / "off", None)+ refused = _ask(off, "webapp-launch")+ assert refused["ok"] is False and "webapp.enabled" in refused["error"]+ busy, _, _ = _start_runtime_api(+ monkeypatch, tmp_path / "busy", "webapp:\n enabled: true\n port: 9555\n", busy=True)+ refused = _ask(busy, "webapp-launch")+ assert refused["ok"] is False and "127.0.0.1:9555" in refused["error"]++[email protected]("verb", ["webapp-status", "webapp-launch", "webapp-sign-out"])+def test_webapp_verbs_answer_only_an_authenticated_same_user_peer(monkeypatch, tmp_path, verb):+ runner, _, _ = _start_runtime_api(monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n")+ refused = _ask(runner, verb, peer=None)+ assert refused["ok"] is False and "PermissionError" in refused["error"]+++def test_where_one_use_links_cannot_be_redeemed_the_launcher_gets_the_private_link(monkeypatch, tmp_path):+ monkeypatch.setattr(webapp, "_one_use_links_work", lambda: False) # macOS+ runner, _, _ = _start_runtime_api(monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n")+ web = SimpleNamespace(_SESSION_TOKEN="s" * 43, app=SimpleNamespace(state=SimpleNamespace()))+ runner.session_api.app = SimpleNamespace(web=web)+ result = _ask(runner, "webapp-launch")["result"]+ assert result == {"url": "http://127.0.0.1:9555/#hermes-session=" + "s" * 43, "private": True,+ "expires_in_seconds": None}+ assert not getattr(web.app.state, "webapp_window_tickets", None)+++def _serving_runner(monkeypatch, tmp_path):+ runner, _, _ = _start_runtime_api(monkeypatch, tmp_path, "webapp:\n enabled: true\n port: 9555\n")+ web = SimpleNamespace(_SESSION_TOKEN="s" * 43, app=SimpleNamespace(state=SimpleNamespace()))+ runner.session_api.app = SimpleNamespace(web=web)+ return runner+++def test_a_launch_link_for_a_named_profile_opens_that_profile(monkeypatch, tmp_path):+ from urllib.parse import parse_qs+ runner = _serving_runner(monkeypatch, tmp_path)+ url = _ask(runner, "webapp-launch", params={"profile": "work"})["result"]["url"]+ page, fragment = url.split("#", 1)+ assert page == "http://127.0.0.1:9555/webapp/launch"+ assert parse_qs(fragment)["query"] == ["?profile=work"]+ monkeypatch.setattr(webapp, "_one_use_links_work", lambda: False)+ private = _ask(runner, "webapp-launch", params={"profile": "work"})["result"]["url"]+ assert private == "http://127.0.0.1:9555/?profile=work#hermes-session=" + "s" * 43++[email protected]("profile", ["../etc", "a b", "", "x" * 65, 7])+def test_a_launch_link_refuses_a_malformed_profile_name(monkeypatch, tmp_path, profile):+ runner = _serving_runner(monkeypatch, tmp_path)+ refused = _ask(runner, "webapp-launch", params={"profile": profile})+ assert refused["ok"] is False and "profile" in refused["error"]+++def test_a_webapp_listener_that_cannot_start_still_leaves_native_clients_a_listener(monkeypatch, tmp_path):+ refusal = RuntimeError("A non-loopback listener needs a dashboard sign-in provider")+ runner, calls, _ = _start_runtime_api(+ monkeypatch, tmp_path, "webapp:\n enabled: true\n host: 0.0.0.0\n", refuse=refusal)+ assert [(host, port) for host, port, _ in calls] == [("0.0.0.0", webapp.DEFAULT_PORT), ("127.0.0.1", 0)]+ assert runner.webapp_status["state"] == "unavailable"+ assert "sign-in provider" in runner.webapp_status["reason"]+ assert runner.session_runtime_descriptor["api_origin"] == "http://127.0.0.1:50001"