oauth.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. """OAuth provider dashboard routes: catalog/status, disconnect, and in-browser device-code login flows.
  2. Extracted from ``hermes_cli.web_server``; helpers/state that tests monkeypatch on
  3. ``web_server`` stay there and are late-bound (cycle-safe).
  4. """
  5. import asyncio
  6. import contextlib
  7. import contextvars
  8. import logging
  9. import os
  10. import secrets
  11. import sys
  12. import threading
  13. import time
  14. from datetime import datetime, timezone, UTC
  15. from typing import Any, Callable, Dict, Optional
  16. from fastapi import APIRouter, HTTPException, Request
  17. from hermes_cli.auth_constants import _codex_err
  18. from hermes_cli.web_deps import LateState, late
  19. from hermes_cli.web_server_oauth import (
  20. _external_process_cli_command, _oauth_profile_name, _oauth_sessions, _oauth_sessions_lock, _truncate_token,
  21. )
  22. from hermes_cli.web_models import OAuthSubmitBody
  23. from hermes_cli.web_routers._common import config_scoped_to_thread, scoped_to_thread
  24. _log = logging.getLogger("hermes_cli.web_server")
  25. router = APIRouter()
  26. # Late-bound so a test's monkeypatch on the owning module wins at call time.
  27. _profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
  28. _require_token = late("_require_token")
  29. _resolve_profile_dir = late("_resolve_profile_dir", "hermes_cli.web_server_profiles")
  30. _OAUTH_PROVIDER_CATALOG = LateState("_OAUTH_PROVIDER_CATALOG", "hermes_cli.web_server_oauth")
  31. # Pollers are late-bound: they run on a background thread AFTER the route returns, so a
  32. # test's monkeypatch on web_server_oauth must win at spawn time, not router-import time.
  33. # A direct import here made those mocks no-ops — the real poller then hit the network
  34. # from the leaked thread and segfaulted a later test's collection (CI flake, 2026-09-09).
  35. _nous_sign_in_poller = late("_nous_sign_in_poller", "hermes_cli.web_server_oauth")
  36. _minimax_poller = late("_minimax_poller", "hermes_cli.web_server_oauth")
  37. _xai_device_poller = late("_xai_device_poller", "hermes_cli.web_server_oauth")
  38. _profile_device_poller = late("_profile_device_poller", "hermes_cli.web_server_oauth")
  39. _CODEX_ISSUER = "https://auth.openai.com"
  40. _JSON_HEADERS = {"Content-Type": "application/json"}
  41. _CODEX_EXPIRES_IN = 15 * 60 # OpenAI's effective limit
  42. _CANCELLED: Any = object()
  43. _OAUTH_SESSION_TTL_SECONDS = 15 * 60
  44. def _http_response_error_detail(resp: Any) -> str:
  45. """Best-effort extraction of a short provider error detail."""
  46. try:
  47. payload = resp.json()
  48. except Exception:
  49. payload = None
  50. if isinstance(payload, dict):
  51. error = payload.get("error")
  52. if isinstance(error, dict):
  53. parts = [s for s in (str(error.get(k, "")).strip() for k in ("message", "error_description", "code", "type")) if s]
  54. if parts:
  55. return ": ".join(parts)
  56. for value in (error, *(payload.get(k) for k in ("detail", "message", "error_description"))):
  57. if isinstance(value, str) and value.strip():
  58. return value.strip()
  59. return str(getattr(resp, "text", "") or "").strip()[:500]
  60. def _codex_device_code_start_error(resp: Any) -> str:
  61. """Dashboard-facing OpenAI Codex device-code start failure."""
  62. status = getattr(resp, "status_code", "unknown")
  63. detail = _http_response_error_detail(resp)
  64. lower = detail.lower()
  65. if "device" in lower and ("authori" in lower or "enable" in lower):
  66. message = (
  67. "OpenAI rejected the device-code login request. Your OpenAI "
  68. "account may need device-code authorization enabled before Hermes "
  69. "can start this dashboard login. Enable device-code authorization "
  70. "in OpenAI, then return here and click Login again."
  71. )
  72. else:
  73. message = (
  74. "OpenAI rejected the device-code login request. Please try Login "
  75. "again from the dashboard after checking your OpenAI account settings."
  76. )
  77. return f"{message} (HTTP {status}: {detail})" if detail else f"{message} (HTTP {status})"
  78. def _new_oauth_session(provider_id: str, flow: str, profile: Optional[str] = None) -> tuple[str, dict[str, Any]]:
  79. """Create + register a new OAuth session, return (session_id, session_dict)."""
  80. sid = secrets.token_urlsafe(16)
  81. sess = {
  82. "session_id": sid, "provider": provider_id, "flow": flow, "profile": _oauth_profile_name(profile),
  83. "created_at": time.time(),
  84. "status": "pending", # pending | approved | denied | expired | error
  85. "error_message": None,
  86. }
  87. with _oauth_sessions_lock:
  88. _oauth_sessions[sid] = sess
  89. return sid, sess
  90. def _drop_oauth_session(sid: str) -> None:
  91. """Forget a session that never got started, so the dashboard does not poll a corpse forever."""
  92. with _oauth_sessions_lock:
  93. _oauth_sessions.pop(sid, None)
  94. def _start_poller(target, sid: str, prefix: str = "oauth-poll") -> None:
  95. with _oauth_sessions_lock:
  96. sess = _oauth_sessions.get(sid)
  97. def run() -> None:
  98. try:
  99. target(sid)
  100. finally: # the session's status is final once its poller returns
  101. from hermes_cli.observability.shared_metrics_setup import settle_oauth_setup
  102. settle_oauth_setup(sess)
  103. # The poller saves credentials under ``_profile_scope(sess['profile'])``; an implicit
  104. # selector (None) must resolve in the REQUEST's home (a secondary-profile native ticket's
  105. # override), so the thread runs in a copy of the starting request's context.
  106. context = contextvars.copy_context()
  107. threading.Thread(target=context.run, args=(run,), daemon=True, name=f"{prefix}-{sid[:6]}").start()
  108. def _track_oauth_setup(flow, session_id: str) -> None:
  109. """Hand the setup flow to its session; settle it now if the poller already ended."""
  110. from hermes_cli.observability.shared_metrics_setup import (
  111. attach_oauth_setup, finish_provider_setup, settle_oauth_setup,
  112. )
  113. with _oauth_sessions_lock:
  114. sess = _oauth_sessions.get(session_id)
  115. if sess is None: # cancelled before the start response even returned
  116. finish_provider_setup(flow, "abandoned")
  117. return
  118. attach_oauth_setup(sess, flow)
  119. settle_oauth_setup(sess)
  120. def _device_session_started(
  121. provider_id: str, profile: Optional[str], poller, fields: dict[str, Any],
  122. user_code, verification_url, expires_in: int, poll_interval: int,
  123. ) -> dict[str, Any]:
  124. """Register a device-code session carrying ``fields``, start its poller, return the /start body."""
  125. sid, sess = _new_oauth_session(provider_id, "device_code", profile=profile)
  126. sess.update(fields)
  127. _start_poller(poller, sid)
  128. return {
  129. "session_id": sid, "flow": "device_code", "user_code": user_code,
  130. "verification_url": verification_url, "expires_in": expires_in, "poll_interval": poll_interval,
  131. }
  132. async def _httpx_call(fn: Callable[[Any], Any], timeout: float = 15.0, **client_kwargs) -> Any:
  133. """Run ``fn(client)`` off-loop with a short-lived JSON-accepting ``httpx.Client``."""
  134. import httpx
  135. def _call():
  136. with httpx.Client(
  137. timeout=httpx.Timeout(timeout), headers={"Accept": "application/json"}, **client_kwargs
  138. ) as client:
  139. return fn(client)
  140. return await asyncio.to_thread(_call)
  141. # OpenAI Codex device-code worker. Codex's own deviceauth/usercode (returns
  142. # device_auth_id) + deviceauth/token (polled until 200) endpoints yield
  143. # authorization_code + code_verifier exchanged at CODEX_OAUTH_TOKEN_URL. Replicated
  144. # here rather than calling ``_codex_device_code_login``, which prints/blocks/polls in
  145. # one function — the dashboard needs the user_code before polling completes.
  146. def _codex_cancelled(sess: dict[str, Any], session_id: str, stage: str = "") -> bool:
  147. if not sess.get("cancelled"):
  148. return False
  149. _log.info("oauth/device: openai-codex login cancelled%s (session=%s)", stage, session_id)
  150. return True
  151. def _codex_client(httpx) -> Any:
  152. """15s ``httpx.Client`` for the device-login flow with the CLI flow's 1 MiB auth-body cap (#55253).
  153. The helpers take the ``httpx`` module as a parameter (tests inject a scripted one), so the
  154. dashboard builds its own client here and only shares the response hook, not the client factory.
  155. """
  156. from hermes_cli.auth_codex import _cap_codex_response_body
  157. return httpx.Client(timeout=httpx.Timeout(15.0), event_hooks={"response": [_cap_codex_response_body]})
  158. def _codex_post(httpx, url: str, **kwargs: Any) -> Any:
  159. """One 15s POST for the device-login flow, mirroring ``auth_codex._codex_login_post``.
  160. A transient transport blip (a dropped connection mid-flow) is retried twice with a small
  161. linear backoff before propagating: losing the token exchange to a single SSL EOF wastes a
  162. device-code approval the user already completed in the browser (#114610).
  163. """
  164. from hermes_cli.auth_codex import _is_transient_transport_error
  165. attempt, attempts = 1, 3
  166. while True:
  167. try:
  168. with _codex_client(httpx) as client:
  169. return client.post(url, **kwargs)
  170. except Exception as exc:
  171. if attempt == attempts or not _is_transient_transport_error(exc):
  172. raise
  173. time.sleep(attempt)
  174. attempt += 1
  175. def _codex_http_error(status: int) -> Callable[[str], Exception]:
  176. """Exception type for a non-200 Codex reply: 401/403 is OpenAI refusing this account/client;
  177. 408/429/5xx is the service down or shedding load (a network-class failure)."""
  178. if status in {401, 403}:
  179. return _codex_err
  180. return ConnectionError if status in {408, 429} or status >= 500 else RuntimeError
  181. def _codex_request_user_code(httpx) -> dict[str, Any]:
  182. """Step 1: request device code; returns device_data with ``interval`` clamped (>= 3s)."""
  183. from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID
  184. resp = _codex_post(
  185. httpx, f"{_CODEX_ISSUER}/api/accounts/deviceauth/usercode", json={"client_id": CODEX_OAUTH_CLIENT_ID},
  186. headers=_JSON_HEADERS,
  187. )
  188. if resp.status_code != 200:
  189. raise _codex_http_error(resp.status_code)(_codex_device_code_start_error(resp))
  190. device_data = resp.json()
  191. device_data["interval"] = max(3, int(device_data.get("interval", "5")))
  192. if not device_data.get("user_code") or not device_data.get("device_auth_id"):
  193. raise RuntimeError("device-code response missing user_code or device_auth_id")
  194. return device_data
  195. def _codex_poll_authorization(httpx, sess: dict[str, Any], session_id: str) -> Any:
  196. """Step 2: poll until authorized. ``None`` = expired; ``_CANCELLED`` = user cancelled."""
  197. from hermes_cli.auth_codex import _is_transient_transport_error
  198. deadline = time.monotonic() + sess["expires_in"]
  199. payload = {"device_auth_id": sess["device_auth_id"], "user_code": sess["user_code"]}
  200. max_consecutive_blips = 6 # same cap as the CLI poll loop: survives drops, fails fast on a dead network
  201. consecutive_blips = 0
  202. with _codex_client(httpx) as client:
  203. while time.monotonic() < deadline:
  204. if _codex_cancelled(sess, session_id):
  205. return _CANCELLED
  206. time.sleep(sess["interval"])
  207. if _codex_cancelled(sess, session_id):
  208. return _CANCELLED
  209. try:
  210. poll = client.post(
  211. f"{_CODEX_ISSUER}/api/accounts/deviceauth/token", json=payload, headers=_JSON_HEADERS)
  212. except Exception as exc:
  213. if not _is_transient_transport_error(exc):
  214. raise
  215. consecutive_blips += 1
  216. if consecutive_blips >= max_consecutive_blips:
  217. raise RuntimeError(
  218. f"deviceauth/token poll failed after {consecutive_blips} consecutive"
  219. f" transport errors: {exc}") from exc
  220. _log.info("oauth/device: openai-codex poll transport blip, retrying (session=%s)", session_id)
  221. continue
  222. consecutive_blips = 0
  223. if poll.status_code == 200:
  224. return poll.json()
  225. if poll.status_code in {403, 404}:
  226. continue # user hasn't authorized yet
  227. raise RuntimeError(f"deviceauth/token poll returned {poll.status_code}")
  228. return None
  229. def _codex_exchange_tokens(httpx, code_resp: dict[str, Any]) -> dict[str, str]:
  230. """Step 3: exchange authorization_code for tokens."""
  231. from hermes_cli.auth import CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL
  232. authorization_code = code_resp.get("authorization_code", "")
  233. code_verifier = code_resp.get("code_verifier", "")
  234. if not authorization_code or not code_verifier:
  235. raise RuntimeError("device-auth response missing authorization_code/code_verifier")
  236. token_resp = _codex_post(
  237. httpx, CODEX_OAUTH_TOKEN_URL,
  238. data={
  239. "grant_type": "authorization_code", "code": authorization_code,
  240. "redirect_uri": f"{_CODEX_ISSUER}/deviceauth/callback",
  241. "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier,
  242. },
  243. headers={"Content-Type": "application/x-www-form-urlencoded"},
  244. )
  245. if token_resp.status_code != 200:
  246. raise _codex_http_error(token_resp.status_code)(f"token exchange returned {token_resp.status_code}")
  247. tokens = token_resp.json()
  248. if not tokens.get("access_token"):
  249. raise RuntimeError("token exchange did not return access_token")
  250. return {"access_token": tokens.get("access_token", ""), "refresh_token": tokens.get("refresh_token", "")}
  251. def _codex_full_login_worker(session_id: str) -> None:
  252. """Run the complete OpenAI Codex device-code flow (see comment above)."""
  253. try:
  254. import httpx
  255. device_data = _codex_request_user_code(httpx)
  256. with _oauth_sessions_lock:
  257. sess = _oauth_sessions.get(session_id)
  258. if not sess:
  259. return
  260. sess.update(
  261. user_code=device_data["user_code"], verification_url=f"{_CODEX_ISSUER}/codex/device",
  262. device_auth_id=device_data["device_auth_id"], interval=device_data["interval"],
  263. expires_in=_CODEX_EXPIRES_IN, expires_at=time.time() + _CODEX_EXPIRES_IN,
  264. )
  265. # Captured now (not re-derived after cancel pops the session) so a
  266. # cancelled session can never fall back to the caller's current
  267. # profile scope at save time.
  268. session_profile = sess.get("profile")
  269. code_resp = _codex_poll_authorization(httpx, sess, session_id)
  270. if code_resp is None:
  271. with _oauth_sessions_lock:
  272. sess["status"] = "expired"
  273. sess["error_message"] = "Device code expired before approval"
  274. return
  275. if code_resp is _CANCELLED or _codex_cancelled(sess, session_id, " before token exchange"):
  276. return
  277. tokens = _codex_exchange_tokens(httpx, code_resp)
  278. from hermes_cli.auth import _save_codex_tokens
  279. # The cancellation check and the save are one atomic critical section
  280. # under the lock cancel_oauth_session() uses; otherwise DELETE could
  281. # flip "cancelled" between the check and the save and tokens would be
  282. # persisted after the user believed the login was aborted. The profile scope
  283. # (which holds _SKILLS_PROFILE_LOCK) is entered first, as in every other saver:
  284. # the reverse order deadlocks against a Nous/xAI/MiniMax save finishing at once.
  285. with _profile_scope(session_profile), _oauth_sessions_lock:
  286. if _codex_cancelled(sess, session_id, " before token save"):
  287. return
  288. _save_codex_tokens(tokens)
  289. sess["status"] = "approved"
  290. _log.info("oauth/device: openai-codex login completed (session=%s)", session_id)
  291. except Exception as e:
  292. from hermes_cli.observability.shared_metrics_setup import note_oauth_failure
  293. _log.warning("codex device-code worker failed (session=%s): %s", session_id, e)
  294. with _oauth_sessions_lock:
  295. s = _oauth_sessions.get(session_id)
  296. note_oauth_failure(s, e)
  297. if s:
  298. s["status"] = "error"
  299. s["error_message"] = str(e)
  300. _OMIT: Any = object()
  301. def _status_card(
  302. raw: dict, source, source_label, token_preview, expires_at, has_refresh_token, last_refresh=_OMIT
  303. ) -> dict[str, Any]:
  304. card = {
  305. "logged_in": bool(raw.get("logged_in")), "source": source, "source_label": source_label,
  306. "token_preview": token_preview, "expires_at": expires_at, "has_refresh_token": has_refresh_token,
  307. }
  308. if last_refresh is not _OMIT:
  309. card["last_refresh"] = last_refresh
  310. return card
  311. def _epoch_ms_to_iso(value: Any) -> Optional[str]:
  312. """Epoch ms (Qwen CLI ``expiry_date``) -> the aware ISO string the other cards send."""
  313. return datetime.fromtimestamp(value / 1000, tz=UTC).isoformat() if value else None
  314. # Hand-written status cards per provider id: (hauth getter name, raw -> card).
  315. # Providers absent here fall through to the slug-driven ``get_auth_status``.
  316. # nous: refresh-free local snapshot so listing providers never performs an OAuth
  317. # refresh. xai: source_label is a human-readable origin (auth-store path /
  318. # credential source), not the internal auth_mode string ("oauth_pkce").
  319. _PROVIDER_STATUS: dict[str, tuple[str, Callable[[dict], dict]]] = {
  320. "nous": ("get_nous_auth_status_local", lambda r: {**_status_card(
  321. r, "nous_portal", r.get("portal_base_url") or "Nous Portal",
  322. _truncate_token(r.get("access_token")), r.get("access_expires_at"), bool(r.get("has_refresh_token")),
  323. ), "free_tier": bool(r.get("free_tier")), "account_tier": r.get("account_tier")}),
  324. "openai-codex": ("get_codex_auth_status", lambda r: _status_card(
  325. r, r.get("source") or "openai_codex", r.get("auth_mode") or "OpenAI Codex",
  326. _truncate_token(r.get("api_key")), None, False, r.get("last_refresh"),
  327. )),
  328. "qwen-oauth": ("get_qwen_auth_status", lambda r: _status_card(
  329. r, "qwen_cli", r.get("auth_file") or "Qwen CLI",
  330. _truncate_token(r.get("api_key")), _epoch_ms_to_iso(r.get("expires_at_ms")), bool(r.get("has_refresh_token")),
  331. )),
  332. "minimax-oauth": ("get_minimax_oauth_auth_status", lambda r: _status_card(
  333. r, "minimax_oauth", f"MiniMax ({r.get('region', 'global')})", None, r.get("expires_at"), True,
  334. )),
  335. "xai-oauth": ("get_xai_oauth_auth_status", lambda r: _status_card(
  336. r, r.get("source") or "xai_oauth", r.get("auth_store") or r.get("source") or "xAI Grok OAuth",
  337. _truncate_token(r.get("api_key")), None, True, r.get("last_refresh"),
  338. )),
  339. }
  340. def _resolve_provider_status(provider_id: str, status_fn) -> dict[str, Any]:
  341. """Dispatch to the right status helper for an OAuth provider entry."""
  342. try:
  343. if status_fn is not None:
  344. return status_fn()
  345. from hermes_cli import auth as hauth
  346. entry = _PROVIDER_STATUS.get(provider_id)
  347. if entry is not None:
  348. getter, shape = entry
  349. return shape(getattr(hauth, getter)())
  350. # Catalog-derived providers (status_fn=None, no hand-written card) still
  351. # reflect real login state via the canonical slug-driven dispatcher, so
  352. # a new OAuth/account provider plugin never renders permanently logged-out.
  353. raw = hauth.get_auth_status(provider_id)
  354. if isinstance(raw, dict) and "logged_in" in raw:
  355. return _status_card(
  356. raw,
  357. raw.get("source") or raw.get("provider") or provider_id,
  358. raw.get("source_label") or raw.get("auth_store") or raw.get("auth_store_path")
  359. or raw.get("base_url") or raw.get("name") or "",
  360. _truncate_token(raw.get("access_token") or raw.get("api_key")),
  361. raw.get("expires_at") or raw.get("access_expires_at"),
  362. bool(raw.get("has_refresh_token")),
  363. )
  364. except Exception as e:
  365. return {"logged_in": False, "error": str(e)}
  366. return {"logged_in": False}
  367. async def _start_nous_device_code(profile: Optional[str]) -> dict[str, Any]:
  368. """Start a Nous sign-in: the shared ``anon_auth.run_sign_in`` flow, the plain device-code login.
  369. This route creates the generator, pulls its first state (the device page link and code) and
  370. hands that to the UI, then the poller drains the rest. A free tier the account replaces hands
  371. its apps over after the save, inside the flow."""
  372. from hermes_cli import anon_auth
  373. from hermes_cli.auth import PROVIDER_REGISTRY
  374. from hermes_cli.web_server_profiles import _config_profile_scope
  375. pconfig = PROVIDER_REGISTRY["nous"]
  376. portal_base_url = (
  377. os.getenv("HERMES_PORTAL_BASE_URL") or os.getenv("NOUS_PORTAL_BASE_URL") or pconfig.portal_base_url
  378. ).rstrip("/")
  379. # The session is registered BEFORE the generator exists, so a cancel landing in the start
  380. # window is already visible to the flow's own cancel check and persist guard.
  381. sid, sess = _new_oauth_session("nous", "device_code", profile=profile)
  382. def _cancelled() -> bool:
  383. with _oauth_sessions_lock:
  384. return bool(sess.get("cancelled"))
  385. @contextlib.contextmanager
  386. def _persist_guard():
  387. # The desktop's guarantee: the final cancellation check and the save share one lock.
  388. with _oauth_sessions_lock:
  389. if sess.get("cancelled"):
  390. sess["status"] = "cancelled"
  391. yield False
  392. else:
  393. yield True
  394. gen = anon_auth.run_sign_in(
  395. timeout_seconds=15.0,
  396. cancelled=_cancelled,
  397. # The desktop also connects another account over a signed-in one.
  398. replace_account=True,
  399. persist_guard=_persist_guard,
  400. # Config + auth store only, so the light contextvar scope -- never the skills-module one,
  401. # whose process-global lock would be held across the whole wait.
  402. scope=lambda: _config_profile_scope(_oauth_profile_name(profile)),
  403. )
  404. try:
  405. first = await _httpx_call(lambda _client: next(gen))
  406. except Exception:
  407. with contextlib.suppress(Exception):
  408. gen.close()
  409. _drop_oauth_session(sid)
  410. raise
  411. if getattr(first, "kind", "") != "code": # the store was unreadable or the code request failed
  412. with contextlib.suppress(Exception):
  413. gen.close()
  414. _drop_oauth_session(sid)
  415. raise HTTPException(400, detail=first.copy_terminal)
  416. with _oauth_sessions_lock:
  417. # ``device_code`` stays present because other routes read it; the generator owns the real one.
  418. sess.update(dict(
  419. portal_base_url=portal_base_url, client_id=pconfig.client_id, scope=pconfig.scope,
  420. device_code="", interval=first.interval,
  421. expires_at=time.time() + first.expires_in, _sign_in=gen))
  422. _start_poller(_nous_sign_in_poller, sid) # last: nothing observes `sess` before it is complete
  423. return {
  424. "session_id": sid, "flow": "device_code", "user_code": first.code,
  425. "verification_url": first.link, "expires_in": first.expires_in,
  426. "poll_interval": first.interval,
  427. }
  428. async def _start_codex_device_code(profile: Optional[str]) -> dict[str, Any]:
  429. # The full Codex helper polls inline, so it runs in a worker thread and
  430. # proxies user_code + verification_url back via the session dict; block
  431. # briefly until the worker has populated the user_code, OR errored.
  432. sid, _ = _new_oauth_session("openai-codex", "device_code", profile=profile)
  433. _start_poller(_codex_full_login_worker, sid, prefix="oauth-codex")
  434. deadline = time.monotonic() + 10
  435. while time.monotonic() < deadline:
  436. with _oauth_sessions_lock:
  437. s = _oauth_sessions.get(sid)
  438. if s and (s.get("user_code") or s["status"] != "pending"):
  439. break
  440. await asyncio.sleep(0.1)
  441. with _oauth_sessions_lock:
  442. s = _oauth_sessions.get(sid, {})
  443. if s.get("status") == "error":
  444. from hermes_cli.observability.shared_metrics_setup import _OAUTH_FAILURE_KEY
  445. err = HTTPException(status_code=500, detail=s.get("error_message") or "device-auth failed")
  446. err.setup_failure_class = s.get(_OAUTH_FAILURE_KEY) or "other" # the worker's class, not "500"
  447. raise err
  448. if not s.get("user_code"):
  449. raise HTTPException(status_code=504, detail="device-auth timed out before returning a user code")
  450. return {
  451. "session_id": sid, "flow": "device_code", "user_code": s["user_code"], "verification_url": s["verification_url"],
  452. "expires_in": int(s.get("expires_in") or 900), "poll_interval": int(s.get("interval") or 5),
  453. }
  454. async def _start_minimax_device_code(profile: Optional[str]) -> dict[str, Any]:
  455. # Device-code flow with a PKCE extension: verifier + challenge from
  456. # _minimax_pkce_pair bind the token exchange to the original session.
  457. from hermes_cli.auth import (
  458. MINIMAX_OAUTH_CLIENT_ID, MINIMAX_OAUTH_GLOBAL_BASE, _minimax_pkce_pair, _minimax_request_user_code,
  459. )
  460. verifier, challenge, state = _minimax_pkce_pair()
  461. portal_base_url = (os.getenv("MINIMAX_PORTAL_BASE_URL") or MINIMAX_OAUTH_GLOBAL_BASE).rstrip("/")
  462. device_data = await _httpx_call(lambda client: _minimax_request_user_code(
  463. client=client, portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID,
  464. code_challenge=challenge, state=state,
  465. ), follow_redirects=True)
  466. # MiniMax's `interval` is in milliseconds (defensive default 2000ms in _minimax_poll_token).
  467. interval_raw = device_data.get("interval")
  468. interval_ms = int(interval_raw) if interval_raw is not None else None
  469. # `expired_in` is overloaded — a unix-ms timestamp OR seconds-from-now.
  470. # Mirror the heuristic in _minimax_poll_token; keep the raw value for the
  471. # poller and derive expires_at + UI-friendly expires_in seconds.
  472. expired_in_raw = int(device_data["expired_in"])
  473. if expired_in_raw > 1_000_000_000_000: # likely unix-ms
  474. expires_at_ts = expired_in_raw / 1000.0
  475. expires_in_seconds = max(0, int(expires_at_ts - time.time()))
  476. else:
  477. expires_at_ts = time.time() + expired_in_raw
  478. expires_in_seconds = expired_in_raw
  479. return _device_session_started(
  480. "minimax-oauth", profile, _minimax_poller,
  481. dict(
  482. interval_ms=interval_ms, user_code=str(device_data["user_code"]), code_verifier=verifier, state=state,
  483. portal_base_url=portal_base_url, client_id=MINIMAX_OAUTH_CLIENT_ID, region="global",
  484. expired_in_raw=expired_in_raw, expires_at=expires_at_ts,
  485. ),
  486. str(device_data["user_code"]), str(device_data["verification_uri"]), expires_in_seconds,
  487. max(2, (interval_ms or 2000) // 1000),
  488. )
  489. async def _start_xai_device_code(profile: Optional[str]) -> dict[str, Any]:
  490. from hermes_cli.auth import _xai_oauth_request_device_code
  491. device_data = await _httpx_call(_xai_oauth_request_device_code, timeout=20.0)
  492. return _device_session_started(
  493. "xai-oauth", profile, _xai_device_poller,
  494. dict(
  495. device_code=str(device_data["device_code"]), interval=int(device_data["interval"]),
  496. expires_at=time.time() + int(device_data["expires_in"]),
  497. ),
  498. str(device_data["user_code"]),
  499. str(device_data.get("verification_uri_complete") or device_data["verification_uri"]),
  500. int(device_data["expires_in"]), int(device_data["interval"]),
  501. )
  502. _DEVICE_CODE_STARTERS = {
  503. "nous": _start_nous_device_code, "openai-codex": _start_codex_device_code,
  504. "minimax-oauth": _start_minimax_device_code, "xai-oauth": _start_xai_device_code,
  505. }
  506. def _device_login_profile(provider_id: str):
  507. """The registered provider profile that owns an in-app device-code login, or None."""
  508. from providers import get_provider_profile
  509. prof = get_provider_profile(provider_id)
  510. if prof is None or not (prof.start_device_login and prof.poll_device_login and prof.save_device_login):
  511. return None
  512. return prof
  513. async def _start_profile_device_login(provider_id: str, profile: Optional[str]) -> dict[str, Any]:
  514. """Device-code login a provider profile owns: its ``start_device_login`` runs in the request's
  515. profile scope; ``_profile_device_poller`` polls and saves."""
  516. def _begin():
  517. prof = _device_login_profile(provider_id)
  518. return (prof, dict(prof.start_device_login() or {})) if prof is not None else (None, {})
  519. prof, login = await scoped_to_thread(profile, _begin)
  520. if prof is None or not login:
  521. raise HTTPException(status_code=400, detail=f"Provider {provider_id} does not support device-code flow")
  522. expires_in, interval = int(login["expires_in"]), max(1, int(login["interval"]))
  523. return _device_session_started(
  524. provider_id, profile, _profile_device_poller,
  525. dict(_provider_profile=prof, _device_state=login.get("state"), interval=interval,
  526. expires_at=time.time() + expires_in),
  527. str(login["user_code"]), str(login["verification_url"]), expires_in, interval,
  528. )
  529. async def _start_device_code_flow(provider_id: str, profile: Optional[str] = None) -> dict[str, Any]:
  530. """Hit the provider's device-auth endpoint, spawn its poller, return the display fields."""
  531. starter = _DEVICE_CODE_STARTERS.get(provider_id)
  532. if starter is None:
  533. return await _start_profile_device_login(provider_id, profile)
  534. return await starter(profile)
  535. def _claude_code_disconnect_command(platform: str) -> str:
  536. """Host-native command that removes Claude Code's borrowed credential file.
  537. Windows must not emit ``rm -f``. PowerShell aliases ``rm`` to ``Remove-Item``,
  538. and ``-f`` binds both ``-Force`` and ``-Filter`` (AmbiguousParameter).
  539. """
  540. if platform == "win32":
  541. literal = '"$HOME/.claude/.credentials.json"'
  542. return (
  543. f"if (Test-Path -LiteralPath {literal}) {{ "
  544. f"Remove-Item -LiteralPath {literal} -Force -ErrorAction Stop }}"
  545. )
  546. rm_file = "rm -f ~/.claude/.credentials.json"
  547. if platform == "darwin":
  548. return f'security delete-generic-password -s "Claude Code-credentials" 2>/dev/null; {rm_file}'
  549. return rm_file
  550. def _oauth_provider_disconnect_command(
  551. provider: dict[str, Any], platform: Optional[str] = None
  552. ) -> Optional[str]:
  553. """Shell command that clears an external provider's credentials, or None.
  554. The disconnect API never silently deletes files another CLI owns; the GUI runs
  555. this in its embedded terminal so the user sees exactly what executes. Claude Code
  556. has no scriptable logout, so remove what logout would: the macOS Keychain entry
  557. and/or ``~/.claude/.credentials.json`` (the two ``read_claude_code_credentials()`` sources).
  558. ``platform`` is the host the command will run on (default: this process). Pass it
  559. explicitly in tests; do not fake ``sys.platform``.
  560. """
  561. if provider.get("flow") != "external" or provider.get("id") != "claude-code":
  562. return None
  563. return _claude_code_disconnect_command(platform or sys.platform)
  564. def _oauth_provider_disconnect_hint(provider: dict[str, Any], status: dict[str, Any]) -> Optional[str]:
  565. """Return the manual disconnect path when the API cannot clear this provider."""
  566. # "anthropic" is flow == "external" (no in-dashboard login) but Hermes still
  567. # OWNS its credential (the PKCE file ~/.hermes/.anthropic_oauth.json and its
  568. # credential-pool entry, written by `hermes auth add anthropic`), so it is
  569. # excluded from the "external providers can't be auto-disconnected" rule.
  570. if provider.get("flow") == "external" and provider.get("id") != "anthropic":
  571. if _oauth_provider_disconnect_command(provider):
  572. # Fallback wording for surfaces without the one-click "run in terminal" path.
  573. return "Managed outside Hermes — run the disconnect command to remove it."
  574. return "Managed by that provider's CLI; remove it there."
  575. if status.get("source") == "env_var":
  576. return "Remove the API key from Settings → Keys instead."
  577. return None
  578. def _build_oauth_catalog() -> list[dict[str, Any]]:
  579. """Accounts-tab provider list: ``_OAUTH_PROVIDER_CATALOG`` cards first (curated
  580. order, win on metadata), then every other accounts-tab ``provider_catalog()`` entry
  581. in ``hermes model`` order, so plugin-added OAuth/external providers appear automatically."""
  582. rows: list[dict[str, Any]] = []
  583. seen: set[str] = set()
  584. for entry in _OAUTH_PROVIDER_CATALOG:
  585. if entry["id"] not in seen:
  586. seen.add(entry["id"])
  587. rows.append(dict(entry))
  588. try:
  589. from hermes_cli.provider_catalog import provider_catalog
  590. for d in provider_catalog():
  591. if d.slug in seen:
  592. continue
  593. row = _profile_account_row(d)
  594. if row is not None:
  595. seen.add(d.slug)
  596. rows.append(row)
  597. except Exception:
  598. pass
  599. return rows
  600. def _profile_account_row(d) -> Optional[dict[str, Any]]:
  601. """Accounts-tab card for one catalog provider: the generic external card, overlaid with what its
  602. profile declares (``account_card``, ``account_status``, an in-app ``start_device_login``). A
  603. Keys-tab provider gets a card only when its profile asks for one."""
  604. from providers import get_provider_profile
  605. prof = get_provider_profile(d.slug)
  606. card = dict(getattr(prof, "account_card", None) or {})
  607. device = _device_login_profile(d.slug) is not None
  608. if d.tab != "accounts" and not (card or device):
  609. return None
  610. return {
  611. "id": d.slug, "name": card.get("name") or d.label,
  612. "flow": "device_code" if device else card.get("flow") or "external",
  613. "cli_command": card.get("cli_command") or f"hermes auth add {d.slug}",
  614. "docs_url": card.get("docs_url") or d.signup_url or "",
  615. "status_fn": getattr(prof, "account_status", None),
  616. }
  617. @router.get("/api/providers/oauth")
  618. async def list_oauth_providers(profile: Optional[str] = None):
  619. """Every OAuth-capable provider with current status (token_preview is the last
  620. N chars, never the full token; disconnect_command only for external providers)."""
  621. def _run():
  622. providers = []
  623. for p in _build_oauth_catalog():
  624. status = _resolve_provider_status(p["id"], p.get("status_fn"))
  625. disconnect_hint = _oauth_provider_disconnect_hint(p, status)
  626. providers.append({
  627. "id": p["id"], "name": p["name"], "flow": p["flow"],
  628. "cli_command": _external_process_cli_command(p["id"], p["cli_command"]),
  629. "docs_url": p["docs_url"], "disconnect_hint": disconnect_hint,
  630. "disconnect_command": _oauth_provider_disconnect_command(p),
  631. "disconnectable": disconnect_hint is None, "status": status,
  632. })
  633. return {"providers": providers}
  634. return await scoped_to_thread(profile, _run)
  635. def _reject_if_not_disconnectable(provider: dict[str, Any], status: dict[str, Any]) -> None:
  636. disconnect_hint = _oauth_provider_disconnect_hint(provider, status)
  637. if disconnect_hint:
  638. raise HTTPException(400, f"{provider['name']} cannot be disconnected automatically. {disconnect_hint}")
  639. def _clear_anthropic_auth() -> bool:
  640. """Clear only the Hermes-managed PKCE file and auth-store entry (never ~/.claude/*)."""
  641. cleared = False
  642. try:
  643. from agent.anthropic_credentials import _get_hermes_oauth_file
  644. oauth_file = _get_hermes_oauth_file()
  645. if oauth_file.exists():
  646. oauth_file.unlink()
  647. cleared = True
  648. except Exception:
  649. _log.exception("disconnect anthropic OAuth file failed")
  650. raise
  651. try:
  652. from hermes_cli.auth import clear_provider_auth
  653. cleared = clear_provider_auth("anthropic") or cleared
  654. except Exception:
  655. _log.exception("disconnect anthropic auth store failed")
  656. raise
  657. return cleared
  658. def _disconnect_http_error(status_code: int, provider_name: str) -> HTTPException:
  659. if status_code == 409:
  660. detail = f"No stored credentials were removed for {provider_name}."
  661. else:
  662. detail = f"Failed to remove stored credentials for {provider_name}."
  663. return HTTPException(status_code=status_code, detail=detail)
  664. @router.delete("/api/providers/oauth/{provider_id}")
  665. async def disconnect_oauth_provider(provider_id: str, request: Request, profile: Optional[str] = None):
  666. """Disconnect an OAuth provider. Token-protected (matches /env/reveal)."""
  667. _require_token(request)
  668. def _run():
  669. catalog_by_id = {p["id"]: p for p in _build_oauth_catalog()}
  670. provider = catalog_by_id.get(provider_id)
  671. if provider is None:
  672. raise HTTPException(400, f"Unknown provider: {provider_id}. Available: {', '.join(sorted(catalog_by_id))}")
  673. # Flow-only rejection first so external providers never reach status resolution.
  674. _reject_if_not_disconnectable(provider, {})
  675. _reject_if_not_disconnectable(provider, _resolve_provider_status(provider_id, provider.get("status_fn")))
  676. if provider_id == "anthropic":
  677. try:
  678. cleared = _clear_anthropic_auth()
  679. except HTTPException:
  680. raise
  681. except Exception:
  682. _log.exception("disconnect %s failed", provider_id)
  683. raise _disconnect_http_error(500, provider["name"])
  684. if not cleared:
  685. raise _disconnect_http_error(409, provider["name"])
  686. _log.info("oauth/disconnect: %s", provider_id)
  687. return {"ok": True, "provider": provider_id}
  688. try:
  689. from hermes_cli.auth import clear_provider_auth, invalidate_nous_auth_status_cache
  690. cleared = clear_provider_auth(provider_id)
  691. if provider_id == "nous":
  692. invalidate_nous_auth_status_cache()
  693. if not cleared:
  694. raise _disconnect_http_error(409, provider["name"])
  695. _log.info("oauth/disconnect: %s (cleared=%s)", provider_id, cleared)
  696. return {"ok": True, "provider": provider_id}
  697. except HTTPException:
  698. raise
  699. except Exception:
  700. _log.exception("disconnect %s failed", provider_id)
  701. raise _disconnect_http_error(500, provider["name"])
  702. return await scoped_to_thread(profile, _run)
  703. # In-browser device-code sessions: /start spawns a poller thread and returns the
  704. # display fields; the UI polls .../poll/{session_id} until status != "pending" (on
  705. # "approved" the poller has already saved creds). Anthropic has NO dashboard PKCE
  706. # flow — an unattended endpoint minting Claude subscription tokens outside
  707. # Anthropic's own client violates its OAuth usage policy; that card is "external".
  708. # Sessions are in-memory (single-process), expire after 15 min, GC'd on /start.
  709. def _gc_oauth_sessions() -> None:
  710. cutoff = time.time() - _OAUTH_SESSION_TTL_SECONDS
  711. with _oauth_sessions_lock:
  712. for sid in [sid for sid, sess in _oauth_sessions.items() if sess["created_at"] < cutoff]:
  713. _oauth_sessions.pop(sid, None)
  714. def _validate_oauth_profile(profile: Optional[str]) -> str:
  715. """Validate the requested profile (404 via ``_resolve_profile_dir``) and return its name."""
  716. profile_name = _oauth_profile_name(profile)
  717. if profile_name:
  718. _resolve_profile_dir(profile_name)
  719. return profile_name
  720. @router.post("/api/providers/oauth/{provider_id}/start")
  721. async def start_oauth_login(provider_id: str, request: Request, profile: Optional[str] = None):
  722. """Initiate an OAuth login flow. Token-protected."""
  723. _require_token(request)
  724. _gc_oauth_sessions()
  725. _validate_oauth_profile(profile)
  726. # The whole Accounts catalog, in the request's profile scope: a provider profile's card counts.
  727. catalog = await scoped_to_thread(profile, _build_oauth_catalog)
  728. catalog_entry = next((p for p in catalog if p["id"] == provider_id), None)
  729. if catalog_entry is None:
  730. raise HTTPException(status_code=400, detail=f"Unknown provider {provider_id}")
  731. if catalog_entry["flow"] == "external":
  732. raise HTTPException(400, f"{provider_id} uses an external CLI; run `{catalog_entry['cli_command']}` manually")
  733. if catalog_entry["flow"] != "device_code":
  734. raise HTTPException(status_code=400, detail="Unsupported flow")
  735. flow = await _begin_oauth_setup_metric(provider_id, profile)
  736. try:
  737. body = await _start_device_code_flow(provider_id, profile=profile)
  738. except Exception as e:
  739. await _end_oauth_setup_metric(flow, e)
  740. if isinstance(e, HTTPException):
  741. raise
  742. _log.exception("oauth/start %s failed", provider_id)
  743. raise HTTPException(status_code=500, detail=str(e))
  744. if flow is not None:
  745. await asyncio.to_thread(_track_oauth_setup, flow, body["session_id"])
  746. return body
  747. async def _begin_oauth_setup_metric(provider_id: str, profile: Optional[str]):
  748. """Start the provider-setup metric off the event loop (a cold metrics runtime blocks); None when the
  749. owning profile does not collect. Never raises: the start route's own validation owns errors."""
  750. from hermes_cli.observability.shared_metrics_setup import begin_oauth_setup, collection_enabled
  751. try:
  752. profile_name = _oauth_profile_name(profile)
  753. home = _resolve_profile_dir(profile_name) if profile_name else None
  754. if not collection_enabled(home):
  755. return None
  756. return await asyncio.to_thread(begin_oauth_setup, provider_id, home)
  757. except Exception:
  758. return None
  759. async def _end_oauth_setup_metric(flow, exc: Exception) -> None:
  760. if flow is None:
  761. return
  762. from hermes_cli.observability.shared_metrics_setup import finish_provider_setup, setup_failure_class
  763. with contextlib.suppress(Exception):
  764. # A 401/403 from the start route is the provider refusing this account/client; a 504 is the
  765. # provider not answering in time.
  766. status = exc.status_code if isinstance(exc, HTTPException) else None
  767. failure = {401: "auth", 403: "auth", 504: "network"}.get(status) or setup_failure_class(exc)
  768. await asyncio.to_thread(finish_provider_setup, flow, "failed", failure)
  769. @router.post("/api/providers/oauth/{provider_id}/submit")
  770. async def submit_oauth_code(
  771. provider_id: str, body: OAuthSubmitBody, request: Request, profile: Optional[str] = None,
  772. ):
  773. """Submit the auth code for PKCE flows. Token-protected."""
  774. _require_token(request)
  775. raise HTTPException(status_code=400, detail=f"submit not supported for {provider_id}")
  776. # A long-poll answers as soon as what it watches changes, and otherwise after at most this long, so
  777. # the request stays well inside the desktop's own request timeout.
  778. _LONG_POLL_CAP_SECONDS = 25.0
  779. async def _long_poll(read: Callable[[], Any], changed: Callable[[Any], bool], wait: float, tick: float) -> Any:
  780. """Re-run the async *read* every *tick* seconds until *changed* holds or *wait* (capped) runs out;
  781. the last read is the answer. ``wait <= 0`` is one plain read."""
  782. deadline = time.monotonic() + min(max(wait, 0.0), _LONG_POLL_CAP_SECONDS)
  783. value = await read()
  784. while not changed(value) and (left := deadline - time.monotonic()) > 0:
  785. await asyncio.sleep(min(tick, left))
  786. value = await read()
  787. return value
  788. @router.get("/api/providers/oauth/{provider_id}/poll/{session_id}")
  789. async def poll_oauth_session(provider_id: str, session_id: str, profile: Optional[str] = None, wait: float = 0):
  790. """Poll a session's status (no auth — read-only state). One endpoint serves
  791. every device-code flow: all report progress via the worker-updated ``status``.
  792. With *wait* (seconds) it is a long-poll: it answers once the session leaves ``pending``."""
  793. requested_profile = _validate_oauth_profile(profile)
  794. with _oauth_sessions_lock:
  795. sess = _oauth_sessions.get(session_id)
  796. if not sess:
  797. raise HTTPException(status_code=404, detail="Session not found or expired")
  798. if sess["provider"] != provider_id:
  799. raise HTTPException(status_code=400, detail="Provider mismatch for session")
  800. if sess.get("profile") != requested_profile:
  801. raise HTTPException(status_code=400, detail="OAuth session profile mismatch")
  802. async def _status() -> str:
  803. with _oauth_sessions_lock:
  804. return "cancelled" if sess.get("cancelled") else sess["status"]
  805. # The poller thread writes the session dict, so watching it costs no network.
  806. await _long_poll(_status, lambda status: status != "pending", wait, tick=0.25)
  807. return {
  808. "session_id": session_id, "status": sess["status"],
  809. "error_message": sess.get("error_message"), "expires_at": sess.get("expires_at"),
  810. # Nous: why a sign-in ended, who signed in, and the default model the completion settled on
  811. # (None when the config was on the user's own model).
  812. "reason": sess.get("reason"), "account_email": sess.get("account_email"), "model": sess.get("model"),
  813. # What the replaced free tier's handoff did: one user-facing line each (moved, reconnect),
  814. # and the same result as fields (``guest_handoff.wire_status``; None without a handoff).
  815. "handoff": sess.get("handoff"), "handoff_status": sess.get("handoff_status"),
  816. # Failed Nous sign-ins: can a later attempt succeed, and after how long.
  817. "retryable": sess.get("retryable"), "retry_after": sess.get("retry_after"),
  818. }
  819. @router.get("/api/providers/oauth/nous/handoff")
  820. async def nous_handoff_status(
  821. request: Request, profile: Optional[str] = None, since: Optional[str] = None, wait: float = 0,
  822. ):
  823. """The profile's latest free-tier handoff (``guest_handoff.wire_status``). Token-protected. A
  824. long-poll: given *since* (the ``updated_at`` the caller already shows) and *wait*, it answers once
  825. the record changes. The keepalive retries a move in the background; this only reads."""
  826. _require_token(request)
  827. profile_name = _validate_oauth_profile(profile)
  828. def _read() -> dict[str, Any]:
  829. from hermes_cli.guest_handoff import handoff_status, wire_status
  830. return wire_status(handoff_status())
  831. return await _long_poll(
  832. lambda: config_scoped_to_thread(profile_name, _read),
  833. lambda status: since is None or status.get("updated_at") != since, wait, tick=1.0)
  834. @router.delete("/api/providers/oauth/sessions/{session_id}")
  835. async def cancel_oauth_session(session_id: str, request: Request, profile: Optional[str] = None):
  836. """Cancel a pending OAuth session. Token-protected.
  837. Marks the session dict ``cancelled`` before popping it so a background
  838. worker still holding that dict (e.g. the Codex poller) stops
  839. polling/exchanging/saving instead of completing the login after the user
  840. believed it was aborted.
  841. """
  842. _require_token(request)
  843. requested_profile = _validate_oauth_profile(profile)
  844. with _oauth_sessions_lock:
  845. sess = _oauth_sessions.get(session_id)
  846. if sess is not None:
  847. if sess.get("profile") != requested_profile:
  848. raise HTTPException(status_code=400, detail="OAuth session profile mismatch")
  849. sess["cancelled"] = True
  850. _oauth_sessions.pop(session_id, None)
  851. if sess is None:
  852. return {"ok": False, "message": "session not found"}
  853. # Recorded now, not when the poller next wakes: a Nous/xAI poll can block for the code's lifetime.
  854. from hermes_cli.observability.shared_metrics_setup import settle_oauth_setup
  855. await asyncio.to_thread(settle_oauth_setup, sess)
  856. return {"ok": True, "session_id": session_id}