The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(auth): opt out of borrowing Codex CLI / Claude Code logins (auth.adopt_external_logins)
teknium16c7f693473f3
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.pyindex 5deb9ff10b0..b03aee1b862 100644--- a/agent/anthropic_credentials.py+++ b/agent/anthropic_credentials.py@@ -229,8 +229,8 @@ def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]:def claude_code_credentials_path() -> Path:"""Claude Code's shared OAuth file; every profile reads/writes this same path. Honours ``CLAUDE_CONFIG_DIR``- like the Claude CLI itself (blank = unset, as in ``hermes_cli.foreign_sessions``), so pointing it at an- empty directory opts a Hermes process out of borrowing the login."""+ like the Claude CLI itself (blank = unset, as in ``hermes_cli.foreign_sessions``). The supported opt-out of+ borrowing the login is ``auth.adopt_external_logins: false`` in config.yaml."""override = os.environ.get("CLAUDE_CONFIG_DIR", "").strip()root = Path(override).expanduser() if override else Path.home() / ".claude"return root / ".credentials.json"@@ -244,7 +244,13 @@ def _read_claude_code_credentials_from_file() -> Optional[Dict[str, Any]]:def read_claude_code_credentials() -> Optional[Dict[str, Any]]:"""Read refreshable Claude Code OAuth credentials (Keychain and/or file). When both exist: prefer the onlynon-expired one (Claude Code 2.1.x refreshes one source but not the other), else the later ``expiresAt`` so a- refresh uses the freshest refreshToken. ~/.claude.json primaryApiKey is deliberately excluded."""+ refresh uses the freshest refreshToken. ~/.claude.json primaryApiKey is deliberately excluded.++ This is the only reader of the borrowed login, so ``auth.adopt_external_logins: false`` is enforced here:+ every resolver, pool seed/sync and 401 refresher then sees "no Claude Code login" and never touches the file."""+ from agent.credential_sources import adopt_external_logins_enabled+ if not adopt_external_logins_enabled():+ return Nonekc_creds = _read_claude_code_credentials_from_keychain()file_creds = _read_claude_code_credentials_from_file()if not (kc_creds and file_creds):diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex 458c8c62aae..306eb1323ec 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -2182,11 +2182,16 @@ def _seed_anthropic_singletons(seed: _Seeder) -> None:read_claude_code_credentials,read_hermes_oauth_credentials,)+ from agent.credential_sources import adopt_external_logins_enabled- for source_name, creds in (- ("hermes_pkce", read_hermes_oauth_credentials()),- ("claude_code", read_claude_code_credentials()),- ):+ sources = [("hermes_pkce", read_hermes_oauth_credentials())]+ if adopt_external_logins_enabled():+ sources.append(("claude_code", read_claude_code_credentials()))+ else:+ # Singleton-seeded rows are otherwise never pruned; the opt-out must also drop the row an+ # earlier (adopting) process persisted, or it keeps rotating a login Hermes no longer reads.+ seed.changed |= _retain_sources_not_in(seed.entries, {"claude_code"})+ for source_name, creds in sources:if creds and creds.get("accessToken"):seed.upsert(source_name, {"auth_type": AUTH_TYPE_OAUTH,diff --git a/agent/credential_sources.py b/agent/credential_sources.pyindex ba90e312f14..7a8ab1644c9 100644--- a/agent/credential_sources.py+++ b/agent/credential_sources.py@@ -7,14 +7,47 @@ Readers live in ``agent.credential_pool``; what is unified here is **removal**:dispatcher suppresses ``(provider, source_id)`` in auth.json so the seedingbranch skips the upsert. Adding a source: wire a reader branch in``_seed_from_*``, gate it behind ``is_source_suppressed``, register a step here.++Also home to the one policy switch over *borrowed* CLI logins (Codex CLI's+``~/.codex/auth.json``, Claude Code's ``~/.claude/.credentials.json``):+``auth.adopt_external_logins`` in config.yaml."""from __future__ import annotations+import loggingimport osfrom dataclasses import dataclass, fieldfrom typing import Callable, List, Optional+logger = logging.getLogger(__name__)++EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE = (+ "External CLI logins (Codex CLI, Claude Code) are not adopted: auth.adopt_external_logins is false. "+ "Hermes uses only its own logins; run `hermes auth add <provider>` to add one."+)+_notice_logged = False+++def adopt_external_logins_enabled() -> bool:+ """``auth.adopt_external_logins`` (default True).++ Codex and Claude OAuth refresh tokens are single-use and rotate, so once Hermes borrows a CLI's+ token pair the two programs hold one token family and whichever refreshes first logs the other+ out. When the user opts out, Hermes never reads or refreshes those files and says so once per+ process (INFO) the first time it would have."""+ global _notice_logged+ try:+ from hermes_cli.config import load_config_readonly+ auth_cfg = (load_config_readonly() or {}).get("auth")+ except Exception:+ return True+ enabled = not isinstance(auth_cfg, dict) or bool(auth_cfg.get("adopt_external_logins", True))+ if not enabled and not _notice_logged:+ _notice_logged = True+ logger.info(EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE)+ return enabled+@dataclassclass RemovalResult:diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex f4c029462b4..db55aefe802 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -176,8 +176,14 @@ def _save_codex_tokens(tokens: Dict[str, str], last_refresh: str = None, label:def _recover_codex_tokens_from_cli(reason: str) -> Optional[Dict[str, str]]:- """Adopt a valid Codex CLI token pair into Hermes auth, if available."""+ """Adopt a valid Codex CLI token pair into Hermes auth, if available.++ Automatic adoption only; the interactive import offer in ``_login_openai_codex`` asks first and is+ not subject to ``auth.adopt_external_logins``."""+ from agent.credential_sources import adopt_external_logins_enabledfrom hermes_cli.auth import _import_codex_cli_tokens, _save_codex_tokens+ if not adopt_external_logins_enabled():+ return Noneimported = _import_codex_cli_tokens()# Require BOTH tokens before adopting: persisting a payload without a usable refresh_token# would only break the next refresh cycle.diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.pyindex 7a295f5952e..09f520982ab 100644--- a/hermes_cli/auth_commands.py+++ b/hermes_cli/auth_commands.py@@ -28,6 +28,8 @@ _OAUTH_CAPABLE_PROVIDERS = {"anthropic", "nous", "openai-codex", "xai-oauth", "q# ...and default to it when ``--type`` is omitted. OpenRouter stays API-key-first: the documented# ``hermes auth add openrouter --api-key sk-or-...`` must keep working with no ``--type``._OAUTH_DEFAULT_PROVIDERS = _OAUTH_CAPABLE_PROVIDERS - {"openrouter"}+# Providers whose sibling CLI login Hermes may borrow (``auth.adopt_external_logins``).+EXTERNAL_LOGIN_PROVIDERS = {"anthropic", "openai-codex"}def _get_custom_provider_entries() -> list[dict]:@@ -491,6 +493,15 @@ def auth_list_command(args) -> None:)print(row.rstrip())print()+ if not provider_filter or provider_filter in EXTERNAL_LOGIN_PROVIDERS:+ _print_external_login_notice()+++def _print_external_login_notice() -> None:+ """One line telling the user why no Codex CLI / Claude Code login shows up when adoption is off."""+ from agent.credential_sources import EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE, adopt_external_logins_enabled+ if not adopt_external_logins_enabled():+ print(EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE)def auth_remove_command(args) -> None:@@ -607,6 +618,8 @@ def auth_status_command(args) -> None:if not status.get("logged_in"):reason = status.get("error")print(f"{provider}: logged out" + (f" ({reason})" if reason else ""))+ if provider in EXTERNAL_LOGIN_PROVIDERS:+ _print_external_login_notice()returnprint(f"{provider}: logged in")for key in ("auth_type", "client_id", "redirect_uri", "scope", "expires_at", "api_base_url"):diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 80a3bfbafd6..5f0970c3936 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1644,6 +1644,14 @@ DEFAULT_CONFIG = {# Custom personalities: {"name": "system prompt"} or {"name": {"description", "system_prompt",# "tone", "style"}}."personalities": {},+ "auth": { # Login policy (credentials themselves live in auth.json / .env).+ # Borrow and refresh the Codex CLI (~/.codex/auth.json) and Claude Code (~/.claude/.credentials.json)+ # logins automatically when Hermes has no usable login of its own. Their refresh tokens are single-use+ # and rotate, so two programs on one login can log each other out; set false to make Hermes use only+ # its own logins (`hermes auth add <provider>`). `hermes auth add openai-codex` still offers the import+ # interactively.+ "adopt_external_logins": True,+ },"security": { # Security: pre-exec scanning via tirith plus related guards."allow_private_urls": False, # allow requests to private/internal IPs (OpenWrt, VPNs)# CIDR blocks a local TUN proxy answers DNS with (Mihomo/Clash fake-ip, Surge enhanced).diff --git a/hermes_cli/web_server_config.py b/hermes_cli/web_server_config.pyindex b5fd93f4417..b502ab914f9 100644--- a/hermes_cli/web_server_config.py+++ b/hermes_cli/web_server_config.py@@ -101,6 +101,14 @@ _SCHEMA_OVERRIDES: Dict[str, Dict[str, Any]] = {"description": "Refuse Docker sandboxes when egress is enabled but not configured/running","category": "security",},+ "auth.adopt_external_logins": {+ "type": "boolean",+ "description": (+ "Borrow and refresh the Codex CLI / Claude Code logins when Hermes has no usable login of its own. "+ "Off: Hermes uses only its own logins (`hermes auth add <provider>`)."+ ),+ "category": "security",+ },"tts.provider": _select("Text-to-speech provider","edge", "elevenlabs", "openai", "xai", "minimax", "mistral", "gemini", "neutts", "kittentts", "piper",@@ -197,6 +205,7 @@ _CATEGORY_MERGE: Dict[str, str] = {"session": "general","nous": "agent","connections": "agent",+ "auth": "security",}diff --git a/tests/agent/test_anthropic_external_login_optout.py b/tests/agent/test_anthropic_external_login_optout.pynew file mode 100644index 00000000000..72a3fafa1bf--- /dev/null+++ b/tests/agent/test_anthropic_external_login_optout.py@@ -0,0 +1,82 @@+"""``auth.adopt_external_logins: false`` keeps Hermes off the Claude Code login (#113023).++Claude Code's OAuth refresh token is single-use: once Hermes borrows and refreshes it, Hermes and+Claude Code hold one token family and whichever refreshes first logs the other out. With the opt-out+set, Hermes must neither read nor refresh ``~/.claude/.credentials.json``, must drop the pool row an+earlier adopting process persisted, and must say so in ``hermes auth list``.+"""+from __future__ import annotations++import io+import json+import time+from contextlib import redirect_stdout+from types import SimpleNamespace+from unittest import mock++import urllib.request++from agent import anthropic_credentials as ac+from agent import credential_sources+from agent.credential_pool import load_pool+from hermes_cli.auth_commands import auth_list_command+++def _write_config(hermes_home, adopt):+ body = "model:\n provider: anthropic\n model: claude-sonnet-4-5\n"+ if adopt is not None:+ body += f"auth:\n adopt_external_logins: {'true' if adopt else 'false'}\n# arm {adopt}\n"+ (hermes_home / "config.yaml").write_text(body)+++def test_opt_out_never_reads_or_refreshes_claude_code_login(tmp_path, monkeypatch):+ hermes_home, claude_dir = tmp_path / "hermes", tmp_path / "claude"+ hermes_home.mkdir()+ claude_dir.mkdir()+ (hermes_home / ".env").write_text("")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(claude_dir))+ monkeypatch.setattr(credential_sources, "_notice_logged", False, raising=False)+ cred_file = claude_dir / ".credentials.json"+ cred_file.write_text(json.dumps({"claudeAiOauth": {+ "accessToken": "sk-ant-oat01-expired", "refreshToken": "sk-ant-ort01-cc",+ "expiresAt": int(time.time() * 1000) - 3_600_000, "scopes": ["user:inference"]}}))+ original_bytes = cred_file.read_bytes()++ posts: list = []++ def fake_urlopen(req, timeout=None):+ if "oauth/token" in req.full_url: # the Anthropic token endpoint; other seeders probe other hosts+ posts.append(req.full_url)+ body = json.dumps({"access_token": "sk-ant-oat01-fresh", "refresh_token": "sk-ant-ort01-fresh",+ "expires_in": 3600}).encode()+ resp = mock.MagicMock()+ resp.read.return_value = body+ resp.__enter__.return_value = resp+ return resp++ monkeypatch.setattr(urllib.request, "urlopen", fake_urlopen)++ # Arm A (default): today's behaviour — the borrowed login is seeded into the pool.+ _write_config(hermes_home, adopt=None)+ assert [e.source for e in load_pool("anthropic").entries()] == ["claude_code"]++ # Arm B (opt-out): no read, no refresh POST, the persisted row is dropped, the status line explains why.+ _write_config(hermes_home, adopt=False)+ assert ac.resolve_anthropic_token() is None+ assert posts == []+ assert cred_file.read_bytes() == original_bytes+ assert [e.source for e in load_pool("anthropic").entries()] == []+ out = io.StringIO()+ with redirect_stdout(out):+ auth_list_command(SimpleNamespace(provider=None))+ assert credential_sources.EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE in out.getvalue()++ # Arm A again: flipping back adopts (and refreshes) exactly as before.+ _write_config(hermes_home, adopt=True)+ assert ac.resolve_anthropic_token() == "sk-ant-oat01-fresh"+ assert len(posts) == 1+ out = io.StringIO()+ with redirect_stdout(out):+ auth_list_command(SimpleNamespace(provider=None))+ assert credential_sources.EXTERNAL_LOGINS_NOT_ADOPTED_NOTICE not in out.getvalue()diff --git a/tests/hermes_cli/test_auth_codex_self_heal.py b/tests/hermes_cli/test_auth_codex_self_heal.pyindex 4c92cde2f59..fa6182d7cb2 100644--- a/tests/hermes_cli/test_auth_codex_self_heal.py+++ b/tests/hermes_cli/test_auth_codex_self_heal.py@@ -96,3 +96,34 @@ def test_self_heals_missing_singleton_access_token_from_codex_cli(tmp_path, monkassert tokens["refresh_token"] == "fresh-refresh"+++def test_opt_out_never_adopts_codex_cli_login(tmp_path, monkeypatch):+ """``auth.adopt_external_logins: false`` (#113023): the Codex CLI pair is a single-use refresh-token+ family the user did not hand to Hermes. Both automatic recovery paths must leave it (and Hermes' own+ auth.json) untouched and surface the real error instead."""+ hermes_home = tmp_path / "hermes"+ codex_home = tmp_path / "codex"+ hermes_home.mkdir()+ codex_home.mkdir()+ (hermes_home / "config.yaml").write_text("auth:\n adopt_external_logins: false\n")+ hermes_auth = {"version": 1, "providers": {"openai-codex": {+ "tokens": {"refresh_token": "stale-refresh"}, "auth_mode": "chatgpt"}}}+ (hermes_home / "auth.json").write_text(json.dumps(hermes_auth))+ (codex_home / "auth.json").write_text(json.dumps({+ "tokens": {"access_token": "fresh-access", "refresh_token": "fresh-refresh"}}))+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.setenv("CODEX_HOME", str(codex_home))++ with pytest.raises(AuthError) as info:+ resolve_codex_runtime_credentials()+ assert info.value.code == "codex_auth_missing_access_token"++ def _rejected(*_a, **_k):+ raise AuthError("bad", provider="openai-codex", code="invalid_grant", relogin_required=True)++ monkeypatch.setattr(auth_codex, "refresh_codex_oauth_pure", _rejected)+ with pytest.raises(AuthError) as info:+ _refresh_codex_auth_tokens(dict(STALE), 5.0)+ assert info.value.relogin_required # surfaced, not papered over with the CLI pair+ assert json.loads((hermes_home / "auth.json").read_text()) == hermes_authdiff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex da7ef399bb1..0632b7ad35d 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -91,7 +91,7 @@ Don't have a subscription yet? Get one at [portal.nousresearch.com/manage-subscr:::info Codex Note-The OpenAI Codex provider authenticates via device code (open a URL, enter a code). Hermes stores the resulting credentials in its own auth store under `~/.hermes/auth.json` and can import existing Codex CLI credentials from `~/.codex/auth.json` when present. No Codex CLI installation is required.+The OpenAI Codex provider authenticates via device code (open a URL, enter a code). Hermes stores the resulting credentials in its own auth store under `~/.hermes/auth.json` and can import existing Codex CLI credentials from `~/.codex/auth.json` when present. No Codex CLI installation is required. Automatic adoption of the Codex CLI login (when Hermes' own refresh fails) is controlled by `auth.adopt_external_logins` — see [Borrowed CLI logins](/docs/user-guide/security#borrowed-cli-logins).If a token refresh fails with a terminal error (HTTP 4xx, `invalid_grant`, revoked grant, etc.), Hermes marks the refresh token as dead and stops replaying it so you don't see a flood of identical auth failures. The next request surfaces a typed re-auth message instead. Run `hermes auth add openai-codex` (or `hermes model` → **ChatGPT or Codex Subscription**) to start a fresh device-code login; the quarantine clears on the next successful exchange.@@ -163,7 +163,10 @@ Use Claude models directly through the Anthropic API — no OpenRouter proxy neeWhen no explicit environment credential is selected, Hermes-owned OAuth grantsin the credential pool take precedence over a borrowed Claude Code login. The-borrowed login remains the fallback when no owned OAuth grant is available.+borrowed login remains the fallback when no owned OAuth grant is available —+unless `auth.adopt_external_logins: false` is set, in which case Hermes never+reads or refreshes Claude Code's credentials (see+[Borrowed CLI logins](/docs/user-guide/security#borrowed-cli-logins)).Auxiliary authentication recovery refreshes the credential used by the failedrequest, not an unrelated ambient login; rotating a borrowed login can otherwiseinvalidate its owner's refresh token.diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex d1e8526d535..9b1b77b1383 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -665,6 +665,17 @@ terminal:Paths are relative to `~/.hermes/`. Files are mounted to `/root/.hermes/` inside the container. This list is read by `tools/credential_files.py` (`terminal.credential_files`) — it lives under the `terminal:` block but is loaded by the credential-files module, not the core terminal backend, so it isn't part of the bundled `DEFAULT_CONFIG` snapshot.+### Borrowed CLI logins (Codex CLI, Claude Code) {#borrowed-cli-logins}++When Hermes has no usable login of its own for `openai-codex` or `anthropic`, it can borrow the Codex CLI's `~/.codex/auth.json` and Claude Code's `~/.claude/.credentials.json` (or Keychain entry) and refresh them on your behalf. Both use single-use, rotating refresh tokens: once two programs hold one token family, whichever refreshes first invalidates the other's copy, which shows up as "I logged in once in the terminal and Hermes keeps failing" (or the reverse). If you run those CLIs alongside Hermes, give Hermes its own login and turn adoption off:++```yaml+auth:+ adopt_external_logins: false # default: true+```++With the switch off Hermes never reads or refreshes those files: the `claude_code` credential-pool row disappears, `hermes auth list` prints one line saying so, and the log carries one INFO line per process. Only automatic adoption is affected — `hermes auth add openai-codex` still asks before importing an existing Codex CLI login. Add your own logins with `hermes auth add anthropic` / `hermes auth add openai-codex`.+### What Each Sandbox Filters| Sandbox | Default Filter | Passthrough Override |