Add files via upload
This commit is contained in:
1 parent
b85a53e334
commit
4a169ac39c
8 files changed
+2364
-2
No files matched your search
@@ -1,2 +1,43 @@
|
|||||||
# protocol_chatgpt
|
# OpenAI 协议级注册机
|
||||||
chatgpt协议注册机
|
|
||||||
|
纯 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)
|
||||||
@@ -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 <div class="code">
|
||||||
|
m = re.search(r'<div[^>]*class="code"[^>]*>(\d{6})</div>', 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
|
||||||
@@ -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()
|
||||||
+393
@@ -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 格式: <urlsafe_b64_json>.<sig1>.<sig2>
|
||||||
|
"""
|
||||||
|
for cookie in session.cookies.jar:
|
||||||
|
if cookie.name == "oai-client-auth-session":
|
||||||
|
raw = str(cookie.value)
|
||||||
|
payload_b64 = raw.split(".")[0]
|
||||||
|
padded = payload_b64 + "=" * (4 - len(payload_b64) % 4)
|
||||||
|
try:
|
||||||
|
decoded = base64.urlsafe_b64decode(padded)
|
||||||
|
data = json.loads(decoded.decode("utf-8"))
|
||||||
|
workspaces = data.get("workspaces", [])
|
||||||
|
if workspaces and isinstance(workspaces, list):
|
||||||
|
return str(workspaces[0].get("id", ""))
|
||||||
|
except Exception as e:
|
||||||
|
self._log("cookie_decode", "error", f"解码失败: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# ── Redirect 跟踪 ──
|
||||||
|
|
||||||
|
def _follow_redirects_for_code(self, session, url: str, state: str) -> str:
|
||||||
|
self._log("redirect", "start", f"跟踪: {url[:80]}")
|
||||||
|
for _ in range(15):
|
||||||
|
r = session.get(url, allow_redirects=False, timeout=30)
|
||||||
|
if 300 <= r.status_code < 400:
|
||||||
|
location = r.headers.get("Location", "")
|
||||||
|
if not location:
|
||||||
|
break
|
||||||
|
code = _extract_code_from_url(location, expected_state=state)
|
||||||
|
if code:
|
||||||
|
return code
|
||||||
|
if not location.startswith("http"):
|
||||||
|
parsed = urllib.parse.urlparse(url)
|
||||||
|
location = f"{parsed.scheme}://{parsed.netloc}{location}"
|
||||||
|
url = location
|
||||||
|
else:
|
||||||
|
code = _extract_code_from_url(str(r.url), expected_state=state)
|
||||||
|
if code:
|
||||||
|
return code
|
||||||
|
break
|
||||||
|
return ""
|
||||||
|
|
||||||
|
# ── 错误检测 ──
|
||||||
|
|
||||||
|
def _detect_error_and_raise(self, error_msg: str) -> None:
|
||||||
|
msg_lower = error_msg.lower()
|
||||||
|
for t in ("incorrect email", "incorrect password", "wrong password"):
|
||||||
|
if t in msg_lower:
|
||||||
|
raise PasswordMismatchError(f"incorrect email or password: {error_msg}")
|
||||||
|
for t in ("disabled", "blocked", "suspended", "banned"):
|
||||||
|
if t in msg_lower:
|
||||||
|
raise BannedError(error_msg)
|
||||||
|
|
||||||
|
|
||||||
|
# ── 工具函数 ──
|
||||||
|
|
||||||
|
def _extract_code_from_url(url: str, *, expected_state: str) -> str:
|
||||||
|
if not url:
|
||||||
|
return ""
|
||||||
|
if not (url.startswith(REDIRECT_URI) or "localhost:1455" in url):
|
||||||
|
return ""
|
||||||
|
parsed = urllib.parse.urlparse(url)
|
||||||
|
q = urllib.parse.parse_qs(parsed.query)
|
||||||
|
code = (q.get("code") or [""])[0]
|
||||||
|
if not code:
|
||||||
|
return ""
|
||||||
|
st = (q.get("state") or [""])[0]
|
||||||
|
if st and str(st) != str(expected_state):
|
||||||
|
return ""
|
||||||
|
return str(code)
|
||||||
+299
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
curl_cffi>=0.7.0
|
||||||
|
requests>=2.31.0
|
||||||
@@ -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()
|
||||||
Reference in new issue
Block a user