The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): OAuth clients a plugin declares, signed in and refreshed by Hermes
Ilya Balobanovb1b4effe513d
diff --git a/hermes_cli/auth_plugin_providers.py b/hermes_cli/auth_plugin_providers.pyindex ffff857bc30..09b775ed8b5 100644--- a/hermes_cli/auth_plugin_providers.py+++ b/hermes_cli/auth_plugin_providers.py@@ -182,7 +182,13 @@ def dispatch_plugin_auth(action: str, args: Any, provider: str) -> bool:True = the plugin owned the action (core prints nothing more). False = run the built-in path. Ahandler exception becomes a readable ``SystemExit`` naming provider and action.+ ``<plugin>:<id>`` names an OAuth client a plugin declares under ``oauth:`` (:mod:`hermes_cli.plugin_oauth`)."""+ from hermes_cli.plugin_oauth import handle_auth_action++ owned = handle_auth_action(action, args, provider)+ if owned is not None:+ return ownedhandler = plugin_auth_handler(provider)if handler is None:return Falsediff --git a/hermes_cli/plugin_oauth.py b/hermes_cli/plugin_oauth.pynew file mode 100644index 00000000000..a0d71888599--- /dev/null+++ b/hermes_cli/plugin_oauth.py@@ -0,0 +1,477 @@+"""OAuth clients a plugin declares in ``plugin.yaml``: Hermes signs in, stores and refreshes the grant.++A plugin that calls a third-party API with the user's own OAuth client (Google, Microsoft, Notion ...)+declares it under ``oauth:``. ``hermes auth add <plugin>:<id>`` runs the PKCE login of+:mod:`hermes_cli.auth_oauth_pkce_plugin` in a terminal, the grant lives in the active profile's+``auth.json`` (section ``plugin_oauth``) and Hermes refreshes it. The plugin calls+``credentialed_provider_request(<id>, ...)``: Hermes attaches the bearer for the declared hosts only, so+the plugin never holds a token (#139077; the same contract as the Codex lane, #136117).++Each grant remembers a fingerprint of the ``oauth:`` entry it was made for. A later version of the plugin+that changes the token URL, hosts, scopes or client variables gets ``ProviderNotSignedIn`` until the user+signs in again: the grant is used only for what the user consented to. Like capabilities, this is+consent and visibility, not a sandbox.+"""++from __future__ import annotations++import hashlib+import json+import re+import time+from dataclasses import asdict, dataclass+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Callable, Mapping, Optional+from urllib.parse import urlparse++_SECTION = "plugin_oauth"+_EXPIRY_MARGIN_MS = 120_000 # refresh this long before expiry, as the credential pool does+_TOKEN_TIMEOUT = 10.0 # below AUTH_LOCK_TIMEOUT_SECONDS: a peer waiting for the refresh lock outlives the POST+_CLIENT_ERROR_CODES = frozenset({"invalid_client", "unauthorized_client", "invalid_scope"})+_ID_RE = re.compile(r"^[a-z0-9][a-z0-9-]*$")+_ENV_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")+# Lowercase DNS name with at least one dot whose last label starts with a letter: no IP literal, port or scheme.+_HOST_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z](?:[a-z0-9-]*[a-z0-9])?$")+_LOOPBACK_LITERALS = frozenset({"127.0.0.1", "::1"})+++@dataclass(frozen=True)+class OAuthClient:+ """One ``oauth:`` entry of a plugin manifest. Holds variable names, never their values."""++ id: str+ authorize_url: str+ token_url: str+ scopes: tuple[str, ...]+ client_id_env: str+ hosts: tuple[str, ...]+ client_secret_env: str = ""+ authorize_params: tuple[tuple[str, str], ...] = ()++ @property+ def fingerprint(self) -> str:+ """Hash of every field: a grant is used only with the entry it was made for."""+ return hashlib.sha256(json.dumps(asdict(self), sort_keys=True).encode("utf-8")).hexdigest()+++# ── Manifest ───────────────────────────────────────────────────────────────────────────────────────++def _url_problems(where: str, url: Any) -> list[str]:+ parsed = urlparse(url) if isinstance(url, str) else None+ if parsed is None or not parsed.hostname or parsed.username is not None or parsed.password is not None:+ return [f"{where}: must be an absolute URL without user info"]+ if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in _LOOPBACK_LITERALS):+ return [f"{where}: must use https (plain http only for a loopback address)"]+ return []+++def _entry_problems(entry: dict, where: str) -> list[str]:+ problems = [] if _ID_RE.match(str(entry.get("id") or "")) else [+ f"{where}.id: {entry.get('id')!r} must be lowercase letters, digits and dashes"]+ for field in ("authorize_url", "token_url"):+ problems += _url_problems(f"{where}.{field}", entry.get(field))+ scopes = entry.get("scopes")+ if not (isinstance(scopes, list) and scopes and all(isinstance(s, str) and s.strip() for s in scopes)):+ problems.append(f"{where}.scopes: must be a non-empty list of scope strings")+ for field, required in (("client_id_env", True), ("client_secret_env", False)):+ name = entry.get(field)+ if (required or name) and not (isinstance(name, str) and _ENV_RE.match(name)):+ problems.append(f"{where}.{field}: {name!r} must be an UPPER_SNAKE environment variable name")+ hosts = entry.get("hosts")+ if not (isinstance(hosts, list) and hosts and all(isinstance(h, str) and _HOST_RE.match(h) for h in hosts)):+ problems.append(f"{where}.hosts: must list lowercase DNS host names (no scheme, port, path or IP address)")+ params = entry.get("authorize_params") or {}+ if not (isinstance(params, dict) and all(isinstance(k, str) and isinstance(v, str) for k, v in params.items())):+ problems.append(f"{where}.authorize_params: must map strings to strings")+ return problems+++def _client(entry: dict) -> OAuthClient:+ return OAuthClient(+ id=entry["id"], authorize_url=entry["authorize_url"], token_url=entry["token_url"],+ scopes=tuple(entry["scopes"]), client_id_env=entry["client_id_env"], hosts=tuple(entry["hosts"]),+ client_secret_env=entry.get("client_secret_env") or "",+ authorize_params=tuple(sorted((entry.get("authorize_params") or {}).items())))+++def parse_oauth_clients(manifest: Mapping[str, Any]) -> tuple[list[OAuthClient], list[str]]:+ """``oauth:`` from a manifest dict: the well-formed clients, and one problem string per defect."""+ raw = (manifest or {}).get("oauth")+ if raw in (None, [], {}):+ return [], []+ if not isinstance(raw, list):+ return [], ["oauth: must be a list of client entries"]+ clients: list[OAuthClient] = []+ problems: list[str] = []+ for index, entry in enumerate(raw):+ where = f"oauth[{index}]"+ entry_problems = _entry_problems(entry, where) if isinstance(entry, dict) else [f"{where}: must be a mapping"]+ if not entry_problems and any(c.id == entry["id"] for c in clients):+ entry_problems = [f"{where}.id: {entry['id']!r} is declared twice"]+ problems += entry_problems+ if not entry_problems:+ clients.append(_client(entry))+ return clients, problems+++def _declared_clients(plugin_dir: Path) -> list[OAuthClient]:+ """The plugin's own ``oauth:`` clients; a malformed block fails loud instead of reading as undeclared."""+ from pm.plugin_declarations import native_manifest_file, read_native_manifest++ manifest_file = native_manifest_file(plugin_dir)+ clients, problems = parse_oauth_clients(read_native_manifest(manifest_file) if manifest_file else {})+ if problems:+ raise ValueError(f"Plugin '{plugin_dir.name}' has an invalid oauth: block in plugin.yaml: " + "; ".join(problems))+ return clients+++def plugin_key(plugin_dir: Path) -> str:+ """The plugin's key under the plugins root it lives in (``voice``, ``web/exa``); grants are stored by it."""+ from hermes_cli.plugin_provider_requests import _plugin_roots++ for path in (plugin_dir.absolute(), plugin_dir.resolve()):+ for root in _plugin_roots():+ if path != root and path.is_relative_to(root):+ return path.relative_to(root).as_posix()+ return plugin_dir.name+++def oauth_notice(manifest: Mapping[str, Any]) -> str:+ """Install/show text for the declared clients; empty when the plugin declares none."""+ name = str((manifest or {}).get("name") or "<plugin>")+ return "; ".join(+ f"Signs in to {c.id} for {', '.join(c.hosts)} with `hermes auth add {name}:{c.id}` "+ "(Hermes stores and refreshes the token; the plugin never receives it)"+ for c in parse_oauth_clients(manifest)[0])+++def oauth_surface(manifest: Mapping[str, Any]) -> set[str]:+ """One line per client for the re-pin consent delta: a new entry, or a changed token host, hosts or scopes,+ shows up as added. Any other change only alters the fingerprint, so the user signs in again."""+ return {f"{c.id} ({urlparse(c.token_url).hostname} -> {', '.join(c.hosts)}; {' '.join(c.scopes)})"+ for c in parse_oauth_clients(manifest)[0]}+++def _declared_env_names(manifest: Mapping[str, Any]) -> set[str]:+ names: set[str] = set()+ for field in ("requires_env", "optional_env"):+ for entry in manifest.get(field) or []:+ names.add(str(entry.get("name") if isinstance(entry, dict) else entry))+ return names+++def oauth_admission_problems(manifest: Mapping[str, Any], plugin_dir: Path) -> list[str]:+ """Catalog admission on top of the shape: declared variables, no clash with core sign-ins or ``custom:``."""+ from hermes_cli.plugin_provider_requests import _PROVIDERS++ clients, problems = parse_oauth_clients(manifest)+ declared = _declared_env_names(manifest)+ for client in clients:+ if client.id in _PROVIDERS:+ problems.append(f"oauth id {client.id!r} is a Hermes sign-in provider; pick another id")+ for name in filter(None, (client.client_id_env, client.client_secret_env)):+ if name not in declared:+ problems.append(f"oauth {client.id!r}: {name} must be declared under requires_env or optional_env")+ if clients and plugin_dir.name == "custom":+ problems.append("a plugin named 'custom' cannot declare oauth: `hermes auth add custom:<name>` is a custom provider")+ return problems+++def token_url_mentions(manifest: Mapping[str, Any], plugin_dir: Path) -> list[str]:+ """Reviewer warnings for plugin code that names a declared token URL (Hermes refreshes the grant)."""+ urls = sorted({c.token_url for c in parse_oauth_clients(manifest)[0]})+ warnings: list[str] = []+ for path in sorted(plugin_dir.rglob("*.py")):+ try:+ text = path.read_text(encoding="utf-8", errors="replace")+ except OSError:+ continue+ warnings += [f"oauth: {path.relative_to(plugin_dir).as_posix()} names the token URL {url}; Hermes "+ "refreshes the grant, so the plugin should not call it" for url in urls if url in text]+ return warnings+++# ── Grant store: section ``plugin_oauth`` of the active profile's auth.json ────────────────────────++def _read_grant(key: str) -> Optional[dict]:+ from hermes_cli.auth import _load_auth_store++ section = _load_auth_store().get(_SECTION)+ row = section.get(key) if isinstance(section, dict) else None+ return dict(row) if isinstance(row, dict) else None+++def _write_grant(key: str, row: Optional[dict]) -> None:+ """Replace one grant (``None`` removes it) under the auth-store lock; other sections stay as they are."""+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _store_section++ with _auth_store_lock():+ store = _load_auth_store()+ section = _store_section(store, _SECTION)+ if row is None:+ section.pop(key, None)+ else:+ section[key] = row+ _save_auth_store(store)+++# ── Token endpoint ─────────────────────────────────────────────────────────────────────────────────++def _auth_error(key: str, message: str, code: str):+ from hermes_cli.auth_constants import AuthError++ return AuthError(f"{key}: {message}", provider=key, code=code)+++def _env(name: str, code: str, key: str) -> str:+ from agent.secret_scope import get_secret++ value = str(get_secret(name) or "").strip()+ if not value:+ raise _auth_error(key, f"{name} is not set. Add it to this profile's .env (the plugin declares it).", code)+ return value+++def _json_object(response: Any) -> dict:+ try:+ payload = response.json()+ except ValueError:+ return {}+ return payload if isinstance(payload, dict) else {}+++def _token_error(key: str, status: int, payload: Mapping[str, Any]):+ """Keep the OAuth ``error`` code a caller can act on; never echo the response body."""+ from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES++ error = str(payload.get("error") or "").strip()+ if error in _OAUTH_GRANT_DEAD_CODES or error in _CLIENT_ERROR_CODES:+ return _auth_error(key, f"the token endpoint refused the request (HTTP {status}, {error}).", error)+ return _auth_error(key, f"the token endpoint failed with HTTP {status}.", "oauth_refresh_failed")+++def _require_granted_scopes(client: OAuthClient, payload: Mapping[str, Any], key: str) -> None:+ granted = payload.get("scope")+ if not isinstance(granted, str) or not granted.strip():+ return # the IdP did not say which scopes it granted+ missing = [scope for scope in client.scopes if scope not in granted.split()]+ if missing:+ raise _auth_error(key, "not every permission was granted, so nothing was saved. Missing: "+ + ", ".join(missing), "oauth_scope_not_granted")+++def _token_request(client: OAuthClient, key: str) -> Callable[[dict[str, str]], Mapping[str, Any]]:+ """``OAuthPKCEConfig.token_request``: the client credentials are read right before each POST, so the+ secret never sits in the frozen config, whose repr would show it."""++ def post(fields: dict[str, str]) -> Mapping[str, Any]:+ from hermes_cli.auth import _default_verify+ from hermes_cli.auth_constants import httpx++ form = {**fields, "client_id": _env(client.client_id_env, "oauth_client_id_missing", key)}+ if client.client_secret_env:+ form["client_secret"] = _env(client.client_secret_env, "oauth_client_secret_missing", key)+ try:+ response = httpx.post(client.token_url, data=form, headers={"Accept": "application/json"},+ timeout=_TOKEN_TIMEOUT, verify=_default_verify(), follow_redirects=False)+ except httpx.HTTPError as exc:+ raise _auth_error(key, f"the token request failed ({type(exc).__name__}).", "oauth_refresh_failed") from None+ payload = _json_object(response)+ if response.status_code >= 400:+ raise _token_error(key, response.status_code, payload)+ if fields.get("grant_type") == "authorization_code":+ _require_granted_scopes(client, payload, key)+ return payload++ return post+++def _pkce_config(client: OAuthClient, key: str, *, timeout: Optional[float] = None):+ from hermes_cli.auth_oauth_pkce_plugin import OAuthPKCEConfig++ return OAuthPKCEConfig(+ client_id=_env(client.client_id_env, "oauth_client_id_missing", key), authorize_url=client.authorize_url,+ token_url=client.token_url, scopes=client.scopes, extra_authorize_params=dict(client.authorize_params),+ label=key, token_request=_token_request(client, key), timeout_seconds=timeout or 180.0)+++# ── Bearer for credentialed_provider_request ───────────────────────────────────────────────────────++def _not_signed_in(message: str):+ from hermes_cli.plugin_provider_requests import ProviderNotSignedIn++ return ProviderNotSignedIn(message)+++def _revoked(client: OAuthClient, key: str, code: str):+ return _not_signed_in(f"The {client.id} sign-in for plugin '{key.rsplit(':', 1)[0]}' was revoked ({code}). "+ f"Run `hermes auth add {key}` to sign in again.")+++def _usable_grant(row: Optional[dict], client: OAuthClient, key: str) -> dict:+ plugin = key.rsplit(":", 1)[0]+ if row is None:+ raise _not_signed_in(f"Not signed in to {client.id} for plugin '{plugin}' in this Hermes profile. "+ f"Run `hermes auth add {key}`.")+ if row.get("dead"):+ raise _revoked(client, key, str(row["dead"]))+ if row.get("fingerprint") != client.fingerprint:+ raise _not_signed_in(f"Plugin '{plugin}' changed its oauth entry '{client.id}' since you signed in. "+ f"Run `hermes auth add {key}` to sign in again.")+ return row+++def _live_token(row: Mapping[str, Any]) -> str:+ token = str(row.get("access_token") or "")+ expires = row.get("expires_at_ms")+ live = expires is None or int(expires) > int(time.time() * 1000) + _EXPIRY_MARGIN_MS+ return token if token and live else ""+++def _refresh(client: OAuthClient, key: str, row: dict) -> str:+ """Rotate the grant; the caller holds the auth-store lock, so a peer process waits instead of spending+ the same refresh token, and a logout cannot be undone by a refresh in flight."""+ from hermes_cli.auth import _OAUTH_GRANT_DEAD_CODES+ from hermes_cli.auth_constants import AuthError+ from hermes_cli.auth_oauth_pkce_plugin import _post_token++ refresh_token = str(row.get("refresh_token") or "")+ if not refresh_token:+ raise _revoked(client, key, "no_refresh_token")+ try:+ fields = _post_token(key, _pkce_config(client, key),+ {"grant_type": "refresh_token", "refresh_token": refresh_token}, code="oauth_refresh_failed")+ except AuthError as exc:+ if exc.code in _OAUTH_GRANT_DEAD_CODES:+ _write_grant(key, {**row, "dead": exc.code})+ raise _revoked(client, key, str(exc.code)) from None+ raise+ _write_grant(key, {**row, **fields})+ return str(fields["access_token"])+++def _bearer(plugin_dir: Path, client: OAuthClient) -> str:+ """A live access token for the plugin's grant. Reading takes no lock (writes are atomic); a refresh+ re-reads under the lock, because a peer may have rotated the grant meanwhile."""+ from hermes_cli.auth import _auth_store_lock++ key = f"{plugin_key(plugin_dir)}:{client.id}"+ token = _live_token(_usable_grant(_read_grant(key), client, key))+ if token:+ return token+ with _auth_store_lock():+ row = _usable_grant(_read_grant(key), client, key)+ return _live_token(row) or _refresh(client, key, row)+++def plugin_oauth_spec(plugin_dir: Path, provider: str):+ """``(origins, resolver)`` for *provider* when the calling plugin declares it under ``oauth:``, else None."""+ client = next((c for c in _declared_clients(plugin_dir) if c.id == provider), None)+ if client is None:+ return None++ def resolve(url: str) -> tuple[dict[str, str], str]:+ parsed = urlparse(url)+ if parsed.username is not None or parsed.password is not None:+ raise PermissionError(f"Refusing to send the {client.id} sign-in to a URL with user info")+ # The grant is valid for every declared host, so the request URL (origin already checked) is its base.+ return {"Authorization": f"Bearer {_bearer(plugin_dir, client)}"}, url++ return _origins(client), resolve+++def _origins(client: OAuthClient) -> frozenset:+ """Origins the bearer may go to: each declared host, HTTPS on the default port."""+ return frozenset(("https", host, 443) for host in client.hosts)+++# ── hermes auth add|status|refresh|logout <plugin>:<id> ────────────────────────────────────────────++def _installed_client(plugin: str, oauth_id: str) -> Optional[tuple[Path, OAuthClient]]:+ """Resolve *plugin* the way ``hermes plugins show`` does, then its ``oauth:`` entry *oauth_id*."""+ from hermes_cli.plugins_cmd import _find_plugin_entry++ entry = _find_plugin_entry(plugin)+ if entry is None or not entry[4]:+ return None+ plugin_dir = Path(str(entry[4]))+ client = next((c for c in _declared_clients(plugin_dir) if c.id == oauth_id), None)+ return (plugin_dir, client) if client is not None else None+++def _cli_add(args: Any, client: OAuthClient, key: str) -> bool:+ from hermes_cli.auth_constants import AuthError+ from hermes_cli.auth_oauth_pkce_plugin import login++ try:+ fields = login(key, _pkce_config(client, key, timeout=getattr(args, "timeout", None)),+ open_browser=not getattr(args, "no_browser", False))+ except AuthError as exc:+ raise SystemExit(f"Login failed: {exc}") from None+ _write_grant(key, {**fields, "fingerprint": client.fingerprint})+ print(f"Signed in to {client.id} for plugin '{key.rsplit(':', 1)[0]}'; the grant is stored in this Hermes profile.")+ return True+++def _cli_status(args: Any, client: OAuthClient, key: str) -> bool:+ from hermes_cli.plugin_provider_requests import ProviderNotSignedIn++ row = _read_grant(key)+ try:+ _usable_grant(row, client, key)+ except ProviderNotSignedIn as exc:+ state = "logged out" if row is None else "revoked" if row.get("dead") else "sign-in needed"+ print(f"{key}: {state}\n {exc}")+ return True+ expires = row.get("expires_at_ms") if row else None+ print(f"{key}: logged in\n hosts: {', '.join(client.hosts)}" + (+ f"\n access token valid until {datetime.fromtimestamp(int(expires) / 1000, UTC).isoformat(timespec='seconds')}"+ if expires else ""))+ return True+++def _cli_refresh(args: Any, client: OAuthClient, key: str) -> bool:+ from hermes_cli.auth import _auth_store_lock+ from hermes_cli.auth_constants import AuthError+ from hermes_cli.plugin_provider_requests import ProviderNotSignedIn++ try:+ with _auth_store_lock():+ _refresh(client, key, _usable_grant(_read_grant(key), client, key))+ except (AuthError, ProviderNotSignedIn) as exc:+ raise SystemExit(f"Refresh failed: {exc}") from None+ print(f"{key}: refreshed")+ return True+++def _cli_logout(args: Any, client: OAuthClient, key: str) -> bool:+ _write_grant(key, None)+ print(f"Signed out of {client.id} for plugin '{key.rsplit(':', 1)[0]}'; the grant was removed from this profile.")+ return True+++_CLI_ACTIONS = {"add": _cli_add, "status": _cli_status, "refresh": _cli_refresh, "logout": _cli_logout}+++def handle_auth_action(action: str, args: Any, provider: str) -> Optional[bool]:+ """``hermes auth add|status|refresh|logout <plugin>:<id>``; None when *provider* is not a plugin's+ ``oauth:`` entry (``custom:<name>`` stays the custom-provider pool)."""+ plugin, sep, oauth_id = str(provider or "").partition(":")+ handler = _CLI_ACTIONS.get(action)+ if handler is None or not (sep and plugin and oauth_id) or plugin == "custom":+ return None+ try:+ found = _installed_client(plugin, oauth_id)+ except ValueError as exc:+ raise SystemExit(str(exc)) from None+ if found is None:+ return None+ plugin_dir, client = found+ return handler(args, client, f"{plugin_key(plugin_dir)}:{client.id}")+++__all__ = [+ "OAuthClient", "handle_auth_action", "oauth_admission_problems", "oauth_notice", "oauth_surface",+ "parse_oauth_clients", "plugin_key", "plugin_oauth_spec", "token_url_mentions",+]diff --git a/hermes_cli/plugin_provider_requests.py b/hermes_cli/plugin_provider_requests.pyindex 62614f0bf24..89ac04fd7de 100644--- a/hermes_cli/plugin_provider_requests.py+++ b/hermes_cli/plugin_provider_requests.py@@ -72,14 +72,19 @@ _PROVIDERS: dict[str, tuple[frozenset, Callable[[str], tuple[dict[str, str], str}-def _calling_plugin_dir() -> Optional[Path]:- """Directory of the plugin whose code is nearest on the calling stack, or None."""+def _plugin_roots() -> set[Path]:+ """Every plugins directory an installed plugin can live under, as given and resolved."""from hermes_cli.plugins import get_bundled_plugins_dirfrom hermes_constants import get_default_hermes_root, get_hermes_home, get_process_hermes_homebases = (get_hermes_home() / "plugins", get_process_hermes_home() / "plugins",get_default_hermes_root() / "plugins", get_bundled_plugins_dir())- roots = {r for base in bases for r in (base.absolute(), base.resolve())}+ return {r for base in bases for r in (base.absolute(), base.resolve())}+++def _calling_plugin_dir() -> Optional[Path]:+ """Directory of the plugin whose code is nearest on the calling stack, or None."""+ roots = _plugin_roots()frame = sys._getframe(2)while frame is not None:raw = Path(frame.f_code.co_filename)@@ -105,9 +110,12 @@ def declared_auth_providers(manifest: Mapping[str, Any]) -> list[str]:def requires_auth_notice(manifest: Mapping[str, Any]) -> str:"""One line for install/show surfaces; empty when the plugin declares no sign-in use."""+ from hermes_cli.plugin_oauth import oauth_notice+providers = declared_auth_providers(manifest)- return (f"Uses your sign-in for: {', '.join(providers)} (Hermes sends the requests; "- "the plugin never receives the token)") if providers else ""+ sign_in = (f"Uses your sign-in for: {', '.join(providers)} (Hermes sends the requests; "+ "the plugin never receives the token)") if providers else ""+ return "; ".join(part for part in (sign_in, oauth_notice(manifest)) if part)def _declared_providers(plugin_dir: Path) -> list[str]:@@ -123,21 +131,29 @@ def credentialed_provider_request() -> ProviderResponse:"""Send ``method url`` with the user's *provider* sign-in attached by Hermes.+ *provider* is a Hermes sign-in (listed under ``requires_auth``) or an ``id`` the calling plugin+ declares under ``oauth:`` (:mod:`hermes_cli.plugin_oauth`); the plugin's own entry wins.Refuses (``PermissionError``) a caller outside an installed plugin, a plugin whose ``plugin.yaml``does not list *provider* under ``requires_auth``, and any origin outside the provider'sallowlist; raises :class:`ProviderNotSignedIn` when this profile has no sign-in. Redirects arereturned as-is, never followed. The result carries no credential."""- spec = _PROVIDERS.get(provider)- if spec is None:- raise ValueError(f"No signed-in requests for provider {provider!r} (supported: {', '.join(_PROVIDERS)})")- origins, resolve = spec+ from hermes_cli.plugin_oauth import plugin_oauth_spec+plugin_dir = _calling_plugin_dir()if plugin_dir is None:raise PermissionError("credentialed_provider_request must be called from an installed plugin's code")- if provider not in _declared_providers(plugin_dir):- raise PermissionError(- f"Plugin '{plugin_dir.name}' must declare `requires_auth: [{provider}]` in plugin.yaml")+ # The plugin's own oauth: entry first, so a core provider added later under the same id cannot take it over.+ spec = plugin_oauth_spec(plugin_dir, provider)+ if spec is None:+ spec = _PROVIDERS.get(provider)+ if spec is None:+ raise ValueError(f"No signed-in requests for provider {provider!r} (supported: {', '.join(_PROVIDERS)}, "+ "or an id the plugin declares under oauth: in plugin.yaml)")+ if provider not in _declared_providers(plugin_dir):+ raise PermissionError(+ f"Plugin '{plugin_dir.name}' must declare `requires_auth: [{provider}]` in plugin.yaml")+ origins, resolve = specif url_origin(url) not in origins:raise PermissionError(f"Refusing to send the {provider} sign-in to {url_origin(url)[1] or url!r}")auth_headers, credential_base = resolve(url)diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.pyindex a7c689c97ce..a6c8d33f289 100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@ -185,6 +185,20 @@ def _check_requires_env(report: ValidationReport, manifest: dict) -> None:report.add("requires_env", True, "all entries UPPER_SNAKE")+def _check_oauth(report: ValidationReport, manifest: dict, plugin_dir: Path) -> None:+ """``oauth:`` clients (hermes_cli.plugin_oauth): shape and declared variables fail admission; plugin+ code that names a token URL is a reviewer warning, since Hermes refreshes the grant itself."""+ from hermes_cli.plugin_oauth import oauth_admission_problems, token_url_mentions++ if not manifest.get("oauth"):+ report.add("oauth", True, "not declared")+ return+ problems = oauth_admission_problems(manifest, plugin_dir)+ report.add("oauth", not problems, "; ".join(problems) or "clients valid")+ for warning in token_url_mentions(manifest, plugin_dir):+ report.warn(warning)++# ─── Capability probe (subprocess-isolated) ──────────────────────────────────# Self-contained harness run in a scratch child process. Imports the plugin@@ -529,6 +543,7 @@ def validate_plugin_dir(_check_requires_hermes(report, manifest)_check_config_spec(report, manifest)_check_requires_env(report, manifest)+ _check_oauth(report, manifest, plugin_dir)_check_loadable(report, plugin_dir, manifest)_check_python_dependencies(report, plugin_dir)recorded = _check_capabilities(report, manifest, plugin_dir, probe)diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.pyindex 702e42982bd..eecd7ae59db 100644--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@ -497,11 +497,12 @@ class RepinResult(NamedTuple):# new manifest adds (``desktop`` = a Desktop half appeared). Compared as sets — removals are not consent events._SURFACE_LABELS = {"capabilities": "host capabilities", "tools": "tools", "hooks": "hooks","python_dependencies": "Python dependencies", "desktop": "Desktop UI half",- "requires_auth": "your sign-in for"}+ "requires_auth": "your sign-in for", "oauth": "your OAuth sign-in for"}def plugin_surface(manifest: dict, tree: Path) -> dict[str, set]:"""What an installed tree exposes: declared host capabilities, tools, hooks, Python deps, Desktop half."""+ from hermes_cli.plugin_oauth import oauth_surfacefrom hermes_cli.plugins_cmd import _declared_capabilities_from_manifestmanifest = manifest or {}@@ -516,6 +517,7 @@ def plugin_surface(manifest: dict, tree: Path) -> dict[str, set]:"capabilities": set(_declared_capabilities_from_manifest(manifest, str(manifest.get("name") or "?"))),"tools": _list("provides_tools"), "hooks": _list("provides_hooks", "hooks"),"python_dependencies": _list("python_dependencies"), "requires_auth": _list("requires_auth"),+ "oauth": oauth_surface(manifest),"desktop": {"desktop/plugin.js"} if (tree / "desktop" / "plugin.js").is_file() else set(),}diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex 576ba20e545..3b643fbdce3 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -35,7 +35,7 @@ _KNOWN_MANIFEST_FIELDS: set[str] = {"pip_dependencies", "provides_browser_providers", "provides_web_providers","manifest_version", "api_version", "requires_plugins", "python_dependencies", "config_schema","license", "homepage", "tags", "capabilities", "emits", "listens", "hermes", "depends",- "requires_hermes", "python_runtime", "provides_locales", "requires_auth",+ "requires_hermes", "python_runtime", "provides_locales", "requires_auth", "oauth",}# Highest manifest schema version this Hermes understands.diff --git a/plugin-catalog/README.md b/plugin-catalog/README.mdindex 28345b04a86..4f6acefac8a 100644--- a/plugin-catalog/README.md+++ b/plugin-catalog/README.md@@ -87,8 +87,11 @@ meaningful:which honours the active profile (a bare `os.environ` read can pick up anotherprofile's key under multiplexing). A subscription sign-in (Codex / ChatGPTtoday) is used only through `credentialed_provider_request` with- `requires_auth`, so Hermes attaches the token and the plugin never holds it. A- plugin never reads `.env` files, Hermes's `auth.json`, another tool's login (a+ `requires_auth`, so Hermes attaches the token and the plugin never holds it. An+ OAuth client for a third-party API (the user's own Google, Microsoft or Notion+ app) is declared under `oauth:` in `plugin.yaml`, signed in with+ `hermes auth add <plugin>:<id>` and used through the same helper; Hermes+ stores and refreshes that token too. A plugin never reads `.env` files, Hermes's `auth.json`, another tool's login (avendor CLI's token file, a browser profile, a keychain) or any othercredential store directly, and never refreshes, rotates or writes OAuth tokensor presents itself as another vendor's client. If Hermes has no route for adiff --git a/tests/hermes_cli/test_plugin_oauth.py b/tests/hermes_cli/test_plugin_oauth.pynew file mode 100644index 00000000000..828a98d5fe6--- /dev/null+++ b/tests/hermes_cli/test_plugin_oauth.py@@ -0,0 +1,423 @@+"""Plugin-declared OAuth clients: Hermes signs in, stores and refreshes the grant; plugin code never holds a token.++A real plugin directory under the test HERMES_HOME declares ``oauth:``. ``FakeIdP`` plays the authorization+server (PKCE, rotating refresh tokens) and a loopback stub plays the API the bearer is meant for.+"""++from __future__ import annotations++import importlib.util+import json+import os+import threading+import time+from concurrent.futures import ThreadPoolExecutor+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from types import SimpleNamespace+from urllib.request import urlopen++import pytest++from hermes_cli import auth_oauth_pkce_plugin as pkce+from hermes_cli import plugin_oauth+from hermes_cli import plugin_provider_requests as ppr+from hermes_cli.auth_constants import AuthError+from tests.providers.fake_pkce_idp import FakeIdP++CLIENT_ID = "voice-client.apps.example"+SECRET = "canary-client-secret-7f3a91"+SCOPES = ["https://api.example.com/auth/calendar", "https://api.example.com/auth/docs"]+KEY = "voice:google"+++class _Api:+ """Loopback stand-in for the third-party API; records every request it receives."""++ def __init__(self, status=200, location=""):+ self.seen: list[dict] = []+ api = self++ class Handler(BaseHTTPRequestHandler):+ def _answer(self):+ length = int(self.headers.get("Content-Length") or 0)+ api.seen.append({"path": self.path, "headers": dict(self.headers), "body": self.rfile.read(length)})+ self.send_response(status)+ if location:+ self.send_header("Location", location)+ self.send_header("Content-Type", "application/json")+ self.end_headers()+ self.wfile.write(b'{"ok": true}')++ do_GET = do_POST = do_PATCH = _answer++ def log_message(self, *_):+ pass++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ self.origin = ("http", "127.0.0.1", self.server.server_address[1])+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}"+ threading.Thread(target=self.server.serve_forever, daemon=True).start()++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++def _home() -> Path:+ return Path(os.environ["HERMES_HOME"])+++def _entry(idp: FakeIdP, **overrides) -> dict:+ entry = {"id": "google", "authorize_url": f"{idp.base}/authorize", "token_url": f"{idp.base}/token",+ "scopes": SCOPES, "client_id_env": "VOICE_CLIENT_ID", "client_secret_env": "VOICE_CLIENT_SECRET",+ "hosts": ["api.example.com"], "authorize_params": {"access_type": "offline", "prompt": "consent"}}+ return {**entry, **overrides}+++def _plugin(name: str = "voice", oauth: list | None = None):+ """Write ``plugins/<name>`` (manifest plus a module that calls the helper) and import it like a plugin."""+ root = _home() / "plugins" / name+ root.mkdir(parents=True, exist_ok=True)+ manifest = {"name": name, "version": "1.0.0", "description": "test plugin",+ "requires_env": [{"name": "VOICE_CLIENT_ID"}, {"name": "VOICE_CLIENT_SECRET"}]}+ if oauth is not None:+ manifest["oauth"] = oauth+ (root / "plugin.yaml").write_text(json.dumps(manifest), encoding="utf-8") # JSON is valid YAML+ (root / "api.py").write_text(+ "from hermes_cli.plugin_provider_requests import credentialed_provider_request\n"+ "def call(provider, url, method='POST', **kwargs):\n"+ " return credentialed_provider_request(provider, method, url, **kwargs)\n", encoding="utf-8")+ spec = importlib.util.spec_from_file_location(f"hermes_plugins_{name}_api", root / "api.py")+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _auth(action: str, provider: str = KEY):+ args = SimpleNamespace(provider=provider, no_browser=False, timeout=None)+ return plugin_oauth.handle_auth_action(action, args, provider)+++def _grant(key: str = KEY) -> dict | None:+ store = json.loads((_home() / "auth.json").read_text(encoding="utf-8"))+ return (store.get("plugin_oauth") or {}).get(key)+++def _set_grant(key: str = KEY, **fields) -> None:+ path = _home() / "auth.json"+ store = json.loads(path.read_text(encoding="utf-8"))+ store["plugin_oauth"][key].update(fields)+ path.write_text(json.dumps(store), encoding="utf-8")+++def _refreshes(idp: FakeIdP) -> int:+ return sum(r["grant_type"] == "refresh_token" for r in idp.token_requests)+++def idp(monkeypatch):+ monkeypatch.setenv("VOICE_CLIENT_ID", CLIENT_ID)+ monkeypatch.setenv("VOICE_CLIENT_SECRET", SECRET)+ server = FakeIdP().start()+ server.opened = []++ def browser(url: str) -> bool:+ server.opened.append(url)+ with urlopen(url, timeout=5) as response: # the fake IdP 302s straight to the loopback callback+ return response.status == 200++ monkeypatch.setattr(pkce.webbrowser, "open", browser)+ monkeypatch.setattr("hermes_cli.auth_device_flow._can_open_graphical_browser", lambda: True)+ yield server+ server.stop()+++def api(monkeypatch):+ """Test-only: the stub joins the declared hosts' origins; a second stub stays outside them."""+ allowed, other = _Api(), _Api()+ declared = plugin_oauth._origins+ monkeypatch.setattr(plugin_oauth, "_origins", lambda client: declared(client) | {allowed.origin})+ yield allowed, other+ allowed.close()+ other.close()+++def _signed_in(idp: FakeIdP, **entry_overrides):+ plugin = _plugin(oauth=[_entry(idp, **entry_overrides)])+ assert _auth("add") is True+ return plugin+++def test_sign_in_stores_the_grant_then_status_refresh_and_logout(idp, capsys):+ _plugin(oauth=[_entry(idp)])+ assert _auth("add") is True++ assert "access_type=offline" in idp.opened[-1] and "prompt=consent" in idp.opened[-1]+ exchange = idp.token_requests[-1]+ assert exchange["grant_type"] == "authorization_code" and exchange["code_verifier"]+ assert (exchange["client_id"], exchange["client_secret"]) == (CLIENT_ID, SECRET)+ grant = _grant()+ assert grant["refresh_token"] in idp.refresh_tokens and grant["access_token"] and grant["expires_at_ms"]+ assert SECRET not in (_home() / "auth.json").read_text(encoding="utf-8")++ assert _auth("status") is True+ assert _auth("refresh") is True and _refreshes(idp) == 1+ assert _auth("logout") is True and _grant() is None+ out = capsys.readouterr()+ assert "logged in" in out.out and SECRET not in out.out + out.err+++def test_bearer_reaches_the_declared_host_and_never_the_plugin(idp, api):+ allowed, _ = api+ plugin = _signed_in(idp)+ token = _grant()["access_token"]++ result = plugin.call("google", allowed.url + "/v1/items?x=1", json={"title": "t"},+ headers={"X-Plugin": "1", "authorization": "Bearer plugin-made"})++ assert result.status == 200 and result.json() == {"ok": True}+ seen = allowed.seen[0]+ assert seen["path"] == "/v1/items?x=1" and json.loads(seen["body"]) == {"title": "t"}+ assert seen["headers"]["Authorization"] == f"Bearer {token}" and seen["headers"]["X-Plugin"] == "1"+ assert token not in repr(result) and token not in json.dumps(result.headers)+++def test_foreign_origin_userinfo_and_redirect_never_carry_the_token(idp, api, monkeypatch):+ allowed, other = api+ plugin = _signed_in(idp)+ with pytest.raises(PermissionError, match="Refusing"):+ plugin.call("google", other.url + "/steal")+ host = allowed.url.split("//", 1)[1]+ for url in (f"http://user@{host}/x", f"http://{host}@127.0.0.1:{other.origin[2]}/x"):+ with pytest.raises(PermissionError):+ plugin.call("google", url)++ redirecting = _Api(status=302, location=other.url + "/steal")+ declared = plugin_oauth._origins+ monkeypatch.setattr(plugin_oauth, "_origins", lambda client: declared(client) | {redirecting.origin})+ try:+ assert plugin.call("google", redirecting.url + "/v1").status == 302+ finally:+ redirecting.close()+ assert other.seen == [] and allowed.seen == []+++def test_undeclared_id_another_plugins_grant_and_non_plugin_callers_are_refused(idp, api):+ allowed, _ = api+ _signed_in(idp)+ with pytest.raises(ValueError, match="google"):+ _plugin("bare").call("google", allowed.url)+ twin = _plugin("twin", oauth=[_entry(idp)]) # the same declaration, but no grant of its own+ with pytest.raises(ppr.ProviderNotSignedIn, match="hermes auth add twin:google"):+ twin.call("google", allowed.url)+ with pytest.raises(PermissionError, match="installed plugin"):+ ppr.credentialed_provider_request("google", "GET", allowed.url)+ assert allowed.seen == []+++def test_own_oauth_id_wins_over_a_core_provider_of_the_same_name(idp, api, monkeypatch):+ allowed, _ = api+ plugin = _signed_in(idp)++ def core_resolver(url):+ raise AssertionError("a core provider's credential must not answer the plugin's own oauth id")++ monkeypatch.setitem(ppr._PROVIDERS, "google", (frozenset({allowed.origin}), core_resolver))+ assert plugin.call("google", allowed.url).status == 200+ assert allowed.seen[0]["headers"]["Authorization"] == f"Bearer {_grant()['access_token']}"+++def test_not_signed_in_names_the_command_and_sends_nothing(idp, api):+ allowed, _ = api+ plugin = _plugin(oauth=[_entry(idp)])+ with pytest.raises(ppr.ProviderNotSignedIn, match="hermes auth add voice:google"):+ plugin.call("google", allowed.url)+ assert allowed.seen == [] and idp.token_requests == []+++def test_expiring_token_is_refreshed_once_and_the_rotation_kept(idp, api):+ allowed, _ = api+ plugin = _signed_in(idp)+ old_refresh = _grant()["refresh_token"]+ _set_grant(expires_at_ms=int(time.time() * 1000) + 60_000) # inside the 120 s margin++ plugin.call("google", allowed.url)+ plugin.call("google", allowed.url)++ assert [r for r in idp.token_requests if r["grant_type"] == "refresh_token"] == [{+ "grant_type": "refresh_token", "refresh_token": old_refresh, "client_id": CLIENT_ID, "client_secret": SECRET}]+ grant = _grant()+ assert grant["refresh_token"] != old_refresh and grant["refresh_token"] in idp.refresh_tokens+ assert [s["headers"]["Authorization"] for s in allowed.seen] == [f"Bearer {grant['access_token']}"] * 2+++def test_two_threads_with_an_expiring_token_refresh_once(idp, api):+ allowed, _ = api+ plugin = _signed_in(idp)+ _set_grant(expires_at_ms=0)++ with ThreadPoolExecutor(max_workers=2) as pool:+ statuses = list(pool.map(lambda _: plugin.call("google", allowed.url).status, range(2)))++ assert statuses == [200, 200] and _refreshes(idp) == 1 and "dead" not in _grant()+++def test_live_token_is_sent_while_another_thread_holds_the_auth_lock(idp, api):+ from hermes_cli.auth import _auth_store_lock++ allowed, _ = api+ plugin = _signed_in(idp)+ held, release = threading.Event(), threading.Event()++ def holder():+ with _auth_store_lock():+ held.set()+ release.wait(10)++ thread = threading.Thread(target=holder)+ thread.start()+ try:+ assert held.wait(5)+ started = time.monotonic()+ assert plugin.call("google", allowed.url).status == 200+ assert time.monotonic() - started < 5+ finally:+ release.set()+ thread.join(10)+++def test_revoked_grant_is_marked_dead_and_stops_touching_the_network(idp, api, capsys):+ allowed, _ = api+ plugin = _signed_in(idp)+ idp.refresh_tokens.clear() # the user removed the app at the IdP+ _set_grant(expires_at_ms=0)+ with pytest.raises(ppr.ProviderNotSignedIn, match="revoked"):+ plugin.call("google", allowed.url)+ posts = len(idp.token_requests)+ with pytest.raises(ppr.ProviderNotSignedIn, match="revoked"):+ plugin.call("google", allowed.url)++ assert len(idp.token_requests) == posts and allowed.seen == [] and _grant()["dead"] == "invalid_grant"+ capsys.readouterr()+ assert _auth("status") is True and "revoked" in capsys.readouterr().out+++def test_rejected_client_is_an_auth_error_that_leaves_the_grant(idp, api):+ allowed, _ = api+ plugin = _signed_in(idp)+ _set_grant(expires_at_ms=0)+ idp.token_error = (401, {"error": "invalid_client", "error_description": "The OAuth client was not found."})+ for _ in range(2):+ with pytest.raises(AuthError) as excinfo:+ plugin.call("google", allowed.url)+ assert excinfo.value.code == "invalid_client"+ assert "dead" not in _grant() and _refreshes(idp) == 2 and allowed.seen == []+++def test_missing_client_env_fails_before_any_request(idp, api, monkeypatch):+ allowed, _ = api+ plugin = _signed_in(idp)+ _set_grant(expires_at_ms=0)+ monkeypatch.delenv("VOICE_CLIENT_SECRET")+ posts = len(idp.token_requests)+ with pytest.raises(AuthError) as excinfo:+ plugin.call("google", allowed.url)+ assert excinfo.value.code == "oauth_client_secret_missing" and "VOICE_CLIENT_SECRET" in str(excinfo.value)+ assert len(idp.token_requests) == posts and allowed.seen == []++[email protected]("change", [+ {"token_url": "https://collect.example.net/token"},+ {"hosts": ["api.example.com", "collect.example.net"]},+ {"scopes": SCOPES[:1]},+ {"client_id_env": "OTHER_CLIENT_ID"},+])+def test_entry_changed_since_sign_in_is_not_used(idp, api, change):+ allowed, _ = api+ _signed_in(idp)+ changed = _plugin(oauth=[_entry(idp, **change)]) # a later version of the same plugin+ posts = len(idp.token_requests)+ with pytest.raises(ppr.ProviderNotSignedIn, match="changed"):+ changed.call("google", allowed.url)+ assert len(idp.token_requests) == posts and allowed.seen == []+++def test_partial_consent_saves_nothing_and_names_what_is_missing(idp):+ _plugin(oauth=[_entry(idp)])+ idp.granted_scope = SCOPES[0]+ with pytest.raises(SystemExit, match=SCOPES[1]):+ _auth("add")+ assert not (_home() / "auth.json").exists() or _grant() is None++ idp.granted_scope = " ".join(SCOPES)+ assert _auth("add") is True and _grant()["refresh_token"]+++def test_grant_belongs_to_one_profile(idp, api, monkeypatch, tmp_path):+ allowed, _ = api+ _signed_in(idp)+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "other-profile"))+ with pytest.raises(ppr.ProviderNotSignedIn):+ _plugin(oauth=[_entry(idp)]).call("google", allowed.url)+ assert allowed.seen == []+++def test_client_secret_stays_out_of_config_repr_logs_and_errors(idp, api, caplog, capsys):+ allowed, _ = api+ plugin = _signed_in(idp)+ manifest = json.loads((_home() / "plugins" / "voice" / "plugin.yaml").read_text(encoding="utf-8"))+ client = plugin_oauth.parse_oauth_clients(manifest)[0][0]+ assert SECRET not in repr(plugin_oauth._pkce_config(client, KEY))++ _set_grant(expires_at_ms=0)+ idp.token_error = (500, {"error": "server_error", "error_description": SECRET})+ with pytest.raises(AuthError) as excinfo:+ plugin.call("google", allowed.url)+ out = capsys.readouterr()+ assert excinfo.value.code == "oauth_refresh_failed"+ assert SECRET not in str(excinfo.value) + caplog.text + out.out + out.err+++def test_custom_prefix_never_routes_to_a_plugin_grant(idp):+ _plugin("custom", oauth=[_entry(idp, id="foo")])+ assert _auth("add", "custom:foo") is None and idp.token_requests == []+++def test_other_auth_store_writes_keep_the_plugin_grant(idp):+ from hermes_cli.auth import _save_active_provider_state++ _signed_in(idp)+ before = _grant()+ _save_active_provider_state("nous", {"access_token": "unrelated"})+ assert _grant() == before+++def test_install_notice_and_repin_delta_name_the_oauth_entry(idp, tmp_path):+ from hermes_cli.plugins_cmd_catalog import plugin_surface, surface_delta, surface_delta_lines++ manifest = {"name": "voice", "oauth": [_entry(idp)]}+ notice = ppr.requires_auth_notice(manifest)+ assert "google" in notice and "api.example.com" in notice and "hermes auth add voice:google" in notice++ widened = {"name": "voice", "oauth": [_entry(idp, hosts=["api.example.com", "collect.example.net"])]}+ lines = surface_delta_lines(surface_delta(plugin_surface(manifest, tmp_path), plugin_surface(widened, tmp_path)))+ assert len(lines) == 1 and lines[0].startswith("your OAuth sign-in for") and "collect.example.net" in lines[0]+++def test_hermes_auth_commands_route_a_plugin_grant(idp, capsys):+ from hermes_cli import auth_commands++ _plugin(oauth=[_entry(idp)])+ args = SimpleNamespace(provider=KEY, no_browser=False, timeout=None)++ auth_commands.auth_add_command(args)+ assert _grant()["refresh_token"] in idp.refresh_tokens+ auth_commands.auth_status_command(args)+ auth_commands.auth_refresh_command(args)+ auth_commands.auth_logout_command(args)++ assert _grant() is None and _refreshes(idp) == 1+ assert "voice:google: logged in" in capsys.readouterr().outdiff --git a/tests/hermes_cli/test_plugin_validate.py b/tests/hermes_cli/test_plugin_validate.pyindex 5ad481e4557..cbdb0f2d4f3 100644--- a/tests/hermes_cli/test_plugin_validate.py+++ b/tests/hermes_cli/test_plugin_validate.py@@ -9,6 +9,8 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+import pytest+import hermes_yaml as yamlfrom hermes_cli.plugin_validate import validate_plugin_dir@@ -510,3 +512,53 @@ def test_install_deps_probe_imports_from_the_synced_environment(tmp_path: Path,passchecks = {c["name"]: c for c in json.loads(capsys.readouterr().out)["checks"]}assert checks["capability probe"]["ok"], checks["capability probe"]["detail"]+++OAUTH_MANIFEST = dict(BASE_MANIFEST, requires_env=[{"name": "FIXTURE_CLIENT_ID"}, {"name": "FIXTURE_CLIENT_SECRET"}])+++def _oauth_entry(**overrides) -> dict:+ entry = {"id": "google", "authorize_url": "https://accounts.example.com/o/oauth2/auth",+ "token_url": "https://oauth2.example.com/token", "scopes": ["https://api.example.com/auth/docs"],+ "client_id_env": "FIXTURE_CLIENT_ID", "client_secret_env": "FIXTURE_CLIENT_SECRET",+ "hosts": ["docs.example.com"]}+ return {**entry, **overrides}+++def test_oauth_block_passes_and_a_token_url_in_code_is_only_a_warning(tmp_path):+ plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, oauth=[_oauth_entry()]))+ (plugin / "client.py").write_text('TOKEN_URL = "https://oauth2.example.com/token"\n', encoding="utf-8")++ report = validate_plugin_dir(plugin)++ assert report.ok, report.failures+ assert [ok for name, ok, _ in report.checks if name == "oauth"] == [True]+ assert any("oauth2.example.com/token" in warning for warning in report.warnings)++[email protected]("change, problem", [+ ({"id": "Google"}, "id"),+ ({"authorize_url": "http://accounts.example.com/o/oauth2/auth"}, "authorize_url"),+ ({"scopes": []}, "scopes"),+ ({"hosts": ["https://docs.example.com"]}, "hosts"),+ ({"hosts": ["docs.example.com:8443"]}, "hosts"),+ ({"hosts": ["10.0.0.1"]}, "hosts"),+ ({"client_id_env": "fixture_client_id"}, "client_id_env"),+ ({"client_secret_env": "UNDECLARED_SECRET"}, "UNDECLARED_SECRET"),+ ({"id": "openai-codex"}, "openai-codex"),+])+def test_oauth_form_errors_fail_admission(tmp_path, change, problem):+ plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, oauth=[_oauth_entry(**change)]))++ report = validate_plugin_dir(plugin)++ assert [ok for name, ok, _ in report.checks if name == "oauth"] == [False]+ assert any(problem in failure for failure in report.failures), report.failures+++def test_oauth_in_a_plugin_keyed_custom_fails_admission(tmp_path):+ plugin = _make_plugin(tmp_path, manifest=dict(OAUTH_MANIFEST, name="custom", oauth=[_oauth_entry()]))++ report = validate_plugin_dir(plugin)++ assert [ok for name, ok, _ in report.checks if name == "oauth"] == [False]diff --git a/tests/providers/fake_pkce_idp.py b/tests/providers/fake_pkce_idp.pyindex 8a887e9735b..73893698308 100644--- a/tests/providers/fake_pkce_idp.py+++ b/tests/providers/fake_pkce_idp.py@@ -46,6 +46,8 @@ class FakeIdP:body = parse_qs(self.rfile.read(int(self.headers.get("Content-Length", 0))).decode())form = {k: v[0] for k, v in body.items()}idp.token_requests.append(form)+ if idp.token_error is not None:+ return self._json(*idp.token_error)grant = form.get("grant_type")if grant == "authorization_code":challenge = idp.codes.pop(form.get("code", ""), None)@@ -61,8 +63,11 @@ class FakeIdP:idp.issued += 1refresh = f"rt-{idp.issued}-{secrets.token_hex(4)}"idp.refresh_tokens.add(refresh)- self._json(200, {"access_token": f"at-{idp.issued}-{secrets.token_hex(4)}",- "refresh_token": refresh, "expires_in": 3600, "token_type": "Bearer"})+ payload = {"access_token": f"at-{idp.issued}-{secrets.token_hex(4)}",+ "refresh_token": refresh, "expires_in": 3600, "token_type": "Bearer"}+ if idp.granted_scope is not None:+ payload["scope"] = idp.granted_scope+ self._json(200, payload)def _json(self, status, payload):data = json.dumps(payload).encode()@@ -73,6 +78,8 @@ class FakeIdP:self.wfile.write(data)self.override_state: str | None = None+ self.granted_scope: str | None = None # ``scope`` echoed in token responses (None = omitted)+ self.token_error: tuple[int, dict] | None = None # (status, JSON) answered to every token POSTself.server = HTTPServer(("127.0.0.1", 0), Handler)self.base = f"http://127.0.0.1:{self.server.server_address[1]}"self._thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)diff --git a/website/docs/developer-guide/plugins/catalog-submission.md b/website/docs/developer-guide/plugins/catalog-submission.mdindex 61864aa0d79..1717c3d99bf 100644--- a/website/docs/developer-guide/plugins/catalog-submission.md+++ b/website/docs/developer-guide/plugins/catalog-submission.md@@ -145,8 +145,11 @@ the gallery. There is no separate listing to maintain.which honours the active profile (a bare `os.environ` read can pick up anotherprofile's key under multiplexing). A subscription sign-in (Codex / ChatGPTtoday) is used only through `credentialed_provider_request` with- `requires_auth`, so Hermes attaches the token and the plugin never holds it. A- plugin never reads `.env` files, Hermes's `auth.json`, another tool's login (a+ `requires_auth`, so Hermes attaches the token and the plugin never holds it. An+ OAuth client for a third-party API (the user's own Google, Microsoft or Notion+ app) is declared under `oauth:` in `plugin.yaml`, signed in with+ `hermes auth add <plugin>:<id>` and used through the same helper; Hermes+ stores and refreshes that token too. A plugin never reads `.env` files, Hermes's `auth.json`, another tool's login (avendor CLI's token file, a browser profile, a keychain) or any othercredential store directly, and never refreshes, rotates or writes OAuth tokensor presents itself as another vendor's client. If Hermes has no route for adiff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex b612ee737bf..e137ff1412c 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -466,6 +466,84 @@ returns an `AccountUsageSnapshot` (plan, session/weekly windows with**Sign-out** belongs to Hermes, not to a plugin: point users at`hermes auth logout openai-codex` instead of deleting credential files.+### Use your own OAuth client (Google and other APIs)++A plugin that calls a third-party API with the user's own OAuth client (a+Google Cloud "Desktop app" client, a Microsoft or Notion app) does not run the+consent flow, store the refresh token or refresh it. Declare the client and+Hermes owns the grant:++```yaml+name: gemini-voice+requires_env:+ - name: GEMINI_VOICE_CLIENT_ID+ - name: GEMINI_VOICE_CLIENT_SECRET+ secret: true+oauth:+ - id: google+ authorize_url: https://accounts.google.com/o/oauth2/v2/auth+ token_url: https://oauth2.googleapis.com/token+ scopes:+ - https://www.googleapis.com/auth/calendar.events.owned+ - https://www.googleapis.com/auth/documents+ client_id_env: GEMINI_VOICE_CLIENT_ID+ client_secret_env: GEMINI_VOICE_CLIENT_SECRET # optional: a public PKCE client has none+ hosts: [www.googleapis.com, docs.googleapis.com]+ authorize_params: {access_type: offline, prompt: consent} # Google issues a refresh token only with these+```++The user signs in once from a terminal with `hermes auth add gemini-voice:google`+(the plugin's key, a colon, the entry's `id`). That is the same PKCE login the+model-provider helper runs: a loopback redirect on `127.0.0.1`, with an SSH+tunnel hint when Hermes runs on a remote host. If the IdP grants fewer scopes+than declared, nothing is saved. `hermes auth status|refresh|logout+gemini-voice:google` show, refresh and remove the grant. It lives in the active+profile's `auth.json`; Hermes refreshes it on use once less than two minutes+remain and never starts a sign-in under the gateway or cron.++The plugin calls the API through the same helper, with the entry's `id` as the+provider:++```python+from hermes_cli.auth_constants import AuthError+from hermes_cli.plugin_provider_requests import ProviderNotSignedIn, credentialed_provider_request++def create_document(title: str) -> dict:+ try:+ resp = credentialed_provider_request(+ "google", "POST", "https://docs.googleapis.com/v1/documents", json={"title": title}, timeout=20)+ except ProviderNotSignedIn as exc:+ return {"ok": False, "error": str(exc)} # names `hermes auth add gemini-voice:google`+ except AuthError as exc:+ return {"ok": False, "error": f"{exc.code}: {exc}"}+ return {"ok": resp.status < 300, "status": resp.status, "body": resp.json()}+```++The Codex rules above apply, plus:++- **Declared hosts only.** The bearer goes to `https://<host>` (port 443) for+ the entry's `hosts`. Any other URL, `http`, or a URL with user info raises+ `PermissionError` before a request is made.+- **The plugin's own grant.** The grant is stored under the calling plugin's+ key, so another plugin declaring the same `id` cannot use it, and the plugin's+ own entry wins over a Hermes sign-in of the same name.+- **The grant follows the declaration.** It remembers the entry it was made+ for: a plugin version that changes the token URL, hosts, scopes or client+ variables gets `ProviderNotSignedIn` until the user signs in again, and a+ catalog re-pin that adds an `oauth` entry or changes its token host, hosts or+ scopes asks before updating.+- **Errors.** `ProviderNotSignedIn`: not signed in, revoked, or the entry+ changed since sign-in. `AuthError` codes: `oauth_client_id_missing` and+ `oauth_client_secret_missing` (the variable is not set), `invalid_client`,+ `unauthorized_client` and `invalid_scope` (the IdP rejected the client; the+ user has to fix it), `oauth_refresh_failed` (network or server error; try+ later). A revoked grant (`invalid_grant`) is retired: nothing goes to the+ network until the next sign-in.++`hermes plugins validate` checks the `oauth:` block and that its client+variables are declared, and warns when plugin code names the token URL. Like+`requires_auth`, this is consent and visibility, not a sandbox.+### Manifest v2 reference`plugin.yaml` also supports an additive **v2 schema** (#64165). Every field is@@ -487,6 +565,7 @@ this Hermes understands still loads with a warning.| `tags` | list of str | Free-form discovery tags (e.g. `[gateway, telegram]`). || `provides_locales` | list | Language pack declaration: ids (`- pl`) or `{id, endonym, rtl}` mappings whose `locales/<id>[.tui\|.desktop].yaml` the loader registers automatically — see [Ship a language pack](#ship-a-language-pack). || `requires_auth` | list of str | Providers whose sign-in the plugin uses through Hermes (today: `openai-codex`). Required by `credentialed_provider_request`; shown at install and in `hermes plugins show`. See [Use the user's Codex sign-in](#use-the-users-codex-sign-in-core-made-requests). |+| `oauth` | list of mappings | OAuth clients the plugin uses through Hermes: `id`, `authorize_url`, `token_url`, `scopes`, `client_id_env`, optional `client_secret_env`, `hosts`, optional `authorize_params`. Signed in with `hermes auth add <plugin>:<id>`, used through `credentialed_provider_request`. See [Use your own OAuth client](#use-your-own-oauth-client-google-and-other-apis). |```yaml# plugin.yaml — manifest v2 examplediff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex a52c64ce22e..b60711f46ae 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -572,7 +572,7 @@ granted, `hermes plugins update` surfaces the additions and asks again. Newcapabilities stay off until you consent — a plugin update can never silentlywiden its access. Catalog re-pins go one step further: when the new pin addstools, hooks, Python dependencies, host capabilities, a provider sign-in-(`requires_auth`) or a Desktop UI half the installed version did not have, the CLI shows the delta and asks `y/N` before+(`requires_auth`), a new or changed OAuth client (`oauth:`) or a Desktop UI half the installed version did not have, the CLI shows the delta and asks `y/N` beforeanything moves, and the Desktop / dashboard **Update** button opens the sameconfirmation. Declining (or a non-interactive session) leaves the plugin atthe old pin.