auth.py 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Solstice sign-in: browser PKCE with a loopback redirect, token exchange and refresh brokered by the
  2. Nous portal (NAS), which holds the confidential client secret. Hermes keeps its own PKCE verifier and
  3. the user's tokens; NAS never sees a prompt.
  4. The generic ``hermes_cli.auth_oauth_pkce_plugin`` flow runs the browser leg, the credential-pool row
  5. and the single-use-safe refresh. This module supplies only what is NAS-specific: the client config it
  6. discovers and the token POSTs it brokers. Every NAS call carries the user's Nous access token.
  7. """
  8. from __future__ import annotations
  9. from typing import Any, Dict, Mapping
  10. DEFAULT_NAS_BASE_URL = "https://portal.nousresearch.com"
  11. _CONFIG_PATH = "/api/oauth/gemini-auth/config"
  12. _TOKEN_PATHS = {"authorization_code": "/api/oauth/gemini-auth/exchange", "refresh_token": "/api/oauth/gemini-auth/refresh"}
  13. _TIMEOUT_SECONDS = 30.0
  14. def _err(message: str, code: str, *, relogin: bool = False):
  15. from hermes_cli.auth_constants import AuthError
  16. return AuthError(f"solstice: {message}", provider="solstice", code=code, relogin_required=relogin)
  17. def _nas_base_url() -> str:
  18. """The Nous portal the user is signed into (``HERMES_PORTAL_BASE_URL`` override first)."""
  19. from hermes_cli.auth import _nous_portal_base_url, get_provider_auth_state
  20. return _nous_portal_base_url(get_provider_auth_state("nous") or {})
  21. def _nas_request(method: str, path: str, *, json: Mapping[str, Any] | None = None) -> dict[str, Any]:
  22. from hermes_cli.auth import _default_verify, resolve_nous_access_token
  23. from hermes_cli.auth_constants import httpx
  24. try:
  25. token = resolve_nous_access_token()
  26. except Exception as exc:
  27. raise _err("sign in to Nous Portal first (`hermes auth add nous`).", "solstice_nous_login_required",
  28. relogin=True) from exc
  29. try:
  30. response = httpx.request(method, _nas_base_url() + path, json=json, timeout=_TIMEOUT_SECONDS,
  31. headers={"Accept": "application/json", "Authorization": f"Bearer {token}"},
  32. verify=_default_verify())
  33. except Exception as exc:
  34. raise _err(f"Nous portal request failed: {type(exc).__name__}", "solstice_broker_unreachable") from exc
  35. if response.status_code == 404:
  36. raise _err("not available on this Nous account yet.", "solstice_not_configured")
  37. if response.status_code >= 400:
  38. raise _err(f"Nous portal returned HTTP {response.status_code}.", "solstice_broker_failed")
  39. return response.json()
  40. def discover_client() -> dict[str, str]:
  41. """``client_id`` / ``authorize_url`` / ``scope`` NAS serves for the shared Google client."""
  42. payload = _nas_request("GET", _CONFIG_PATH)
  43. missing = [k for k in ("client_id", "authorize_url", "scope") if not str(payload.get(k) or "").strip()]
  44. if missing:
  45. raise _err(f"Nous portal config is missing {', '.join(missing)}.", "solstice_config_invalid")
  46. return {k: str(payload[k]).strip() for k in ("client_id", "authorize_url", "scope")}
  47. def broker_token_request(grant: Mapping[str, str]) -> Mapping[str, Any]:
  48. """``OAuthPKCEConfig.token_request``: send the grant to NAS, which adds the client secret.
  49. NAS folds every Google token-endpoint failure into HTTP 502, so a refresh it rejects is treated as
  50. a dead grant (re-login) rather than retried against a token Google already refused.
  51. """
  52. path = _TOKEN_PATHS[grant["grant_type"]]
  53. body = {k: v for k, v in grant.items() if k in ("code", "code_verifier", "redirect_uri", "refresh_token")}
  54. try:
  55. return _nas_request("POST", path, json=body)
  56. except Exception as exc:
  57. if grant["grant_type"] == "refresh_token" and getattr(exc, "code", "") == "solstice_broker_failed":
  58. raise _err("the stored sign-in was rejected; run `hermes auth add solstice` again.",
  59. "invalid_grant", relogin=True) from exc
  60. raise