| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215 |
- """本地 Web 控制台:网页配置 + 一键全自动注册→付款→上传 CPA。"""
- from __future__ import annotations
- import json
- import queue
- import threading
- import time
- from dataclasses import asdict
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
- from chatgpt_flow import FullRunContext, run_full
- from config import AppConfig
- from cpa_uploader import build_cpa_auth_payload
- from recheck import recheck_account
- from storage import (
- create_task,
- get_account,
- get_task,
- init_db,
- list_accounts,
- list_events,
- list_tasks,
- )
- from task_runner import get_runner, make_task_id
- HOST = "127.0.0.1" # main() 会读 cfg.api_host 覆盖
- PORT = 7791
- class JobManager:
- def __init__(self):
- self.lock = threading.Lock()
- self.full_ctx: FullRunContext | None = None
- self.thread: threading.Thread | None = None
- self.log_queue: queue.Queue[str] = queue.Queue()
- self.history: list[str] = []
- self.stage: str = ""
- def _log(self, msg: str):
- line = f"[{time.strftime('%H:%M:%S')}] {msg}"
- self.history.append(line)
- if len(self.history) > 4000:
- self.history = self.history[-3000:]
- self.log_queue.put(line)
- def _on_stage(self, name: str):
- self.stage = name
- # stage 也写到日志,便于复盘
- self._log(f"[STAGE] {name}")
- def start(self, cfg: AppConfig) -> str:
- with self.lock:
- if self.thread and self.thread.is_alive():
- return "已有任务在运行"
- self.history.clear()
- while not self.log_queue.empty():
- self.log_queue.get_nowait()
- self.stage = ""
- def runner():
- try:
- self.full_ctx = run_full(cfg, log=self._log, on_stage=self._on_stage)
- except Exception as exc:
- import traceback
- self._log(f"[server] 任务异常: {exc!r}")
- self._log(traceback.format_exc())
- self.thread = threading.Thread(target=runner, daemon=True)
- self.thread.start()
- return ""
- def stop(self):
- if self.full_ctx:
- self.full_ctx.state = "stopped"
- self._log("[user] 已请求停止")
- def status(self) -> dict:
- running = bool(self.thread and self.thread.is_alive())
- ctx = self.full_ctx
- accounts = []
- state = "idle"
- if ctx:
- state = ctx.state
- for a in ctx.accounts:
- accounts.append({
- "email": a.get("email"),
- "stage": a.get("stage"),
- "planType": a.get("planType"),
- "error": a.get("error"),
- "cpaFile": (a.get("cpa") or {}).get("fileName") if a.get("cpa") else None,
- })
- return {
- "running": running,
- "state": state,
- "stage": self.stage,
- "accounts": accounts,
- }
- JOB = JobManager()
- INDEX_HTML = r"""<!doctype html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- <title>ChatGPT Plus 全自动注册</title>
- <style>
- :root { color-scheme: light; font-family: -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif; }
- body { margin:0; background:#f5f5f7; color:#111; }
- .wrap { max-width: 980px; margin: 24px auto; padding: 0 16px; }
- .card { background:#fff; border:1px solid #ddd; border-radius:18px; padding:22px; box-shadow:0 14px 40px rgba(0,0,0,.06); margin-bottom:18px; }
- h1 { margin: 0 0 6px; font-size: 22px; }
- h2 { margin: 0 0 10px; font-size: 16px; }
- p, li { color:#666; line-height:1.6; }
- label { display:block; margin:14px 0 6px; font-weight:600; }
- input, select { width:100%; box-sizing:border-box; border:1px solid #ccc; border-radius:10px; padding:9px 10px; font:inherit; background:#fff; }
- .grid { display:grid; grid-template-columns: 1fr 1fr; gap: 14px; }
- .grid-3 { display:grid; grid-template-columns: 1fr 1fr 1fr; gap: 14px; }
- .row { display:flex; gap:10px; align-items:center; flex-wrap:wrap; margin-top:14px; }
- button { border:0; border-radius:12px; background:#111; color:#fff; padding:10px 16px; font-weight:700; cursor:pointer; }
- button.secondary { background:#e9e9ec; color:#111; }
- button:disabled { opacity:.55; cursor:not-allowed; }
- .muted { color:#777; font-size:13px; }
- .chip { display:inline-block; padding:3px 10px; border-radius:999px; font-size:12px; background:#eef; color:#225; }
- .chip.green { background:#e6f7ec; color:#0f5f22; }
- .chip.red { background:#fde7e7; color:#a40000; }
- .chip.gray { background:#eee; color:#444; }
- .chip.blue { background:#e7f0ff; color:#1d4ed8; }
- pre.log { height:340px; overflow:auto; background:#0b0b10; color:#d6d6dc; padding:12px; border-radius:12px; font-size:12px; line-height:1.5; white-space:pre-wrap; word-break:break-all; }
- table { width:100%; border-collapse: collapse; font-size:13px; table-layout: fixed; }
- th, td { padding:8px 10px; border-bottom:1px solid #eee; text-align:left; vertical-align:top; word-break: break-word; }
- th { background:#fafafa; font-weight:600; color:#333; }
- /* 已注册账号库表 */
- #dbTable th.col-email, #dbTable td.col-email { width: 24%; }
- #dbTable th.col-plan, #dbTable td.col-plan { width: 60px; }
- #dbTable th.col-stat, #dbTable td.col-stat { width: 110px; }
- #dbTable th.col-cpa, #dbTable td.col-cpa { width: 22%; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; }
- #dbTable th.col-time, #dbTable td.col-time { width: 130px; white-space: nowrap; }
- #dbTable th.col-err, #dbTable td.col-err { width: 14%; color:#a40000; }
- #dbTable th.col-act, #dbTable td.col-act { width: 150px; white-space: nowrap; text-align: right; }
- #dbTable td.col-act .action-btn { display:inline-block; padding:4px 10px; border-radius:8px; font-weight:600; font-size:12px; text-decoration:none; white-space:nowrap; margin-left:6px; cursor:pointer; border:0; }
- #dbTable td.col-act .action-btn.detail { background:#e9e9ec; color:#111; }
- #dbTable td.col-act .action-btn.download { background:#e6f7ec; color:#0f5f22; }
- #dbTable td.col-act .action-btn.recheck { background:#fff4d6; color:#7a4f00; }
- #dbTable td.col-act .action-btn:disabled { opacity:.6; cursor:not-allowed; }
- #dbTable td.col-email code { font-size: 12px; word-break: break-all; }
- .stage-box { padding:10px 14px; border-radius:12px; background:#fffaf0; border:1px solid #ffe2a8; color:#7a4f00; font-size:13px; min-height: 22px; }
- </style>
- </head>
- <body>
- <div class="wrap">
- <div class="card">
- <h1>ChatGPT Plus 全自动注册 + CPA 上传</h1>
- <div class="muted">流程:a4sky 邮箱注册 → 拿 Plus 长链 → PayPal 创建账号付款 → 校验 plan=plus → 上传 CPA。手机号统一 +15822201173。</div>
- </div>
- <div class="card">
- <h2>配置</h2>
- <div class="grid">
- <div>
- <label>账号数量</label>
- <input id="cfg_account_count" type="number" min="1" value="1" />
- </div>
- <div>
- <label>浏览器模式</label>
- <select id="cfg_headless">
- <option value="false" selected>有头(推荐,方便干预)</option>
- <option value="true">无头</option>
- </select>
- </div>
- </div>
- <div class="grid">
- <div>
- <label>邮件助手 URL</label>
- <input id="cfg_mail_helper_url" placeholder="http://ali.ss5.xyz:17373" />
- </div>
- <div>
- <label>邮箱域名</label>
- <input id="cfg_mail_domain" placeholder="edu.a4sky.com" />
- </div>
- </div>
- <div class="grid-3">
- <div>
- <label>邮箱轮询间隔(秒)</label>
- <input id="cfg_mail_poll_interval_sec" type="number" min="1" value="4" />
- </div>
- <div>
- <label>邮箱轮询次数</label>
- <input id="cfg_mail_poll_max_attempts" type="number" min="5" value="60" />
- </div>
- <div>
- <label>使用 1 个月免费 promo</label>
- <select id="cfg_use_promo">
- <option value="true" selected>是</option>
- <option value="false">否</option>
- </select>
- </div>
- </div>
- <div class="grid">
- <div>
- <label>PayPal 短信手机号 (E164)</label>
- <input id="cfg_phone_e164" placeholder="+15822201173" />
- </div>
- <div>
- <label>接码 API URL</label>
- <input id="cfg_sms_api_url" placeholder="http://a.62-us.com/api/get_sms?key=..." />
- </div>
- </div>
- <div class="grid">
- <div>
- <label>CPA 地址</label>
- <input id="cfg_cpa_url" placeholder="http://your-cpa-host:port" />
- </div>
- <div>
- <label>CPA 管理密钥</label>
- <input id="cfg_cpa_management_key" placeholder="管理 token" />
- </div>
- </div>
- <h2 style="margin-top:18px">外网 API 接入</h2>
- <div class="grid-3">
- <div>
- <label>API 监听 host</label>
- <input id="cfg_api_host" placeholder="127.0.0.1 或 0.0.0.0" />
- </div>
- <div>
- <label>API 端口</label>
- <input id="cfg_api_port" type="number" min="1" max="65535" placeholder="7791" />
- </div>
- <div>
- <label>API Token(外网必填)</label>
- <input id="cfg_api_token" placeholder="留空 = 不校验" />
- </div>
- </div>
- <div>
- <label>CORS Allow-Origin</label>
- <input id="cfg_api_cors_origin" placeholder="* 或 https://your-frontend.com" />
- </div>
- <p class="muted" style="margin-top:6px">
- 在线 API 文档:<a href="/docs" target="_blank" rel="noopener">/docs</a> ·
- OpenAPI 规范:<a href="/openapi.json" target="_blank" rel="noopener">/openapi.json</a>
- </p>
- <div class="grid">
- <div>
- <label>全局代理(ChatGPT 注册 / 长链 / 默认浏览器;留空则直连)</label>
- <input id="cfg_proxy_url" placeholder="http://user:pass@host:port (留空 = ChatGPT 注册直连)" />
- </div>
- <div>
- <label>PayPal 独立代理(仅 PayPal 阶段;留空则继承全局)</label>
- <input id="cfg_paypal_only_proxy" placeholder="http://user:pass@host:port" />
- </div>
- </div>
- <div class="row">
- <button id="save">保存配置</button>
- <button id="go">开始全自动</button>
- <button id="stop" class="secondary" disabled>停止</button>
- <span id="state" class="chip gray">空闲</span>
- </div>
- </div>
- <div class="card">
- <h2>当前阶段</h2>
- <div id="stageBox" class="stage-box">空闲</div>
- </div>
- <div class="card">
- <h2>账号进度</h2>
- <table id="accTable">
- <thead><tr><th>#</th><th>邮箱</th><th>阶段</th><th>planType</th><th>CPA 文件</th><th>错误</th></tr></thead>
- <tbody></tbody>
- </table>
- </div>
- <div class="card">
- <h2>已注册账号库</h2>
- <div class="row" style="margin-top:0">
- <button id="refreshAccounts" class="secondary">刷新</button>
- <select id="accFilter" style="max-width:200px">
- <option value="">全部状态</option>
- <option value="registered">已注册</option>
- <option value="paid">已付款</option>
- <option value="plus">已 Plus</option>
- <option value="cpa_uploaded">已上传 CPA</option>
- <option value="cpa_skipped">CPA 跳过</option>
- <option value="failed">失败</option>
- <option value="plus_check_failed">Plus 校验失败</option>
- <option value="cpa_failed">CPA 上传失败</option>
- </select>
- <span class="muted">数据库:<code>data/accounts.db</code></span>
- </div>
- <table id="dbTable">
- <thead><tr>
- <th class="col-email">邮箱</th>
- <th class="col-plan">plan</th>
- <th class="col-stat">状态</th>
- <th class="col-cpa">CPA 文件</th>
- <th class="col-time">注册时间</th>
- <th class="col-time">更新时间</th>
- <th class="col-err">错误</th>
- <th class="col-act">动作</th>
- </tr></thead>
- <tbody></tbody>
- </table>
- <details style="margin-top:10px">
- <summary class="muted">点击查看选中账号详情</summary>
- <pre id="accDetail" class="log" style="height:240px"></pre>
- </details>
- </div>
- <div class="card">
- <h2>实时日志</h2>
- <pre id="log" class="log"></pre>
- </div>
- </div>
- <script>
- const $ = id => document.getElementById(id);
- const FIELDS = [
- ['cfg_account_count','account_count','int'],
- ['cfg_headless','headless','bool'],
- ['cfg_mail_helper_url','mail_helper_url','str'],
- ['cfg_mail_domain','mail_domain','str'],
- ['cfg_mail_poll_interval_sec','mail_poll_interval_sec','int'],
- ['cfg_mail_poll_max_attempts','mail_poll_max_attempts','int'],
- ['cfg_use_promo','use_promo','bool'],
- ['cfg_phone_e164','phone_e164','str'],
- ['cfg_sms_api_url','sms_api_url','str'],
- ['cfg_cpa_url','cpa_url','str'],
- ['cfg_cpa_management_key','cpa_management_key','str'],
- ['cfg_proxy_url','proxy_url','str'],
- ['cfg_paypal_only_proxy','paypal_only_proxy','str'],
- ['cfg_api_host','api_host','str'],
- ['cfg_api_port','api_port','int'],
- ['cfg_api_token','api_token','str'],
- ['cfg_api_cors_origin','api_cors_origin','str'],
- ];
- function fillForm(cfg) {
- for (const [domId, key, kind] of FIELDS) {
- const el = $(domId);
- if (!el || cfg[key] === undefined) continue;
- if (kind === 'bool') {
- el.value = cfg[key] ? 'true' : 'false';
- } else {
- el.value = cfg[key];
- }
- }
- }
- function readForm() {
- const out = {};
- for (const [domId, key, kind] of FIELDS) {
- const el = $(domId);
- if (!el) continue;
- let v = el.value;
- if (kind === 'int') v = Number(v) || 0;
- else if (kind === 'bool') v = (v === 'true' || v === true);
- out[key] = v;
- }
- return out;
- }
- async function loadConfig() {
- const r = await fetch('/api/config');
- const data = await r.json();
- fillForm(data);
- }
- async function saveConfig() {
- const body = readForm();
- const r = await fetch('/api/config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(body)});
- if (!r.ok) { alert('保存失败 HTTP ' + r.status); return; }
- const data = await r.json();
- fillForm(data);
- }
- function setState(text, cls) {
- const el = $('state');
- el.textContent = text;
- el.className = 'chip ' + (cls || 'gray');
- }
- let evtSource = null;
- function startLogStream() {
- if (evtSource) evtSource.close();
- evtSource = new EventSource('/api/log');
- evtSource.onmessage = e => {
- if (!e.data) return;
- const log = $('log');
- log.textContent += e.data + '\n';
- log.scrollTop = log.scrollHeight;
- };
- }
- function renderAccounts(accounts) {
- const tbody = $('accTable').querySelector('tbody');
- tbody.innerHTML = '';
- accounts.forEach((a, idx) => {
- const tr = document.createElement('tr');
- tr.innerHTML = `<td>${idx+1}</td><td>${a.email||''}</td><td>${a.stage||''}</td><td>${a.planType||''}</td><td>${a.cpaFile||''}</td><td style="color:#a40000">${a.error||''}</td>`;
- tbody.appendChild(tr);
- });
- }
- async function refreshStatus() {
- try {
- const r = await fetch('/api/status');
- const data = await r.json();
- $('stageBox').textContent = data.stage || '空闲';
- renderAccounts(data.accounts || []);
- if (data.running) {
- setState('执行中', 'green');
- $('go').disabled = true;
- $('stop').disabled = false;
- } else {
- $('go').disabled = false;
- $('stop').disabled = true;
- if (data.state === 'done') setState('完成', 'green');
- else if (data.state === 'error') setState('异常', 'red');
- else if (data.state === 'stopped') setState('已停止', 'red');
- else setState('空闲', 'gray');
- }
- } catch (_) {}
- }
- setInterval(refreshStatus, 1500);
- refreshStatus();
- startLogStream();
- loadConfig();
- loadAccounts();
- function fmtTime(ms) {
- if (!ms) return '';
- const d = new Date(Number(ms));
- if (isNaN(d.getTime())) return '';
- const pad = n => String(n).padStart(2,'0');
- // 紧凑成两行:MM-DD\n HH:MM:SS(避免一行被挤断)
- return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
- }
- async function loadAccounts() {
- const status = $('accFilter').value || '';
- const url = status ? '/api/accounts?status=' + encodeURIComponent(status) : '/api/accounts';
- try {
- const r = await fetch(url);
- const data = await r.json();
- const tbody = $('dbTable').querySelector('tbody');
- tbody.innerHTML = '';
- (data.accounts || []).forEach(a => {
- const tr = document.createElement('tr');
- const detailBtn = `<button class="action-btn detail" data-email="${a.email}" data-action="detail">详情</button>`;
- const dlBtn = a.cpa_file_name
- ? `<a class="action-btn download" href="/api/account/${encodeURIComponent(a.email)}/cpa.json" target="_blank" rel="noopener" download>下载 CPA</a>`
- : '';
- // 失败类状态可重新校验:plus_check_failed / cpa_failed / failed / cpa_skipped
- const failedStatuses = ['plus_check_failed','cpa_failed','failed','cpa_skipped','registered','paid'];
- const recheckBtn = failedStatuses.includes(a.final_status||'')
- ? `<button class="action-btn recheck" data-email="${a.email}" data-action="recheck">重新校验</button>`
- : '';
- const emailHtml = `<code title="${a.email||''}">${a.email||''}</code>`;
- const cpaHtml = a.cpa_file_name ? `<span title="${a.cpa_file_name}">${a.cpa_file_name}</span>` : '';
- const errHtml = a.last_error ? `<span title="${(a.last_error||'').replace(/"/g,'"')}">${a.last_error}</span>` : '';
- tr.innerHTML = `<td class="col-email">${emailHtml}</td><td class="col-plan">${a.plan_type||''}</td><td class="col-stat">${a.final_status||''}</td><td class="col-cpa">${cpaHtml}</td><td class="col-time">${fmtTime(a.created_at)}</td><td class="col-time">${fmtTime(a.updated_at)}</td><td class="col-err">${errHtml}</td><td class="col-act">${detailBtn}${recheckBtn}${dlBtn}</td>`;
- tbody.appendChild(tr);
- });
- tbody.querySelectorAll('button[data-action="detail"]').forEach(btn => {
- btn.addEventListener('click', () => loadAccountDetail(btn.dataset.email));
- });
- tbody.querySelectorAll('button[data-action="recheck"]').forEach(btn => {
- btn.addEventListener('click', () => triggerRecheck(btn));
- });
- } catch (e) {
- console.error(e);
- }
- }
- async function loadAccountDetail(email) {
- try {
- const r = await fetch('/api/account/' + encodeURIComponent(email));
- const data = await r.json();
- $('accDetail').textContent = JSON.stringify(data, null, 2);
- } catch (e) {
- $('accDetail').textContent = String(e);
- }
- }
- async function triggerRecheck(btn) {
- const email = btn.dataset.email;
- if (!email) return;
- const orig = btn.textContent;
- btn.disabled = true;
- btn.textContent = '校验中...';
- try {
- const r = await fetch('/api/account/' + encodeURIComponent(email) + '/recheck', {method:'POST'});
- const data = await r.json();
- if (data.ok) {
- const action = data.action || '';
- const tip = action === 'cpa_uploaded' ? '已上传 CPA'
- : action === 'plus_no_cpa_config' ? '已 Plus(未配置 CPA)'
- : '已 Plus';
- btn.textContent = '✓ ' + tip;
- } else if (data.action === 'still_not_plus') {
- btn.textContent = `仍非 plus(${data.planType||'?'})`;
- } else {
- btn.textContent = '✗ 失败';
- console.warn('recheck error', data);
- }
- setTimeout(() => loadAccounts(), 1200);
- } catch (e) {
- alert(e.message || String(e));
- btn.disabled = false;
- btn.textContent = orig;
- }
- }
- $('refreshAccounts').addEventListener('click', loadAccounts);
- $('accFilter').addEventListener('change', loadAccounts);
- // 全自动跑完后自动刷一次账号库
- const _origRefreshStatus = refreshStatus;
- let _wasRunning = false;
- async function refreshStatusWithDb() {
- await _origRefreshStatus();
- try {
- const r = await fetch('/api/status');
- const s = await r.json();
- if (_wasRunning && !s.running) loadAccounts();
- _wasRunning = !!s.running;
- } catch (_) {}
- }
- clearInterval(window.__statusTimer);
- window.__statusTimer = setInterval(refreshStatusWithDb, 1500);
- $('save').addEventListener('click', saveConfig);
- $('go').addEventListener('click', async () => {
- // 自动先保存一次配置
- await saveConfig();
- $('log').textContent = '';
- $('go').disabled = true;
- setState('启动中', 'gray');
- try {
- const r = await fetch('/api/start', {method:'POST'});
- const data = await r.json();
- if (data.error) {
- alert(data.error);
- $('go').disabled = false;
- setState('空闲', 'gray');
- }
- } catch (e) {
- alert(e.message || String(e));
- $('go').disabled = false;
- }
- });
- $('stop').addEventListener('click', async () => {
- await fetch('/api/stop', {method: 'POST'});
- });
- </script>
- </body>
- </html>"""
- def _read_json(handler) -> dict:
- length = int(handler.headers.get("content-length") or "0")
- if length <= 0:
- return {}
- raw = handler.rfile.read(length).decode("utf-8", errors="replace")
- return json.loads(raw or "{}")
- class Handler(BaseHTTPRequestHandler):
- def do_GET(self):
- path = self.path.split("?", 1)[0]
- query = self.path.split("?", 1)[1] if "?" in self.path else ""
- if path in ("/", "/index.html"):
- self._send(200, INDEX_HTML.encode("utf-8"), "text/html; charset=utf-8")
- return
- if path in ("/docs", "/docs/"):
- self._send(200, SWAGGER_HTML.encode("utf-8"), "text/html; charset=utf-8")
- return
- if path == "/openapi.json":
- self._send_json(200, _build_openapi_spec())
- return
- if not self._check_auth():
- return
- if path == "/api/status":
- self._send_json(200, JOB.status())
- return
- if path == "/api/config":
- self._send_json(200, asdict(AppConfig.load()))
- return
- if path == "/api/log":
- self._stream_log()
- return
- # ===== 任务化 API(GET)=====
- if path == "/api/tasks":
- from urllib.parse import parse_qs
- q = parse_qs(query)
- status = (q.get("status") or [""])[0] or None
- limit = int((q.get("limit") or ["100"])[0])
- try:
- tasks = list_tasks(limit=limit, status=status)
- self._send_json(200, {"tasks": tasks})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path.startswith("/api/tasks/"):
- from urllib.parse import unquote
- task_id = unquote(path[len("/api/tasks/"):])
- t = get_task(task_id)
- if not t:
- self._send_json(404, {"error": "task not found"})
- return
- self._send_json(200, {"task": t})
- return
- if path == "/api/accounts":
- try:
- from urllib.parse import parse_qs
- q = parse_qs(query)
- status = (q.get("status") or [""])[0] or None
- limit = int((q.get("limit") or ["200"])[0])
- accounts = list_accounts(limit=limit, status=status)
- # 别把 session 全文 dump 给列表,太大;列表只回主要字段
- slim = []
- for a in accounts:
- slim.append({k: a.get(k) for k in (
- "email", "plan_type", "final_status", "cpa_file_name",
- "long_link", "last_error", "created_at", "updated_at",
- "cpa_uploaded_at"
- )})
- self._send_json(200, {"accounts": slim})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path.startswith("/api/account/") and path.endswith("/cpa.json"):
- from urllib.parse import unquote
- email = unquote(path[len("/api/account/"):-len("/cpa.json")])
- acc = get_account(email)
- if not acc:
- self._send_json(404, {"error": "account not found"})
- return
- session = acc.get("plus_session") or acc.get("initial_session")
- if not session:
- self._send_json(404, {"error": "该账号没有可下载的 session"})
- return
- try:
- payload = build_cpa_auth_payload(session, email_hint=email)
- except Exception as exc:
- self._send_json(500, {"error": f"构造 CPA auth JSON 失败: {exc}"})
- return
- file_name = acc.get("cpa_file_name") or payload["fileName"]
- content = json.dumps(payload["authJson"], ensure_ascii=False, indent=2).encode("utf-8")
- self.send_response(200)
- self.send_header("Content-Type", "application/json; charset=utf-8")
- self.send_header("Content-Disposition", f'attachment; filename="{file_name}"')
- self.send_header("Cache-Control", "no-store")
- self.send_header("Content-Length", str(len(content)))
- self.end_headers()
- self.wfile.write(content)
- return
- if path.startswith("/api/account/"):
- from urllib.parse import unquote
- email = unquote(path[len("/api/account/"):])
- acc = get_account(email)
- if not acc:
- self._send_json(404, {"error": "account not found"})
- return
- events = list_events(email, limit=200)
- self._send_json(200, {"account": acc, "events": events})
- return
- self._send_json(404, {"error": "not found"})
- def do_POST(self):
- path = self.path.split("?", 1)[0]
- if not self._check_auth():
- return
- if path == "/api/config":
- try:
- body = _read_json(self)
- cfg = AppConfig.load().update(body or {})
- self._send_json(200, asdict(cfg))
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- # ===== 任务化 API =====
- if path == "/api/tasks":
- try:
- body = _read_json(self) or {}
- mode = (body.get("mode") or "full").strip().lower()
- if mode not in ("full", "pay_only"):
- self._send_json(400, {"error": "mode 必须是 full 或 pay_only"})
- return
- params = body.get("params") or {}
- if mode == "pay_only":
- sess = params.get("session")
- if not isinstance(sess, dict) or not sess.get("accessToken"):
- self._send_json(400, {"error": "pay_only 需要 params.session 是 JSON 且包含 accessToken"})
- return
- max_attempts = int(body.get("max_attempts") or 3)
- max_attempts = max(1, min(10, max_attempts))
- task_id = make_task_id()
- t = create_task(task_id, mode, params, max_attempts=max_attempts)
- # 启动 runner(幂等)
- get_runner(log=lambda m: JOB._log(m))
- self._send_json(200, {"task_id": task_id, "task": t})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path.startswith("/api/tasks/") and path.endswith("/cancel"):
- from urllib.parse import unquote
- task_id = unquote(path[len("/api/tasks/"):-len("/cancel")])
- t = get_task(task_id)
- if not t:
- self._send_json(404, {"error": "task not found"})
- return
- runner = get_runner(log=lambda m: JOB._log(m))
- runner.cancel(task_id)
- self._send_json(200, {"ok": True, "task_id": task_id})
- return
- if path == "/api/start":
- try:
- cfg = AppConfig.load()
- err = JOB.start(cfg)
- if err:
- self._send_json(409, {"error": err})
- else:
- self._send_json(200, {"ok": True})
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path.startswith("/api/account/") and path.endswith("/recheck"):
- from urllib.parse import unquote
- email = unquote(path[len("/api/account/"):-len("/recheck")])
- cfg = AppConfig.load()
- try:
- result = recheck_account(
- email,
- cpa_url=cfg.cpa_url,
- cpa_management_key=cfg.cpa_management_key,
- log=lambda msg: JOB._log(f"[acc:{email[:24]}] {msg}"),
- )
- self._send_json(200, result)
- except Exception as exc:
- self._send_json(500, {"error": str(exc)})
- return
- if path == "/api/stop":
- JOB.stop()
- self._send_json(200, {"ok": True})
- return
- self._send_json(404, {"error": "not found"})
- def _stream_log(self):
- self.send_response(200)
- self.send_header("Content-Type", "text/event-stream; charset=utf-8")
- self.send_header("Cache-Control", "no-cache")
- self.send_header("Connection", "keep-alive")
- self.end_headers()
- try:
- for line in JOB.history[-300:]:
- self._sse_send(line)
- while True:
- try:
- line = JOB.log_queue.get(timeout=15)
- self._sse_send(line)
- except queue.Empty:
- self.wfile.write(b": ping\n\n")
- self.wfile.flush()
- except (BrokenPipeError, ConnectionResetError):
- return
- def _sse_send(self, line: str):
- for piece in line.splitlines() or [""]:
- self.wfile.write(b"data: " + piece.encode("utf-8") + b"\n")
- self.wfile.write(b"\n")
- self.wfile.flush()
- def _send_json(self, status: int, payload: dict):
- self._send(status, json.dumps(payload, ensure_ascii=False).encode("utf-8"), "application/json; charset=utf-8")
- def _send(self, status: int, content: bytes, content_type: str):
- self.send_response(status)
- self.send_header("Content-Type", content_type)
- self.send_header("Cache-Control", "no-store")
- self.send_header("Content-Length", str(len(content)))
- # CORS(仅 /api/* 需要时由调用方决定,但统一发也无害)
- try:
- cfg = AppConfig.load()
- origin = (cfg.api_cors_origin or "*").strip()
- self.send_header("Access-Control-Allow-Origin", origin)
- self.send_header("Access-Control-Allow-Credentials", "true")
- except Exception:
- self.send_header("Access-Control-Allow-Origin", "*")
- self.end_headers()
- self.wfile.write(content)
- def do_OPTIONS(self):
- # CORS preflight
- self.send_response(204)
- try:
- cfg = AppConfig.load()
- origin = (cfg.api_cors_origin or "*").strip()
- except Exception:
- origin = "*"
- self.send_header("Access-Control-Allow-Origin", origin)
- self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
- self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
- self.send_header("Access-Control-Max-Age", "86400")
- self.send_header("Access-Control-Allow-Credentials", "true")
- self.end_headers()
- def _check_auth(self) -> bool:
- """非空 api_token 时校验 Authorization: Bearer。返回 True 表示放行。"""
- try:
- cfg = AppConfig.load()
- token = (cfg.api_token or "").strip()
- except Exception:
- token = ""
- if not token:
- return True
- # 公开接口豁免:根页面、OpenAPI 文档、Swagger UI、static 静态
- path = self.path.split("?", 1)[0]
- public = ("/", "/index.html", "/docs", "/docs/", "/openapi.json", "/openapi.yaml")
- if path in public:
- return True
- auth = self.headers.get("Authorization", "")
- if auth == f"Bearer {token}":
- return True
- # 也支持 ?token=xxx
- if "token=" in (self.path.split("?", 1)[1] if "?" in self.path else ""):
- from urllib.parse import parse_qs
- q = parse_qs(self.path.split("?", 1)[1])
- if (q.get("token") or [""])[0] == token:
- return True
- self._send_json(401, {"error": "missing or invalid Bearer token"})
- return False
- def log_message(self, fmt, *args):
- return
- def handle_one_request(self):
- try:
- return super().handle_one_request()
- except (ConnectionResetError, BrokenPipeError):
- # 浏览器主动断开 SSE / fetch 时打印栈很碍眼,直接静音
- self.close_connection = True
- SWAGGER_HTML = r"""<!doctype html>
- <html lang="zh-CN">
- <head>
- <meta charset="utf-8" />
- <title>API 文档 · ChatGPT Plus 自动化</title>
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui.css" />
- <style>body{margin:0}#swagger-ui{max-width:1280px;margin:0 auto}</style>
- </head>
- <body>
- <div id="swagger-ui"></div>
- <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui-bundle.js"></script>
- <script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14/swagger-ui-standalone-preset.js"></script>
- <script>
- window.onload = () => {
- window.ui = SwaggerUIBundle({
- url: '/openapi.json',
- dom_id: '#swagger-ui',
- deepLinking: true,
- presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
- layout: 'StandaloneLayout',
- persistAuthorization: true,
- tryItOutEnabled: true,
- });
- };
- </script>
- </body>
- </html>"""
- def _build_openapi_spec() -> dict:
- """生成 OpenAPI 3.1 规范。"""
- cfg = AppConfig.load()
- return {
- "openapi": "3.1.0",
- "info": {
- "title": "ChatGPT Plus 自动化 API",
- "version": "1.0.0",
- "description": (
- "ChatGPT Plus 全自动注册 + PayPal 付款 + CPA 上传。\n\n"
- "**两种模式**:\n"
- "- `full` — 全自动注册新 ChatGPT 账号,注册→付款→上传 CPA\n"
- "- `pay_only` — 传入已有 session JSON,跳过注册直接付款→上传 CPA\n\n"
- "**调用流程**:\n"
- "1. POST `/api/tasks` 创建任务,立即拿到 `task_id`\n"
- "2. 轮询 GET `/api/tasks/{task_id}` 看 `status` 和 `stage`\n"
- "3. `status` 变 `success` 时可调 GET `/api/account/{email}/cpa.json` 下载 CPA 文件\n\n"
- "**重试**:每个任务整体失败会重试 `max_attempts` 次(默认 3)。"
- ),
- },
- "servers": [
- {"url": f"http://{cfg.api_host or '127.0.0.1'}:{cfg.api_port or 7791}", "description": "当前实例"},
- ],
- "components": {
- "securitySchemes": {
- "BearerAuth": {
- "type": "http",
- "scheme": "bearer",
- "description": "如果配置了 `api_token`,所有 /api/* 请求需带 `Authorization: Bearer <token>`。也支持 `?token=xxx` 查询参数。",
- }
- },
- "schemas": {
- "Task": {
- "type": "object",
- "properties": {
- "task_id": {"type": "string", "example": "t-1779470219-65e44d55"},
- "mode": {"type": "string", "enum": ["full", "pay_only"]},
- "status": {"type": "string", "enum": ["queued", "running", "success", "failed", "cancelled"]},
- "stage": {"type": "string", "description": "当前阶段描述"},
- "attempts": {"type": "integer"},
- "max_attempts": {"type": "integer"},
- "params": {"type": "object", "description": "创建任务时传入的参数(脱敏后)"},
- "result": {"type": "object", "nullable": True, "description": "成功时的结果(含 CPA 文件名等)"},
- "last_error": {"type": "string", "nullable": True},
- "email": {"type": "string", "nullable": True, "description": "注册成功的 ChatGPT 邮箱"},
- "plan_type": {"type": "string", "nullable": True, "example": "plus"},
- "cpa_file_name": {"type": "string", "nullable": True, "example": "codex-foo@example.com-plus.json"},
- "created_at": {"type": "integer", "description": "毫秒时间戳"},
- "updated_at": {"type": "integer"},
- "started_at": {"type": "integer", "nullable": True},
- "finished_at": {"type": "integer", "nullable": True},
- },
- },
- "CreateTaskRequest": {
- "type": "object",
- "required": ["mode"],
- "properties": {
- "mode": {"type": "string", "enum": ["full", "pay_only"]},
- "max_attempts": {"type": "integer", "default": 3, "minimum": 1, "maximum": 10},
- "params": {
- "type": "object",
- "description": "可覆盖全局配置;pay_only 模式必须包含 session 字段",
- "properties": {
- "session": {
- "type": "object",
- "description": "ChatGPT /api/auth/session 完整 JSON(仅 pay_only 模式必填)",
- "properties": {
- "accessToken": {"type": "string"},
- "user": {"type": "object"},
- "account": {"type": "object"},
- },
- },
- "headless": {"type": "boolean"},
- "use_promo": {"type": "boolean"},
- "phone_e164": {"type": "string", "example": "+15822201173"},
- "sms_api_url": {"type": "string"},
- "cpa_url": {"type": "string"},
- "cpa_management_key": {"type": "string"},
- "proxy_url": {"type": "string"},
- "paypal_only_proxy": {"type": "string"},
- "mail_helper_url": {"type": "string"},
- "mail_domain": {"type": "string"},
- },
- },
- },
- },
- "Account": {
- "type": "object",
- "properties": {
- "email": {"type": "string"},
- "plan_type": {"type": "string", "nullable": True},
- "final_status": {"type": "string"},
- "cpa_file_name": {"type": "string", "nullable": True},
- "long_link": {"type": "string", "nullable": True},
- "last_error": {"type": "string", "nullable": True},
- "created_at": {"type": "integer"},
- "updated_at": {"type": "integer"},
- "cpa_uploaded_at": {"type": "integer", "nullable": True},
- },
- },
- "Error": {
- "type": "object",
- "properties": {"error": {"type": "string"}},
- },
- },
- },
- "security": [{"BearerAuth": []}] if cfg.api_token else [],
- "paths": {
- "/api/tasks": {
- "post": {
- "tags": ["Tasks"],
- "summary": "创建任务",
- "description": "创建一个 full 或 pay_only 任务,立即返回 task_id,任务异步执行。",
- "requestBody": {
- "required": True,
- "content": {
- "application/json": {
- "schema": {"$ref": "#/components/schemas/CreateTaskRequest"},
- "examples": {
- "full": {
- "summary": "全自动注册",
- "value": {
- "mode": "full",
- "max_attempts": 3,
- "params": {},
- },
- },
- "pay_only": {
- "summary": "传入 session 直接付款",
- "value": {
- "mode": "pay_only",
- "max_attempts": 3,
- "params": {
- "session": {
- "accessToken": "eyJxxx...",
- "user": {"email": "user@example.com"},
- "account": {"planType": "free"},
- }
- },
- },
- },
- },
- }
- },
- },
- "responses": {
- "200": {
- "description": "任务已创建",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "task_id": {"type": "string"},
- "task": {"$ref": "#/components/schemas/Task"},
- },
- }
- }
- },
- },
- "400": {"description": "参数错误", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}},
- "401": {"description": "Bearer token 缺失或无效"},
- },
- },
- "get": {
- "tags": ["Tasks"],
- "summary": "列出任务",
- "parameters": [
- {"name": "status", "in": "query", "schema": {"type": "string", "enum": ["queued", "running", "success", "failed", "cancelled"]}},
- {"name": "limit", "in": "query", "schema": {"type": "integer", "default": 100}},
- ],
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {"tasks": {"type": "array", "items": {"$ref": "#/components/schemas/Task"}}},
- }
- }
- }
- }
- },
- },
- },
- "/api/tasks/{task_id}": {
- "get": {
- "tags": ["Tasks"],
- "summary": "查询任务进度",
- "description": "轮询此接口查任务实时 status 和 stage。建议 5-10 秒间隔。",
- "parameters": [{"name": "task_id", "in": "path", "required": True, "schema": {"type": "string"}}],
- "responses": {
- "200": {"content": {"application/json": {"schema": {"type": "object", "properties": {"task": {"$ref": "#/components/schemas/Task"}}}}}},
- "404": {"description": "任务不存在"},
- },
- }
- },
- "/api/tasks/{task_id}/cancel": {
- "post": {
- "tags": ["Tasks"],
- "summary": "取消任务",
- "description": "请求取消任务。如果任务已经在跑,会在下一个 stop 检查点退出。",
- "parameters": [{"name": "task_id", "in": "path", "required": True, "schema": {"type": "string"}}],
- "responses": {"200": {"description": "已请求取消"}, "404": {"description": "任务不存在"}},
- }
- },
- "/api/accounts": {
- "get": {
- "tags": ["Accounts"],
- "summary": "列出已注册账号",
- "parameters": [
- {"name": "status", "in": "query", "schema": {"type": "string"}, "description": "如 cpa_uploaded / plus_check_failed"},
- {"name": "limit", "in": "query", "schema": {"type": "integer", "default": 200}},
- ],
- "responses": {
- "200": {
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {"accounts": {"type": "array", "items": {"$ref": "#/components/schemas/Account"}}},
- }
- }
- }
- }
- },
- }
- },
- "/api/account/{email}": {
- "get": {
- "tags": ["Accounts"],
- "summary": "查询账号详情(含完整 session 和事件流)",
- "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
- "responses": {"200": {"description": "OK"}, "404": {"description": "账号不存在"}},
- }
- },
- "/api/account/{email}/cpa.json": {
- "get": {
- "tags": ["Accounts"],
- "summary": "下载 CPA codex auth JSON",
- "description": "返回该账号当时上传给 CPA 的完整 codex auth JSON 文件。带 Content-Disposition 头,浏览器会自动下载。",
- "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
- "responses": {
- "200": {"description": "OK", "content": {"application/json": {}}},
- "404": {"description": "账号或 session 不存在"},
- },
- }
- },
- "/api/account/{email}/recheck": {
- "post": {
- "tags": ["Accounts"],
- "summary": "对失败账号补救",
- "description": "用 DB 里存的 access_token 调 backend-api/me,若已 plus 则自动重传 CPA。",
- "parameters": [{"name": "email", "in": "path", "required": True, "schema": {"type": "string"}}],
- "responses": {"200": {"description": "OK"}, "404": {"description": "账号不存在"}},
- }
- },
- "/api/config": {
- "get": {"tags": ["Config"], "summary": "读取当前配置", "responses": {"200": {"description": "OK"}}},
- "post": {
- "tags": ["Config"],
- "summary": "更新配置",
- "requestBody": {"content": {"application/json": {"schema": {"type": "object"}}}},
- "responses": {"200": {"description": "OK"}},
- },
- },
- "/api/status": {
- "get": {"tags": ["Misc"], "summary": "(旧)读取 UI 任务状态", "responses": {"200": {"description": "OK"}}}
- },
- "/api/log": {
- "get": {"tags": ["Misc"], "summary": "实时日志(Server-Sent Events)", "responses": {"200": {"description": "text/event-stream"}}}
- },
- },
- "tags": [
- {"name": "Tasks", "description": "任务化 API(推荐用法)"},
- {"name": "Accounts", "description": "账号库"},
- {"name": "Config", "description": "服务配置"},
- {"name": "Misc", "description": "其他"},
- ],
- }
- def _silence_threading_excepthook():
- """ThreadingHTTPServer 在 worker 线程里仍可能抛 ConnectionResetError;接住它。"""
- import threading
- prev = threading.excepthook
- def hook(args):
- if isinstance(args.exc_value, (ConnectionResetError, BrokenPipeError)):
- return
- prev(args)
- threading.excepthook = hook
- def main():
- init_db()
- _silence_threading_excepthook()
- # 启动后台任务 worker(幂等)
- get_runner(log=lambda m: JOB._log(m))
- cfg = AppConfig.load()
- host = (cfg.api_host or HOST).strip() or HOST
- port = int(cfg.api_port or PORT)
- server = ThreadingHTTPServer((host, port), Handler)
- print(f"ChatGPT Plus Auto Console:")
- print(f" Web UI: http://{host}:{port}/")
- print(f" Docs: http://{host}:{port}/docs")
- print(f" OpenAPI: http://{host}:{port}/openapi.json")
- if cfg.api_token:
- print(f" Auth: Bearer <token>(已启用)")
- if host == "0.0.0.0":
- print(f" ⚠️ 当前监听所有网卡,外网可访问。建议设置 api_token。")
- try:
- server.serve_forever()
- except KeyboardInterrupt:
- print("\nStopped.")
- if __name__ == "__main__":
- main()
|