The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(webapp): API to turn the gateway's Webapp on for your network or your own URL, behind Nous sign-in
IAvecilla3c92c1a264fa
diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.pynew file mode 100644index 00000000000..2026bd33a45--- /dev/null+++ b/hermes_cli/web_routers/webapp_access.py@@ -0,0 +1,88 @@+"""Web Access routes: Desktop's Web Access pane turns the gateway-served Webapp on and off here.++Thin HTTP over :mod:`hermes_cli.webapp_access`. Every handler acts on the home of the gateway that+serves the requested profile; start and stop write its ``webapp:`` config and restart that gateway,+which reads the config only when it starts.+"""++from __future__ import annotations++import asyncio+from contextlib import contextmanager+from typing import Any, Callable, Optional++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel++from hermes_cli import webapp_access+from hermes_cli.web_deps import late+from hermes_cli.web_routers._common import _profile_scope, config_write_scope, destructive_profile++_restart_gateway_after = late("_restart_gateway_after", "hermes_cli.web_server_gateway")++router = APIRouter()+++class StartBody(BaseModel):+ mode: str+ public_url: Optional[str] = None+++@contextmanager+def _gateway_scope(profile: Optional[str], *, config_write: bool):+ """Scope to the home of the gateway serving *profile*; yields that gateway's profile name."""+ from hermes_constants import profile_name_for_home++ with _profile_scope(profile):+ name = profile_name_for_home(webapp_access.gateway_home()) or profile+ with config_write_scope(name) if config_write else _profile_scope(name):+ yield name+++async def _scoped(profile: Optional[str], fn: Callable[[Optional[str]], Any], *, config_write: bool = False) -> Any:+ """Run ``fn(gateway profile)`` in the gateway's scope off the loop; access errors become 400s.+ Only a ``config.yaml`` write takes the config lock; registration waits on the portal outside it."""++ def _run():+ with _gateway_scope(profile, config_write=config_write) as gateway_profile:+ return fn(gateway_profile)++ try:+ return await asyncio.to_thread(_run)+ except webapp_access.WebappAccessError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+++def _restart(gateway_profile: Optional[str], what: str) -> dict:+ """The status after asking the gateway to restart onto the new config. A refused restart (a live+ chat) keeps the saved config and reports ``restart_error``."""+ restart = _restart_gateway_after(gateway_profile, what=what, label="Web Access")+ return {**webapp_access.access_status(), **restart}++[email protected]("/api/webapp-access/status")+async def webapp_access_status(profile: Optional[str] = None):+ return await _scoped(profile, lambda _gateway: webapp_access.access_status())++[email protected]("/api/webapp-access/start")+async def start_webapp_access(body: StartBody, profile: Optional[str] = None):+ profile = destructive_profile(profile, "POST /api/webapp-access/start")+ host, public_url = await _scoped(profile, lambda _gateway: webapp_access.register(body.mode, body.public_url))++ def _start(gateway):+ webapp_access.serve(host, public_url)+ return _restart(gateway, "turning on Web Access")++ return await _scoped(profile, _start, config_write=True)++[email protected]("/api/webapp-access/stop")+async def stop_webapp_access(profile: Optional[str] = None):+ profile = destructive_profile(profile, "POST /api/webapp-access/stop")++ def _stop(gateway):+ webapp_access.turn_off()+ return _restart(gateway, "turning off Web Access")++ return await _scoped(profile, _stop, config_write=True)diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 15b15215d40..776a6d794db 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -797,6 +797,7 @@ from hermes_cli.web_routers import (webapp as _webapp_routes,shared_metrics as _shared_metrics_routes,delegation as _delegation_routes,+ webapp_access as _webapp_access_routes,)import hermes_cli.web_routers.uploads as _upload_routes@@ -835,6 +836,7 @@ app.include_router(_dashboard_ui_routes.router)app.include_router(_webapp_routes.router)app.include_router(_shared_metrics_routes.router)app.include_router(_delegation_routes.router)+app.include_router(_webapp_access_routes.router)# Plugin API routes and the dashboard auth routes (/login, /auth/*, /api/auth/*)# mount before the SPA catch-all so /{full_path:path} doesn't swallow them. Authdiff --git a/hermes_cli/webapp_access.py b/hermes_cli/webapp_access.pynew file mode 100644index 00000000000..ff0a11c00a2--- /dev/null+++ b/hermes_cli/webapp_access.py@@ -0,0 +1,176 @@+"""Remote access to the gateway-served Webapp, for Desktop's Web Access pane.++The gateway serves the Webapp (``gateway.webapp_listener``) from the ``webapp:`` block of its home's+``config.yaml``, read when it starts, so this writes that home's config and the caller restarts the+gateway. Sign-in is the user's Nous account (a self-hosted portal client registered with the right+callback); a gated bind without it would keep the Webapp off. Two shapes:++- ``lan``: ``webapp.host: 0.0.0.0``, opened at ``http://<this machine's LAN address>:<port>``; the+ wildcard bind engages the sign-in gate and the callback is rebuilt from each request.+- ``public``: an HTTPS URL the user already runs that forwards to ``127.0.0.1:<port>``.+ ``dashboard.public_url`` engages the gate on the loopback bind and fixes the callback.+"""++from __future__ import annotations++import os+import socket+from pathlib import Path+from typing import Optional+from urllib.parse import urlsplit++from gateway.webapp_listener import DEFAULT_PORT++_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})+_PUBLIC_URL_ENV = "HERMES_DASHBOARD_PUBLIC_URL"+_CLIENT_ID_ENV = "HERMES_DASHBOARD_OAUTH_CLIENT_ID"+++class WebappAccessError(RuntimeError):+ """Remote access cannot be set up as asked; ``str(exc)`` is the user-facing reason."""+++def lan_address() -> Optional[str]:+ """This machine's primary LAN IPv4 address, or None. Connecting a UDP socket only asks the kernel+ which interface routes to a non-local address; no packet is sent."""+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as probe:+ probe.connect(("10.255.255.255", 1))+ address = probe.getsockname()[0]+ except OSError:+ return None+ return None if address.startswith("127.") or address == "0.0.0.0" else address+++def _public_url(raw: Optional[str]) -> str:+ """``https://host[:port][/prefix]`` without a trailing slash, or WebappAccessError."""+ value = (raw or "").strip().rstrip("/")+ parsed = urlsplit(value)+ if parsed.scheme != "https" or not parsed.hostname or parsed.hostname in _LOOPBACK_HOSTS:+ raise WebappAccessError("The public URL must be an https:// address other devices use.")+ if parsed.query or parsed.fragment or parsed.username or parsed.password:+ raise WebappAccessError("The public URL cannot carry credentials, a query or a fragment.")+ return value+++def gateway_home() -> Path:+ """The home whose gateway serves the current one; its config holds the Webapp's settings."""+ from hermes_cli.webapp_launcher import _gateway_home+ from hermes_constants import get_hermes_home++ return _gateway_home(get_hermes_home())+++def nous_signed_in() -> bool:+ """Whether this home holds a Nous account to register sign-in under (a free-tier guest has none).+ Refresh-free: it reads the auth store and never spends a refresh token."""+ from hermes_cli.auth_nous import get_nous_auth_status_local++ status = get_nous_auth_status_local()+ return bool(status.get("logged_in") and not status.get("free_tier"))+++def _register_nous_sign_in(callback_url: str) -> None:+ """Register (or update in place) this home's portal client with *callback_url*, as+ ``hermes dashboard register --redirect-uri`` does."""+ from hermes_cli.auth import resolve_nous_access_token+ from hermes_cli.config import save_env_value+ from hermes_cli.dashboard_register import (+ _env_value,+ _generate_dashboard_name,+ _register_self_hosted_client,+ _resolve_portal_base_url,+ )++ existing = (_env_value(_CLIENT_ID_ENV) or "").strip() or None+ try:+ result = _register_self_hosted_client(+ access_token=resolve_nous_access_token(),+ portal_base_url=_resolve_portal_base_url(os.environ.get("HERMES_DASHBOARD_PORTAL_URL")),+ name=None if existing else _generate_dashboard_name(),+ custom_redirect_uri=callback_url, existing_client_id=existing)+ except Exception as exc:+ raise WebappAccessError(f"Couldn't register Nous sign-in: {exc}") from exc+ save_env_value(_CLIENT_ID_ENV, str(result["client_id"]))+++def register(mode: str, public_url: Optional[str] = None) -> tuple[str, str]:+ """Register Nous sign-in for *mode*; returns the ``(host, public_url)`` for :func:`serve`.++ Re-registered on every start, so the callback follows a changed LAN address or URL. Writes no+ config: it waits on the portal, so callers do it before taking the config lock."""+ if mode == "lan":+ address = lan_address()+ if address is None:+ raise WebappAccessError("This machine has no network address other devices can reach.")+ host, url, pinned = "0.0.0.0", f"http://{address}:{DEFAULT_PORT}", ""+ elif mode == "public":+ host, url = "127.0.0.1", _public_url(public_url)+ pinned = url+ else:+ raise WebappAccessError(f"Unknown access mode {mode!r}.")+ if not nous_signed_in():+ raise WebappAccessError("Sign in to your Nous account under Providers first.")+ _register_nous_sign_in(f"{url}/auth/callback")+ return host, pinned+++def serve(host: str, public_url: str) -> None:+ """Serve the Webapp on *host* from the gateway's next start. Call :func:`register` first."""+ _write_config(enabled=True, host=host, public_url=public_url)+++def turn_off() -> None:+ """Stop serving the Webapp from the gateway's next start."""+ _write_config(enabled=False)+++def _write_config(*, enabled: bool, host: str = "", public_url: str = "") -> None:+ """The ``webapp:`` block and ``dashboard.public_url``, which gates the gateway's listener and so goes+ with the Webapp. A ``.env`` copy of the URL would shadow it (env wins), so that goes too."""+ from hermes_cli.config import load_config, remove_env_value, save_config++ cfg = load_config()+ webapp = cfg.get("webapp") if isinstance(cfg.get("webapp"), dict) else {}+ webapp.update(enabled=enabled, **({"host": host, "port": DEFAULT_PORT} if enabled else {}))+ cfg["webapp"] = webapp+ dashboard = cfg.setdefault("dashboard", {})+ if public_url:+ dashboard["public_url"] = public_url+ else:+ dashboard.pop("public_url", None)+ save_config(cfg)+ remove_env_value(_PUBLIC_URL_ENV)+++def _gateway_state(home: Path) -> dict:+ """What *home*'s gateway serves now (``serving``, ``off``, ``unavailable`` with a ``reason``, or+ ``stopped`` when none answers). It reads the config at start, so it can lag until a restart."""+ from hermes_cli.webapp_launcher import GatewayUnreachable, _control++ try:+ response = _control(home, "webapp-status")+ except GatewayUnreachable:+ return {"state": "stopped", "url": None, "reason": None}+ if not response.get("ok"):+ return {"state": "unavailable", "url": None, "reason": str(response.get("error") or "")}+ return dict(response["result"])+++def access_status() -> dict:+ """Everything the Web Access pane shows, read for the gateway home in scope."""+ from gateway.webapp_listener import _is_wildcard, webapp_settings+ from hermes_cli.dashboard_auth.prefix import resolve_public_url++ home = gateway_home()+ settings = webapp_settings(home)+ public_url = resolve_public_url()+ return {+ "enabled": settings.enabled,+ "mode": ("lan" if _is_wildcard(settings.host) else "public") if settings.enabled else None,+ "port": settings.port,+ "gateway": _gateway_state(home),+ "lan_address": lan_address(),+ "public_url": public_url,+ "nous_signed_in": nous_signed_in(),+ }diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.pynew file mode 100644index 00000000000..a43841846eb--- /dev/null+++ b/tests/hermes_cli/test_webapp_access.py@@ -0,0 +1,100 @@+"""Remote Webapp access (``hermes_cli.webapp_access``, ``/api/webapp-access/*``).++Contracts: a public URL gates the gateway's loopback bind until Web Access is stopped, LAN access+registers the LAN callback and unpins a public URL, and nothing is written or restarted without a+Nous account to sign in with.+"""++from __future__ import annotations++import pytest++pytest.importorskip("fastapi")+from fastapi.testclient import TestClient+++def client():+ from hermes_cli import web_server++ c = TestClient(web_server.app, raise_server_exceptions=False)+ c.headers["Authorization"] = f"Bearer {web_server._SESSION_TOKEN}"+ return c+++def restarts(monkeypatch):+ """Capture the gateway restart that applies the config instead of spawning it."""+ import hermes_cli.web_server_gateway as gw++ calls: list[str] = []++ def _restart(profile, *, what, label):+ calls.append(what)+ return {"restart_started": True}++ monkeypatch.setattr(gw, "_restart_gateway_after", _restart)+ return calls+++def nous(monkeypatch):+ """A signed-in Nous account; portal registration is captured (no network)."""+ from hermes_cli import webapp_access++ callbacks: list[str] = []+ monkeypatch.setattr(webapp_access, "nous_signed_in", lambda: True)+ monkeypatch.setattr(webapp_access, "_register_nous_sign_in", callbacks.append)+ monkeypatch.setattr(webapp_access, "lan_address", lambda: "192.168.1.50")+ return callbacks+++def _config() -> dict:+ from hermes_cli.config import load_config++ return load_config()+++def test_public_url_gates_the_loopback_bind_until_stopped(client, restarts, nous):+ from hermes_cli.web_server_boundary import _dashboard_public_hosts, listener_auth_required++ response = client.post("/api/webapp-access/start", json={"mode": "public", "public_url": "https://hermes.example.test"})++ assert response.status_code == 200, response.text+ assert _config()["webapp"] == {"enabled": True, "host": "127.0.0.1", "port": 9120}+ assert nous == ["https://hermes.example.test/auth/callback"]+ # What the restarted gateway decides for its listener (gateway.run_api.start_gateway_api).+ assert listener_auth_required("127.0.0.1", _dashboard_public_hosts())++ # Stop takes the public URL with it: it would keep gating the gateway's private listener.+ assert client.post("/api/webapp-access/stop").status_code == 200+ assert _config()["webapp"]["enabled"] is False+ assert not listener_auth_required("127.0.0.1", _dashboard_public_hosts())+ assert restarts == ["turning on Web Access", "turning off Web Access"]+++def test_lan_access_registers_the_lan_callback_and_unpins_a_public_url(client, restarts, nous):+ from hermes_cli.config import load_env, save_config, save_env_value+ from hermes_cli.dashboard_auth.prefix import resolve_public_url++ # A public URL from an earlier "own URL" setup, and an older .env pin that would shadow it.+ save_config({**_config(), "dashboard": {"public_url": "https://old.example.test"}})+ save_env_value("HERMES_DASHBOARD_PUBLIC_URL", "https://older.example.test")++ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 200++ assert nous == ["http://192.168.1.50:9120/auth/callback"]+ assert _config()["webapp"]["host"] == "0.0.0.0"+ assert resolve_public_url() == ""+ assert "HERMES_DASHBOARD_PUBLIC_URL" not in load_env()+++def test_start_without_a_nous_account_writes_and_restarts_nothing(client, restarts, nous, monkeypatch):+ from hermes_cli import webapp_access++ monkeypatch.setattr(webapp_access, "nous_signed_in", lambda: False)++ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 400+ assert nous == []+ assert restarts == []+ assert not _config().get("webapp", {}).get("enabled")