Skip to content

The agent that grows with you

refactor(hermes_cli/web_routers): split codex login worker into phases, unify device-code session bootstrap + httpx off-loop calls in oauth

Tekniumd2d2668dcbb9
diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.py
index ac8905ca3c2..3157b8f2b9d 100644
--- a/hermes_cli/web_routers/oauth.py
+++ b/hermes_cli/web_routers/oauth.py
@@ -4,19 +4,20 @@ Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch o
``web_server`` stay there and are late-bound (cycle-safe).
"""
-import logging
import asyncio
+import logging
+import os
+import secrets
import sys
+import threading
import time
-from fastapi import APIRouter
+from typing import Any, Callable, Dict, Optional
+
+from fastapi import APIRouter, HTTPException, Request
+
from hermes_cli.web_deps import LateState, late
-from hermes_cli.web_routers._common import scoped_to_thread
-from fastapi import HTTPException, Request
from hermes_cli.web_models import OAuthSubmitBody
-from typing import Any, Callable, Dict, Optional
-import threading
-import os
-import secrets
+from hermes_cli.web_routers._common import scoped_to_thread
_log = logging.getLogger("hermes_cli.web_server")
router = APIRouter()
@@ -35,6 +36,12 @@ _oauth_sessions = LateState("_oauth_sessions")
_oauth_sessions_lock = LateState("_oauth_sessions_lock")
_OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG")
+_CODEX_ISSUER = "https://auth.openai.com"
+_JSON_HEADERS = {"Content-Type": "application/json"}
+_CODEX_EXPIRES_IN = 15 * 60 # OpenAI's effective limit
+_CANCELLED: Any = object()
+_OAUTH_SESSION_TTL_SECONDS = 15 * 60
+
def _http_response_error_detail(resp: Any) -> str:
"""Best-effort extraction of a short provider error detail."""
@@ -45,21 +52,13 @@ def _http_response_error_detail(resp: Any) -> str:
if isinstance(payload, dict):
error = payload.get("error")
if isinstance(error, dict):
- parts = [
- str(error.get(key, "")).strip()
- for key in ("message", "error_description", "code", "type")
- if str(error.get(key, "")).strip()
- ]
+ parts = [s for s in (str(error.get(k, "")).strip() for k in ("message", "error_description", "code", "type")) if s]
if parts:
return ": ".join(parts)
- if isinstance(error, str) and error.strip():
- return error.strip()
- for key in ("detail", "message", "error_description"):
- value = payload.get(key)
+ for value in (error, *(payload.get(k) for k in ("detail", "message", "error_description"))):
if isinstance(value, str) and value.strip():
return value.strip()
- text = str(getattr(resp, "text", "") or "").strip()
- return text[:500]
+ return str(getattr(resp, "text", "") or "").strip()[:500]
def _codex_device_code_start_error(resp: Any) -> str:
@@ -79,21 +78,14 @@ def _codex_device_code_start_error(resp: Any) -> str:
"OpenAI rejected the device-code login request. Please try Login "
"again from the dashboard after checking your OpenAI account settings."
)
- if detail:
- return f"{message} (HTTP {status}: {detail})"
- return f"{message} (HTTP {status})"
+ return f"{message} (HTTP {status}: {detail})" if detail else f"{message} (HTTP {status})"
-def _new_oauth_session(
- provider_id: str, flow: str, profile: Optional[str] = None,
-) -> tuple[str, Dict[str, Any]]:
+def _new_oauth_session(provider_id: str, flow: str, profile: Optional[str] = None) -> tuple[str, Dict[str, Any]]:
"""Create + register a new OAuth session, return (session_id, session_dict)."""
sid = secrets.token_urlsafe(16)
sess = {
- "session_id": sid,
- "provider": provider_id,
- "flow": flow,
- "profile": _oauth_profile_name(profile),
+ "session_id": sid, "provider": provider_id, "flow": flow, "profile": _oauth_profile_name(profile),
"created_at": time.time(),
"status": "pending", # pending | approved | denied | expired | error
"error_message": None,
@@ -103,120 +95,145 @@ def _new_oauth_session(
return sid, sess
-def _start_poller(target, sid: str) -> None:
- threading.Thread(target=target, args=(sid,), daemon=True, name=f"oauth-poll-{sid[:6]}").start()
+def _start_poller(target, sid: str, prefix: str = "oauth-poll") -> None:
+ threading.Thread(target=target, args=(sid,), daemon=True, name=f"{prefix}-{sid[:6]}").start()
-def _device_code_started(sid: str, user_code, verification_url, expires_in: int, poll_interval: int) -> Dict[str, Any]:
- """The /start response shape shared by every device-code flow."""
+def _device_session_started(
+ provider_id: str, profile: Optional[str], poller, fields: Dict[str, Any],
+ user_code, verification_url, expires_in: int, poll_interval: int,
+) -> Dict[str, Any]:
+ """Register a device-code session carrying ``fields``, start its poller, return the /start body."""
+ sid, sess = _new_oauth_session(provider_id, "device_code", profile=profile)
+ sess.update(fields)
+ _start_poller(poller, sid)
return {
"session_id": sid, "flow": "device_code", "user_code": user_code,
"verification_url": verification_url, "expires_in": expires_in, "poll_interval": poll_interval,
}
+async def _httpx_call(fn: Callable[[Any], Any], timeout: float = 15.0, **client_kwargs) -> Any:
+ """Run ``fn(client)`` off-loop with a short-lived JSON-accepting ``httpx.Client``."""
+ import httpx
+
+ def _call():
+ with httpx.Client(
+ timeout=httpx.Timeout(timeout), headers={"Accept": "application/json"}, **client_kwargs
+ ) as client:
+ return fn(client)
+
+ return await asyncio.get_running_loop().run_in_executor(None, _call)
+
+
+# OpenAI Codex device-code worker. Codex's own deviceauth/usercode (returns
+# device_auth_id) + deviceauth/token (polled until 200) endpoints yield
+# authorization_code + code_verifier exchanged at CODEX_OAUTH_TOKEN_URL. Replicated
+# here rather than calling ``_codex_device_code_login``, which prints/blocks/polls in
+# one function — the dashboard needs the user_code before polling completes.
+
+
+def _codex_cancelled(sess: Dict[str, Any], session_id: str, stage: str = "") -> bool:
+ if not sess.get("cancelled"):
+ return False
+ _log.info("oauth/device: openai-codex login cancelled%s (session=%s)", stage, session_id)
+ return True
+
+
+def _codex_request_user_code(httpx) -> Dict[str, Any]:
+ """Step 1: request device code; returns device_data with ``interval`` clamped (>= 3s)."""
+ from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID
+
+ with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ resp = client.post(
+ f"{_CODEX_ISSUER}/api/accounts/deviceauth/usercode", json={"client_id": CODEX_OAUTH_CLIENT_ID},
+ headers=_JSON_HEADERS,
+ )
+ if resp.status_code != 200:
+ raise RuntimeError(_codex_device_code_start_error(resp))
+ device_data = resp.json()
+ device_data["interval"] = max(3, int(device_data.get("interval", "5")))
+ if not device_data.get("user_code") or not device_data.get("device_auth_id"):
+ raise RuntimeError("device-code response missing user_code or device_auth_id")
+ return device_data
+
+
+def _codex_poll_authorization(httpx, sess: Dict[str, Any], session_id: str) -> Any:
+ """Step 2: poll until authorized. ``None`` = expired; ``_CANCELLED`` = user cancelled."""
+ deadline = time.monotonic() + sess["expires_in"]
+ payload = {"device_auth_id": sess["device_auth_id"], "user_code": sess["user_code"]}
+ with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ while time.monotonic() < deadline:
+ if _codex_cancelled(sess, session_id):
+ return _CANCELLED
+ time.sleep(sess["interval"])
+ if _codex_cancelled(sess, session_id):
+ return _CANCELLED
+ poll = client.post(f"{_CODEX_ISSUER}/api/accounts/deviceauth/token", json=payload, headers=_JSON_HEADERS)
+ if poll.status_code == 200:
+ return poll.json()
+ if poll.status_code in {403, 404}:
+ continue # user hasn't authorized yet
+ raise RuntimeError(f"deviceauth/token poll returned {poll.status_code}")
+ return None
+
+
+def _codex_exchange_tokens(httpx, code_resp: Dict[str, Any]) -> Dict[str, str]:
+ """Step 3: exchange authorization_code for tokens."""
+ from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL
+
+ authorization_code = code_resp.get("authorization_code", "")
+ code_verifier = code_resp.get("code_verifier", "")
+ if not authorization_code or not code_verifier:
+ raise RuntimeError("device-auth response missing authorization_code/code_verifier")
+ with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
+ token_resp = client.post(
+ CODEX_OAUTH_TOKEN_URL,
+ data={
+ "grant_type": "authorization_code", "code": authorization_code,
+ "redirect_uri": f"{_CODEX_ISSUER}/deviceauth/callback",
+ "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier,
+ },
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ )
+ if token_resp.status_code != 200:
+ raise RuntimeError(f"token exchange returned {token_resp.status_code}")
+ tokens = token_resp.json()
+ if not tokens.get("access_token"):
+ raise RuntimeError("token exchange did not return access_token")
+ return {"access_token": tokens.get("access_token", ""), "refresh_token": tokens.get("refresh_token", "")}
+
+
def _codex_full_login_worker(session_id: str) -> None:
- """Run the complete OpenAI Codex device-code flow.
-
- Codex has its own ``/api/accounts/deviceauth/usercode`` (returns
- ``device_auth_id``) and ``/api/accounts/deviceauth/token`` (polled until
- 200) endpoints; success yields ``authorization_code`` + ``code_verifier``
- exchanged at CODEX_OAUTH_TOKEN_URL. Replicated inline rather than calling
- ``_codex_device_code_login`` because that helper prints/blocks/polls in one
- function — the dashboard needs the user_code before polling completes.
- """
+ """Run the complete OpenAI Codex device-code flow (see comment above)."""
try:
import httpx
- from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL
- issuer = "https://auth.openai.com"
-
- # Step 1: request device code
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
- resp = client.post(
- f"{issuer}/api/accounts/deviceauth/usercode",
- json={"client_id": CODEX_OAUTH_CLIENT_ID},
- headers={"Content-Type": "application/json"},
- )
- if resp.status_code != 200:
- raise RuntimeError(_codex_device_code_start_error(resp))
- device_data = resp.json()
- user_code = device_data.get("user_code", "")
- device_auth_id = device_data.get("device_auth_id", "")
- poll_interval = max(3, int(device_data.get("interval", "5")))
- if not user_code or not device_auth_id:
- raise RuntimeError("device-code response missing user_code or device_auth_id")
+
+ device_data = _codex_request_user_code(httpx)
with _oauth_sessions_lock:
sess = _oauth_sessions.get(session_id)
if not sess:
return
- sess["user_code"] = user_code
- sess["verification_url"] = f"{issuer}/codex/device"
- sess["device_auth_id"] = device_auth_id
- sess["interval"] = poll_interval
- sess["expires_in"] = 15 * 60 # OpenAI's effective limit
- sess["expires_at"] = time.time() + sess["expires_in"]
+ sess.update(
+ user_code=device_data["user_code"], verification_url=f"{_CODEX_ISSUER}/codex/device",
+ device_auth_id=device_data["device_auth_id"], interval=device_data["interval"],
+ expires_in=_CODEX_EXPIRES_IN, expires_at=time.time() + _CODEX_EXPIRES_IN,
+ )
# Captured now (not re-derived after cancel pops the session) so a
# cancelled session can never fall back to the caller's current
# profile scope at save time.
session_profile = sess.get("profile")
- # Step 2: poll until authorized
- deadline = time.monotonic() + sess["expires_in"]
- code_resp = None
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
- while time.monotonic() < deadline:
- if sess.get("cancelled"):
- _log.info("oauth/device: openai-codex login cancelled (session=%s)", session_id)
- return
- time.sleep(poll_interval)
- if sess.get("cancelled"):
- _log.info("oauth/device: openai-codex login cancelled (session=%s)", session_id)
- return
- poll = client.post(
- f"{issuer}/api/accounts/deviceauth/token",
- json={"device_auth_id": device_auth_id, "user_code": user_code},
- headers={"Content-Type": "application/json"},
- )
- if poll.status_code == 200:
- code_resp = poll.json()
- break
- if poll.status_code in {403, 404}:
- continue # user hasn't authorized yet
- raise RuntimeError(f"deviceauth/token poll returned {poll.status_code}")
-
+ code_resp = _codex_poll_authorization(httpx, sess, session_id)
if code_resp is None:
with _oauth_sessions_lock:
sess["status"] = "expired"
sess["error_message"] = "Device code expired before approval"
return
-
- if sess.get("cancelled"):
- _log.info("oauth/device: openai-codex login cancelled before token exchange (session=%s)", session_id)
+ if code_resp is _CANCELLED or _codex_cancelled(sess, session_id, " before token exchange"):
return
- # Step 3: exchange authorization_code for tokens
- authorization_code = code_resp.get("authorization_code", "")
- code_verifier = code_resp.get("code_verifier", "")
- if not authorization_code or not code_verifier:
- raise RuntimeError("device-auth response missing authorization_code/code_verifier")
- with httpx.Client(timeout=httpx.Timeout(15.0)) as client:
- token_resp = client.post(
- CODEX_OAUTH_TOKEN_URL,
- data={
- "grant_type": "authorization_code", "code": authorization_code,
- "redirect_uri": f"{issuer}/deviceauth/callback",
- "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier,
- },
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- )
- if token_resp.status_code != 200:
- raise RuntimeError(f"token exchange returned {token_resp.status_code}")
- tokens = token_resp.json()
- access_token = tokens.get("access_token", "")
- refresh_token = tokens.get("refresh_token", "")
- if not access_token:
- raise RuntimeError("token exchange did not return access_token")
-
+ tokens = _codex_exchange_tokens(httpx, code_resp)
from hermes_cli.auth import _save_codex_tokens
# The cancellation check and the save are one atomic critical section
@@ -224,11 +241,10 @@ def _codex_full_login_worker(session_id: str) -> None:
# flip "cancelled" between the check and the save and tokens would be
# persisted after the user believed the login was aborted.
with _oauth_sessions_lock:
- if sess.get("cancelled"):
- _log.info("oauth/device: openai-codex login cancelled before token save (session=%s)", session_id)
+ if _codex_cancelled(sess, session_id, " before token save"):
return
with _profile_scope(session_profile):
- _save_codex_tokens({"access_token": access_token, "refresh_token": refresh_token})
+ _save_codex_tokens(tokens)
sess["status"] = "approved"
_log.info("oauth/device: openai-codex login completed (session=%s)", session_id)
except Exception as e:
@@ -285,12 +301,9 @@ _PROVIDER_STATUS: Dict[str, tuple[str, Callable[[dict], dict]]] = {
def _resolve_provider_status(provider_id: str, status_fn) -> Dict[str, Any]:
"""Dispatch to the right status helper for an OAuth provider entry."""
- if status_fn is not None:
- try:
- return status_fn()
- except Exception as e:
- return {"logged_in": False, "error": str(e)}
try:
+ if status_fn is not None:
+ return status_fn()
from hermes_cli import auth as hauth
entry = _PROVIDER_STATUS.get(provider_id)
if entry is not None:
@@ -316,46 +329,32 @@ def _resolve_provider_status(provider_id: str, status_fn) -> Dict[str, Any]:
async def _start_nous_device_code(profile: Optional[str]) -> Dict[str, Any]:
- from hermes_cli.auth import _request_device_code, PROVIDER_REGISTRY
- import httpx
+ from hermes_cli.auth import PROVIDER_REGISTRY, _request_device_code
pconfig = PROVIDER_REGISTRY["nous"]
portal_base_url = (
- os.getenv("HERMES_PORTAL_BASE_URL")
- or os.getenv("NOUS_PORTAL_BASE_URL")
- or pconfig.portal_base_url
+ os.getenv("HERMES_PORTAL_BASE_URL") or os.getenv("NOUS_PORTAL_BASE_URL") or pconfig.portal_base_url
).rstrip("/")
- client_id = pconfig.client_id
- scope = pconfig.scope
-
- def _do_nous_device_request():
- with httpx.Client(timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}) as client:
- return (
- _request_device_code(
- client=client, portal_base_url=portal_base_url, client_id=client_id, scope=scope
- ),
- scope,
- )
-
- device_data, effective_scope = await asyncio.get_running_loop().run_in_executor(None, _do_nous_device_request)
- sid, sess = _new_oauth_session("nous", "device_code", profile=profile)
- sess.update(
- device_code=str(device_data["device_code"]), interval=int(device_data["interval"]),
- expires_at=time.time() + int(device_data["expires_in"]), portal_base_url=portal_base_url,
- client_id=client_id, scope=effective_scope,
- )
- _start_poller(_nous_poller, sid)
- return _device_code_started(
- sid, str(device_data["user_code"]), str(device_data["verification_uri_complete"]),
+ device_data = await _httpx_call(lambda client: _request_device_code(
+ client=client, portal_base_url=portal_base_url, client_id=pconfig.client_id, scope=pconfig.scope,
+ ))
+ return _device_session_started(
+ "nous", profile, _nous_poller,
+ dict(
+ device_code=str(device_data["device_code"]), interval=int(device_data["interval"]),
+ expires_at=time.time() + int(device_data["expires_in"]), portal_base_url=portal_base_url,
+ client_id=pconfig.client_id, scope=pconfig.scope,
+ ),
+ str(device_data["user_code"]), str(device_data["verification_uri_complete"]),
int(device_data["expires_in"]), int(device_data["interval"]),
)
async def _start_codex_device_code(profile: Optional[str]) -> Dict[str, Any]:
# The full Codex helper polls inline, so it runs in a worker thread and
- # proxies user_code + verification_url back via the session dict.
+ # proxies user_code + verification_url back via the session dict; block
+ # briefly until the worker has populated the user_code, OR errored.
sid, _ = _new_oauth_session("openai-codex", "device_code", profile=profile)
- threading.Thread(target=_codex_full_login_worker, args=(sid,), daemon=True, name=f"oauth-codex-{sid[:6]}").start()
- # Block briefly until the worker has populated the user_code, OR error.
+ _start_poller(_codex_full_login_worker, sid, prefix="oauth-codex")
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
with _oauth_sessions_lock:
@@ -369,75 +368,59 @@ async def _start_codex_device_code(profile: Optional[str]) -> Dict[str, Any]:
raise HTTPException(status_code=500, detail=s.get("error_message") or "device-auth failed")
if not s.get("user_code"):
raise HTTPException(status_code=504, detail="device-auth timed out before returning a user code")
- return _device_code_started(
- sid, s["user_code"], s["verification_url"], int(s.get("expires_in") or 900), int(s.get("interval") or 5)
- )
+ return {
+ "session_id": sid, "flow": "device_code", "user_code": s["user_code"], "verification_url": s["verification_url"],
+ "expires_in": int(s.get("expires_in") or 900), "poll_interval": int(s.get("interval") or 5),
+ }
async def _start_minimax_device_code(profile: Optional[str]) -> Dict[str, Any]:
# Device-code flow with a PKCE extension: verifier + challenge from
# _minimax_pkce_pair bind the token exchange to the original session.
from hermes_cli.auth import (
- _minimax_pkce_pair, _minimax_request_user_code, MINIMAX_OAUTH_CLIENT_ID, MINIMAX_OAUTH_GLOBAL_BASE,
+ MINIMAX_OAUTH_CLIENT_ID, MINIMAX_OAUTH_GLOBAL_BASE, _minimax_pkce_pair, _minimax_request_user_code,
)
- import httpx
verifier, challenge, state = _minimax_pkce_pair()
portal_base_url = (os.getenv("MINIMAX_PORTAL_BASE_URL") or MINIMAX_OAUTH_GLOBAL_BASE).rstrip("/")
-
- def _do_minimax_request():
- with httpx.Client(
- timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}, follow_redirects=True
- ) as client:
- return _minimax_request_user_code(
- client=client, portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID,
- code_challenge=challenge, state=state,
- )
-
- device_data = await asyncio.get_event_loop().run_in_executor(None, _do_minimax_request)
- sid, sess = _new_oauth_session("minimax-oauth", "device_code", profile=profile)
+ device_data = await _httpx_call(lambda client: _minimax_request_user_code(
+ client=client, portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID,
+ code_challenge=challenge, state=state,
+ ), follow_redirects=True)
# MiniMax's `interval` is in milliseconds (defensive default 2000ms in _minimax_poll_token).
interval_raw = device_data.get("interval")
- sess.update(
- interval_ms=int(interval_raw) if interval_raw is not None else None,
- user_code=str(device_data["user_code"]), code_verifier=verifier, state=state,
- portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID, region="global",
- )
+ interval_ms = int(interval_raw) if interval_raw is not None else None
# `expired_in` is overloaded — a unix-ms timestamp OR seconds-from-now.
# Mirror the heuristic in _minimax_poll_token; keep the raw value for the
# poller and derive expires_at + UI-friendly expires_in seconds.
expired_in_raw = int(device_data["expired_in"])
- sess["expired_in_raw"] = expired_in_raw
if expired_in_raw > 1_000_000_000_000: # likely unix-ms
expires_at_ts = expired_in_raw / 1000.0
expires_in_seconds = max(0, int(expires_at_ts - time.time()))
else:
expires_at_ts = time.time() + expired_in_raw
expires_in_seconds = expired_in_raw
- sess["expires_at"] = expires_at_ts
- _start_poller(_minimax_poller, sid)
- return _device_code_started(
- sid, str(device_data["user_code"]), str(device_data["verification_uri"]), expires_in_seconds,
- max(2, (sess["interval_ms"] or 2000) // 1000),
+ return _device_session_started(
+ "minimax-oauth", profile, _minimax_poller,
+ dict(
+ interval_ms=interval_ms, user_code=str(device_data["user_code"]), code_verifier=verifier, state=state,
+ portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID, region="global",
+ expired_in_raw=expired_in_raw, expires_at=expires_at_ts,
+ ),
+ str(device_data["user_code"]), str(device_data["verification_uri"]), expires_in_seconds,
+ max(2, (interval_ms or 2000) // 1000),
)
async def _start_xai_device_code(profile: Optional[str]) -> Dict[str, Any]:
from hermes_cli.auth import _xai_oauth_request_device_code
- import httpx
-
- def _do_xai_device_request():
- with httpx.Client(timeout=httpx.Timeout(20.0), headers={"Accept": "application/json"}) as client:
- return _xai_oauth_request_device_code(client)
-
- device_data = await asyncio.get_running_loop().run_in_executor(None, _do_xai_device_request)
- sid, sess = _new_oauth_session("xai-oauth", "device_code", profile=profile)
- sess.update(
- device_code=str(device_data["device_code"]), interval=int(device_data["interval"]),
- expires_at=time.time() + int(device_data["expires_in"]),
- )
- _start_poller(_xai_device_poller, sid)
- return _device_code_started(
- sid, str(device_data["user_code"]),
+ device_data = await _httpx_call(_xai_oauth_request_device_code, timeout=20.0)
+ return _device_session_started(
+ "xai-oauth", profile, _xai_device_poller,
+ dict(
+ device_code=str(device_data["device_code"]), interval=int(device_data["interval"]),
+ expires_at=time.time() + int(device_data["expires_in"]),
+ ),
+ str(device_data["user_code"]),
str(device_data.get("verification_uri_complete") or device_data["verification_uri"]),
int(device_data["expires_in"]), int(device_data["interval"]),
)
@@ -449,15 +432,8 @@ _DEVICE_CODE_STARTERS = {
}
-async def _start_device_code_flow(
- provider_id: str, profile: Optional[str] = None,
-) -> Dict[str, Any]:
- """Initiate a device-code flow (Nous, OpenAI Codex, MiniMax, or xAI).
-
- Calls the provider's device-auth endpoint via the CLI helpers, then spawns
- a background poller. Returns the user-facing display fields (verification
- link + user code).
- """
+async def _start_device_code_flow(provider_id: str, profile: Optional[str] = None) -> Dict[str, Any]:
+ """Hit the provider's device-auth endpoint, spawn its poller, return the display fields."""
starter = _DEVICE_CODE_STARTERS.get(provider_id)
if starter is None:
raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow")
@@ -465,25 +441,19 @@ async def _start_device_code_flow(
def _oauth_provider_disconnect_command(provider: Dict[str, Any]) -> Optional[str]:
- """Shell command that clears an external provider's credentials.
-
- External providers store credentials outside Hermes, so the disconnect API
- refuses them (never silently delete files another CLI owns); instead the
- GUI gets a command to run in the embedded terminal, so the user sees
- exactly what executes. Claude Code has no scriptable logout, so we remove
- the credential the way logout does: the macOS Keychain entry
- (``Claude Code-credentials``) and/or ``~/.claude/.credentials.json`` — the
- two sources ``read_claude_code_credentials()`` consults. None for providers
- we can't safely clear (the GUI shows a manual hint).
+ """Shell command that clears an external provider's credentials, or None.
+
+ The disconnect API never silently deletes files another CLI owns; the GUI runs
+ this in its embedded terminal so the user sees exactly what executes. Claude Code
+ has no scriptable logout, so remove what logout would: the macOS Keychain entry
+ and/or ``~/.claude/.credentials.json`` (the two ``read_claude_code_credentials()`` sources).
"""
- if provider.get("flow") != "external":
+ if provider.get("flow") != "external" or provider.get("id") != "claude-code":
return None
- if provider.get("id") == "claude-code":
- rm_file = "rm -f ~/.claude/.credentials.json"
- if sys.platform == "darwin":
- return f'security delete-generic-password -s "Claude Code-credentials" 2>/dev/null; {rm_file}'
- return rm_file
- return None
+ rm_file = "rm -f ~/.claude/.credentials.json"
+ if sys.platform == "darwin":
+ return f'security delete-generic-password -s "Claude Code-credentials" 2>/dev/null; {rm_file}'
+ return rm_file
def _oauth_provider_disconnect_hint(provider: Dict[str, Any], status: Dict[str, Any]) -> Optional[str]:
@@ -503,24 +473,15 @@ def _oauth_provider_disconnect_hint(provider: Dict[str, Any], status: Dict[str,
def _build_oauth_catalog() -> list[Dict[str, Any]]:
- """Build the Accounts-tab provider list.
-
- Membership is the union of ``_OAUTH_PROVIDER_CATALOG`` (hand-tuned cards
- with bespoke flow / status_fn / cli_command, incl. the Anthropic PKCE card
- and the synthetic claude-code row) and every accounts-tab provider in the
- unified ``provider_catalog()``, so a plugin-added OAuth/external provider
- appears automatically. Explicit cards win on metadata and come first in
- curated order; catalog-only providers follow in ``hermes model`` order.
- """
+ """Accounts-tab provider list: ``_OAUTH_PROVIDER_CATALOG`` cards first (curated
+ order, win on metadata), then every other accounts-tab ``provider_catalog()`` entry
+ in ``hermes model`` order, so plugin-added OAuth/external providers appear automatically."""
rows: list[Dict[str, Any]] = []
seen: set[str] = set()
-
for entry in _OAUTH_PROVIDER_CATALOG:
- if entry["id"] in seen:
- continue
- seen.add(entry["id"])
- rows.append(dict(entry))
-
+ if entry["id"] not in seen:
+ seen.add(entry["id"])
+ rows.append(dict(entry))
try:
from hermes_cli.provider_catalog import provider_catalog
for d in provider_catalog():
@@ -529,25 +490,17 @@ def _build_oauth_catalog() -> list[Dict[str, Any]]:
seen.add(d.slug)
rows.append({
"id": d.slug, "name": d.label, "flow": "external",
- "cli_command": f"hermes auth add {d.slug}", "docs_url": d.signup_url or "",
- "status_fn": None,
+ "cli_command": f"hermes auth add {d.slug}", "docs_url": d.signup_url or "", "status_fn": None,
})
except Exception:
pass
-
return rows
@router.get("/api/providers/oauth")
async def list_oauth_providers(profile: Optional[str] = None):
- """Enumerate every OAuth-capable LLM provider with current status.
-
- Per provider: id (used in the DELETE path), name, flow
- ("device_code" | "external"), cli_command (manual fallback),
- disconnect_command (shell command for external providers, else null),
- docs_url, and status {logged_in, source slug, source_label, token_preview
- (last N chars, never the full token), expires_at, has_refresh_token}.
- """
+ """Every OAuth-capable provider with current status (token_preview is the last
+ N chars, never the full token; disconnect_command only for external providers)."""
def _run():
providers = []
for p in _build_oauth_catalog():
@@ -568,16 +521,30 @@ async def list_oauth_providers(profile: Optional[str] = None):
def _reject_if_not_disconnectable(provider: Dict[str, Any], status: Dict[str, Any]) -> None:
disconnect_hint = _oauth_provider_disconnect_hint(provider, status)
if disconnect_hint:
- raise HTTPException(
- status_code=400,
- detail=f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}",
- )
+ raise HTTPException(400, f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}")
+
+
+def _clear_anthropic_auth() -> bool:
+ """Clear only the Hermes-managed PKCE file and auth-store entry (never ~/.claude/*)."""
+ cleared = False
+ try:
+ from agent.anthropic_adapter import _get_hermes_oauth_file
+ oauth_file = _get_hermes_oauth_file()
+ if oauth_file.exists():
+ oauth_file.unlink()
+ cleared = True
+ except Exception:
+ pass
+ try:
+ from hermes_cli.auth import clear_provider_auth
+ cleared = clear_provider_auth("anthropic") or cleared
+ except Exception:
+ pass
+ return cleared
@router.delete("/api/providers/oauth/{provider_id}")
-async def disconnect_oauth_provider(
- provider_id: str, request: Request, profile: Optional[str] = None,
-):
+async def disconnect_oauth_provider(provider_id: str, request: Request, profile: Optional[str] = None):
"""Disconnect an OAuth provider. Token-protected (matches /env/reveal)."""
_require_token(request)
@@ -585,38 +552,15 @@ async def disconnect_oauth_provider(
catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}
provider = catalog_by_id.get(provider_id)
if provider is None:
- raise HTTPException(
- status_code=400,
- detail=f"Unknown provider: {provider_id}. "
- f"Available: {', '.join(sorted(catalog_by_id))}",
- )
-
+ raise HTTPException(400, f"Unknown provider: {provider_id}. Available: {', '.join(sorted(catalog_by_id))}")
+ # Flow-only rejection first so external providers never reach status resolution.
_reject_if_not_disconnectable(provider, {})
- _reject_if_not_disconnectable(
- provider, _resolve_provider_status(provider_id, provider.get("status_fn"))
- )
+ _reject_if_not_disconnectable(provider, _resolve_provider_status(provider_id, provider.get("status_fn")))
- # Anthropic clears only the Hermes-managed PKCE file and auth-store
- # entry; the external claude-code row was rejected above so we never
- # pretend to remove ~/.claude/* credentials owned by the CLI.
if provider_id == "anthropic":
- cleared = False
- try:
- from agent.anthropic_adapter import _get_hermes_oauth_file
- oauth_file = _get_hermes_oauth_file()
- if oauth_file.exists():
- oauth_file.unlink()
- cleared = True
- except Exception:
- pass
- try:
- from hermes_cli.auth import clear_provider_auth
- cleared = clear_provider_auth("anthropic") or cleared
- except Exception:
- pass
+ cleared = _clear_anthropic_auth()
_log.info("oauth/disconnect: %s", provider_id)
return {"ok": bool(cleared), "provider": provider_id}
-
try:
from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache
cleared = clear_provider_auth(provider_id)
@@ -631,42 +575,31 @@ async def disconnect_oauth_provider(
return await scoped_to_thread(profile, _run)
-# In-browser device-code flows (Nous, OpenAI Codex, MiniMax, xAI):
-# 1. POST /api/providers/oauth/{provider}/start hits the provider's
-# device-auth endpoint, spawns a poller thread that polls the token
-# endpoint every `interval` seconds, and returns
-# {session_id, flow, user_code, verification_url, expires_in, poll_interval}.
-# 2. UI opens verification_url and shows user_code, then polls
-# GET /api/providers/oauth/{provider}/poll/{session_id} until status != "pending".
-# 3. On "approved" the poller has already saved creds; UI refreshes the list.
-# Anthropic has NO dashboard PKCE flow: an unattended endpoint minting Claude
-# subscription tokens outside Anthropic's own client violates its OAuth usage
-# policy; that card is flow == "external" (`hermes auth add anthropic`).
-# Sessions are in-memory (single-process) and expire after 15 minutes; /start
-# GCs expired ones so the dict is bounded.
-
-_OAUTH_SESSION_TTL_SECONDS = 15 * 60
+# In-browser device-code sessions: /start spawns a poller thread and returns the
+# display fields; the UI polls .../poll/{session_id} until status != "pending" (on
+# "approved" the poller has already saved creds). Anthropic has NO dashboard PKCE
+# flow — an unattended endpoint minting Claude subscription tokens outside
+# Anthropic's own client violates its OAuth usage policy; that card is "external".
+# Sessions are in-memory (single-process), expire after 15 min, GC'd on /start.
def _gc_oauth_sessions() -> None:
- """Drop expired sessions. Called opportunistically on /start."""
cutoff = time.time() - _OAUTH_SESSION_TTL_SECONDS
with _oauth_sessions_lock:
- stale = [sid for sid, sess in _oauth_sessions.items() if sess["created_at"] < cutoff]
- for sid in stale:
+ for sid in [sid for sid, sess in _oauth_sessions.items() if sess["created_at"] < cutoff]:
_oauth_sessions.pop(sid, None)
-def _validate_oauth_profile(profile: Optional[str]) -> None:
+def _validate_oauth_profile(profile: Optional[str]) -> str:
+ """Validate the requested profile (404 via ``_resolve_profile_dir``) and return its name."""
profile_name = _oauth_profile_name(profile)
if profile_name:
_resolve_profile_dir(profile_name)
+ return profile_name
@router.post("/api/providers/oauth/{provider_id}/start")
-async def start_oauth_login(
- provider_id: str, request: Request, profile: Optional[str] = None,
-):
+async def start_oauth_login(provider_id: str, request: Request, profile: Optional[str] = None):
"""Initiate an OAuth login flow. Token-protected."""
_require_token(request)
_gc_oauth_sessions()
@@ -675,10 +608,7 @@ async def start_oauth_login(
if catalog_entry is None:
raise HTTPException(status_code=400, detail=f"Unknown provider {provider_id}")
if catalog_entry["flow"] == "external":
- raise HTTPException(
- status_code=400,
- detail=f"{provider_id} uses an external CLI; run `{catalog_entry['cli_command']}` manually",
- )
+ raise HTTPException(400, f"{provider_id} uses an external CLI; run `{catalog_entry['cli_command']}` manually")
try:
if catalog_entry["flow"] == "device_code":
return await _start_device_code_flow(provider_id, profile=profile)
@@ -700,13 +630,10 @@ async def submit_oauth_code(
@router.get("/api/providers/oauth/{provider_id}/poll/{session_id}")
-async def poll_oauth_session(
- provider_id: str, session_id: str, profile: Optional[str] = None,
-):
+async def poll_oauth_session(provider_id: str, session_id: str, profile: Optional[str] = None):
"""Poll a session's status (no auth — read-only state). One endpoint serves
every device-code flow: all report progress via the worker-updated ``status``."""
- _validate_oauth_profile(profile)
- requested_profile = _oauth_profile_name(profile)
+ requested_profile = _validate_oauth_profile(profile)
with _oauth_sessions_lock:
sess = _oauth_sessions.get(session_id)
if not sess:
@@ -722,9 +649,7 @@ async def poll_oauth_session(
@router.delete("/api/providers/oauth/sessions/{session_id}")
-async def cancel_oauth_session(
- session_id: str, request: Request, profile: Optional[str] = None,
-):
+async def cancel_oauth_session(session_id: str, request: Request, profile: Optional[str] = None):
"""Cancel a pending OAuth session. Token-protected.
Marks the session dict ``cancelled`` before popping it so a background
@@ -733,8 +658,7 @@ async def cancel_oauth_session(
believed it was aborted.
"""
_require_token(request)
- _validate_oauth_profile(profile)
- requested_profile = _oauth_profile_name(profile)
+ requested_profile = _validate_oauth_profile(profile)
with _oauth_sessions_lock:
sess = _oauth_sessions.get(session_id)
if sess is not None: