auth_constants.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. """Shared constants, the lazy ``httpx`` proxy and :class:`AuthError` for the auth package.
  2. Pure leaf: imports nothing from ``hermes_cli.auth`` so the per-provider modules
  3. (``auth_nous``, ``auth_codex``, ...) can import it at module scope without cycles."""
  4. from __future__ import annotations
  5. import base64
  6. import json
  7. from typing import Any, Callable, Dict, Optional
  8. # httpx is imported lazily (~30ms) because hermes_cli.auth is on the interactive-CLI startup path
  9. # (credential_pool -> auxiliary_client -> cli_commands_mixin). The proxy resolves on first attribute
  10. # access; ``from __future__ import annotations`` keeps ``httpx.Client`` annotations unevaluated.
  11. import importlib as _importlib
  12. from typing import TYPE_CHECKING
  13. if TYPE_CHECKING:
  14. import httpx
  15. else:
  16. class _LazyHttpx:
  17. __slots__ = ("_mod",)
  18. def __init__(self) -> None:
  19. object.__setattr__(self, "_mod", None)
  20. def _resolve(self):
  21. mod = object.__getattribute__(self, "_mod")
  22. if mod is None:
  23. mod = _importlib.import_module("httpx")
  24. object.__setattr__(self, "_mod", mod)
  25. return mod
  26. def __getattr__(self, name):
  27. return getattr(self._resolve(), name)
  28. # set/del forward to the real module so monkeypatch.setattr("hermes_cli.auth.httpx.Client")
  29. # keeps working in tests.
  30. def __setattr__(self, name, value):
  31. setattr(self._resolve(), name, value)
  32. def __delattr__(self, name):
  33. delattr(self._resolve(), name)
  34. httpx = _LazyHttpx()
  35. # ── Constants ───────────────────────────────────────────────────────────────────────────────────────
  36. AUTH_STORE_VERSION = 1
  37. AUTH_LOCK_TIMEOUT_SECONDS = 15.0
  38. # Nous Portal defaults
  39. DEFAULT_NOUS_PORTAL_URL = "https://portal.nousresearch.com"
  40. DEFAULT_NOUS_INFERENCE_URL = "https://inference-api.nousresearch.com/v1"
  41. # The free tier's (anonymous account) inference host. NAS hands it to the client on every token
  42. # exchange (``inference_base_url``); this literal is the fallback when that field is absent or fails
  43. # the host allowlist, because the paid host cross-refuses an anonymous JWT with a 400.
  44. DEFAULT_NOUS_WELCOME_URL = "https://welcome-api.nousresearch.com/v1"
  45. DEFAULT_NOUS_CLIENT_ID = "hermes-cli"
  46. # On every guest minted since the welcome trial: True when the desktop's first install claimed it
  47. # (``hermes_cli.welcome_trial``), False for a connector mint. Absent = minted before the trial existed.
  48. WELCOME_CLAIM_FLAG = "welcome_claim"
  49. NOUS_INFERENCE_INVOKE_SCOPE = "inference:invoke"
  50. NOUS_BILLING_MANAGE_SCOPE = "billing:manage"
  51. DEFAULT_NOUS_SCOPE = NOUS_INFERENCE_INVOKE_SCOPE
  52. NOUS_DEVICE_CODE_SOURCE = "device_code"
  53. NOUS_AUTH_PATH_INVOKE_JWT = "invoke_jwt"
  54. ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120 # refresh 2 min before expiry
  55. NOUS_INVOKE_JWT_MIN_TTL_SECONDS = ACCESS_TOKEN_REFRESH_SKEW_SECONDS
  56. DEVICE_AUTH_POLL_INTERVAL_CAP_SECONDS = 1 # poll at most every 1s
  57. DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
  58. _FORM_JSON_HEADERS = {"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"}
  59. DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api/codex"
  60. DEFAULT_XAI_OAUTH_BASE_URL = "https://api.x.ai/v1"
  61. MINIMAX_OAUTH_CLIENT_ID = "78257093-7e40-4613-99e0-527b14b39113"
  62. MINIMAX_OAUTH_SCOPE = "group_id profile model.completion"
  63. MINIMAX_OAUTH_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:user_code"
  64. MINIMAX_OAUTH_GLOBAL_BASE = "https://api.minimax.io"
  65. MINIMAX_OAUTH_CN_BASE = "https://api.minimaxi.com"
  66. MINIMAX_OAUTH_GLOBAL_INFERENCE = "https://api.minimax.io/anthropic"
  67. MINIMAX_OAUTH_CN_INFERENCE = "https://api.minimaxi.com/anthropic"
  68. MINIMAX_OAUTH_REFRESH_SKEW_SECONDS = 60
  69. DEFAULT_QWEN_BASE_URL = "https://portal.qwen.ai/v1"
  70. DEFAULT_OLLAMA_CLOUD_BASE_URL = "https://ollama.com/v1"
  71. DEFAULT_ACTUAL_BASE_URL = "https://api.actual.inc/v1"
  72. DEFAULT_ACTUAL_LOCAL_BASE_URL = "http://127.0.0.1:8080/v1"
  73. STEPFUN_STEP_PLAN_INTL_BASE_URL = "https://api.stepfun.ai/step_plan/v1"
  74. STEPFUN_STEP_PLAN_CN_BASE_URL = "https://api.stepfun.com/step_plan/v1"
  75. CODEX_OAUTH_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann"
  76. CODEX_OAUTH_TOKEN_URL = "https://auth.openai.com/oauth/token"
  77. CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120
  78. XAI_OAUTH_ISSUER = "https://auth.x.ai"
  79. XAI_OAUTH_DISCOVERY_URL = f"{XAI_OAUTH_ISSUER}/.well-known/openid-configuration"
  80. XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828"
  81. XAI_OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access"
  82. XAI_OAUTH_DEVICE_CODE_URL = f"{XAI_OAUTH_ISSUER}/oauth2/device/code"
  83. # xAI/Grok OAuth access tokens are short-lived (~6h). A two-minute refresh window leaves noisy
  84. # credential-expiry gaps for gateway/cron workloads that touch the provider every ~30 min, so refresh
  85. # up to an hour early.
  86. XAI_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 3600
  87. QWEN_OAUTH_CLIENT_ID = "f0304373b74a44d2b584a3fb70ca9e56"
  88. QWEN_OAUTH_TOKEN_URL = "https://chat.qwen.ai/api/v1/oauth2/token"
  89. QWEN_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 120
  90. # OpenRouter PKCE (https://openrouter.ai/docs/guides/overview/auth/oauth): the "token" endpoint
  91. # mints a plain user-controlled API key; there is no refresh token.
  92. OPENROUTER_AUTH_URL = "https://openrouter.ai/auth"
  93. OPENROUTER_AUTH_KEYS_URL = "https://openrouter.ai/api/v1/auth/keys"
  94. OPENROUTER_OAUTH_DOCS_URL = "https://openrouter.ai/docs/guides/overview/auth/oauth"
  95. OAUTH_OVER_SSH_DOCS_URL = "https://hermes-agent.nousresearch.com/docs/guides/oauth-over-ssh"
  96. # LM Studio's default no-auth mode still needs *some* non-empty bearer for the API-key code paths to
  97. # treat the provider as configured. Sent only to LM Studio, never to a remote service.
  98. LMSTUDIO_NOAUTH_PLACEHOLDER = "dummy-lm-api-key"
  99. ACTUAL_LOCAL_NOAUTH_PLACEHOLDER = "dummy-actual-local-api-key"
  100. # Upstream rate-limit / usage-quota exhaustion (HTTP 429): transient, re-authenticating cannot resolve
  101. # it, so it must stay distinct from missing/expired-credential errors.
  102. CODEX_RATE_LIMITED_CODE = "codex_rate_limited"
  103. class AuthError(RuntimeError):
  104. """Structured auth error with UX mapping hints."""
  105. def __init__(
  106. self, message: str, *, provider: str = "", code: Optional[str] = None, relogin_required: bool = False,
  107. retry_after: Optional[float] = None, retryable: Optional[bool] = None,
  108. ) -> None:
  109. super().__init__(message)
  110. self.provider = provider
  111. self.code = code
  112. self.relogin_required = relogin_required
  113. # Optional wait hint in seconds (a server ``Retry-After`` or a client cooldown) and whether a
  114. # later attempt can succeed at all. None = the raiser did not say; callers treat None as
  115. # "retryable, no hint" for transport-shaped errors and as terminal for auth refusals.
  116. self.retry_after = retry_after
  117. self.retryable = retryable
  118. def _provider_error_factory(provider: str) -> Callable[..., AuthError]:
  119. def factory(message: str, code: Optional[str] = None, *, relogin: bool = False) -> AuthError:
  120. return AuthError(message, provider=provider, code=code, relogin_required=relogin)
  121. return factory
  122. # Per-provider AuthError constructors: ``_xai_err(message, code, relogin=True)``.
  123. _nous_err = _provider_error_factory("nous")
  124. _xai_err = _provider_error_factory("xai-oauth")
  125. _codex_err = _provider_error_factory("openai-codex")
  126. _qwen_err = _provider_error_factory("qwen-oauth")
  127. _minimax_err = _provider_error_factory("minimax-oauth")
  128. _openrouter_err = _provider_error_factory("openrouter")
  129. def _decode_jwt_claims(token: Any) -> dict[str, Any]:
  130. if not isinstance(token, str) or token.count(".") != 2:
  131. return {}
  132. payload = token.split(".")[1]
  133. payload += "=" * ((4 - len(payload) % 4) % 4)
  134. try:
  135. raw = base64.urlsafe_b64decode(payload.encode("utf-8"))
  136. claims = json.loads(raw.decode("utf-8"))
  137. except Exception:
  138. return {}
  139. return claims if isinstance(claims, dict) else {}