auth_minimax.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. """MiniMax OAuth (user-code grant) login, refresh and runtime credentials.
  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 hashlib
  9. import json
  10. import time
  11. import uuid
  12. from datetime import datetime, timezone, UTC
  13. from typing import Any, Callable, Dict, Optional, TYPE_CHECKING
  14. from hermes_cli.auth_constants import (
  15. AuthError, MINIMAX_OAUTH_GRANT_TYPE, MINIMAX_OAUTH_REFRESH_SKEW_SECONDS, MINIMAX_OAUTH_SCOPE,
  16. _FORM_JSON_HEADERS, _minimax_err, httpx,
  17. )
  18. if TYPE_CHECKING: # annotation-only; the runtime import would be a cycle
  19. from hermes_cli.auth import ProviderConfig
  20. logger = logging.getLogger("hermes_cli.auth")
  21. _MINIMAX_OAUTH_ERROR_BODY_LIMIT = 16 * 1024
  22. def _minimax_response_error_text(response: httpx.Response, *, limit: int = _MINIMAX_OAUTH_ERROR_BODY_LIMIT) -> str:
  23. """Return a bounded error body from a streamed MiniMax OAuth response."""
  24. limit = max(0, int(limit))
  25. try:
  26. if getattr(response, "is_stream_consumed", False):
  27. text = response.text
  28. return text[:limit] + ("...[truncated]" if len(text) > limit else "")
  29. # Read at most limit+1 bytes so truncation can be detected without buffering the whole body.
  30. chunks: list[bytes] = []
  31. total = 0
  32. for chunk in response.iter_bytes():
  33. if not chunk:
  34. continue
  35. chunks.append(chunk[: limit + 1 - total])
  36. total += len(chunks[-1])
  37. if total > limit:
  38. break
  39. raw = b"".join(chunks)
  40. text = raw[:limit].decode(response.encoding or "utf-8", errors="replace")
  41. return text + ("...[truncated]" if len(raw) > limit else "")
  42. finally:
  43. response.close()
  44. def _minimax_post_form(client: httpx.Client, url: str, *, data: dict[str, Any], headers: dict[str, str]) -> httpx.Response:
  45. """POST a MiniMax OAuth form without eagerly reading error bodies."""
  46. response = client.send(client.build_request("POST", url, data=data, headers=headers), stream=True)
  47. if response.status_code == 200:
  48. response.read()
  49. return response
  50. def _minimax_pkce_pair() -> tuple:
  51. """Generate (code_verifier, code_challenge_S256, state) for MiniMax OAuth."""
  52. import secrets
  53. verifier = secrets.token_urlsafe(64)[:96]
  54. challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")
  55. return verifier, challenge, secrets.token_urlsafe(16)
  56. def _minimax_request_user_code(
  57. client: httpx.Client, *, portal_base_url: str, client_id: str, code_challenge: str, state: str
  58. ) -> dict[str, Any]:
  59. response = _minimax_post_form(
  60. client,
  61. f"{portal_base_url}/oauth/code",
  62. data={
  63. "response_type": "code", "client_id": client_id, "scope": MINIMAX_OAUTH_SCOPE,
  64. "code_challenge": code_challenge, "code_challenge_method": "S256", "state": state,
  65. },
  66. headers={**_FORM_JSON_HEADERS, "x-request-id": str(uuid.uuid4())},
  67. )
  68. if response.status_code != 200:
  69. body = _minimax_response_error_text(response)
  70. raise _minimax_err(f"MiniMax OAuth authorization failed: {body or response.reason_phrase}", "authorization_failed")
  71. payload = response.json()
  72. for field in ("user_code", "verification_uri", "expired_in"):
  73. if field not in payload:
  74. raise _minimax_err(f"MiniMax OAuth response missing field: {field}", "authorization_incomplete")
  75. if payload.get("state") != state:
  76. raise _minimax_err("MiniMax OAuth state mismatch (possible CSRF).", "state_mismatch")
  77. return payload
  78. def _minimax_expired_in_looks_like_unix_ms(expired_in: int, *, now_ms: int) -> bool:
  79. """True if ``expired_in`` is plausibly a unix-ms absolute time (vs TTL seconds)."""
  80. return int(expired_in) > (now_ms // 2)
  81. def _minimax_resolve_token_expiry_unix(expired_in: int, *, now: datetime) -> float:
  82. """Return access-token expiry as unix seconds (MiniMax uses ms epoch or TTL seconds)."""
  83. raw = int(expired_in)
  84. if _minimax_expired_in_looks_like_unix_ms(raw, now_ms=int(now.timestamp() * 1000)):
  85. return raw / 1000.0
  86. return now.timestamp() + max(1, raw)
  87. def _minimax_expiry_fields(expired_in: Any) -> dict[str, Any]:
  88. """``obtained_at`` / ``expires_at`` / ``expires_in`` derived from a MiniMax ``expired_in``."""
  89. now = datetime.now(UTC)
  90. expires_at_unix = _minimax_resolve_token_expiry_unix(int(expired_in), now=now)
  91. return {
  92. "obtained_at": now.isoformat(),
  93. "expires_at": datetime.fromtimestamp(expires_at_unix, tz=UTC).isoformat(),
  94. "expires_in": max(0, int(expires_at_unix - now.timestamp())),
  95. }
  96. def _minimax_poll_token(
  97. client: httpx.Client, *, portal_base_url: str, client_id: str,
  98. user_code: str, code_verifier: str, expired_in: int, interval_ms: Optional[int],
  99. ) -> dict[str, Any]:
  100. # expired_in is a unix-ms timestamp upstream (OpenClaw) but small values are TTL seconds.
  101. deadline = _minimax_resolve_token_expiry_unix(expired_in, now=datetime.now(UTC))
  102. interval = max(2.0, (interval_ms or 2000) / 1000.0)
  103. while time.time() < deadline:
  104. response = _minimax_post_form(
  105. client,
  106. f"{portal_base_url}/oauth/token",
  107. data={
  108. "grant_type": MINIMAX_OAUTH_GRANT_TYPE, "client_id": client_id,
  109. "user_code": user_code, "code_verifier": code_verifier,
  110. },
  111. headers=_FORM_JSON_HEADERS,
  112. )
  113. if response.status_code != 200:
  114. error_text = _minimax_response_error_text(response)
  115. try:
  116. payload = json.loads(error_text) if error_text else {}
  117. except Exception:
  118. payload = {}
  119. msg = (payload.get("base_resp", {}) or {}).get("status_msg") or error_text
  120. raise _minimax_err(f"MiniMax OAuth error: {msg or 'unknown'}", "token_exchange_failed")
  121. try:
  122. payload = response.json() if response.text else {}
  123. except Exception:
  124. payload = {}
  125. status = payload.get("status")
  126. if status == "error":
  127. raise _minimax_err("MiniMax OAuth reported an error. Please try again later.", "authorization_denied")
  128. if status == "success":
  129. if not all(payload.get(k) for k in ("access_token", "refresh_token", "expired_in")):
  130. raise _minimax_err("MiniMax OAuth success payload missing required token fields.", "token_incomplete")
  131. return payload
  132. # "pending" or any other status -> keep polling
  133. time.sleep(interval)
  134. raise _minimax_err("MiniMax OAuth timed out before authorization completed.", "timeout")
  135. def _minimax_save_auth_state(auth_state: dict[str, Any], *, set_active: bool = True) -> None:
  136. """Persist MiniMax OAuth state to Hermes auth store (~/.hermes/auth.json).
  137. ``set_active=False`` rewrites credentials without making minimax-oauth the
  138. active provider (``_save_provider_state_to_source``'s rule: a token refresh
  139. rewrites credentials, not the user's choice of provider); only
  140. ``_minimax_oauth_login`` — the user just chose the provider — sets active.
  141. """
  142. from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store, _store_provider_state
  143. with _auth_store_lock():
  144. auth_store = _load_auth_store()
  145. _store_provider_state(auth_store, "minimax-oauth", auth_state, set_active=set_active)
  146. _save_auth_store(auth_store)
  147. def _minimax_oauth_login(*, region: str = "global", open_browser: bool = True, timeout_seconds: float = 15.0) -> dict[str, Any]:
  148. """Run MiniMax OAuth flow, persist tokens, return auth state dict."""
  149. from hermes_cli.auth import PROVIDER_REGISTRY, _can_open_graphical_browser, _is_remote_session, _minimax_pkce_pair, _minimax_request_user_code, _minimax_save_auth_state, _print_device_code_instructions
  150. pconfig = PROVIDER_REGISTRY["minimax-oauth"]
  151. if region == "cn":
  152. portal_base_url = pconfig.extra["cn_portal_base_url"]
  153. inference_base_url = pconfig.extra["cn_inference_base_url"]
  154. else:
  155. portal_base_url = pconfig.portal_base_url
  156. inference_base_url = pconfig.inference_base_url
  157. verifier, challenge, state = _minimax_pkce_pair()
  158. if _is_remote_session():
  159. open_browser = False
  160. print(f"Starting Hermes login via MiniMax ({region}) OAuth...")
  161. print(f"Portal: {portal_base_url}")
  162. with httpx.Client(timeout=httpx.Timeout(timeout_seconds), headers={"Accept": "application/json"},
  163. follow_redirects=True) as client:
  164. code_data = _minimax_request_user_code(
  165. client, portal_base_url=portal_base_url, client_id=pconfig.client_id, code_challenge=challenge, state=state,
  166. )
  167. _print_device_code_instructions(
  168. str(code_data["verification_uri"]), str(code_data["user_code"]),
  169. open_browser=open_browser and _can_open_graphical_browser(),
  170. )
  171. interval_raw = code_data.get("interval")
  172. print("Waiting for approval...")
  173. token_data = _minimax_poll_token(
  174. client, portal_base_url=portal_base_url, client_id=pconfig.client_id,
  175. user_code=str(code_data["user_code"]), code_verifier=verifier,
  176. expired_in=int(code_data["expired_in"]),
  177. interval_ms=int(interval_raw) if interval_raw is not None else None,
  178. )
  179. auth_state = {
  180. "provider": "minimax-oauth",
  181. "region": region,
  182. "portal_base_url": portal_base_url,
  183. "inference_base_url": inference_base_url,
  184. "client_id": pconfig.client_id,
  185. "scope": MINIMAX_OAUTH_SCOPE,
  186. "token_type": token_data.get("token_type", "Bearer"),
  187. "access_token": token_data["access_token"],
  188. "refresh_token": token_data["refresh_token"],
  189. "resource_url": token_data.get("resource_url"),
  190. **_minimax_expiry_fields(token_data["expired_in"]),
  191. }
  192. _minimax_save_auth_state(auth_state)
  193. print("\u2713 MiniMax OAuth login successful.")
  194. if msg := token_data.get("notification_message"):
  195. print(f"Note from MiniMax: {msg}")
  196. return auth_state
  197. def _refresh_minimax_oauth_state(state: dict[str, Any], *, timeout_seconds: float = 15.0, force: bool = False) -> dict[str, Any]:
  198. """Refresh MiniMax OAuth access token if close to expiry (or forced)."""
  199. from hermes_cli.auth import _minimax_save_auth_state
  200. if not state.get("refresh_token"):
  201. raise _minimax_err("MiniMax OAuth state has no refresh_token; please re-login.", "no_refresh_token", relogin=True)
  202. try:
  203. expires_at = datetime.fromisoformat(state.get("expires_at", "")).timestamp()
  204. except Exception:
  205. expires_at = 0.0
  206. if not force and (expires_at - time.time()) > MINIMAX_OAUTH_REFRESH_SKEW_SECONDS:
  207. return state
  208. with httpx.Client(timeout=httpx.Timeout(timeout_seconds), follow_redirects=True) as client:
  209. response = _minimax_post_form(
  210. client,
  211. f"{state['portal_base_url']}/oauth/token",
  212. data={"grant_type": "refresh_token", "client_id": state["client_id"], "refresh_token": state["refresh_token"]},
  213. headers=_FORM_JSON_HEADERS,
  214. )
  215. # Non-200 reads a STREAMED body, so it must run inside the client context (iter_bytes()
  216. # after close raises StreamClosed); the 200 body was already read by _minimax_post_form.
  217. if response.status_code != 200:
  218. body = _minimax_response_error_text(response)
  219. body_lower = body.lower()
  220. relogin = any(m in body_lower for m in ("invalid_grant", "refresh_token_reused", "invalid_refresh_token"))
  221. raise _minimax_err(
  222. f"MiniMax OAuth refresh failed: {body or response.reason_phrase}", "refresh_failed", relogin=relogin,
  223. )
  224. payload = response.json()
  225. if payload.get("status") != "success":
  226. raise _minimax_err("MiniMax OAuth refresh did not return success.", "refresh_failed", relogin=True)
  227. new_state = {
  228. **state,
  229. "access_token": payload["access_token"],
  230. "refresh_token": payload.get("refresh_token", state["refresh_token"]),
  231. **_minimax_expiry_fields(payload["expired_in"]),
  232. }
  233. # set_active=False: an aux-triggered refresh rewrites credentials, not the user's
  234. # choice of provider (same rule as _save_provider_state_to_source).
  235. _minimax_save_auth_state(new_state, set_active=False)
  236. return new_state
  237. def _minimax_oauth_quarantine_on_terminal_refresh(state: dict[str, Any], exc: AuthError) -> None:
  238. """Wipe dead tokens from auth.json after a terminal refresh failure (fail fast, no network retry)."""
  239. from hermes_cli.auth import _minimax_save_auth_state, _quarantine_flat_oauth_state
  240. if not (exc.relogin_required and state.get("refresh_token")):
  241. return
  242. _quarantine_flat_oauth_state(state, "minimax-oauth", exc)
  243. try:
  244. # set_active=False: wiping dead tokens is hygiene, not a provider choice.
  245. _minimax_save_auth_state(state, set_active=False)
  246. except Exception as _save_exc:
  247. logger.debug("MiniMax OAuth: failed to persist quarantined state: %s", _save_exc)
  248. def _minimax_fresh_state() -> dict[str, Any]:
  249. """Load the MiniMax OAuth state and refresh it if near expiry; quarantine on terminal failure.
  250. The whole read → refresh → save runs inside ``_auth_store_lock`` (reentrant, so the
  251. inner ``_minimax_save_auth_state`` re-locks harmlessly): MiniMax refresh tokens are
  252. single-use and rotate, so two concurrent consumers (main agent + an aux task) that
  253. both see a near-expiry token would otherwise race — the loser replays the consumed
  254. token, gets ``refresh_token_reused``, and the quarantine wipes the winner's fresh
  255. tokens. Re-reading inside the lock makes the second caller see the first caller's
  256. new expiry and skip its own refresh. The lock timeout outlives the refresh POST so
  257. a waiter adopts the rotated pair instead of timing out (codex pattern).
  258. """
  259. from hermes_cli.auth import (
  260. AUTH_LOCK_TIMEOUT_SECONDS, _auth_store_lock, _refresh_minimax_oauth_state,
  261. get_provider_auth_state,
  262. )
  263. with _auth_store_lock(timeout_seconds=max(AUTH_LOCK_TIMEOUT_SECONDS, 15.0 + 5.0)):
  264. state = get_provider_auth_state("minimax-oauth")
  265. if not state or not state.get("access_token"):
  266. raise _minimax_err(
  267. "Not logged into MiniMax OAuth. Run `hermes model` and select MiniMax (OAuth).",
  268. "not_logged_in", relogin=True,
  269. )
  270. try:
  271. return _refresh_minimax_oauth_state(state)
  272. except AuthError as exc:
  273. _minimax_oauth_quarantine_on_terminal_refresh(state, exc)
  274. raise
  275. def build_minimax_oauth_token_provider() -> Callable[[], str]:
  276. """Zero-arg callable yielding a fresh MiniMax access token.
  277. The Anthropic SDK caches ``api_key`` at construction; MiniMax tokens live ~15 minutes, so a
  278. static bearer would start 401-ing mid-session.
  279. """
  280. def _provide() -> str:
  281. token = _minimax_fresh_state().get("access_token")
  282. if not token:
  283. raise _minimax_err("MiniMax OAuth state has no access_token after refresh.", "no_access_token", relogin=True)
  284. return token
  285. from agent.credential_source import MINIMAX_OAUTH, tag_credential_source
  286. return tag_credential_source(_provide, MINIMAX_OAUTH)
  287. def resolve_minimax_oauth_runtime_credentials(
  288. *, min_token_ttl_seconds: int = MINIMAX_OAUTH_REFRESH_SKEW_SECONDS,
  289. as_token_provider: bool = False,
  290. ) -> dict[str, Any]:
  291. """Return {provider, api_key, base_url, source}; string ``api_key`` by default (``hermes status`` contract)."""
  292. state = _minimax_fresh_state()
  293. return {
  294. "provider": "minimax-oauth",
  295. "api_key": build_minimax_oauth_token_provider() if as_token_provider else state["access_token"],
  296. "base_url": state["inference_base_url"].rstrip("/"),
  297. "source": "oauth",
  298. }
  299. def _login_minimax_oauth(args, pconfig: ProviderConfig) -> None:
  300. """CLI entry for MiniMax OAuth login."""
  301. from hermes_cli.auth import format_auth_error
  302. try:
  303. _minimax_oauth_login(
  304. region=getattr(args, "region", None) or "global",
  305. open_browser=not getattr(args, "no_browser", False),
  306. timeout_seconds=getattr(args, "timeout", None) or 15.0,
  307. )
  308. except AuthError as exc:
  309. print(format_auth_error(exc))
  310. raise SystemExit(1)