393 lines
16 KiB
Python
393 lines
16 KiB
Python
"""协议级 OAuth 登录模块 - 纯 HTTP JSON API 模拟 PKCE OAuth 授权流程
|
|
|
|
流程 (基于 auth.openai.com React SPA 逆向 + 端到端验证):
|
|
1. GET auth_url (PKCE) → allow_redirects=True → /log-in (建立 auth session)
|
|
2. POST /api/accounts/authorize/continue {username: {kind:"email",value:...}}
|
|
→ login_password
|
|
3. POST /api/first_party_authorize/next {origin_page_type, data}
|
|
→ sign_in_with_chatgpt_codex_consent
|
|
4. 解码 oai-client-auth-session cookie → 提取 workspace_id
|
|
5. POST /api/accounts/workspace/select {workspace_id}
|
|
→ sign_in_with_chatgpt_codex_org
|
|
6. POST /api/accounts/organization/select {org_id, project_id}
|
|
→ external_url + continue_url
|
|
7. 跟踪 redirect chain → localhost:1455/auth/callback?code=...
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import json
|
|
import time
|
|
import urllib.parse
|
|
from typing import Optional
|
|
|
|
from curl_cffi import requests as cffi_requests
|
|
|
|
from email_service import wait_for_code as email_wait_for_code
|
|
|
|
# ── 常量 ──
|
|
AUTH_BASE = "https://auth.openai.com"
|
|
AUTH_API_BASE = f"{AUTH_BASE}/api/accounts"
|
|
FPA_URL = f"{AUTH_BASE}/api/first_party_authorize/next"
|
|
SENTINEL_FALLBACK = json.dumps({"e": "q2n8w7x5z1"})
|
|
REDIRECT_URI = "http://localhost:1455/auth/callback"
|
|
|
|
|
|
class PasswordMismatchError(RuntimeError):
|
|
pass
|
|
|
|
|
|
class BannedError(RuntimeError):
|
|
pass
|
|
|
|
|
|
class OAuthLogin:
|
|
"""协议级 OAuth 授权器 - 纯 HTTP JSON API,无浏览器依赖"""
|
|
|
|
def __init__(self, *, proxy: str = "", impersonate: str = "chrome136"):
|
|
self.proxy = proxy
|
|
self.impersonate = impersonate
|
|
|
|
def _log(self, step: str, status: str, message: str = ""):
|
|
print(f"[oauth][{step}] {status}: {message}")
|
|
|
|
def _create_session(self) -> cffi_requests.Session:
|
|
session = cffi_requests.Session(impersonate=self.impersonate)
|
|
if self.proxy:
|
|
session.proxies = {"http": self.proxy, "https": self.proxy}
|
|
return session
|
|
|
|
def _api_headers(self, referer: str = f"{AUTH_BASE}/log-in") -> dict:
|
|
return {
|
|
"Accept": "application/json",
|
|
"Content-Type": "application/json",
|
|
"Origin": AUTH_BASE,
|
|
"Referer": referer,
|
|
"OpenAI-Sentinel-Token": SENTINEL_FALLBACK,
|
|
}
|
|
|
|
def _api_post(self, session, url: str, payload: dict,
|
|
referer: str = f"{AUTH_BASE}/log-in") -> tuple[dict, int]:
|
|
r = session.post(url, json=payload, headers=self._api_headers(referer), timeout=30)
|
|
try:
|
|
data = r.json()
|
|
except Exception:
|
|
data = {"error": r.text[:500]}
|
|
return data, r.status_code
|
|
|
|
def _api_get(self, session, url: str,
|
|
referer: str = f"{AUTH_BASE}/log-in") -> tuple[dict, int]:
|
|
r = session.get(url, headers=self._api_headers(referer), timeout=30)
|
|
try:
|
|
data = r.json()
|
|
except Exception:
|
|
data = {"error": r.text[:500]}
|
|
return data, r.status_code
|
|
|
|
def _get_page_type(self, data: dict) -> str:
|
|
"""从 API 响应中提取 page type,兼容两种格式"""
|
|
page = data.get("page", {})
|
|
if isinstance(page, dict) and page.get("type"):
|
|
return page["type"]
|
|
if data.get("type"):
|
|
return data["type"]
|
|
return str(page) if page else ""
|
|
|
|
def _extract_error(self, data: dict) -> str:
|
|
error = data.get("error", "")
|
|
if isinstance(error, dict):
|
|
return error.get("message", str(error))
|
|
return str(error)
|
|
|
|
# ── 主流程 ──
|
|
|
|
def authorize(
|
|
self,
|
|
*,
|
|
auth_url: str,
|
|
state: str,
|
|
email: str,
|
|
password: str,
|
|
use_email_otp: bool = False,
|
|
) -> str:
|
|
"""
|
|
执行 PKCE OAuth 授权流程,返回 authorization code。
|
|
|
|
参数:
|
|
auth_url: PKCE authorize URL
|
|
state: PKCE state 参数
|
|
email: 登录邮箱
|
|
password: 登录密码
|
|
use_email_otp: 是否支持邮箱 OTP 验证(需要临时邮箱服务)
|
|
"""
|
|
session = self._create_session()
|
|
|
|
# 1. 建立 OAuth 会话
|
|
self._log("session", "start", f"建立 OAuth 会话: {auth_url[:80]}")
|
|
if not self._establish_auth_session(session, auth_url):
|
|
raise RuntimeError("OAuth 会话建立失败")
|
|
|
|
# 2. 提交邮箱
|
|
self._log("email", "start", f"提交邮箱: {email}")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/authorize/continue",
|
|
{"username": {"kind": "email", "value": email}},
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("email", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
raise RuntimeError(f"邮箱提交失败: {status} {self._extract_error(data)}")
|
|
|
|
# 3. 密码登录
|
|
if page_type == "login_password":
|
|
self._log("password", "start", "提交密码")
|
|
data, status = self._api_post(
|
|
session, FPA_URL,
|
|
{
|
|
"origin_page_type": "login_password",
|
|
"data": {
|
|
"intent": "validate",
|
|
"username": {"value": email, "kind": "email"},
|
|
"password": password,
|
|
},
|
|
},
|
|
referer=f"{AUTH_BASE}/log-in/password",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("password", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
error_msg = self._extract_error(data)
|
|
self._detect_error_and_raise(error_msg)
|
|
raise RuntimeError(f"密码提交失败: {status} {error_msg}")
|
|
|
|
if page_type == "error":
|
|
error_msg = data.get("detail", self._extract_error(data))
|
|
self._detect_error_and_raise(str(error_msg))
|
|
raise RuntimeError(f"密码验证错误: {error_msg}")
|
|
|
|
# 3b. 邮箱 OTP 验证
|
|
if page_type in ("email_otp_verification", "email_otp_send"):
|
|
if not use_email_otp:
|
|
raise RuntimeError("需要邮箱验证码但 use_email_otp=False")
|
|
|
|
if page_type == "email_otp_send":
|
|
self._log("otp_send", "start", "触发发送 OTP")
|
|
self._api_get(session, f"{AUTH_API_BASE}/email-otp/send",
|
|
referer=f"{AUTH_BASE}/email-verification")
|
|
|
|
self._log("otp_wait", "start", "等待验证邮件")
|
|
code = email_wait_for_code(email)
|
|
if not code:
|
|
raise RuntimeError("验证码获取超时")
|
|
|
|
self._log("otp_validate", "start", f"提交验证码: {code}")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/email-otp/validate",
|
|
{"code": code},
|
|
referer=f"{AUTH_BASE}/email-verification",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("otp_validate", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
raise RuntimeError(f"验证码校验失败: {status} {self._extract_error(data)}")
|
|
|
|
# 3c. Onboarding (about_you)
|
|
if page_type in ("about_you", "create_account_start"):
|
|
self._log("onboarding", "start", "填写 onboarding 信息 (about_you)")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/create_account",
|
|
{"name": "John Doe", "birthdate": "1990-05-12"},
|
|
referer=f"{AUTH_BASE}/about-you",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("onboarding", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
raise RuntimeError(f"Onboarding 失败: {status} {self._extract_error(data)}")
|
|
|
|
continue_url = data.get("continue_url", "")
|
|
if continue_url and continue_url.startswith("http"):
|
|
self._log("onboarding", "info", f"following continue_url: {continue_url[:80]}")
|
|
r = session.get(continue_url, allow_redirects=True, timeout=30)
|
|
code = _extract_code_from_url(str(r.url), expected_state=state)
|
|
if code:
|
|
self._log("oauth", "ok", "获取 code 成功 (onboarding → redirect)")
|
|
return code
|
|
|
|
# 重新走 PKCE 流程
|
|
self._log("onboarding", "info", "onboarding 完成,重新提交邮箱继续 PKCE 流程")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/authorize/continue",
|
|
{"username": {"kind": "email", "value": email}},
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
|
|
if page_type == "login_password":
|
|
data, status = self._api_post(
|
|
session, FPA_URL,
|
|
{
|
|
"origin_page_type": "login_password",
|
|
"data": {
|
|
"intent": "validate",
|
|
"username": {"value": email, "kind": "email"},
|
|
"password": password,
|
|
},
|
|
},
|
|
referer=f"{AUTH_BASE}/log-in/password",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
|
|
# 4. Consent / Workspace 选择
|
|
if page_type == "sign_in_with_chatgpt_codex_consent":
|
|
self._log("consent", "start", "处理 codex consent (workspace select)")
|
|
|
|
workspace_id = self._extract_workspace_id(session)
|
|
if not workspace_id:
|
|
raise RuntimeError("无法从 session cookie 中提取 workspace_id")
|
|
|
|
self._log("consent", "info", f"workspace_id={workspace_id}")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/workspace/select",
|
|
{"workspace_id": workspace_id},
|
|
referer=f"{AUTH_BASE}/sign-in-with-chatgpt-codex-consent",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("consent", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
raise RuntimeError(f"Workspace 选择失败: {status} {self._extract_error(data)}")
|
|
|
|
# 4b. Organization / Project 选择
|
|
if page_type == "sign_in_with_chatgpt_codex_org":
|
|
self._log("org_select", "start", "处理 codex org (organization select)")
|
|
|
|
orgs = data.get("data", {}).get("orgs", [])
|
|
if not orgs:
|
|
raise RuntimeError("organization/select: 响应中无 orgs 数据")
|
|
|
|
org_id = orgs[0].get("id", "")
|
|
projects = orgs[0].get("projects", [])
|
|
project_id = projects[0].get("id", "") if projects else ""
|
|
|
|
if not org_id or not project_id:
|
|
raise RuntimeError(f"organization/select: 缺少 org_id={org_id} 或 project_id={project_id}")
|
|
|
|
self._log("org_select", "info", f"org_id={org_id}, project_id={project_id}")
|
|
data, status = self._api_post(
|
|
session, f"{AUTH_API_BASE}/organization/select",
|
|
{"org_id": org_id, "project_id": project_id},
|
|
referer=f"{AUTH_BASE}/sign-in-with-chatgpt/codex/organization",
|
|
)
|
|
page_type = self._get_page_type(data)
|
|
self._log("org_select", "info", f"status={status} page={page_type}")
|
|
|
|
if status != 200:
|
|
raise RuntimeError(f"Organization 选择失败: {status} {self._extract_error(data)}")
|
|
|
|
# 5. 跟踪 continue_url 获取 code
|
|
continue_url = data.get("continue_url", "")
|
|
if continue_url and continue_url.startswith("http"):
|
|
code = self._follow_redirects_for_code(session, continue_url, state)
|
|
if code:
|
|
self._log("oauth", "ok", "获取 code 成功")
|
|
return code
|
|
|
|
# 尝试从 data 直接提取
|
|
code = _extract_code_from_url(data.get("continue_url", ""), expected_state=state)
|
|
if code:
|
|
self._log("oauth", "ok", "获取 code 成功")
|
|
return code
|
|
|
|
raise RuntimeError(f"OAuth 流程未能获取 code,最终 page_type: {page_type}")
|
|
|
|
# ── 会话建立 ──
|
|
|
|
def _establish_auth_session(self, session: cffi_requests.Session, auth_url: str) -> bool:
|
|
try:
|
|
r = session.get(auth_url, allow_redirects=True, timeout=30)
|
|
final_url = str(r.url)
|
|
self._log("session", "ok", f"会话已建立, final={final_url[:80]}")
|
|
if "auth.openai.com" not in final_url:
|
|
self._log("session", "error", f"未到达 auth.openai.com: {final_url[:100]}")
|
|
return False
|
|
return True
|
|
except Exception as e:
|
|
self._log("session", "error", f"会话建立异常: {e}")
|
|
return False
|
|
|
|
# ── Cookie 解码 ──
|
|
|
|
def _extract_workspace_id(self, session: cffi_requests.Session) -> str:
|
|
"""从 oai-client-auth-session cookie 中提取 workspace_id。
|
|
Cookie 格式: <urlsafe_b64_json>.<sig1>.<sig2>
|
|
"""
|
|
for cookie in session.cookies.jar:
|
|
if cookie.name == "oai-client-auth-session":
|
|
raw = str(cookie.value)
|
|
payload_b64 = raw.split(".")[0]
|
|
padded = payload_b64 + "=" * (4 - len(payload_b64) % 4)
|
|
try:
|
|
decoded = base64.urlsafe_b64decode(padded)
|
|
data = json.loads(decoded.decode("utf-8"))
|
|
workspaces = data.get("workspaces", [])
|
|
if workspaces and isinstance(workspaces, list):
|
|
return str(workspaces[0].get("id", ""))
|
|
except Exception as e:
|
|
self._log("cookie_decode", "error", f"解码失败: {e}")
|
|
return ""
|
|
|
|
# ── Redirect 跟踪 ──
|
|
|
|
def _follow_redirects_for_code(self, session, url: str, state: str) -> str:
|
|
self._log("redirect", "start", f"跟踪: {url[:80]}")
|
|
for _ in range(15):
|
|
r = session.get(url, allow_redirects=False, timeout=30)
|
|
if 300 <= r.status_code < 400:
|
|
location = r.headers.get("Location", "")
|
|
if not location:
|
|
break
|
|
code = _extract_code_from_url(location, expected_state=state)
|
|
if code:
|
|
return code
|
|
if not location.startswith("http"):
|
|
parsed = urllib.parse.urlparse(url)
|
|
location = f"{parsed.scheme}://{parsed.netloc}{location}"
|
|
url = location
|
|
else:
|
|
code = _extract_code_from_url(str(r.url), expected_state=state)
|
|
if code:
|
|
return code
|
|
break
|
|
return ""
|
|
|
|
# ── 错误检测 ──
|
|
|
|
def _detect_error_and_raise(self, error_msg: str) -> None:
|
|
msg_lower = error_msg.lower()
|
|
for t in ("incorrect email", "incorrect password", "wrong password"):
|
|
if t in msg_lower:
|
|
raise PasswordMismatchError(f"incorrect email or password: {error_msg}")
|
|
for t in ("disabled", "blocked", "suspended", "banned"):
|
|
if t in msg_lower:
|
|
raise BannedError(error_msg)
|
|
|
|
|
|
# ── 工具函数 ──
|
|
|
|
def _extract_code_from_url(url: str, *, expected_state: str) -> str:
|
|
if not url:
|
|
return ""
|
|
if not (url.startswith(REDIRECT_URI) or "localhost:1455" in url):
|
|
return ""
|
|
parsed = urllib.parse.urlparse(url)
|
|
q = urllib.parse.parse_qs(parsed.query)
|
|
code = (q.get("code") or [""])[0]
|
|
if not code:
|
|
return ""
|
|
st = (q.get("state") or [""])[0]
|
|
if st and str(st) != str(expected_state):
|
|
return ""
|
|
return str(code) |