From a089da31cd1781578471c42653f1c7623a5c81e1 Mon Sep 17 00:00:00 2001 From: chashaochang <1139396584@qq.com> Date: Sat, 21 Mar 2026 20:51:55 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=BB=B4=E6=8A=A4=E5=8F=B0=20maintain?= =?UTF-8?q?=EF=BC=88=E5=B7=A1=E6=A3=80/=E8=A1=A5=E5=8F=B7/=E6=97=A5?= =?UTF-8?q?=E5=BF=97=EF=BC=89+=20=E9=85=8D=E7=BD=AE=E4=B8=8E=20.gitignore?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Flask 控制台:Cliproxy 巡检、批量补号、流水线、运行日志 - codex_stats_oauth_dir 支持统计 Cliproxy auth 目录 - 忽略 accounts/oauth、.venv、本地 DB/日志与 new.py Made-with: Cursor --- .env.cpa-runner.example | 33 ++ .gitignore | 33 ++ README.md | 91 ++++ accounts/failed/.gitkeep | 0 accounts/oauth/.gitkeep | 0 email_service.py | 382 +++++++++---- maintain/__init__.py | 1 + maintain/__main__.py | 4 + maintain/app.py | 864 ++++++++++++++++++++++++++++++ maintain/batch_register.py | 60 +++ maintain/cliproxy_mgmt.py | 109 ++++ maintain/cpa_runner_core.py | 453 ++++++++++++++++ maintain/data/.gitkeep | 0 maintain/db.py | 480 +++++++++++++++++ maintain/runtime_log.py | 37 ++ maintain/static/.gitkeep | 0 maintain/templates/dashboard.html | 607 +++++++++++++++++++++ maintain/templates/login.html | 36 ++ maintain/verify_batch_register.py | 48 ++ register.py | 596 ++++++++++----------- requirements.txt | 4 +- run.py | 487 +++++++++-------- scripts/cpa_runner.py | 25 + 23 files changed, 3719 insertions(+), 631 deletions(-) create mode 100644 .env.cpa-runner.example create mode 100644 .gitignore create mode 100644 accounts/failed/.gitkeep create mode 100644 accounts/oauth/.gitkeep create mode 100644 maintain/__init__.py create mode 100644 maintain/__main__.py create mode 100644 maintain/app.py create mode 100644 maintain/batch_register.py create mode 100644 maintain/cliproxy_mgmt.py create mode 100644 maintain/cpa_runner_core.py create mode 100644 maintain/data/.gitkeep create mode 100644 maintain/db.py create mode 100644 maintain/runtime_log.py create mode 100644 maintain/static/.gitkeep create mode 100644 maintain/templates/dashboard.html create mode 100644 maintain/templates/login.html create mode 100644 maintain/verify_batch_register.py create mode 100644 scripts/cpa_runner.py diff --git a/.env.cpa-runner.example b/.env.cpa-runner.example new file mode 100644 index 0000000..3cda426 --- /dev/null +++ b/.env.cpa-runner.example @@ -0,0 +1,33 @@ +# CPA 定时 runner(scripts/cpa_runner.py)— 复制为 .env.cpa-runner 或写入仓库根 .env +# 若已用 `python -m maintain` 并开启「流水线 → 定时」,请勿再跑本脚本。 +# 状态文件默认与维护台一致:maintain/data/pipeline_state.json(可用 STATE_FILE 覆盖) + +# 必填:注册脚本(默认本仓库 run.py) +# RUN_SCRIPT=/home/ubt/protocol_chatgpt/run.py + +# OAuth JSON 源目录(run.py 写入处) +# OAUTH_DIR=/home/ubt/protocol_chatgpt/accounts/oauth + +# 同步目标(Docker/CPA 消费端读此目录) +# TARGET_DIR=/www/wwwroot/docker/cpa/auths + +# Python 解释器 +# PYTHON_BIN=python3 + +# 定时间隔(分钟) +# RUN_EVERY_MINUTES=10 + +# run.py 子进程超时(秒),默认 480 +# RUN_SUBPROCESS_TIMEOUT_SEC=480 + +# 未迁出任何 json 时:发钉钉后是否退出进程(1=与旧版一致,适合 systemd 重启;0=scheduler 继续跑) +# CPA_EXIT_ON_EMPTY=1 + +# 状态 / 日志 / 锁文件(默认 maintain/data/ 下) +# STATE_FILE= +# LOG_FILE= +# LOCK_FILE= + +# 钉钉机器人(可选,不填则跳过通知) +# DINGTALK_WEBHOOK= +# DINGTALK_SECRET= diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9060ce3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# 虚拟环境 +.venv/ +venv/ + +# Python +__pycache__/ +*.py[cod] +*.so +.Python + +# 密钥与环境(示例文件可提交) +.env +.env.* +!.env.cpa-runner.example + +# 账号 OAuth / 失败记录(含 token,切勿提交) +accounts/oauth/* +!accounts/oauth/.gitkeep +accounts/failed/* +!accounts/failed/.gitkeep + +# 迁出目录 +export/ + +# 维护台本地数据(库与日志) +maintain/data/*.db +maintain/data/*.log +maintain/data/pipeline_state.json +maintain/data/*.lock +!maintain/data/.gitkeep + +# 本地草稿 +new.py diff --git a/README.md b/README.md index 0a08b4c..150cfb3 100644 --- a/README.md +++ b/README.md @@ -37,3 +37,94 @@ protocol_bot/ ├── oauth_login.py # 协议级 OAuth 登录模块 └── README.md ``` + +## 一条命令跑整条流水线(推荐) + +维护台把 **CPA 统计 / 补号 / 子进程 run.py / 迁出 JSON / 钉钉** 收在一个进程里: + +```bash +pip install -r requirements.txt +export CODEX_MAINTAIN_PASSWORD='你的密码' # 默认 admin +export CODEX_MAINTAIN_SECRET='随机长串' # 生产务必设置 +python -m maintain +# 本机浏览器: http://127.0.0.1:8765 +``` + +### 用服务器公网 IP 访问不到 8765 + +默认 **`CODEX_MAINTAIN_HOST=127.0.0.1`**,进程只接受本机连接,**用别的机器浏览器打 `http://IP:8765` 会连不上**。 + +1. 启动前监听所有网卡: + +```bash +export CODEX_MAINTAIN_HOST=0.0.0.0 +export CODEX_MAINTAIN_PORT=8765 # 可选 +python -m maintain +# 或 .venv/bin/python -m maintain +``` + +2. **放行端口**:云厂商安全组 / 本机 `ufw allow 8765/tcp` 或 `iptables` 等。 + +3. 仍不通时用 `ss -tlnp | grep 8765`(或 `netstat`)确认进程是否在 `0.0.0.0:8765` 监听。 + +4. 公网暴露务必强密码 + `CODEX_MAINTAIN_SECRET`;更好是前面加 **Nginx + HTTPS** 或 **SSH 隧道** / 仅内网访问。 + +### 服务器上 `pip install` 报 SSL / 连不上 PyPI + +若出现 `SSLEOFError`、`EOF occurred in violation of protocol`、`Could not find a version that satisfies the requirement flask`,多半是到 **pypi.org** 的 HTTPS 被墙、劫持或本机证书过旧,**不是** Flask 真的不存在。 + +1. **换国内镜像再装**(推荐先试清华): + +```bash +.venv/bin/pip install -U pip setuptools wheel +.venv/bin/pip install -r requirements.txt \ + -i https://pypi.tuna.tsinghua.edu.cn/simple \ + --trusted-host pypi.tuna.tsinghua.edu.cn +``` + +其它镜像可把域名换成:`https://mirrors.aliyun.com/pypi/simple/`(`--trusted-host mirrors.aliyun.com`)。 + +2. **更新系统 CA**(Debian/Ubuntu):`sudo apt-get update && sudo apt-get install -y ca-certificates` + +3. 若机房**必须走 HTTP 代理**,先 `export https_proxy=...` 再执行 pip。 + +4. **Python 版本**:维护台依赖 Flask 3,需 **Python ≥ 3.8**;能升到 3.10+ 更省心(`python3.10 -m venv .venv`)。 + +| 页签 | 能力 | +|------|------| +| **任务中心** | 巡检:管理 API 探测 + 删失效本地 JSON;仍有缺口则**自动进程内批量注册**(每批 ≤ `max_auto_register_per_tick`,与手动补号**同一把 REGISTER_LOCK**) | +| **流水线** | **仅**定时/手动的 `run.py`→迁出;**不再**由巡检触发。仍按当前统计的有效缺口决定是否执行 | +| **代理池 / 配置** | Cliproxy **管理 Base** + **Key**;若成功账号 JSON **已迁入 CPA auth 目录**,务必填 **`codex_stats_oauth_dir`** 为该目录绝对路径(与 Manager 列表一致),否则统计/巡检仍只扫项目内 `accounts/oauth`,会一直像 0 个号 | + +- **巡检**一把锁(INSPECT_LOCK);**子进程流水线**一把锁(PIPELINE_LOCK);**所有批量注册**(手动 + 巡检跟进)共 **REGISTER_LOCK**。 +- 巡检与批量注册、流水线若并行可能争写 `accounts/oauth`,建议错峰。 +- 状态文件:`maintain/data/pipeline_state.json`;业务库:`maintain/data/maintain.db`。 +- **日志**:维护台进程内任务写 `maintain/data/maintain_runtime.log`;流水线(`run.py` 输出等)写 `maintain/data/pipeline.log`(可在 SQLite `pipeline_log_file` 改路径)。Web 页签 **「运行日志」** 可拉取文件尾;亦可 SSH 执行 `tail -f`。 +- 设置项 **`codex_stats_oauth_dir`**:维护台统计、巡检探测、按失败删 JSON 的目录。留空 = `accounts/oauth`;与 Cliproxy **同机**且文件最终在 **`~/.cli-proxy-api/`** 等目录时,填该绝对路径。自定义目录下 JSON 若无 `type` 字段也会计入(Cliproxy 落盘常见);默认目录仍要求 `type=codex`。 +- 新注册写入的 oauth JSON 会带 `cpa_id` / `cpa_code`;无 `cpa_id` 的旧文件计入唯一账号池(id=1)。默认只预置一条「账号池」;若仍使用**旧版库里的两条 CPA**,可自行在 SQLite 里删掉多余行或合并目标。 + +### 验证补号链路(不真实请求 OpenAI) + +在虚拟环境里执行(会 mock `run._do_one`,只测 `run_batch` 并行、成功计数、`register context` 清理): + +```bash +python3 -m venv .venv && .venv/bin/pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn +.venv/bin/python -m maintain.verify_batch_register +``` + +应输出 `verify_batch_register: OK ...`。**真实注册**仍依赖代理、邮箱服务等:在维护台用「开始批量注册」先试 `count=1`,或巡检后看是否出现 `inspect_register` 任务并观察成功/失败数。 + +## 可选:独立 cpa_runner 进程 + +若不跑维护台、只想要旧版「定时子进程 + 迁文件」,仍可用 `scripts/cpa_runner.py` + `.env.cpa-runner`(见 `.env.cpa-runner.example`)。**维护台已开启「定时流水线」时不要同时跑本脚本。** + +### systemd(仅维护台) + +```ini +[Service] +WorkingDirectory=/home/ubt/protocol_chatgpt +EnvironmentFile=/home/ubt/protocol_chatgpt/.env +Environment=CODEX_MAINTAIN_HOST=0.0.0.0 +ExecStart=/home/ubt/protocol_chatgpt/.venv/bin/python -m maintain +Restart=on-failure +``` diff --git a/accounts/failed/.gitkeep b/accounts/failed/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/accounts/oauth/.gitkeep b/accounts/oauth/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/email_service.py b/email_service.py index c7863ac..9afaafb 100644 --- a/email_service.py +++ b/email_service.py @@ -1,101 +1,281 @@ -"""临时邮箱服务 - mail.chatgpt.org.uk API""" -from __future__ import annotations - -import re -import time -from typing import Optional, Tuple - -import requests -import urllib3 - -urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) - -BASE_URL = "https://mail.chatgpt.org.uk/api" -HEADERS = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36", - "Origin": "https://mail.chatgpt.org.uk", - "Referer": "https://mail.chatgpt.org.uk/", -} - - -def create_temp_email() -> Optional[str]: - """创建临时邮箱,返回邮箱地址""" - try: - r = requests.get( - f"{BASE_URL}/generate-email", - headers={**HEADERS, "Content-Type": "application/json"}, - timeout=10, - verify=False, - ) - if r.status_code == 200: - data = r.json() - if data.get("success") and data.get("data", {}).get("email"): - return data["data"]["email"] - except Exception as e: - print(f"[email] 创建失败: {e}") - return None - - -def fetch_emails(email_address: str) -> list[dict]: - """获取邮件列表""" - try: - ts = int(time.time() * 1000) - r = requests.get( - f"{BASE_URL}/emails?email={email_address}&_t={ts}", - headers={**HEADERS, "Cache-Control": "no-cache"}, - timeout=30, - verify=False, - ) - if r.status_code == 200: - data = r.json() - if data.get("success") and data.get("data", {}).get("emails"): - return data["data"]["emails"] - except Exception as e: - print(f"[email] 获取邮件错误: {e}") - return [] - - -def extract_code(email_data: dict) -> Optional[str]: - """从邮件中提取验证码""" - for field in ["subject", "html_content", "content", "text_content", "body"]: - content = email_data.get(field, "") - if not content: - continue - # HTML
- m = re.search(r']*class="code"[^>]*>(\d{6})
', content, re.I) - if m: - return m.group(1) - # verification code: XXXXXX - m = re.search(r'[Vv]erification\s+code:?\s*(\d{6})', content) - if m: - return m.group(1) - # code: XXXXXX - m = re.search(r'code:?\s*(\d{6})', content, re.I) - if m: - return m.group(1) - # 独立6位数字 - clean = re.sub(r'<[^>]+>', ' ', content) - m = re.search(r'\b(\d{6})\b', clean) - if m and m.group(1) != "177010": - return m.group(1) - return None - - -def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]: - """轮询等待验证码""" - start = time.time() - seen = set() - while time.time() - start < timeout: - for mail in fetch_emails(email_address): - mid = mail.get("id") or mail.get("date") - if mid in seen: - continue - seen.add(mid) - sender = str(mail.get("from", "") or mail.get("sender", "")).lower() - subject = str(mail.get("subject", "")).lower() - if any(k in sender or k in subject for k in ("openai", "chatgpt", "verification")): - code = extract_code(mail) - if code: - return code - time.sleep(5) - return None \ No newline at end of file +"""临时邮箱 — [GPTMail](https://mail.chatgpt.org.uk) 网页模拟 + +对外接口: +- create_temp_email() -> Optional[str] +- fetch_emails(email_address) -> list[dict] +- wait_for_code(email_address, timeout=120) -> Optional[str] + +通过网页同款鉴权(/api/inbox-token + X-Inbox-Token)访问收件接口, +避免 API key 配额限制。 +""" +from __future__ import annotations + +import re +import time +from typing import Optional + +import requests + +GPTMAIL_BASE = "https://mail.chatgpt.org.uk" + +# 当前进程内:本脚本创建的邮箱 -> 会话信息 +_MAIL_STATE: dict[str, dict] = {} + +UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36" + +def _gptmail_headers() -> dict: + return { + "User-Agent": UA, + "Accept": "application/json", + } + + +def _normalize_gptmail_message(raw: dict) -> dict: + """统一成 extract_code / wait_for_code 可用的字段""" + sender = (raw.get("from_address") or raw.get("from") or "").strip() + mid = raw.get("id") + text = raw.get("content") or raw.get("text") or "" + html = raw.get("html_content") or raw.get("html") or "" + return { + "id": mid, + "from": sender, + "sender": sender, + "subject": raw.get("subject", "") or "", + "text_content": text, + "html_content": html, + "content": text, + "body": text, + "date": raw.get("created_at") or raw.get("timestamp"), + } + + +def _new_session() -> requests.Session: + s = requests.Session() + s.headers.update(_gptmail_headers()) + return s + + +def _bootstrap_session(session: requests.Session) -> bool: + """先访问首页拿 gm_sid,后续 inbox-token 才会通过""" + try: + r = session.get( + f"{GPTMAIL_BASE}/", + headers={ + "Referer": f"{GPTMAIL_BASE}/", + "Origin": GPTMAIL_BASE, + **_gptmail_headers(), + }, + timeout=20, + ) + return r.status_code == 200 + except Exception: + return False + + +def _refresh_inbox_token(session: requests.Session, email: str = "") -> Optional[dict]: + r = session.post( + f"{GPTMAIL_BASE}/api/inbox-token", + json={"email": (email or "").strip().lower()}, + headers={ + "Content-Type": "application/json", + "Referer": f"{GPTMAIL_BASE}/", + "Origin": GPTMAIL_BASE, + **_gptmail_headers(), + }, + timeout=20, + ) + if r.status_code != 200: + return None + try: + body = r.json() + except Exception: + return None + if not body.get("success"): + return None + auth = body.get("auth") or {} + if not isinstance(auth, dict): + return None + token = (auth.get("token") or "").strip() + if not token: + return None + return { + "token": token, + "email": (auth.get("email") or "").strip().lower(), + "expires_at": int(auth.get("expires_at") or 0), + } + + +def _auth_fetch( + session: requests.Session, + method: str, + path: str, + *, + auth_email: str, + params: dict | None = None, + json_data: dict | None = None, +) -> requests.Response: + auth = _refresh_inbox_token(session, auth_email) + headers = {} + if auth and auth.get("token"): + headers["X-Inbox-Token"] = auth["token"] + return session.request( + method, + f"{GPTMAIL_BASE}{path}", + params=params, + json=json_data, + headers=headers, + timeout=20, + ) + + +def _gptmail_fetch_detail(session: requests.Session, email_address: str, email_id: str) -> Optional[dict]: + r = _auth_fetch(session, "GET", f"/api/email/{email_id}", auth_email=email_address) + if r.status_code != 200: + return None + try: + body = r.json() + except Exception: + return None + if not body.get("success"): + return None + data = body.get("data") or {} + return data if isinstance(data, dict) else None + + +def _gptmail_create_email() -> Optional[str]: + session = _new_session() + if not _bootstrap_session(session): + print("[email] GPTMail 会话初始化失败") + return None + r = _auth_fetch(session, "GET", "/api/generate-email", auth_email="") + try: + body = r.json() + except Exception: + print(f"[email] GPTMail 响应非 JSON: HTTP {r.status_code}") + return None + + if not body.get("success"): + err = body.get("error") or body.get("message") or r.text[:200] + print(f"[email] GPTMail 创建失败: {err}") + return None + + data = body.get("data") or {} + email = (data.get("email") or "").strip() + if not email or "@" not in email: + print("[email] GPTMail 返回缺少 email") + return None + + _MAIL_STATE[email] = { + "provider": "gptmail", + "session": session, + } + return email + + +def create_temp_email() -> Optional[str]: + """创建临时邮箱,返回邮箱地址""" + try: + return _gptmail_create_email() + except Exception as e: + print(f"[email] 创建失败: {e}") + return None + + +def fetch_emails(email_address: str) -> list[dict]: + """获取邮件列表(统一输出字典列表)""" + state = _MAIL_STATE.get(email_address) + if not state or state.get("provider") != "gptmail": + return [] + + session = state.get("session") + if not isinstance(session, requests.Session): + session = _new_session() + _bootstrap_session(session) + state["session"] = session + + try: + r = _auth_fetch( + session, + "GET", + "/api/emails", + auth_email=email_address, + params={"email": email_address}, + ) + if r.status_code != 200: + return [] + + body = r.json() + if not body.get("success"): + return [] + + data = body.get("data") or {} + members = data.get("emails") or [] + if not isinstance(members, list): + return [] + + out: list[dict] = [] + for msg in members: + if not isinstance(msg, dict): + continue + mid = msg.get("id") + detail = msg + if mid and not (msg.get("content") or msg.get("html_content")): + d = _gptmail_fetch_detail(session, email_address, mid) + if d: + detail = {**msg, **d} + + out.append(_normalize_gptmail_message(detail)) + + return out + except Exception as e: + print(f"[email] 获取邮件错误: {e}") + return [] + + +def extract_code(email_data: dict) -> Optional[str]: + """从邮件中提取验证码""" + for field in ["subject", "html_content", "content", "text_content", "body"]: + content = email_data.get(field, "") + if not content: + continue + # HTML
+ m = re.search(r']*class="code"[^>]*>(\d{6})
', content, re.I) + if m: + return m.group(1) + # verification code: XXXXXX + m = re.search(r'[Vv]erification\s+code:?\s*(\d{6})', content) + if m: + return m.group(1) + # code: XXXXXX + m = re.search(r'code:?\s*(\d{6})', content, re.I) + if m: + return m.group(1) + # 独立6位数字 + clean = re.sub(r"<[^>]+>", " ", content) + m = re.search(r"\b(\d{6})\b", clean) + if m and m.group(1) != "177010": + return m.group(1) + return None + + +def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]: + """轮询等待验证码""" + start = time.time() + seen = set() + while time.time() - start < timeout: + for mail in fetch_emails(email_address): + mid = mail.get("id") or mail.get("date") + if mid in seen: + continue + seen.add(mid) + sender = str(mail.get("from", "") or mail.get("sender", "")).lower() + subject = str(mail.get("subject", "")).lower() + if any( + k in sender or k in subject + for k in ("openai", "chatgpt", "verification", "noreply") + ): + code = extract_code(mail) + if code: + return code + time.sleep(5) + return None diff --git a/maintain/__init__.py b/maintain/__init__.py new file mode 100644 index 0000000..3421591 --- /dev/null +++ b/maintain/__init__.py @@ -0,0 +1 @@ +"""Codex 自动维护 Web 控制台""" diff --git a/maintain/__main__.py b/maintain/__main__.py new file mode 100644 index 0000000..ca9b084 --- /dev/null +++ b/maintain/__main__.py @@ -0,0 +1,4 @@ +from maintain.app import main + +if __name__ == "__main__": + main() diff --git a/maintain/app.py b/maintain/app.py new file mode 100644 index 0000000..9b8b37e --- /dev/null +++ b/maintain/app.py @@ -0,0 +1,864 @@ +#!/usr/bin/env python3 +"""Codex 自动维护 Web 控制台 — python -m maintain.app""" +from __future__ import annotations + +import json +import logging +import os +import sys +import threading +import time +from collections import defaultdict +from datetime import datetime, timezone +from functools import wraps +from pathlib import Path +from typing import Any, Optional + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +from flask import Flask, jsonify, render_template, request, session + +from maintain import db +from maintain.batch_register import run_batch +from maintain.runtime_log import rtlog, runtime_log_path +from maintain.cliproxy_mgmt import ( + probe_auth_file_models_for_oauth_stem, + verify_management_auth, +) +from maintain.cpa_runner_core import ( + execute_pipeline_cycle, + load_state, + runner_config_from_db, + save_state, +) + +_plog = logging.getLogger("cpa-runner") +if not _plog.handlers: + _h = logging.StreamHandler() + _h.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")) + _plog.addHandler(_h) + _plog.setLevel(logging.INFO) + +app = Flask( + __name__, + template_folder=os.path.join(os.path.dirname(__file__), "templates"), + static_folder=os.path.join(os.path.dirname(__file__), "static"), +) +app.secret_key = os.environ.get("CODEX_MAINTAIN_SECRET", "dev-change-me-in-production") + +rtlog() + +# 进程内补号(run_batch)与 子进程流水线(run.py→迁出)分开加锁: +# - 巡检结束后若仍有缺口 → 自动批量注册(REGISTER_LOCK),每批不超过 max_auto_register_per_tick +# - 定时流水线仍用 PIPELINE_LOCK;手动批量补号与巡检触发的补号共 REGISTER_LOCK +REGISTER_LOCK = threading.Lock() +PIPELINE_LOCK = threading.Lock() +INSPECT_LOCK = threading.Lock() +_workers_started = False +_worker_lock = threading.Lock() + + +def _lock_busy(lock: threading.Lock) -> bool: + if lock.acquire(blocking=False): + lock.release() + return False + return True + + +def _pipeline_lock_busy() -> bool: + return _lock_busy(PIPELINE_LOCK) + + +def _register_lock_busy() -> bool: + return _lock_busy(REGISTER_LOCK) + + +def _inspect_lock_busy() -> bool: + return _lock_busy(INSPECT_LOCK) + + +def _pipeline_public_snapshot() -> dict[str, Any]: + cfg = runner_config_from_db(db.get_setting) + st = load_state(cfg.state_file) + s = db.all_settings() + return { + "state": st, + "lock_busy": _pipeline_lock_busy(), + "inspect_busy": _inspect_lock_busy(), + "auto_enabled": s.get("pipeline_auto_enabled", "0") == "1", + "interval_min": s.get("pipeline_interval_min", "10"), + "paths": { + "run_script": str(cfg.run_script), + "oauth_dir": str(cfg.oauth_dir), + "target_dir": str(cfg.target_dir), + "state_file": str(cfg.state_file), + }, + "dingtalk_configured": bool(s.get("dingtalk_webhook", "").strip()), + "register_busy": _register_lock_busy(), + } + + +def _password_ok(pw: str) -> bool: + expected = os.environ.get("CODEX_MAINTAIN_PASSWORD", "admin") + return pw == expected + + +def require_login(f): + @wraps(f) + def w(*args, **kwargs): + if not session.get("maintain_user"): + return jsonify({"error": "未登录"}), 401 + return f(*args, **kwargs) + + return w + + +def _tail_text_file(path: Path, *, max_lines: int, max_bytes: int) -> str: + if not path.is_file(): + return f"(文件不存在,执行任务后会生成)\n路径: {path}\n" + try: + data = path.read_bytes() + except OSError as e: + return f"(读取失败: {e})\n" + if len(data) > max_bytes: + data = data[-max_bytes:] + text = data.decode("utf-8", errors="replace") + lines = text.splitlines() + if len(lines) > max_lines: + lines = lines[-max_lines:] + lines.insert(0, f"... 仅显示最后 {max_lines} 行 ...") + out = "\n".join(lines) + return out if out.endswith("\n") else out + "\n" + + +@app.get("/api/logs/tail") +@require_login +def api_logs_tail(): + """维护台任务日志 / 流水线 cpa-runner 日志(文件尾)。""" + name = request.args.get("name", "runtime").strip().lower() + try: + nlines = max(20, min(2000, int(request.args.get("lines", "400")))) + except ValueError: + nlines = 400 + repo = Path(ROOT).resolve() + if name == "runtime": + path = runtime_log_path().resolve() + elif name == "pipeline": + raw = db.get_setting( + "pipeline_log_file", + str(repo / "maintain" / "data" / "pipeline.log"), + ) + path = Path(raw).expanduser().resolve() + else: + return jsonify({"error": "name 须为 runtime 或 pipeline"}), 400 + try: + path.relative_to(repo) + except ValueError: + return jsonify({"error": "日志路径必须在项目根目录内"}), 400 + content = _tail_text_file(path, max_lines=nlines, max_bytes=400000) + return jsonify({"name": name, "path": str(path), "content": content}) + + +@app.route("/") +def index(): + if not session.get("maintain_user"): + return render_template("login.html") + return render_template("dashboard.html") + + +@app.route("/api/login", methods=["POST"]) +def api_login(): + data = request.get_json(silent=True) or {} + if _password_ok(str(data.get("password", ""))): + session["maintain_user"] = "1" + return jsonify({"ok": True}) + return jsonify({"ok": False, "error": "密码错误"}), 403 + + +@app.route("/api/logout", methods=["POST"]) +def api_logout(): + session.pop("maintain_user", None) + return jsonify({"ok": True}) + + +@app.get("/api/me") +def api_me(): + return jsonify({"logged_in": bool(session.get("maintain_user"))}) + + +@app.get("/api/overview") +@require_login +def api_overview(): + stats = db.overview_stats() + active = db.get_active_task() + settings = db.all_settings() + if active: + cpa_name = "" + if active.get("cpa_id"): + c = next( + (x for x in stats["cpas"] if x["id"] == active["cpa_id"]), + None, + ) + if c: + cpa_name = c["name"] + active = { + **active, + "cpa_name": cpa_name, + } + return jsonify( + { + "stats": stats, + "active_task": active, + "recent_tasks": db.list_recent_tasks(20), + "pipeline": _pipeline_public_snapshot(), + "settings": { + "auto_inspect_enabled": settings.get("auto_inspect_enabled", "0"), + "inspect_interval_min": settings.get("inspect_interval_min", "60"), + "use_proxy_pool_auto": settings.get("use_proxy_pool_auto", "1"), + "max_auto_register_per_tick": settings.get( + "max_auto_register_per_tick", "30" + ), + "default_threads": settings.get("default_threads", "1"), + "skip_oauth": settings.get("skip_oauth", "0"), + "manual_default_proxy": settings.get("manual_default_proxy", ""), + "pipeline_auto_enabled": settings.get("pipeline_auto_enabled", "0"), + "pipeline_interval_min": settings.get("pipeline_interval_min", "10"), + "pipeline_run_script": settings.get( + "pipeline_run_script", "" + ), + "pipeline_oauth_dir": settings.get("pipeline_oauth_dir", ""), + "cpa_target_dir": settings.get("cpa_target_dir", ""), + "pipeline_python_bin": settings.get("pipeline_python_bin", "python3"), + "run_subprocess_timeout_sec": settings.get( + "run_subprocess_timeout_sec", "480" + ), + "cpa_exit_on_empty": settings.get("cpa_exit_on_empty", "0"), + "dingtalk_webhook": settings.get("dingtalk_webhook", ""), + "dingtalk_secret": settings.get("dingtalk_secret", ""), + "cliproxy_management_base": settings.get( + "cliproxy_management_base", "" + ), + "cliproxy_management_key_set": bool( + settings.get("cliproxy_management_key", "").strip() + ), + "cliproxy_probe_timeout_sec": settings.get( + "cliproxy_probe_timeout_sec", "30" + ), + "codex_stats_oauth_dir": settings.get("codex_stats_oauth_dir", ""), + }, + } + ) + + +@app.get("/api/proxies") +@require_login +def api_proxies(): + return jsonify({"proxies": db.list_proxies()}) + + +@app.post("/api/proxies") +@require_login +def api_proxies_add(): + data = request.get_json(silent=True) or {} + url = str(data.get("url", "")).strip() + if not url: + return jsonify({"error": "url 必填"}), 400 + pid = db.add_proxy(url, str(data.get("label", ""))) + return jsonify({"ok": True, "id": pid}) + + +@app.delete("/api/proxies/") +@require_login +def api_proxies_del(pid: int): + db.delete_proxy(pid) + return jsonify({"ok": True}) + + +@app.put("/api/cpas/") +@require_login +def api_cpa_update(cid: int): + data = request.get_json(silent=True) or {} + kw: dict[str, Any] = {} + if "name" in data: + kw["name"] = str(data["name"]) + if "target_count" in data: + kw["target_count"] = int(data["target_count"]) + if "api_base_url" in data: + kw["api_base_url"] = str(data["api_base_url"]) + if kw: + db.update_cpa(cid, **kw) + return jsonify({"ok": True}) + + +@app.post("/api/settings") +@require_login +def api_settings_save(): + data = request.get_json(silent=True) or {} + for k, v in data.items(): + if isinstance(v, (dict, list)): + continue + db.set_setting(str(k), str(v)) + return jsonify({"ok": True}) + + +def _resolve_proxy(use_pool: bool) -> str: + if use_pool: + p = db.pick_random_proxy_url() + if p: + return p + return db.get_setting("manual_default_proxy", "").strip() + + +def _try_start_register_for_gap( + best: dict[str, Any], + *, + inspect_task_id: Optional[int], + source: str, +) -> tuple[bool, Optional[int], str]: + """ + 按当前缺口启动一批进程内注册(与手动批量补号同源)。 + 返回 (是否已排队, 补号任务 id, reason)。 + """ + if not REGISTER_LOCK.acquire(blocking=False): + if inspect_task_id is not None: + t = db.get_task(inspect_task_id) + if t: + prev = (t.get("message") or "").strip() + db.update_task( + inspect_task_id, + message=prev + ";仍有缺口但补号锁占用(已有批量注册在进行),未自动补号", + ) + return False, None, "register_busy" + + gap = int(best.get("gap", 0)) + cap = max(1, int(db.get_setting("max_auto_register_per_tick", "30"))) + count = min(gap, cap, 500) + cpa_id = int(best["id"]) + cpa_code = str(best.get("code") or "").strip() + if not cpa_code: + REGISTER_LOCK.release() + if inspect_task_id is not None: + t = db.get_task(inspect_task_id) + if t: + prev = (t.get("message") or "").strip() + db.update_task( + inspect_task_id, + message=prev + ";无法补号:账号池缺少 code", + ) + return False, None, "no_code" + + skip_oauth = db.get_setting("skip_oauth", "0") == "1" + use_pool = db.get_setting("use_proxy_pool_auto", "1") == "1" + proxy = _resolve_proxy(use_pool) + + reg_tid = db.create_task( + "inspect_register", + "queued", + f"{source} 补号 {count}/{gap}…", + cpa_id=cpa_id, + total=count, + ) + rtlog().info( + "[register#%s] 排队补号 gap=%s 本批=%s cpa_id=%s (%s)", + reg_tid, + gap, + count, + cpa_id, + source, + ) + + def reg_bg() -> None: + try: + _run_batch_task( + reg_tid, + cpa_id=cpa_id, + cpa_code=cpa_code, + count=count, + proxy=proxy, + skip_oauth=skip_oauth, + ) + finally: + REGISTER_LOCK.release() + + threading.Thread(target=reg_bg, daemon=True).start() + + if inspect_task_id is not None: + t = db.get_task(inspect_task_id) + if t: + prev = (t.get("message") or "").strip() + db.update_task( + inspect_task_id, + message=prev + + f";已排队批量补号 #{reg_tid}(本批 {count} 个,当前缺口 {gap})", + ) + + return True, reg_tid, "ok" + + +def _accounts_insufficient() -> tuple[bool, dict[str, Any]]: + stats = db.overview_stats() + if not stats["cpas"]: + return False, {} + best = max(stats["cpas"], key=lambda x: x["gap"]) + return best["gap"] > 0, best + + +def _persist_probe_result( + by_cpa: dict[int, int], + total_ok: int, + total_fail: int, + errors_sample: list[str], + *, + removed_count: int = 0, +) -> None: + probed_at = datetime.now(timezone.utc).isoformat() + db.set_setting( + "inspect_probe_valid_json", + json.dumps( + { + "by_cpa": {str(k): v for k, v in by_cpa.items()}, + "total_ok": total_ok, + "total_fail": total_fail, + "removed_count": removed_count, + "probed_at": probed_at, + "errors_sample": errors_sample[:12], + }, + ensure_ascii=False, + ), + ) + + +def _probe_error_skip_delete(err: str) -> bool: + """网络/服务端波动或全局鉴权异常时不删本地文件。""" + e = (err or "").lower() + if "http 401" in e or "http 403" in e: + return True + needles = ( + "timeout", + "timed out", + "connection", + "econnrefused", + "network is unreachable", + "name or service not known", + "temporary failure", + "http 502", + "http 503", + "http 504", + "http 500", + ) + return any(n in e for n in needles) + + +def _run_cliproxy_inspect_worker(task_id: int, source: str) -> None: + base = db.get_setting("cliproxy_management_base", "").strip() + key = db.get_setting("cliproxy_management_key", "").strip() + if not base or not key: + rtlog().warning( + "[inspect#%s] %s 中止: 未配置管理地址或密钥", task_id, source + ) + db.update_task( + task_id, + status="error", + message="请先在「配置编辑」填写 Cliproxy 管理地址与密钥", + ) + return + + timeout = float(db.get_setting("cliproxy_probe_timeout_sec", "30")) + ping_to = min(timeout, 20.0) + ok_mgmt, mgmt_err = verify_management_auth(base, key, timeout_sec=ping_to) + if not ok_mgmt: + rtlog().error( + "[inspect#%s] %s 管理端预检失败: %s", task_id, source, mgmt_err + ) + db.update_task( + task_id, + status="error", + message=f"管理端不可用或密钥无效(未删任何文件): {mgmt_err}", + ) + return + entries = db.list_oauth_codex_entries() + total = len(entries) + rtlog().info( + "[inspect#%s] %s 统计目录=%s 待探测条目=%s timeout=%s", + task_id, + source, + db.resolve_oauth_stats_dir(), + total, + timeout, + ) + if total == 0: + _persist_probe_result({}, 0, 0, [], removed_count=0) + rtlog().info("[inspect#%s] %s 无 oauth 条目,结束", task_id, source) + db.update_task( + task_id, + status="done", + message=f"{source}: 无 codex oauth JSON,已清空探测缓存", + done=1, + ) + return + + by_cpa: defaultdict[int, int] = defaultdict(int) + ok = 0 + fail = 0 + removed = 0 + errors_sample: list[str] = [] + db.update_task(task_id, status="running", message=f"{source}: 0/{total} …", done=0) + for i, ent in enumerate(entries): + if i % 7 == 0: + db.update_task( + task_id, + message=f"{source}: 管理端探测 {i}/{total} …", + done=i, + ) + good, err = probe_auth_file_models_for_oauth_stem( + base, key, str(ent["stem"]), timeout_sec=timeout + ) + if good: + ok += 1 + by_cpa[int(ent["cpa_id"])] += 1 + else: + fail += 1 + path_str = str(ent.get("path") or "") + if _probe_error_skip_delete(err): + if len(errors_sample) < 10: + errors_sample.append(f'{ent["stem"]}: {err}(未删,疑为网络/服务波动)') + elif db.safe_unlink_oauth_json(path_str): + removed += 1 + if len(errors_sample) < 10: + errors_sample.append(f'{ent["stem"]}: 已删本地 JSON — {err}') + else: + if len(errors_sample) < 10: + errors_sample.append(f'{ent["stem"]}: {err}(删文件失败)') + + _persist_probe_result( + dict(by_cpa), ok, fail, errors_sample, removed_count=removed + ) + msg = f"{source}: 有效 {ok},探测失败 {fail},已删失效 {removed} 个本地 JSON" + rtlog().info("[inspect#%s] %s", task_id, msg) + if errors_sample: + rtlog().info( + "[inspect#%s] 样例: %s", + task_id, + "; ".join(errors_sample[:5]), + ) + db.update_task( + task_id, + status="done", + message=msg, + done=total, + ) + + +def _start_inspect_job(source: str) -> tuple[bool, Optional[int], str]: + if not db.cliproxy_inspect_configured(): + return False, None, "no_config" + if not INSPECT_LOCK.acquire(blocking=False): + return False, None, "busy" + tid = db.create_task( + "mgmt_inspect", + "queued", + f"{source}:排队…", + None, + 1, + ) + + def bg() -> None: + try: + _run_cliproxy_inspect_worker(tid, source) + tdone = db.get_task(tid) + if not tdone or tdone.get("status") != "done": + return + need, best = _accounts_insufficient() + if need: + _try_start_register_for_gap( + best, inspect_task_id=tid, source=source + ) + except Exception as e: + rtlog().exception("[inspect#%s] 后台异常: %s", tid, e) + db.update_task(tid, status="error", message=str(e)[:500]) + finally: + INSPECT_LOCK.release() + + threading.Thread(target=bg, daemon=True).start() + return True, tid, "ok" + + +def _start_pipeline_job(source: str) -> tuple[bool, Optional[int], str]: + """ + 异步启动一条子进程流水线。全局 PIPELINE_LOCK 保证同时最多一条。 + 返回 (是否已成功排队, task_id, 说明);说明为 busy 表示已有流水线在执行。 + """ + if not PIPELINE_LOCK.acquire(blocking=False): + return False, None, "busy" + tid = db.create_task( + "pipeline_runpy", + "queued", + f"{source}:准备中…", + None, + 1, + ) + + def bg() -> None: + try: + db.update_task(tid, status="running", message=f"{source}:run.py …", done=0) + cfg = runner_config_from_db(db.get_setting) + rtlog().info( + "[pipeline#%s] %s 开始 run_script=%s log=%s", + tid, + source, + cfg.run_script, + cfg.log_file, + ) + cfg.target_dir.mkdir(parents=True, exist_ok=True) + st = load_state(cfg.state_file) + st = execute_pipeline_cycle(cfg, st, allow_sys_exit_on_empty=False) + save_state(cfg.state_file, st) + moved = st.get("last_run_moved", 0) + rc = st.get("last_run_return_code") + err = (st.get("last_error") or "").strip() + if err: + rtlog().warning("[pipeline#%s] last_error=%s", tid, err[:500]) + rtlog().info( + "[pipeline#%s] %s 完成 迁出=%s rc=%s", + tid, + source, + moved, + rc, + ) + db.update_task( + tid, + status="done", + message=f"{source} 完成: 迁出 {moved} 个, 返回码 {rc}", + done=1, + ) + except Exception as e: + rtlog().exception("[pipeline#%s] %s 异常: %s", tid, source, e) + db.update_task(tid, status="error", message=str(e)[:500]) + finally: + PIPELINE_LOCK.release() + + threading.Thread(target=bg, daemon=True).start() + return True, tid, "ok" + + +def _run_batch_task( + task_id: int, + *, + cpa_id: int, + cpa_code: str, + count: int, + proxy: str, + skip_oauth: bool, +) -> None: + threads = int(db.get_setting("default_threads", "1")) + + def on_progress(done: int, total: int) -> None: + cpa = next((x for x in db.list_cpas() if x["id"] == cpa_id), {}) + name = cpa.get("name", "") + db.update_task( + task_id, + message=f"{done}/{total} 正在补号({name or '账号池'})…", + done=done, + ) + + try: + db.update_task(task_id, status="running", message="启动注册线程…", done=0) + rtlog().info( + "[register#%s] 开始 cpa_id=%s count=%s threads=%s skip_oauth=%s proxy=%s", + task_id, + cpa_id, + count, + threads, + skip_oauth, + proxy or "(空)", + ) + ok, fail = run_batch( + count=count, + threads=threads, + proxy=proxy, + skip_oauth=skip_oauth, + cpa_id=cpa_id, + cpa_code=cpa_code, + on_progress=on_progress, + ) + rtlog().info( + "[register#%s] 结束 成功=%s 失败=%s", task_id, ok, fail + ) + db.update_task( + task_id, + status="done", + message=f"完成: 成功 {ok}, 失败 {fail}", + done=count, + ) + except Exception as e: + rtlog().exception("[register#%s] 异常: %s", task_id, e) + db.update_task(task_id, status="error", message=str(e)[:500]) + + +@app.post("/api/pipeline/run-once") +@require_login +def api_pipeline_run_once(): + """手动执行一次子进程流水线(与巡检/定时共用 PIPELINE_LOCK,同时仅一条)""" + started, tid, _ = _start_pipeline_job("手动流水线") + if not started: + return jsonify({"error": "已有流水线在执行,请稍后再试"}), 409 + return jsonify({"ok": True, "task_id": tid}) + + +@app.post("/api/tasks/manual") +@require_login +def api_task_manual(): + if not REGISTER_LOCK.acquire(blocking=False): + return jsonify({"error": "已有批量补号任务在运行"}), 409 + data = request.get_json(silent=True) or {} + cpa_id = int(data.get("cpa_id", 0)) + count = int(data.get("count", 1)) + use_pool = bool(data.get("use_proxy_pool", True)) + if count < 1 or count > 500: + REGISTER_LOCK.release() + return jsonify({"error": "count 范围 1–500"}), 400 + cpas = db.list_cpas() + cpa = next((c for c in cpas if c["id"] == cpa_id), None) + if not cpa: + REGISTER_LOCK.release() + return jsonify({"error": "账号池不存在"}), 400 + skip_oauth = db.get_setting("skip_oauth", "0") == "1" + proxy = _resolve_proxy(use_pool) + + tid = db.create_task( + "manual_register", + "queued", + "", + cpa_id=cpa_id, + total=count, + ) + + def bg(): + try: + _run_batch_task( + tid, + cpa_id=cpa_id, + cpa_code=str(cpa["code"]), + count=count, + proxy=proxy, + skip_oauth=skip_oauth, + ) + finally: + REGISTER_LOCK.release() + + threading.Thread(target=bg, daemon=True).start() + return jsonify({"ok": True, "task_id": tid}) + + +@app.post("/api/tasks/inspect-now") +@require_login +def api_task_inspect_now(): + """ + 巡检:Cliproxy 管理 API 探测、删失效 JSON;完成后若仍低于目标则排队一批批量注册。 + """ + if not db.cliproxy_inspect_configured(): + return jsonify( + { + "error": "未配置 Cliproxy 管理地址/密钥,请在「配置编辑」填写 cliproxy_management_base 与密钥", + } + ), 400 + started, tid, reason = _start_inspect_job("手动巡检") + if reason == "busy": + return jsonify( + {"error": "已有巡检任务在执行,请稍后再试", "task_id": None} + ), 409 + return jsonify( + { + "ok": True, + "task_id": tid, + "message": "已排队巡检;完成后若仍有缺口将自动批量补号(每批上限见 max_auto_register_per_tick)", + } + ) + + +def _pipeline_scheduler_loop() -> None: + last_run = 0.0 + while True: + time.sleep(20) + try: + if db.get_setting("pipeline_auto_enabled", "0") != "1": + continue + need, _ = _accounts_insufficient() + now = time.time() + if not need: + last_run = now + continue + interval = float(db.get_setting("pipeline_interval_min", "10")) * 60.0 + if now - last_run < interval: + continue + started, _, _ = _start_pipeline_job("定时流水线") + if started: + last_run = time.time() + except Exception: + time.sleep(30) + + +def _auto_worker_loop() -> None: + """自动巡检:按间隔触发管理端全量探测;完成后若有效账号不足则排队流水线。""" + last_run = 0.0 + while True: + time.sleep(15) + try: + if db.get_setting("auto_inspect_enabled", "0") != "1": + continue + if not db.cliproxy_inspect_configured(): + continue + interval = float(db.get_setting("inspect_interval_min", "60")) * 60.0 + now = time.time() + if now - last_run < interval: + continue + started, _, reason = _start_inspect_job("自动巡检") + if started: + last_run = time.time() + elif reason == "busy": + pass + except Exception: + time.sleep(30) + + +def _ensure_worker() -> None: + global _workers_started + with _worker_lock: + if _workers_started: + return + threading.Thread( + target=_auto_worker_loop, daemon=True, name="maintain-auto-inspect" + ).start() + threading.Thread( + target=_pipeline_scheduler_loop, daemon=True, name="maintain-pipeline" + ).start() + _workers_started = True + + +@app.before_request +def _before(): + if request.endpoint and request.endpoint != "static": + _ensure_worker() + + +def main() -> None: + db.init_db() + host = os.environ.get("CODEX_MAINTAIN_HOST", "127.0.0.1") + port = int(os.environ.get("CODEX_MAINTAIN_PORT", "8765")) + print( + f"Codex 维护台 http://{host}:{port} " + f"(任务中心+流水线一体)密码: CODEX_MAINTAIN_PASSWORD,默认 admin" + ) + if host in ("127.0.0.1", "localhost", "::1"): + print( + "提示: 当前仅监听本机;用公网 IP 访问请设置 CODEX_MAINTAIN_HOST=0.0.0.0," + "并放行防火墙/安全组 TCP 端口。" + ) + app.run(host=host, port=port, debug=False, threaded=True) + + +if __name__ == "__main__": + db.init_db() + main() diff --git a/maintain/batch_register.py b/maintain/batch_register.py new file mode 100644 index 0000000..86ec3ec --- /dev/null +++ b/maintain/batch_register.py @@ -0,0 +1,60 @@ +"""调用现有 run 模块执行批量注册(写入 cpa_id / cpa_code)""" +from __future__ import annotations + +import os +import sys +import threading +from concurrent.futures import ThreadPoolExecutor, as_completed +from typing import Callable, Optional + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +from register import RegisterConfig + +import run as run_module + + +def run_batch( + *, + count: int, + threads: int, + proxy: str, + skip_oauth: bool, + cpa_id: int, + cpa_code: str, + on_progress: Optional[Callable[[int, int], None]] = None, +) -> tuple[int, int]: + """ + 执行 count 次注册,返回 (success, failed)。 + on_progress(done, total) 每完成 1 个账号回调一次(并行时顺序不定)。 + """ + run_module._counter["success"] = 0 + run_module._counter["failed"] = 0 + run_module.set_register_context(cpa_id=cpa_id, cpa_code=cpa_code) + try: + config = RegisterConfig(proxy=proxy or "") + th = max(1, min(int(threads), int(count))) + prog_lock = threading.Lock() + completed = {"n": 0} + + def one(i: int) -> None: + run_module._do_one(i, config, proxy or "", skip_oauth) + if on_progress: + with prog_lock: + completed["n"] += 1 + on_progress(completed["n"], count) + + if th <= 1: + for i in range(1, count + 1): + one(i) + else: + with ThreadPoolExecutor(max_workers=th) as ex: + futs = {ex.submit(one, i): i for i in range(1, count + 1)} + for fut in as_completed(futs): + fut.result() + + return run_module._counter["success"], run_module._counter["failed"] + finally: + run_module.clear_register_context() diff --git a/maintain/cliproxy_mgmt.py b/maintain/cliproxy_mgmt.py new file mode 100644 index 0000000..73d84ae --- /dev/null +++ b/maintain/cliproxy_mgmt.py @@ -0,0 +1,109 @@ +"""Cliproxy 管理 API:与 Web 管理台相同的 auth 文件连通性探测。""" +from __future__ import annotations + +import re +from urllib.parse import quote, urljoin + +import requests + +_MANAGEMENT_PREFIX = "/v0/management" + + +def normalize_management_base(raw: str) -> str: + base = (raw or "").strip() + if not base: + return "" + base = re.sub(r"/?v0/management/?$", "", base, flags=re.IGNORECASE) + base = base.rstrip("/") + if not re.match(r"^https?://", base, re.IGNORECASE): + base = "http://" + base + return base + + +def management_api_root(base: str) -> str: + b = normalize_management_base(base) + if not b: + return "" + return b.rstrip("/") + _MANAGEMENT_PREFIX + + +def probe_auth_file_models( + management_base: str, + management_key: str, + auth_file_name: str, + *, + timeout_sec: float = 30.0, +) -> tuple[bool, str]: + """ + 请求 GET .../v0/management/auth-files/models?name= + 与 Cli-Proxy-API-Management-Center 中 getModelsForAuthFile 一致。 + """ + root = management_api_root(management_base) + if not root or not management_key.strip(): + return False, "未配置管理地址或密钥" + name = (auth_file_name or "").strip() + if not name: + return False, "文件名为空" + url = urljoin(root + "/", "auth-files/models") + url = f"{url}?name={quote(name, safe='')}" + try: + r = requests.get( + url, + headers={"Authorization": f"Bearer {management_key.strip()}"}, + timeout=timeout_sec, + ) + except requests.RequestException as e: + return False, str(e)[:200] + if r.status_code == 200: + return True, "" + tail = (r.text or "")[:300].replace("\n", " ") + return False, f"HTTP {r.status_code} {tail}".strip() + + +def verify_management_auth( + management_base: str, + management_key: str, + *, + timeout_sec: float = 15.0, +) -> tuple[bool, str]: + """先拉 auth-files,密钥错误或不可达时勿对单文件做删除类操作。""" + root = management_api_root(management_base) + if not root or not management_key.strip(): + return False, "未配置管理地址或密钥" + url = urljoin(root + "/", "auth-files") + try: + r = requests.get( + url, + headers={"Authorization": f"Bearer {management_key.strip()}"}, + timeout=timeout_sec, + ) + except requests.RequestException as e: + return False, str(e)[:200] + if r.status_code == 200: + return True, "" + return False, f"HTTP {r.status_code}" + + +def probe_auth_file_models_for_oauth_stem( + management_base: str, + management_key: str, + oauth_json_stem: str, + *, + timeout_sec: float = 30.0, +) -> tuple[bool, str]: + """先按 oauth 文件名(无 .json)探测,再试带 .json,与常见 Cliproxy 命名一致。""" + stem = (oauth_json_stem or "").strip() + if not stem: + return False, "文件名为空" + names = [stem] + if not stem.lower().endswith(".json"): + names.append(f"{stem}.json") + last_err = "" + for name in names: + ok, err = probe_auth_file_models( + management_base, management_key, name, timeout_sec=timeout_sec + ) + if ok: + return True, "" + last_err = err + return False, last_err diff --git a/maintain/cpa_runner_core.py b/maintain/cpa_runner_core.py new file mode 100644 index 0000000..d50b082 --- /dev/null +++ b/maintain/cpa_runner_core.py @@ -0,0 +1,453 @@ +""" +流水线:子进程执行 run.py → 将 accounts/oauth/*.json 迁到目标目录 → 可选钉钉通知。 + +- 独立进程:`python scripts/cpa_runner.py`(读环境变量 / .env) +- 嵌入维护台:由 `maintain.app` 调用 `execute_pipeline_cycle`,配置来自 SQLite +""" +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import logging +import os +import shutil +import subprocess +import time +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import Any, Callable, Optional +from urllib.parse import quote_plus + +import requests + +REPO_ROOT = Path(__file__).resolve().parent.parent + +logger = logging.getLogger("cpa-runner") + + +def load_env(path: Path) -> None: + if not path.exists(): + return + for line in path.read_text(encoding="utf-8").splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, value = line.split("=", 1) + os.environ.setdefault(key.strip(), value.strip()) + + +load_env(REPO_ROOT / ".env") +load_env(REPO_ROOT / ".env.cpa-runner") + + +def env_int(name: str, default: int) -> int: + value = os.getenv(name, str(default)).strip() + try: + return int(value) + except ValueError: + return default + + +def env_bool(name: str, default: bool) -> bool: + v = os.getenv(name, "").strip().lower() + if not v: + return default + return v in ("1", "true", "yes", "on") + + +@dataclass +class RunnerConfig: + run_script: Path + oauth_dir: Path + target_dir: Path + python_bin: str = "python3" + dingtalk_webhook: str = "" + dingtalk_secret: str = "" + exit_on_zero_moved: bool = True + subprocess_timeout_sec: int = 60 * 8 + state_file: Path = REPO_ROOT / "maintain" / "data" / "pipeline_state.json" + log_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.log" + lock_file: Path = REPO_ROOT / "maintain" / "data" / "cpa_runner.lock" + + +def runner_config_from_env() -> RunnerConfig: + return RunnerConfig( + run_script=Path( + os.getenv("RUN_SCRIPT", str(REPO_ROOT / "run.py")) + ).resolve(), + oauth_dir=Path( + os.getenv("OAUTH_DIR", str(REPO_ROOT / "accounts" / "oauth")) + ).resolve(), + target_dir=Path( + os.getenv( + "TARGET_DIR", + str(REPO_ROOT / "export" / "cpa_auths"), + ) + ).resolve(), + python_bin=os.getenv("PYTHON_BIN", "python3"), + dingtalk_webhook=os.getenv("DINGTALK_WEBHOOK", "").strip(), + dingtalk_secret=os.getenv("DINGTALK_SECRET", "").strip(), + exit_on_zero_moved=env_bool("CPA_EXIT_ON_EMPTY", True), + subprocess_timeout_sec=env_int("RUN_SUBPROCESS_TIMEOUT_SEC", 60 * 8), + state_file=Path( + os.getenv( + "STATE_FILE", + str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"), + ) + ).resolve(), + log_file=Path( + os.getenv( + "LOG_FILE", + str(REPO_ROOT / "maintain" / "data" / "cpa_runner.log"), + ) + ).resolve(), + lock_file=Path( + os.getenv( + "LOCK_FILE", + str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"), + ) + ).resolve(), + ) + + +CONFIG = runner_config_from_env() + +DEFAULT_STATE: dict[str, Any] = { + "last_run_at": None, + "last_notify_at": None, + "last_run_moved": 0, + "last_run_return_code": None, + "last_stdout_tail": "", + "last_stderr_tail": "", + "last_error": "", +} + +LOCK_HANDLE: Any = None + + +def _setup_cli_logging(cfg: RunnerConfig) -> None: + cfg.log_file.parent.mkdir(parents=True, exist_ok=True) + if logger.handlers: + return + logger.setLevel(logging.INFO) + fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") + fh = logging.FileHandler(cfg.log_file, encoding="utf-8") + fh.setFormatter(fmt) + sh = logging.StreamHandler() + sh.setFormatter(fmt) + logger.addHandler(fh) + logger.addHandler(sh) + + +def ensure_pipeline_file_handler(cfg: RunnerConfig) -> None: + """ + 嵌入维护台时 cpa-runner 可能已有 StreamHandler 而无 FileHandler; + 保证流水线日志写入 cfg.log_file(run.py 输出等)。 + """ + cfg.log_file.parent.mkdir(parents=True, exist_ok=True) + logger.setLevel(logging.INFO) + fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") + want = str(cfg.log_file.resolve()) + for h in logger.handlers: + if isinstance(h, logging.FileHandler): + try: + if os.path.abspath(h.baseFilename) == want: + return + except (OSError, ValueError, AttributeError): + continue + fh = logging.FileHandler(cfg.log_file, encoding="utf-8") + fh.setFormatter(fmt) + logger.addHandler(fh) + + +def load_state(path: Path) -> dict[str, Any]: + if path.exists(): + try: + return {**DEFAULT_STATE, **json.loads(path.read_text(encoding="utf-8"))} + except Exception as e: + logger.warning("load state failed: %s", e) + return {**DEFAULT_STATE} + + +def save_state(path: Path, state: dict[str, Any]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8") + + +def acquire_single_instance_lock(cfg: RunnerConfig) -> None: + global LOCK_HANDLE + try: + import fcntl + except ImportError: + logger.warning("fcntl unavailable, skip single-instance lock (non-Unix)") + return + cfg.lock_file.parent.mkdir(parents=True, exist_ok=True) + lock_handle = cfg.lock_file.open("w") + try: + fcntl.flock(lock_handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + logger.error( + "another cpa-runner instance is already running, lock=%s", cfg.lock_file + ) + raise SystemExit(1) + lock_handle.write(str(os.getpid())) + lock_handle.flush() + LOCK_HANDLE = lock_handle + + +def build_dingtalk_url(webhook: str, secret: str) -> str: + if not secret: + return webhook + timestamp = str(round(time.time() * 1000)) + sign_data = f"{timestamp}\n{secret}".encode("utf-8") + sign = quote_plus( + base64.b64encode( + hmac.new(secret.encode("utf-8"), sign_data, digestmod=hashlib.sha256).digest() + ) + ) + sep = "&" if "?" in webhook else "?" + return f"{webhook}{sep}timestamp={timestamp}&sign={sign}" + + +def send_dingtalk(cfg: RunnerConfig, payload: dict) -> bool: + if not cfg.dingtalk_webhook: + logger.info("skip notify: dingtalk webhook empty") + return False + url = build_dingtalk_url(cfg.dingtalk_webhook, cfg.dingtalk_secret) + try: + resp = requests.post(url, json=payload, timeout=15) + resp.raise_for_status() + data = resp.json() + if data.get("errcode") != 0: + logger.error("dingtalk notify failed: %s", data) + return False + return True + except Exception as e: + logger.exception("send dingtalk notify error: %s", e) + return False + + +def send_dingtalk_markdown(cfg: RunnerConfig, title: str, markdown_text: str) -> bool: + return send_dingtalk( + cfg, + { + "msgtype": "markdown", + "markdown": {"title": title, "text": markdown_text}, + }, + ) + + +def format_ts(ts: Optional[int]) -> str: + if not ts: + return "-" + return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") + + +def _tail(s: str, n: int = 4000) -> str: + s = (s or "").strip() + if len(s) <= n: + return s + return "…" + s[-n:] + + +def build_status_markdown( + *, + moved: int, + return_code: int, + title: str, + status_label: str, + status_emoji: str, + state: dict[str, Any], + cfg: RunnerConfig, + note: Optional[str] = None, +) -> str: + lines = [ + f"# {status_emoji} {title}", + "", + f"> 状态:**{status_label}**", + "", + f"- 本次迁出 JSON:**{moved}** 个", + f"- run.py 返回码:**{return_code}**", + f"- 执行时间:`{format_ts(state.get('last_run_at'))}`", + f"- 目标目录:`{cfg.target_dir}`", + ] + if note: + lines.extend(["", f"> {note}"]) + return "\n".join(lines) + + +def move_json_files(cfg: RunnerConfig) -> int: + moved = 0 + if not cfg.oauth_dir.exists(): + logger.warning("oauth dir not found: %s", cfg.oauth_dir) + return 0 + cfg.target_dir.mkdir(parents=True, exist_ok=True) + for src in sorted(cfg.oauth_dir.glob("*.json")): + target = cfg.target_dir / src.name + if target.exists(): + stem = src.stem + suffix = src.suffix + target = cfg.target_dir / f"{stem}_{int(time.time())}{suffix}" + shutil.move(str(src), str(target)) + moved += 1 + logger.info("moved json: %s -> %s", src, target) + return moved + + +def execute_pipeline_cycle( + cfg: RunnerConfig, + state: dict[str, Any], + *, + allow_sys_exit_on_empty: bool = False, +) -> dict[str, Any]: + """ + 执行一次:run.py → 迁出 oauth json → 钉钉。 + 返回更新后的 state(调用方负责 save_state)。 + allow_sys_exit_on_empty:仅独立脚本进程应为 True。 + """ + out = {**DEFAULT_STATE, **state} + ensure_pipeline_file_handler(cfg) + logger.info("pipeline cycle start run_script=%s", cfg.run_script) + cmd = [cfg.python_bin, str(cfg.run_script)] + try: + completed = subprocess.run( + cmd, + cwd=str(cfg.run_script.parent), + capture_output=True, + text=True, + timeout=cfg.subprocess_timeout_sec, + ) + rc = completed.returncode + logger.info("run.py return code: %s", rc) + if completed.stdout: + logger.info("run.py stdout:\n%s", completed.stdout.strip()) + if completed.stderr: + logger.warning("run.py stderr:\n%s", completed.stderr.strip()) + out["last_stdout_tail"] = _tail(completed.stdout or "") + out["last_stderr_tail"] = _tail(completed.stderr or "") + out["last_error"] = "" + + moved = move_json_files(cfg) + out["last_run_moved"] = moved + out["last_run_return_code"] = rc + out["last_run_at"] = int(time.time()) + + if moved == 0: + md = build_status_markdown( + moved=moved, + return_code=rc, + title="流水线告警", + status_label="未迁出任何 JSON", + status_emoji="🚨", + state=out, + cfg=cfg, + note=f"OAuth 目录:`{cfg.oauth_dir}`", + ) + send_dingtalk_markdown(cfg, "流水线告警", md) + logger.warning("pipeline: moved=0, alert sent") + if cfg.exit_on_zero_moved and allow_sys_exit_on_empty: + raise SystemExit(0) + else: + md = build_status_markdown( + moved=moved, + return_code=rc, + title="流水线战报", + status_label="执行完成", + status_emoji="✅", + state=out, + cfg=cfg, + ) + send_dingtalk_markdown(cfg, "流水线战报", md) + out["last_notify_at"] = int(time.time()) + logger.info("pipeline done moved=%s", moved) + + except subprocess.TimeoutExpired: + logger.exception("run.py timeout") + out["last_run_return_code"] = -1 + out["last_run_at"] = int(time.time()) + out["last_error"] = "subprocess timeout" + except Exception as e: + logger.exception("execute_pipeline_cycle failed") + out["last_run_return_code"] = -2 + out["last_run_at"] = int(time.time()) + out["last_error"] = str(e)[:500] + + return out + + +def run_once_cli() -> None: + """独立进程入口使用:读 CONFIG,写 state 文件。""" + global CONFIG + CONFIG = runner_config_from_env() + _setup_cli_logging(CONFIG) + CONFIG.target_dir.mkdir(parents=True, exist_ok=True) + st = load_state(CONFIG.state_file) + st = execute_pipeline_cycle(CONFIG, st, allow_sys_exit_on_empty=True) + save_state(CONFIG.state_file, st) + + +def main_blocking() -> None: + from apscheduler.schedulers.blocking import BlockingScheduler + from apscheduler.triggers.interval import IntervalTrigger + + global CONFIG + CONFIG = runner_config_from_env() + _setup_cli_logging(CONFIG) + acquire_single_instance_lock(CONFIG) + logger.info("cpa-runner (standalone) starting") + logger.info("run_script=%s", CONFIG.run_script) + logger.info("interval_min=%s", env_int("RUN_EVERY_MINUTES", 10)) + + scheduler = BlockingScheduler(timezone="Asia/Shanghai") + scheduler.add_job( + run_once_cli, + IntervalTrigger(minutes=env_int("RUN_EVERY_MINUTES", 10)), + id="run_job", + max_instances=1, + coalesce=True, + ) + + run_once_cli() + scheduler.start() + + +def runner_config_from_db(get_setting: Callable[[str, str], str]) -> RunnerConfig: + """从维护台 SQLite settings 构造配置。""" + g = get_setting + return RunnerConfig( + run_script=Path( + g("pipeline_run_script", str(REPO_ROOT / "run.py")) + ).resolve(), + oauth_dir=Path( + g("pipeline_oauth_dir", str(REPO_ROOT / "accounts" / "oauth")) + ).resolve(), + target_dir=Path( + g("cpa_target_dir", str(REPO_ROOT / "export" / "cpa_auths")) + ).resolve(), + python_bin=g("pipeline_python_bin", "python3"), + dingtalk_webhook=g("dingtalk_webhook", "").strip(), + dingtalk_secret=g("dingtalk_secret", "").strip(), + exit_on_zero_moved=g("cpa_exit_on_empty", "0") == "1", + subprocess_timeout_sec=int(g("run_subprocess_timeout_sec", "480") or 480), + state_file=Path( + g( + "pipeline_state_file", + str(REPO_ROOT / "maintain" / "data" / "pipeline_state.json"), + ) + ).resolve(), + log_file=Path( + g( + "pipeline_log_file", + str(REPO_ROOT / "maintain" / "data" / "pipeline.log"), + ) + ).resolve(), + lock_file=Path( + g( + "pipeline_lock_file", + str(REPO_ROOT / "maintain" / "data" / "cpa_runner.lock"), + ) + ).resolve(), + ) diff --git a/maintain/data/.gitkeep b/maintain/data/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/maintain/db.py b/maintain/db.py new file mode 100644 index 0000000..e5808b1 --- /dev/null +++ b/maintain/db.py @@ -0,0 +1,480 @@ +from __future__ import annotations + +import json +import os +import sqlite3 +import threading +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional + +ROOT = Path(__file__).resolve().parent.parent +DB_PATH = ROOT / "maintain" / "data" / "maintain.db" +ACCOUNTS_OAUTH = ROOT / "accounts" / "oauth" + +_lock = threading.Lock() + + +def resolve_oauth_stats_dir() -> Path: + """ + 统计 / 巡检用的 codex JSON 目录。 + 留空 = 项目内 accounts/oauth;若注册成功后文件迁入 Cliproxy auth 目录,填该目录绝对路径。 + """ + raw = get_setting("codex_stats_oauth_dir", "").strip() + if not raw: + return ACCOUNTS_OAUTH.resolve() + return Path(raw).expanduser().resolve() + + +def safe_unlink_oauth_json(path_str: str) -> bool: + """仅允许删除「统计目录」下的 .json 文件,防路径穿越。""" + try: + p = Path(path_str).resolve() + root = resolve_oauth_stats_dir() + p.relative_to(root) + except (ValueError, OSError): + return False + if p.suffix.lower() != ".json": + return False + if not p.is_file(): + return False + try: + p.unlink() + return True + except OSError: + return False + + +def _conn() -> sqlite3.Connection: + DB_PATH.parent.mkdir(parents=True, exist_ok=True) + c = sqlite3.connect(str(DB_PATH), check_same_thread=False) + c.row_factory = sqlite3.Row + return c + + +def init_db() -> None: + with _lock: + c = _conn() + try: + c.executescript( + """ + CREATE TABLE IF NOT EXISTS cpa ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + code TEXT NOT NULL UNIQUE, + target_count INTEGER NOT NULL DEFAULT 0, + api_base_url TEXT DEFAULT '' + ); + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL + ); + CREATE TABLE IF NOT EXISTS proxies ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + url TEXT NOT NULL, + label TEXT DEFAULT '', + enabled INTEGER NOT NULL DEFAULT 1 + ); + CREATE TABLE IF NOT EXISTS tasks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + task_type TEXT NOT NULL, + status TEXT NOT NULL, + message TEXT DEFAULT '', + cpa_id INTEGER, + total INTEGER DEFAULT 0, + done INTEGER DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + """ + ) + cur = c.execute("SELECT COUNT(*) FROM cpa") + if cur.fetchone()[0] == 0: + c.execute( + "INSERT INTO cpa (name, code, target_count, api_base_url) VALUES (?,?,?,?)", + ("账号池", "default", 8000, ""), + ) + defaults = { + "auto_inspect_enabled": "0", + "inspect_interval_min": "60", + "use_proxy_pool_auto": "1", + "max_auto_register_per_tick": "30", + "default_threads": "1", + "skip_oauth": "0", + "manual_default_proxy": "", + # 子进程流水线(run.py → 迁出 JSON),与维护台共用 pipeline_state.json + "pipeline_auto_enabled": "0", + "pipeline_interval_min": "10", + "pipeline_run_script": str(ROOT / "run.py"), + "pipeline_oauth_dir": str(ROOT / "accounts" / "oauth"), + "cpa_target_dir": str(ROOT / "export" / "cpa_auths"), + "pipeline_python_bin": "python3", + "run_subprocess_timeout_sec": "480", + "cpa_exit_on_empty": "0", + "dingtalk_webhook": "", + "dingtalk_secret": "", + # Cliproxy 管理端巡检(与 Web 管理台「探测模型」同源) + "cliproxy_management_base": "", + "cliproxy_management_key": "", + "cliproxy_probe_timeout_sec": "30", + # 成功后 JSON 若在 Cliproxy auth 目录,填绝对路径;留空则用项目 accounts/oauth + "codex_stats_oauth_dir": "", + "inspect_probe_valid_json": "", + "pipeline_state_file": str(ROOT / "maintain" / "data" / "pipeline_state.json"), + "pipeline_log_file": str(ROOT / "maintain" / "data" / "pipeline.log"), + "pipeline_lock_file": str(ROOT / "maintain" / "data" / "cpa_runner.lock"), + } + for k, v in defaults.items(): + c.execute( + "INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (k, v) + ) + c.commit() + finally: + c.close() + + +def get_setting(key: str, default: str = "") -> str: + with _lock: + c = _conn() + try: + row = c.execute("SELECT value FROM settings WHERE key=?", (key,)).fetchone() + return row["value"] if row else default + finally: + c.close() + + +def set_setting(key: str, value: str) -> None: + with _lock: + c = _conn() + try: + c.execute( + "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value", + (key, value), + ) + c.commit() + finally: + c.close() + + +def all_settings() -> dict[str, str]: + with _lock: + c = _conn() + try: + rows = c.execute("SELECT key, value FROM settings").fetchall() + return {r["key"]: r["value"] for r in rows} + finally: + c.close() + + +def list_cpas() -> list[dict[str, Any]]: + with _lock: + c = _conn() + try: + rows = c.execute( + "SELECT id, name, code, target_count, api_base_url FROM cpa ORDER BY id" + ).fetchall() + return [dict(r) for r in rows] + finally: + c.close() + + +def update_cpa( + cpa_id: int, + *, + name: Optional[str] = None, + target_count: Optional[int] = None, + api_base_url: Optional[str] = None, +) -> None: + with _lock: + c = _conn() + try: + if name is not None: + c.execute("UPDATE cpa SET name=? WHERE id=?", (name, cpa_id)) + if target_count is not None: + c.execute("UPDATE cpa SET target_count=? WHERE id=?", (target_count, cpa_id)) + if api_base_url is not None: + c.execute("UPDATE cpa SET api_base_url=? WHERE id=?", (api_base_url, cpa_id)) + c.commit() + finally: + c.close() + + +def list_proxies() -> list[dict[str, Any]]: + with _lock: + c = _conn() + try: + rows = c.execute( + "SELECT id, url, label, enabled FROM proxies ORDER BY id" + ).fetchall() + return [dict(r) for r in rows] + finally: + c.close() + + +def add_proxy(url: str, label: str = "") -> int: + with _lock: + c = _conn() + try: + cur = c.execute( + "INSERT INTO proxies (url, label, enabled) VALUES (?,?,1)", + (url.strip(), label.strip()), + ) + c.commit() + return int(cur.lastrowid) + finally: + c.close() + + +def delete_proxy(proxy_id: int) -> None: + with _lock: + c = _conn() + try: + c.execute("DELETE FROM proxies WHERE id=?", (proxy_id,)) + c.commit() + finally: + c.close() + + +def pick_random_proxy_url() -> Optional[str]: + rows = [p for p in list_proxies() if p.get("enabled")] + if not rows: + return None + import random + + return random.choice(rows)["url"] + + +def cliproxy_inspect_configured() -> bool: + return bool(get_setting("cliproxy_management_base", "").strip()) and bool( + get_setting("cliproxy_management_key", "").strip() + ) + + +def _oauth_json_is_codex_candidate(data: dict[str, Any], *, strict_codex_type: bool) -> bool: + if data.get("disabled"): + return False + if strict_codex_type: + return data.get("type") == "codex" + t = data.get("type") + if t == "codex": + return True + if t in (None, ""): + return True + return False + + +def _oauth_cpa_id_from_json(data: dict[str, Any]) -> int: + cid = data.get("cpa_id") + if cid is None: + return 1 + try: + return int(cid) + except (TypeError, ValueError): + return 1 + + +def parse_inspect_probe_cache() -> Optional[dict[str, Any]]: + raw = get_setting("inspect_probe_valid_json", "").strip() + if not raw: + return None + try: + o = json.loads(raw) + except (json.JSONDecodeError, TypeError): + return None + if not isinstance(o, dict) or "by_cpa" not in o: + return None + return o + + +def list_oauth_codex_entries() -> list[dict[str, Any]]: + """每个统计目录下 *.json 一条;stem 与 Cliproxy auth 文件名对应。""" + root = resolve_oauth_stats_dir() + strict = root.resolve() == ACCOUNTS_OAUTH.resolve() + out: list[dict[str, Any]] = [] + if not root.is_dir(): + return out + for path in sorted(root.glob("*.json")): + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except Exception: + continue + if not isinstance(data, dict): + continue + if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict): + continue + cid = _oauth_cpa_id_from_json(data) + out.append({"cpa_id": cid, "stem": path.stem, "path": str(path)}) + return out + + +def count_oauth_accounts_by_cpa() -> dict[int, int]: + """按统计目录统计;无 cpa_id 归入 id=1。""" + root = resolve_oauth_stats_dir() + strict = root.resolve() == ACCOUNTS_OAUTH.resolve() + counts: dict[int, int] = {} + if not root.is_dir(): + return counts + for path in root.glob("*.json"): + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + except Exception: + continue + if not isinstance(data, dict): + continue + if not _oauth_json_is_codex_candidate(data, strict_codex_type=strict): + continue + cid = _oauth_cpa_id_from_json(data) + counts[cid] = counts.get(cid, 0) + 1 + return counts + + +def overview_stats() -> dict[str, Any]: + cpas = list_cpas() + by_file = count_oauth_accounts_by_cpa() + probe = parse_inspect_probe_cache() + use_probe = cliproxy_inspect_configured() and probe is not None + by_valid: dict[int, int] = {} + if use_probe and isinstance(probe.get("by_cpa"), dict): + raw_bc = probe["by_cpa"] + for c in cpas: + cid = c["id"] + v = raw_bc.get(str(cid), raw_bc.get(cid)) + if v is None: + v = 0 + try: + by_valid[cid] = int(v) + except (TypeError, ValueError): + by_valid[cid] = 0 + rows = [] + total = 0 + total_raw = 0 + total_target = 0 + for c in cpas: + cid = c["id"] + n_raw = by_file.get(cid, 0) + total_raw += n_raw + n = by_valid.get(cid, n_raw) if use_probe else n_raw + total += n + tgt = int(c["target_count"] or 0) + total_target += tgt + health = (n / tgt * 100.0) if tgt > 0 else 100.0 + gap = max(0, tgt - n) + status = "健康" if health >= 95 else ("偏低" if health >= 70 else "告警") + row: dict[str, Any] = { + **c, + "candidates": n, + "health_pct": round(health, 2), + "gap": gap, + "status": status, + } + if use_probe and n_raw != n: + row["raw_candidates"] = n_raw + rows.append(row) + global_health = (total / total_target * 100.0) if total_target > 0 else 100.0 + out: dict[str, Any] = { + "cpas": rows, + "total_accounts": total, + "total_candidates": total, + "total_target": total_target, + "global_health_pct": round(global_health, 2), + "global_status": "健康" if global_health >= 95 else ("偏低" if global_health >= 70 else "告警"), + "inspect_probe_mode": use_probe, + "inspect_last_at": (probe or {}).get("probed_at") if use_probe else None, + "total_accounts_raw": total_raw, + } + if cliproxy_inspect_configured() and not use_probe: + out["inspect_probe_pending"] = True + stats_root = resolve_oauth_stats_dir() + out["oauth_stats_dir"] = str(stats_root) + out["oauth_stats_dir_is_default"] = stats_root.resolve() == ACCOUNTS_OAUTH.resolve() + return out + + +def create_task( + task_type: str, + status: str, + message: str = "", + cpa_id: Optional[int] = None, + total: int = 0, +) -> int: + now = datetime.now(timezone.utc).isoformat() + with _lock: + c = _conn() + try: + cur = c.execute( + """INSERT INTO tasks (task_type, status, message, cpa_id, total, done, created_at, updated_at) + VALUES (?,?,?,?,?,?,?,?)""", + (task_type, status, message, cpa_id, total, 0, now, now), + ) + c.commit() + return int(cur.lastrowid) + finally: + c.close() + + +def update_task( + task_id: int, + *, + status: Optional[str] = None, + message: Optional[str] = None, + done: Optional[int] = None, +) -> None: + now = datetime.now(timezone.utc).isoformat() + parts = ["updated_at=?"] + vals: list[Any] = [now] + if status is not None: + parts.append("status=?") + vals.append(status) + if message is not None: + parts.append("message=?") + vals.append(message) + if done is not None: + parts.append("done=?") + vals.append(done) + vals.append(task_id) + with _lock: + c = _conn() + try: + c.execute(f"UPDATE tasks SET {','.join(parts)} WHERE id=?", vals) + c.commit() + finally: + c.close() + + +def get_active_task() -> Optional[dict[str, Any]]: + with _lock: + c = _conn() + try: + row = c.execute( + """SELECT * FROM tasks WHERE status IN ('running','queued') + ORDER BY id DESC LIMIT 1""" + ).fetchone() + return dict(row) if row else None + finally: + c.close() + + +def get_task(task_id: int) -> Optional[dict[str, Any]]: + with _lock: + c = _conn() + try: + row = c.execute("SELECT * FROM tasks WHERE id=?", (task_id,)).fetchone() + return dict(row) if row else None + finally: + c.close() + + +def list_recent_tasks(limit: int = 20) -> list[dict[str, Any]]: + lim = max(1, min(int(limit), 100)) + with _lock: + c = _conn() + try: + rows = c.execute( + "SELECT * FROM tasks ORDER BY id DESC LIMIT ?", + (lim,), + ).fetchall() + return [dict(r) for r in rows] + finally: + c.close() diff --git a/maintain/runtime_log.py b/maintain/runtime_log.py new file mode 100644 index 0000000..c359671 --- /dev/null +++ b/maintain/runtime_log.py @@ -0,0 +1,37 @@ +"""维护台进程内任务日志(巡检 / 补号 / 与流水线摘要),写入 data/maintain_runtime.log""" +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Optional + +REPO_ROOT = Path(__file__).resolve().parent.parent +DEFAULT_PATH = REPO_ROOT / "maintain" / "data" / "maintain_runtime.log" + +_logger: Optional[logging.Logger] = None + + +def runtime_log_path() -> Path: + return DEFAULT_PATH + + +def setup_runtime_logging() -> logging.Logger: + global _logger + if _logger is not None: + return _logger + DEFAULT_PATH.parent.mkdir(parents=True, exist_ok=True) + lg = logging.getLogger("maintain.runtime") + lg.setLevel(logging.INFO) + lg.propagate = False + if not lg.handlers: + fh = logging.FileHandler(DEFAULT_PATH, encoding="utf-8") + fh.setFormatter( + logging.Formatter("%(asctime)s [%(levelname)s] %(message)s") + ) + lg.addHandler(fh) + _logger = lg + return lg + + +def rtlog() -> logging.Logger: + return setup_runtime_logging() diff --git a/maintain/static/.gitkeep b/maintain/static/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/maintain/templates/dashboard.html b/maintain/templates/dashboard.html new file mode 100644 index 0000000..b7aea95 --- /dev/null +++ b/maintain/templates/dashboard.html @@ -0,0 +1,607 @@ + + + + + + Codex 自动维护 + + + +
+

Codex 自动维护

+
+ + + +
+
+ +
+
+ +
+ 子进程流水线 — — +
+
+
+

任务进度与历史

+ 自动轮询只更新此处与统计、账号表、流水线摘要,不会改写各页配置表单。填表前可先点「同步表单」拉服务端当前值。 +
+
+ + + +
#类型状态进度说明更新
+
+
+
+
账号总数
—
+
有效账号
—
+
目标阈值
—
+
健康度
—
+
+

+

账号池

+ + + +
名称有效 / 本地文件目标健康度缺口状态操作
+
+
+

自动巡检 → 批量补号

+

按间隔 Cliproxy 管理 API 全量探测;失败条目删本地 JSON(预检密钥;超时/5xx/401 不删)。再按有效数算缺口,仍不足则自动进程内批量注册,每批不超过配置里的 单次自动注册上限(与手动补号共锁,勿并行)。

+
+ + + +
+
+

手动巡检

+ + + +
+ + +
+ +
+ +
+
+
+
+
+

当前状态

+

+      
+
+
+

定时:run.py → 迁出 JSON

+
+ + + + + + +
+ +
+
+

路径与钉钉

+ + + + + + + + + + + +
+
+

定时流水线按维护台当前统计的有效账号缺口(已配置管理端且跑过巡检后,与探测结果一致;否则按本地文件数)。充足则跳过。勿与 scripts/cpa_runner.py 双开。

+
+
+
+

代理池(HTTP / HTTPS / SOCKS5 URL 每行一条)

+
+ + + + + +
+
+
+
+

Cliproxy 管理端(巡检必填)

+

与 管理 API 一致。若注册成功后的 JSON 已迁入 Cliproxy 的 auth 目录,须填写下方「统计目录」为该目录绝对路径,否则维护台仍只扫项目内 accounts/oauth,账号数会显示 0。巡检按该目录下的文件名调用 auth-files/models;删除失效 JSON 也在该目录内。密钥存 SQLite。

+ + + + + + + + + +
+
+

运行参数

+ + + + +
+ + + +
+
+
+
+

运行日志(文件尾部)

+

+ 维护台:巡检 / 批量补号排队与异常写入 maintain/data/maintain_runtime.log。
+ 流水线:run.py 的 stdout/stderr 及迁出记录写入 SQLite 里的 pipeline_log_file(默认 maintain/data/pipeline.log)。
+ 服务器上也可 tail -f maintain/data/maintain_runtime.log 实时看。 +

+
+ + + +
+
+
+
(点「加载日志」)
+
+
+
+
+

安全

+

+ 登录密码由环境变量 CODEX_MAINTAIN_PASSWORD 控制(默认 admin)。
+ 生产环境请同时设置 CODEX_MAINTAIN_SECRET 作为会话密钥。 +

+
+
+
+
+ + + diff --git a/maintain/templates/login.html b/maintain/templates/login.html new file mode 100644 index 0000000..d339e67 --- /dev/null +++ b/maintain/templates/login.html @@ -0,0 +1,36 @@ + + + + + + 登录 — Codex 自动维护 + + + +
+

Codex 自动维护

+ + +

+
+ + + diff --git a/maintain/verify_batch_register.py b/maintain/verify_batch_register.py new file mode 100644 index 0000000..03f0b1c --- /dev/null +++ b/maintain/verify_batch_register.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""验证批量补号链路:run_batch 并行、计数、register context 清理(不真实打注册接口)。""" +from __future__ import annotations + +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + + +def main() -> int: + import run as run_module + from maintain.batch_register import run_batch + + calls: list[int] = [] + + def fake_do_one(index: int, config, proxy: str, skip_oauth: bool) -> dict: + calls.append(index) + run_module._counter["success"] += 1 + return {} + + orig = run_module._do_one + run_module._do_one = fake_do_one # type: ignore[assignment] + try: + ok, fail = run_batch( + count=5, + threads=3, + proxy="", + skip_oauth=False, + cpa_id=1, + cpa_code="default", + on_progress=None, + ) + assert ok == 5 and fail == 0, (ok, fail) + assert len(calls) == 5 and set(calls) == {1, 2, 3, 4, 5}, calls + assert getattr(run_module._register_ctx, "cpa_id", None) is None + assert getattr(run_module._register_ctx, "cpa_code", None) is None + finally: + run_module._do_one = orig # type: ignore[assignment] + + print("verify_batch_register: OK (mocked _do_one, count=5 threads=3)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/register.py b/register.py index c192616..f17487b 100644 --- a/register.py +++ b/register.py @@ -1,299 +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}") +"""协议级注册模块 - 纯 HTTP 请求模拟 OpenAI 注册流程 + +流程 (基于 auth.openai.com React SPA 逆向): + 1. chatgpt.com/api/auth/csrf → CSRF token + 2. POST chatgpt.com/api/auth/signin/openai → auth.openai.com authorize URL + 3. GET authorize URL (screen_hint=signup) → 302 → /create-account + 4. POST /authorize/continue {username: {kind:"email",value:...}, screen_hint:"signup"} + → page: create_account_password + 5. POST /user/register {password, username} + → page: email_otp_send + 6. GET /email-otp/send → 触发发送验证码 + 7. POST /email-otp/validate {code} → 验证码校验 + 8. POST /create-account {name, birthdate} → onboarding + 9. Follow continue_url → OAuth callback 完成注册 +""" +from __future__ import annotations + +import json +import random +import string +import time +from dataclasses import dataclass, field +from typing import Dict, Optional +from urllib.parse import urlencode, urlparse, parse_qs, urlunparse + +from curl_cffi import requests as cffi_requests + +from email_service import create_temp_email, wait_for_code + + +def generate_random_password(length: int = 16) -> str: + chars = string.ascii_letters + string.digits + "!@#$%" + password = "".join(random.choice(chars) for _ in range(length)) + password = ( + random.choice(string.ascii_uppercase) + + random.choice(string.ascii_lowercase) + + random.choice(string.digits) + + random.choice("!@#$%") + + password[4:] + ) + return password + + +# Auth API 常量 +AUTH_API_BASE = "https://auth.openai.com/api/accounts" +SENTINEL_FALLBACK = json.dumps({"e": "q2n8w7x5z1"}) + + +@dataclass +class RegisterConfig: + proxy: str = "" + default_name: str = "John Doe" + default_birthday: Dict[str, str] = field(default_factory=lambda: {"year": "1990", "month": "05", "day": "12"}) + impersonate: str = "chrome136" + + +@dataclass +class RegisterResult: + success: bool + email: Optional[str] = None + password: Optional[str] = None + error: Optional[str] = None + + +class AccountRegister: + """协议级账号注册器 - 纯 HTTP JSON API,无浏览器依赖""" + + def __init__(self, config: RegisterConfig): + self.config = config + + def _log(self, step: str, status: str, message: str = ""): + print(f"[register][{step}] {status}: {message}") + + def _create_session(self) -> cffi_requests.Session: + session = cffi_requests.Session(impersonate=self.config.impersonate) + if self.config.proxy: + session.proxies = {"http": self.config.proxy, "https": self.config.proxy} + return session + + def _api_headers(self, referer: str = "https://auth.openai.com/create-account") -> dict: + return { + "Accept": "application/json", + "Content-Type": "application/json", + "Origin": "https://auth.openai.com", + "Referer": referer, + "OpenAI-Sentinel-Token": SENTINEL_FALLBACK, + } + + def _api_post(self, session, path: str, payload: dict, + referer: str = "https://auth.openai.com/create-account") -> tuple[dict, int]: + url = f"{AUTH_API_BASE}{path}" + r = session.post(url, json=payload, headers=self._api_headers(referer), timeout=30) + try: + data = r.json() + except Exception: + data = {"error": r.text[:500]} + return data, r.status_code + + def _api_get(self, session, path: str, + referer: str = "https://auth.openai.com/create-account") -> tuple[dict, int]: + url = f"{AUTH_API_BASE}{path}" + r = session.get(url, headers=self._api_headers(referer), timeout=30) + try: + data = r.json() + except Exception: + data = {"error": r.text[:500]} + return data, r.status_code + + def _get_page_type(self, data: dict) -> str: + page = data.get("page", {}) + if isinstance(page, dict): + return page.get("type", "") + return str(page) + + def _extract_error(self, data: dict) -> str: + err = data.get("error", {}) + if isinstance(err, dict): + return err.get("message", str(err)) + return str(err) + + # ── 主流程 ── + + def register_one(self) -> RegisterResult: + email = None + password = None + + try: + # 1. 创建临时邮箱 + self._log("create_email", "start", "创建临时邮箱") + email = create_temp_email() + if not email: + self._log("create_email", "error", "邮箱创建失败") + return RegisterResult(success=False, error="邮箱创建失败") + self._log("create_email", "ok", f"邮箱: {email}") + + # 2. 生成密码 + password = generate_random_password() + self._log("generate_password", "ok", f"password={password}") + + # 3. 创建 HTTP session + session = self._create_session() + + # 4. 建立 OAuth 会话 (screen_hint=signup → /create-account) + self._log("oauth_session", "start", "建立 OAuth 会话") + if not self._establish_auth_session(session): + return RegisterResult(success=False, email=email, password=password, + error="OAuth 会话建立失败") + + # 5. 提交邮箱 + self._log("submit_email", "start", f"提交邮箱: {email}") + data, status = self._api_post(session, "/authorize/continue", { + "username": {"kind": "email", "value": email}, + "screen_hint": "signup", + }) + page_type = self._get_page_type(data) + self._log("submit_email", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"邮箱提交失败: {status} {self._extract_error(data)}") + + if page_type != "create_account_password": + self._log("submit_email", "error", f"预期 create_account_password,实际 {page_type}") + return RegisterResult(success=False, email=email, password=password, + error=f"邮箱提交后页面异常: {page_type}") + + # 6. 提交密码 (POST /user/register) + self._log("submit_password", "start", "提交密码到 /user/register") + data, status = self._api_post( + session, "/user/register", + {"password": password, "username": email}, + referer="https://auth.openai.com/create-account/password", + ) + page_type = self._get_page_type(data) + self._log("submit_password", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"密码提交失败: {status} {self._extract_error(data)}") + + # 7. 邮箱 OTP 验证 + if page_type == "email_otp_send": + self._log("otp_send", "start", "触发发送 OTP") + send_data, send_status = self._api_get( + session, "/email-otp/send", + referer="https://auth.openai.com/email-verification", + ) + self._log("otp_send", "info", f"status={send_status}") + + self._log("otp_wait", "start", "等待验证邮件") + code = wait_for_code(email) + if not code: + self._log("otp_wait", "error", "验证码获取超时") + return RegisterResult(success=False, email=email, password=password, + error="验证码获取超时") + + self._log("otp_validate", "start", f"提交验证码: {code}") + data, status = self._api_post( + session, "/email-otp/validate", + {"code": code}, + referer="https://auth.openai.com/email-verification", + ) + page_type = self._get_page_type(data) + self._log("otp_validate", "info", f"status={status} page={page_type}") + + if status != 200: + return RegisterResult(success=False, email=email, password=password, + error=f"验证码校验失败: {status} {self._extract_error(data)}") + + # 8. Onboarding (about_you / create_account_start) + if page_type in ("about_you", "create_account_start"): + self._log("onboarding", "start", "填写 onboarding 信息") + bd = self.config.default_birthday + birthday_str = f"{bd['year']}-{bd['month'].zfill(2)}-{bd['day'].zfill(2)}" + + data, status = self._api_post( + session, "/create_account", + {"name": self.config.default_name, "birthdate": birthday_str}, + referer="https://auth.openai.com/about-you", + ) + self._log("onboarding", "info", f"status={status}") + + if status != 200: + error_msg = self._extract_error(data) + self._log("onboarding", "error", f"Onboarding 失败: {error_msg}") + return RegisterResult(success=False, email=email, password=password, + error=f"Onboarding 失败: {status} {error_msg}") + + continue_url = data.get("continue_url", "") + if continue_url and continue_url.startswith("http"): + self._log("onboarding", "ok", f"Continue: {continue_url[:80]}") + session.get(continue_url, allow_redirects=True, timeout=30) + page_type = self._get_page_type(data) + + # 9. 如果还有 continue_url,跟随完成 + continue_url = data.get("continue_url", "") + if continue_url and continue_url.startswith("http"): + self._log("finalize", "info", f"Following continue_url: {continue_url[:80]}") + session.get(continue_url, allow_redirects=True, timeout=30) + + self._log("register", "ok", f"注册成功: {email}") + return RegisterResult(success=True, email=email, password=password) + + except Exception as e: + self._log("register", "error", str(e)) + return RegisterResult(success=False, email=email, password=password, error=str(e)) + + # ── 会话建立 ── + + def _establish_auth_session(self, session: cffi_requests.Session) -> bool: + """建立注册会话: CSRF → signin/openai → authorize(screen_hint=signup) → /create-account""" + try: + # CSRF token + r = session.get("https://chatgpt.com/api/auth/csrf", timeout=30) + if r.status_code != 200: + self._log("oauth_session", "error", f"CSRF 获取失败: {r.status_code}") + return False + csrf = r.json().get("csrfToken", "") + if not csrf: + self._log("oauth_session", "error", "CSRF token 为空") + return False + self._log("oauth_session", "info", f"CSRF: {csrf[:20]}...") + + # POST signin/openai → auth URL + r = session.post( + "https://chatgpt.com/api/auth/signin/openai", + data={ + "csrfToken": csrf, + "callbackUrl": "https://chatgpt.com/", + "json": "true", + }, + headers={"Content-Type": "application/x-www-form-urlencoded"}, + timeout=30, + ) + if r.status_code != 200: + self._log("oauth_session", "error", f"signin 失败: {r.status_code}") + return False + + auth_url = r.json().get("url", "") + if not auth_url or "auth.openai.com" not in auth_url: + self._log("oauth_session", "error", f"无效 auth URL: {auth_url[:100]}") + return False + + # 添加 screen_hint=signup + parsed = urlparse(auth_url) + qs = parse_qs(parsed.query, keep_blank_values=True) + qs["screen_hint"] = ["signup"] + auth_url = urlunparse(parsed._replace(query=urlencode(qs, doseq=True))) + self._log("oauth_session", "info", f"Auth URL: {auth_url[:120]}...") + + # GET authorize → 302 → /create-account (建立 session cookies) + r = session.get(auth_url, allow_redirects=True, timeout=30) + final_url = str(r.url) + self._log("oauth_session", "ok", f"会话已建立, final={final_url[:80]}") + return True + + except Exception as e: + self._log("oauth_session", "error", f"会话建立异常: {e}") return False \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index cc61b68..acb4363 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,4 @@ curl_cffi>=0.7.0 -requests>=2.31.0 \ No newline at end of file +requests>=2.31.0 +flask>=3.0.0 +apscheduler>=3.10.0 \ No newline at end of file diff --git a/run.py b/run.py index 079f92d..c95e6cf 100644 --- a/run.py +++ b/run.py @@ -1,232 +1,257 @@ -#!/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__": +#!/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 = 1 # 并行线程数 (1 = 单线程顺序执行) +COUNT = 50 # 注册账号数量 +SKIP_OAUTH = False # True = 只注册不做 OAuth 获取 token +PROXY = "http://127.0.0.1:7897" # 代理地址 + +# ══════════════════════════════════════════════════════════ + +# 确保当前目录在 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} + +# 供控制台批量任务写入 cpa_id / cpa_code(线程局部,避免并行任务互相污染) +_register_ctx = threading.local() + + +def set_register_context(*, cpa_id: int | None = None, cpa_code: str | None = None) -> None: + _register_ctx.cpa_id = cpa_id + _register_ctx.cpa_code = cpa_code + + +def clear_register_context() -> None: + _register_ctx.cpa_id = None + _register_ctx.cpa_code = None + + +def _merge_register_context(record: dict) -> None: + cid = getattr(_register_ctx, "cpa_id", None) + code = getattr(_register_ctx, "cpa_code", None) + if cid is not None: + record["cpa_id"] = cid + if code: + record["cpa_code"] = code + + +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 | None) -> str: + """将邮箱转为文件名: @ 和 . 替换为 _;空值回退 unknown""" + if not email: + return "unknown" + return str(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) + + _merge_register_context(record) + email = record.get("email", "unknown") + filename = _email_to_filename(email) + filepath = os.path.join(target_dir, f"{filename}.json") + with open(filepath, "w", encoding="utf-8") as f: + json.dump(record, f, ensure_ascii=False, indent=2) + print(f"[save] {filepath}") + + +def _build_oauth_record(email: str, tokens: dict) -> dict: + """从 OAuth token 响应构建目标格式的 record""" + access_token = tokens.get("access_token", "") + refresh_token = tokens.get("refresh_token", "") + id_token = tokens.get("id_token", "") + + # 从 access_token 解析 account_id 和 expired + jwt_payload = _decode_jwt_payload(access_token) + auth_info = jwt_payload.get("https://api.openai.com/auth", {}) + account_id = auth_info.get("chatgpt_account_id", "") + + # exp → ISO 8601 带时区 + exp = jwt_payload.get("exp") + if exp: + expired_dt = datetime.fromtimestamp(exp, tz=timezone(timedelta(hours=8))) + expired = expired_dt.isoformat() + else: + expired = "" + + now_dt = datetime.now(tz=timezone(timedelta(hours=8))) + + return { + "access_token": access_token, + "account_id": account_id, + "disabled": False, + "email": email, + "expired": expired, + "id_token": id_token, + "last_refresh": now_dt.isoformat(), + "refresh_token": refresh_token, + "type": "codex", + } + + +def _do_one(index: int, config: RegisterConfig, proxy: str, skip_oauth: bool) -> dict: + result = do_register(config) + + if not result.success: + record = { + "email": result.email, + "password": result.password, + "register_error": result.error or "unknown", + } + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + return record + + if skip_oauth: + record = {"email": result.email, "password": result.password} + save_account(record) + with _lock: + _counter["success"] += 1 + return record + + try: + tokens = do_oauth(result.email, result.password, proxy) + record = _build_oauth_record(result.email, tokens) + record["password"] = result.password + save_account(record) + with _lock: + _counter["success"] += 1 + except PasswordMismatchError as e: + record = {"email": result.email, "password": result.password, "oauth_error": f"password_mismatch: {e}"} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + except BannedError as e: + record = {"email": result.email, "password": result.password, "oauth_error": f"banned: {e}"} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + except Exception as e: + record = {"email": result.email, "password": result.password, "oauth_error": str(e)} + save_account(record, is_failed=True) + with _lock: + _counter["failed"] += 1 + + return record + + +def main(): + count = COUNT + threads = max(1, min(THREADS, count)) + proxy = PROXY + skip_oauth = SKIP_OAUTH + + config = RegisterConfig(proxy=proxy) + + _counter["success"] = 0 + _counter["failed"] = 0 + + print(f"开始批量注册: {count} 个账号, {threads} 线程并行") + print(f"代理: {proxy}") + print(f"跳过 OAuth: {skip_oauth}") + print(f"{'='*60}") + + import time as _time + start_time = _time.time() + + if threads <= 1: + for i in range(count): + _do_one(i + 1, config, proxy, skip_oauth) + else: + with ThreadPoolExecutor(max_workers=threads) as executor: + futures = { + executor.submit(_do_one, i + 1, config, proxy, skip_oauth): i + for i in range(count) + } + for future in as_completed(futures): + try: + future.result() + except Exception as e: + print(f"[error] 线程异常: {e}") + + elapsed = _time.time() - start_time + avg_time = elapsed / count if count > 0 else 0 + + print(f"\n{'='*60}") + print(f"完成: 成功 {_counter['success']}, 失败 {_counter['failed']}, 共 {count}") + print(f"总耗时: {elapsed:.1f}s | 平均速度: {avg_time:.1f}s/个") + print(f"账号文件保存在: {ACCOUNTS_DIR}") + + +if __name__ == "__main__": main() \ No newline at end of file diff --git a/scripts/cpa_runner.py b/scripts/cpa_runner.py new file mode 100644 index 0000000..dbe3c89 --- /dev/null +++ b/scripts/cpa_runner.py @@ -0,0 +1,25 @@ +#!/usr/bin/env python3 +"""CPA 定时同步入口:定时执行 run.py,迁出 oauth JSON,钉钉通知。 + +用法: + cd /path/to/protocol_chatgpt + pip install -r requirements.txt + cp .env.cpa-runner.example .env.cpa-runner # 按需修改 + python scripts/cpa_runner.py + +若维护台已开启「流水线 → 启用定时流水线」,请勿再运行本脚本(会抢同一套 oauth 目录与全局锁逻辑外的文件锁)。 + +仅在不跑 `python -m maintain`、或维护台未启用定时流水线时使用;勿起第二个 cpa_runner(`cpa_runner.lock`)。 +""" +from __future__ import annotations + +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO)) + +from maintain.cpa_runner_core import main_blocking # noqa: E402 + +if __name__ == "__main__": + main_blocking()