From 4a169ac39c7e594420eb806fe3339fd1038d09f1 Mon Sep 17 00:00:00 2001 From: keggin <109941504+keggin-CHN@users.noreply.github.com> Date: Sun, 15 Feb 2026 16:38:48 +0800 Subject: [PATCH] Add files via upload --- README.md | 45 +- email_service.py | 101 ++++ oauth_client.py | 81 ++++ oauth_login.py | 393 +++++++++++++++ register.py | 299 ++++++++++++ requirements.txt | 2 + run.py | 232 +++++++++ 接口逆向.md | 1213 ++++++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 2364 insertions(+), 2 deletions(-) create mode 100644 email_service.py create mode 100644 oauth_client.py create mode 100644 oauth_login.py create mode 100644 register.py create mode 100644 requirements.txt create mode 100644 run.py create mode 100644 接口逆向.md diff --git a/README.md b/README.md index 0431e9d..d79ceb0 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,43 @@ -# protocol_chatgpt -chatgpt协议注册机 +# OpenAI 协议级注册机 + +纯 HTTP 协议实现的 OpenAI/ChatGPT 账号注册 + OAuth Token 获取工具。 + +无浏览器依赖,使用 `curl_cffi` 模拟 Chrome TLS 指纹。 + +## 安装 + +```bash +pip install curl_cffi requests +``` + +## 使用 + +```bash +# 注册单个账号并获取 OAuth Token +python run.py + +# 批量注册 +python run.py --count 5 + +# 仅注册不获取 Token +python run.py --no-oauth + +# 指定代理 +python run.py --proxy http://127.0.0.1:10808 +``` + +## 文件结构 + +``` +protocol_bot/ +├── run.py # 入口脚本 +├── email_service.py # 临时邮箱服务 +├── oauth_client.py # PKCE OAuth 客户端 +├── register.py # 协议级注册模块 +├── oauth_login.py # 协议级 OAuth 登录模块 +└── README.md +``` + +## 技术文档 + +详见 [REVERSE_ENGINEERING.md](../REVERSE_ENGINEERING.md) \ No newline at end of file diff --git a/email_service.py b/email_service.py new file mode 100644 index 0000000..c7863ac --- /dev/null +++ b/email_service.py @@ -0,0 +1,101 @@ +"""临时邮箱服务 - mail.chatgpt.org.uk API""" +from __future__ import annotations + +import re +import time +from typing import Optional, Tuple + +import requests +import urllib3 + +urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) + +BASE_URL = "https://mail.chatgpt.org.uk/api" +HEADERS = { + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", + "Origin": "https://mail.chatgpt.org.uk", + "Referer": "https://mail.chatgpt.org.uk/", +} + + +def create_temp_email() -> Optional[str]: + """创建临时邮箱,返回邮箱地址""" + try: + r = requests.get( + f"{BASE_URL}/generate-email", + headers={**HEADERS, "Content-Type": "application/json"}, + timeout=10, + verify=False, + ) + if r.status_code == 200: + data = r.json() + if data.get("success") and data.get("data", {}).get("email"): + return data["data"]["email"] + except Exception as e: + print(f"[email] 创建失败: {e}") + return None + + +def fetch_emails(email_address: str) -> list[dict]: + """获取邮件列表""" + try: + ts = int(time.time() * 1000) + r = requests.get( + f"{BASE_URL}/emails?email={email_address}&_t={ts}", + headers={**HEADERS, "Cache-Control": "no-cache"}, + timeout=30, + verify=False, + ) + if r.status_code == 200: + data = r.json() + if data.get("success") and data.get("data", {}).get("emails"): + return data["data"]["emails"] + except Exception as e: + print(f"[email] 获取邮件错误: {e}") + return [] + + +def extract_code(email_data: dict) -> Optional[str]: + """从邮件中提取验证码""" + for field in ["subject", "html_content", "content", "text_content", "body"]: + content = email_data.get(field, "") + if not content: + continue + # HTML
+ m = re.search(r']*class="code"[^>]*>(\d{6})
', content, re.I) + if m: + return m.group(1) + # verification code: XXXXXX + m = re.search(r'[Vv]erification\s+code:?\s*(\d{6})', content) + if m: + return m.group(1) + # code: XXXXXX + m = re.search(r'code:?\s*(\d{6})', content, re.I) + if m: + return m.group(1) + # 独立6位数字 + clean = re.sub(r'<[^>]+>', ' ', content) + m = re.search(r'\b(\d{6})\b', clean) + if m and m.group(1) != "177010": + return m.group(1) + return None + + +def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]: + """轮询等待验证码""" + start = time.time() + seen = set() + while time.time() - start < timeout: + for mail in fetch_emails(email_address): + mid = mail.get("id") or mail.get("date") + if mid in seen: + continue + seen.add(mid) + sender = str(mail.get("from", "") or mail.get("sender", "")).lower() + subject = str(mail.get("subject", "")).lower() + if any(k in sender or k in subject for k in ("openai", "chatgpt", "verification")): + code = extract_code(mail) + if code: + return code + time.sleep(5) + return None \ No newline at end of file diff --git a/oauth_client.py b/oauth_client.py new file mode 100644 index 0000000..c370f5a --- /dev/null +++ b/oauth_client.py @@ -0,0 +1,81 @@ +"""PKCE OAuth 客户端 - 用于获取 ChatGPT access_token / refresh_token""" +from __future__ import annotations + +import hashlib +import base64 +import secrets +from urllib.parse import urlencode + +from curl_cffi import requests as cffi_requests + +# ── PKCE / Codex OAuth 配置 ── +CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" +REDIRECT_URI = "http://localhost:1455/auth/callback" +AUTH_BASE = "https://auth.openai.com" +TOKEN_URL = f"{AUTH_BASE}/oauth/token" +AUTHORIZE_URL = f"{AUTH_BASE}/oauth/authorize" +SCOPE = "openid email profile offline_access" +AUDIENCE = "https://api.openai.com/v1" + + +def generate_pkce() -> dict: + """生成 PKCE code_verifier + code_challenge""" + verifier = secrets.token_urlsafe(32) + digest = hashlib.sha256(verifier.encode()).digest() + challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() + return {"code_verifier": verifier, "code_challenge": challenge} + + +def build_authorize_url(pkce: dict, state: str | None = None) -> str: + """构建 /oauth/authorize URL""" + if state is None: + state = secrets.token_urlsafe(24) + params = { + "client_id": CLIENT_ID, + "redirect_uri": REDIRECT_URI, + "response_type": "code", + "scope": SCOPE, + "audience": AUDIENCE, + "code_challenge": pkce["code_challenge"], + "code_challenge_method": "S256", + "state": state, + } + return f"{AUTHORIZE_URL}?{urlencode(params)}" + + +def exchange_code(code: str, code_verifier: str, proxy: str | None = None) -> dict: + """用 authorization code 换取 access_token + refresh_token""" + payload = { + "grant_type": "authorization_code", + "client_id": CLIENT_ID, + "code": code, + "redirect_uri": REDIRECT_URI, + "code_verifier": code_verifier, + } + r = cffi_requests.post( + TOKEN_URL, + json=payload, + impersonate="chrome136", + proxy=proxy, + timeout=30, + ) + r.raise_for_status() + return r.json() + + +def refresh(refresh_token: str, proxy: str | None = None) -> dict: + """用 refresh_token 刷新 access_token""" + payload = { + "grant_type": "refresh_token", + "client_id": CLIENT_ID, + "refresh_token": refresh_token, + } + r = cffi_requests.post( + TOKEN_URL, + json=payload, + impersonate="chrome136", + proxy=proxy, + timeout=30, + ) + r.raise_for_status() + return r.json() \ No newline at end of file diff --git a/oauth_login.py b/oauth_login.py new file mode 100644 index 0000000..2e203d8 --- /dev/null +++ b/oauth_login.py @@ -0,0 +1,393 @@ +"""协议级 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 格式: .. + """ + 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) \ No newline at end of file diff --git a/register.py b/register.py new file mode 100644 index 0000000..c192616 --- /dev/null +++ b/register.py @@ -0,0 +1,299 @@ +"""协议级注册模块 - 纯 HTTP 请求模拟 OpenAI 注册流程 + +流程 (基于 auth.openai.com React SPA 逆向): + 1. chatgpt.com/api/auth/csrf → CSRF token + 2. POST chatgpt.com/api/auth/signin/openai → auth.openai.com authorize URL + 3. GET authorize URL (screen_hint=signup) → 302 → /create-account + 4. POST /authorize/continue {username: {kind:"email",value:...}, screen_hint:"signup"} + → page: create_account_password + 5. POST /user/register {password, username} + → page: email_otp_send + 6. GET /email-otp/send → 触发发送验证码 + 7. POST /email-otp/validate {code} → 验证码校验 + 8. POST /create-account {name, birthdate} → onboarding + 9. Follow continue_url → OAuth callback 完成注册 +""" +from __future__ import annotations + +import json +import random +import string +import time +from dataclasses import dataclass, field +from typing import Dict, Optional +from urllib.parse import urlencode, urlparse, parse_qs, urlunparse + +from curl_cffi import requests as cffi_requests + +from email_service import create_temp_email, wait_for_code + + +def generate_random_password(length: int = 16) -> str: + chars = string.ascii_letters + string.digits + "!@#$%" + password = "".join(random.choice(chars) for _ in range(length)) + password = ( + random.choice(string.ascii_uppercase) + + random.choice(string.ascii_lowercase) + + random.choice(string.digits) + + random.choice("!@#$%") + + password[4:] + ) + return password + + +# Auth API 常量 +AUTH_API_BASE = "https://auth.openai.com/api/accounts" +SENTINEL_FALLBACK = json.dumps({"e": "q2n8w7x5z1"}) + + +@dataclass +class RegisterConfig: + proxy: str = "" + default_name: str = "John Doe" + default_birthday: Dict[str, str] = field(default_factory=lambda: {"year": "1990", "month": "05", "day": "12"}) + impersonate: str = "chrome136" + + +@dataclass +class RegisterResult: + success: bool + email: Optional[str] = None + password: Optional[str] = None + error: Optional[str] = None + + +class AccountRegister: + """协议级账号注册器 - 纯 HTTP JSON API,无浏览器依赖""" + + def __init__(self, config: RegisterConfig): + self.config = config + + def _log(self, step: str, status: str, message: str = ""): + print(f"[register][{step}] {status}: {message}") + + def _create_session(self) -> cffi_requests.Session: + session = cffi_requests.Session(impersonate=self.config.impersonate) + if self.config.proxy: + session.proxies = {"http": self.config.proxy, "https": self.config.proxy} + return session + + def _api_headers(self, referer: str = "https://auth.openai.com/create-account") -> dict: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": "https://auth.openai.com", + "Referer": referer, + "OpenAI-Sentinel-Token": SENTINEL_FALLBACK, + } + + def _api_post(self, session, path: str, payload: dict, + referer: str = "https://auth.openai.com/create-account") -> tuple[dict, int]: + url = f"{AUTH_API_BASE}{path}" + 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, path: str, + referer: str = "https://auth.openai.com/create-account") -> tuple[dict, int]: + url = f"{AUTH_API_BASE}{path}" + 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: + page = data.get("page", {}) + if isinstance(page, dict): + return page.get("type", "") + return str(page) + + def _extract_error(self, data: dict) -> str: + err = data.get("error", {}) + if isinstance(err, dict): + return err.get("message", str(err)) + return str(err) + + # ── 主流程 ── + + def register_one(self) -> RegisterResult: + email = None + password = None + + try: + # 1. 创建临时邮箱 + self._log("create_email", "start", "创建临时邮箱") + email = create_temp_email() + if not email: + self._log("create_email", "error", "邮箱创建失败") + return RegisterResult(success=False, error="邮箱创建失败") + self._log("create_email", "ok", f"邮箱: {email}") + + # 2. 生成密码 + password = generate_random_password() + self._log("generate_password", "ok", f"password={password}") + + # 3. 创建 HTTP session + session = self._create_session() + + # 4. 建立 OAuth 会话 (screen_hint=signup → /create-account) + self._log("oauth_session", "start", "建立 OAuth 会话") + if not self._establish_auth_session(session): + return RegisterResult(success=False, email=email, password=password, + error="OAuth 会话建立失败") + + # 5. 提交邮箱 + self._log("submit_email", "start", f"提交邮箱: {email}") + data, status = self._api_post(session, "/authorize/continue", { + "username": {"kind": "email", "value": email}, + "screen_hint": "signup", + }) + page_type = self._get_page_type(data) + self._log("submit_email", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"邮箱提交失败: {status} {self._extract_error(data)}") + + if page_type != "create_account_password": + self._log("submit_email", "error", f"预期 create_account_password,实际 {page_type}") + return RegisterResult(success=False, email=email, password=password, + error=f"邮箱提交后页面异常: {page_type}") + + # 6. 提交密码 (POST /user/register) + self._log("submit_password", "start", "提交密码到 /user/register") + data, status = self._api_post( + session, "/user/register", + {"password": password, "username": email}, + referer="https://auth.openai.com/create-account/password", + ) + page_type = self._get_page_type(data) + self._log("submit_password", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"密码提交失败: {status} {self._extract_error(data)}") + + # 7. 邮箱 OTP 验证 + if page_type == "email_otp_send": + self._log("otp_send", "start", "触发发送 OTP") + send_data, send_status = self._api_get( + session, "/email-otp/send", + referer="https://auth.openai.com/email-verification", + ) + self._log("otp_send", "info", f"status={send_status}") + + self._log("otp_wait", "start", "等待验证邮件") + code = wait_for_code(email) + if not code: + self._log("otp_wait", "error", "验证码获取超时") + return RegisterResult(success=False, email=email, password=password, + error="验证码获取超时") + + self._log("otp_validate", "start", f"提交验证码: {code}") + data, status = self._api_post( + session, "/email-otp/validate", + {"code": code}, + referer="https://auth.openai.com/email-verification", + ) + page_type = self._get_page_type(data) + self._log("otp_validate", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"验证码校验失败: {status} {self._extract_error(data)}") + + # 8. Onboarding (about_you / create_account_start) + if page_type in ("about_you", "create_account_start"): + self._log("onboarding", "start", "填写 onboarding 信息") + bd = self.config.default_birthday + birthday_str = f"{bd['year']}-{bd['month'].zfill(2)}-{bd['day'].zfill(2)}" + + data, status = self._api_post( + session, "/create_account", + {"name": self.config.default_name, "birthdate": birthday_str}, + referer="https://auth.openai.com/about-you", + ) + self._log("onboarding", "info", f"status={status}") + + if status != 200: + error_msg = self._extract_error(data) + self._log("onboarding", "error", f"Onboarding 失败: {error_msg}") + return RegisterResult(success=False, email=email, password=password, + error=f"Onboarding 失败: {status} {error_msg}") + + continue_url = data.get("continue_url", "") + if continue_url and continue_url.startswith("http"): + self._log("onboarding", "ok", f"Continue: {continue_url[:80]}") + session.get(continue_url, allow_redirects=True, timeout=30) + page_type = self._get_page_type(data) + + # 9. 如果还有 continue_url,跟随完成 + continue_url = data.get("continue_url", "") + if continue_url and continue_url.startswith("http"): + self._log("finalize", "info", f"Following continue_url: {continue_url[:80]}") + session.get(continue_url, allow_redirects=True, timeout=30) + + self._log("register", "ok", f"注册成功: {email}") + return RegisterResult(success=True, email=email, password=password) + + except Exception as e: + self._log("register", "error", str(e)) + return RegisterResult(success=False, email=email, password=password, error=str(e)) + + # ── 会话建立 ── + + def _establish_auth_session(self, session: cffi_requests.Session) -> bool: + """建立注册会话: CSRF → signin/openai → authorize(screen_hint=signup) → /create-account""" + try: + # CSRF token + r = session.get("https://chatgpt.com/api/auth/csrf", timeout=30) + if r.status_code != 200: + self._log("oauth_session", "error", f"CSRF 获取失败: {r.status_code}") + return False + csrf = r.json().get("csrfToken", "") + if not csrf: + self._log("oauth_session", "error", "CSRF token 为空") + return False + self._log("oauth_session", "info", f"CSRF: {csrf[:20]}...") + + # POST signin/openai → auth URL + r = session.post( + "https://chatgpt.com/api/auth/signin/openai", + data={ + "csrfToken": csrf, + "callbackUrl": "https://chatgpt.com/", + "json": "true", + }, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + timeout=30, + ) + if r.status_code != 200: + self._log("oauth_session", "error", f"signin 失败: {r.status_code}") + return False + + auth_url = r.json().get("url", "") + if not auth_url or "auth.openai.com" not in auth_url: + self._log("oauth_session", "error", f"无效 auth URL: {auth_url[:100]}") + return False + + # 添加 screen_hint=signup + parsed = urlparse(auth_url) + qs = parse_qs(parsed.query, keep_blank_values=True) + qs["screen_hint"] = ["signup"] + auth_url = urlunparse(parsed._replace(query=urlencode(qs, doseq=True))) + self._log("oauth_session", "info", f"Auth URL: {auth_url[:120]}...") + + # GET authorize → 302 → /create-account (建立 session cookies) + r = session.get(auth_url, allow_redirects=True, timeout=30) + final_url = str(r.url) + self._log("oauth_session", "ok", f"会话已建立, final={final_url[:80]}") + return True + + except Exception as e: + self._log("oauth_session", "error", f"会话建立异常: {e}") + return False \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..cc61b68 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +curl_cffi>=0.7.0 +requests>=2.31.0 \ No newline at end of file diff --git a/run.py b/run.py new file mode 100644 index 0000000..079f92d --- /dev/null +++ b/run.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python3 +"""OpenAI 协议注册机 - 直接运行 python run.py 即可 + +修改下面的配置即可控制行为: +""" +from __future__ import annotations + +import base64 +import json +import os +import sys +import threading +from concurrent.futures import ThreadPoolExecutor, as_completed +from datetime import datetime, timezone, timedelta + +# ╔══════════════════════════════════════════════════════════╗ +# ║ 配 置 区 域 ║ +# ║ 修改以下变量即可,直接 python run.py 运行 ║ +# ╚══════════════════════════════════════════════════════════╝ + +THREADS = 8 # 并行线程数 (1 = 单线程顺序执行) +COUNT = 16 # 注册账号数量 +SKIP_OAUTH = False # True = 只注册不做 OAuth 获取 token +PROXY = "http://127.0.0.1:10808" # 代理地址 + +# ══════════════════════════════════════════════════════════ + +# 确保当前目录在 sys.path 中 +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) + +from register import AccountRegister, RegisterConfig, RegisterResult +from oauth_login import OAuthLogin, PasswordMismatchError, BannedError +from oauth_client import generate_pkce, build_authorize_url, exchange_code + +ACCOUNTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "accounts") + +_lock = threading.Lock() +_counter = {"success": 0, "failed": 0} + + +def do_register(config: RegisterConfig) -> RegisterResult: + reg = AccountRegister(config=config) + return reg.register_one() + + +def do_oauth(email: str, password: str, proxy: str) -> dict: + pkce = generate_pkce() + state = "bot_" + datetime.now().strftime("%Y%m%d%H%M%S") + auth_url = build_authorize_url(pkce, state=state) + + login = OAuthLogin(proxy=proxy) + code = login.authorize( + auth_url=auth_url, + state=state, + email=email, + password=password, + use_email_otp=True, + ) + + tokens = exchange_code(code, pkce["code_verifier"], proxy=proxy) + return tokens + + +def _decode_jwt_payload(token: str) -> dict: + """解码 JWT payload(不验证签名)""" + try: + parts = token.split(".") + if len(parts) < 2: + return {} + payload_b64 = parts[1] + padded = payload_b64 + "=" * (4 - len(payload_b64) % 4) + decoded = base64.urlsafe_b64decode(padded) + return json.loads(decoded.decode("utf-8")) + except Exception: + return {} + + +def _email_to_filename(email: str) -> str: + """将邮箱转为文件名: @ 和 . 替换为 _""" + return email.replace("@", "_").replace(".", "_") + + +def save_account(record: dict, *, is_failed: bool = False): + """按状态保存到不同子文件夹: + - accounts/oauth/ 注册+OAuth 都成功 + - accounts/unoauth/ 注册成功但未做/跳过 OAuth + - accounts/failed/ 注册失败或 OAuth 失败 + """ + if is_failed: + subdir = "failed" + elif record.get("type") == "codex": + subdir = "oauth" + else: + subdir = "unoauth" + + target_dir = os.path.join(ACCOUNTS_DIR, subdir) + os.makedirs(target_dir, exist_ok=True) + + email = record.get("email", "unknown") + filename = _email_to_filename(email) + filepath = os.path.join(target_dir, f"{filename}.json") + with open(filepath, "w", encoding="utf-8") as f: + json.dump(record, f, ensure_ascii=False, indent=2) + print(f"[save] {filepath}") + + +def _build_oauth_record(email: str, tokens: dict) -> dict: + """从 OAuth token 响应构建目标格式的 record""" + access_token = tokens.get("access_token", "") + refresh_token = tokens.get("refresh_token", "") + id_token = tokens.get("id_token", "") + + # 从 access_token 解析 account_id 和 expired + jwt_payload = _decode_jwt_payload(access_token) + auth_info = jwt_payload.get("https://api.openai.com/auth", {}) + account_id = auth_info.get("chatgpt_account_id", "") + + # exp → ISO 8601 带时区 + exp = jwt_payload.get("exp") + if exp: + expired_dt = datetime.fromtimestamp(exp, tz=timezone(timedelta(hours=8))) + expired = expired_dt.isoformat() + else: + expired = "" + + now_dt = datetime.now(tz=timezone(timedelta(hours=8))) + + return { + "access_token": access_token, + "account_id": account_id, + "disabled": False, + "email": email, + "expired": expired, + "id_token": id_token, + "last_refresh": now_dt.isoformat(), + "refresh_token": refresh_token, + "type": "codex", + } + + +def _do_one(index: int, config: RegisterConfig, proxy: str, skip_oauth: bool) -> dict: + result = do_register(config) + + if not result.success: + record = { + "email": result.email, + "password": result.password, + "register_error": result.error or "unknown", + } + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + return record + + if skip_oauth: + record = {"email": result.email, "password": result.password} + save_account(record) + with _lock: + _counter["success"] += 1 + return record + + try: + tokens = do_oauth(result.email, result.password, proxy) + record = _build_oauth_record(result.email, tokens) + record["password"] = result.password + save_account(record) + with _lock: + _counter["success"] += 1 + except PasswordMismatchError as e: + record = {"email": result.email, "password": result.password, "oauth_error": f"password_mismatch: {e}"} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + except BannedError as e: + record = {"email": result.email, "password": result.password, "oauth_error": f"banned: {e}"} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + except Exception as e: + record = {"email": result.email, "password": result.password, "oauth_error": str(e)} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + + return record + + +def main(): + count = COUNT + threads = max(1, min(THREADS, count)) + proxy = PROXY + skip_oauth = SKIP_OAUTH + + config = RegisterConfig(proxy=proxy) + + _counter["success"] = 0 + _counter["failed"] = 0 + + print(f"开始批量注册: {count} 个账号, {threads} 线程并行") + print(f"代理: {proxy}") + print(f"跳过 OAuth: {skip_oauth}") + print(f"{'='*60}") + + import time as _time + start_time = _time.time() + + if threads <= 1: + for i in range(count): + _do_one(i + 1, config, proxy, skip_oauth) + else: + with ThreadPoolExecutor(max_workers=threads) as executor: + futures = { + executor.submit(_do_one, i + 1, config, proxy, skip_oauth): i + for i in range(count) + } + for future in as_completed(futures): + try: + future.result() + except Exception as e: + print(f"[error] 线程异常: {e}") + + elapsed = _time.time() - start_time + avg_time = elapsed / count if count > 0 else 0 + + print(f"\n{'='*60}") + print(f"完成: 成功 {_counter['success']}, 失败 {_counter['failed']}, 共 {count}") + print(f"总耗时: {elapsed:.1f}s | 平均速度: {avg_time:.1f}s/个") + print(f"账号文件保存在: {ACCOUNTS_DIR}") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/接口逆向.md b/接口逆向.md new file mode 100644 index 0000000..bffbde7 --- /dev/null +++ b/接口逆向.md @@ -0,0 +1,1213 @@ +# OpenAI auth.openai.com 逆向工程文档 + +> 本文档记录了对 `auth.openai.com` 认证系统的完整逆向工程过程,包括架构分析、API 端点发现、认证流程破解、以及绕过方法。所有内容均基于实际测试验证。 + +--- + +## 目录 + +1. [架构概述](#1-架构概述) +2. [JS Bundle 分析方法](#2-js-bundle-分析方法) +3. [两套 OAuth 客户端配置](#3-两套-oauth-客户端配置) +4. [API 端点完整列表](#4-api-端点完整列表) +5. [注册流程 (Registration)](#5-注册流程-registration) +6. [PKCE OAuth 登录流程](#6-pkce-oauth-登录流程) +7. [Cookie 格式与解码](#7-cookie-格式与解码) +8. [OpenAI-Sentinel-Token 头](#8-openai-sentinel-token-头) +9. [TLS 指纹模拟](#9-tls-指纹模拟) +10. [常见问题与解决方案](#10-常见问题与解决方案) +11. [完整示例代码](#11-完整示例代码) + +--- + +## 1. 架构概述 + +### 1.1 auth.openai.com 不是传统 HTML 表单 + +**关键发现**: `auth.openai.com` 是一个 **React SPA** (Single Page Application),使用 **React Router v7** 配合 **SSR Streaming** 渲染。 + +这意味着: +- 所有页面都是 React 组件,不是传统的 HTML `
` 表单 +- 所有认证步骤通过 **JSON API** 完成,不是 form POST +- 页面 HTML 中看不到有用的表单元素,只有 React 挂载点 +- 传统的 HTML 解析 + form 提交方式完全无效 + +### 1.2 SSR Streaming 响应格式 + +访问 `auth.openai.com` 的任何页面,返回的 HTML 包含: + +```html + + + + + +``` + +HTML body 中的实际内容是 SSR 预渲染的 React 组件输出,但所有交互逻辑都在 JS bundle 中。 + +### 1.3 技术栈 + +| 组件 | 技术 | +|------|------| +| 前端框架 | React 18+ | +| 路由 | React Router v7 (SSR mode) | +| 构建工具 | Vite | +| API 通信 | fetch + JSON | +| 状态管理 | React Router loaders/actions | +| 部署 | Cloudflare (CDN + WAF) | + +--- + +## 2. JS Bundle 分析方法 + +### 2.1 React Router Manifest + +React Router v7 在 HTML 中嵌入了路由清单 (manifest),包含所有路由模块的映射: + +``` +GET https://auth.openai.com/__manifest +``` + +返回 JSON 格式的路由清单: + +```json +{ + "version": "...", + "entry": { "module": "/assets/entry.client-XXXXX.js" }, + "routes": { + "root": { + "id": "root", + "path": "", + "module": "/assets/root-XXXXX.js" + }, + "routes/log-in": { + "id": "routes/log-in", + "path": "log-in", + "parentId": "root", + "module": "/assets/log-in-XXXXX.js" + }, + "routes/create-account": { + "id": "routes/create-account", + "path": "create-account", + "module": "/assets/create-account-XXXXX.js" + } + // ... 更多路由 + } +} +``` + +### 2.2 路由模块分析 + +每个路由模块 JS 文件包含该页面的完整逻辑,包括: +- `loader` 函数:页面加载时的数据获取 +- `action` 函数:表单提交处理 +- React 组件:UI 渲染 + +**关键路由模块及其发现**: + +| 路由 | 模块文件 | 关键发现 | +|------|----------|----------| +| `/log-in` | `log-in-XXXXX.js` | 邮箱提交 → `/api/accounts/authorize/continue` | +| `/log-in/password` | `password-XXXXX.js` | 密码提交 → `/api/first_party_authorize/next` | +| `/create-account` | `create-account-XXXXX.js` | 注册邮箱提交 → `/api/accounts/authorize/continue` + `screen_hint=signup` | +| `/create-account/password` | `password-XXXXX.js` | 注册密码 → `/api/accounts/user/register` | +| `/email-verification` | `email-verification-XXXXX.js` | OTP 发送/验证 | +| `/about-you` | `about-you-XXXXX.js` | Onboarding → `/api/accounts/create_account` | +| `/sign-in-with-chatgpt-codex-consent` | `consent-XXXXX.js` | Workspace 选择 → `/api/accounts/workspace/select` | +| `/sign-in-with-chatgpt-consent` | `consent-XXXXX.js` | 普通 consent → `/api/accounts/consent/grant` | + +### 2.3 JS Bundle 中的 API 调用模式 + +在 JS bundle 中,API 调用使用统一的 helper 函数: + +```javascript +// 简化后的 API 调用模式 +async function apiPost(session, path, body) { + const response = await fetch(`/api/accounts${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "OpenAI-Sentinel-Token": getSentinelToken(), + }, + body: JSON.stringify(body), + }); + return response.json(); +} + +// 密码提交使用不同的端点 +async function firstPartyAuthorize(data) { + return fetch("/api/first_party_authorize/next", { + method: "POST", + headers: { "Content-Type": "application/json", "OpenAI-Sentinel-Token": "..." }, + body: JSON.stringify(data), + }); +} +``` + +### 2.4 如何找到正确的 API 端点 + +1. 从 `__manifest` 获取路由模块 URL +2. 下载对应的 JS 文件 +3. 搜索 `fetch(` 或 `/api/` 关键字 +4. 分析 `action` 函数中的请求构造逻辑 +5. 注意 `FormData` → `JSON.stringify` 的转换 + +**示例 - 从 JS bundle 中发现密码提交端点**: + +```javascript +// 在 password route module 中找到: +let action = async ({ request }) => { + let formData = await request.formData(); + let response = await fetch("/api/first_party_authorize/next", { + method: "POST", + body: JSON.stringify({ + origin_page_type: "login_password", + data: { + intent: formData.get("intent"), + username: { value: formData.get("email"), kind: "email" }, + password: formData.get("password"), + }, + }), + }); + // ... +}; +``` + +--- + +## 3. 两套 OAuth 客户端配置 + +OpenAI 使用两套完全不同的 OAuth 客户端,支持不同的 API 端点: + +### 3.1 ChatGPT 内部客户端 (NextAuth) + +用于 `chatgpt.com` 的内部认证,通过 NextAuth 框架管理。 + +| 参数 | 值 | +|------|-----| +| 触发方式 | `chatgpt.com/api/auth/signin/openai` | +| client_id | `app_X8zY6vW2pQ9tR3dE7nK1jL5gH` (由服务端管理) | +| redirect_uri | `https://chatgpt.com/api/auth/callback/openai` | +| 用途 | 注册、chatgpt.com 网页登录 | + +**支持的端点**: +- `/api/accounts/authorize/continue` — 邮箱提交 +- `/api/accounts/user/login` — 密码登录 ✅ +- `/api/accounts/user/register` — 注册 ✅ +- `/api/accounts/email-otp/send` — 发送 OTP ✅ +- `/api/accounts/email-otp/validate` — 验证 OTP ✅ +- `/api/accounts/create_account` — Onboarding ✅ + +### 3.2 PKCE / Codex 客户端 + +用于第三方应用 (如 Codex CLI) 的 OAuth 授权。 + +| 参数 | 值 | +|------|-----| +| client_id | `app_EMoamEEZ73f0CkXaXp7hrann` | +| redirect_uri | `http://localhost:1455/auth/callback` | +| response_type | `code` | +| scope | `openid email profile offline_access` | +| audience | `https://api.openai.com/v1` | +| code_challenge_method | `S256` | + +**支持的端点**: +- `/api/accounts/authorize/continue` — 邮箱提交 ✅ +- `/api/first_party_authorize/next` — 密码提交 ✅ (注意: 不是 `/user/login`) +- `/api/accounts/workspace/select` — Workspace 选择 ✅ +- `/api/accounts/organization/select` — Organization + Project 选择 ✅ +- `/api/accounts/email-otp/send` — 发送 OTP ✅ +- `/api/accounts/email-otp/validate` — 验证 OTP ✅ + +**不支持的端点**: +- `/api/accounts/user/login` — 返回 404 ❌ +- `/api/accounts/user/register` — 返回 404 ❌ + +### 3.3 关键区别 + +| 特性 | 内部客户端 | PKCE 客户端 | +|------|-----------|-------------| +| 密码提交 | `/user/login` | `/first_party_authorize/next` | +| 密码 payload | `{password, username}` | `{origin_page_type, data: {intent, username, password}}` | +| Consent 页面 | `sign_in_with_chatgpt_consent` | `sign_in_with_chatgpt_codex_consent` | +| Consent 处理 | `/consent/grant` | `/workspace/select` → `/organization/select` | +| 返回值 | session cookie | authorization code | + +--- + +## 4. API 端点完整列表 + +### 4.1 chatgpt.com 端点 + +``` +GET https://chatgpt.com/api/auth/csrf + → {"csrfToken": "..."} + +POST https://chatgpt.com/api/auth/signin/openai + Content-Type: application/x-www-form-urlencoded + Body: csrfToken=...&callbackUrl=https://chatgpt.com/&json=true + → {"url": "https://auth.openai.com/oauth/authorize?..."} +``` + +### 4.2 auth.openai.com 端点 + +#### 邮箱提交 (两种流程通用) +``` +POST https://auth.openai.com/api/accounts/authorize/continue +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +# 登录: +{"username": {"kind": "email", "value": "user@example.com"}} + +# 注册: +{"username": {"kind": "email", "value": "user@example.com"}, "screen_hint": "signup"} + +→ 200 {"page": {"type": "login_password"}} # 已注册用户 +→ 200 {"page": {"type": "create_account_password"}} # 新用户注册 +``` + +#### 密码登录 (PKCE 流程) +``` +POST https://auth.openai.com/api/first_party_authorize/next +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +{ + "origin_page_type": "login_password", + "data": { + "intent": "validate", + "username": {"value": "user@example.com", "kind": "email"}, + "password": "your_password" + } +} + +→ 200 {"type": "sign_in_with_chatgpt_codex_consent"} # 需要 consent +→ 200 {"type": "external_url", "continue_url": "..."} # 直接完成 +``` + +#### 密码注册 (内部客户端) +``` +POST https://auth.openai.com/api/accounts/user/register +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +{"password": "your_password", "username": "user@example.com"} + +→ 200 {"page": {"type": "email_otp_send"}} +``` + +#### OTP 发送 +``` +GET https://auth.openai.com/api/accounts/email-otp/send +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +→ 200 {"page": {"type": "email_otp_verification"}} +``` + +#### OTP 验证 +``` +POST https://auth.openai.com/api/accounts/email-otp/validate +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +{"code": "123456"} + +→ 200 {"page": {"type": "about_you"}} # 需要 onboarding +→ 200 {"page": {"type": "..."}, "continue_url": "..."} # 直接完成 +``` + +#### Onboarding +``` +POST https://auth.openai.com/api/accounts/create_account +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +{"name": "John Doe", "birthdate": "1990-05-12"} + +→ 200 {"continue_url": "https://auth.openai.com/oauth/authorize/continue?..."} +→ 400 {"error": {"message": "unsupported_email"}} # 邮箱域名被封 +``` + +#### Workspace 选择 (PKCE Codex Consent) +``` +POST https://auth.openai.com/api/accounts/workspace/select +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} + +{"workspace_id": "wsp_xxxxxxxxxxxxxxxx"} + +→ 200 {"type": "sign_in_with_chatgpt_codex_org", "data": {"orgs": [...]}} + 或 +→ 200 {"type": "external_url", "continue_url": "https://..."} +``` + +#### Organization 选择 (PKCE Codex Org) +``` +POST https://auth.openai.com/api/accounts/organization/select +Content-Type: application/json +OpenAI-Sentinel-Token: {"e":"q2n8w7x5z1"} +Referer: https://auth.openai.com/sign-in-with-chatgpt/codex/organization + +{"org_id": "org-xxxxxxxxxxxxxxxx", "project_id": "proj_xxxxxxxxxxxxxxxx"} + +→ 200 {"type": "external_url", "continue_url": "https://auth.openai.com/api/oauth/oauth2/auth?..."} +``` + +`workspace/select` 返回的 `data.orgs` 结构: +```json +{ + "data": { + "orgs": [ + { + "id": "org-x8jWL8oV4Mn5mroVr3icqiOS", + "projects": [ + {"id": "proj_A6Sn7l4h85zuDvWcZfozZMeP"} + ] + } + ] + } +} +``` + +#### Consent Grant (非 Codex 流程) +``` +POST https://auth.openai.com/api/accounts/consent/grant +Content-Type: application/json + +→ 200 {"continue_url": "..."} +``` + +### 4.3 Token 端点 + +``` +POST https://auth.openai.com/oauth/token +Content-Type: application/json + +{ + "grant_type": "authorization_code", + "client_id": "app_EMoamEEZ73f0CkXaXp7hrann", + "code": "auth_code_here", + "redirect_uri": "http://localhost:1455/auth/callback", + "code_verifier": "pkce_verifier_here" +} + +→ 200 { + "access_token": "eyJhbGciOi...", + "refresh_token": "v1.xxx...", + "token_type": "Bearer", + "expires_in": 3600 +} +``` + +--- + +## 5. 注册流程 (Registration) + +### 5.1 流程图 + +``` +chatgpt.com/api/auth/csrf + │ GET → csrfToken + ▼ +chatgpt.com/api/auth/signin/openai + │ POST (csrfToken) → auth_url + ▼ +auth.openai.com/oauth/authorize?...&screen_hint=signup + │ GET (allow_redirects=True) → 建立 session cookies + ▼ +/api/accounts/authorize/continue + │ POST {username: {kind:"email", value:...}, screen_hint:"signup"} + │ → page: create_account_password + ▼ +/api/accounts/user/register + │ POST {password, username} + │ → page: email_otp_send + ▼ +/api/accounts/email-otp/send + │ GET → 触发发送验证码邮件 + ▼ +[等待邮件,提取 6 位验证码] + ▼ +/api/accounts/email-otp/validate + │ POST {code: "123456"} + │ → page: about_you + ▼ +/api/accounts/create_account + │ POST {name, birthdate} + │ → continue_url + ▼ +GET continue_url (follow redirects) → 注册完成 +``` + +### 5.2 关键细节 + +1. **screen_hint=signup**: 必须在 authorize URL 中添加此参数,否则会进入登录流程而非注册 +2. **结构化 username**: 邮箱必须以 `{"kind": "email", "value": "..."}` 格式提交,不能直接传字符串 +3. **session cookies**: `allow_redirects=True` 让 curl_cffi 自动跟随重定向,建立完整的 session +4. **邮箱域名限制**: 某些临时邮箱域名 (如 `bpmft.cn`) 会在 onboarding 阶段被拒绝 (`unsupported_email`) + +### 5.3 示例代码 + +```python +from curl_cffi import requests as cffi_requests +import json + +PROXY = "http://127.0.0.1:10808" +SENTINEL = json.dumps({"e": "q2n8w7x5z1"}) +AUTH_API = "https://auth.openai.com/api/accounts" + +session = cffi_requests.Session(impersonate="chrome136") +session.proxies = {"http": PROXY, "https": PROXY} + +headers = { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": "https://auth.openai.com", + "Referer": "https://auth.openai.com/create-account", + "OpenAI-Sentinel-Token": SENTINEL, +} + +# 1. CSRF +csrf = session.get("https://chatgpt.com/api/auth/csrf").json()["csrfToken"] + +# 2. 获取 auth URL +r = session.post("https://chatgpt.com/api/auth/signin/openai", data={ + "csrfToken": csrf, "callbackUrl": "https://chatgpt.com/", "json": "true", +}, headers={"Content-Type": "application/x-www-form-urlencoded"}) +auth_url = r.json()["url"] + "&screen_hint=signup" + +# 3. 建立 session +session.get(auth_url, allow_redirects=True) + +# 4. 提交邮箱 +r = session.post(f"{AUTH_API}/authorize/continue", json={ + "username": {"kind": "email", "value": "user@example.com"}, + "screen_hint": "signup", +}, headers=headers) +print(r.json()) # {"page": {"type": "create_account_password"}} + +# 5. 提交密码 +r = session.post(f"{AUTH_API}/user/register", json={ + "password": "MyP@ssw0rd123", "username": "user@example.com", +}, headers=headers) +print(r.json()) # {"page": {"type": "email_otp_send"}} + +# 6. 触发 OTP +session.get(f"{AUTH_API}/email-otp/send", headers=headers) + +# 7. 验证 OTP (从邮件中获取验证码) +r = session.post(f"{AUTH_API}/email-otp/validate", json={ + "code": "123456", +}, headers=headers) +print(r.json()) # {"page": {"type": "about_you"}} + +# 8. Onboarding +r = session.post(f"{AUTH_API}/create_account", json={ + "name": "John Doe", "birthdate": "1990-05-12", +}, headers=headers) +print(r.json()) # {"continue_url": "https://..."} +``` + +--- + +## 6. PKCE OAuth 登录流程 + +### 6.1 流程图 + +``` +生成 PKCE (code_verifier + code_challenge) + ▼ +构建 authorize URL: + auth.openai.com/oauth/authorize? + client_id=app_EMoamEEZ73f0CkXaXp7hrann + &redirect_uri=http://localhost:1455/auth/callback + &response_type=code + &scope=openid email profile offline_access + &audience=https://api.openai.com/v1 + &code_challenge=... + &code_challenge_method=S256 + &state=... + ▼ +GET authorize URL (allow_redirects=True) + │ → 建立 session cookies, 最终到达 /log-in + ▼ +POST /api/accounts/authorize/continue + │ {username: {kind:"email", value:...}} + │ → page: login_password + ▼ +POST /api/first_party_authorize/next ← 注意: 不是 /user/login ! + │ {origin_page_type: "login_password", + │ data: {intent:"validate", username:{...}, password:...}} + │ → type: sign_in_with_chatgpt_codex_consent + ▼ +解码 oai-client-auth-session cookie → workspace_id + ▼ +POST /api/accounts/workspace/select + │ {workspace_id: "wsp_xxx"} + │ → type: sign_in_with_chatgpt_codex_org, data: {orgs: [...]} + ▼ +POST /api/accounts/organization/select + │ {org_id: "org-xxx", project_id: "proj_xxx"} + │ → type: external_url, continue_url: "https://..." + ▼ +跟踪 redirect chain (allow_redirects=False, 逐跳) + │ auth.openai.com/oauth/authorize/continue?... + │ → 302 → ... → 302 → localhost:1455/auth/callback?code=...&state=... + ▼ +提取 code 参数 + ▼ +POST auth.openai.com/oauth/token + │ {grant_type:"authorization_code", client_id, code, redirect_uri, code_verifier} + ▼ +获得 access_token + refresh_token +``` + +### 6.2 关键发现 + +#### 6.2.1 `/user/login` 在 PKCE 流程中返回 404 + +这是最重要的发现之一。PKCE 客户端的 session 不支持 `/api/accounts/user/login` 端点。必须使用 `/api/first_party_authorize/next`。 + +**错误方式**: +```python +# ❌ 这在 PKCE 流程中会返回 404 +session.post(f"{AUTH_API}/user/login", json={ + "password": "...", "username": "..." +}) +``` + +**正确方式**: +```python +# ✅ PKCE 流程必须使用这个端点 +session.post("https://auth.openai.com/api/first_party_authorize/next", json={ + "origin_page_type": "login_password", + "data": { + "intent": "validate", + "username": {"value": "user@example.com", "kind": "email"}, + "password": "MyP@ssw0rd123", + }, +}) +``` + +#### 6.2.2 响应格式不一致 + +不同端点返回的 page type 格式不同: + +```python +# /api/accounts/authorize/continue 返回: +{"page": {"type": "login_password"}} + +# /api/first_party_authorize/next 返回: +{"type": "sign_in_with_chatgpt_codex_consent"} # 注意: 没有 "page" 包装 + +# /api/accounts/workspace/select 返回: +{"type": "external_url", "continue_url": "..."} +``` + +代码中需要兼容两种格式: + +```python +def get_page_type(data: dict) -> str: + # 格式1: {"page": {"type": "..."}} + page = data.get("page", {}) + if isinstance(page, dict) and page.get("type"): + return page["type"] + # 格式2: {"type": "..."} + if data.get("type"): + return data["type"] + return "" +``` + +#### 6.2.3 Codex Consent vs 普通 Consent + +PKCE 流程进入的是 `sign_in_with_chatgpt_codex_consent`,不是 `sign_in_with_chatgpt_consent`。 + +三者使用完全不同的 API: + +| Consent 类型 | 端点 | Payload | +|-------------|------|---------| +| `sign_in_with_chatgpt_consent` | `/api/accounts/consent/grant` | `{}` (空) | +| `sign_in_with_chatgpt_codex_consent` | `/api/accounts/workspace/select` | `{"workspace_id": "wsp_xxx"}` | +| `sign_in_with_chatgpt_codex_org` | `/api/accounts/organization/select` | `{"org_id": "org-xxx", "project_id": "proj_xxx"}` | + +PKCE 流程的完整 consent 链: `codex_consent` → `workspace/select` → `codex_org` → `organization/select` → `external_url`。 + +如果对 codex consent 使用 `/consent/grant`,会返回 400 错误。 + +### 6.3 示例代码 + +```python +import hashlib, base64, secrets, json, urllib.parse +from curl_cffi import requests as cffi_requests + +PROXY = "http://127.0.0.1:10808" +CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" +REDIRECT_URI = "http://localhost:1455/auth/callback" +SENTINEL = json.dumps({"e": "q2n8w7x5z1"}) + +# PKCE +verifier = secrets.token_urlsafe(32) +challenge = base64.urlsafe_b64encode( + hashlib.sha256(verifier.encode()).digest() +).rstrip(b"=").decode() +state = secrets.token_urlsafe(24) + +auth_url = ( + f"https://auth.openai.com/oauth/authorize?" + f"client_id={CLIENT_ID}&redirect_uri={urllib.parse.quote(REDIRECT_URI)}" + f"&response_type=code&scope=openid+email+profile+offline_access" + f"&audience=https://api.openai.com/v1" + f"&code_challenge={challenge}&code_challenge_method=S256&state={state}" +) + +session = cffi_requests.Session(impersonate="chrome136") +session.proxies = {"http": PROXY, "https": PROXY} + +headers = { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": "https://auth.openai.com", + "Referer": "https://auth.openai.com/log-in", + "OpenAI-Sentinel-Token": SENTINEL, +} + +# 1. 建立 session +session.get(auth_url, allow_redirects=True) + +# 2. 提交邮箱 +r = session.post( + "https://auth.openai.com/api/accounts/authorize/continue", + json={"username": {"kind": "email", "value": "user@example.com"}}, + headers=headers, +) +# → {"page": {"type": "login_password"}} + +# 3. 提交密码 +r = session.post( + "https://auth.openai.com/api/first_party_authorize/next", + json={ + "origin_page_type": "login_password", + "data": { + "intent": "validate", + "username": {"value": "user@example.com", "kind": "email"}, + "password": "MyP@ssw0rd123", + }, + }, + headers={**headers, "Referer": "https://auth.openai.com/log-in/password"}, +) +data = r.json() +# → {"type": "sign_in_with_chatgpt_codex_consent"} + +# 4. 提取 workspace_id +for cookie in session.cookies.jar: + if cookie.name == "oai-client-auth-session": + payload_b64 = str(cookie.value).split(".")[0] + padded = payload_b64 + "=" * (4 - len(payload_b64) % 4) + decoded = json.loads(base64.urlsafe_b64decode(padded)) + workspace_id = decoded["workspaces"][0]["id"] + break + +# 5. Workspace 选择 +r = session.post( + "https://auth.openai.com/api/accounts/workspace/select", + json={"workspace_id": workspace_id}, + headers={**headers, "Referer": "https://auth.openai.com/sign-in-with-chatgpt-codex-consent"}, +) +data = r.json() +continue_url = data["continue_url"] + +# 6. 跟踪重定向获取 code +url = continue_url +for _ in range(15): + r = session.get(url, allow_redirects=False) + if 300 <= r.status_code < 400: + location = r.headers.get("Location", "") + if "localhost:1455" in location: + parsed = urllib.parse.urlparse(location) + q = urllib.parse.parse_qs(parsed.query) + code = q["code"][0] + print(f" +Authorization code: {code}") + break + if not location.startswith("http"): + parsed = urllib.parse.urlparse(url) + location = f"{parsed.scheme}://{parsed.netloc}{location}" + url = location + else: + break + +# 7. 换取 token +r = cffi_requests.post("https://auth.openai.com/oauth/token", json={ + "grant_type": "authorization_code", + "client_id": CLIENT_ID, + "code": code, + "redirect_uri": REDIRECT_URI, + "code_verifier": verifier, +}, impersonate="chrome136", proxy=PROXY) +tokens = r.json() +print(f"access_token: {tokens['access_token'][:50]}...") +print(f"refresh_token: {tokens['refresh_token'][:30]}...") +``` + +--- + +## 7. Cookie 格式与解码 + +### 7.1 oai-client-auth-session Cookie + +这是 PKCE 流程中最关键的 cookie,包含用户的 workspace 信息。 + +**格式**: `..` + +``` +eyJ1c2VyX2lkIjoiLi4uIiwid29ya3NwYWNlcyI6W3siaWQiOiJ3c3BfLi4uIn1dfQ.XXXXX.YYYYY +``` + +### 7.2 解码方法 + +```python +import base64, json + +cookie_value = "eyJ1c2VyX2lkIjoi..." # 完整 cookie 值 + +# 关键: 必须先按 '.' 分割,只取第一部分 +payload_b64 = cookie_value.split(".")[0] + +# URL-safe base64 解码(需要补齐 padding) +padded = payload_b64 + "=" * (4 - len(payload_b64) % 4) +decoded = base64.urlsafe_b64decode(padded) +data = json.loads(decoded.decode("utf-8")) + +print(data) +# { +# "user_id": "user-xxxxxxxx", +# "workspaces": [ +# {"id": "wsp_xxxxxxxxxxxxxxxx", "name": "Personal", ...} +# ], +# ... +# } + +workspace_id = data["workspaces"][0]["id"] +``` + +### 7.3 常见错误 + +1. **直接对整个 cookie 值做 base64 解码** → 失败,因为 `.sig1.sig2` 部分不是 base64 +2. **使用标准 base64 而非 urlsafe** → 失败,payload 使用 URL-safe 编码 (`-` 和 `_` 替代 `+` 和 `/`) +3. **不补齐 padding** → 某些 base64 库会报错 + +--- + +## 8. OpenAI-Sentinel-Token 头 + +### 8.1 概述 + +所有 `auth.openai.com` 的 API 请求都需要 `OpenAI-Sentinel-Token` 请求头。 + +在浏览器中,这个 token 由前端 JS 动态生成(可能涉及 Turnstile/reCAPTCHA 或其他反机器人机制)。 + +### 8.2 Fallback 值 + +经过测试发现,可以使用一个固定的 fallback 值绕过: + +```python +import json + +# 这个 fallback 值在所有测试中均有效 +sentinel_token = json.dumps({"e": "q2n8w7x5z1"}) +# 结果: '{"e":"q2n8w7x5z1"}' +``` + +### 8.3 使用方式 + +```python +headers = { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": "https://auth.openai.com", + "Referer": "https://auth.openai.com/log-in", + "OpenAI-Sentinel-Token": '{"e":"q2n8w7x5z1"}', +} +``` + +### 8.4 注意事项 + +- 如果不提供此头,API 会返回 403 或其他错误 +- 这个 fallback 值可能在未来失效,届时需要逆向 JS 中的 token 生成逻辑 +- 在 JS bundle 中搜索 `sentinel` 或 `getSentinelToken` 可以找到生成逻辑 + +--- + +## 9. TLS 指纹模拟 + +### 9.1 为什么需要 TLS 指纹模拟 + +Cloudflare 会检查 TLS 握手的指纹 (JA3/JA4) 来识别非浏览器客户端。普通的 Python `requests` 库的 TLS 指纹与浏览器不同,会被 Cloudflare 拦截。 + +### 9.2 curl_cffi 解决方案 + +`curl_cffi` 是一个基于 curl 的 Python HTTP 库,支持模拟浏览器的 TLS 指纹: + +```python +from curl_cffi import requests as cffi_requests + +# 模拟 Chrome 136 的 TLS 指纹 +session = cffi_requests.Session(impersonate="chrome136") + +# 设置代理 +session.proxies = { + "http": "http://127.0.0.1:10808", + "https": "http://127.0.0.1:10808", +} + +# 正常使用 +r = session.get("https://auth.openai.com/log-in") +print(r.status_code) # 200 (不会被 Cloudflare 拦截) +``` + +### 9.3 支持的浏览器指纹 + +```python +# 常用的 impersonate 值: +"chrome136" # Chrome 136 (推荐) +"chrome120" # Chrome 120 +"chrome110" # Chrome 110 +"safari17_0" # Safari 17.0 +"edge101" # Edge 101 +``` + +### 9.4 对比: 普通 requests vs curl_cffi + +```python +import requests +from curl_cffi import requests as cffi_requests + +# ❌ 普通 requests - 被 Cloudflare 拦截 +r = requests.get("https://auth.openai.com/log-in") +# → 403 Forbidden (Cloudflare challenge) + +# ✅ curl_cffi - 通过 Cloudflare +r = cffi_requests.get("https://auth.openai.com/log-in", impersonate="chrome136") +# → 200 OK +``` + +--- + +## 10. 常见问题与解决方案 + +### 10.1 405 Method Not Allowed + +**原因**: 尝试对 React SPA 页面做 form POST +**解决**: 使用 JSON API 端点,不要尝试提交 HTML 表单 + +### 10.2 404 Not Found (PKCE 流程中的 /user/login) + +**原因**: PKCE 客户端 session 不支持 `/api/accounts/user/login` +**解决**: 使用 `/api/first_party_authorize/next` 端点 + +### 10.3 400 Bad Request (consent/grant) + +**原因**: 对 codex consent 使用了错误的端点 +**解决**: codex consent 使用 `/api/accounts/workspace/select`,不是 `/api/accounts/consent/grant` + +### 10.4 403 Forbidden (Cloudflare) + +**原因**: TLS 指纹不匹配或缺少必要的请求头 +**解决**: +1. 使用 `curl_cffi` 的 `impersonate="chrome136"` +2. 确保包含 `Origin`, `Referer`, `OpenAI-Sentinel-Token` 头 + +### 10.5 Cookie 解码失败 (base64 padding error) + +**原因**: 直接对整个 cookie 值做 base64 解码 +**解决**: 先按 `.` 分割,只对第一部分做 urlsafe_b64decode,并补齐 padding + +### 10.6 Onboarding 失败 (unsupported_email) + +**原因**: 某些临时邮箱域名被 OpenAI 列入黑名单 +**解决**: 使用未被封禁的邮箱域名。已知被封域名: `bpmft.cn` + +### 10.7 OAuth 会话建立失败 (Cloudflare 403 on continue_url) + +**原因**: 使用 `allow_redirects=False` 逐跳跟踪 authorize URL 时,中间某个 URL 被 Cloudflare 拦截 +**解决**: 对初始 authorize URL 使用 `allow_redirects=True`,让 curl_cffi 自动处理整个重定向链 + +```python +# ❌ 逐跳跟踪 - 可能被 Cloudflare 拦截 +r = session.get(auth_url, allow_redirects=False) +# → 某个中间 URL 返回 403 + +# ✅ 自动跟随 - curl_cffi 处理所有重定向 +r = session.get(auth_url, allow_redirects=True) +# → 最终到达 /log-in,session cookies 已建立 +``` + +### 10.8 新注册账号 OAuth 时遇到 about_you 页面 + +**原因**: 注册时 onboarding 失败(域名被封),账号未完成 onboarding +**解决**: 在 OAuth 流程中也处理 `about_you` 页面,调用 `/api/accounts/create_account` + +--- + +## 11. 完整示例代码 + +### 11.1 完整注册 + OAuth 流程 + +```python +#!/usr/bin/env python3 +"""完整的 OpenAI 账号注册 + OAuth 获取 token 示例""" + +import base64 +import hashlib +import json +import secrets +import time +import urllib.parse + +from curl_cffi import requests as cffi_requests + +# ── 配置 ── +PROXY = "http://127.0.0.1:10808" +SENTINEL = json.dumps({"e": "q2n8w7x5z1"}) +AUTH_API = "https://auth.openai.com/api/accounts" +AUTH_BASE = "https://auth.openai.com" +FPA_URL = f"{AUTH_BASE}/api/first_party_authorize/next" +CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann" +REDIRECT_URI = "http://localhost:1455/auth/callback" + + +def create_session(): + session = cffi_requests.Session(impersonate="chrome136") + session.proxies = {"http": PROXY, "https": PROXY} + return session + + +def api_headers(referer="https://auth.openai.com/log-in"): + return { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": AUTH_BASE, + "Referer": referer, + "OpenAI-Sentinel-Token": SENTINEL, + } + + +def get_page_type(data): + """兼容两种响应格式""" + page = data.get("page", {}) + if isinstance(page, dict) and page.get("type"): + return page["type"] + if data.get("type"): + return data["type"] + return "" + + +def extract_workspace_id(session): + """从 oai-client-auth-session cookie 提取 workspace_id""" + for cookie in session.cookies.jar: + if cookie.name == "oai-client-auth-session": + payload_b64 = str(cookie.value).split(".")[0] + padded = payload_b64 + "=" * (4 - len(payload_b64) % 4) + decoded = json.loads(base64.urlsafe_b64decode(padded)) + return decoded["workspaces"][0]["id"] + return None + + +def follow_redirects_for_code(session, url, state): + """逐跳跟踪重定向,提取 authorization code""" + for _ in range(15): + r = session.get(url, allow_redirects=False) + if 300 <= r.status_code < 400: + location = r.headers.get("Location", "") + if "localhost:1455" in location: + q = urllib.parse.parse_qs(urllib.parse.urlparse(location).query) + return q["code"][0] + if not location.startswith("http"): + parsed = urllib.parse.urlparse(url) + location = f"{parsed.scheme}://{parsed.netloc}{location}" + url = location + else: + break + return None + + +# ══════════════════════════════════════════════ +# 注册流程 +# ══════════════════════════════════════════════ + +def register(email, password, get_otp_code): + """ + 注册新账号。 + get_otp_code: callable,接收 email 参数,返回 6 位验证码字符串 + """ + session = create_session() + h = api_headers("https://auth.openai.com/create-account") + + # 1. 建立注册 session + csrf = session.get("https://chatgpt.com/api/auth/csrf").json()["csrfToken"] + r = session.post("https://chatgpt.com/api/auth/signin/openai", data={ + "csrfToken": csrf, "callbackUrl": "https://chatgpt.com/", "json": "true", + }, headers={"Content-Type": "application/x-www-form-urlencoded"}) + auth_url = r.json()["url"] + "&screen_hint=signup" + session.get(auth_url, allow_redirects=True) + + # 2. 提交邮箱 + r = session.post(f"{AUTH_API}/authorize/continue", json={ + "username": {"kind": "email", "value": email}, "screen_hint": "signup", + }, headers=h) + assert get_page_type(r.json()) == "create_account_password" + + # 3. 提交密码 + r = session.post(f"{AUTH_API}/user/register", json={ + "password": password, "username": email, + }, headers={**h, "Referer": "https://auth.openai.com/create-account/password"}) + assert get_page_type(r.json()) == "email_otp_send" + + # 4. OTP + session.get(f"{AUTH_API}/email-otp/send", headers={**h, "Referer": "https://auth.openai.com/email-verification"}) + code = get_otp_code(email) + r = session.post(f"{AUTH_API}/email-otp/validate", json={"code": code}, + headers={**h, "Referer": "https://auth.openai.com/email-verification"}) + page = get_page_type(r.json()) + + # 5. Onboarding + if page in ("about_you", "create_account_start"): + r = session.post(f"{AUTH_API}/create_account", json={ + "name": "John Doe", "birthdate": "1990-05-12", + }, headers={**h, "Referer": "https://auth.openai.com/about-you"}) + continue_url = r.json().get("continue_url", "") + if continue_url: + session.get(continue_url, allow_redirects=True) + + print(f"注册成功: {email}") + return True + + +# ══════════════════════════════════════════════ +# PKCE OAuth 登录流程 +# ══════════════════════════════════════════════ + +def oauth_login(email, password): + """PKCE OAuth 登录,返回 {access_token, refresh_token, ...}""" + session = create_session() + + # PKCE + verifier = secrets.token_urlsafe(32) + challenge = base64.urlsafe_b64encode( + hashlib.sha256(verifier.encode()).digest() + ).rstrip(b"=").decode() + state = secrets.token_urlsafe(24) + + auth_url = ( + f"{AUTH_BASE}/oauth/authorize?" + f"client_id={CLIENT_ID}&redirect_uri={urllib.parse.quote(REDIRECT_URI)}" + f"&response_type=code&scope=openid+email+profile+offline_access" + f"&audience=https://api.openai.com/v1" + f"&code_challenge={challenge}&code_challenge_method=S256&state={state}" + ) + + # 1. 建立 session + session.get(auth_url, allow_redirects=True) + + # 2. 提交邮箱 + r = session.post(f"{AUTH_API}/authorize/continue", + json={"username": {"kind": "email", "value": email}}, + headers=api_headers()) + page = get_page_type(r.json()) + + # 3. 提交密码 + if page == "login_password": + r = session.post(FPA_URL, json={ + "origin_page_type": "login_password", + "data": { + "intent": "validate", + "username": {"value": email, "kind": "email"}, + "password": password, + }, + }, headers=api_headers(f"{AUTH_BASE}/log-in/password")) + data = r.json() + page = get_page_type(data) + + # 4. Consent → Workspace 选择 + if page == "sign_in_with_chatgpt_codex_consent": + wid = extract_workspace_id(session) + r = session.post(f"{AUTH_API}/workspace/select", + json={"workspace_id": wid}, + headers=api_headers(f"{AUTH_BASE}/sign-in-with-chatgpt-codex-consent")) + data = r.json() + page = get_page_type(data) + + # 4b. Organization + Project 选择 + if page == "sign_in_with_chatgpt_codex_org": + orgs = data.get("data", {}).get("orgs", []) + org_id = orgs[0]["id"] + project_id = orgs[0]["projects"][0]["id"] + r = session.post(f"{AUTH_API}/organization/select", + json={"org_id": org_id, "project_id": project_id}, + headers=api_headers(f"{AUTH_BASE}/sign-in-with-chatgpt/codex/organization")) + data = r.json() + + # 5. 获取 code + continue_url = data.get("continue_url", "") + code = follow_redirects_for_code(session, continue_url, state) + + # 6. 换取 token + r = cffi_requests.post(f"{AUTH_BASE}/oauth/token", json={ + "grant_type": "authorization_code", + "client_id": CLIENT_ID, + "code": code, + "redirect_uri": REDIRECT_URI, + "code_verifier": verifier, + }, impersonate="chrome136", proxy=PROXY) + + return r.json() + + +# ══════════════════════════════════════════════ +# 使用示例 +# ══════════════════════════════════════════════ + +if __name__ == "__main__": + # OAuth 登录已有账号 + tokens = oauth_login("your_email@example.com", "your_password") + print(f"access_token: {tokens['access_token'][:50]}...") + print(f"refresh_token: {tokens['refresh_token'][:30]}...") +``` + +--- + +## 附录: 临时邮箱服务 + +本项目使用 `https://mail.chatgpt.org.uk/api` 作为临时邮箱服务: + +```python +import requests, re, time + +MAIL_API = "https://mail.chatgpt.org.uk/api" + +# 创建临时邮箱 +r = requests.get(f"{MAIL_API}/generate-email", verify=False) +email = r.json()["data"]["email"] +print(f"临时邮箱: {email}") + +# 轮询等待验证码 +for _ in range(24): # 120 秒超时 + time.sleep(5) + r = requests.get(f"{MAIL_API}/emails?email={email}", verify=False) + emails = r.json().get("data", {}).get("emails", []) + for mail in emails: + sender = str(mail.get("from", "")).lower() + if "openai" in sender or "chatgpt" in sender: + # 提取 6 位验证码 + content = mail.get("html_content", "") or mail.get("content", "") + m = re.search(r'(\d{6})', re.sub(r'<[^>]+>', ' ', content)) + if m: + print(f"验证码: {m.group(1)}") +``` \ No newline at end of file