The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(hermes_cli): dashboard_auth docstring/comment compaction (keep WHY); native_flow pending lookup helper; prefix warn-once helper; commands registry repack
Teknium7443080d5a15
diff --git a/hermes_cli/commands.py b/hermes_cli/commands.pyindex 9f80a57d29a..a2a610e60f8 100644--- a/hermes_cli/commands.py+++ b/hermes_cli/commands.py@@ -90,8 +90,7 @@ COMMAND_REGISTRY: list[CommandDef] = [CommandDef("stop", "Kill all running background processes", "Session",busy_policy="interrupt_then_dispatch", busy_handler="stop"),CommandDef("pause", "Pause new work globally (emergency stop); '/pause off' resumes", "Session",- gateway_only=True, args_hint="[reason | off]",- busy_policy="dispatch"),+ gateway_only=True, args_hint="[reason | off]", busy_policy="dispatch"),CommandDef("approve", "Approve a pending dangerous command", "Session",gateway_only=True, args_hint="[session|always]", busy_policy="dispatch",desktop="messaging"),@@ -106,11 +105,9 @@ COMMAND_REGISTRY: list[CommandDef] = [aliases=("tasks",), busy_policy="dispatch"),CommandDef("journey", "Open the learning journey timeline","Session", aliases=("learning", "memory-graph"), cli_only=True,- args_hint="[list|delete <id>|edit <id>]",- subcommands=("list", "delete", "edit")),+ args_hint="[list|delete <id>|edit <id>]", subcommands=("list", "delete", "edit")),CommandDef("queue", "Queue a prompt for the next turn (doesn't interrupt)", "Session",- aliases=("q",), args_hint="<prompt>",- busy_policy="dispatch", busy_handler="queue"),+ aliases=("q",), args_hint="<prompt>", busy_policy="dispatch", busy_handler="queue"),CommandDef("steer", "Inject a message after the next tool call without interrupting", "Session",args_hint="<prompt>", busy_policy="dispatch", busy_handler="steer"),CommandDef("goal", "Set a standing goal Hermes works on across turns until achieved", "Session",@@ -137,12 +134,10 @@ COMMAND_REGISTRY: list[CommandDef] = [CommandDef("status", "Show session, model, token, and context info", "Session",busy_policy="dispatch"),CommandDef("egress", "Show Docker egress proxy status", "Session",- args_hint="[status]", subcommands=("status",),- busy_policy="dispatch", busy_handler="egress",- execute="egress"),+ args_hint="[status]", subcommands=("status",), busy_policy="dispatch",+ busy_handler="egress", execute="egress"),CommandDef("context", "Show detailed context window view with usage gauge, category breakdown, compression stats, and throughput", "Session",- aliases=("ctx",), args_hint="[all]", subcommands=("all",),- busy_policy="dispatch"),+ aliases=("ctx",), args_hint="[all]", subcommands=("all",), busy_policy="dispatch"),CommandDef("whoami", "Show your slash command access (admin / user)", "Info"),CommandDef("profile", "Show active profile name and home directory", "Info",busy_policy="dispatch", execute="profile"),@@ -159,8 +154,7 @@ COMMAND_REGISTRY: list[CommandDef] = [args_hint="[model] [--provider name] [--global|--session] [--refresh]",busy_policy="reject", busy_handler="model", desktop="hidden"),CommandDef("codex-runtime", "Toggle codex app-server runtime for OpenAI/Codex models",- "Configuration", aliases=("codex_runtime",),- args_hint="[auto|codex_app_server]",+ "Configuration", aliases=("codex_runtime",), args_hint="[auto|codex_app_server]",busy_policy="reject", busy_handler="codex-runtime"),CommandDef("personality", "Set a predefined personality", "Configuration",args_hint="[name]", argument_mode="options"),@@ -176,16 +170,14 @@ COMMAND_REGISTRY: list[CommandDef] = [args_hint="[staged|all|session] [--stat] [path...]",subcommands=("staged", "all", "session")),CommandDef("verbose", "Cycle tool progress display: off -> new -> all -> verbose",- "Configuration", cli_only=True,- gateway_config_gate="display.tool_progress_command",+ "Configuration", cli_only=True, gateway_config_gate="display.tool_progress_command",busy_policy="dispatch", desktop="terminal"),CommandDef("focus", "Toggle focus view — show only your prompt and the final response","Configuration", cli_only=True, args_hint="[on|off|status]",subcommands=("on", "off", "status")),CommandDef("footer", "Toggle gateway runtime-metadata footer on final replies",- "Configuration", args_hint="[on|off|status]",- subcommands=("on", "off", "status"), busy_policy="dispatch",- desktop="terminal"),+ "Configuration", args_hint="[on|off|status]", subcommands=("on", "off", "status"),+ busy_policy="dispatch", desktop="terminal"),CommandDef("yolo", "Toggle YOLO mode (skip all dangerous command approvals)","Configuration", busy_policy="dispatch"),CommandDef("approvals", "Show or set the persistent dangerous-command approval mode",@@ -208,8 +200,7 @@ COMMAND_REGISTRY: list[CommandDef] = [args_hint="[on|off|tts|status]", subcommands=("on", "off", "tts", "status"),desktop="composer-voice"),CommandDef("wake", "Toggle the 'Hey Hermes' wake word listener", "Configuration",- cli_only=True, args_hint="[on|off|status]",- subcommands=("on", "off", "status")),+ cli_only=True, args_hint="[on|off|status]", subcommands=("on", "off", "status")),CommandDef("busy", "Control how messages behave while Hermes is working", "Configuration",args_hint="[queue|steer|interrupt|status]",subcommands=("queue", "steer", "interrupt", "status"),@@ -217,8 +208,7 @@ COMMAND_REGISTRY: list[CommandDef] = [# Tools & SkillsCommandDef("tools", "Manage tools: /tools [list|disable|enable] [name...]", "Tools & Skills",- args_hint="[list|disable|enable] [name...]", cli_only=True,- argument_mode="options"),+ args_hint="[list|disable|enable] [name...]", cli_only=True, argument_mode="options"),CommandDef("toolsets", "List available toolsets", "Tools & Skills",cli_only=True, desktop="terminal"),CommandDef("skills", "Search, install, inspect, or manage skills",@@ -228,8 +218,7 @@ COMMAND_REGISTRY: list[CommandDef] = ["pending", "approve", "reject", "diff", "approval"),desktop="settings"),CommandDef("memory", "Review pending memory writes / toggle the approval gate",- "Tools & Skills",- args_hint="[pending|approve|reject|approval] [id|on|off]",+ "Tools & Skills", args_hint="[pending|approve|reject|approval] [id|on|off]",subcommands=("pending", "approve", "reject", "approval")),CommandDef("bundles", "List skill bundles (aliases /<name> for multiple skills)","Tools & Skills", execute="bundles"),@@ -311,9 +300,7 @@ COMMAND_REGISTRY: list[CommandDef] = [# ExitCommandDef("quit", "Exit the CLI (use --delete to also remove session history)", "Exit",- cli_only=True, aliases=("exit",), args_hint="[--delete]",- desktop="terminal"),-]+ cli_only=True, aliases=("exit",), args_hint="[--delete]", desktop="terminal")]# Distinguishes ``mixed`` (subcommands plus free-text) from ``options``; no subcommands => ``text``.@@ -382,8 +369,7 @@ HELP_SESSION_SUBGROUPS: dict[str, tuple[str, ...]] = {"Context": ("compress", "compact", "context", "ctx", "status"),"Background & Automation": ("bg", "btw", "agents", "tasks", "queue", "q", "steer", "goal", "subgoal", "heartbeat", "hb",- "refine", "loop", "proactive", "moa", "journey", "learning", "memory-graph"),-}+ "refine", "loop", "proactive", "moa", "journey", "learning", "memory-graph")}# All names + aliases the gateway dispatches. Config-gated commands are# included; their handler checks the gate at runtime.diff --git a/hermes_cli/dashboard_auth/__init__.py b/hermes_cli/dashboard_auth/__init__.pyindex 9e3fc6fd6f2..d08372826c5 100644--- a/hermes_cli/dashboard_auth/__init__.py+++ b/hermes_cli/dashboard_auth/__init__.py@@ -1,24 +1,17 @@-"""Dashboard authentication provider framework.--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``.-"""+"""Dashboard authentication provider framework. 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`` (Nous provider 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,- classify_jwks_lookup_error,-)+ 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,-)+ 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",-]+ "list_token_providers", "list_session_providers", "clear_providers"]diff --git a/hermes_cli/dashboard_auth/audit.py b/hermes_cli/dashboard_auth/audit.pyindex 24294ec51bc..7ebe401f53f 100644--- a/hermes_cli/dashboard_auth/audit.py+++ b/hermes_cli/dashboard_auth/audit.py@@ -1,10 +1,7 @@-"""Audit log for dashboard-auth events.--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.-"""+"""Audit log for dashboard-auth events: ``$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 annotationsimport datetime as _dt@@ -26,7 +23,6 @@ _REDACTED_FIELDS: frozenset = frozenset({class AuditEvent(enum.Enum):"""Event types; values are the literal ``event`` field on the JSON line."""-LOGIN_START = "login_start"LOGIN_SUCCESS = "login_success"LOGIN_FAILURE = "login_failure"@@ -47,19 +43,14 @@ class AuditEvent(enum.Enum):def _resolve_log_path() -> Path:- """``$HERMES_HOME/logs/dashboard-auth.log`` (lazy leaf import: honours- profile overrides and the native-Windows ``%LOCALAPPDATA%`` fallback)."""+ """Lazy leaf import: honours profile overrides + the native-Windows ``%LOCALAPPDATA%`` fallback."""from hermes_constants import get_hermes_home-return get_hermes_home() / "logs" / "dashboard-auth.log"def audit_log(event: AuditEvent, **fields: Any) -> None:- """Append one event; token-like fields dropped, log dir created.-- Write failures are logged at WARNING but never raise — auth must not- fail because the audit logger broke.- """+ """Append one event; token-like fields dropped, log dir created. Write failures are logged at+ WARNING but never raise — auth must not fail because the audit logger broke."""entry = {"ts": _dt.datetime.now(_dt.timezone.utc).isoformat(),"event": event.value,diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 17ed5d2b13c..7aee171215f 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -8,12 +8,8 @@ from typing import Optional@dataclass(frozen=True)class Session:- """A verified interactive identity (from ``complete_login`` / ``verify_session``).-- All fields mandatory; providers without orgs set ``org_id=""``. The tokens- are opaque to Hermes.- """-+ """A verified interactive identity (from ``complete_login`` / ``verify_session``). All fields+ mandatory; providers without orgs set ``org_id=""``. The tokens are opaque to Hermes."""user_id: stremail: strdisplay_name: str@@ -26,13 +22,9 @@ class Session:@dataclass(frozen=True)class TokenPrincipal:- """A verified non-interactive (service-to-service) caller — the token analog- of :class:`Session`: one bearer token on one request, no login/cookie/refresh.-- ``principal`` is an opaque stable caller id; ``scopes`` empty means- "unscoped" (a route MAY enforce a required scope).- """-+ """A verified non-interactive (service-to-service) caller — the token analog of+ :class:`Session`: one bearer token on one request, no login/cookie/refresh. ``principal`` is+ an opaque stable caller id; ``scopes`` empty means "unscoped" (a route MAY enforce one)."""principal: strprovider: strscopes: tuple[str, ...] = ()@@ -40,14 +32,9 @@ class TokenPrincipal:@dataclass(frozen=True)class LoginStart:- """First leg of the OAuth round trip.-- ``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``).- """-+ """First leg of the OAuth round trip: ``redirect_url`` is the IDP's authorize endpoint;+ ``cookie_payload`` maps cookie name -> serialised PKCE/CSRF state that the auth route sets+ (HttpOnly, Secure + ``SameSite=None`` over HTTPS, TTL <= 10 min; see ``set_pkce_cookie``)."""redirect_url: strcookie_payload: dict[str, str]@@ -61,33 +48,28 @@ class InvalidCodeError(Exception):class InvalidCredentialsError(Exception):- """Username/password rejected. The route answers a generic 401 (never- distinguishing unknown user from wrong password — no username oracle)."""+ """Username/password rejected. The route answers a generic 401 (no username oracle)."""class RefreshExpiredError(Exception):- """This provider rejects the refresh token. Not proof of ownership in a- multi-provider deployment, so middleware tries the remaining providers and- forces re-login only after every reachable one rejects it."""+ """This provider rejects the refresh token. Not proof of ownership in a multi-provider+ deployment: middleware tries the rest and forces re-login only after every reachable one+ rejects it."""def classify_jwks_lookup_error(exc: BaseException) -> Exception:- """Map a ``PyJWKClient.get_signing_key_from_jwt`` failure to the protocol.-- Only a genuine transport failure (``PyJWKClientConnectionError``, or an- unexpected JWKS shape) is a :class:`ProviderError` (503, never forces logout).- A non-JWT bearer (``DecodeError``), a JWKS with no key for this ``kid``- (``PyJWKSetError``) or any other invalid token is simply not verifiable by this- provider -> :class:`InvalidCodeError` (``verify_session`` returns ``None``).- Folding "cannot parse" into "cannot reach" once made every opaque bearer a- fast 503 against a healthy Portal.- """+ """Map a ``PyJWKClient.get_signing_key_from_jwt`` failure to the protocol. Only a genuine+ transport failure (``PyJWKClientConnectionError``, or an unexpected JWKS shape) is a+ :class:`ProviderError` (503, never forces logout). A non-JWT bearer (``DecodeError``), a JWKS+ with no key for this ``kid`` (``PyJWKSetError``) or any other invalid token is simply not+ verifiable by this provider -> :class:`InvalidCodeError` (``verify_session`` returns ``None``).+ Folding "cannot parse" into "cannot reach" once made every opaque bearer a fast 503."""try: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.+ # Order matters: DecodeError/PyJWKSetError before their PyJWKClientError/InvalidTokenError+ # parents.if isinstance(exc, jwt.PyJWKClientConnectionError):return ProviderError(f"JWKS lookup failed: {exc}")if isinstance(exc, (jwt.DecodeError, jwt.PyJWKSetError)):@@ -102,29 +84,21 @@ def classify_jwks_lookup_error(exc: BaseException) -> Exception:class DashboardAuthProvider(ABC):"""Protocol every dashboard-auth provider plugin implements.- Lifecycle: ``start_login`` (redirect URL + PKCE state) -> IDP ->- ``complete_login`` (code + verifier -> Session) -> ``verify_session`` per- request -> ``refresh_session`` near expiry -> ``revoke_session`` on logout- (best-effort, must not raise).-- Failure semantics:- * ``start_login`` / ``complete_login`` raise ``ProviderError`` when the IDP- is unreachable; ``complete_login`` raises ``InvalidCodeError`` on a bad- code/state.- * ``verify_session`` returns ``None`` for expired/unknown tokens (middleware- refreshes) and raises ``ProviderError`` when unreachable (503).- * ``refresh_session`` raises ``RefreshExpiredError`` when the token is invalid- for that provider (an opaque foreign token looks expired, so middleware- tries the rest) and ``ProviderError`` on network failure (503, cookies kept).-- Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``.- Capability flags: ``supports_password`` (credential form +- ``complete_password_login``; OAuth methods may be ``NotImplementedError``- stubs), ``supports_token`` (``verify_token`` for the token-auth seam),- ``supports_session`` (False for token-only credentials such as drain, never- offered a login). Everything downstream of login is identical for every session.+ Lifecycle: ``start_login`` (redirect URL + PKCE state) -> IDP -> ``complete_login`` (code ++ verifier -> Session) -> ``verify_session`` per request -> ``refresh_session`` near expiry ->+ ``revoke_session`` on logout (best-effort, must not raise). Failure semantics: ``start_login``+ / ``complete_login`` raise ``ProviderError`` when the IDP is unreachable, ``complete_login``+ ``InvalidCodeError`` on a bad code/state; ``verify_session`` returns ``None`` for+ expired/unknown tokens (middleware refreshes) and raises ``ProviderError`` when unreachable+ (503); ``refresh_session`` raises ``RefreshExpiredError`` when the token is invalid for that+ provider (a foreign opaque token looks expired, so middleware tries the rest) and+ ``ProviderError`` on network failure (503, cookies kept).++ Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``. Capability flags:+ ``supports_password`` (credential form + ``complete_password_login``; OAuth methods may be+ ``NotImplementedError`` stubs), ``supports_token`` (``verify_token`` for the token-auth seam),+ ``supports_session`` (False for token-only credentials such as drain, never offered a login)."""-name: str = ""display_name: str = ""supports_password: bool = False@@ -136,8 +110,7 @@ class DashboardAuthProvider(ABC):@abstractmethoddef complete_login(- self, *, code: str, state: str, code_verifier: str, redirect_uri: str,- ) -> Session: ...+ self, *, code: str, state: str, code_verifier: str, redirect_uri: str) -> Session: ...@abstractmethoddef verify_session(self, *, access_token: str) -> Optional[Session]: ...@@ -149,35 +122,27 @@ class DashboardAuthProvider(ABC):def revoke_session(self, *, refresh_token: str) -> None: ...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- ``InvalidCredentialsError`` on rejection (SHOULD be constant time for- unknown users — no timing oracle) and ``ProviderError`` when the store is- unreachable. The default raises so a mis-flagged provider fails loudly.- """+ """Verify a username/password pair and mint a :class:`Session` (only called when+ ``supports_password``). Raise ``InvalidCredentialsError`` on rejection (SHOULD be constant+ time for unknown users — no timing oracle) and ``ProviderError`` when the store is+ unreachable. The default raises so a mis-flagged provider fails loudly."""raise NotImplementedError(f"{type(self).__name__} does not support password login "- "(set supports_password = True and override "- "complete_password_login)")+ "(set supports_password = True and override complete_password_login)")def verify_token(self, *, token: str) -> "Optional[TokenPrincipal]":- """Verify a non-interactive bearer token; return its principal.-- Mirrors ``verify_session``: return ``None`` (never raise) for an- unrecognised token so the seam falls through; raise ``ProviderError`` ONLY- for a genuine backing-store outage. Shared secrets MUST be compared with- ``hmac.compare_digest``. The default raises so a mis-flagged provider fails- loudly.- """+ """Verify a non-interactive bearer token; return its principal. Mirrors ``verify_session``:+ return ``None`` (never raise) for an unrecognised token so the seam falls through; raise+ ``ProviderError`` ONLY for a genuine backing-store outage. Shared secrets MUST be compared+ with ``hmac.compare_digest``. The default raises so a mis-flagged provider fails loudly."""raise NotImplementedError(f"{type(self).__name__} does not support token auth ""(set supports_token = True and override verify_token)")def assert_protocol_compliance(cls: type) -> None:- """Raise ``TypeError`` if ``cls`` doesn't fully implement the provider protocol- (call it from every provider plugin's unit tests)."""+ """Raise ``TypeError`` if ``cls`` doesn't fully implement the protocol (call it from every+ provider plugin's unit tests)."""for attr in ("name", "display_name"):if not getattr(cls, attr, ""):raise TypeError(f"{cls.__name__} missing or empty attribute: {attr!r}")diff --git a/hermes_cli/dashboard_auth/cookies.py b/hermes_cli/dashboard_auth/cookies.pyindex 49f1bcdb1ff..7e33273bc53 100644--- a/hermes_cli/dashboard_auth/cookies.py+++ b/hermes_cli/dashboard_auth/cookies.py@@ -1,24 +1,16 @@"""Cookie helpers for dashboard auth.-All HttpOnly, ``SameSite=Lax`` unless noted, Path = proxy prefix or /:- - hermes_session_at access token; Max-Age = token TTL (~15 min)- - hermes_session_rt rotating refresh token; written only when the provider- returned one, always cleared on logout/expiry- - hermes_session_provider non-secret routing hint so an RT is not handed to the- wrong provider when several auth plugins are enabled- - hermes_session_pkce PKCE state + CSRF nonce + provider hint, 10 min.- ``SameSite=None; Secure`` over HTTPS: it is set on the- /auth/login 302 and must survive the cross-site redirect- chain (Chromium drops Lax cookies set on such a 302,- crbug 40508226); plain HTTP falls back to Lax.- - hermes_sso_attempt one-shot auto-SSO loop-guard marker (60 s)--``Secure`` only when ``request.url.scheme`` is https (honours ``X-Forwarded-Proto``-only from uvicorn's ``forwarded_allow_ips``). Cookie-prefix hardening per-draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS with-Path=/; ``__Secure-`` behind a proxy prefix (``__Host-`` forbids Path != /). Setters-and readers BOTH resolve the name via :func:`_resolved_name` — a mismatch silently-breaks sessions.+All HttpOnly, ``SameSite=Lax`` unless noted, Path = proxy prefix or /: ``hermes_session_at``+(access token; Max-Age = token TTL), ``hermes_session_rt`` (rotating refresh token; written only+when the provider returned one, always cleared on logout/expiry), ``hermes_session_provider``+(non-secret routing hint so an RT is not handed to the wrong provider), ``hermes_session_pkce``+(PKCE state + CSRF nonce + provider hint, 10 min; ``SameSite=None; Secure`` over HTTPS because it+is set on the /auth/login 302 and must survive the cross-site redirect chain — Chromium drops Lax+cookies set on such a 302, crbug 40508226), ``hermes_sso_attempt`` (auto-SSO loop guard, 60 s).+``Secure`` only when ``request.url.scheme`` is https. Cookie-prefix hardening per+draft-west-cookie-prefixes: bare name over HTTP; ``__Host-`` on gated HTTPS with Path=/;+``__Secure-`` behind a proxy prefix (``__Host-`` forbids Path != /). Setters and readers BOTH+resolve the name via :func:`_resolved_name` — a mismatch silently breaks sessions."""from __future__ import annotations@@ -41,16 +33,14 @@ SSO_ATTEMPT_COOKIE = "hermes_sso_attempt"# Name variants a reader may have to try; most strict first._NAME_VARIANTS = ("__Host-", "__Secure-", "")-# RT cookie lifetime is a generous browser-side upper bound; the provider's own-# RT TTL is the real authority (an expired RT -> RefreshExpiredError -> re-login).+# RT cookie lifetime is a generous browser-side upper bound; the provider's own RT TTL is the+# real authority (an expired RT -> RefreshExpiredError -> re-login)._RT_MAX_AGE = 30 * 24 * 60 * 60_PKCE_MAX_AGE = 10 * 60-# Long enough for one portal round trip / back-button; short enough that a-# user returning later gets a fresh silent attempt rather than a stuck /login.+# Long enough for one portal round trip / back-button; short enough that a user returning later+# gets a fresh silent attempt rather than a stuck /login._SSO_ATTEMPT_MAX_AGE = 60--# Cheap pre-filter: legacy wire forms always contain ``%`` or ``;``, which are-# outside the base64url alphabet, so they never reach the base64 decoder.+# Cheap pre-filter: legacy wire forms always contain ``%`` or ``;`` (outside base64url)._B64URL_RE = re.compile(r"^[A-Za-z0-9_-]+={0,2}$")@@ -62,8 +52,7 @@ def _resolved_name(bare: str, *, use_https: bool, prefix: str) -> str:def _cookie_path(prefix: str) -> str:- """``Path=/hermes`` under a proxy prefix (so the cookie does not leak to- sibling apps), else ``/``."""+ """``Path=/hermes`` under a proxy prefix (no leak to sibling apps), else ``/``."""return prefix if prefix else "/"@@ -101,13 +90,9 @@ def set_session_provider_cookie(def set_session_cookies(response: Response, *, access_token: str, refresh_token: str, access_token_expires_in: int,use_https: bool, prefix: str = "", provider: str = "") -> None:- """Set the session cookies.-- ``access_token_expires_in`` is seconds (the provider's reported TTL). An- empty ``refresh_token`` means "don't persist the RT cookie" — a literal- empty cookie would be dead state at best, attack surface at worst.- ``prefix`` is the normalised X-Forwarded-Prefix or ``""``.- """+ """``access_token_expires_in`` is seconds (the provider's reported TTL). An empty+ ``refresh_token`` means "don't persist the RT cookie" — a literal empty cookie would be dead+ state at best, attack surface at worst."""_set(response, SESSION_AT_COOKIE, access_token, max_age=access_token_expires_in,use_https=use_https, prefix=prefix)if refresh_token:@@ -119,14 +104,10 @@ def set_session_cookies(def _clear_cookie_variants(response: Response, bare_name: str, *, prefix: str,https_samesite: Literal["lax", "strict", "none"], bare_attrs: dict) -> None:- """Emit Max-Age=0 deletions for every plausible name variant of a cookie.-- We don't know which variant the setter used (it depends on the setting- request's shape). Prefixed names are rejected by the browser unless they- carry ``Secure`` (``__Host-`` additionally needs ``Path=/``), so those- deletions always carry them; the bare deletion mirrors the setter's shape- (``bare_attrs``), which works on both HTTP and HTTPS origins.- """+ """Emit Max-Age=0 deletions for every plausible name variant (the setting request's shape is+ unknown). Prefixed names are rejected by the browser unless they carry ``Secure`` (``__Host-``+ additionally ``Path=/``), so those deletions always do; the bare deletion mirrors the setter's+ shape (``bare_attrs``), which works on both HTTP and HTTPS origins."""for variant, path in (("__Host-", "/"), ("__Secure-", _cookie_path(prefix))):response.set_cookie(f"{variant}{bare_name}", "", max_age=0, path=path, httponly=True,@@ -143,41 +124,32 @@ def clear_session_cookies(response: Response, *, prefix: str = "") -> None:def encode_pkce_payload(parts: dict[str, str]) -> str:- """Serialise PKCE segments to the wire value ``base64url(JSON)``, no padding.-- The urlsafe alphabet is a strict subset of RFC 6265 cookie-octets, so- http.cookies never quotes it (strict proxies such as Go net/http reject the- quoted form) and no value can collide with a delimiter. Padding ``=`` would- trigger quoting; the parser restores it.- """+ """Wire value ``base64url(JSON)``, no padding. The urlsafe alphabet is a strict subset of RFC+ 6265 cookie-octets, so http.cookies never quotes it (strict proxies such as Go net/http reject+ the quoted form) and no value can collide with a delimiter; padding ``=`` would trigger+ quoting, the parser restores it."""raw = json.dumps(parts, separators=(",", ":"), sort_keys=True)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:- """Set the PKCE cookie (``payload`` is the segment dict; see module docstring- for the SameSite=None rationale)."""+ """``payload`` is the segment dict; see module docstring for the SameSite=None rationale."""_set(response, PKCE_COOKIE, encode_pkce_payload(payload), max_age=_PKCE_MAX_AGE,use_https=use_https, prefix=prefix, attrs=_pkce_attrs(use_https=use_https, prefix=prefix))def clear_pkce_cookie(response: Response, *, use_https: bool, prefix: str = "") -> None:- """Delete every PKCE cookie variant; the bare deletion mirrors the setter's- shape for the active origin, the prefixed ones carry ``Secure; SameSite=None``."""+ """Delete every PKCE cookie variant (prefixed ones carry ``Secure; SameSite=None``)."""_clear_cookie_variants(response, PKCE_COOKIE, prefix=prefix, https_samesite="none",bare_attrs=_pkce_attrs(use_https=use_https, prefix=prefix))def _read_with_fallback(request: Request, bare_name: str) -> Optional[str]:- """Read a cookie trying every prefix variant (the reading request may not- have the same shape as the one that set it)."""- for variant in _NAME_VARIANTS:- value = request.cookies.get(f"{variant}{bare_name}")- if value is not None:- return value- return None+ """Try every prefix variant (the reading request may not match the setting request's shape)."""+ return next((v for v in (request.cookies.get(f"{p}{bare_name}") for p in _NAME_VARIANTS)+ if v is not None), None)def read_session_cookies(request: Request) -> Tuple[Optional[str], Optional[str]]:@@ -197,18 +169,12 @@ def read_pkce_cookie(request: Request) -> Optional[str]:def parse_pkce_payload(raw: str) -> dict[str, str]:- """Decode a PKCE cookie value into its segment dict (inverse of- :func:`encode_pkce_payload`). EVERY reader must go through this — reading the- raw wire value parses zero segments and silently disables the check it feeds- (provider dispatch, CSRF state, broker binding).-- Compatibility ladder for cookies minted by an older server mid-upgrade:- 1. base64url(JSON) — current.- 2. Flat form with raw ``;`` delimiters — split WITHOUT unquoting (the ``next``- segment carries its own URL-encoding; a ``%3B`` inside it is not a delimiter).- 3. URL-encoded flat form — unquote once, split.- A NEW cookie hitting an OLD server fails the state check; the user retries.- """+ """Inverse of :func:`encode_pkce_payload`. EVERY reader must go through this — reading the raw+ wire value parses zero segments and silently disables the check it feeds (provider dispatch,+ CSRF state, broker binding). Compatibility ladder for cookies minted by an older server+ mid-upgrade: 1. base64url(JSON); 2. flat form with raw ``;`` delimiters, split WITHOUT+ unquoting (the ``next`` segment carries its own URL-encoding); 3. URL-encoded flat form,+ unquote once then split. A NEW cookie hitting an OLD server fails the state check."""if _B64URL_RE.match(raw):try:padded = raw + "=" * (-len(raw) % 4)@@ -233,14 +199,12 @@ def read_sso_attempt_cookie(request: Request) -> Optional[str]:def clear_sso_attempt_cookie(response: Response, *, prefix: str = "") -> None:- """Delete the auto-SSO marker (every variant) so it never suppresses a- later silent attempt."""+ """Delete the auto-SSO marker (every variant) so it never suppresses a later silent attempt."""_clear_cookie_variants(response, SSO_ATTEMPT_COOKIE, prefix=prefix, https_samesite="lax",bare_attrs=_common_attrs(use_https=False, prefix=prefix))def detect_https(request: Request) -> bool:- """``Secure`` flag decision: ``request.url.scheme == "https"`` (honours- ``X-Forwarded-Proto`` under uvicorn ``proxy_headers=True``)."""+ """``Secure`` flag decision (honours ``X-Forwarded-Proto`` under uvicorn ``proxy_headers``)."""return request.url.scheme == "https"diff --git a/hermes_cli/dashboard_auth/native_flow.py b/hermes_cli/dashboard_auth/native_flow.pyindex 19b3ecdf696..d74909207fa 100644--- a/hermes_cli/dashboard_auth/native_flow.py+++ b/hermes_cli/dashboard_auth/native_flow.py@@ -25,14 +25,11 @@ from typing import Dict, Optionalfrom hermes_cli.dashboard_auth.base import Session-# Pending authorization: the whole interactive login (mirrors the PKCE cookie).-_PENDING_TTL_SECONDS = 600-# Minted code: only the loopback redirect + immediate token POST.-_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 and lock out logins.+_PENDING_TTL_SECONDS = 600 # whole interactive login (mirrors the PKCE cookie)+_CODE_TTL_SECONDS = 120 # loopback redirect + immediate token POST only+_MAX_ENTRIES = 256 # global cap so a misbehaving client cannot grow the store unbounded+# Per-IP cap on PENDING entries: /auth/native/authorize is a public pre-auth route, so one+# spammer must not fill the global store and lock out logins._MAX_PENDING_PER_IP = 8_lock = threading.Lock()@@ -41,7 +38,6 @@ _lock = threading.Lock()@dataclassclass _Pending:"""In-flight native authorization awaiting the upstream callback."""-code_challenge: str # the DESKTOP's S256 challenge (cc_d), base64url no-padredirect_uri: str # the desktop's loopback redirect (127.0.0.1:<port>/...)client_state: str # the desktop's own ``state`` (echoed back on redirect)@@ -52,7 +48,6 @@ class _Pending:@dataclassclass _IssuedCode:"""A minted one-time gateway authorization code bound to a Session."""-code_challenge: str # cc_d — verified against cv_d at redemptionsession: Sessionexpires_at: int@@ -95,12 +90,20 @@ def _now(now: Optional[int]) -> int:return int(time.time()) if now is None else now+def _pop_pending_locked(broker_state: str, *, consume: bool) -> _Pending:+ """Look up (optionally consuming) a pending entry; :class:`PendingNotFound` if unknown."""+ entry = (_pending.pop if consume else _pending.get)(broker_state, None)+ if entry is None:+ raise PendingNotFound("unknown or expired native authorization")+ return entry++def register_pending(*, 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``.- ``code_challenge`` is the DESKTOP's cc_d. Raises ``NativeFlowError`` (fail closed)- at store capacity or when ``client_ip`` holds ``_MAX_PENDING_PER_IP`` entries."""+ """Stash a pending native authorization; return an opaque ``broker_state``. ``code_challenge``+ is the DESKTOP's cc_d. Raises ``NativeFlowError`` (fail closed) at store capacity or when+ ``client_ip`` holds ``_MAX_PENDING_PER_IP`` entries."""now = _now(now)broker_state = secrets.token_urlsafe(32)with _lock:@@ -117,26 +120,19 @@ 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."""+ """Peek (without consuming) the pending authorization."""with _lock:_gc_locked(_now(now))- entry = _pending.get(broker_state)- if entry is None:- raise PendingNotFound("unknown or expired native authorization")- return entry+ return _pop_pending_locked(broker_state, consume=False)def complete_pending(broker_state: str, *, session: Session, now: Optional[int] = None) -> str:- """Consume a pending authorization (single use) and mint a one-time gateway code- bound to the desktop's challenge + ``session``; :class:`PendingNotFound` if- unknown/expired."""+ """Consume a pending authorization (single use) and mint a one-time gateway code bound to the+ desktop's challenge + ``session``."""now = _now(now)with _lock:_gc_locked(now)- pending = _pending.pop(broker_state, None)- if pending is None:- raise PendingNotFound("unknown or expired native authorization")+ pending = _pop_pending_locked(broker_state, consume=True)if not _capacity_ok_locked():raise NativeFlowError("native-flow code store at capacity")gw_code = secrets.token_urlsafe(32)@@ -147,9 +143,8 @@ def complete_pending(broker_state: str, *, session: Session, now: Optional[int]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 be retried- (no oracle, no replay). Raises :class:`CodeInvalid`."""+ """Verify PKCE + consume a gateway code; return the bound :class:`Session`. The entry is popped+ BEFORE the PKCE check so a wrong verifier cannot be retried (no oracle, no replay)."""now = _now(now)with _lock:_gc_locked(now)diff --git a/hermes_cli/dashboard_auth/prefix.py b/hermes_cli/dashboard_auth/prefix.pyindex 13e950ec013..1619de37eec 100644--- a/hermes_cli/dashboard_auth/prefix.py+++ b/hermes_cli/dashboard_auth/prefix.py@@ -16,57 +16,51 @@ from typing import Optional_log = logging.getLogger(__name__)-# Home Assistant ingress prefixes are already 63 chars before a deployment adds-# its own sub-path; keep a bounded header budget with room for real mounts.+# Home Assistant ingress prefixes are already 63 chars before a deployment adds its own+# sub-path; keep a bounded header budget with room for real mounts._MAX_PREFIX_LENGTH = 256--# Presence of any of these in a public_url / prefix means a typo or a-# header-injection attempt: reject the whole value, never sanitise.+# Any of these in a public_url / prefix means a typo or a header-injection attempt: reject the+# whole value, never sanitise._REJECT_CHARS = frozenset(('"', "'", "<", ">", " ", "\n", "\r", "\t"))--# ``resolve_public_url`` runs on every authenticated request, so warnings are-# de-duplicated per distinct (source, value) — a changed value warns afresh.+# ``resolve_public_url`` runs on every authenticated request, so warnings are de-duplicated per+# distinct (source, value) — a changed value warns afresh._warned_malformed_public_urls: set = set()_warned_malformed_prefixes: set = set()+def _warn_once(seen: set, key: tuple, cleaned: str, msg: str, *args) -> None:+ if not cleaned or key in seen:+ return+ seen.add(key)+ _log.warning(msg, *args)++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; silently falling back to header reconstruction can yield- the wrong scheme behind a proxy)."""+ """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 or (source, cleaned) in _warned_malformed_public_urls:- return- _warned_malformed_public_urls.add((source, cleaned))- _log.warning(+ _warn_once(+ _warned_malformed_public_urls, (source, cleaned), cleaned,"%s is set to %r but was ignored because it is not a valid ""absolute URL — it must include an http:// or https:// scheme ""(e.g. https://%s). Falling back to reconstructing the OAuth ""redirect URI from request headers, which may produce the wrong ""scheme behind a reverse proxy.",- source,- cleaned,- cleaned.split("://")[-1] or "hermes.example.com")+ source, cleaned, cleaned.split("://")[-1] or "hermes.example.com")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 or (cleaned, reason) in _warned_malformed_prefixes:- return- _warned_malformed_prefixes.add((cleaned, reason))- _log.warning(+ _warn_once(+ _warned_malformed_prefixes, (cleaned, reason), cleaned,"X-Forwarded-Prefix header %r was ignored because %s. "- "Dashboard URLs will be generated without a reverse-proxy path prefix.",- cleaned,- reason)+ "Dashboard URLs will be generated without a reverse-proxy path prefix.", cleaned, reason)def normalise_prefix(raw: Optional[str]) -> str:- """Normalise an X-Forwarded-Prefix header to ``"/hermes"`` form (no trailing- slash) or ``""`` when unset/malformed. ``..``, ``//`` and injection- characters are rejected so a hostile proxy cannot smuggle HTML or traversal.- """+ """``"/hermes"`` form (no trailing slash) or ``""`` when unset/malformed. ``..``, ``//`` and+ injection characters are rejected so a hostile proxy cannot smuggle HTML or traversal."""p = raw.strip() if raw else ""if not p:return ""@@ -89,11 +83,9 @@ def prefix_from_request(request) -> str:# --- HERMES_DASHBOARD_PUBLIC_URL / dashboard.public_url ---------------------def _normalise_public_url(raw: Optional[str]) -> str:"""Cleaned ``scheme://netloc[/path]`` (trailing slash stripped) or ``""`` when- empty/malformed/injection-suspect; ``""`` means "fall back to request- reconstruction" (an explicit empty value equals an unset env var)."""+ empty/malformed/injection-suspect (= fall back to request reconstruction)."""url = raw.strip() if raw else ""if not url or any(c in url for c in _REJECT_CHARS):return ""@@ -107,8 +99,7 @@ def _normalise_public_url(raw: Optional[str]) -> str:def _load_dashboard_section() -> dict:- """``dashboard`` block of config.yaml as a dict, or ``{}`` when the config- cannot be loaded or the block is absent/non-dict."""+ """``dashboard`` block of config.yaml as a dict, or ``{}`` when unloadable/absent/non-dict."""try:from hermes_cli.config import load_configexcept Exception:@@ -116,20 +107,17 @@ def _load_dashboard_section() -> dict:try:cfg = load_config()except Exception as exc: # noqa: BLE001 — broad catch is intentional- _log.debug(- "dashboard-auth.prefix: load_config() raised %s; "- "falling back to env-only configuration",- exc)+ _log.debug("dashboard-auth.prefix: load_config() raised %s; "+ "falling back to env-only configuration", exc)return {}section = cfg.get("dashboard") if isinstance(cfg, dict) else Nonereturn section if isinstance(section, dict) else {}def resolve_public_url() -> str:- """Operator-declared dashboard public URL, or ``""`` (reconstruct from request).- Precedence: ``HERMES_DASHBOARD_PUBLIC_URL`` env (blank counts as unset so a- provisioned-but-blank secret cannot shadow config.yaml), then- ``dashboard.public_url``; a malformed value warns and falls through."""+ """Operator-declared dashboard public URL, or ``""`` (reconstruct from request). Precedence:+ ``HERMES_DASHBOARD_PUBLIC_URL`` env (blank counts as unset so a provisioned-but-blank secret+ cannot shadow config.yaml), then ``dashboard.public_url``; malformed warns and falls through."""env_raw = os.environ.get("HERMES_DASHBOARD_PUBLIC_URL", "")env_clean = _normalise_public_url(env_raw)if env_clean:diff --git a/hermes_cli/dashboard_auth/public_paths.py b/hermes_cli/dashboard_auth/public_paths.pyindex 559ac426223..a4793ab7e81 100644--- a/hermes_cli/dashboard_auth/public_paths.py+++ b/hermes_cli/dashboard_auth/public_paths.py@@ -1,13 +1,9 @@-"""Shared allowlist of ``/api/*`` paths that bypass dashboard auth.--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.-"""+"""Shared allowlist of ``/api/*`` paths that bypass dashboard auth. Imported by BOTH gates —+``web_server.auth_middleware`` (loopback / ``--insecure``) and+``dashboard_auth.middleware.gated_auth_middleware`` (OAuth cookie) — so the lists cannot drift+again (a drift once 401'd ``/api/status`` 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({@@ -28,5 +24,4 @@ PUBLIC_API_PATHS: frozenset[str] = frozenset({# 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 — the JWT, not this allowlist, is the security boundary.- "/api/cron/fire",-})+ "/api/cron/fire"})diff --git a/hermes_cli/dashboard_auth/registry.py b/hermes_cli/dashboard_auth/registry.pyindex eeb98cbbce2..43bbcbc1ac5 100644--- a/hermes_cli/dashboard_auth/registry.py+++ b/hermes_cli/dashboard_auth/registry.py@@ -1,9 +1,6 @@-"""Module-level registry for DashboardAuthProvider instances.--Plugins call ``register_provider`` via the plugin context hook at startup.-The auth gate middleware iterates ``list_providers()`` and uses-``get_provider`` to dispatch on the session's ``provider`` field.-"""+"""Module-level registry for DashboardAuthProvider instances. Plugins call ``register_provider``+via the plugin context hook at startup; the auth gate iterates ``list_providers()`` and uses+``get_provider`` to dispatch on the session's ``provider`` field."""from __future__ import annotationsimport logging@@ -37,12 +34,7 @@ def _log_registered(kind: str, provider: DashboardAuthProvider) -> None:def register_provider(provider: DashboardAuthProvider, *, scope: Optional[str] = None) -> None:- """Register a provider.-- Raises:- TypeError: on protocol violation.- ValueError: if a provider with the same name is already registered.- """+ """Raises ``TypeError`` on protocol violation, ``ValueError`` on a duplicate name."""assert_protocol_compliance(type(provider))with _lock:target = _target(scope, create=True)@@ -89,31 +81,24 @@ def list_providers(*, scope: Optional[str] = None) -> List[DashboardAuthProviderdef list_token_providers() -> List[DashboardAuthProvider]:- """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.- """+ """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)."""return [p for p in list_providers() if getattr(p, "supports_token", False)]def list_session_providers() -> List[DashboardAuthProvider]:- """Providers with ``supports_session`` True (interactive cookie sessions);- the login page, /auth/login and the gate's verify/refresh loops use only these."""+ """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 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``.- """+ """Register a host-owned provider in the process-global slot (upsert). The registry is shared+ across every profile one dashboard process serves, so these 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@@ -121,8 +106,8 @@ def register_global_provider(provider: DashboardAuthProvider) -> None: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)."""+ """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 d70f0834bf9..fa161474668 100644--- a/hermes_cli/dashboard_auth/request_utils.py+++ b/hermes_cli/dashboard_auth/request_utils.py@@ -11,18 +11,15 @@ from fastapi.responses import JSONResponsefrom hermes_cli.dashboard_auth import list_session_providersfrom hermes_cli.dashboard_auth.base import DashboardAuthProvider, ProviderError-# Paths a post-login redirect must never land on: the auth flow itself (would-# loop) and any ``/api/*`` target (renders raw JSON in the address bar and is-# indistinguishable from an attacker weaponising the redirect).+# Paths a post-login redirect must never land on: the auth flow itself (would loop) and any+# ``/api/*`` target (raw JSON in the address bar, indistinguishable from a weaponised redirect)._NEXT_DENY_PREFIXES = ("/login", "/auth/", "/api/auth/")def client_ip(request: Request) -> str:"""First ``X-Forwarded-For`` hop, else the peer address."""fwd = request.headers.get("x-forwarded-for", "")- if fwd:- return fwd.split(",")[0].strip()- return request.client.host if request.client else ""+ return fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "")def extract_bearer(request: Request) -> str:@@ -34,11 +31,8 @@ def extract_bearer(request: Request) -> str:def is_safe_next_path(path: str) -> bool:- """True if ``path`` is a same-origin post-login target.-- Rejects non-relative and protocol-relative (``//evil``) values, the auth- routes themselves, and every ``/api`` path.- """+ """Same-origin post-login target: rejects non-relative and protocol-relative (``//evil``)+ values, the auth routes themselves, and every ``/api`` path."""if not path.startswith("/") or path.startswith("//"):return Falseif any(path == p or path.startswith(p) for p in _NEXT_DENY_PREFIXES):@@ -57,23 +51,17 @@ def unreachable_response(provider_name: str) -> JSONResponse:def scan_session_providers(- provider_hint: Optional[str],- call: Callable[[DashboardAuthProvider], object],- *,- phase: str,- log: logging.Logger,- swallow: tuple[type[BaseException], ...] = (),+ provider_hint: Optional[str], call: Callable[[DashboardAuthProvider], object], *, phase: str,+ log: logging.Logger, swallow: tuple[type[BaseException], ...] = (),on_swallow: Optional[Callable[[DashboardAuthProvider], None]] = None,on_unreachable: Optional[Callable[[DashboardAuthProvider], None]] = None):"""Run ``call`` across the session providers; first non-``None`` result or ``None``.- The hinted provider goes first (stable sort; a stale/unknown hint leaves- registration order intact). ``swallow`` exceptions reject that candidate- only. A ``ProviderError`` (IDP/JWKS unreachable) must NOT abort the chain —- the credential may belong to a different, reachable provider; it is logged- under ``phase`` and, if nothing else succeeds, re-raised as- ``ProviderError(name)`` so the caller answers 503 instead of forcing a- re-login through a possibly-unreachable path.+ The hinted provider goes first (stable sort; a stale/unknown hint leaves registration order+ intact). ``swallow`` exceptions reject that candidate only. A ``ProviderError`` (IDP/JWKS+ unreachable) must NOT abort the chain — the credential may belong to a different, reachable+ provider; it is logged under ``phase`` and, if nothing else succeeds, re-raised as+ ``ProviderError(name)`` so the caller answers 503 instead of forcing a re-login."""providers = list_session_providers()if provider_hint:diff --git a/hermes_cli/dashboard_auth/token_auth.py b/hermes_cli/dashboard_auth/token_auth.pyindex 7d70f40f0d2..649bfba113e 100644--- a/hermes_cli/dashboard_auth/token_auth.py+++ b/hermes_cli/dashboard_auth/token_auth.py@@ -1,16 +1,11 @@"""Route-agnostic non-interactive (bearer-token) auth seam for the dashboard.-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 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.+Any machine-credential provider plugs in here. 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) and+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 to /login);+otherwise 401, or 503 when a provider's backing store was unreachable. Fails closed."""from __future__ import annotations@@ -34,8 +29,7 @@ _lock = threading.Lock()def register_token_route(path: str) -> None:- """Mark ``path`` (exact match) as token-authable. Idempotent; does NOT make- the route public — it authenticates by token instead of by cookie."""+ """Mark ``path`` (exact match) as token-authable. Idempotent; does NOT make the route public."""with _lock:_token_routes.add(path)@@ -53,13 +47,9 @@ def clear_token_routes() -> None: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- no recogniser (401); ``(None, name)`` when no provider accepted it AND at- least one was unreachable (caller surfaces 503, not "bad credentials").- Never raises — a buggy provider must not 500 the gate.- """+ """Try every token provider against the request's bearer token. Returns ``(principal, None)``+ on success; ``(None, None)`` for no token or no recogniser (401); ``(None, name)`` when no+ provider accepted it AND at least one was unreachable (caller surfaces 503). Never raises."""token = extract_bearer_token(request)if not token:return None, None@@ -84,18 +74,16 @@ def authenticate_token(request: Request) -> Tuple[Optional[TokenPrincipal], Optiasync def token_auth_middleware(request: Request, call_next: Callable[[Request], Awaitable[Response]]) -> Response:- """Outermost auth seam: pass-through for unregistered paths; for a token- route, valid token -> attach principal + flag, unreachable -> 503, else 401."""+ """Pass-through for unregistered paths; for a token route, valid token -> attach principal ++ flag, unreachable -> 503, else 401."""path = request.url.pathif not is_token_route(path):return await call_next(request)-principal, unreachable = authenticate_token(request)if principal is not None:request.state.token_principal = principalrequest.state.token_authenticated = Truereturn await call_next(request)-if unreachable:audit_log(AuditEvent.TOKEN_AUTH_FAILURE, provider=unreachable, reason="provider_unreachable",diff --git a/hermes_cli/dashboard_auth/ws_tickets.py b/hermes_cli/dashboard_auth/ws_tickets.pyindex 74a683f1456..aef1456b84e 100644--- a/hermes_cli/dashboard_auth/ws_tickets.py+++ b/hermes_cli/dashboard_auth/ws_tickets.py@@ -1,23 +1,15 @@"""WS-upgrade auth credentials for gated mode.-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``) 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``.+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``) fetched via authenticated ``POST /api/auth/ws-ticket`` and+passed as ``?ticket=`` on the upgrade — 30 s TTL, a leak is uninteresting; (2) a process-lifetime+internal credential (``internal_ws_credential`` / ``consume_internal_credential``) for+*server-spawned* WS clients (the embedded-TUI PTY child on ``/api/ws`` + ``/api/pub``), which+reuse their attach URL on every reconnect, possibly >30 s after boot — minted once, never expires,+multi-use, never injected into any HTML/SPA (leaves the process only via the child's environment,+so browser XSS cannot read it; grants no more than a ticket). In-memory; ``time.time`` patchable."""-from __future__ import annotationsimport secrets@@ -25,18 +17,14 @@ import threadingimport timefrom typing import Any, Dict, Optional, Tuple-#: Ticket TTL: long enough for ``getWsTicket()`` -> open WS, short enough that-#: a leaked ticket is uninteresting.+#: 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)+_internal_credential: Optional[str] = None # lazily minted; guarded by ``_lock``-#: Process-lifetime internal credential, lazily minted; guarded by ``_lock``.-_internal_credential: Optional[str] = None--#: Identity recorded for internal-credential connections so audit logs-#: distinguish them from browser-initiated tickets.+#: Identity recorded for internal-credential connections (audit logs distinguish them from tickets).INTERNAL_USER_ID = "server-internal"INTERNAL_PROVIDER = "server-internal"@@ -46,8 +34,8 @@ class TicketInvalid(Exception):def mint_ticket(*, user_id: str, provider: str) -> str:- """Generate a one-shot base64url ticket (32 random bytes) bound to this- identity; ``consume_ticket`` hands the ``info`` dict back to the WS handler."""+ """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())}with _lock:@@ -57,8 +45,7 @@ def mint_ticket(*, user_id: str, provider: str) -> str:def consume_ticket(ticket: str) -> Dict[str, Any]:- """Validate and consume (single-use: a second call raises). Raises- :class:`TicketInvalid` on missing/expired/used."""+ """Validate and consume (single-use). Raises :class:`TicketInvalid` on missing/expired/used."""now = int(time.time())with _lock:entry = _tickets.pop(ticket, None)@@ -80,11 +67,8 @@ def _gc_expired_locked() -> None:def internal_ws_credential() -> str:- """Return the process-lifetime internal WS credential, minting it once.-- Stable, multi-use, never expires; never injected into the SPA or returned- over REST — only passed to a spawned child via its environment.- """+ """Process-lifetime internal WS credential, minted once. Never injected into the SPA or+ returned over REST — only passed to a spawned child via its environment."""global _internal_credentialwith _lock:if _internal_credential is None:@@ -93,12 +77,9 @@ def internal_ws_credential() -> str:def consume_internal_credential(value: str) -> Dict[str, Any]:- """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.- """+ """Validate an internal credential (NOT single-use); 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_credentialif not value or expected is None: