auth_openrouter.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. """OpenRouter OAuth PKCE login (``hermes auth add openrouter --type oauth``).
  2. Contract: https://openrouter.ai/docs/guides/overview/auth/oauth. The browser is sent to
  3. ``/auth?callback_url=...&code_challenge=...&code_challenge_method=S256``; the redirect carries
  4. ``?code=``; ``POST /api/v1/auth/keys`` swaps ``{code, code_verifier, code_challenge_method}`` for
  5. ``{"key": "sk-or-v1-..."}`` — a plain user-controlled API key, no refresh token. OpenRouter echoes no
  6. ``state`` parameter, so the CSRF nonce rides in the loopback callback PATH: a redirect to any other
  7. path is a 404 and never reaches the exchange.
  8. """
  9. from __future__ import annotations
  10. import secrets
  11. import webbrowser
  12. from typing import Any, Dict
  13. from urllib.parse import urlencode
  14. from hermes_cli.auth_constants import (
  15. OPENROUTER_AUTH_KEYS_URL, OPENROUTER_AUTH_URL, OPENROUTER_OAUTH_DOCS_URL, _openrouter_err, httpx)
  16. from hermes_cli.auth_device_flow import (
  17. _bind_loopback_callback_server, _can_open_graphical_browser, _is_remote_session,
  18. _make_loopback_callback_handler, _pkce_code_challenge, _pkce_code_verifier, _serve_loopback_callback)
  19. _ERROR_BODY_LIMIT = 2048
  20. def _openrouter_exchange_code(code: str, code_verifier: str, *, timeout_seconds: float = 20.0) -> str:
  21. """Exchange the authorization code for an API key; the key never enters a log or error message."""
  22. try:
  23. response = httpx.post(
  24. OPENROUTER_AUTH_KEYS_URL, json={
  25. "code": code, "code_verifier": code_verifier, "code_challenge_method": "S256"},
  26. headers={"Content-Type": "application/json"}, timeout=timeout_seconds)
  27. except Exception as exc:
  28. raise _openrouter_err(f"OpenRouter code exchange failed: {exc}", "openrouter_token_exchange_failed") from exc
  29. if response.status_code == 403:
  30. raise _openrouter_err(
  31. "OpenRouter rejected the authorization code (invalid, already used, or older than 10 minutes). "
  32. "Run the login again.", "openrouter_token_exchange_denied", relogin=True)
  33. if response.status_code >= 400:
  34. detail = response.text.strip()[:_ERROR_BODY_LIMIT]
  35. raise _openrouter_err(
  36. f"OpenRouter code exchange failed (HTTP {response.status_code})." + (f" Response: {detail}" if detail else ""),
  37. "openrouter_token_exchange_failed")
  38. try:
  39. payload = response.json()
  40. except ValueError as exc:
  41. raise _openrouter_err(
  42. "OpenRouter code exchange returned a non-JSON body.", "openrouter_token_exchange_invalid") from exc
  43. key = str(payload.get("key") or "").strip() if isinstance(payload, dict) else ""
  44. if not key:
  45. raise _openrouter_err(
  46. "OpenRouter code exchange response did not include a 'key'.", "openrouter_token_exchange_invalid")
  47. return key
  48. def _openrouter_headless_code(auth_url: str) -> str:
  49. """Remote/SSH: OpenRouter shows the code on screen when ``callback_url`` is omitted; the user pastes it."""
  50. from hermes_cli.secret_prompt import masked_secret_prompt
  51. print(
  52. "Remote session detected — using OpenRouter's headless flow.\n"
  53. f"Open this URL in a browser on any machine, authorize, then paste the code shown:\n {auth_url}\n")
  54. code = masked_secret_prompt("Authorization code: ").strip()
  55. if not code:
  56. raise _openrouter_err("No authorization code entered.", "openrouter_auth_no_code")
  57. return code
  58. def _openrouter_loopback_code(auth_url_params: dict[str, str], *, open_browser: bool, timeout_seconds: float) -> str:
  59. nonce = secrets.token_urlsafe(16)
  60. path = f"/callback/{nonce}"
  61. handler_cls, result = _make_loopback_callback_handler(path, display_name="OpenRouter")
  62. server = _bind_loopback_callback_server(
  63. "127.0.0.1", 0, handler_cls, err=_openrouter_err, bind_failed_code="openrouter_callback_bind_failed")
  64. redirect_uri = f"http://127.0.0.1:{server.server_address[1]}{path}"
  65. auth_url = f"{OPENROUTER_AUTH_URL}?{urlencode({'callback_url': redirect_uri, **auth_url_params})}"
  66. print(f"Open this URL to authorize Hermes with OpenRouter:\n {auth_url}\n\nDocs: {OPENROUTER_OAUTH_DOCS_URL}")
  67. if open_browser and _can_open_graphical_browser():
  68. try:
  69. opened = webbrowser.open(auth_url)
  70. except Exception:
  71. opened = False
  72. print("Browser opened for OpenRouter authorization." if opened
  73. else "Could not open the browser automatically; use the URL above.")
  74. print("Waiting for the OpenRouter callback...")
  75. callback = _serve_loopback_callback(
  76. server, result, timeout_seconds=timeout_seconds, err=_openrouter_err,
  77. timeout_code="openrouter_callback_timeout")
  78. if callback.get("error"):
  79. raise _openrouter_err(
  80. f"OpenRouter authorization failed: {callback.get('error_description') or callback['error']}",
  81. "openrouter_auth_denied")
  82. code = str(callback.get("code") or "").strip()
  83. if not code:
  84. raise _openrouter_err("OpenRouter callback did not carry an authorization code.", "openrouter_auth_no_code")
  85. return code
  86. def _openrouter_pkce_login(*, open_browser: bool = True, timeout_seconds: float = 300.0) -> dict[str, Any]:
  87. """Run the PKCE flow and return ``{"api_key": ...}`` for the credential-pool add path."""
  88. code_verifier = _pkce_code_verifier()
  89. params = {"code_challenge": _pkce_code_challenge(code_verifier), "code_challenge_method": "S256"}
  90. if _is_remote_session():
  91. code = _openrouter_headless_code(f"{OPENROUTER_AUTH_URL}?{urlencode({**params, 'key_label': 'hermes-agent'})}")
  92. else:
  93. code = _openrouter_loopback_code(params, open_browser=open_browser, timeout_seconds=timeout_seconds)
  94. print("Exchanging the authorization code for an OpenRouter API key...")
  95. return {"api_key": _openrouter_exchange_code(code, code_verifier)}