Add files via upload
This commit is contained in:
1 parent
b85a53e334
commit
4a169ac39c
8 files changed
+2364
-2
No files matched your search
+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
|
||||
Reference in new issue
Block a user