Skip to content

The agent that grows with you

fix(webapp): Web Access signs the Webapp in with a Nous Portal client of its own

emozillad740c0f7575c
diff --git a/gateway/run_api.py b/gateway/run_api.py
index 055eb975824..2ecf286903b 100644
--- a/gateway/run_api.py
+++ b/gateway/run_api.py
@@ -60,6 +60,7 @@ class GatewayDashboardMount:
self._lifespan = None
self._closed = False
self._replaced_session_token = None
+ self._undo_own_sign_in = None
@property
def loaded(self) -> bool:
@@ -82,6 +83,9 @@ class GatewayDashboardMount:
web.app.state.listener_public_url = own_url
elif hasattr(web.app.state, "listener_public_url"):
delattr(web.app.state, "listener_public_url")
+ if webapp is not None: # before the gate looks for a sign-in provider
+ from gateway.webapp_listener import use_own_sign_in
+ self._undo_own_sign_in = use_own_sign_in(webapp)
web._configure_auth_gate(self._state.bound_host, False, None, None)
web.app.state.gateway_runner = self.runner
web.app.state.session_authority = getattr(self.runner, "session_authority", None)
@@ -99,6 +103,9 @@ class GatewayDashboardMount:
web._SESSION_TOKEN = browser_session_token(webapp.home)
def _unbind_state(self) -> None:
+ undo_own_sign_in, self._undo_own_sign_in = self._undo_own_sign_in, None
+ if undo_own_sign_in is not None: # a listener mounted next signs in with the configured client
+ undo_own_sign_in()
if self.web is not None:
self.web.app.state.gateway_runner = None
self.web.app.state.session_authority = None
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index 44bdd2e86d0..87420a8a672 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -196,6 +196,19 @@ def listener_plan(home) -> tuple[str, int, WebappMount | None, str | None]:
return (*settings.bind, mount, None)
+def use_own_sign_in(webapp: WebappMount):
+ """Sign the Webapp's browsers in to Nous with the Portal client Web Access registered for it
+ (``hermes_cli.webapp_access.sign_in_client``), never the dashboard's
+ ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, until the returned undo runs. None, changing nothing, when
+ Web Access registered no client of its own (Nous sign-in set up by hand keeps the configured
+ client) or the Nous sign-in plugin is not enabled."""
+ from hermes_cli.webapp_access import sign_in_client
+ from plugins.dashboard_auth import nous
+
+ client = sign_in_client(webapp.home)
+ return None if client is None else nous.use_listener_client(*client)
+
+
def browser_session_token(home, *, rotate: bool = False) -> str:
"""The dashboard session token a Webapp browser holds, kept user-only in *home*.
diff --git a/hermes_cli/dashboard_register.py b/hermes_cli/dashboard_register.py
index a9f0fceece9..a6d2d1e248f 100644
--- a/hermes_cli/dashboard_register.py
+++ b/hermes_cli/dashboard_register.py
@@ -209,10 +209,6 @@ def cmd_dashboard_register(args) -> None:
print(f"✗ Failed to write HERMES_DASHBOARD_OAUTH_CLIENT_ID to .env: {exc}\n"
f" Set it manually: HERMES_DASHBOARD_OAUTH_CLIENT_ID={client_id}")
sys.exit(1)
- # Web Access shares this client and never posts the same callback twice; this registration may
- # have replaced it, so Web Access registers its callback again on its next start.
- from hermes_cli.webapp_access import forget_registration
- forget_registration()
# Explicit portal → always persist (the user asked); inferred → only if unset AND non-default.
existing_portal = _env_value("HERMES_DASHBOARD_PORTAL_URL")
should_write_portal = (
diff --git a/hermes_cli/webapp_access.py b/hermes_cli/webapp_access.py
index 5aa1e9775c9..ccd0f5703ba 100644
--- a/hermes_cli/webapp_access.py
+++ b/hermes_cli/webapp_access.py
@@ -11,9 +11,10 @@ callback); a gated bind without it would keep the Webapp off. Two shapes:
``webapp.public_url`` engages the gate on the loopback bind and fixes the callback.
Of the config it writes only the ``webapp:`` block; ``dashboard.public_url`` belongs to the standalone
-dashboard, which may sit behind its own tunnel or proxy. Registering a callback saves the portal
-client's id as ``HERMES_DASHBOARD_OAUTH_CLIENT_ID`` in ``.env``, the client the dashboard's Nous
-sign-in reads.
+dashboard, which may sit behind its own tunnel or proxy. Nous sign-in uses a portal client of Web
+Access's own, never the dashboard's ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, so registering the Webapp's
+callback cannot change the redirect URI the dashboard's sign-in needs. Its id is kept in a user-only
+file under the gateway home, which the gateway reads when it serves the Webapp; ``.env`` is untouched.
"""
from __future__ import annotations
@@ -28,7 +29,7 @@ from urllib.parse import urlsplit
from gateway.webapp_listener import DEFAULT_PORT
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
-_CLIENT_ID_ENV = "HERMES_DASHBOARD_OAUTH_CLIENT_ID"
+# Web Access's portal client: its id, the Portal it lives on and the callback last registered on it.
_REGISTRATION_PATH = Path("webapp") / "sign-in-registration.json"
@@ -76,25 +77,25 @@ def nous_signed_in() -> bool:
return bool(status.get("logged_in") and not status.get("free_tier"))
-def _registration_path() -> Path:
- """Where this home records the sign-in callback Web Access last registered with the Portal."""
- from hermes_constants import get_hermes_home
-
- return get_hermes_home() / _REGISTRATION_PATH
-
-
-def forget_registration() -> None:
- """Drop the record of the callback Web Access registered, so its next start registers again.
- ``hermes dashboard register`` calls this: it updates the same Portal client, and the Portal may
- replace that client's redirect URI."""
- _registration_path().unlink(missing_ok=True)
-
-
-def _registered(record: dict) -> bool:
+def _registration(home: Path) -> dict:
+ """*home*'s registration record, or ``{}`` when there is none or it cannot be read."""
try:
- return json.loads(_registration_path().read_text(encoding="utf-8-sig")) == record
+ record = json.loads((Path(home) / _REGISTRATION_PATH).read_text(encoding="utf-8-sig"))
except (OSError, ValueError):
- return False
+ return {}
+ return record if isinstance(record, dict) else {}
+
+
+def sign_in_client(home) -> Optional[tuple[str, str]]:
+ """``(client_id, portal)`` of the portal client Web Access registered for *home*'s Webapp, or None.
+ A record from an earlier build of Web Access names the dashboard's client, which it registered on
+ then: that is not Web Access's own, so the Webapp keeps the configured client until the next Start
+ registers one."""
+ record = _registration(home)
+ client_id, portal = record.get("client_id"), record.get("portal")
+ if record.get("own_client") is not True or not isinstance(portal, str) or not portal:
+ return None
+ return (client_id, portal) if isinstance(client_id, str) and client_id.startswith("agent:") else None
def registered_lan_origin(home: Path, port: int) -> Optional[str]:
@@ -102,10 +103,9 @@ def registered_lan_origin(home: Path, port: int) -> Optional[str]:
Webapp on the LAN at that address and *port*, and the address is still this machine's; else None.
Sign-in returns only to the callback the Portal has, so ``hermes webapp`` opens this address."""
try:
- record = json.loads((Path(home) / _REGISTRATION_PATH).read_text(encoding="utf-8-sig"))
- parts = urlsplit(record["callback"])
+ parts = urlsplit(_registration(home)["callback"])
recorded_port = parts.port
- except (OSError, ValueError, KeyError, TypeError, AttributeError):
+ except (ValueError, KeyError, TypeError, AttributeError):
return None
if (parts.scheme, parts.path, parts.query, parts.fragment) != ("http", "/auth/callback", "", ""):
return None
@@ -115,39 +115,37 @@ def registered_lan_origin(home: Path, port: int) -> Optional[str]:
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.
-
- The client is the dashboard's (``HERMES_DASHBOARD_OAUTH_CLIENT_ID``) and the Portal may replace
- its redirect URI on every registration, so the same callback for the same client and Portal is
- never posted twice: a start with nothing changed asks the Portal nothing."""
+ """Register Web Access's own portal client with *callback_url*, or update it in place, as
+ ``hermes dashboard register --redirect-uri`` does for the dashboard's. It never sends the
+ dashboard's client id and writes nothing to ``.env``: the Portal may replace a client's redirect
+ URI on every registration. The same callback for the same client and Portal is never posted
+ twice, so a start with nothing changed asks the Portal nothing."""
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,
)
+ from hermes_constants import get_hermes_home
from utils import atomic_write_text
- existing = (_env_value(_CLIENT_ID_ENV) or "").strip() or None
+ home = get_hermes_home()
portal = _resolve_portal_base_url(os.environ.get("HERMES_DASHBOARD_PORTAL_URL"))
- if existing and _registered({"portal": portal, "client_id": existing, "callback": callback_url}):
+ own = sign_in_client(home)
+ existing = own[0] if own and own[1] == portal else None
+ if existing and _registration(home).get("callback") == callback_url:
return
try:
result = _register_self_hosted_client(
access_token=resolve_nous_access_token(),
portal_base_url=portal,
- name=None if existing else _generate_dashboard_name(),
+ name=None if existing else f"webapp_{_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
- client_id = str(result["client_id"])
- save_env_value(_CLIENT_ID_ENV, client_id)
- path = _registration_path()
+ path = home / _REGISTRATION_PATH
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
- record = {"portal": portal, "client_id": client_id, "callback": callback_url}
+ record = {"own_client": True, "portal": portal, "client_id": str(result["client_id"]), "callback": callback_url}
atomic_write_text(path, json.dumps(record) + "\n", mode=0o600)
@@ -184,9 +182,9 @@ def build_bundle() -> None:
def register(callback_url: str) -> None:
- """Register Nous sign-in for *callback_url*, unless Web Access already registered it for this
- client and Portal, 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."""
+ """Register Nous sign-in for *callback_url* on Web Access's own portal client, unless it already
+ carries that callback on this Portal, 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."""
_register_nous_sign_in(callback_url)
diff --git a/plugins/dashboard_auth/nous/__init__.py b/plugins/dashboard_auth/nous/__init__.py
index 66723b5a75e..9881a541b2f 100644
--- a/plugins/dashboard_auth/nous/__init__.py
+++ b/plugins/dashboard_auth/nous/__init__.py
@@ -6,12 +6,15 @@ when a client_id (``dashboard.oauth.client_id`` / ``HERMES_DASHBOARD_OAUTH_CLIEN
Portal JWKS with ``aud`` = bare client_id. Portal issues a 24h *rotating* refresh token with
reuse detection: the middleware MUST persist ``Session.refresh_token`` back to the cookie on
every refresh or the next refresh replays a rotated token and revokes the whole session.
+
+While the gateway serves the Webapp, its sign-in uses the client Web Access registered for the
+Webapp instead of the configured one (:func:`use_listener_client`).
"""
from __future__ import annotations
import logging
-from typing import Any, Dict, Optional
+from typing import Any, Callable, Optional
from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session
from plugins.dashboard_auth._shared import (
@@ -37,6 +40,11 @@ _SCOPE = "agent_dashboard:access" # contract C3
_EXPECTED_CONTRACT_VERSION = 1 # contract C11
LAST_SKIP_REASON: str = "" # cleared on every register() so restarts don't leak stale reasons
+# Whether plugin discovery has run register() in this process, i.e. the plugin is enabled here.
+_DISCOVERED = False
+# (client_id, portal_url) the listener this process serves signs in with instead of the configured
+# client, or None: see use_listener_client.
+_LISTENER_CLIENT: Optional[tuple[str, str]] = None
class NousDashboardAuthProvider(JwtOAuthProvider):
@@ -131,6 +139,10 @@ def _load_config_oauth_section() -> dict:
def _settings() -> dict:
"""Resolve NousDashboardAuthProvider kwargs; the skip reason names BOTH configuration surfaces."""
section = _load_config_oauth_section()
+ if _LISTENER_CLIENT is not None: # a plugin reload while the listener uses its own client keeps it
+ client_id, portal_url = _LISTENER_CLIENT
+ return {"client_id": client_id, "portal_url": portal_url,
+ "token_leeway": parse_leeway(section.get("token_leeway"))}
client_id = resolve_env_or_cfg("HERMES_DASHBOARD_OAUTH_CLIENT_ID", section.get("client_id", ""))
portal_url = resolve_env_or_cfg("HERMES_DASHBOARD_PORTAL_URL", section.get("portal_url", "")) or _DEFAULT_PORTAL_URL
if not client_id:
@@ -154,10 +166,37 @@ def _settings() -> dict:
def register(ctx) -> None:
"""Register ``NousDashboardAuthProvider`` when a client_id is configured."""
- global LAST_SKIP_REASON
+ global LAST_SKIP_REASON, _DISCOVERED
+ _DISCOVERED = True
LAST_SKIP_REASON = ""
kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, NousDashboardAuthProvider, _settings)
if kwargs is not None:
logger.info(
"dashboard-auth-nous: registered provider (client_id=%s, portal=%s, token_leeway=%ss)",
kwargs["client_id"], kwargs["portal_url"], kwargs["token_leeway"])
+
+
+def use_listener_client(client_id: str, portal_url: str) -> Optional[Callable[[], None]]:
+ """Sign in with the Portal client *client_id* on *portal_url* instead of the configured one until
+ the returned undo runs, which puts the configured provider (or none) back. The gateway does this
+ while it serves the Webapp with the client Web Access registered for it, so the dashboard's
+ ``HERMES_DASHBOARD_OAUTH_CLIENT_ID`` keeps the redirect URI its own sign-in needs. None, changing
+ nothing, where the plugin is not enabled (discovery never ran :func:`register`)."""
+ from hermes_cli.dashboard_auth.registry import (
+ register_global_provider, restore_registration, snapshot_registration)
+
+ global _LISTENER_CLIENT
+ if not _DISCOVERED:
+ return None
+ previous = snapshot_registration(NousDashboardAuthProvider.name)
+ leeway = parse_leeway(_load_config_oauth_section().get("token_leeway"))
+ provider = NousDashboardAuthProvider(client_id=client_id, portal_url=portal_url, token_leeway=leeway)
+ _LISTENER_CLIENT = (client_id, portal_url)
+ register_global_provider(provider)
+
+ def undo() -> None:
+ global _LISTENER_CLIENT
+ _LISTENER_CLIENT = None
+ restore_registration(NousDashboardAuthProvider.name, provider, previous)
+
+ return undo
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index 2d3076c581b..fe0fde2604f 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -1,8 +1,9 @@
"""Remote Webapp access (``hermes_cli.webapp_access``, ``/api/webapp-access/*``).
Contracts: Web Access writes only the ``webapp:`` block (the own-URL mode's URL in
-``webapp.public_url``), LAN access registers the LAN callback, and nothing is written or restarted
-without a Nous account to sign in with.
+``webapp.public_url``), LAN access registers the LAN callback on a Nous Portal client of Web Access's
+own (never the dashboard's, never in ``.env``), and nothing is written or restarted without a Nous
+account to sign in with.
"""
from __future__ import annotations
@@ -318,42 +319,303 @@ def test_a_restart_refused_by_a_running_chat_is_reported_as_busy(client, nous, m
assert response.json()["enabled"] is True
-def test_the_portal_is_asked_again_only_when_the_callback_or_client_changed(monkeypatch):
- """Registering posts the callback under the dashboard's shared OAuth client id, and the Portal
- may replace that client's redirect URI, so Web Access does not post the same callback for the
- same client and Portal twice. A new LAN address, a new client id, or a registration made by
- ``hermes dashboard register`` in between makes the next start register again."""
- import argparse
+DASHBOARD_CLIENT = "agent:dashboard"
+DASHBOARD_CALLBACK = "https://dashboard.example.test/auth/callback"
+LAN_CALLBACK = "http://192.168.1.50:9120/auth/callback"
+
+
+def portal(monkeypatch):
+ """A signed-in Nous account and a fake Nous Portal (no network). Its self-hosted-client endpoint
+ mints ``agent:client-N`` for a request without a known client id and, for one it knows, REPLACES
+ that client's redirect URI: the worst case the real Portal may do. It already holds the
+ standalone dashboard's client (``agent:dashboard``)."""
+ from types import SimpleNamespace
from hermes_cli import auth, dashboard_register, webapp_access
- from hermes_cli.config import save_env_value
- posts: list[tuple] = []
+ clients = {DASHBOARD_CLIENT: DASHBOARD_CALLBACK}
+ requests: list[dict] = []
+
+ def register(*, access_token, portal_base_url, name, custom_redirect_uri, existing_client_id=None, timeout=15.0):
+ requests.append({"portal": portal_base_url, "name": name, "callback": custom_redirect_uri,
+ "client_id": existing_client_id})
+ client_id = existing_client_id if existing_client_id in clients else f"agent:client-{len(clients)}"
+ clients[client_id] = custom_redirect_uri
+ return {"client_id": client_id, "name": name or "kept"}
+
+ monkeypatch.delenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", raising=False)
+ monkeypatch.setenv("HERMES_DASHBOARD_PORTAL_URL", "https://portal.example.test")
+ monkeypatch.setattr(dashboard_register, "_register_self_hosted_client", register)
+ monkeypatch.setattr(auth, "resolve_nous_access_token", lambda: "throwaway-access-token")
+ monkeypatch.setattr(webapp_access, "nous_signed_in", lambda: True)
+ monkeypatch.setattr(webapp_access, "lan_address", lambda: "192.168.1.50")
+ return SimpleNamespace(clients=clients, requests=requests)
+
+
+def _env_bytes() -> bytes:
+ from hermes_cli.config import get_env_path
- def portal(*, access_token, portal_base_url, name, custom_redirect_uri, existing_client_id, timeout=15.0):
- posts.append((custom_redirect_uri, existing_client_id))
- return {"client_id": existing_client_id or "client-1", "name": name or "kept"}
+ path = get_env_path()
+ return path.read_bytes() if path.exists() else b""
- monkeypatch.delenv("HERMES_DASHBOARD_PORTAL_URL", raising=False)
- monkeypatch.setattr(dashboard_register, "_register_self_hosted_client", portal)
- monkeypatch.setattr(dashboard_register, "_resolve_portal_base_url", lambda _override=None: "https://portal.example.test")
- monkeypatch.setattr(auth, "resolve_nous_access_token", lambda: "token")
- lan = "http://192.168.1.50:9120/auth/callback"
- webapp_access.register(lan)
- webapp_access.register(lan)
- assert posts == [(lan, None)]
+def test_start_registers_a_portal_client_of_its_own_and_never_the_dashboards(client, restarts, portal, monkeypatch):
+ """Web Access signs the Webapp in with a Portal client of its own, so turning it on can never
+ change the redirect URI of the standalone dashboard's client, whatever the Portal does on an
+ update. The first Start registers a new client, never ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, and
+ writes nothing to ``.env``; a second Start with the same callback asks the Portal nothing; a moved
+ callback updates Web Access's own client. The dashboard's client keeps its redirect URI and
+ ``.env`` stays exactly as it was."""
+ from hermes_cli import webapp_access
+ from hermes_cli.config import save_env_value
+
+ save_env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID", DASHBOARD_CLIENT)
+ env = _env_bytes()
+
+ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 200
+ assert [(r["callback"], r["client_id"]) for r in portal.requests] == [(LAN_CALLBACK, None)]
+ assert portal.requests[0]["name"]
+ own = next(cid for cid, callback in portal.clients.items() if cid != DASHBOARD_CLIENT)
+ assert portal.clients == {DASHBOARD_CLIENT: DASHBOARD_CALLBACK, own: LAN_CALLBACK}
+ assert _env_bytes() == env
+
+ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 200
+ assert len(portal.requests) == 1
+ monkeypatch.setattr(webapp_access, "lan_address", lambda: "192.168.1.51")
+ assert client.post("/api/webapp-access/start", json={"mode": "lan"}).status_code == 200
moved = "http://192.168.1.51:9120/auth/callback"
- webapp_access.register(moved)
- assert posts[-1] == (moved, "client-1")
+ assert (portal.requests[-1]["callback"], portal.requests[-1]["client_id"]) == (moved, own)
+ assert portal.clients == {DASHBOARD_CLIENT: DASHBOARD_CALLBACK, own: moved}
+ assert _env_bytes() == env
+
+
+def test_web_access_keeps_its_client_id_under_the_gateway_home_not_in_env(portal):
+ """The id of Web Access's client lives in ``webapp/sign-in-registration.json`` under the gateway
+ home, beside the Portal it was registered on and the callback it carries; ``.env`` gets no
+ ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, so a standalone dashboard on this home finds no client it
+ did not register itself."""
+ import json
+
+ from hermes_cli import webapp_access
+ from hermes_cli.config import load_env
+ from hermes_constants import get_hermes_home
+
+ webapp_access.register(LAN_CALLBACK)
+
+ record = json.loads((get_hermes_home() / "webapp" / "sign-in-registration.json").read_text(encoding="utf-8"))
+ assert {key: record.get(key) for key in ("portal", "client_id", "callback")} == {
+ "portal": "https://portal.example.test", "client_id": "agent:client-1", "callback": LAN_CALLBACK}
+ assert "HERMES_DASHBOARD_OAUTH_CLIENT_ID" not in load_env()
+ assert webapp_access.sign_in_client(get_hermes_home()) == ("agent:client-1", "https://portal.example.test")
+
- save_env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID", "client-2")
- webapp_access.register(moved)
- assert posts[-1] == (moved, "client-2")
[email protected]("posix") # POSIX mode bits; a Windows home keeps its own ACL
+def test_web_access_keeps_its_client_record_user_only(portal):
+ import stat
+
+ from hermes_cli import webapp_access
+ from hermes_constants import get_hermes_home
+
+ webapp_access.register(LAN_CALLBACK)
+ record = get_hermes_home() / "webapp" / "sign-in-registration.json"
+ assert stat.S_IMODE(record.stat().st_mode) == 0o600
+ assert stat.S_IMODE(record.parent.stat().st_mode) == 0o700
+
+
+def test_a_home_registered_on_the_dashboards_client_gets_its_own_at_the_next_start(portal):
+ """Earlier builds of Web Access registered the Webapp's callback on the dashboard's client and
+ recorded that client's id. The next Start registers a client of its own, even for the same
+ callback, and leaves the dashboard's client and ``.env`` alone; until then the record names no
+ client of Web Access's own, so the Webapp keeps signing in with the configured one."""
+ import json
+
+ from hermes_cli import webapp_access
+ from hermes_cli.config import save_env_value
+ from hermes_constants import get_hermes_home
+
+ save_env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID", DASHBOARD_CLIENT)
+ record = get_hermes_home() / "webapp" / "sign-in-registration.json"
+ record.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
+ record.write_text(json.dumps({"portal": "https://portal.example.test", "client_id": DASHBOARD_CLIENT,
+ "callback": LAN_CALLBACK}) + "\n", encoding="utf-8")
+ env = _env_bytes()
+ assert webapp_access.sign_in_client(get_hermes_home()) is None
+
+ webapp_access.register(LAN_CALLBACK)
+
+ assert [(r["callback"], r["client_id"]) for r in portal.requests] == [(LAN_CALLBACK, None)]
+ assert portal.clients[DASHBOARD_CLIENT] == DASHBOARD_CALLBACK
+ assert webapp_access.sign_in_client(get_hermes_home()) == ("agent:client-1", "https://portal.example.test")
+ assert _env_bytes() == env
+ webapp_access.register(LAN_CALLBACK)
+ assert len(portal.requests) == 1
+
+
+def test_dashboard_register_leaves_web_access_and_its_client_alone(portal):
+ """``hermes dashboard register`` updates the dashboard's own client only: Web Access's client,
+ its record and its next Start (which asks the Portal nothing for an unchanged callback) are
+ untouched."""
+ import argparse
+
+ from hermes_cli import dashboard_register, webapp_access
+ from hermes_cli.config import save_env_value
+ from hermes_constants import get_hermes_home
+
+ save_env_value("HERMES_DASHBOARD_OAUTH_CLIENT_ID", DASHBOARD_CLIENT)
+ webapp_access.register(LAN_CALLBACK)
+ record = (get_hermes_home() / "webapp" / "sign-in-registration.json").read_bytes()
dashboard_register.cmd_dashboard_register(argparse.Namespace(
- name=None, redirect_uri="https://dashboard.example.test/auth/callback", portal_url=None))
- webapp_access.register(moved)
- assert posts[-1] == (moved, "client-2")
- assert len(posts) == 5
+ name=None, redirect_uri="https://dashboard2.example.test/auth/callback", portal_url=None))
+
+ assert portal.requests[-1]["client_id"] == DASHBOARD_CLIENT
+ assert portal.clients["agent:client-1"] == LAN_CALLBACK
+ assert (get_hermes_home() / "webapp" / "sign-in-registration.json").read_bytes() == record
+ webapp_access.register(LAN_CALLBACK)
+ assert len(portal.requests) == 2
+
+
+async def _login_client_id(mount, origin: str) -> str:
+ """The Portal client id the listener behind *mount* sends a browser starting Nous sign-in with."""
+ from urllib.parse import parse_qs, urlsplit
+
+ import httpx
+
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=mount), base_url=origin) as browser:
+ started = await browser.get("/auth/login", params={"provider": "nous"})
+ assert started.status_code in {302, 307}, started.text
+ location = urlsplit(started.headers["location"])
+ assert f"{location.scheme}://{location.netloc}" == "https://portal.example.test"
+ return parse_qs(location.query)["client_id"][0]
+
+
+def gateway_listeners(tmp_path, monkeypatch):
+ """The gateway's dashboard mount over the process's dashboard app, as the gateway builds it at
+ start: ``listener(webapp=True)`` is the Webapp's listener (every interface, behind sign-in), else
+ the private one. ``discover()`` runs the Nous plugin's registration as plugin discovery does at
+ gateway start (and on a plugin reload). The auth registry is emptied before and after."""
+ import types
+
+ import plugins.dashboard_auth.nous as nous_plugin
+ from gateway.run_api import GatewayDashboardMount
+ from gateway.webapp_listener import WebappMount
+ from hermes_cli import web_server
+ from hermes_cli.dashboard_auth import clear_providers
+ from hermes_cli.dashboard_auth.registry import register_global_provider
+ from hermes_constants import get_hermes_home
+
+ for key in ("bound_host", "bound_port", "auth_required", "trusted_public_hosts"):
+ monkeypatch.setattr(web_server.app.state, key, getattr(web_server.app.state, key, None), raising=False)
+ dist = tmp_path / "dist-webapp"
+ dist.mkdir()
+ (dist / "index.html").write_text("<!doctype html><html><body>WEBAPP</body></html>", encoding="utf-8")
+ discovery = types.SimpleNamespace(register_dashboard_auth_provider=register_global_provider)
+
+ def listener(*, webapp: bool):
+ state = types.SimpleNamespace(bound_host="0.0.0.0", bound_port=9120,
+ **({"webapp": WebappMount(dist, get_hermes_home())} if webapp else {}))
+ return GatewayDashboardMount(types.SimpleNamespace(session_authority=None), state)
+
+ clear_providers()
+ yield types.SimpleNamespace(listener=listener, discover=lambda: nous_plugin.register(discovery))
+ clear_providers()
+
+
[email protected]("dashboard_client", [DASHBOARD_CLIENT, None])
+def test_the_webapps_nous_sign_in_uses_its_own_client_and_the_dashboards_keeps_its_own(
+ portal, gateway_listeners, monkeypatch, dashboard_client):
+ """The gateway's Webapp listener signs browsers in to Nous with the client Web Access registered
+ for it, also on a home with no dashboard client at all. The gateway's private listener mounted
+ after it signs in with ``HERMES_DASHBOARD_OAUTH_CLIENT_ID`` as on main (the standalone dashboard
+ reads the same setting), or offers no Nous sign-in when that is unset."""
+ import asyncio
+
+ from hermes_cli import webapp_access
+ from hermes_cli.dashboard_auth import get_provider
+
+ webapp_access.register(LAN_CALLBACK)
+ if dashboard_client:
+ monkeypatch.setenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", dashboard_client)
+ gateway_listeners.discover()
+
+ async def scenario():
+ webapp = gateway_listeners.listener(webapp=True)
+ await webapp.ensure()
+ try:
+ assert await _login_client_id(webapp, "http://192.168.1.50:9120") == "agent:client-1"
+ finally:
+ await webapp.close()
+ if dashboard_client is None:
+ assert get_provider("nous") is None
+ return
+ private = gateway_listeners.listener(webapp=False)
+ await private.ensure()
+ try:
+ assert await _login_client_id(private, "http://192.168.1.50:9120") == DASHBOARD_CLIENT
+ finally:
+ await private.close()
+
+ asyncio.run(scenario())
+
+
+def test_a_plugin_reload_while_the_webapp_serves_keeps_its_own_client(portal, gateway_listeners, monkeypatch):
+ """Reloading plugins re-registers the Nous provider; while the gateway serves the Webapp it
+ is rebuilt on Web Access's client, not on ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``."""
+ import asyncio
+
+ from hermes_cli import webapp_access
+
+ webapp_access.register(LAN_CALLBACK)
+ monkeypatch.setenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", DASHBOARD_CLIENT)
+ gateway_listeners.discover()
+
+ async def scenario():
+ webapp = gateway_listeners.listener(webapp=True)
+ await webapp.ensure()
+ try:
+ gateway_listeners.discover()
+ assert await _login_client_id(webapp, "http://192.168.1.50:9120") == "agent:client-1"
+ finally:
+ await webapp.close()
+
+ asyncio.run(scenario())
+
+
+def test_a_disabled_nous_plugin_keeps_nous_sign_in_off_the_webapp(portal, monkeypatch, tmp_path):
+ """Web Access's client signs the Webapp in only through the Nous sign-in plugin: where
+ ``plugins.disabled`` keeps that plugin from loading (discovery never registered it), the Webapp
+ gets no Nous sign-in from Web Access either."""
+ import plugins.dashboard_auth.nous as nous_plugin
+ from gateway.webapp_listener import WebappMount, use_own_sign_in
+ from hermes_cli import webapp_access
+ from hermes_cli.dashboard_auth import clear_providers, get_provider
+ from hermes_constants import get_hermes_home
+
+ webapp_access.register(LAN_CALLBACK)
+ monkeypatch.setattr(nous_plugin, "_DISCOVERED", False)
+ clear_providers()
+
+ assert use_own_sign_in(WebappMount(tmp_path, get_hermes_home())) is None
+ assert get_provider("nous") is None
+
+
+def test_a_webapp_without_a_web_access_client_signs_in_with_the_configured_one(portal, gateway_listeners, monkeypatch):
+ """A Webapp whose Nous sign-in was set up by hand (``hermes dashboard register`` for its address,
+ no Web Access Start) keeps signing in with ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``."""
+ import asyncio
+
+ monkeypatch.setenv("HERMES_DASHBOARD_OAUTH_CLIENT_ID", DASHBOARD_CLIENT)
+ gateway_listeners.discover()
+
+ async def scenario():
+ webapp = gateway_listeners.listener(webapp=True)
+ await webapp.ensure()
+ try:
+ assert await _login_client_id(webapp, "http://192.168.1.50:9120") == DASHBOARD_CLIENT
+ finally:
+ await webapp.close()
+
+ asyncio.run(scenario())
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 8c3fd3efab2..94291f8f1b8 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -128,10 +128,12 @@ turns the Webapp off the same way. A Webapp you turned on for this computer only
Web Access changes only the `webapp:` settings and keeps your `webapp.port`. It leaves
`dashboard.public_url` alone, so a standalone dashboard you publish separately keeps its own address.
-When it registers a sign-in address, it saves your Nous sign-in client's id as
-`HERMES_DASHBOARD_OAUTH_CLIENT_ID` in `.env`; the standalone dashboard's Nous sign-in uses the same
-client. A standalone profile with its own gateway needs its own `webapp.port` to serve a Webapp
-beside the default gateway's. `hermes update` rebuilds the Webapp whenever a profile has it turned on.
+Its Nous sign-in uses a sign-in client of its own, which the first Start registers with your Nous
+account and keeps in the gateway's home (`webapp/sign-in-registration.json`). Start never reads or
+writes `HERMES_DASHBOARD_OAUTH_CLIENT_ID` in `.env`, so turning Web Access on never changes the
+standalone dashboard's Nous sign-in. A standalone profile with its own gateway needs its own
+`webapp.port` to serve a Webapp beside the default gateway's. `hermes update` rebuilds the Webapp
+whenever a profile has it turned on.
If that build fails, the gateway reports the Webapp unavailable, and the page says so, until
`hermes webapp` rebuilds it.