The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(auth): opt-in browser authorization-code + PKCE login for openai-codex
astraltrekkinde66512ab78d
diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 908b1e31b67..1e90a1aafdf 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -2068,6 +2068,23 @@ telemetry:# endpoint: https://telemetry.nousresearch.com/v1/telemetry+# =============================================================================+# Login Policy (credentials themselves live in auth.json / .env)+# =============================================================================+auth:+ # Borrow and refresh the Codex CLI (~/.codex/auth.json) and Claude Code logins when Hermes has+ # no usable login of its own. Their refresh tokens are single-use, so two programs on one login+ # can log each other out; set false to make Hermes use only its own logins.+ adopt_external_logins: true+ # How `hermes auth add openai-codex` / `hermes model` sign in to OpenAI Codex.+ # device_code (default) — open a URL and enter a code.+ # browser — authorization-code + PKCE on http://localhost:1455/auth/callback (the redirect+ # OpenAI registered for the Codex client) for organizations that disable the+ # device-code grant; falls back to device code when that port is busy.+ # `hermes auth add openai-codex --browser` opts in for a single login without changing this.+ codex_login_flow: device_code++# =============================================================================# Update Behavior# =============================================================================diff --git a/hermes_cli/auth_codex.py b/hermes_cli/auth_codex.pyindex b2f3a930813..37940c25ad4 100644--- a/hermes_cli/auth_codex.py+++ b/hermes_cli/auth_codex.py@@ -874,12 +874,14 @@ def _pool_codex_access_token() -> str:def _login_openai_codex(args, pconfig: ProviderConfig, *, force_new_login: bool = False) -> None:- """OpenAI Codex login via device code flow. Tokens stored in ~/.hermes/auth.json."""+ """OpenAI Codex login: device code by default, browser PKCE when opted in (``--browser`` /+ ``auth.codex_login_flow``). Tokens stored in ~/.hermes/auth.json."""from hermes_cli.auth import (- _codex_access_token_is_expiring, _codex_device_code_login, _import_codex_cli_tokens,+ _codex_access_token_is_expiring, _import_codex_cli_tokens,_offer_existing_oauth_credentials, _print_login_success, _prompt_yes_no, _save_codex_tokens,_update_config_for_provider, resolve_codex_runtime_credentials)- del args, pconfig # kept for parity with other provider login helpers+ from hermes_cli.auth_codex_browser import codex_oauth_login+ del pconfig # kept for parity with other provider login helpersif not force_new_login:if _offer_existing_oauth_credentials("openai-codex", resolve=resolve_codex_runtime_credentials,@@ -901,12 +903,10 @@ def _login_openai_codex(args, pconfig: ProviderConfig, *, force_new_login: boolprint(f" Config updated: {config_path} (model.provider=openai-codex)")return- # Run a fresh device code flow — Hermes gets its own OAuth session+ # Run a fresh OAuth flow — Hermes gets its own session (device code unless the user opted in+ # to the browser flow).print()- print("Signing in to OpenAI Codex...")- print("(Hermes creates its own session — won't affect Codex CLI or VS Code)")- print()- creds = _codex_device_code_login()+ creds = codex_oauth_login(args)_save_codex_tokens(creds["tokens"], creds.get("last_refresh"))config_path = _update_config_for_provider("openai-codex", creds.get("base_url", DEFAULT_CODEX_BASE_URL))diff --git a/hermes_cli/auth_codex_browser.py b/hermes_cli/auth_codex_browser.pynew file mode 100644index 00000000000..399ba11fa70--- /dev/null+++ b/hermes_cli/auth_codex_browser.py@@ -0,0 +1,169 @@+"""OpenAI Codex browser login: authorization-code + PKCE on a loopback listener (opt-in).++``hermes auth add openai-codex --browser`` (or ``auth.codex_login_flow: browser``) sends the+system browser to OpenAI's authorize endpoint and receives the code on+``http://localhost:1455/auth/callback`` — the redirect URI fixed by the public Codex client+registration, so the port is not negotiable. Organizations that disable the device-code grant can+still sign in this way (#95743). The device-code flow in ``auth_codex.py`` stays the default and is+the fallback whenever the loopback port is already taken (a Codex CLI login in progress).++Credentials come back in the same dict shape as ``_codex_device_code_login`` with+``source="loopback_pkce"`` so the pool/singleton save paths treat both flows alike. Tokens,+authorization codes and the PKCE verifier are never logged or printed.++Derived from #97058 by @astraltrekkin, re-homed after the ``auth_codex.py`` split.+"""++from __future__ import annotations++import hmac+import logging+import secrets+import webbrowser+from typing import Any, Dict, Optional+from urllib.parse import urlencode++from hermes_cli.auth_constants import AuthError, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL, _codex_err+from hermes_cli.auth_device_flow import (+ _bind_loopback_callback_server, _can_open_graphical_browser, _make_loopback_callback_handler,+ _pkce_code_challenge, _pkce_code_verifier, _print_loopback_ssh_hint, _serve_loopback_callback)++logger = logging.getLogger("hermes_cli.auth")++CODEX_OAUTH_AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize"+CODEX_OAUTH_BROWSER_SCOPE = "openid profile email offline_access"+# Registered with the Codex client: ``http://localhost:1455/auth/callback``. The listener binds+# 127.0.0.1 explicitly; only the redirect URI string says ``localhost``.+CODEX_BROWSER_CALLBACK_PORT = 1455+CODEX_BROWSER_CALLBACK_PATH = "/auth/callback"+CODEX_BROWSER_CALLBACK_TIMEOUT_SECONDS = 300.0+CODEX_LOGIN_FLOWS = ("device_code", "browser")+CODEX_BROWSER_PORT_BUSY_CODE = "codex_browser_port_busy"++_PORT_BUSY_NOTICE = (+ f"Port {CODEX_BROWSER_CALLBACK_PORT} is already in use (a Codex CLI sign-in may be running). "+ "OpenAI only redirects to that port, so falling back to the device-code login.")+++def _codex_login_flow(args: Any) -> str:+ """``browser`` only when the user asked for it: ``--browser`` or ``auth.codex_login_flow``."""+ if getattr(args, "browser", False):+ return "browser"+ from hermes_cli.config import load_config_readonly+ auth_cfg = (load_config_readonly() or {}).get("auth")+ flow = str((auth_cfg or {}).get("codex_login_flow", "device_code") if isinstance(auth_cfg, dict) else "device_code")+ flow = flow.strip().lower() or "device_code"+ if flow not in CODEX_LOGIN_FLOWS:+ print(f"Ignoring unknown auth.codex_login_flow {flow!r} (expected one of {', '.join(CODEX_LOGIN_FLOWS)}).")+ return "device_code"+ return flow+++def codex_oauth_login(args: Any) -> Dict[str, Any]:+ """Run the Codex OAuth flow selected by *args*/config; port-busy browser attempts fall back."""+ from hermes_cli import auth as auth_mod # late: ``hermes_cli.auth.<name>`` patches must intercept+ if _codex_login_flow(args) == "browser":+ try:+ return _codex_browser_login(+ open_browser=not getattr(args, "no_browser", False),+ timeout_seconds=getattr(args, "timeout", None))+ except AuthError as exc:+ if exc.code != CODEX_BROWSER_PORT_BUSY_CODE:+ raise+ print(_PORT_BUSY_NOTICE)+ print()+ print("Signing in to OpenAI Codex...")+ print("(Hermes creates its own session — won't affect Codex CLI or VS Code)")+ print()+ return auth_mod._codex_device_code_login()+++def _codex_browser_authorize_url(*, redirect_uri: str, state: str, code_challenge: str) -> str:+ return f"{CODEX_OAUTH_AUTHORIZE_URL}?" + urlencode({+ "response_type": "code", "client_id": CODEX_OAUTH_CLIENT_ID, "redirect_uri": redirect_uri,+ "scope": CODEX_OAUTH_BROWSER_SCOPE, "code_challenge": code_challenge,+ "code_challenge_method": "S256", "id_token_add_organizations": "true", "state": state})+++def _codex_browser_exchange_code(code: str, *, redirect_uri: str, code_verifier: str) -> Dict[str, Any]:+ """Swap the authorization code for tokens at the token endpoint the device flow also uses."""+ from hermes_cli.auth_codex import _codex_login_post, _codex_login_rate_limited_error+ token_resp = _codex_login_post(+ CODEX_OAUTH_TOKEN_URL,+ data={+ "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri,+ "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ failure=("Token exchange failed", "token_exchange_failed"))+ if token_resp.status_code == 429:+ raise _codex_login_rate_limited_error(token_resp, during=" during token exchange")+ if token_resp.status_code != 200:+ raise _codex_err(+ f"Token exchange returned status {token_resp.status_code}.", "token_exchange_error")+ tokens = token_resp.json()+ if not tokens.get("access_token", ""):+ raise _codex_err(+ "Token exchange did not return an access_token.", "token_exchange_no_access_token")+ return tokens+++def _codex_browser_login(+ *, open_browser: bool = True, timeout_seconds: Optional[float] = None) -> Dict[str, Any]:+ """Authorization-code + PKCE login on the loopback listener; returns the device-flow creds shape.++ Raises ``AuthError(code=CODEX_BROWSER_PORT_BUSY_CODE)`` when :1455 cannot be bound so the caller+ can fall back to the device-code flow instead of failing the login.+ """+ from hermes_cli.auth import _utc_now_z+ from hermes_cli.auth_codex import _codex_base_url+ code_verifier = _pkce_code_verifier()+ state = secrets.token_urlsafe(32)+ handler_cls, result = _make_loopback_callback_handler(CODEX_BROWSER_CALLBACK_PATH, display_name="OpenAI Codex")+ server = _bind_loopback_callback_server(+ "127.0.0.1", CODEX_BROWSER_CALLBACK_PORT, handler_cls, err=_codex_err,+ bind_failed_code=CODEX_BROWSER_PORT_BUSY_CODE)+ redirect_uri = f"http://localhost:{server.server_address[1]}{CODEX_BROWSER_CALLBACK_PATH}"+ auth_url = _codex_browser_authorize_url(+ redirect_uri=redirect_uri, state=state, code_challenge=_pkce_code_challenge(code_verifier))++ print()+ print("Signing in to OpenAI Codex (browser authorization)...")+ print("(Hermes creates its own session — won't affect Codex CLI or VS Code)")+ print()+ print(f"Open this URL to authorize Hermes:\n {auth_url}\n")+ _print_loopback_ssh_hint(redirect_uri)+ if open_browser and _can_open_graphical_browser():+ try:+ opened = webbrowser.open(auth_url)+ except Exception:+ opened = False+ print("Browser opened for OpenAI authorization." if opened+ else "Could not open the browser automatically; use the URL above.")+ wait = float(timeout_seconds or CODEX_BROWSER_CALLBACK_TIMEOUT_SECONDS)+ print(f"Waiting for the OpenAI callback on {redirect_uri} (timeout {int(wait)}s, Ctrl+C to cancel)...")+ try:+ callback = _serve_loopback_callback(+ server, result, timeout_seconds=wait, err=_codex_err, timeout_code="codex_browser_callback_timeout")+ except KeyboardInterrupt:+ print("\nLogin cancelled.")+ raise SystemExit(130)++ if callback.get("error"):+ detail = callback.get("error_description") or callback["error"]+ raise _codex_err(f"OpenAI authorization failed: {detail}", "codex_browser_auth_denied")+ if not hmac.compare_digest(str(callback.get("state") or ""), state):+ raise _codex_err(+ "Authorization callback state mismatch — the redirect did not come from this login. Aborting.",+ "codex_browser_state_mismatch")+ code = str(callback.get("code") or "").strip()+ if not code:+ raise _codex_err("Authorization callback did not carry a code.", "codex_browser_no_code")++ print("Exchanging the authorization code for Codex tokens...")+ tokens = _codex_browser_exchange_code(code, redirect_uri=redirect_uri, code_verifier=code_verifier)+ return {+ "tokens": {+ "access_token": tokens.get("access_token", ""),+ "refresh_token": tokens.get("refresh_token", "")},+ "base_url": _codex_base_url(), "last_refresh": _utc_now_z(), "auth_mode": "chatgpt",+ "source": "loopback_pkce"}diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.pyindex 43d12bf2c39..90ded946045 100644--- a/hermes_cli/auth_commands.py+++ b/hermes_cli/auth_commands.py@@ -218,7 +218,9 @@ class _OAuthAddSpec:login: Callable[[Any], dict]token: Callable[[dict], str]- source: str+ # Pool ``source`` string, or a callable deriving it from the login result when one provider+ # offers several flows (Codex: device code vs browser PKCE).+ source: str | Callable[[dict], str]fields: Callable[[dict, str], dict]activate_first: bool = False# OpenRouter's PKCE exchange mints a plain API key (no refresh pair), so its pool entry is an@@ -226,6 +228,17 @@ class _OAuthAddSpec:auth_type: str = AUTH_TYPE_OAUTH+def _codex_login(args) -> dict:+ from hermes_cli.auth_codex_browser import codex_oauth_login+ return codex_oauth_login(args)+++def _codex_pool_source(creds: dict) -> str:+ if creds.get("source") == "loopback_pkce":+ return f"{SOURCE_MANUAL}:loopback_pkce"+ return SOURCE_MANUAL_DEVICE_CODE++_OAUTH_ADD_SPECS: dict[str, _OAuthAddSpec] = {"anthropic": _OAuthAddSpec(login=_anthropic_oauth_login,@@ -236,9 +249,9 @@ _OAUTH_ADD_SPECS: dict[str, _OAuthAddSpec] = {"expires_at_ms": creds.get("expires_at_ms"),"base_url": _provider_base_url(provider)}),"openai-codex": _OAuthAddSpec(- login=lambda args: auth_mod._codex_device_code_login(),+ login=_codex_login,token=lambda creds: creds["tokens"]["access_token"],- source=SOURCE_MANUAL_DEVICE_CODE,+ source=_codex_pool_source,fields=lambda creds, provider: {"refresh_token": creds["tokens"].get("refresh_token"),"base_url": creds.get("base_url"),@@ -380,7 +393,11 @@ def auth_add_command(args) -> None:_unsuppress_provider_sources(provider)wanted_priority = getattr(args, "priority", None)- entry = _add_credential(args, provider, pool, requested_type)+ try:+ entry = _add_credential(args, provider, pool, requested_type)+ except auth_mod.AuthError as exc:+ # A denied / mismatched / timed-out OAuth login is a user-facing outcome, not a crash.+ raise SystemExit(f"Login failed: {auth_mod.format_auth_error(exc)}") from excif wanted_priority is not None:placed_pool = load_pool(provider)moved = placed_pool.move_entry(entry.id, int(wanted_priority))@@ -406,7 +423,8 @@ def _add_credential(args, provider: str, pool, requested_type: str) -> PooledCre# ``manual:*`` entries refresh from their own token pair, so they need no singleton shadow.entry = PooledCredential(provider=provider, id=uuid.uuid4().hex[:6], label=label, auth_type=spec.auth_type, priority=0,- source=spec.source, access_token=token, **spec.fields(creds, provider))+ source=spec.source(creds) if callable(spec.source) else spec.source,+ access_token=token, **spec.fields(creds, provider))existing = pool.entries()entry = pool.add_entry(entry)# The first Codex/xAI credential becomes the active provider (as the old singleton save pathdiff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 4b519f3ca7c..9d9a6b6cae0 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1688,6 +1688,13 @@ DEFAULT_CONFIG = {# its own logins (`hermes auth add <provider>`). `hermes auth add openai-codex` still offers the import# interactively."adopt_external_logins": True,+ # How `hermes auth add openai-codex` / `hermes model` sign in to OpenAI Codex.+ # "device_code" (default): open a URL, enter a code. "browser": authorization-code + PKCE on+ # the loopback listener http://localhost:1455/auth/callback (the redirect OpenAI registered+ # for the Codex client) — for organizations that disable the device-code grant. Falls back+ # to device code when that port is busy. `hermes auth add openai-codex --browser` opts in+ # for one login without changing this key.+ "codex_login_flow": "device_code",},"security": { # Security: pre-exec scanning via tirith plus related guards."allow_private_urls": False, # allow requests to private/internal IPs (OpenWrt, VPNs)diff --git a/hermes_cli/subcommands/auth.py b/hermes_cli/subcommands/auth.pyindex 686f9ffb1e6..f53097a8799 100644--- a/hermes_cli/subcommands/auth.py+++ b/hermes_cli/subcommands/auth.py@@ -27,6 +27,11 @@ def build_auth_parser(subparsers, *, cmd_auth: Callable) -> None:auth_add.add_argument("--scope", help="OAuth scope override")auth_add.add_argument("--no-browser", action="store_true", help="Do not auto-open a browser for OAuth login")+ auth_add.add_argument(+ "--browser", action="store_true",+ help="openai-codex only: sign in with the browser authorization-code (PKCE) flow on "+ "http://localhost:1455/auth/callback instead of the default device-code flow; falls back "+ "to device code when that port is busy (config: auth.codex_login_flow)")auth_add.add_argument("--timeout", type=float, help="OAuth/network timeout in seconds")auth_add.add_argument("--insecure", action="store_true", help="Disable TLS verification for OAuth login")