auth_codex_browser.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. """OpenAI Codex browser login: authorization-code + PKCE on a loopback listener (opt-in).
  2. ``hermes auth add openai-codex --browser`` (or ``auth.codex_login_flow: browser``) sends the
  3. system browser to OpenAI's authorize endpoint and receives the code on
  4. ``http://localhost:1455/auth/callback`` — the redirect URI fixed by the public Codex client
  5. registration, so the port is not negotiable. Organizations that disable the device-code grant can
  6. still sign in this way (#95743). The device-code flow in ``auth_codex.py`` stays the default and is
  7. the fallback whenever the loopback port is already taken (a Codex CLI login in progress).
  8. Credentials come back in the same dict shape as ``_codex_device_code_login`` with
  9. ``source="loopback_pkce"`` so the pool/singleton save paths treat both flows alike. Tokens,
  10. authorization codes and the PKCE verifier are never logged or printed.
  11. Derived from #97058 by @astraltrekkin, re-homed after the ``auth_codex.py`` split.
  12. """
  13. from __future__ import annotations
  14. import hmac
  15. import logging
  16. import secrets
  17. import webbrowser
  18. from typing import Any, Dict, Optional
  19. from urllib.parse import urlencode
  20. from hermes_cli.auth_constants import AuthError, CODEX_OAUTH_CLIENT_ID, CODEX_OAUTH_TOKEN_URL, _codex_err
  21. from hermes_cli.auth_device_flow import (
  22. _bind_loopback_callback_server, _can_open_graphical_browser, _make_loopback_callback_handler,
  23. _pkce_code_challenge, _pkce_code_verifier, _print_loopback_ssh_hint, _serve_loopback_callback)
  24. logger = logging.getLogger("hermes_cli.auth")
  25. CODEX_OAUTH_AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize"
  26. CODEX_OAUTH_BROWSER_SCOPE = "openid profile email offline_access"
  27. # Registered with the Codex client: ``http://localhost:1455/auth/callback``. The listener binds
  28. # 127.0.0.1 explicitly; only the redirect URI string says ``localhost``.
  29. CODEX_BROWSER_CALLBACK_PORT = 1455
  30. CODEX_BROWSER_CALLBACK_PATH = "/auth/callback"
  31. CODEX_BROWSER_CALLBACK_TIMEOUT_SECONDS = 300.0
  32. CODEX_LOGIN_FLOWS = ("device_code", "browser")
  33. CODEX_BROWSER_PORT_BUSY_CODE = "codex_browser_port_busy"
  34. _PORT_BUSY_NOTICE = (
  35. f"Port {CODEX_BROWSER_CALLBACK_PORT} is already in use (a Codex CLI sign-in may be running). "
  36. "OpenAI only redirects to that port, so falling back to the device-code login.")
  37. def _codex_login_flow(args: Any) -> str:
  38. """``browser`` only when the user asked for it: ``--browser`` or ``auth.codex_login_flow``."""
  39. if getattr(args, "browser", False):
  40. return "browser"
  41. from hermes_cli.config import load_config_readonly
  42. auth_cfg = (load_config_readonly() or {}).get("auth")
  43. flow = str((auth_cfg or {}).get("codex_login_flow", "device_code") if isinstance(auth_cfg, dict) else "device_code")
  44. flow = flow.strip().lower() or "device_code"
  45. if flow not in CODEX_LOGIN_FLOWS:
  46. print(f"Ignoring unknown auth.codex_login_flow {flow!r} (expected one of {', '.join(CODEX_LOGIN_FLOWS)}).")
  47. return "device_code"
  48. return flow
  49. def codex_oauth_login(args: Any) -> dict[str, Any]:
  50. """Run the Codex OAuth flow selected by *args*/config; port-busy browser attempts fall back."""
  51. from hermes_cli import auth as auth_mod # late: ``hermes_cli.auth.<name>`` patches must intercept
  52. if _codex_login_flow(args) == "browser":
  53. try:
  54. return _codex_browser_login(
  55. open_browser=not getattr(args, "no_browser", False),
  56. timeout_seconds=getattr(args, "timeout", None))
  57. except AuthError as exc:
  58. if exc.code != CODEX_BROWSER_PORT_BUSY_CODE:
  59. raise
  60. print(_PORT_BUSY_NOTICE)
  61. print()
  62. print("Signing in to OpenAI Codex...")
  63. print("(Hermes creates its own session — won't affect Codex CLI or VS Code)")
  64. print()
  65. return auth_mod._codex_device_code_login()
  66. def _codex_browser_authorize_url(*, redirect_uri: str, state: str, code_challenge: str) -> str:
  67. return f"{CODEX_OAUTH_AUTHORIZE_URL}?" + urlencode({
  68. "response_type": "code", "client_id": CODEX_OAUTH_CLIENT_ID, "redirect_uri": redirect_uri,
  69. "scope": CODEX_OAUTH_BROWSER_SCOPE, "code_challenge": code_challenge,
  70. "code_challenge_method": "S256", "id_token_add_organizations": "true", "state": state})
  71. def _codex_browser_exchange_code(code: str, *, redirect_uri: str, code_verifier: str) -> dict[str, Any]:
  72. """Swap the authorization code for tokens at the token endpoint the device flow also uses."""
  73. from hermes_cli.auth_codex import _codex_login_post, _codex_login_rate_limited_error
  74. token_resp = _codex_login_post(
  75. CODEX_OAUTH_TOKEN_URL,
  76. data={
  77. "grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri,
  78. "client_id": CODEX_OAUTH_CLIENT_ID, "code_verifier": code_verifier},
  79. headers={"Content-Type": "application/x-www-form-urlencoded"},
  80. failure=("Token exchange failed", "token_exchange_failed"))
  81. if token_resp.status_code == 429:
  82. raise _codex_login_rate_limited_error(token_resp, during=" during token exchange")
  83. if token_resp.status_code != 200:
  84. raise _codex_err(
  85. f"Token exchange returned status {token_resp.status_code}.", "token_exchange_error")
  86. tokens = token_resp.json()
  87. if not tokens.get("access_token", ""):
  88. raise _codex_err(
  89. "Token exchange did not return an access_token.", "token_exchange_no_access_token")
  90. return tokens
  91. def _codex_browser_login(
  92. *, open_browser: bool = True, timeout_seconds: Optional[float] = None) -> dict[str, Any]:
  93. """Authorization-code + PKCE login on the loopback listener; returns the device-flow creds shape.
  94. Raises ``AuthError(code=CODEX_BROWSER_PORT_BUSY_CODE)`` when :1455 cannot be bound so the caller
  95. can fall back to the device-code flow instead of failing the login.
  96. """
  97. from hermes_cli.auth import _utc_now_z
  98. from hermes_cli.auth_codex import _codex_base_url
  99. code_verifier = _pkce_code_verifier()
  100. state = secrets.token_urlsafe(32)
  101. handler_cls, result = _make_loopback_callback_handler(CODEX_BROWSER_CALLBACK_PATH, display_name="OpenAI Codex")
  102. server = _bind_loopback_callback_server(
  103. "127.0.0.1", CODEX_BROWSER_CALLBACK_PORT, handler_cls, err=_codex_err,
  104. bind_failed_code=CODEX_BROWSER_PORT_BUSY_CODE)
  105. redirect_uri = f"http://localhost:{server.server_address[1]}{CODEX_BROWSER_CALLBACK_PATH}"
  106. auth_url = _codex_browser_authorize_url(
  107. redirect_uri=redirect_uri, state=state, code_challenge=_pkce_code_challenge(code_verifier))
  108. print()
  109. print("Signing in to OpenAI Codex (browser authorization)...")
  110. print("(Hermes creates its own session — won't affect Codex CLI or VS Code)")
  111. print()
  112. print(f"Open this URL to authorize Hermes:\n {auth_url}\n")
  113. _print_loopback_ssh_hint(redirect_uri)
  114. if open_browser and _can_open_graphical_browser():
  115. try:
  116. opened = webbrowser.open(auth_url)
  117. except Exception:
  118. opened = False
  119. print("Browser opened for OpenAI authorization." if opened
  120. else "Could not open the browser automatically; use the URL above.")
  121. wait = float(timeout_seconds or CODEX_BROWSER_CALLBACK_TIMEOUT_SECONDS)
  122. print(f"Waiting for the OpenAI callback on {redirect_uri} (timeout {int(wait)}s, Ctrl+C to cancel)...")
  123. try:
  124. callback = _serve_loopback_callback(
  125. server, result, timeout_seconds=wait, err=_codex_err, timeout_code="codex_browser_callback_timeout")
  126. except KeyboardInterrupt:
  127. print("\nLogin cancelled.")
  128. raise SystemExit(130)
  129. if callback.get("error"):
  130. detail = callback.get("error_description") or callback["error"]
  131. raise _codex_err(f"OpenAI authorization failed: {detail}", "codex_browser_auth_denied")
  132. if not hmac.compare_digest(str(callback.get("state") or ""), state):
  133. raise _codex_err(
  134. "Authorization callback state mismatch — the redirect did not come from this login. Aborting.",
  135. "codex_browser_state_mismatch")
  136. code = str(callback.get("code") or "").strip()
  137. if not code:
  138. raise _codex_err("Authorization callback did not carry a code.", "codex_browser_no_code")
  139. print("Exchanging the authorization code for Codex tokens...")
  140. tokens = _codex_browser_exchange_code(code, redirect_uri=redirect_uri, code_verifier=code_verifier)
  141. return {
  142. "tokens": {
  143. "access_token": tokens.get("access_token", ""),
  144. "refresh_token": tokens.get("refresh_token", "")},
  145. "base_url": _codex_base_url(), "last_refresh": _utc_now_z(), "auth_mode": "chatgpt",
  146. "source": "loopback_pkce"}