Files
codex_auto/接口逆向.md
T
2026-02-15 16:49:11 +08:00

38 KiB
Raw Blame History


目录

  1. 架构概述
  2. JS Bundle 分析方法
  3. 两套 OAuth 客户端配置
  4. API 端点完整列表
  5. 注册流程 (Registration)
  6. PKCE OAuth 登录流程
  7. Cookie 格式与解码
  8. OpenAI-Sentinel-Token 头
  9. TLS 指纹模拟
  10. 常见问题与解决方案
  11. 完整示例代码

1. 架构概述

1.1 auth.openai.com 不是传统 HTML 表单

关键发现: auth.openai.com 是一个 React SPA (Single Page Application),使用 React Router v7 配合 SSR Streaming 渲染。

这意味着:

  • 所有页面都是 React 组件,不是传统的 HTML <form> 表单
  • 所有认证步骤通过 JSON API 完成,不是 form POST
  • 页面 HTML 中看不到有用的表单元素,只有 React 挂载点
  • 传统的 HTML 解析 + form 提交方式完全无效

1.2 SSR Streaming 响应格式

访问 auth.openai.com 的任何页面,返回的 HTML 包含:

<!-- React Router v7 SSR streaming -->
<script>
window.__reactRouterContext = { ... };
window.__reactRouterRouteModules = { ... };
</script>

<!-- React Router manifest -->
<script type="module">
import { ... } from "/@id/__x00__react-router/manifest";
</script>

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 格式的路由清单:

{
  "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 函数:

// 简化后的 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 中发现密码提交端点:

// 在 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"}}  # 邮箱域名被封
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 结构:

{
  "data": {
    "orgs": [
      {
        "id": "org-x8jWL8oV4Mn5mroVr3icqiOS",
        "projects": [
          {"id": "proj_A6Sn7l4h85zuDvWcZfozZMeP"}
        ]
      }
    ]
  }
}
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 示例代码

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。

错误方式:

# ❌ 这在 PKCE 流程中会返回 404
session.post(f"{AUTH_API}/user/login", json={
    "password": "...", "username": "..."
})

正确方式:

# ✅ 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 格式不同:

# /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": "..."}

代码中需要兼容两种格式:

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 ""

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 示例代码

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]}...")

这是 PKCE 流程中最关键的 cookie,包含用户的 workspace 信息。

格式: <urlsafe_base64_json>.<signature1>.<signature2>

eyJ1c2VyX2lkIjoiLi4uIiwid29ya3NwYWNlcyI6W3siaWQiOiJ3c3BfLi4uIn1dfQ.XXXXX.YYYYY

7.2 解码方法

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 值绕过:

import json

# 这个 fallback 值在所有测试中均有效
sentinel_token = json.dumps({"e": "q2n8w7x5z1"})
# 结果: '{"e":"q2n8w7x5z1"}'

8.3 使用方式

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 指纹:

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 支持的浏览器指纹

# 常用的 impersonate 值:
"chrome136"   # Chrome 136 (推荐)
"chrome120"   # Chrome 120
"chrome110"   # Chrome 110
"safari17_0"  # Safari 17.0
"edge101"     # Edge 101

9.4 对比: 普通 requests vs curl_cffi

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 头

原因: 直接对整个 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 自动处理整个重定向链

# ❌ 逐跳跟踪 - 可能被 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 流程

#!/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 作为临时邮箱服务:

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)}")