web_server_oauth.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. """Dashboard OAuth/login-status helpers: provider catalog, per-provider device pollers,
  2. Anthropic/Claude-Code status probes, and the poller for provider-profile device logins.
  3. """
  4. import contextlib
  5. import logging
  6. import functools
  7. import os
  8. import threading
  9. import time
  10. from datetime import datetime, timezone, UTC
  11. from typing import Any, Dict, Optional
  12. # Same logger the code used before extraction (record parity).
  13. _log = logging.getLogger("hermes_cli.web_server")
  14. _LOGGED_OUT: dict[str, Any] = {"logged_in": False, "source": None}
  15. def _truncate_token(value: Optional[str], visible: int = 6) -> str:
  16. """``…XXXXXX`` (last N chars) for UI display. JWTs show only the tail of the signature
  17. segment. A callable (Azure Foundry Entra-ID bearer provider) is NEVER invoked — it yields
  18. the ``<entra-id-bearer>`` placeholder."""
  19. if not value:
  20. return ""
  21. if callable(value) and not isinstance(value, str):
  22. return "<entra-id-bearer>"
  23. s = str(value)
  24. if s.count(".") >= 2:
  25. s = s.rsplit(".", 1)[-1]
  26. return s if len(s) <= visible else f"…{s[-visible:]}"
  27. def _token_status(source: str, source_label: str, creds: dict[str, Any]) -> dict[str, Any]:
  28. return {
  29. "logged_in": True, "source": source, "source_label": source_label,
  30. "token_preview": _truncate_token(creds.get("accessToken")),
  31. "expires_at": creds.get("expiresAt"), "has_refresh_token": bool(creds.get("refreshToken")),
  32. }
  33. def _anthropic_oauth_status() -> dict[str, Any]:
  34. """Status for the "Anthropic Account" card: Hermes-managed PKCE file first, then the
  35. registry-ordered env vars (process env — where Bitwarden-sourced secrets land — then .env).
  36. Claude Code's ``~/.claude/.credentials.json`` is deliberately NOT read here; it has its own
  37. ``claude-code`` entry, and counting it here would shadow a real ANTHROPIC_API_KEY.
  38. """
  39. try:
  40. from agent.anthropic_credentials import read_hermes_oauth_credentials, _get_hermes_oauth_file
  41. hermes_creds = read_hermes_oauth_credentials()
  42. except Exception:
  43. hermes_creds = None
  44. if hermes_creds and hermes_creds.get("accessToken"):
  45. return _token_status("hermes_pkce", f"Hermes PKCE ({_get_hermes_oauth_file()})", hermes_creds)
  46. env_var_order: tuple = ("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN")
  47. try:
  48. from hermes_cli.auth import PROVIDER_REGISTRY
  49. env_var_order = PROVIDER_REGISTRY["anthropic"].api_key_env_vars
  50. except (ImportError, KeyError):
  51. pass
  52. from hermes_cli.config import get_env_value
  53. from hermes_cli.env_loader import format_secret_source_suffix
  54. for var in env_var_order:
  55. value = get_env_value(var) or os.getenv(var)
  56. if value:
  57. return {
  58. "logged_in": True, "source": "env_var", "source_label": f"{var}{format_secret_source_suffix(var)}",
  59. "token_preview": _truncate_token(value), "expires_at": None, "has_refresh_token": False,
  60. }
  61. return dict(_LOGGED_OUT)
  62. def _claude_code_only_status() -> dict[str, Any]:
  63. """Claude Code CLI credentials as their own entry, independent of the Anthropic card.
  64. Connected follows the same local validity gate as Anthropic resolution. A
  65. persisted access token that has already expired is not a usable login.
  66. """
  67. try:
  68. from agent.anthropic_credentials import (
  69. is_claude_code_token_valid,
  70. read_claude_code_credentials,
  71. )
  72. creds = read_claude_code_credentials()
  73. if creds and is_claude_code_token_valid(creds):
  74. return _token_status("claude_code_cli", "~/.claude/.credentials.json", creds)
  75. except Exception:
  76. pass
  77. return dict(_LOGGED_OUT)
  78. def _external_process_cli_command(provider_id: str, default: str) -> str:
  79. """Render an external-process provider's sign-in command with the CLI actually configured
  80. (its profile's ``process_command_env_vars`` override); others get ``default`` untouched."""
  81. try:
  82. from hermes_cli.auth import PROVIDER_REGISTRY, get_external_process_provider_status
  83. pconfig = PROVIDER_REGISTRY.get(provider_id)
  84. if not pconfig or pconfig.auth_type != "external_process":
  85. return default
  86. status = get_external_process_provider_status(provider_id) or {}
  87. command = str(status.get("command") or "").strip()
  88. if command:
  89. parts = default.split(" ", 1)
  90. tail = f" {parts[1]}" if len(parts) > 1 else ""
  91. return f"{command}{tail}"
  92. except Exception:
  93. pass
  94. return default
  95. # Hand-tuned OAuth/account cards: the bits not derivable from the unified provider catalog
  96. # (``flow``, ``status_fn``, ``cli_command``, display order). OVERRIDE BASE for
  97. # ``_build_oauth_catalog()``, which unions them with every accounts-tab provider so new
  98. # providers appear automatically (a provider profile customises its own card through
  99. # ``account_card`` / ``account_status`` / ``start_device_login``). Also carries two non-catalog rows:
  100. # the Anthropic credential-status card and the synthetic ``claude-code`` row.
  101. # ``flow``: ``device_code`` = show code + URL + poll; ``external`` = delegated to a terminal/CLI.
  102. _OAUTH_PROVIDER_CATALOG: tuple[dict[str, Any], ...] = (
  103. # status_fn None → dispatched via auth.get_<provider>_auth_status.
  104. {"id": "nous", "name": "Nous Portal", "flow": "device_code", "cli_command": "hermes auth add nous",
  105. "docs_url": "https://portal.nousresearch.com", "status_fn": None},
  106. {"id": "openai-codex", "name": "ChatGPT or Codex Subscription", "flow": "device_code",
  107. "cli_command": "hermes auth add openai-codex", "docs_url": "https://platform.openai.com/docs",
  108. "status_fn": None},
  109. {"id": "qwen-oauth", "name": "Qwen (via Qwen CLI)", "flow": "external",
  110. "cli_command": "hermes auth add qwen-oauth", "docs_url": "https://github.com/QwenLM/qwen-code",
  111. "status_fn": None},
  112. # Structurally device-code (verification URI + user code + token polling) with a PKCE
  113. # code-binding extension that doesn't change the operator UX.
  114. {"id": "minimax-oauth", "name": "MiniMax (OAuth)", "flow": "device_code",
  115. "cli_command": "hermes auth add minimax-oauth", "docs_url": "https://www.minimax.io", "status_fn": None},
  116. # Device code works in remote shells/containers without a reachable 127.0.0.1 callback.
  117. {"id": "xai-oauth", "name": "xAI Grok OAuth (SuperGrok / Premium+)", "flow": "device_code",
  118. "cli_command": "hermes auth add xai-oauth",
  119. "docs_url": "https://hermes-agent.nousresearch.com/docs/guides/xai-grok-oauth", "status_fn": None},
  120. # Anthropic / Claude entries sit at the bottom. Deliberately flow == "external": an
  121. # in-dashboard Connect button would let a scriptable HTTP endpoint mint Claude Pro/Max
  122. # subscription tokens outside Anthropic's own client, against its OAuth usage policies.
  123. # Login works via the terminal (`hermes auth add anthropic`) or a plain API key.
  124. {"id": "anthropic", "name": "Anthropic Account", "flow": "external", "cli_command": "hermes auth add anthropic",
  125. "docs_url": "https://docs.claude.com/en/api/getting-started", "status_fn": _anthropic_oauth_status},
  126. {"id": "claude-code", "name": "Anthropic OAuth: Required Extra Usage Credits to Use Subscription",
  127. "flow": "external", "cli_command": "claude setup-token",
  128. "docs_url": "https://docs.claude.com/en/docs/claude-code", "status_fn": _claude_code_only_status},
  129. )
  130. _oauth_sessions: dict[str, dict[str, Any]] = {}
  131. _oauth_sessions_lock = threading.Lock()
  132. def _oauth_profile_name(profile: Optional[str]) -> Optional[str]:
  133. requested = (profile or "").strip()
  134. if not requested or requested.lower() == "current":
  135. return None
  136. return requested
  137. def _oauth_poller(label: str):
  138. """Wrap a device-code poller body ``fn(session_id, sess)``: vanished session is a no-op,
  139. success marks ``approved``, any exception records ``error`` + ``error_message`` on the
  140. session instead of raising (the thread has no caller; the dashboard reads the status)."""
  141. def deco(fn):
  142. @functools.wraps(fn)
  143. def poller(session_id: str) -> None:
  144. with _oauth_sessions_lock:
  145. sess = _oauth_sessions.get(session_id)
  146. if not sess:
  147. return
  148. try:
  149. fn(session_id, sess)
  150. with _oauth_sessions_lock:
  151. # A body that already settled the session (a sign-in the user declined in the
  152. # browser is ``denied`` with a ``reason``) keeps its verdict.
  153. settled = sess["status"] != "pending"
  154. if not settled:
  155. sess["status"] = "approved"
  156. if settled:
  157. _log.info("oauth/device: %s login ended %s (session=%s)", label, sess["status"], session_id)
  158. else:
  159. _log.info("oauth/device: %s login completed (session=%s)", label, session_id)
  160. except Exception as e:
  161. from hermes_cli.observability.shared_metrics_setup import note_oauth_failure
  162. _log.warning("%s device-code poll failed (session=%s): %s", label, session_id, e)
  163. note_oauth_failure(sess, e)
  164. with _oauth_sessions_lock:
  165. sess["status"] = "error"
  166. sess["error_message"] = str(e)
  167. return poller
  168. return deco
  169. def _record_sign_in_state(sess: dict[str, Any], state: Any) -> None:
  170. """Write one ``anon_auth.SignInState`` onto the dashboard session, under the sessions lock.
  171. The whole desktop mapping lives here: the state carries its own copy, so nothing below turns a
  172. reason into a string. ``completed`` deliberately leaves ``status`` on ``"pending"`` so the
  173. :func:`_oauth_poller` wrapper stamps ``"approved"`` when the poller returns.
  174. """
  175. kind = getattr(state, "kind", "")
  176. if kind in ("code", "waiting"):
  177. return # the start route already published the code
  178. with _oauth_sessions_lock:
  179. if kind == "completed":
  180. sess["account_email"] = state.email or None
  181. # None when the config was left on the user's own model, as the poll route documents.
  182. sess["model"] = state.model if state.model_changed else None
  183. # What the free tier's handoff did (moved apps, apps to reconnect); empty without one.
  184. sess["handoff"] = list(state.handoff)
  185. # The same result as fields, so the desktop can name the apps and follow a retry.
  186. sess["handoff_status"] = state.handoff_status
  187. return
  188. if kind == "cancelled":
  189. sess["status"] = "cancelled"
  190. return
  191. if kind == "timed_out":
  192. sess["status"], sess["reason"] = "error", "timeout"
  193. # The enriched device-auth guidance, which the dashboard has room for.
  194. sess["error_message"] = state.detail or state.copy
  195. return
  196. sess["status"] = "error"
  197. sess["reason"] = getattr(state, "reason", "") or kind or "error"
  198. sess["error_message"] = state.copy # the chat form: no raw exception reaches the UI
  199. # Whether a later attempt can succeed, and the wait the service named (seconds).
  200. sess["retryable"] = bool(getattr(state, "retryable", False))
  201. sess["retry_after"] = int(getattr(state, "retry_after", 0) or 0)
  202. @_oauth_poller("nous")
  203. def _nous_sign_in_poller(session_id: str, sess: dict[str, Any]) -> None:
  204. """Drain the sign-in the start route began: the one shared flow, rendered onto the session.
  205. The generator was created and advanced to its ``Code`` state by ``_start_nous_device_code``, so
  206. it is already holding the device code and its HTTP client. Nothing here is wrapped in
  207. ``_profile_scope``: that context manager holds a process-global lock and swaps module
  208. attributes across its ``yield``, and this loop can last the sign-in code's whole expiry. The
  209. generator scopes its own short config/auth-store sections instead.
  210. """
  211. gen = sess.get("_sign_in")
  212. if gen is None:
  213. return
  214. try:
  215. for state in gen:
  216. _record_sign_in_state(sess, state)
  217. finally:
  218. with contextlib.suppress(Exception):
  219. gen.close() # unwinds the suspended HTTP client if we leave early
  220. @_oauth_poller("minimax")
  221. def _minimax_poller(session_id: str, sess: dict[str, Any]) -> None:
  222. """MiniMax poller: PKCE-style ``code_verifier`` + ``user_code`` instead of Nous's
  223. ``device_code``. Builds the same auth_state as the CLI's ``_minimax_oauth_login`` and persists
  224. via ``_minimax_save_auth_state`` so the system ends up as after ``hermes auth add minimax-oauth``.
  225. Region is fixed to "global" here; cn-region operators use the CLI's ``--region cn``."""
  226. from hermes_cli.web_server_profiles import _profile_scope
  227. from hermes_cli.auth import (
  228. _minimax_poll_token, _minimax_resolve_token_expiry_unix, _minimax_save_auth_state,
  229. MINIMAX_OAUTH_GLOBAL_INFERENCE, MINIMAX_OAUTH_SCOPE,
  230. )
  231. import httpx
  232. portal_base_url, client_id = sess["portal_base_url"], sess["client_id"]
  233. with httpx.Client(
  234. timeout=httpx.Timeout(15.0), headers={"Accept": "application/json"}, follow_redirects=True
  235. ) as client:
  236. token_data = _minimax_poll_token(
  237. client=client, portal_base_url=portal_base_url, client_id=client_id,
  238. user_code=sess["user_code"], code_verifier=sess["code_verifier"],
  239. expired_in=sess["expired_in_raw"], interval_ms=sess.get("interval_ms"),
  240. )
  241. now = datetime.now(UTC)
  242. expires_at_ts = _minimax_resolve_token_expiry_unix(int(token_data["expired_in"]), now=now)
  243. auth_state = {
  244. "provider": "minimax-oauth",
  245. "region": sess.get("region", "global"),
  246. "portal_base_url": portal_base_url,
  247. "inference_base_url": MINIMAX_OAUTH_GLOBAL_INFERENCE,
  248. "client_id": client_id,
  249. "scope": MINIMAX_OAUTH_SCOPE,
  250. "token_type": token_data.get("token_type", "Bearer"),
  251. "access_token": token_data["access_token"],
  252. "refresh_token": token_data["refresh_token"],
  253. "resource_url": token_data.get("resource_url"),
  254. "obtained_at": now.isoformat(),
  255. "expires_at": datetime.fromtimestamp(expires_at_ts, tz=UTC).isoformat(),
  256. "expires_in": max(0, int(expires_at_ts - now.timestamp())),
  257. }
  258. with _profile_scope(sess.get("profile")):
  259. # The cancellation check and the save share the session lock, so a cancel cannot land
  260. # between them (the same contract as the Nous and Codex savers).
  261. with _oauth_sessions_lock:
  262. if sess.get("cancelled"):
  263. sess["status"] = "cancelled"
  264. return
  265. _minimax_save_auth_state(auth_state)
  266. @_oauth_poller("xai")
  267. def _xai_device_poller(session_id: str, sess: dict[str, Any]) -> None:
  268. """Background poller for xAI's OAuth device-code flow."""
  269. from hermes_cli.web_server_profiles import _profile_scope
  270. import httpx
  271. from hermes_cli.auth import (
  272. _save_xai_oauth_tokens, _xai_oauth_discovery, _xai_oauth_poll_device_token,
  273. mark_provider_active_if_unset, unsuppress_credential_source,
  274. )
  275. discovery = _xai_oauth_discovery(20.0)
  276. with httpx.Client(timeout=httpx.Timeout(20.0), headers={"Accept": "application/json"}) as client:
  277. token_data = _xai_oauth_poll_device_token(
  278. client, token_endpoint=discovery["token_endpoint"], device_code=sess["device_code"],
  279. expires_in=max(60, int(sess["expires_at"] - time.time())), poll_interval=int(sess["interval"]),
  280. )
  281. tokens = {
  282. "access_token": str(token_data.get("access_token", "") or "").strip(),
  283. "refresh_token": str(token_data.get("refresh_token", "") or "").strip(),
  284. "id_token": str(token_data.get("id_token", "") or "").strip(),
  285. "expires_in": token_data.get("expires_in"),
  286. "token_type": str(token_data.get("token_type") or "Bearer").strip() or "Bearer",
  287. }
  288. with _profile_scope(sess.get("profile")), _oauth_sessions_lock:
  289. # One critical section with the cancel check, as in the Nous and Codex savers.
  290. if sess.get("cancelled"):
  291. sess["status"] = "cancelled"
  292. return
  293. # set_active=False: persist without hijacking an existing active chat provider.
  294. _save_xai_oauth_tokens(
  295. tokens, discovery=discovery, auth_mode="oauth_device_code", set_active=False,
  296. last_refresh=datetime.now(UTC).isoformat().replace("+00:00", "Z"),
  297. )
  298. # Mirror `hermes auth add xai-oauth`: first credential may become active; never overwrite.
  299. mark_provider_active_if_unset("xai-oauth")
  300. # The singleton write is the source of truth (the pool load seeds it as the canonical
  301. # ``device_code`` entry). Do NOT add a parallel ``manual:dashboard_*`` pool entry — it
  302. # duplicates the single-use refresh token and triggers ``refresh_token_reused`` churn.
  303. # An interactive login is an explicit re-enable, so clear any prior suppression.
  304. unsuppress_credential_source("xai-oauth", "device_code")
  305. def _sleep_unless_cancelled(sess: dict[str, Any], seconds: float) -> bool:
  306. """Sleep *seconds* in short ticks; True as soon as the session is cancelled."""
  307. deadline = time.monotonic() + seconds
  308. while True:
  309. with _oauth_sessions_lock:
  310. if sess.get("cancelled"):
  311. return True
  312. left = deadline - time.monotonic()
  313. if left <= 0:
  314. return False
  315. time.sleep(min(0.25, left))
  316. _DEVICE_LOGIN_ENDINGS = {"denied": "Authorization was denied.", "expired": "Device code expired before approval"}
  317. @_oauth_poller("provider-profile")
  318. def _profile_device_poller(session_id: str, sess: dict[str, Any]) -> None:
  319. """Drive a device-code login a provider profile owns (``ProviderProfile.start_device_login``):
  320. one ``poll_device_login`` per interval (each bound to the session's profile) until approved, then
  321. ``save_device_login`` under the session's profile scope, in one critical section with the cancel check like the built-in savers."""
  322. from hermes_cli.web_server_profiles import _config_profile_scope, _profile_scope
  323. profile, state, interval = sess["_provider_profile"], sess["_device_state"], int(sess["interval"])
  324. result: dict[str, Any] = {}
  325. while time.time() < sess["expires_at"]:
  326. if _sleep_unless_cancelled(sess, interval):
  327. break
  328. with _config_profile_scope(sess.get("profile")): # await-safe: no skills lock across the wait
  329. result = dict(profile.poll_device_login(state) or {})
  330. state = result.get("state", state)
  331. if result.get("status") != "pending":
  332. break
  333. interval = int(result.get("interval") or interval)
  334. with _profile_scope(sess.get("profile")), _oauth_sessions_lock:
  335. if sess.get("cancelled"):
  336. sess["status"] = "cancelled"
  337. return
  338. status = result.get("status")
  339. if status in (None, "pending"): # the code's lifetime ran out
  340. status = "expired"
  341. if status != "approved":
  342. sess["status"] = status if status in _DEVICE_LOGIN_ENDINGS else "error"
  343. sess["error_message"] = result.get("message") or _DEVICE_LOGIN_ENDINGS.get(status) or "Sign-in failed"
  344. return
  345. profile.save_device_login(result.get("credential"))