auth_xai.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. """xAI Grok OAuth: token store, discovery, refresh, device-code login.
  2. Split out of ``hermes_cli/auth.py``; origin helpers are imported lazily per function so
  3. ``hermes_cli.auth.<helper>`` patches still intercept and no cycle forms.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import base64
  8. import json
  9. import os
  10. import time
  11. from pathlib import Path
  12. from typing import Any, Dict, Optional, TYPE_CHECKING
  13. from urllib.parse import urlparse
  14. from hermes_cli.auth_codex import _load_auth_store_maybe_locked, _refresh_payload_access_token
  15. from hermes_cli.auth_constants import (
  16. AUTH_LOCK_TIMEOUT_SECONDS, AuthError, DEFAULT_XAI_OAUTH_BASE_URL, DEVICE_CODE_GRANT_TYPE,
  17. XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS, XAI_OAUTH_CLIENT_ID, XAI_OAUTH_DEVICE_CODE_URL,
  18. XAI_OAUTH_DISCOVERY_URL, XAI_OAUTH_SCOPE, _FORM_JSON_HEADERS, _xai_err, httpx,
  19. )
  20. from utils import env_float
  21. if TYPE_CHECKING: # annotation-only; the runtime import would be a cycle
  22. from hermes_cli.auth import ProviderConfig
  23. logger = logging.getLogger("hermes_cli.auth")
  24. _RELOGIN = "Re-authenticate with `hermes model`."
  25. def _clean(value: Any) -> str:
  26. return str(value or "").strip()
  27. def _token_pair(tokens: Any) -> tuple[str, str]:
  28. """``(access_token, refresh_token)`` stripped; empty strings when *tokens* is not a dict."""
  29. if not isinstance(tokens, dict):
  30. return "", ""
  31. return _clean(tokens.get("access_token")), _clean(tokens.get("refresh_token"))
  32. def _xai_oauth_state_from_store(auth_store: dict[str, Any]) -> Optional[dict[str, Any]]:
  33. """Return usable xAI OAuth state from provider state or credential pool."""
  34. from hermes_cli.auth import _load_provider_state
  35. state = _load_provider_state(auth_store, "xai-oauth")
  36. if isinstance(state, dict) and all(_token_pair(state.get("tokens"))):
  37. return state
  38. credential_pool = auth_store.get("credential_pool")
  39. entries = credential_pool.get("xai-oauth") if isinstance(credential_pool, dict) else None
  40. for entry in entries if isinstance(entries, list) else ():
  41. access_token, refresh_token = _token_pair(entry)
  42. if not access_token or not refresh_token:
  43. continue
  44. merged = dict(state or {})
  45. merged["tokens"] = {
  46. "access_token": access_token, "refresh_token": refresh_token,
  47. "token_type": str(entry.get("token_type") or "Bearer"),
  48. }
  49. if entry.get("last_refresh"):
  50. merged["last_refresh"] = entry.get("last_refresh")
  51. merged.setdefault("auth_mode", "oauth_pkce")
  52. return merged
  53. return state if isinstance(state, dict) else None
  54. def _xai_oauth_state_has_usable_tokens(state: Optional[dict[str, Any]]) -> bool:
  55. return isinstance(state, dict) and all(_token_pair(state.get("tokens")))
  56. def _read_xai_oauth_tokens(*, _lock: bool = True) -> dict[str, Any]:
  57. from hermes_cli.auth import _load_global_auth_store
  58. state = _xai_oauth_state_from_store(_load_auth_store_maybe_locked(_lock))
  59. if not _xai_oauth_state_has_usable_tokens(state):
  60. global_state = _xai_oauth_state_from_store(_load_global_auth_store())
  61. if _xai_oauth_state_has_usable_tokens(global_state):
  62. state = global_state
  63. if not state:
  64. raise _xai_err(
  65. "No xAI OAuth credentials stored. Select xAI Grok OAuth (SuperGrok / Premium+) in `hermes model`.",
  66. "xai_auth_missing", relogin=True,
  67. )
  68. tokens = state.get("tokens")
  69. if not isinstance(tokens, dict):
  70. raise _xai_err(f"xAI OAuth state is missing tokens. {_RELOGIN}", "xai_auth_invalid_shape", relogin=True)
  71. access_token, refresh_token = _token_pair(tokens)
  72. for value, field in ((access_token, "access_token"), (refresh_token, "refresh_token")):
  73. if not value:
  74. raise _xai_err(
  75. f"xAI OAuth state is missing {field}. {_RELOGIN}", f"xai_auth_missing_{field}", relogin=True,
  76. )
  77. return {
  78. "tokens": tokens, "last_refresh": state.get("last_refresh"),
  79. "discovery": state.get("discovery") or {}, "redirect_uri": state.get("redirect_uri"),
  80. }
  81. def _write_through_xai_oauth_to_global_root(state: dict[str, Any]) -> None:
  82. """Best-effort persist of a rotated xAI grant into the global-root auth.json.
  83. xAI rotates refresh_token on every refresh, so a profile that refreshed a root-resolved grant
  84. must write the chain back to root. Touches only root ``providers.xai-oauth``; swallows all
  85. errors (root-stale is better than breaking the profile's own save).
  86. """
  87. from hermes_cli.auth import _global_auth_file_path, _persist_provider_state_to_store
  88. global_path = _global_auth_file_path()
  89. if global_path is None: # classic mode (profile == root); the profile save already hit root
  90. return
  91. # Seat belt: under pytest never write the real ~/.hermes/auth.json (mirrors the read-side guard
  92. # in _load_global_auth_store). Uses raw HOME, not Path.home(), which fixtures may monkeypatch.
  93. real_home_env = os.environ.get("HOME", "") if os.environ.get("PYTEST_CURRENT_TEST") else ""
  94. if real_home_env:
  95. real_root = Path(real_home_env) / ".hermes" / "auth.json"
  96. try:
  97. if global_path.resolve(strict=False) == real_root.resolve(strict=False):
  98. return
  99. except Exception:
  100. return
  101. try:
  102. _persist_provider_state_to_store("xai-oauth", state, global_path, set_active=False)
  103. except Exception as exc: # pragma: no cover - best effort
  104. logger.debug("xAI OAuth: write-through to global root failed: %s", exc)
  105. def _save_xai_oauth_tokens(
  106. tokens: dict[str, Any], *, discovery: Optional[dict[str, Any]] = None, redirect_uri: str = "",
  107. last_refresh: Optional[str] = None, auth_mode: str = "oauth_device_code",
  108. set_active: bool = True,
  109. ) -> None:
  110. """Persist xAI OAuth tokens; *set_active* also promotes ``xai-oauth`` to ``active_provider``.
  111. Pass ``set_active=False`` for side-tool bootstrap (TTS/setup, tools config, dashboard, refresh)
  112. so inference routing is unchanged.
  113. """
  114. from hermes_cli.auth import _auth_store_lock, _global_auth_file_path, _load_auth_store, _load_provider_state_with_source, _same_path, _save_auth_store, _store_provider_state, _utc_now_z, _write_through_xai_oauth_to_global_root
  115. if last_refresh is None:
  116. last_refresh = _utc_now_z()
  117. with _auth_store_lock():
  118. auth_store = _load_auth_store()
  119. # A profile lacking its own xai-oauth block reads root's grant via fallback; refreshing it
  120. # must write the rotated chain back to root or root keeps a revoked refresh token. Decide by
  121. # where the grant was resolved FROM (key presence lies: _store_provider_state creates it).
  122. state, source_path = _load_provider_state_with_source(auth_store, "xai-oauth")
  123. state = state if state is not None else {}
  124. state.update(tokens=tokens, last_refresh=last_refresh, auth_mode=auth_mode)
  125. if discovery:
  126. state["discovery"] = discovery
  127. if redirect_uri:
  128. state["redirect_uri"] = redirect_uri
  129. global_root = _global_auth_file_path()
  130. if source_path is not None and global_root is not None and _same_path(source_path, global_root):
  131. # Root-only write-back: a profile copy would shadow root and disable write-through.
  132. _write_through_xai_oauth_to_global_root(state)
  133. else:
  134. _store_provider_state(auth_store, "xai-oauth", state, set_active=set_active)
  135. _save_auth_store(auth_store)
  136. def _xai_jwt_exp(access_token: Any) -> Optional[float]:
  137. """``exp`` claim of a JWT-shaped access token, or None when absent/undecodable."""
  138. if not isinstance(access_token, str) or "." not in access_token:
  139. return None
  140. try:
  141. parts = access_token.split(".")
  142. if len(parts) < 2:
  143. return None
  144. payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
  145. exp = json.loads(base64.urlsafe_b64decode(payload_b64.encode("ascii")).decode("utf-8")).get("exp")
  146. return float(exp) if isinstance(exp, (int, float)) else None
  147. except Exception:
  148. return None
  149. def _xai_access_token_is_expiring(access_token: str, skew_seconds: int = 0) -> bool:
  150. exp = _xai_jwt_exp(access_token)
  151. return exp is not None and exp <= time.time() + max(0, int(skew_seconds))
  152. def _xai_proactive_refresh_skew_seconds(access_token: str) -> int:
  153. """Proactive-refresh lead time before JWT ``exp``.
  154. Device-code logins often return ~15-minute JWTs; the full hour-long skew would refresh on every
  155. resolution, burning single-use refresh tokens and racing callers into ``invalid_grant``.
  156. """
  157. max_skew = XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS
  158. exp = _xai_jwt_exp(access_token)
  159. if exp is None:
  160. return max_skew
  161. remaining = exp - time.time()
  162. return min(120, max_skew) if 0 < remaining <= 45 * 60 else max_skew
  163. def _is_xai_origin_host(host: str) -> bool:
  164. """``x.ai`` is the bare apex, so an exact match or any ``.x.ai`` suffix is accepted."""
  165. return host == "x.ai" or host.endswith(".x.ai")
  166. def _xai_url_problem(url: str) -> tuple[Optional[str], str]:
  167. """``(problem, host)`` — problem is ``"scheme"``, ``"host"``, ``"origin"`` or None when *url* is HTTPS on x.ai."""
  168. parsed = urlparse(url)
  169. host = (parsed.hostname or "").lower()
  170. if parsed.scheme != "https":
  171. return "scheme", host
  172. if not host:
  173. return "host", host
  174. if not _is_xai_origin_host(host):
  175. return "origin", host
  176. return None, host
  177. def _xai_validate_oauth_endpoint(url: str, *, field: str) -> str:
  178. """Refuse a discovery endpoint that isn't HTTPS on the xAI origin.
  179. Discovery is cached in auth.json, so one MITM at login could plant a ``token_endpoint`` that
  180. receives the refresh_token forever; pinning scheme + host (RFC 8414 §2) removes that.
  181. """
  182. problem, host = _xai_url_problem(url)
  183. if problem is None:
  184. return url
  185. message = {
  186. "scheme": f"xAI OIDC discovery returned a non-HTTPS {field}: {url!r}.",
  187. "host": f"xAI OIDC discovery {field} is missing a hostname: {url!r}.",
  188. "origin": (
  189. f"xAI OIDC discovery {field} host {host!r} is not on the xAI origin "
  190. f"(expected x.ai or a *.x.ai subdomain). Refusing to use a cached "
  191. f"endpoint that may have been substituted by a MITM during initial "
  192. f"discovery; re-authenticate with `hermes model` to re-fetch."
  193. ),
  194. }[problem]
  195. raise _xai_err(message, "xai_discovery_invalid")
  196. def _xai_validate_inference_base_url(value: str, *, fallback: str) -> str:
  197. """Pin the OAuth inference base_url to ``*.x.ai``; warn and use *fallback* on rejection.
  198. Warn-not-raise: a bad env var must not deadlock auth, but the bearer must never leak elsewhere.
  199. """
  200. candidate = (value or "").strip().rstrip("/")
  201. if not candidate:
  202. return fallback
  203. try:
  204. problem, host = _xai_url_problem(candidate)
  205. except Exception:
  206. logger.warning("Ignoring malformed xAI base_url override %r; using %s instead.", candidate, fallback)
  207. return fallback
  208. if problem is None:
  209. return candidate
  210. if problem == "scheme":
  211. logger.warning(
  212. "Refusing non-HTTPS xAI base_url override %r (xai-oauth bearer would "
  213. "be sent in cleartext); falling back to %s.",
  214. candidate, fallback,
  215. )
  216. elif problem == "host":
  217. logger.warning("Ignoring xAI base_url override %r with no hostname; using %s instead.", candidate, fallback)
  218. else:
  219. logger.warning(
  220. "Refusing xAI base_url override %r — host %r is not on the xAI origin "
  221. "(expected x.ai or a *.x.ai subdomain). The xai-oauth bearer is only "
  222. "valid against xAI's inference API; sending it elsewhere would leak "
  223. "the credential. Falling back to %s.",
  224. candidate, host, fallback,
  225. )
  226. return fallback
  227. def _xai_oauth_discovery(timeout_seconds: float = 15.0) -> dict[str, str]:
  228. try:
  229. response = httpx.get(XAI_OAUTH_DISCOVERY_URL, headers={"Accept": "application/json"}, timeout=timeout_seconds)
  230. except Exception as exc:
  231. raise _xai_err(f"xAI OIDC discovery failed: {exc}", "xai_discovery_failed") from exc
  232. if response.status_code != 200:
  233. raise _xai_err(f"xAI OIDC discovery returned status {response.status_code}.", "xai_discovery_failed")
  234. try:
  235. payload = response.json()
  236. except Exception as exc:
  237. raise _xai_err(f"xAI OIDC discovery returned invalid JSON: {exc}", "xai_discovery_invalid_json") from exc
  238. if not isinstance(payload, dict):
  239. raise _xai_err("xAI OIDC discovery response was not a JSON object.", "xai_discovery_incomplete")
  240. endpoints = {k: _clean(payload.get(k)) for k in ("authorization_endpoint", "token_endpoint")}
  241. if not all(endpoints.values()):
  242. raise _xai_err("xAI OIDC discovery response was missing required endpoints.", "xai_discovery_incomplete")
  243. for field, url in endpoints.items():
  244. _xai_validate_oauth_endpoint(url, field=field)
  245. return endpoints
  246. def _xai_tokens_from_payload(payload: dict[str, Any], access_token: str, fallback_refresh: str) -> dict[str, Any]:
  247. """Token block persisted for xAI OAuth; falls back to *fallback_refresh* when none is rotated in."""
  248. return {
  249. "access_token": access_token,
  250. "refresh_token": str(payload.get("refresh_token") or fallback_refresh).strip(),
  251. "id_token": _clean(payload.get("id_token")), "expires_in": payload.get("expires_in"),
  252. "token_type": _clean(payload.get("token_type") or "Bearer") or "Bearer",
  253. }
  254. def refresh_xai_oauth_pure(
  255. access_token: str, refresh_token: str, *, token_endpoint: str = "",
  256. timeout_seconds: float = 20.0,
  257. ) -> dict[str, Any]:
  258. from hermes_cli.auth import _nonempty_str, _utc_now_z, _xai_oauth_discovery
  259. del access_token
  260. if not _nonempty_str(refresh_token):
  261. raise _xai_err(
  262. f"xAI OAuth is missing refresh_token. {_RELOGIN}", "xai_auth_missing_refresh_token", relogin=True,
  263. )
  264. endpoint = token_endpoint.strip() or _xai_oauth_discovery(timeout_seconds)["token_endpoint"]
  265. # Re-validate cached endpoints: an old/hand-edited auth.json may carry a non-xAI token_endpoint
  266. # that would otherwise receive every future refresh_token.
  267. _xai_validate_oauth_endpoint(endpoint, field="token_endpoint")
  268. timeout = httpx.Timeout(max(5.0, float(timeout_seconds)))
  269. with httpx.Client(timeout=timeout, headers={"Accept": "application/json"}) as client:
  270. response = client.post(
  271. endpoint, headers={"Content-Type": "application/x-www-form-urlencoded"},
  272. data={"grant_type": "refresh_token", "client_id": XAI_OAUTH_CLIENT_ID, "refresh_token": refresh_token},
  273. )
  274. if response.status_code != 200:
  275. detail = response.text.strip()
  276. suffix = f" Response: {detail}" if detail else ""
  277. # 403 is almost always a tier/entitlement gate; re-login won't fix it, so use a separate
  278. # code and format_auth_error skips the re-authenticate hint.
  279. # ``403`` from xAI's token endpoint is almost always a tier / entitlement gate (the OAuth grant
  280. # exists but the account isn't on the allowlist for API access). Re-running ``hermes model`` won't
  281. # fix that — surface a separate error code so ``format_auth_error`` doesn't append a misleading
  282. # re-authenticate hint, and point users at the ``XAI_API_KEY`` fallback. See #26847.
  283. if response.status_code == 403:
  284. raise _xai_err(
  285. "xAI token refresh failed with HTTP 403." + suffix
  286. + " This OAuth account is not authorized for xAI API"
  287. " access — xAI may be restricting API/OAuth use to"
  288. " specific SuperGrok tiers despite the in-app"
  289. " subscription being active. Re-logging in won't"
  290. " change that; set ``XAI_API_KEY`` and switch to"
  291. " ``provider: xai`` (API-key path) if available, or"
  292. " upgrade your subscription at https://x.ai/grok.",
  293. "xai_oauth_tier_denied", relogin=False,
  294. )
  295. raise _xai_err(
  296. "xAI token refresh failed." + suffix, "xai_refresh_failed", relogin=response.status_code in {400, 401},
  297. )
  298. payload, refreshed_access = _refresh_payload_access_token(
  299. response, provider="xai-oauth",
  300. invalid_json=("xAI token refresh returned invalid JSON: {exc}", "xai_refresh_invalid_json"),
  301. invalid_json_relogin=False, strict_str=False,
  302. invalid_response=("xAI token refresh response was not a JSON object.", "xai_refresh_invalid_response"),
  303. missing_access=("xAI token refresh response was missing access_token.", "xai_refresh_missing_access_token"),
  304. )
  305. return {**_xai_tokens_from_payload(payload, refreshed_access, refresh_token), "last_refresh": _utc_now_z()}
  306. def _refresh_xai_oauth_tokens(
  307. tokens: dict[str, Any], *, token_endpoint: str, redirect_uri: str = "", timeout_seconds: float
  308. ) -> dict[str, Any]:
  309. # Keep the stored auth_mode (legacy logins may carry ``oauth_pkce``): refresh must not relabel it.
  310. from hermes_cli.auth import _load_auth_store, _load_provider_state, refresh_xai_oauth_pure
  311. try:
  312. state = _load_provider_state(_load_auth_store(), "xai-oauth") or {}
  313. auth_mode = str(state.get("auth_mode") or "oauth_device_code")
  314. except Exception:
  315. auth_mode = "oauth_device_code"
  316. refreshed = refresh_xai_oauth_pure(
  317. _clean(tokens.get("access_token")), _clean(tokens.get("refresh_token")),
  318. token_endpoint=token_endpoint, timeout_seconds=timeout_seconds,
  319. )
  320. updated_tokens = dict(tokens)
  321. updated_tokens["access_token"] = refreshed["access_token"]
  322. updated_tokens["refresh_token"] = refreshed["refresh_token"]
  323. if refreshed.get("id_token"):
  324. updated_tokens["id_token"] = refreshed["id_token"]
  325. if refreshed.get("expires_in") is not None:
  326. updated_tokens["expires_in"] = refreshed["expires_in"]
  327. if refreshed.get("token_type"):
  328. updated_tokens["token_type"] = refreshed["token_type"]
  329. # set_active=False: side tools (TTS) refresh xAI tokens while chat routes elsewhere.
  330. _save_xai_oauth_tokens(
  331. updated_tokens, discovery={"token_endpoint": token_endpoint}, redirect_uri=redirect_uri,
  332. last_refresh=refreshed["last_refresh"], auth_mode=auth_mode, set_active=False,
  333. )
  334. return updated_tokens
  335. def _quarantine_xai_oauth_tokens(exc: AuthError) -> None:
  336. """Clear dead xAI tokens after a terminal (400/401/403) refresh failure so later sessions fail fast.
  337. Best-effort: persistence failures are logged and swallowed; the caller re-raises regardless.
  338. """
  339. from hermes_cli.auth import _last_auth_error_marker, _load_auth_store, _load_provider_state, _save_auth_store, _store_provider_state
  340. try:
  341. store = _load_auth_store()
  342. state = _load_provider_state(store, "xai-oauth") or {}
  343. tokens = dict(state.get("tokens") or {})
  344. tokens.pop("access_token", None)
  345. tokens.pop("refresh_token", None)
  346. # Capture the previous singleton tokens BEFORE overwriting them. The pool-sync step uses this to
  347. # distinguish legacy singleton-aliases (which should be refreshed) from independent accounts that
  348. # ``hermes auth add openai-codex`` created (which must not be overwritten — see #39236).
  349. state["tokens"] = tokens
  350. state["last_auth_error"] = _last_auth_error_marker(
  351. "xai-oauth", exc, reason="runtime_refresh_failure", default_code="xai_refresh_failed",
  352. )
  353. _store_provider_state(store, "xai-oauth", state, set_active=False)
  354. _save_auth_store(store)
  355. except Exception as save_exc:
  356. logger.debug("xAI OAuth: failed to persist quarantined state: %s", save_exc)
  357. def _xai_oauth_inference_base_url() -> str:
  358. return _xai_validate_inference_base_url(
  359. os.getenv("HERMES_XAI_BASE_URL", "").strip().rstrip("/") or os.getenv("XAI_BASE_URL", "").strip().rstrip("/"),
  360. fallback=DEFAULT_XAI_OAUTH_BASE_URL,
  361. )
  362. def resolve_xai_oauth_runtime_credentials(
  363. *, force_refresh: bool = False, refresh_if_expiring: bool = True,
  364. refresh_skew_seconds: Optional[int] = None,
  365. ) -> dict[str, Any]:
  366. from hermes_cli.auth import _auth_store_lock, _is_terminal_xai_oauth_refresh_error, _refresh_xai_oauth_tokens, _xai_oauth_discovery
  367. def _should_refresh(data: dict[str, Any]) -> bool:
  368. access_token = _clean(data["tokens"].get("access_token"))
  369. skew = (
  370. int(refresh_skew_seconds) if refresh_skew_seconds is not None
  371. else _xai_proactive_refresh_skew_seconds(access_token)
  372. )
  373. return bool(force_refresh) or bool(
  374. refresh_if_expiring and _xai_access_token_is_expiring(access_token, skew)
  375. )
  376. data = _read_xai_oauth_tokens()
  377. tokens = dict(data["tokens"])
  378. refresh_timeout_seconds = env_float("HERMES_XAI_REFRESH_TIMEOUT_SECONDS", 20)
  379. if _should_refresh(data):
  380. with _auth_store_lock(timeout_seconds=max(float(AUTH_LOCK_TIMEOUT_SECONDS), refresh_timeout_seconds + 5.0)):
  381. # Re-read under the lock: a concurrent caller may already have rotated the grant.
  382. data = _read_xai_oauth_tokens(_lock=False)
  383. tokens = dict(data["tokens"])
  384. if _should_refresh(data):
  385. token_endpoint = (
  386. _clean(dict(data.get("discovery") or {}).get("token_endpoint"))
  387. or _xai_oauth_discovery(refresh_timeout_seconds)["token_endpoint"]
  388. )
  389. try:
  390. tokens = _refresh_xai_oauth_tokens(
  391. tokens, token_endpoint=token_endpoint, redirect_uri=_clean(data.get("redirect_uri")),
  392. timeout_seconds=refresh_timeout_seconds,
  393. )
  394. except AuthError as exc:
  395. if _is_terminal_xai_oauth_refresh_error(exc):
  396. _quarantine_xai_oauth_tokens(exc)
  397. raise
  398. return {
  399. "provider": "xai-oauth",
  400. "base_url": _xai_oauth_inference_base_url(),
  401. "api_key": _clean(tokens.get("access_token")),
  402. "source": "hermes-auth-store",
  403. "last_refresh": data.get("last_refresh"),
  404. # Display only; auth.json may still carry a legacy ``oauth_pkce`` label.
  405. "auth_mode": "oauth_device_code",
  406. }
  407. def _login_xai_oauth(args, pconfig: ProviderConfig, *, force_new_login: bool = False) -> None:
  408. from hermes_cli.auth import _is_remote_session, _offer_existing_oauth_credentials, _print_login_success, _update_config_for_provider, _xai_oauth_device_code_login, resolve_xai_oauth_runtime_credentials, unsuppress_credential_source
  409. del pconfig
  410. if not force_new_login and _offer_existing_oauth_credentials(
  411. "xai-oauth",
  412. resolve=resolve_xai_oauth_runtime_credentials,
  413. is_expiring=_xai_access_token_is_expiring,
  414. display_name="xAI OAuth",
  415. default_base_url=DEFAULT_XAI_OAUTH_BASE_URL,
  416. ):
  417. return
  418. print()
  419. print("Signing in to xAI Grok OAuth (SuperGrok / Premium+)...")
  420. print("(Hermes creates its own local OAuth session)")
  421. print()
  422. timeout_seconds = float(getattr(args, "timeout", None) or 20.0)
  423. open_browser = not getattr(args, "no_browser", False)
  424. if _is_remote_session():
  425. open_browser = False
  426. creds = _xai_oauth_device_code_login(timeout_seconds=timeout_seconds, open_browser=open_browser)
  427. _save_xai_oauth_tokens(
  428. creds["tokens"], discovery=creds.get("discovery"),
  429. redirect_uri=creds.get("redirect_uri", ""), last_refresh=creds.get("last_refresh"),
  430. auth_mode="oauth_device_code",
  431. )
  432. # Explicit re-login re-enables the credential: clear the ``device_code`` suppression marker left
  433. # by ``hermes auth remove xai-oauth``. Deliberately NOT inside _save_xai_oauth_tokens — the
  434. # refresh hot path shares that helper and must never mutate suppression state.
  435. unsuppress_credential_source("xai-oauth", "device_code")
  436. config_path = _update_config_for_provider("xai-oauth", creds.get("base_url", DEFAULT_XAI_OAUTH_BASE_URL))
  437. _print_login_success("xai-oauth", config_path, show_auth_state=True)
  438. def _xai_oauth_request_device_code(client: httpx.Client, *, scope: str = XAI_OAUTH_SCOPE) -> dict[str, Any]:
  439. response = client.post(
  440. XAI_OAUTH_DEVICE_CODE_URL, headers=_FORM_JSON_HEADERS, data={"client_id": XAI_OAUTH_CLIENT_ID, "scope": scope},
  441. )
  442. if response.status_code != 200:
  443. raise _xai_err(
  444. f"xAI device-code request failed (HTTP {response.status_code})."
  445. + (f" Response: {response.text.strip()}" if response.text else ""),
  446. "device_code_request_failed",
  447. )
  448. payload = response.json()
  449. required = ("device_code", "user_code", "verification_uri", "verification_uri_complete", "expires_in", "interval")
  450. missing = [key for key in required if key not in payload]
  451. if missing:
  452. raise _xai_err(f"xAI device-code response missing fields: {', '.join(missing)}", "device_code_invalid")
  453. return payload
  454. def _xai_oauth_poll_device_token(
  455. client: httpx.Client, *, token_endpoint: str, device_code: str, expires_in: int,
  456. poll_interval: int,
  457. ) -> dict[str, Any]:
  458. from hermes_cli.auth import _poll_device_token_generic
  459. def _validate(payload: dict[str, Any]) -> None:
  460. for field_name, article in (("access_token", "an"), ("refresh_token", "a")):
  461. if not payload.get(field_name):
  462. raise _xai_err(
  463. f"xAI device-code token response did not include {article} {field_name}.",
  464. "xai_device_token_invalid",
  465. )
  466. def _error(response, error_payload) -> Exception:
  467. description = error_payload.get("error_description") or error_payload.get("error") or response.text
  468. err = _xai_err(f"xAI device-code token polling failed: {description}", "xai_device_token_failed")
  469. err.oauth_error_code = str(error_payload.get("error") or "") # a declined or expired code is a walk-away
  470. return err
  471. return _poll_device_token_generic(
  472. lambda: client.post(
  473. token_endpoint, headers=_FORM_JSON_HEADERS,
  474. data={"grant_type": DEVICE_CODE_GRANT_TYPE, "client_id": XAI_OAUTH_CLIENT_ID, "device_code": device_code},
  475. ),
  476. expires_in=int(expires_in),
  477. poll_interval=max(1, int(poll_interval)),
  478. validate_success=_validate,
  479. on_non_json_error=lambda _r: _xai_err(
  480. "xAI device-code token polling returned a non-JSON error response.", "xai_device_token_failed",
  481. ),
  482. on_error=_error,
  483. on_timeout=lambda: _xai_err("Timed out waiting for xAI device authorization.", "device_code_timeout"),
  484. )
  485. def _xai_oauth_device_code_login(*, timeout_seconds: float = 20.0, open_browser: bool = True) -> dict[str, Any]:
  486. from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session, _print_device_code_instructions, _utc_now_z, _xai_oauth_discovery, _xai_oauth_poll_device_token
  487. discovery = _xai_oauth_discovery(timeout_seconds)
  488. timeout = httpx.Timeout(max(20.0, timeout_seconds))
  489. with httpx.Client(timeout=timeout, headers={"Accept": "application/json"}) as client:
  490. device_data = _xai_oauth_request_device_code(client)
  491. interval = int(device_data["interval"])
  492. _print_device_code_instructions(
  493. str(device_data.get("verification_uri_complete") or device_data["verification_uri"]),
  494. str(device_data["user_code"]),
  495. open_browser=open_browser and not _is_remote_session() and _can_open_graphical_browser(),
  496. swallow_open_errors=True,
  497. )
  498. print(f"Waiting for approval (polling every {max(1, interval)}s)...")
  499. payload = _xai_oauth_poll_device_token(
  500. client, token_endpoint=discovery["token_endpoint"],
  501. device_code=str(device_data["device_code"]), expires_in=int(device_data["expires_in"]),
  502. poll_interval=interval,
  503. )
  504. access_token, refresh_token = _token_pair(payload)
  505. if not access_token or not refresh_token:
  506. raise _xai_err("xAI device-code token response was missing required tokens.", "xai_device_token_invalid")
  507. return {
  508. "tokens": _xai_tokens_from_payload(payload, access_token, refresh_token),
  509. "discovery": discovery, "redirect_uri": "", "base_url": _xai_oauth_inference_base_url(),
  510. "last_refresh": _utc_now_z(), "source": "oauth-device-code",
  511. }