feat(webui): support remote Codex OAuth login (#5174)

This commit is contained in:
chengyongru authored and GitHub committed 2026-07-30 15:06:34 +08:00
1 parent e2563e2e74
commit 606ac56e8f
22 files changed
+1233 -150

No files matched your search

+89 -50
View File
@@ -131,10 +131,10 @@ _IMAGE_GENERATION_ASPECT_RATIOS = {
}
_CONTEXT_WINDOW_TOKEN_OPTIONS = {65_536, 200_000, 262_144, 500_000, 1_048_576}
_OAUTH_PROXY_PROVIDERS = {"openai_codex", "xai_grok"}
_XAI_WEBUI_OAUTH_TIMEOUT_S = 600
_XAI_WEBUI_OAUTH_MAX_FLOWS = 8
_xai_webui_oauth_flows: dict[str, Any] = {}
_xai_webui_oauth_flows_lock = threading.Lock()
_WEBUI_OAUTH_TIMEOUT_S = 600
_WEBUI_OAUTH_MAX_FLOWS = 8
_webui_oauth_flows: dict[str, tuple[str, Any]] = {}
_webui_oauth_flows_lock = threading.Lock()
_MODEL_CONFIGURATION_SLUG_RE = re.compile(r"[^a-z0-9_-]+")
_ENV_REF_RE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
@@ -1810,7 +1810,7 @@ def login_oauth_provider(query: QueryParams) -> dict[str, Any]:
if spec.name == "openai_codex":
try:
from oauth_cli_kit import get_token, login_oauth_interactive
from nanobot.providers.openai_codex_oauth import start_openai_codex_oauth_login
except ImportError:
raise WebUISettingsError(
"oauth_cli_kit not installed. Run: pip install oauth-cli-kit", status=500
@@ -1820,19 +1820,30 @@ def login_oauth_provider(query: QueryParams) -> dict[str, Any]:
proxy = resolve_config_env_vars(load_config()).providers.openai_codex.proxy or None
except ValueError as e:
raise WebUISettingsError(str(e), status=400) from e
token = None
with suppress(Exception):
token = get_token(proxy=proxy)
if not (token and token.access):
messages: list[str] = []
token = login_oauth_interactive(
print_fn=lambda message: messages.append(str(message)),
prompt_fn=lambda _prompt: "",
remote_browser_value = _query_first(query, "remote_browser")
remote_browser = (
_parse_bool(remote_browser_value, "remote_browser")
if remote_browser_value is not None
else False
)
try:
flow = start_openai_codex_oauth_login(
proxy=proxy,
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
open_browser=not remote_browser,
)
if not (token and token.access):
raise WebUISettingsError("OAuth login failed", status=401)
return settings_payload()
except Exception as e:
raise WebUISettingsError(f"OpenAI Codex OAuth login failed: {e}", status=502) from e
flow_id = secrets.token_urlsafe(24)
_register_webui_oauth_flow(spec.name, flow_id, flow)
return {
"status": "authorization_required",
"provider": spec.name,
"flow_id": flow_id,
"authorization_url": flow.authorization_url,
"expires_in": flow.remaining_seconds,
"completion_input": "callback_url",
}
if spec.name == "github_copilot":
try:
@@ -1862,18 +1873,19 @@ def login_oauth_provider(query: QueryParams) -> dict[str, Any]:
try:
flow = start_xai_oauth_login(
proxy=proxy,
timeout_s=_XAI_WEBUI_OAUTH_TIMEOUT_S,
timeout_s=_WEBUI_OAUTH_TIMEOUT_S,
)
except Exception as e:
raise WebUISettingsError(f"xAI OAuth login failed: {e}", status=502) from e
flow_id = secrets.token_urlsafe(24)
_register_xai_webui_oauth_flow(flow_id, flow)
_register_webui_oauth_flow(spec.name, flow_id, flow)
return {
"status": "authorization_required",
"provider": spec.name,
"flow_id": flow_id,
"authorization_url": flow.authorization_url,
"expires_in": flow.remaining_seconds,
"completion_input": "authorization_code",
}
raise WebUISettingsError("OAuth login is not supported for this provider")
@@ -1881,34 +1893,47 @@ def login_oauth_provider(query: QueryParams) -> dict[str, Any]:
def complete_oauth_provider(
query: QueryParams,
authorization_code: str | None = None,
authorization_response: str | None = None,
) -> dict[str, Any]:
provider_name = (_query_first(query, "provider") or "").strip()
flow_id = (_query_first(query, "flow_id") or "").strip()
spec = find_by_name(provider_name)
if spec is None or spec.name != "xai_grok":
if spec is None or spec.name not in {"openai_codex", "xai_grok"}:
raise WebUISettingsError("OAuth completion is not supported for this provider")
if not flow_id:
raise WebUISettingsError("flow_id is required")
flow = _get_xai_webui_oauth_flow(flow_id)
flow = _get_webui_oauth_flow(spec.name, flow_id)
if flow is None:
raise WebUISettingsError("xAI sign-in expired. Start again.", status=410)
from nanobot.providers.xai_oauth import complete_xai_oauth_login
raise WebUISettingsError(f"{spec.label} sign-in expired. Start again.", status=410)
try:
token = complete_xai_oauth_login(flow, authorization_code)
if spec.name == "openai_codex":
from nanobot.providers.openai_codex_oauth import (
OpenAICodexOAuthInputError,
complete_openai_codex_oauth_login,
)
try:
token = complete_openai_codex_oauth_login(flow, authorization_response)
except OpenAICodexOAuthInputError as e:
raise WebUISettingsError(str(e), status=400) from e
else:
from nanobot.providers.xai_oauth import complete_xai_oauth_login
token = complete_xai_oauth_login(flow, authorization_response)
except WebUISettingsError:
raise
except Exception as e:
_remove_xai_webui_oauth_flow(flow_id, flow)
raise WebUISettingsError(f"xAI OAuth login failed: {e}", status=502) from e
_remove_webui_oauth_flow(spec.name, flow_id, flow)
raise WebUISettingsError(f"{spec.label} OAuth login failed: {e}", status=502) from e
if token is None:
return {
"status": "pending",
"provider": spec.name,
"flow_id": flow_id,
}
_remove_xai_webui_oauth_flow(flow_id, flow, cancel=False)
_remove_webui_oauth_flow(spec.name, flow_id, flow, cancel=False)
if not token.access:
raise WebUISettingsError("OAuth login failed", status=401)
return settings_payload()
@@ -1930,6 +1955,7 @@ def logout_oauth_provider(query: QueryParams) -> dict[str, Any]:
raise WebUISettingsError(
"oauth_cli_kit not installed. Run: pip install oauth-cli-kit", status=500
) from None
_clear_webui_oauth_flows(spec.name)
token_path = FileTokenStorage(token_filename=OPENAI_CODEX_PROVIDER.token_filename).get_token_path()
elif spec.name == "github_copilot":
try:
@@ -1942,7 +1968,7 @@ def logout_oauth_provider(query: QueryParams) -> dict[str, Any]:
elif spec.name == "xai_grok":
from nanobot.providers.xai_oauth import logout_xai_oauth
_clear_xai_webui_oauth_flows()
_clear_webui_oauth_flows(spec.name)
logout_xai_oauth()
return settings_payload()
else:
@@ -1954,47 +1980,60 @@ def logout_oauth_provider(query: QueryParams) -> dict[str, Any]:
return settings_payload()
def _register_xai_webui_oauth_flow(flow_id: str, flow: Any) -> None:
def _register_webui_oauth_flow(provider_name: str, flow_id: str, flow: Any) -> None:
discarded: list[Any] = []
with _xai_webui_oauth_flows_lock:
for existing_id, existing in list(_xai_webui_oauth_flows.items()):
with _webui_oauth_flows_lock:
for existing_id, (_provider_name, existing) in list(_webui_oauth_flows.items()):
if existing.expired:
discarded.append(_xai_webui_oauth_flows.pop(existing_id))
while len(_xai_webui_oauth_flows) >= _XAI_WEBUI_OAUTH_MAX_FLOWS:
oldest_id = next(iter(_xai_webui_oauth_flows))
discarded.append(_xai_webui_oauth_flows.pop(oldest_id))
_xai_webui_oauth_flows[flow_id] = flow
discarded.append(_webui_oauth_flows.pop(existing_id)[1])
while len(_webui_oauth_flows) >= _WEBUI_OAUTH_MAX_FLOWS:
oldest_id = next(iter(_webui_oauth_flows))
discarded.append(_webui_oauth_flows.pop(oldest_id)[1])
_webui_oauth_flows[flow_id] = (provider_name, flow)
for existing in discarded:
existing.cancel()
def _get_xai_webui_oauth_flow(flow_id: str) -> Any | None:
with _xai_webui_oauth_flows_lock:
flow = _xai_webui_oauth_flows.get(flow_id)
if flow is None or not flow.expired:
def _get_webui_oauth_flow(provider_name: str, flow_id: str) -> Any | None:
with _webui_oauth_flows_lock:
registered = _webui_oauth_flows.get(flow_id)
if registered is None or registered[0] != provider_name:
return None
flow = registered[1]
if not flow.expired:
return flow
_xai_webui_oauth_flows.pop(flow_id, None)
_webui_oauth_flows.pop(flow_id, None)
flow.cancel()
return None
def _remove_xai_webui_oauth_flow(
def _remove_webui_oauth_flow(
provider_name: str,
flow_id: str,
flow: Any,
*,
cancel: bool = True,
) -> None:
with _xai_webui_oauth_flows_lock:
if _xai_webui_oauth_flows.get(flow_id) is flow:
_xai_webui_oauth_flows.pop(flow_id)
with _webui_oauth_flows_lock:
registered = _webui_oauth_flows.get(flow_id)
if (
registered is not None
and registered[0] == provider_name
and registered[1] is flow
):
_webui_oauth_flows.pop(flow_id)
if cancel:
flow.cancel()
def _clear_xai_webui_oauth_flows() -> None:
with _xai_webui_oauth_flows_lock:
flows = list(_xai_webui_oauth_flows.values())
_xai_webui_oauth_flows.clear()
def _clear_webui_oauth_flows(provider_name: str) -> None:
with _webui_oauth_flows_lock:
flow_ids = [
flow_id
for flow_id, (registered_provider, _flow) in _webui_oauth_flows.items()
if registered_provider == provider_name
]
flows = [_webui_oauth_flows.pop(flow_id)[1] for flow_id in flow_ids]
for flow in flows:
flow.cancel()