Prefer browser PKCE mint over flaky direct HTTP to auth.x.ai.

Logs show curl(28)/ReadTimeout on direct mint while registration browser
still works; skip slow requests fallback, shorten HTTP step timeout, and
mint via page first when available.
This commit is contained in:
chaos committed 2026-07-14 10:19:25 +08:00
1 parent 8b399277e7
commit 96061cbd78
3 files changed
+68 -55

No files matched your search

+31 -11
View File
@@ -72,7 +72,13 @@ def _mint_tokens(
log: Callable[[str], None],
proxy: str | None,
) -> dict[str, Any]:
"""优先 HTTP SSO 授权码;TLS 失败时用注册浏览器 PKCE;可选设备码。"""
"""铸造策略(有 page 时优先浏览器,避免直连 auth.x.ai 卡超时):
1. page+sso 且 cpa_prefer_browser_mint:直接浏览器 PKCE
2. 否则 HTTP SSO→OAuth(curl_cffi,短超时)
3. HTTP 失败且有 page:浏览器 PKCE
4. 可选设备码(通常无 referrer,默认关)
"""
from oidc_mint.oauth_code import (
OAuthCodeError,
_is_http_tls_failure,
@@ -84,10 +90,31 @@ def _mint_tokens(
sso_token = normalize_sso_cookie(sso or "")
prefer_sso = bool(cfg.get("cpa_prefer_sso_oauth", True))
allow_browser = bool(cfg.get("cpa_allow_browser_fallback", True))
# 有注册浏览器时默认先浏览器:直连/跨境对 auth.x.ai 经常 curl(28)/ReadTimeout
prefer_browser = bool(cfg.get("cpa_prefer_browser_mint", True))
allow_device = bool(cfg.get("cpa_allow_device_fallback", False))
timeout = float(cfg.get("mint_timeout_sec", 300) or 300)
require_ref = bool(cfg.get("cpa_require_referrer", True))
http_err: Exception | None = None
browser_timeout = min(timeout, float(cfg.get("cpa_browser_mint_timeout_sec", 120) or 120))
def _browser_mint(reason: str) -> dict[str, Any]:
log(f"[cpa] 浏览器 PKCE 铸造({reason})")
return mint_from_sso_browser(
sso_token,
page,
log=lambda m: log(f"[Debug] {m}"),
require_referrer=require_ref,
timeout_sec=browser_timeout,
)
# 路径 A:有 page 时优先浏览器(最稳,不依赖 Python→auth.x.ai 直连)
if prefer_sso and sso_token and allow_browser and page is not None and prefer_browser:
try:
return _browser_mint("优先浏览器,绕开 Python 直连 auth.x.ai")
except Exception as exc: # noqa: BLE001
log(f"[!] 浏览器 PKCE 优先路径失败: {exc}")
log("[cpa] 继续尝试 HTTP SSO→OAuth")
if prefer_sso and sso_token:
log("[cpa] 使用 SSO→OAuth(PKCE, referrer=grok-build)")
@@ -105,18 +132,11 @@ def _mint_tokens(
http_err = exc
log(f"[!] SSO→OAuth 异常: {exc}")
# HTTP 失败后:有 page+sso 就优先浏览器 PKCE(Chrome TLS 通常正常,且保留 referrer)
# HTTP 失败后:有 page+sso 再试浏览器(若优先路径没走过或当时失败)
if allow_browser and page is not None and sso_token and http_err is not None:
why = "TLS/连接" if _is_http_tls_failure(http_err) else "HTTP"
log(f"[cpa] 回退浏览器 PKCE 铸造({why}失败,绕开 Python TLS)")
why = "TLS/连接/超时" if _is_http_tls_failure(http_err) else "HTTP"
try:
return mint_from_sso_browser(
sso_token,
page,
log=lambda m: log(f"[Debug] {m}"),
require_referrer=require_ref,
timeout_sec=min(timeout, 120.0),
)
return _browser_mint(f"{why}失败后回退")
except Exception as exc: # noqa: BLE001
log(f"[!] 浏览器 PKCE 失败: {exc}")
if not allow_device: