The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): compact dashboard_auth package (registry/native_flow/audit/prefix/docs)
Tekniuma3d7a0c25b51
diff --git a/hermes_cli/dashboard_auth/__init__.py b/hermes_cli/dashboard_auth/__init__.pyindex 9a997fd224c..9e3fc6fd6f2 100644--- a/hermes_cli/dashboard_auth/__init__.py+++ b/hermes_cli/dashboard_auth/__init__.py@@ -1,50 +1,24 @@"""Dashboard authentication provider framework.-The dashboard auth gate engages only when the dashboard binds to a-non-loopback host without ``--insecure``. In that mode, every request must-carry a verified session from one of the registered ``DashboardAuthProvider``-plugins.--The Nous provider lives in ``plugins/dashboard-auth-nous/`` and is the-default. Third parties register their own providers via the plugin hook-``ctx.register_dashboard_auth_provider``.+The auth gate engages only when the dashboard binds to a non-loopback host+without ``--insecure``; every request must then carry a verified session from+a registered ``DashboardAuthProvider``. The Nous provider+(``plugins/dashboard-auth-nous/``) is the default; third parties register+theirs via the plugin hook ``ctx.register_dashboard_auth_provider``."""from hermes_cli.dashboard_auth.base import (- DashboardAuthProvider,- Session,- TokenPrincipal,- LoginStart,- InvalidCodeError,- InvalidCredentialsError,- ProviderError,- RefreshExpiredError,- assert_protocol_compliance,+ DashboardAuthProvider, Session, TokenPrincipal, LoginStart, InvalidCodeError,+ InvalidCredentialsError, ProviderError, RefreshExpiredError, assert_protocol_compliance,classify_jwks_lookup_error,)from hermes_cli.dashboard_auth.registry import (- register_provider,- get_provider,- list_providers,- list_token_providers,- list_session_providers,- clear_providers,+ register_provider, get_provider, list_providers, list_token_providers,+ list_session_providers, clear_providers,)__all__ = [- "DashboardAuthProvider",- "Session",- "TokenPrincipal",- "LoginStart",- "InvalidCodeError",- "InvalidCredentialsError",- "ProviderError",- "RefreshExpiredError",- "assert_protocol_compliance",- "classify_jwks_lookup_error",- "register_provider",- "get_provider",- "list_providers",- "list_token_providers",- "list_session_providers",- "clear_providers",+ "DashboardAuthProvider", "Session", "TokenPrincipal", "LoginStart", "InvalidCodeError",+ "InvalidCredentialsError", "ProviderError", "RefreshExpiredError", "assert_protocol_compliance",+ "classify_jwks_lookup_error", "register_provider", "get_provider", "list_providers",+ "list_token_providers", "list_session_providers", "clear_providers",]diff --git a/hermes_cli/dashboard_auth/audit.py b/hermes_cli/dashboard_auth/audit.pyindex 937fa95a75b..dbad5d8d073 100644--- a/hermes_cli/dashboard_auth/audit.py+++ b/hermes_cli/dashboard_auth/audit.py@@ -1,13 +1,9 @@"""Audit log for dashboard-auth events.-Profile-aware location: ``$HERMES_HOME/logs/dashboard-auth.log``.-Format: one JSON object per line. Token-like fields are stripped before-serialisation to avoid leaking refresh tokens or JWTs to disk.--This module deliberately keeps a minimal dependency surface — no imports-from ``hermes_constants`` or other hermes_cli modules — so it can be-imported safely from middleware code that loads early in the startup-sequence.+Profile-aware location: ``$HERMES_HOME/logs/dashboard-auth.log``, one JSON+object per line. Token-like fields are stripped before serialisation so+refresh tokens / JWTs never reach disk. Minimal import surface (no+``hermes_constants`` at import time) so early-loading middleware can import it."""from __future__ import annotations@@ -15,7 +11,6 @@ import datetime as _dtimport enumimport jsonimport logging-import osimport threadingfrom pathlib import Pathfrom typing import Any@@ -23,8 +18,7 @@ from typing import Any_log = logging.getLogger(__name__)_write_lock = threading.Lock()-# Field names that must never appear in the log raw. Any kwarg matching-# these is silently dropped.+# Field names that must never appear in the log raw; matching kwargs are dropped._REDACTED_FIELDS: frozenset = frozenset({"access_token", "refresh_token", "code", "code_verifier","state", "ticket", "cookie", "Authorization", "authorization",@@ -32,10 +26,7 @@ _REDACTED_FIELDS: frozenset = frozenset({class AuditEvent(enum.Enum):- """Event types written to dashboard-auth.log.-- Values are the literal ``event`` field on the JSON line.- """+ """Event types; values are the literal ``event`` field on the JSON line."""LOGIN_START = "login_start"LOGIN_SUCCESS = "login_success"@@ -57,39 +48,29 @@ class AuditEvent(enum.Enum):def _resolve_log_path() -> Path:- """``$HERMES_HOME/logs/dashboard-auth.log``.-- Uses ``hermes_constants.get_hermes_home()`` (a leaf module — no import- cycle) so profile overrides and the native-Windows ``%LOCALAPPDATA%``- fallback are honored.- """+ """``$HERMES_HOME/logs/dashboard-auth.log`` (lazy leaf import: honours+ profile overrides and the native-Windows ``%LOCALAPPDATA%`` fallback)."""from hermes_constants import get_hermes_homereturn get_hermes_home() / "logs" / "dashboard-auth.log"def audit_log(event: AuditEvent, **fields: Any) -> None:- """Append one event to the audit log.+ """Append one event; token-like fields dropped, log dir created.- Token-like fields are dropped. Missing log directory is created.Write failures are logged at WARNING but never raise — auth must notfail because the audit logger broke."""- safe_fields = {- k: v for k, v in fields.items()- if k not in _REDACTED_FIELDS- }entry = {"ts": _dt.datetime.now(_dt.timezone.utc).isoformat(),"event": event.value,- **safe_fields,+ **{k: v for k, v in fields.items() if k not in _REDACTED_FIELDS},}line = json.dumps(entry, separators=(",", ":")) + "\n"path = _resolve_log_path()try:path.parent.mkdir(parents=True, exist_ok=True)- with _write_lock:- with open(path, "a", encoding="utf-8") as f:- f.write(line)+ with _write_lock, open(path, "a", encoding="utf-8") as f:+ f.write(line)except Exception as e:_log.warning("dashboard-auth audit log write failed: %s", e)diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 9559ded817f..f944782eaeb 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -42,11 +42,10 @@ class TokenPrincipal:class LoginStart:"""First leg of the OAuth round trip.- ``redirect_url`` is where the browser goes (the IDP's authorize endpoint);- ``cookie_payload`` maps cookie name -> serialised PKCE/CSRF state that the- auth route sets (HttpOnly, Secure over HTTPS, TTL <= 10 min). The PKCE- cookie is ``SameSite=None; Secure`` over HTTPS so it survives the cross-site- redirect chain — see :func:`hermes_cli.dashboard_auth.cookies.set_pkce_cookie`.+ ``redirect_url`` is the IDP's authorize endpoint; ``cookie_payload`` maps+ cookie name -> serialised PKCE/CSRF state that the auth route sets+ (HttpOnly, Secure over HTTPS, TTL <= 10 min, ``SameSite=None`` over HTTPS+ so it survives the cross-site redirect chain — see ``cookies.set_pkce_cookie``)."""redirect_url: str@@ -88,6 +87,8 @@ def classify_jwks_lookup_error(exc: BaseException) -> Exception:import jwtexcept Exception: # pragma: no cover - jwt is a hard dep of these providersreturn ProviderError(f"JWKS lookup failed: {exc!r}")+ # Order matters: DecodeError/PyJWKSetError are checked before their+ # PyJWKClientError / InvalidTokenError parents.if isinstance(exc, jwt.PyJWKClientConnectionError):return ProviderError(f"JWKS lookup failed: {exc}")if isinstance(exc, (jwt.DecodeError, jwt.PyJWKSetError)):@@ -140,12 +141,7 @@ class DashboardAuthProvider(ABC):@abstractmethoddef complete_login(- self,- *,- code: str,- state: str,- code_verifier: str,- redirect_uri: str,+ self, *, code: str, state: str, code_verifier: str, redirect_uri: str,) -> Session: ...@abstractmethod@@ -157,9 +153,7 @@ class DashboardAuthProvider(ABC):@abstractmethoddef revoke_session(self, *, refresh_token: str) -> None: ...- def complete_password_login(- self, *, username: str, password: str- ) -> "Session":+ def complete_password_login(self, *, username: str, password: str) -> "Session":"""Verify a username/password pair and mint a :class:`Session`.Only called when ``supports_password`` is True. Raise@@ -197,17 +191,12 @@ def assert_protocol_compliance(cls: type) -> None:"""for attr in ("name", "display_name"):if not getattr(cls, attr, ""):- raise TypeError(- f"{cls.__name__} missing or empty attribute: {attr!r}"- )- for method in (- "start_login", "complete_login", "verify_session",- "refresh_session", "revoke_session",- ):+ raise TypeError(f"{cls.__name__} missing or empty attribute: {attr!r}")+ for method in ("start_login", "complete_login", "verify_session", "refresh_session",+ "revoke_session"):if not callable(getattr(cls, method, None)):raise TypeError(f"{cls.__name__} missing method: {method}")if getattr(cls, "__abstractmethods__", None):raise TypeError(- f"{cls.__name__} has unimplemented abstract methods: "- f"{sorted(cls.__abstractmethods__)}"+ f"{cls.__name__} has unimplemented abstract methods: {sorted(cls.__abstractmethods__)}")diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.pyindex 0b248ff6be1..1d8169d01a3 100644--- a/hermes_cli/dashboard_auth/cookies.py+++ b/hermes_cli/dashboard_auth/cookies.py@@ -151,7 +151,9 @@ def clear_session_cookies(response: Response, *, prefix: str = "") -> None:"""Delete the AT, RT and provider cookies (every name variant, active path)."""bare_attrs = _lax_bare_attrs(prefix)for name in (SESSION_AT_COOKIE, SESSION_RT_COOKIE, SESSION_PROVIDER_COOKIE):- _clear_cookie_variants(response, name, prefix=prefix, https_samesite="lax", bare_attrs=bare_attrs)+ _clear_cookie_variants(+ response, name, prefix=prefix, https_samesite="lax", bare_attrs=bare_attrs,+ )def encode_pkce_payload(parts: dict[str, str]) -> str:@@ -167,7 +169,9 @@ def encode_pkce_payload(parts: dict[str, str]) -> str:return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=")-def set_pkce_cookie(response: Response, *, payload: dict[str, str], use_https: bool, prefix: str = "") -> None:+def set_pkce_cookie(+ response: Response, *, payload: dict[str, str], use_https: bool, prefix: str = "",+) -> None:"""Set the PKCE cookie (``payload`` is the segment dict; see module docstringfor the SameSite=None rationale)."""_set(response, PKCE_COOKIE, encode_pkce_payload(payload), max_age=_PKCE_MAX_AGE,@@ -195,7 +199,10 @@ def _read_with_fallback(request: Request, bare_name: str) -> Optional[str]:def read_session_cookies(request: Request) -> Tuple[Optional[str], Optional[str]]:"""Returns (access_token, refresh_token), either may be None."""- return _read_with_fallback(request, SESSION_AT_COOKIE), _read_with_fallback(request, SESSION_RT_COOKIE)+ return (+ _read_with_fallback(request, SESSION_AT_COOKIE),+ _read_with_fallback(request, SESSION_RT_COOKIE),+ )def read_session_provider(request: Request) -> Optional[str]:@@ -237,7 +244,8 @@ def parse_pkce_payload(raw: str) -> dict[str, str]:def set_sso_attempt_cookie(response: Response, *, use_https: bool, prefix: str = "") -> None:"""Set the auto-SSO loop-guard marker; only its presence matters."""- _set(response, SSO_ATTEMPT_COOKIE, "1", max_age=_SSO_ATTEMPT_MAX_AGE, use_https=use_https, prefix=prefix)+ _set(response, SSO_ATTEMPT_COOKIE, "1", max_age=_SSO_ATTEMPT_MAX_AGE,+ use_https=use_https, prefix=prefix)def read_sso_attempt_cookie(request: Request) -> Optional[str]:@@ -249,7 +257,8 @@ def clear_sso_attempt_cookie(response: Response, *, prefix: str = "") -> None:"""Delete the auto-SSO marker (every variant) so it never suppresses alater silent attempt."""_clear_cookie_variants(- response, SSO_ATTEMPT_COOKIE, prefix=prefix, https_samesite="lax", bare_attrs=_lax_bare_attrs(prefix),+ response, SSO_ATTEMPT_COOKIE, prefix=prefix, https_samesite="lax",+ bare_attrs=_lax_bare_attrs(prefix),)diff --git a/hermes_cli/dashboard_auth/login_page.py b/hermes_cli/dashboard_auth/login_page.pyindex 201ae3ab050..1a5b07a89c8 100644--- a/hermes_cli/dashboard_auth/login_page.py+++ b/hermes_cli/dashboard_auth/login_page.py@@ -449,25 +449,17 @@ def render_login_html(*, next_path: str = "") -> str:providers = list_session_providers()if not providers:return _EMPTY_HTML-# URL-encode then HTML-escape, matching the gate's ``_safe_next_target``# shape so a round-tripped value is byte-identical.- next_qs = (- f"&next={html.escape(quote(next_path, safe=''), quote=True)}" if next_path else ""- )-- buttons = []- needs_password_script = False- for p in providers:- if getattr(p, "supports_password", False):- needs_password_script = True- buttons.append(_render_password_form(p, next_path))- else:- buttons.append(- f' <a class="provider-btn" '- f'href="/auth/login?provider={html.escape(p.name, quote=True)}{next_qs}">'- f'Sign in with {html.escape(p.display_name)}</a>'- )+ next_qs = f"&next={html.escape(quote(next_path, safe=''), quote=True)}" if next_path else ""+ buttons = [+ _render_password_form(p, next_path) if getattr(p, "supports_password", False) else+ f' <a class="provider-btn" '+ f'href="/auth/login?provider={html.escape(p.name, quote=True)}{next_qs}">'+ f'Sign in with {html.escape(p.display_name)}</a>'+ for p in providers+ ]+ needs_password_script = any(getattr(p, "supports_password", False) for p in providers)return _LOGIN_HTML_TEMPLATE.format(provider_buttons="\n".join(buttons),password_script=_PASSWORD_FORM_SCRIPT if needs_password_script else "",diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex 0768722cfb3..b838bdd1851 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -98,9 +98,12 @@ def _unauth_response(request: Request, *, reason: str) -> Response:prefix = prefix_from_request(request)login_url = f"{prefix}/login?next={next_param}" if next_param else f"{prefix}/login"if request.url.path.startswith("/api/"):- error_code = "session_expired" if reason == "invalid_or_expired_session" else "unauthenticated"+ error_code = (+ "session_expired" if reason == "invalid_or_expired_session" else "unauthenticated"+ )return JSONResponse(- {"error": error_code, "detail": "Unauthorized", "reason": reason, "login_url": login_url},+ {"error": error_code, "detail": "Unauthorized", "reason": reason,+ "login_url": login_url},status_code=401,)return RedirectResponse(url=login_url, status_code=302)@@ -134,7 +137,8 @@ def _auto_sso_response(request: Request) -> Response | None:auth_login = f"{auth_login}&next={next_param}"resp = RedirectResponse(url=auth_login, status_code=302)set_sso_attempt_cookie(resp, use_https=detect_https(request), prefix=prefix)- audit_log(AuditEvent.LOGIN_START, provider=provider.name, reason="auto_sso", ip=_client_ip(request))+ audit_log(AuditEvent.LOGIN_START, provider=provider.name, reason="auto_sso",+ ip=_client_ip(request))return resp@@ -232,7 +236,8 @@ async def gated_auth_middleware()return response- audit_log(AuditEvent.SESSION_VERIFY_FAILURE, reason="no_provider_recognises", ip=_client_ip(request))+ audit_log(AuditEvent.SESSION_VERIFY_FAILURE, reason="no_provider_recognises",+ ip=_client_ip(request))response = _unauth_response(request, reason="invalid_or_expired_session")# Refresh failed (or no RT): clear the dead cookies under the active# prefix so the deletion Path matches the set Path.@@ -262,7 +267,8 @@ def _attempt_refresh(request: Request, *, refresh_token, provider_hint: str | Nodef _audit_failure(reason):return lambda provider: audit_log(- AuditEvent.REFRESH_FAILURE, provider=provider.name, reason=reason, ip=_client_ip(request),+ AuditEvent.REFRESH_FAILURE, provider=provider.name, reason=reason,+ ip=_client_ip(request),)def _refresh(provider):@@ -271,5 +277,6 @@ def _attempt_refresh(request: Request, *, refresh_token, provider_hint: str | Noreturn scan_session_providers(provider_hint, _refresh, phase="refresh", log=_log, swallow=(RefreshExpiredError,),- on_swallow=_audit_failure("refresh_expired"), on_unreachable=_audit_failure("provider_unreachable"),+ on_swallow=_audit_failure("refresh_expired"),+ on_unreachable=_audit_failure("provider_unreachable"),)diff --git a/hermes_cli/dashboard_auth/native_flow.py b/hermes_cli/dashboard_auth/native_flow.pyindex 2e1abcf7db2..295bebc9b5f 100644--- a/hermes_cli/dashboard_auth/native_flow.py+++ b/hermes_cli/dashboard_auth/native_flow.py@@ -1,32 +1,15 @@"""Gateway-brokered RFC 8252 (OAuth 2.0 for Native Apps) authorization store.The desktop cannot be a direct OAuth client of the upstream IDP (the Portal-``client_id`` is per gateway instance and only accepts the gateway's own-``/auth/callback`` redirect), so the gateway brokers: it is the authorization-server *to the desktop* and an OAuth client *to the Portal* — still textbook-RFC 8252: system browser, loopback redirect, PKCE, tokens returned to the app-and never as cookies.-- 1. Desktop generates its own PKCE pair (cv_d, cc_d) + ``state``, opens a- loopback listener, and opens the system browser at- ``/auth/native/authorize`` with cc_d, state and its loopback redirect_uri.- 2. The gateway stashes a *pending authorization* (:func:`register_pending`)- keyed by an opaque ``broker_state`` and runs the EXISTING upstream flow;- broker_state rides inside the gateway's own PKCE cookie, so no desktop- secret reaches the Portal.- 3. On the upstream callback (or a successful password login) the gateway- mints a one-time gateway code bound to cc_d (:func:`complete_pending`) and- 302s the browser to ``redirect_uri?code=<gw_code>&state=<state>``.- 4. The desktop POSTs ``/auth/native/token`` with gw_code + cv_d; the gateway- checks ``S256(cv_d) == cc_d`` (:func:`redeem_code`), consumes the code and- returns the upstream tokens in the JSON body.- 5. The desktop keeps them in the OS keychain and uses ``Authorization: Bearer``.--Security properties: PKCE binding (an intercepted gw_code is useless without-cv_d), single use (redemption pops the entry), short TTLs, 256-bit opaque-handles compared in constant time, no secret logging. In-memory and-process-local (single dashboard process); functional API keeps ``time.time``-patchable in tests.+``client_id`` is per gateway and only accepts the gateway's ``/auth/callback``),+so the gateway brokers: authorization server *to the desktop*, OAuth client+*to the Portal*. Desktop PKCE pair (cv_d, cc_d) + state -> ``/auth/native/authorize``+stashes a pending entry (:func:`register_pending`) keyed by an opaque+``broker_state`` riding in the gateway's own PKCE cookie -> upstream callback+or password login mints a one-time code bound to cc_d (:func:`complete_pending`)+-> desktop redeems it with cv_d at ``/auth/native/token`` (:func:`redeem_code`).+PKCE binding, single use, short TTLs, 256-bit handles compared in constant time,+no secret logging; in-memory, process-local, ``time.time`` patchable in tests."""from __future__ import annotations@@ -49,8 +32,7 @@ _CODE_TTL_SECONDS = 120# Global cap so a misbehaving client cannot grow the store unbounded._MAX_ENTRIES = 256# Per-IP cap on PENDING entries: /auth/native/authorize is a public pre-auth-# route, so one spammer must not fill the global store (600 s each) and lock-# out legitimate native logins.+# route, so one spammer must not fill the global store and lock out logins._MAX_PENDING_PER_IP = 8_lock = threading.Lock()@@ -92,14 +74,10 @@ class CodeInvalid(NativeFlowError):"""The gateway code is unknown, expired, already redeemed, or PKCE-mismatched."""-def _b64url_no_pad(raw: bytes) -> str:- """Base64url without ``=`` padding (RFC 7636 §4)."""- return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")--def _s256(verifier: str) -> str:- """RFC 7636 S256 transform: base64url(sha256(ascii(verifier)))."""- return _b64url_no_pad(hashlib.sha256(verifier.encode("ascii")).digest())+ """RFC 7636 S256 transform: base64url(sha256(ascii(verifier))), no padding."""+ digest = hashlib.sha256(verifier.encode("ascii")).digest()+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")def _gc_locked(now: int) -> None:@@ -118,11 +96,7 @@ def _now(now: Optional[int]) -> int:def register_pending(- *,- code_challenge: str,- redirect_uri: str,- client_state: str,- client_ip: str = "",+ *, code_challenge: str, redirect_uri: str, client_state: str, client_ip: str = "",now: Optional[int] = None,) -> str:"""Stash a pending native authorization; return an opaque ``broker_state``.@@ -137,19 +111,12 @@ def register_pending(_gc_locked(now)if not _capacity_ok_locked():raise NativeFlowError("native-flow authorization store at capacity")- if client_ip and (- sum(1 for v in _pending.values() if v.client_ip == client_ip)- >= _MAX_PENDING_PER_IP- ):- raise NativeFlowError(- "too many pending native authorizations from this address"- )+ per_ip = sum(1 for v in _pending.values() if v.client_ip == client_ip)+ if client_ip and per_ip >= _MAX_PENDING_PER_IP:+ raise NativeFlowError("too many pending native authorizations from this address")_pending[broker_state] = _Pending(- code_challenge=code_challenge,- redirect_uri=redirect_uri,- client_state=client_state,- client_ip=client_ip,- expires_at=now + _PENDING_TTL_SECONDS,+ code_challenge=code_challenge, redirect_uri=redirect_uri, client_state=client_state,+ client_ip=client_ip, expires_at=now + _PENDING_TTL_SECONDS,)return broker_state@@ -157,21 +124,15 @@ def register_pending(def get_pending(broker_state: str, *, now: Optional[int] = None) -> _Pending:"""Peek (without consuming) the pending authorization; raises:class:`PendingNotFound` if unknown or expired."""- now = _now(now)with _lock:- _gc_locked(now)+ _gc_locked(_now(now))entry = _pending.get(broker_state)if entry is None:raise PendingNotFound("unknown or expired native authorization")return entry-def complete_pending(- broker_state: str,- *,- session: Session,- now: Optional[int] = None,-) -> str:+def complete_pending(broker_state: str, *, session: Session, now: Optional[int] = None) -> str:"""Consume a pending authorization (single use) and mint a one-time gatewaycode bound to the desktop's challenge + the verified ``session``.@@ -187,19 +148,13 @@ def complete_pending(raise NativeFlowError("native-flow code store at capacity")gw_code = secrets.token_urlsafe(32)_issued[gw_code] = _IssuedCode(- code_challenge=pending.code_challenge,- session=session,+ code_challenge=pending.code_challenge, session=session,expires_at=now + _CODE_TTL_SECONDS,)return gw_code-def redeem_code(- *,- code: str,- code_verifier: str,- now: Optional[int] = None,-) -> Session:+def redeem_code(*, code: str, code_verifier: str, now: Optional[int] = None) -> Session:"""Verify PKCE + consume a gateway code; return the bound :class:`Session`.The entry is popped BEFORE the PKCE check so a wrong verifier cannot bediff --git a/hermes_cli/dashboard_auth/prefix.py b/hermes_cli/dashboard_auth/prefix.pyindex 84a24e44c0e..cf9c6172232 100644--- a/hermes_cli/dashboard_auth/prefix.py+++ b/hermes_cli/dashboard_auth/prefix.py@@ -1,12 +1,11 @@"""X-Forwarded-Prefix and public-URL resolution for reverse-proxied deploys.-Mission-control style deploys proxy the dashboard at a path prefix and inject-``X-Forwarded-Prefix: /hermes`` so the backend can build prefixed URLs-(Location headers, OAuth redirect_uri, cookie Path, SPA asset URLs). When the-operator declares a complete ``HERMES_DASHBOARD_PUBLIC_URL`` /-``dashboard.public_url`` instead, that is used verbatim for the OAuth-redirect_uri (relief valve for unreliable proxy header chains). Single source-of truth so the gate, routes, cookies and SPA mount agree on validation.+Proxies mounting the dashboard at a path inject ``X-Forwarded-Prefix: /hermes``+so the backend can build prefixed URLs (Location headers, OAuth redirect_uri,+cookie Path, SPA asset URLs). An operator-declared ``HERMES_DASHBOARD_PUBLIC_URL``+/ ``dashboard.public_url`` is used verbatim for the OAuth redirect_uri instead+(relief valve for unreliable proxy header chains). Single source of truth so+the gate, routes, cookies and SPA mount agree on validation."""from __future__ import annotations@@ -32,19 +31,13 @@ _warned_malformed_prefixes: set = set()def _warn_if_malformed(source: str, raw: str) -> None:- """Warn once when a non-empty public-url value was rejected.-- Almost always a missing scheme; without this the value is silently- discarded and the OAuth callback falls back to header reconstruction,- which behind a proxy can yield the wrong scheme.- """+ """Warn once when a non-empty public-url value was rejected (almost always+ a missing scheme; silently falling back to header reconstruction can yield+ the wrong scheme behind a proxy)."""cleaned = raw.strip() if raw else ""- if not cleaned:- return # empty/unset is a legitimate "no override"- key = (source, cleaned)- if key in _warned_malformed_public_urls:+ if not cleaned or (source, cleaned) in _warned_malformed_public_urls:return- _warned_malformed_public_urls.add(key)+ _warned_malformed_public_urls.add((source, cleaned))_log.warning("%s is set to %r but was ignored because it is not a valid ""absolute URL — it must include an http:// or https:// scheme "@@ -60,12 +53,9 @@ def _warn_if_malformed(source: str, raw: str) -> None:def _warn_if_malformed_prefix(raw: Optional[str], reason: str) -> None:"""Warn once when a non-empty X-Forwarded-Prefix value is rejected."""cleaned = raw.strip() if raw else ""- if not cleaned:- return- key = (cleaned, reason)- if key in _warned_malformed_prefixes:+ if not cleaned or (cleaned, reason) in _warned_malformed_prefixes:return- _warned_malformed_prefixes.add(key)+ _warned_malformed_prefixes.add((cleaned, reason))_log.warning("X-Forwarded-Prefix header %r was ignored because %s. ""Dashboard URLs will be generated without a reverse-proxy path prefix.",@@ -86,14 +76,10 @@ def normalise_prefix(raw: Optional[str]) -> str:p = "/" + pp = p.rstrip("/")if "//" in p or ".." in p or any(c in p for c in _REJECT_CHARS):- _warn_if_malformed_prefix(- raw, "it contains a disallowed character or path sequence",- )+ _warn_if_malformed_prefix(raw, "it contains a disallowed character or path sequence")return ""if len(p) > _MAX_PREFIX_LENGTH:- _warn_if_malformed_prefix(- raw, f"it is longer than {_MAX_PREFIX_LENGTH} characters",- )+ _warn_if_malformed_prefix(raw, f"it is longer than {_MAX_PREFIX_LENGTH} characters")return ""return p@@ -103,16 +89,14 @@ def prefix_from_request(request) -> str:return normalise_prefix(request.headers.get("x-forwarded-prefix"))-# ----------------------------------------------------------------------------# HERMES_DASHBOARD_PUBLIC_URL / dashboard.public_url-# ---------------------------------------------------------------------------+# --- HERMES_DASHBOARD_PUBLIC_URL / dashboard.public_url --------------------def _normalise_public_url(raw: Optional[str]) -> str:"""Cleaned ``scheme://netloc[/path]`` (trailing slash stripped so callerscan append paths) or ``""`` when empty/malformed/injection-suspect. Callers- must treat ``""`` as "fall back to request reconstruction" — an explicit- empty value is indistinguishable from an unset env var.+ treat ``""`` as "fall back to request reconstruction" — an explicit empty+ value is indistinguishable from an unset env var."""url = raw.strip() if raw else ""if not url or any(c in url for c in _REJECT_CHARS):diff --git a/hermes_cli/dashboard_auth/public_paths.py b/hermes_cli/dashboard_auth/public_paths.pyindex befedb1070a..559ac426223 100644--- a/hermes_cli/dashboard_auth/public_paths.py+++ b/hermes_cli/dashboard_auth/public_paths.py@@ -1,60 +1,32 @@"""Shared allowlist of ``/api/*`` paths that bypass dashboard auth.-Two middlewares enforce dashboard auth and previously kept independent-copies of this list:--* ``hermes_cli.web_server.auth_middleware`` — loopback / ``--insecure``- mode, gates on the ephemeral ``_SESSION_TOKEN``.-* ``hermes_cli.dashboard_auth.middleware.gated_auth_middleware`` —- non-loopback mode, gates on the OAuth session cookie.--When the lists drifted, ``/api/status`` ended up public under the legacy-gate but 401'd under the OAuth gate. That broke the portal's wildcard-liveness probe (``nous-account-service`` ``fly-provider.ts``-``getInstanceRuntimeStatus``), which fetches ``/api/status`` without a-cookie as its sole signal of "agent dashboard is alive": every healthy-wildcard-subdomain agent surfaced as STARTING/down in the portal UI even-though the dashboard was serving correctly.--Centralising the allowlist here so both middlewares import the same-frozenset prevents the next drift. Keep this list minimal — only truly-non-sensitive, read-only endpoints belong here. As a sanity check, every-entry should be safe to expose to:-- * external uptime probes (Pingdom, Better Stack, NAS),- * the dashboard SPA before the user has logged in,- * anyone who happens to ``curl`` the hostname.--If a new endpoint doesn't pass all three tests, it should be gated and-the SPA should bootstrap it after login instead.+Imported by BOTH gates — ``web_server.auth_middleware`` (loopback /+``--insecure``, ephemeral ``_SESSION_TOKEN``) and+``dashboard_auth.middleware.gated_auth_middleware`` (OAuth cookie) — so the+lists cannot drift again (a drift once 401'd ``/api/status`` under the OAuth+gate and broke the portal's cookie-less liveness probe). Keep minimal: every+entry must be safe for external uptime probes, the pre-login SPA, and anyone+who ``curl``s the hostname; otherwise gate it and bootstrap after login."""from __future__ import annotationsPUBLIC_API_PATHS: frozenset[str] = frozenset({- # Minimal process liveness probe for desktop/backend boot handshakes. It- # intentionally avoids gateway config, platform discovery, MCP setup, and- # host-local detail so readiness checks cannot spend their budget inside- # cold plugin imports.+ # Minimal process liveness probe for desktop/backend boot handshakes; avoids+ # gateway config, platform discovery, MCP setup and cold plugin imports."/api/health",- # Liveness probe target. Returns version, gateway state, active- # session count, and the dashboard auth-gate shape. No bodies, no- # session content, no secrets. Documented as the portal's wildcard- # liveness probe in- # ``docs/agent-dashboard-public-url-contract.md`` (NAS side).+ # Portal wildcard liveness probe (``docs/agent-dashboard-public-url-contract.md``,+ # NAS side): version, gateway state, session count, auth-gate shape. No secrets."/api/status",# Read-only config-defaults / schema feeds for the SPA's Config page."/api/config/defaults","/api/config/schema",- # Read-only model metadata (context windows, etc.) — same shape as- # provider catalogs already exposed on the public internet.+ # Read-only model metadata — same shape as public provider catalogs."/api/model/info",# Read-only theme + plugin manifests for the dashboard skin engine."/api/dashboard/themes","/api/dashboard/plugins",# Chronos managed-cron fire webhook (NAS -> agent). NOT cookie-gated: it# carries its own short-lived NAS-minted JWT (purpose=cron_fire), which the- # handler verifies as the real auth. Must bypass the dashboard auth gate so- # the NAS relay's bearer-only callback reaches the verifier instead of a- # 401 no_cookie. The JWT — not this allowlist — is the security boundary.+ # handler verifies — the JWT, not this allowlist, is the security boundary."/api/cron/fire",})diff --git a/hermes_cli/dashboard_auth/registry.py b/hermes_cli/dashboard_auth/registry.pyindex 33b58305179..02cb3bc91c8 100644--- a/hermes_cli/dashboard_auth/registry.py+++ b/hermes_cli/dashboard_auth/registry.py@@ -11,10 +11,7 @@ import threadingfrom typing import List, Optionalfrom hermes_constants import hermes_home_key-from hermes_cli.dashboard_auth.base import (- DashboardAuthProvider,- assert_protocol_compliance,-)+from hermes_cli.dashboard_auth.base import DashboardAuthProvider, assert_protocol_compliance_log = logging.getLogger(__name__)_lock = threading.Lock()@@ -28,11 +25,18 @@ def _merged(scope: Optional[str] = None) -> dict[str, DashboardAuthProvider]:return providers-def register_provider(- provider: DashboardAuthProvider,- *,- scope: Optional[str] = None,-) -> None:+def _target(scope: Optional[str], *, create: bool) -> dict[str, DashboardAuthProvider]:+ """Global map for ``scope is None``, else that scope's overlay."""+ if scope is None:+ return _providers+ return _scoped_providers.setdefault(scope, {}) if create else _scoped_providers.get(scope, {})+++def _log_registered(kind: str, provider: DashboardAuthProvider) -> None:+ _log.info("dashboard-auth: registered %s%r (%s)", kind, provider.name, provider.display_name)+++def register_provider(provider: DashboardAuthProvider, *, scope: Optional[str] = None) -> None:"""Register a provider.Raises:@@ -41,49 +45,34 @@ def register_provider("""assert_protocol_compliance(type(provider))with _lock:- target = _providers if scope is None else _scoped_providers.setdefault(scope, {})+ target = _target(scope, create=True)effective = target if scope is None else _merged(scope)if provider.name in effective:- raise ValueError(- f"dashboard-auth provider already registered: {provider.name!r}"- )+ raise ValueError(f"dashboard-auth provider already registered: {provider.name!r}")target[provider.name] = provider- _log.info(- "dashboard-auth: registered provider %r (%s)",- provider.name, provider.display_name,- )+ _log_registered("provider ", provider)-def get_provider(- name: str,- *,- scope: Optional[str] = None,-) -> Optional[DashboardAuthProvider]:+def get_provider(name: str, *, scope: Optional[str] = None) -> Optional[DashboardAuthProvider]:"""Return the registered provider for ``name``, or None if unknown."""with _lock:return _merged(scope).get(name)def snapshot_registration(- name: str,- *,- scope: Optional[str] = None,+ name: str, *, scope: Optional[str] = None,) -> Optional[DashboardAuthProvider]:with _lock:- target = _providers if scope is None else _scoped_providers.get(scope, {})- return target.get(name)+ return _target(scope, create=False).get(name)def restore_registration(- name: str,- current: DashboardAuthProvider,- previous: Optional[DashboardAuthProvider],- *,- scope: Optional[str] = None,+ name: str, current: DashboardAuthProvider, previous: Optional[DashboardAuthProvider],+ *, scope: Optional[str] = None,) -> bool:"""Restore a host-owned provider registration if it is still current."""with _lock:- target = _providers if scope is None else _scoped_providers.setdefault(scope, {})+ target = _target(scope, create=True)if target.get(name) is not current:return Falseif previous is None:@@ -102,57 +91,40 @@ def list_providers(*, scope: Optional[str] = None) -> List[DashboardAuthProviderdef list_token_providers() -> List[DashboardAuthProvider]:- """Registered providers that support non-interactive token auth.-- The subset of ``list_providers()`` whose ``supports_token`` flag is True,- in registration order. The ``token_auth`` middleware seam consults these- (and only these) when a token-authable route is hit, so OAuth/password-only- providers are never asked to ``verify_token``. Returns an empty list when- no token provider is registered — a token-authable route then fails- closed (401), never open.+ """Providers with ``supports_token`` True, in registration order.++ The ``token_auth`` seam consults only these, so OAuth/password-only+ providers are never asked to ``verify_token``. Empty => a token-authable+ route fails closed (401), never open."""return [p for p in list_providers() if getattr(p, "supports_token", False)]def list_session_providers() -> List[DashboardAuthProvider]:- """Registered providers with supports_session True (interactive cookie- sessions). The login page, /auth/login, and the gate's verify/refresh loops- consult only these. Mirror of list_token_providers.- """+ """Providers with ``supports_session`` True (interactive cookie sessions);+ the login page, /auth/login and the gate's verify/refresh loops use only these."""return [p for p in list_providers() if getattr(p, "supports_session", True)]def register_global_provider(provider: DashboardAuthProvider) -> None:"""Register a host-owned provider in the process-global slot (upsert).- The dashboard auth registry is process-global and shared across every- profile the dashboard serves from one process, so its providers must- outlive any single per-home plugin manager. Unlike ``register_provider``- this always targets the global ``_providers`` map (never a per-home- overlay) and *replaces* any same-name entry instead of raising, so a- forced plugin re-discovery (e.g. after a password change) rotates the- provider in place. Pairs with ``unregister_global_provider`` for teardown- of the exact object still current (#91701).+ The registry is process-global and shared across every profile one+ dashboard process serves, so these providers outlive any per-home plugin+ manager. Always targets ``_providers`` (never a per-home overlay) and+ *replaces* a same-name entry instead of raising, so a forced plugin+ re-discovery (e.g. after a password change) rotates the provider in place.+ Pairs with ``unregister_global_provider``."""assert_protocol_compliance(type(provider))with _lock:_providers[provider.name] = provider- _log.info(- "dashboard-auth: registered global provider %r (%s)",- provider.name, provider.display_name,- )+ _log_registered("global provider ", provider)-def unregister_global_provider(- name: str,- provider: DashboardAuthProvider,-) -> bool:- """Remove a global provider registration if ``provider`` is still current.-- Identity-conditional so a stale handle (whose provider was already- replaced by a later ``register_global_provider``) never clears the live- registration.- """+def unregister_global_provider(name: str, provider: DashboardAuthProvider) -> bool:+ """Remove a global registration if ``provider`` is still current (a stale+ handle whose provider was already replaced never clears the live one)."""with _lock:if _providers.get(name) is provider:_providers.pop(name, None)diff --git a/hermes_cli/dashboard_auth/request_utils.py b/hermes_cli/dashboard_auth/request_utils.pyindex e52e5e6416c..93ca543bed1 100644--- a/hermes_cli/dashboard_auth/request_utils.py+++ b/hermes_cli/dashboard_auth/request_utils.py@@ -88,7 +88,8 @@ def scan_session_providers(on_swallow(provider)continueexcept ProviderError as e:- log.warning("dashboard-auth: provider %r unreachable during %s: %s", provider.name, phase, e)+ log.warning("dashboard-auth: provider %r unreachable during %s: %s",+ provider.name, phase, e)if on_unreachable is not None:on_unreachable(provider)if unreachable is None:diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex 88576067bdb..7973e1c05a9 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -28,7 +28,9 @@ from fastapi import APIRouter, HTTPException, Requestfrom fastapi.responses import HTMLResponse, JSONResponse, RedirectResponsefrom pydantic import BaseModel-from hermes_cli.dashboard_auth import get_provider, list_providers, list_session_providers, native_flow+from hermes_cli.dashboard_auth import (+ get_provider, list_providers, list_session_providers, native_flow,+)from hermes_cli.dashboard_auth import prefix as _prefix_modfrom hermes_cli.dashboard_auth.audit import AuditEvent, audit_logfrom hermes_cli.dashboard_auth.base import (@@ -124,7 +126,9 @@ def _bearer_payload(session: Session) -> dict[str, Any]:}-def _finish_native_login(request: Request, *, broker_state: str, session: Session, provider: str) -> str:+def _finish_native_login(+ request: Request, *, broker_state: str, session: Session, provider: str,+) -> str:"""Mint the one-time loopback code for a pending native authorization.Shared tail of ``/auth/callback`` and ``/auth/password-login``: returns the@@ -136,16 +140,19 @@ def _finish_native_login(request: Request, *, broker_state: str, session: Sessiopending = native_flow.get_pending(broker_state)gw_code = native_flow.complete_pending(broker_state, session=session)except native_flow.NativeFlowError:- audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, provider=provider, reason="pending_not_found", ip=ip)+ audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, provider=provider, reason="pending_not_found",+ ip=ip)raise _http(400, _NATIVE_EXPIRED_DETAIL)sep = "&" if "?" in pending.redirect_uri else "?"- loopback = f"{pending.redirect_uri}{sep}{urlencode({'code': gw_code, 'state': pending.client_state})}"+ query = urlencode({'code': gw_code, 'state': pending.client_state})+ loopback = f"{pending.redirect_uri}{sep}{query}"audit_log(AuditEvent.NATIVE_CODE_ISSUED, provider=provider, user_id=session.user_id, ip=ip)return loopbackdef _login_failure(request: Request, provider: str, reason: str, **extra) -> None:- audit_log(AuditEvent.LOGIN_FAILURE, provider=provider, reason=reason, **extra, ip=_client_ip(request))+ audit_log(AuditEvent.LOGIN_FAILURE, provider=provider, reason=reason, **extra,+ ip=_client_ip(request))def _login_success(request: Request, session: Session, provider: str) -> None:@@ -301,7 +308,9 @@ async def auth_native_authorize(_set_pkce(resp, request, {"provider": p.name, "broker": broker_state})return resp- resp = _start_upstream_login(request, p, audit_failure=False, extra_pkce={"broker": broker_state})+ resp = _start_upstream_login(+ request, p, audit_failure=False, extra_pkce={"broker": broker_state},+ )audit_log(AuditEvent.NATIVE_AUTHORIZE_START, provider=p.name, ip=_client_ip(request))return resp@@ -435,7 +444,8 @@ async def auth_password_login(request: Request, body: _PasswordLoginBody):pkce_parts = parse_pkce_payload(pkce_raw) if pkce_raw else {}broker_state = pkce_parts.get("broker", "")if broker_state and pkce_parts.get("provider", "") != body.provider:- audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, provider=body.provider, reason="provider_mismatch", ip=ip)+ audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, provider=body.provider,+ reason="provider_mismatch", ip=ip)raise _http(400, "This native sign-in was started for a different provider; ""use that provider's form or restart sign-in.")@@ -518,7 +528,8 @@ async def api_auth_ws_ticket(request: Request):from hermes_cli.dashboard_auth.ws_tickets import TTL_SECONDS, mint_ticketticket = mint_ticket(user_id=sess.user_id, provider=sess.provider)- audit_log(AuditEvent.WS_TICKET_MINTED, provider=sess.provider, user_id=sess.user_id, ip=_client_ip(request))+ audit_log(AuditEvent.WS_TICKET_MINTED, provider=sess.provider, user_id=sess.user_id,+ ip=_client_ip(request))return {"ticket": ticket, "ttl_seconds": TTL_SECONDS}@@ -541,7 +552,8 @@ async def auth_native_token(request: Request, body: _NativeTokenBody):try:session = native_flow.redeem_code(code=body.code, code_verifier=body.code_verifier)except native_flow.CodeInvalid:- audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, reason="invalid_code_or_pkce", ip=_client_ip(request))+ audit_log(AuditEvent.NATIVE_TOKEN_FAILURE, reason="invalid_code_or_pkce",+ ip=_client_ip(request))raise _http(400, "Invalid or expired authorization code.")audit_log(AuditEvent.NATIVE_TOKEN_SUCCESS, provider=session.provider, user_id=session.user_id,@@ -578,8 +590,10 @@ async def auth_native_refresh(request: Request, body: _NativeRefreshBody):ip=_client_ip(request),)return _bearer_payload(session)- audit_log(AuditEvent.REFRESH_FAILURE, reason="all_providers_rejected_rt", ip=_client_ip(request))+ audit_log(AuditEvent.REFRESH_FAILURE, reason="all_providers_rejected_rt",+ ip=_client_ip(request))return JSONResponse(- {"error": "session_expired", "detail": "Refresh token expired or invalid; start a new sign-in."},+ {"error": "session_expired",+ "detail": "Refresh token expired or invalid; start a new sign-in."},status_code=401,)diff --git a/hermes_cli/dashboard_auth/token_auth.py b/hermes_cli/dashboard_auth/token_auth.pyindex 821f5531a8d..0093173b809 100644--- a/hermes_cli/dashboard_auth/token_auth.py+++ b/hermes_cli/dashboard_auth/token_auth.py@@ -1,16 +1,16 @@"""Route-agnostic non-interactive (bearer-token) auth seam for the dashboard.-The generic API-token capability any machine-credential provider plugs into-(the drain bearer-secret plugin is merely the first consumer). A route opts in-by registering its exact path via :func:`register_token_route`; only registered-paths are token-authable, so the auth surface of existing routes never widens.+Any machine-credential provider plugs in here (the drain bearer-secret plugin is+the first consumer). A route opts in by registering its exact path via+:func:`register_token_route`; only registered paths are token-authable, so the+auth surface of existing routes never widens.:func:`token_auth_middleware` runs OUTERMOST (installed last in web_server.py)and fully owns the decision for a token route: a recognised token attaches``request.state.token_principal`` + ``token_authenticated`` (the cookie gates-honour that flag and never bounce the request to /login); otherwise 401, or-503 when a provider's backing store was unreachable. Fails closed: no-provider, no token, or an unrecognised token is always 401.+honour that flag and never bounce to /login); otherwise 401, or 503 when a+provider's backing store was unreachable. Fails closed: no provider, no token,+or an unrecognised token is always 401."""from __future__ import annotations@@ -55,9 +55,7 @@ def clear_token_routes() -> None:_token_routes.clear()-def authenticate_token(- request: Request,-) -> Tuple[Optional[TokenPrincipal], Optional[str]]:+def authenticate_token(request: Request) -> Tuple[Optional[TokenPrincipal], Optional[str]]:"""Try every token provider against the request's bearer token.Returns ``(principal, None)`` on success; ``(None, None)`` for no token or@@ -73,18 +71,14 @@ def authenticate_token(try:principal = provider.verify_token(token=token)except ProviderError as e:- _log.warning(- "dashboard-auth: token provider %r unreachable during verify: %s",- provider.name, e,- )+ _log.warning("dashboard-auth: token provider %r unreachable during verify: %s",+ provider.name, e)if unreachable is None:unreachable = provider.namecontinueexcept Exception as e: # noqa: BLE001 — a buggy provider must not 500 the gate- _log.warning(- "dashboard-auth: token provider %r raised during verify: %s",- provider.name, e,- )+ _log.warning("dashboard-auth: token provider %r raised during verify: %s",+ provider.name, e)continueif principal is not None:return principal, None@@ -92,8 +86,7 @@ def authenticate_token(async def token_auth_middleware(- request: Request,- call_next: Callable[[Request], Awaitable[Response]],+ request: Request, call_next: Callable[[Request], Awaitable[Response]],) -> Response:"""Outermost auth seam: pass-through for unregistered paths; for a tokenroute, valid token -> attach principal + flag, unreachable -> 503, else 401."""@@ -109,21 +102,13 @@ async def token_auth_middleware(if unreachable:audit_log(- AuditEvent.TOKEN_AUTH_FAILURE,- provider=unreachable,- reason="provider_unreachable",- path=path,- ip=_client_ip(request),+ AuditEvent.TOKEN_AUTH_FAILURE, provider=unreachable, reason="provider_unreachable",+ path=path, ip=_client_ip(request),)return unreachable_response(unreachable)audit_log(- AuditEvent.TOKEN_AUTH_FAILURE,- reason="no_provider_recognises_token",- path=path,+ AuditEvent.TOKEN_AUTH_FAILURE, reason="no_provider_recognises_token", path=path,ip=_client_ip(request),)- return JSONResponse(- {"error": "unauthenticated", "detail": "Unauthorized"},- status_code=401,- )+ return JSONResponse({"error": "unauthenticated", "detail": "Unauthorized"}, status_code=401)diff --git a/hermes_cli/dashboard_auth/ws_tickets.py b/hermes_cli/dashboard_auth/ws_tickets.pyindex 118a988e142..74a683f1456 100644--- a/hermes_cli/dashboard_auth/ws_tickets.py+++ b/hermes_cli/dashboard_auth/ws_tickets.py@@ -1,32 +1,21 @@"""WS-upgrade auth credentials for gated mode.-Browsers cannot set ``Authorization`` on a WebSocket upgrade. In loopback-mode the legacy ``?token=<_SESSION_TOKEN>`` query param works because the-token is injected into the SPA bundle. In gated mode there is no injected-token — so this module provides two credential shapes:--1. **Single-use browser tickets** (``mint_ticket`` / ``consume_ticket``).- The SPA gets a fresh ticket via the authenticated REST endpoint- ``POST /api/auth/ws-ticket`` and passes it as ``?ticket=`` on the WS- upgrade. Single-use, TTL = 30 seconds — a leaked ticket is uninteresting.+Browsers cannot set ``Authorization`` on a WebSocket upgrade, and gated mode+has no token injected into the SPA, so two credential shapes exist:+1. **Single-use browser tickets** (``mint_ticket`` / ``consume_ticket``): the+ SPA fetches one via authenticated ``POST /api/auth/ws-ticket`` and passes it+ as ``?ticket=`` on the upgrade. Single-use, 30 s TTL — a leak is uninteresting.2. **A process-lifetime internal credential** (``internal_ws_credential`` /- ``consume_internal_credential``). This authenticates *server-spawned*- WS clients — specifically the embedded-TUI PTY child, which attaches to- ``/api/ws`` (JSON-RPC gateway) and ``/api/pub`` (event sidecar) over- loopback. A single-use 30s ticket is the wrong shape for that link: the- child reads its attach URL once at startup and **reuses it on every- reconnect**, and on a slow cold boot the child may not dial within 30s.- The internal credential is minted once per process, never expires, is- multi-use, and — critically — is **never injected into any HTML/SPA**:- it only ever leaves the process via the spawned child's environment, so- browser-side XSS cannot read it. A leaked internal credential grants no- more than a single-use ticket already does (the same two internal WS- endpoints), and the same Origin / host guards still apply downstream.--In-memory; the dashboard is a single process so no distributed coordination-is needed. The module exposes a small functional API rather than a class so-tests can patch ``time.time`` cleanly.+ ``consume_internal_credential``) for *server-spawned* WS clients (the+ embedded-TUI PTY child on ``/api/ws`` + ``/api/pub``), which read their attach+ URL once and reuse it on every reconnect, possibly >30 s after a cold boot.+ Minted once, never expires, multi-use, and never injected into any HTML/SPA:+ it leaves the process only via the child's environment, so browser XSS cannot+ read it; a leak grants no more than a ticket does (same two endpoints, same+ Origin/host guards).++In-memory (single process). Functional API so tests can patch ``time.time``."""from __future__ import annotations@@ -36,21 +25,18 @@ import threadingimport timefrom typing import Any, Dict, Optional, Tuple-#: Time-to-live for newly-minted tickets in seconds. 30 s is long enough-#: that the SPA can call ``getWsTicket()`` and immediately open the WS,-#: short enough that a leaked ticket is uninteresting.+#: Ticket TTL: long enough for ``getWsTicket()`` -> open WS, short enough that+#: a leaked ticket is uninteresting.TTL_SECONDS = 30_lock = threading.Lock()_tickets: Dict[str, Tuple[int, Dict[str, Any]]] = {} # ticket -> (expires_at, info)-#: The process-lifetime internal credential (see module docstring). Lazily-#: minted on first ``internal_ws_credential()`` call and stable for the life-#: of the process. Guarded by ``_lock``.+#: Process-lifetime internal credential, lazily minted; guarded by ``_lock``._internal_credential: Optional[str] = None-#: Identity recorded for connections that authenticate via the internal-#: credential, so audit logs distinguish them from browser-initiated tickets.+#: Identity recorded for internal-credential connections so audit logs+#: distinguish them from browser-initiated tickets.INTERNAL_USER_ID = "server-internal"INTERNAL_PROVIDER = "server-internal"@@ -60,18 +46,10 @@ class TicketInvalid(Exception):def mint_ticket(*, user_id: str, provider: str) -> str:- """Generate a one-shot ticket bound to this user identity.-- The returned token is base64url, 43 bytes of entropy (32-byte random- seed). Stash returns the ``info`` dict to the caller on consume so the- WS handler can carry the identity forward into its session log.- """+ """Generate a one-shot base64url ticket (32 random bytes) bound to this+ identity; ``consume_ticket`` hands the ``info`` dict back to the WS handler."""ticket = secrets.token_urlsafe(32)- info = {- "user_id": user_id,- "provider": provider,- "minted_at": int(time.time()),- }+ info = {"user_id": user_id, "provider": provider, "minted_at": int(time.time())}with _lock:_tickets[ticket] = (int(time.time()) + TTL_SECONDS, info)_gc_expired_locked()@@ -79,18 +57,13 @@ def mint_ticket(*, user_id: str, provider: str) -> str:def consume_ticket(ticket: str) -> Dict[str, Any]:- """Validate and consume. Raises :class:`TicketInvalid` on missing/expired/used.-- Single-use semantics: a successful consume immediately removes the- ticket from the store, so a second call with the same value raises- ``TicketInvalid("unknown ticket: …")``.- """+ """Validate and consume (single-use: a second call raises). Raises+ :class:`TicketInvalid` on missing/expired/used."""now = int(time.time())with _lock:entry = _tickets.pop(ticket, None)if entry is None:- # Truncate ticket value in the error so misuse never logs the- # secret in full.+ # Truncated so misuse never logs the secret in full.truncated = (ticket[:8] + "…") if ticket else "<empty>"raise TicketInvalid(f"unknown ticket: {truncated}")expires_at, info = entry@@ -102,22 +75,15 @@ def consume_ticket(ticket: str) -> Dict[str, Any]:def _gc_expired_locked() -> None:"""Drop expired tickets. Caller must hold ``_lock``."""now = int(time.time())- expired = [t for t, (exp, _) in _tickets.items() if exp < now]- for t in expired:+ for t in [t for t, (exp, _) in _tickets.items() if exp < now]:_tickets.pop(t, None)def internal_ws_credential() -> str:"""Return the process-lifetime internal WS credential, minting it once.- Used by the server to authenticate WS clients it spawns itself (the- embedded-TUI PTY child). The value is stable for the life of the process,- multi-use, and never expires — so a server-spawned child can reconnect- its ``/api/ws`` / ``/api/pub`` sockets indefinitely without re-minting.-- The credential is never injected into the SPA HTML or returned over any- REST endpoint; it is only ever passed to a child process via its- environment. See the module docstring for the threat-model rationale.+ Stable, multi-use, never expires; never injected into the SPA or returned+ over REST — only passed to a spawned child via its environment."""global _internal_credentialwith _lock:@@ -127,19 +93,11 @@ def internal_ws_credential() -> str:def consume_internal_credential(value: str) -> Dict[str, Any]:- """Validate an internal credential. Raises :class:`TicketInvalid` on mismatch.-- Unlike :func:`consume_ticket` this is **not** single-use — the value is- not removed on success, so a server-spawned child can present it on every- (re)connect. Returns the fixed server-internal identity ``info`` dict- (``{user_id, provider}``), mirroring the ``info`` shape ``consume_ticket``- returns, so a caller that wants to record the connecting identity can; the- current ``_ws_auth_ok`` caller validates for the boolean outcome only and- discards the dict.-- A constant-time compare against the (lazily-minted) credential avoids- leaking length / prefix information on mismatch. If no internal- credential has been minted yet, any value is rejected.+ """Validate an internal credential (NOT single-use). Raises :class:`TicketInvalid`.++ Returns the fixed server-internal ``{user_id, provider}`` info dict, mirroring+ ``consume_ticket``. Constant-time compare; any value is rejected until a+ credential has been minted."""with _lock:expected = _internal_credential@@ -147,10 +105,7 @@ def consume_internal_credential(value: str) -> Dict[str, Any]:raise TicketInvalid("no internal credential")if not secrets.compare_digest(value.encode(), expected.encode()):raise TicketInvalid("internal credential mismatch")- return {- "user_id": INTERNAL_USER_ID,- "provider": INTERNAL_PROVIDER,- }+ return {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}def _reset_for_tests() -> None: