diff --git a/README.md b/README.md index 714e00c..0304867 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# OpenAI 协议级注册机 +# Codex账号维护工具 纯 HTTP 协议实现的 OpenAI/ChatGPT 账号注册 + OAuth Token 获取工具。 -无浏览器依赖,使用 `curl_cffi` 模拟 Chrome TLS 指纹。 +注册 / OAuth 主流程无浏览器依赖(使用 `curl_cffi` 模拟 Chrome TLS 指纹);临时邮箱支持可选 `EMAIL_PROVIDER=web`(Playwright)。 ## 服务器上更新代码 @@ -18,40 +18,12 @@ git pull origin main ## 安装 ```bash -pip install curl_cffi requests +pip install -r requirements.txt ``` -## 使用 +## 维护台模式(推荐) -```bash -# 注册单个账号并获取 OAuth Token -python run.py - -# 批量注册 -python run.py --count 5 - -# 仅注册不获取 Token -python run.py --no-oauth - -# 指定代理 -python run.py --proxy http://127.0.0.1:10808 -``` - -## 文件结构 - -``` -protocol_bot/ -├── run.py # 入口脚本 -├── email_service.py # 临时邮箱服务 -├── oauth_client.py # PKCE OAuth 客户端 -├── register.py # 协议级注册模块 -├── oauth_login.py # 协议级 OAuth 登录模块 -└── README.md -``` - -## 一条命令跑整条流水线(推荐) - -维护台把 **CPA 统计 / 补号 / 子进程 run.py / 迁出 JSON / 钉钉** 收在一个进程里: +### 1) 快速启动 ```bash pip install -r requirements.txt @@ -61,6 +33,42 @@ python -m maintain # 本机浏览器: http://127.0.0.1:8765 ``` +### 2) 自动化链路(核心) + +在“任务中心”启用自动巡检后,维护台会按间隔自动执行: + +1. 先按 `/usage` 连续失败阈值清理(等价 `cliproxy_auth_sweeper.py` 逻辑); +2. 再做管理 API 探测(`auth-files/models`)并清理失效本地 JSON; +3. 若仍有缺口,自动触发一批进程内补号(受 `max_auto_register_per_tick` 限制)。 + +另外“流水线”页签的定时任务是独立链路:按缺口决定是否执行 `run.py -> 迁出 JSON -> 钉钉`。 + +### 3) 必填配置(配置编辑页) + +- `cliproxy_management_base`、`cliproxy_management_key`:巡检/清理必填。 +- `codex_stats_oauth_dir`:若 JSON 不在项目内 `accounts/oauth`,必须填真实目录(如 `~/.cli-proxy-api`)。 +- `cliproxy_sweeper_threshold` / `cliproxy_sweeper_run_mode`:控制 `/usage` 清理阈值与 delete/observe 模式。 + +### 临时邮箱(mail.chatgpt.org.uk) + +- **`MAIL_API_KEY`** 或 **`EMAIL_API_KEY`**:调用 `https://mail.chatgpt.org.uk/api` 时放在请求头 **`X-API-Key`**(默认占位 `gpt-test`,生产请改成你自己的 key)。 +- **`EMAIL_PROVIDER`**:`web`(默认,Playwright)或 `api`(纯 HTTP,走 `X-API-Key`)。使用 `web` 时需在环境里执行一次 **`playwright install chromium`**。 +- 可选:**`HTTP_PROXY` / `HTTPS_PROXY`**;调试:**`EMAIL_DEBUG=1`**。 + +## 文件结构 + +``` +protocol_chatgpt/ +├── run.py # 入口脚本 +├── email_service.py # 临时邮箱服务 +├── oauth_client.py # PKCE OAuth 客户端 +├── register.py # 协议级注册模块 +├── oauth_login.py # 协议级 OAuth 登录模块 +└── README.md +``` + +## 维护台运行说明 + ### 用服务器公网 IP 访问不到 8765 默认 **`CODEX_MAINTAIN_HOST=127.0.0.1`**,进程只接受本机连接,**用别的机器浏览器打 `http://IP:8765` 会连不上**。 @@ -103,7 +111,7 @@ python -m maintain | 页签 | 能力 | |------|------| -| **任务中心** | 巡检:管理 API 探测 + 删失效本地 JSON;仍有缺口则**自动进程内批量注册**(每批 ≤ `max_auto_register_per_tick`,与手动补号**同一把 REGISTER_LOCK**) | +| **任务中心** | 巡检:先按 `/usage` 阈值清理,再做管理 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 个号 | @@ -125,6 +133,29 @@ python3 -m venv .venv && .venv/bin/pip install -r requirements.txt -i https://py 应输出 `verify_batch_register: OK ...`。**真实注册**仍依赖代理、邮箱服务等:在维护台用「开始批量注册」先试 `count=1`,或巡检后看是否出现 `inspect_register` 任务并观察成功/失败数。 +## 脚本模式(可选) + +### 直接跑 `run.py` + +`run.py` 当前是“文件内常量配置”模式(不是命令行参数模式)。默认直接运行: + +```bash +python run.py +``` + +需要改数量/线程/代理/是否跳过 OAuth,请编辑 `run.py` 顶部配置项:`COUNT`、`THREADS`、`PROXY`、`SKIP_OAUTH`。 + +### 单独运行 CliProxy 失效清理脚本 + +```bash +export MANAGEMENT_KEY='你的管理密钥' +# 可选:BASE_URL 默认 http://localhost:8317/v0/management +# 可选:RUN_MODE=observe 先观察不删除 +python cliproxy_auth_sweeper.py +``` + +常用环境变量:`THRESHOLD`(默认 `3`)、`RUN_MODE=delete|observe`、`TIMEOUT`(默认 `10`)、`ALLOW_NAME_FALLBACK=1|0`、`INSECURE=1|0`、`VERBOSE=1|0`。 + ## 可选:独立 cpa_runner 进程 若不跑维护台、只想要旧版「定时子进程 + 迁文件」,仍可用 `scripts/cpa_runner.py` + `.env.cpa-runner`(见 `.env.cpa-runner.example`)。**维护台已开启「定时流水线」时不要同时跑本脚本。** diff --git a/cliproxy_auth_sweeper.py b/cliproxy_auth_sweeper.py new file mode 100644 index 0000000..1fed909 --- /dev/null +++ b/cliproxy_auth_sweeper.py @@ -0,0 +1,524 @@ +#!/usr/bin/env python3 +"""CliProxyAuthSweeper (env-only mode, no jq required). + +Environment variables: + MANAGEMENT_KEY Required. Management API key. + BASE_URL Optional. Default: http://localhost:8317/v0/management + THRESHOLD Optional. Default: 3 + RUN_MODE Optional. delete|observe (default: delete) + ALLOW_NAME_FALLBACK Optional. 1|0 (default: 1) + TIMEOUT Optional. HTTP timeout seconds (default: 10) + INSECURE Optional. 1|0 (default: 0) + VERBOSE Optional. 1|0 (default: 0) +""" +from __future__ import annotations + +import json +import os +import re +import ssl +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from datetime import datetime, timezone + + +def to_bool(v: object, default: bool = False) -> bool: + if v is None: + return default + return str(v).strip().lower() in {"1", "true", "yes", "y", "on"} + + +def info(msg: str) -> None: + print(msg) + + +def die(msg: str, code: int = 1) -> None: + print(f"ERROR: {msg}", file=sys.stderr) + raise SystemExit(code) + + +def parse_int(name: str, raw: object, min_value: int | None = None, required: bool = False) -> int | None: + if raw is None or raw == "": + if required: + die(f"{name} is required") + return None + try: + value = int(str(raw)) + except Exception: + die(f"{name} must be an integer") + if min_value is not None and value < min_value: + die(f"{name} must be >= {min_value}") + return value + + +def parse_timestamp_to_epoch(ts: object) -> int | None: + if not isinstance(ts, str): + return None + s = ts.strip() + if not s: + return None + + m = re.match( + r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})?$", + s, + ) + if not m: + return None + + base, frac, tz = m.group(1), m.group(2), m.group(3) + if frac: + frac = frac[:6] + norm = f"{base}.{frac}" + else: + norm = base + + if tz is None or tz == "Z": + tz = "+00:00" + norm = f"{norm}{tz}" + + try: + dt = datetime.fromisoformat(norm) + except Exception: + return None + if dt.tzinfo is None: + dt = dt.replace(tzinfo=timezone.utc) + return int(dt.timestamp()) + + +def http_request_with_retry( + base_url: str, + path: str, + method: str, + headers: dict[str, str], + timeout: int, + insecure: bool, +) -> tuple[int, str]: + max_attempts = 3 + delay = 1 + context = ssl._create_unverified_context() if insecure else None + url = f"{base_url}{path}" + + for attempt in range(1, max_attempts + 1): + req = urllib.request.Request(url=url, headers=headers, method=method) + try: + with urllib.request.urlopen(req, timeout=timeout, context=context) as resp: + code = resp.getcode() + body = resp.read().decode("utf-8", errors="replace") + return code, body + except urllib.error.HTTPError as e: + code = int(getattr(e, "code", 0) or 0) + body = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else "" + if (code == 429 or 500 <= code <= 599) and attempt < max_attempts: + time.sleep(delay) + delay *= 2 + continue + return code, body + except Exception: + if attempt < max_attempts: + time.sleep(delay) + delay *= 2 + continue + return 0, "" + return 0, "" + + +def request_json_or_die( + base_url: str, + path: str, + method: str, + headers: dict[str, str], + timeout: int, + insecure: bool, +) -> dict: + code, body = http_request_with_retry( + base_url=base_url, + path=path, + method=method, + headers=headers, + timeout=timeout, + insecure=insecure, + ) + if not (200 <= code < 300): + die(f"{method} {path} failed with HTTP {code}; body={body}") + try: + data = json.loads(body) + except Exception: + die(f"{method} {path} returned invalid JSON") + if not isinstance(data, dict): + die(f"{method} {path} returned non-object JSON") + return data + + +def build_usage_analysis(usage_obj: dict, threshold: int, run_started_epoch: int) -> dict: + events: list[dict[str, object]] = [] + usage = usage_obj.get("usage", {}) if isinstance(usage_obj, dict) else {} + apis = usage.get("apis", {}) if isinstance(usage, dict) else {} + if isinstance(apis, dict): + for _, api_data in apis.items(): + models = api_data.get("models", {}) if isinstance(api_data, dict) else {} + if not isinstance(models, dict): + continue + for _, model_data in models.items(): + details = model_data.get("details", []) if isinstance(model_data, dict) else [] + if not isinstance(details, list): + continue + for d in details: + if not isinstance(d, dict): + continue + if "timestamp" not in d or "auth_index" not in d: + continue + epoch = parse_timestamp_to_epoch(str(d.get("timestamp"))) + if epoch is None: + continue + failed = d.get("failed", False) + if not isinstance(failed, bool): + failed = False + events.append( + { + "timestamp": str(d.get("timestamp")), + "epoch": epoch, + "auth_index": str(d.get("auth_index")), + "failed": failed, + } + ) + + window_events = [e for e in events if int(e["epoch"]) <= run_started_epoch] + window_mode = "full" + window_events.sort(key=lambda x: int(x["epoch"])) + + streaks: dict[str, dict[str, object]] = {} + for e in window_events: + idx = str(e["auth_index"]) + state = streaks.setdefault( + idx, + { + "current_streak": 0, + "max_streak": 0, + "last_timestamp": None, + "last_failed": None, + }, + ) + if bool(e["failed"]): + state["current_streak"] = int(state["current_streak"]) + 1 + else: + state["current_streak"] = 0 + if int(state["current_streak"]) > int(state["max_streak"]): + state["max_streak"] = int(state["current_streak"]) + state["last_timestamp"] = str(e["timestamp"]) + state["last_failed"] = bool(e["failed"]) + + bad_auth_indexes: list[dict[str, object]] = [] + for auth_index, st in streaks.items(): + if int(st["max_streak"]) >= threshold: + bad_auth_indexes.append( + { + "auth_index": auth_index, + "max_streak": int(st["max_streak"]), + "last_timestamp": st["last_timestamp"], + "last_failed": bool(st["last_failed"]), + } + ) + bad_auth_indexes.sort(key=lambda x: str(x["auth_index"])) + + return { + "usage_total_events": len(events), + "usage_window_events": len(window_events), + "window_mode": window_mode, + "bad_auth_indexes": bad_auth_indexes, + } + + +def build_candidates(analysis: dict, auth_files_obj: dict, allow_name_fallback: bool) -> dict: + files = auth_files_obj.get("files", []) if isinstance(auth_files_obj, dict) else [] + if not isinstance(files, list): + files = [] + bad = analysis.get("bad_auth_indexes", []) + if not isinstance(bad, list): + bad = [] + + def normalize_value(v: object) -> str: + if v is None: + return "" + return str(v).strip() + + def normalize_name(name: object) -> str: + s = normalize_value(name) + return s[:-5] if s.lower().endswith(".json") else s + + def equals_idx(a: object, b: object) -> bool: + av = normalize_value(a) + bv = normalize_value(b) + if not av or not bv: + return False + return av == bv or av.lower() == bv.lower() + + def find_by_auth_index(idx: str) -> list[dict]: + out = [] + for f in files: + if not isinstance(f, dict): + continue + raw = f.get("auth_index", f.get("authIndex")) + if equals_idx(raw, idx): + out.append(f) + return out + + def find_by_id(idx: str) -> list[dict]: + out = [] + for f in files: + if not isinstance(f, dict): + continue + file_id = normalize_value(f.get("id")) + if not file_id: + continue + if equals_idx(file_id, idx) or equals_idx(normalize_name(file_id), idx): + out.append(f) + return out + + def find_by_name(idx: str) -> list[dict]: + out = [] + for f in files: + if not isinstance(f, dict): + continue + name = normalize_value(f.get("name", "")) + if equals_idx(name, idx) or equals_idx(normalize_name(name), idx): + out.append(f) + return out + + candidates = [] + skipped = [] + for b in bad: + idx = normalize_value(b.get("auth_index", "")) + matches = find_by_auth_index(idx) + match_mode = "auth_index" + + if not matches: + matches = find_by_id(idx) + match_mode = "id" + if not matches and allow_name_fallback: + matches = find_by_name(idx) + match_mode = "name_fallback" + if not matches: + continue + if len(matches) > 1: + skipped.append( + { + "auth_index": idx, + "reason": "ambiguous_match", + "match_count": len(matches), + } + ) + continue + + f = matches[0] + file_name = str(f.get("name", "")) + if str(f.get("source", "")) != "file": + skipped.append({"auth_index": idx, "file_name": file_name, "reason": "source_not_file"}) + continue + if bool(f.get("runtime_only", False)) is True: + skipped.append({"auth_index": idx, "file_name": file_name, "reason": "runtime_only"}) + continue + if not file_name.endswith(".json"): + skipped.append({"auth_index": idx, "file_name": file_name, "reason": "not_json"}) + continue + + candidates.append( + { + "auth_index": idx, + "file_name": file_name, + "file_id": f.get("id"), + "match_mode": match_mode, + "max_streak": b.get("max_streak"), + "last_timestamp": b.get("last_timestamp"), + } + ) + + seen = set() + uniq = [] + for c in sorted(candidates, key=lambda x: str(x["file_name"])): + fn = str(c["file_name"]) + if fn in seen: + continue + seen.add(fn) + uniq.append(c) + + return {"candidates": uniq, "skipped": skipped} + + +def main() -> None: + management_key = os.getenv("MANAGEMENT_KEY", "").strip() + if not management_key: + die("MANAGEMENT_KEY is required") + + base_url = os.getenv("BASE_URL", "http://localhost:8317/v0/management").rstrip("/") + threshold = parse_int("THRESHOLD", os.getenv("THRESHOLD", "3"), min_value=1, required=True) + run_mode = os.getenv("RUN_MODE", "delete").strip().lower() + if run_mode not in {"delete", "observe"}: + die("RUN_MODE must be one of: delete, observe") + allow_name_fallback = to_bool(os.getenv("ALLOW_NAME_FALLBACK", "1"), default=True) + timeout = parse_int("TIMEOUT", os.getenv("TIMEOUT", "10"), min_value=1, required=True) + insecure = to_bool(os.getenv("INSECURE", "0"), default=False) + verbose = to_bool(os.getenv("VERBOSE", "0"), default=False) + + if threshold is None or timeout is None: + die("invalid THRESHOLD/TIMEOUT") + + apply_mode = run_mode == "delete" + run_started_epoch = int(time.time()) + run_started_at = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + info(f"run_started_at={run_started_at}") + info(f"run_mode={run_mode} (default is delete)") + info("window=full (always full scan)") + + headers = { + "Accept": "application/json", + "Authorization": f"Bearer {management_key}", + "X-Management-Key": management_key, + } + + usage_obj = request_json_or_die( + base_url=base_url, + path="/usage", + method="GET", + headers=headers, + timeout=timeout, + insecure=insecure, + ) + analysis = build_usage_analysis(usage_obj=usage_obj, threshold=threshold, run_started_epoch=run_started_epoch) + + auth_files_obj = request_json_or_die( + base_url=base_url, + path="/auth-files", + method="GET", + headers=headers, + timeout=timeout, + insecure=insecure, + ) + match = build_candidates(analysis=analysis, auth_files_obj=auth_files_obj, allow_name_fallback=allow_name_fallback) + + usage_total_events = int(analysis.get("usage_total_events", 0)) + usage_window_events = int(analysis.get("usage_window_events", 0)) + window_mode = str(analysis.get("window_mode", "unknown")) + visible_bad_indexes = {str(c.get("auth_index", "")) for c in match.get("candidates", [])} | { + str(s.get("auth_index", "")) for s in match.get("skipped", []) + } + visible_bad_auth_indexes = [ + b for b in analysis.get("bad_auth_indexes", []) if str(b.get("auth_index", "")) in visible_bad_indexes + ] + + bad_count = len(visible_bad_auth_indexes) + candidate_count = len(match.get("candidates", [])) + skipped_count = len(match.get("skipped", [])) + + info(f"usage_total_events={usage_total_events} usage_window_events={usage_window_events} window_mode={window_mode}") + info(f"bad_auth_indexes={bad_count} delete_candidates={candidate_count} skipped={skipped_count}") + + if candidate_count > 0: + info("candidates:") + for c in match["candidates"]: + info( + f"- {c['file_name']} " + f"(auth_index={c['auth_index']}, max_streak={c['max_streak']}, match={c['match_mode']})" + ) + + deleted = [] + errors = [] + if apply_mode: + for c in match.get("candidates", []): + file_name = str(c["file_name"]) + encoded_name = urllib.parse.quote(file_name, safe="") + code, body = http_request_with_retry( + base_url=base_url, + path=f"/auth-files?name={encoded_name}", + method="DELETE", + headers=headers, + timeout=timeout, + insecure=insecure, + ) + if 200 <= code < 300: + deleted.append({"file_name": file_name, "http_code": code}) + else: + errors.append({"file_name": file_name, "http_code": code, "response_body": body}) + info(f"delete_result: deleted={len(deleted)} failed={len(errors)}") + else: + info("observe mode: no deletion executed") + + report = { + "run_started_at": run_started_at, + "run_started_epoch": run_started_epoch, + "run_mode": run_mode, + "threshold": threshold, + "base_url": base_url, + "allow_name_fallback": allow_name_fallback, + "window_mode": window_mode, + "usage_total_events": usage_total_events, + "usage_window_events": usage_window_events, + "bad_auth_indexes": visible_bad_auth_indexes, + "delete_candidates": match.get("candidates", []), + "skipped": match.get("skipped", []), + "deleted": deleted, + "errors": errors, + } + + run_mode_cn = "删除模式" if run_mode == "delete" else "观察模式" + window_mode_cn = "全量" + allow_name_fallback_cn = "开启" if allow_name_fallback else "关闭" + window_range = f"起始 -> {run_started_at}" + + info("=============== CliProxyAuthSweeper 运行报告 ===============") + info(f"运行时间(UTC) : {run_started_at}") + info(f"运行模式 : {run_mode_cn}") + info(f"统计模式 : {window_mode_cn}") + info(f"统计窗口 : {window_range}") + info(f"失败阈值 : 连续失败 >= {threshold}") + info(f"名称回退匹配 : {allow_name_fallback_cn}") + info("") + info("请求统计") + info(f"- 总事件数 : {usage_total_events}") + info(f"- 窗口事件数 : {usage_window_events}") + info("") + info("检测结果") + info(f"- 失效授权索引数 : {bad_count}") + info(f"- 待删文件数 : {candidate_count}") + info(f"- 跳过数量 : {skipped_count}") + if candidate_count > 0: + info("") + info("待删文件列表") + for i, c in enumerate(match.get("candidates", []), 1): + info( + f"{i}) auth_index={c.get('auth_index')} " + f"file={c.get('file_name')} max_streak={c.get('max_streak')} " + f"match={c.get('match_mode')}" + ) + if skipped_count > 0: + info("") + info("跳过列表") + for i, s in enumerate(match.get("skipped", []), 1): + line = f"{i}) auth_index={s.get('auth_index')} reason={s.get('reason')}" + if s.get("file_name"): + line += f" file={s.get('file_name')}" + if s.get("match_count") is not None: + line += f" match_count={s.get('match_count')}" + info(line) + info("") + info("删除结果") + info(f"- 删除成功 : {len(deleted)}") + info(f"- 删除失败 : {len(errors)}") + if errors: + info("") + info("删除失败明细") + for i, e in enumerate(errors, 1): + info(f"{i}) file={e.get('file_name')} http_code={e.get('http_code')}") + info("===========================================================") + if verbose: + info("report_json=" + json.dumps(report, ensure_ascii=False, separators=(",", ":"))) + + if apply_mode and errors: + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/email_service.py b/email_service.py index 9afaafb..1780cc3 100644 --- a/email_service.py +++ b/email_service.py @@ -1,256 +1,425 @@ -"""临时邮箱 — [GPTMail](https://mail.chatgpt.org.uk) 网页模拟 +"""临时邮箱 — mail.chatgpt.org.uk -对外接口: +对外接口(与 register / oauth_login 一致): - 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 配额限制。 +模式由环境变量 **EMAIL_PROVIDER** 控制: +- **api**(默认):`GET /api/generate-email`,需 `MAIL_API_KEY` 或 `EMAIL_API_KEY` +- **web**:Playwright 打开网页自动取号;取码时轮询收件页 + +服务器首次使用 web 模式需安装浏览器内核:`playwright install chromium` """ from __future__ import annotations +import os +import random import re +import string import time -from typing import Optional +from datetime import datetime +from typing import Any, Optional import requests -GPTMAIL_BASE = "https://mail.chatgpt.org.uk" +MAIL_API_BASE = "https://mail.chatgpt.org.uk/api" +MAIL_API_KEY = os.getenv("MAIL_API_KEY") or os.getenv("EMAIL_API_KEY") or "gpt-test" +EMAIL_PROVIDER = os.getenv("EMAIL_PROVIDER", "web").lower() # 'api' or 'web' -# 当前进程内:本脚本创建的邮箱 -> 会话信息 -_MAIL_STATE: dict[str, dict] = {} +_UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36" -UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136 Safari/537.36" +_MAIL_STATE: dict[str, dict[str, Any]] = {} -def _gptmail_headers() -> dict: - return { - "User-Agent": UA, - "Accept": "application/json", - } +_EMAIL_DEBUG = os.getenv("EMAIL_DEBUG", "").strip().lower() in {"1", "true", "yes", "on"} + +_HTTP = requests.Session() -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 _proxies() -> dict[str, str]: + h = (os.getenv("HTTP_PROXY") or os.getenv("http_proxy") or "").strip() + hs = (os.getenv("HTTPS_PROXY") or os.getenv("https_proxy") or "").strip() + if not h and not hs: + return {} + return {"http": h or hs, "https": hs or h} -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 才会通过""" +def _safe_print(msg: str) -> None: 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 + print(msg, flush=True) + except OSError: + pass -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 +def _dlog(msg: str) -> None: + if _EMAIL_DEBUG: + _safe_print(f"[email][mail_api] {msg}") + + +def _clip(s: str, n: int = 240) -> str: + s = (s or "").replace("\n", " ").replace("\r", " ") + return s if len(s) <= n else s[:n] + "..." + + +def _api_headers() -> dict[str, str]: return { - "token": token, - "email": (auth.get("email") or "").strip().lower(), - "expires_at": int(auth.get("expires_at") or 0), + "User-Agent": _UA, + "X-API-Key": MAIL_API_KEY, } -def _auth_fetch( - session: requests.Session, +def _request( method: str, - path: str, + url: str, *, - auth_email: str, - params: dict | None = None, - json_data: dict | None = None, + timeout: int = 15, + retries: int = 2, + **kwargs: Any, ) -> 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, + last_exc: Optional[Exception] = None + now = datetime.now() + formatted_time = now.strftime("%Y-%m-%d %H:%M:%S") + px = _proxies() + if px: + kwargs.setdefault("proxies", px) + + for attempt in range(retries + 1): + try: + r = _HTTP.request(method, url, timeout=timeout, **kwargs) + except requests.RequestException as e: + last_exc = e + _dlog( + f"[{formatted_time}]{method} {url} network_error={e.__class__.__name__}: {e} " + f"(attempt {attempt + 1}/{retries + 1})" + ) + if attempt >= retries: + raise + time.sleep(0.6 * (2**attempt) + random.random() * 0.2) + continue + + if r.status_code in (429, 500, 502, 503, 504): + _dlog( + f"[{formatted_time}]{method} {url} status={r.status_code} body={_clip(r.text)} " + f"(attempt {attempt + 1}/{retries + 1})" + ) + if attempt >= retries: + return r + + sleep_s = 0.8 * (2**attempt) + random.random() * 0.2 + if r.status_code == 429: + ra = (r.headers.get("Retry-After") or "").strip() + if ra.isdigit(): + sleep_s = max(sleep_s, float(ra)) + time.sleep(min(sleep_s, 8.0)) + continue + + return r + + if last_exc: + raise last_exc + raise RuntimeError("request failed") + + +def _mailapi_create_email() -> Optional[str]: + r = _request( + "GET", + f"{MAIL_API_BASE}/generate-email", + headers=_api_headers(), + timeout=15, + retries=2, ) - - -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}") + _dlog(f"GET /generate-email failed: status={r.status_code} body={_clip(r.text)}") return None - if not body.get("success"): - err = body.get("error") or body.get("message") or r.text[:200] - print(f"[email] GPTMail 创建失败: {err}") + data = r.json() if r.content else {} + if not data.get("success"): + _dlog(f"GET /generate-email success=false body={_clip(r.text)}") return None - data = body.get("data") or {} - email = (data.get("email") or "").strip() - if not email or "@" not in email: - print("[email] GPTMail 返回缺少 email") + email = ((data.get("data") or {}).get("email") or "").strip() + if not email: + _dlog("generate-email missing email field") return None _MAIL_STATE[email] = { - "provider": "gptmail", - "session": session, + "provider": "mail_api", + "created_at": time.time(), } + _dlog(f"email created ok: {email}") return email -def create_temp_email() -> Optional[str]: - """创建临时邮箱,返回邮箱地址""" +def _web_create_email() -> Optional[str]: try: - return _gptmail_create_email() + from playwright.sync_api import TimeoutError as PlaywrightTimeoutError + from playwright.sync_api import sync_playwright + except ImportError: + _safe_print( + "[email] EMAIL_PROVIDER=web 需要安装 playwright:pip install playwright && playwright install chromium" + ) + return None + + try: + with sync_playwright() as p: + browser = p.chromium.launch( + headless=True, + args=[ + "--no-sandbox", + "--disable-setuid-sandbox", + "--disable-dev-shm-usage", + ], + ) + try: + context = browser.new_context( + viewport={"width": 1920, "height": 1080}, + user_agent=_UA, + ) + page = context.new_page() + + _dlog("[playwright] Navigating to mail site...") + page.goto( + "https://mail.chatgpt.org.uk/", + timeout=60000, + wait_until="domcontentloaded", + ) + + try: + page.wait_for_selector("//button[contains(., '我知道了')]", timeout=8000) + page.click("//button[contains(., '我知道了')]") + _dlog("[playwright] Closed popup.") + except PlaywrightTimeoutError: + pass + + _dlog("[playwright] Waiting for auto-generated email...") + try: + email_el = page.wait_for_selector("#emailDisplay", timeout=30000) + for _ in range(40): + raw = email_el.text_content() or "" + email_text = raw.strip() + if "@" in email_text and "loading" not in email_text.lower(): + _MAIL_STATE[email_text] = { + "provider": "playwright_web", + "created_at": time.time(), + } + _dlog(f"[playwright] email created ok: {email_text}") + return email_text + time.sleep(0.5) + + _dlog("[playwright] Timeout waiting for valid email text.") + try: + page.screenshot(path="debug_create_email_timeout.png") + except OSError: + pass + return None + except Exception as e: + _dlog(f"[playwright] Error finding email element: {e}") + try: + page.screenshot(path="debug_create_email_error.png") + except OSError: + pass + return None + finally: + browser.close() except Exception as e: - print(f"[email] 创建失败: {e}") + _safe_print(f"[email][playwright] _web_create_email failed: {e}") + return None + + +def _web_wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]: + try: + from playwright.sync_api import TimeoutError as PlaywrightTimeoutError + from playwright.sync_api import sync_playwright + except ImportError: + return None + + try: + with sync_playwright() as p: + browser = p.chromium.launch( + headless=True, + args=[ + "--no-sandbox", + "--disable-setuid-sandbox", + "--disable-dev-shm-usage", + ], + ) + try: + context = browser.new_context( + viewport={"width": 1920, "height": 1080}, + user_agent=_UA, + ) + page = context.new_page() + + inbox_url = f"https://mail.chatgpt.org.uk/{email_address}" + _dlog(f"[playwright] Starting poll on {inbox_url}") + page.goto(inbox_url, timeout=30000) + + try: + page.wait_for_selector("//button[contains(., '我知道了')]", timeout=5000) + page.click("//button[contains(., '我知道了')]") + except PlaywrightTimeoutError: + pass + + start_time = time.time() + while time.time() - start_time < timeout: + _dlog("[playwright] Scanning page text for code...") + try: + body_text = page.locator("body").text_content() or "" + patterns = [ + r"Your ChatGPT code is\s*(\d{6})", + r"verification code:?\s*(\d{6})", + r"code is\s*(\d{6})", + ] + found_code: Optional[str] = None + for pat in patterns: + match = re.search(pat, body_text, re.IGNORECASE) + if match: + found_code = match.group(1) + break + if found_code: + _dlog(f"[playwright] Success! Found code: {found_code}") + return found_code + match = re.search(r"(\d{6})", body_text) + if match: + code = match.group(1) + _dlog(f"[playwright] Success! Found code (generic): {code}") + return code + except Exception as e: + _dlog(f"[playwright] Error reading text: {e}") + + try: + refresh_btn = page.locator("//button[contains(., '刷新')]") + if refresh_btn.is_visible(): + refresh_btn.click() + else: + page.reload() + except Exception: + page.reload() + time.sleep(5) + + _dlog("[playwright] Timeout polling for code.") + return None + finally: + browser.close() + except Exception as e: + _safe_print(f"[email][playwright] _web_wait_for_code failed: {e}") + return None + + +def create_temp_email() -> Optional[str]: + try: + if EMAIL_PROVIDER == "web": + _safe_print("[email] Using web provider (Playwright)") + return _web_create_email() + _safe_print("[email] Using api provider") + return _mailapi_create_email() + except Exception as e: + _safe_print(f"[email] create failed: {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": + if not state: + return [] + if state.get("provider") != "mail_api": 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, + headers = _api_headers() + r = _request( "GET", - "/api/emails", - auth_email=email_address, + f"{MAIL_API_BASE}/emails", params={"email": email_address}, + headers=headers, + timeout=20, + retries=2, ) if r.status_code != 200: + _dlog(f"GET /emails failed: status={r.status_code} body={_clip(r.text)}") return [] - body = r.json() - if not body.get("success"): + data = r.json() if r.content else {} + if not data.get("success"): + _dlog(f"GET /emails success=false body={_clip(r.text)}") return [] - data = body.get("data") or {} - members = data.get("emails") or [] + payload = data.get("data") + if isinstance(payload, dict) and "emails" in payload: + members = payload.get("emails") or [] + else: + members = payload or [] + if not isinstance(members, list): + _dlog("GET /emails data is not a list") return [] - out: list[dict] = [] + out: list[dict[str, Any]] = [] 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)) + mid = msg.get("id") or msg.get("email_id") + detail: dict[str, Any] = {} + if mid: + rd = _request( + "GET", + f"{MAIL_API_BASE}/email/{mid}", + headers=headers, + timeout=20, + retries=2, + ) + if rd.status_code == 200: + d = rd.json() if rd.content else {} + detail = d.get("data") if isinstance(d, dict) else {} + + sender = ( + detail.get("from_address") + or msg.get("from_address") + or msg.get("from") + or msg.get("sender") + or "" + ) + subject = detail.get("subject") or msg.get("subject") or "" + text_content = detail.get("content") or msg.get("content") or "" + html_content = detail.get("html_content") or msg.get("html_content") or "" + created_at = detail.get("created_at") or msg.get("created_at") + timestamp = detail.get("timestamp") or msg.get("timestamp") + + out.append( + { + "id": mid, + "from": sender, + "sender": sender, + "subject": subject, + "text_content": text_content, + "html_content": html_content, + "content": text_content, + "body": text_content, + "date": created_at or timestamp, + } + ) return out except Exception as e: - print(f"[email] 获取邮件错误: {e}") + _safe_print(f"[email] fetch failed: {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) + 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) + 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": @@ -259,9 +428,16 @@ def extract_code(email_data: dict) -> Optional[str]: def wait_for_code(email_address: str, timeout: int = 120) -> Optional[str]: - """轮询等待验证码""" + state = _MAIL_STATE.get(email_address, {}) + provider = state.get("provider") + + if provider == "playwright_web": + _safe_print("[email] Waiting for code via web provider (Playwright UI)") + return _web_wait_for_code(email_address, timeout=timeout) + + _safe_print("[email] Waiting for code via api provider") start = time.time() - seen = set() + seen: set[Any] = set() while time.time() - start < timeout: for mail in fetch_emails(email_address): mid = mail.get("id") or mail.get("date") diff --git a/maintain/app.py b/maintain/app.py index 9b8b37e..37ebe4b 100644 --- a/maintain/app.py +++ b/maintain/app.py @@ -8,6 +8,7 @@ import os import sys import threading import time +import urllib.parse from collections import defaultdict from datetime import datetime, timezone from functools import wraps @@ -33,6 +34,7 @@ from maintain.cpa_runner_core import ( runner_config_from_db, save_state, ) +import cliproxy_auth_sweeper as cliproxy_sweeper _plog = logging.getLogger("cpa-runner") if not _plog.handlers: @@ -246,6 +248,15 @@ def api_overview(): "cliproxy_probe_timeout_sec": settings.get( "cliproxy_probe_timeout_sec", "30" ), + "cliproxy_sweeper_threshold": settings.get( + "cliproxy_sweeper_threshold", "3" + ), + "cliproxy_sweeper_run_mode": settings.get( + "cliproxy_sweeper_run_mode", "delete" + ), + "cliproxy_sweeper_allow_name_fallback": settings.get( + "cliproxy_sweeper_allow_name_fallback", "1" + ), "codex_stats_oauth_dir": settings.get("codex_stats_oauth_dir", ""), }, } @@ -478,6 +489,27 @@ def _run_cliproxy_inspect_worker(task_id: int, source: str) -> None: message=f"管理端不可用或密钥无效(未删任何文件): {mgmt_err}", ) return + + # 巡检前先跑一次 usage 阈值失效清理,保证“巡检=检查+清理”。 + try: + sweep = _run_cliproxy_sweeper_worker( + task_id, + f"{source} usage清理", + finalize_task=False, + ) + rtlog().info( + "[inspect#%s] %s usage清理完成 threshold=%s matched=%s deleted=%s failed=%s mode=%s", + task_id, + source, + sweep.get("threshold"), + sweep.get("matched"), + sweep.get("deleted"), + sweep.get("failed"), + sweep.get("mode"), + ) + except Exception as e: + rtlog().warning("[inspect#%s] %s usage清理异常,继续探测流程: %s", task_id, source, e) + entries = db.list_oauth_codex_entries() total = len(entries) rtlog().info( @@ -585,6 +617,137 @@ def _start_inspect_job(source: str) -> tuple[bool, Optional[int], str]: return True, tid, "ok" +def _run_cliproxy_sweeper_worker( + task_id: int, + source: str, + *, + finalize_task: bool = True, +) -> dict[str, int | str]: + """按 usage 连续失败阈值清理 auth-files 里的失效 JSON。""" + base = db.get_setting("cliproxy_management_base", "").strip() + key = db.get_setting("cliproxy_management_key", "").strip() + if not base or not key: + msg = "请先在「配置编辑」填写 Cliproxy 管理地址与密钥" + if finalize_task: + db.update_task(task_id, status="error", message=msg) + raise RuntimeError(msg) + + timeout = max(1, int(float(db.get_setting("cliproxy_probe_timeout_sec", "30")))) + threshold = max(1, int(db.get_setting("cliproxy_sweeper_threshold", "3"))) + run_mode = db.get_setting("cliproxy_sweeper_run_mode", "delete").strip().lower() + if run_mode not in {"delete", "observe"}: + run_mode = "delete" + allow_name_fallback = ( + db.get_setting("cliproxy_sweeper_allow_name_fallback", "1").strip() == "1" + ) + apply_mode = run_mode == "delete" + + rtlog().info( + "[sweeper#%s] %s 开始 base=%s threshold=%s mode=%s", + task_id, + source, + base, + threshold, + run_mode, + ) + db.update_task(task_id, status="running", message=f"{source}: 拉取 usage/auth-files …", done=0) + + headers = { + "Accept": "application/json", + "Authorization": f"Bearer {key}", + "X-Management-Key": key, + } + run_started_epoch = int(time.time()) + + usage_obj = cliproxy_sweeper.request_json_or_die( + base_url=base.rstrip("/"), + path="/usage", + method="GET", + headers=headers, + timeout=timeout, + insecure=False, + ) + analysis = cliproxy_sweeper.build_usage_analysis( + usage_obj=usage_obj, + threshold=threshold, + run_started_epoch=run_started_epoch, + ) + auth_files_obj = cliproxy_sweeper.request_json_or_die( + base_url=base.rstrip("/"), + path="/auth-files", + method="GET", + headers=headers, + timeout=timeout, + insecure=False, + ) + match = cliproxy_sweeper.build_candidates( + analysis=analysis, + auth_files_obj=auth_files_obj, + allow_name_fallback=allow_name_fallback, + ) + + candidates = match.get("candidates", []) + deleted = 0 + failed = 0 + if apply_mode: + total = len(candidates) + for i, c in enumerate(candidates, 1): + db.update_task( + task_id, + message=f"{source}: 删除 {i}/{total} …", + done=i, + ) + file_name = str(c.get("file_name", "")) + encoded_name = urllib.parse.quote(file_name, safe="") + code, _ = cliproxy_sweeper.http_request_with_retry( + base_url=base.rstrip("/"), + path=f"/auth-files?name={encoded_name}", + method="DELETE", + headers=headers, + timeout=timeout, + insecure=False, + ) + if 200 <= code < 300: + deleted += 1 + else: + failed += 1 + + msg = ( + f"{source}: 阈值={threshold} 命中={len(candidates)} " + f"已删={deleted} 删除失败={failed} 模式={run_mode}" + ) + rtlog().info("[sweeper#%s] %s", task_id, msg) + if finalize_task: + db.update_task(task_id, status="done", message=msg, done=1) + return { + "threshold": threshold, + "matched": len(candidates), + "deleted": deleted, + "failed": failed, + "mode": run_mode, + "message": msg, + } + + +def _start_sweeper_job(source: str) -> tuple[bool, Optional[int], str]: + # 与巡检共用锁,避免并发删除同一批 auth-files。 + if not INSPECT_LOCK.acquire(blocking=False): + return False, None, "busy" + tid = db.create_task("cliproxy_sweeper", "queued", f"{source}:排队…", None, 1) + + def bg() -> None: + try: + _run_cliproxy_sweeper_worker(tid, source) + except Exception as e: + rtlog().exception("[sweeper#%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 保证同时最多一条。 @@ -773,7 +936,28 @@ def api_task_inspect_now(): { "ok": True, "task_id": tid, - "message": "已排队巡检;完成后若仍有缺口将自动批量补号(每批上限见 max_auto_register_per_tick)", + "message": "已排队巡检(先按 /usage 阈值清理,再探测删失效);完成后若仍有缺口将自动批量补号", + } + ) + + +@app.post("/api/tasks/sweep-failed-now") +@require_login +def api_task_sweep_failed_now(): + if not db.cliproxy_inspect_configured(): + return jsonify( + { + "error": "未配置 Cliproxy 管理地址/密钥,请在「配置编辑」填写 cliproxy_management_base 与密钥", + } + ), 400 + started, tid, reason = _start_sweeper_job("手动失效清理") + if reason == "busy": + return jsonify({"error": "已有巡检/清理任务在执行,请稍后再试"}), 409 + return jsonify( + { + "ok": True, + "task_id": tid, + "message": "已排队失效清理任务(基于 /usage 连续失败阈值)", } ) diff --git a/maintain/db.py b/maintain/db.py index e5808b1..1e1f196 100644 --- a/maintain/db.py +++ b/maintain/db.py @@ -117,6 +117,9 @@ def init_db() -> None: "cliproxy_management_base": "", "cliproxy_management_key": "", "cliproxy_probe_timeout_sec": "30", + "cliproxy_sweeper_threshold": "3", + "cliproxy_sweeper_run_mode": "delete", + "cliproxy_sweeper_allow_name_fallback": "1", # 成功后 JSON 若在 Cliproxy auth 目录,填绝对路径;留空则用项目 accounts/oauth "codex_stats_oauth_dir": "", "inspect_probe_valid_json": "", diff --git a/maintain/templates/dashboard.html b/maintain/templates/dashboard.html index b7aea95..a4e60de 100644 --- a/maintain/templates/dashboard.html +++ b/maintain/templates/dashboard.html @@ -126,6 +126,7 @@

手动巡检

+
@@ -196,6 +197,14 @@ + + + + +
@@ -297,6 +306,9 @@ $('cfgStatsOauthDir').value = st.codex_stats_oauth_dir || ''; $('cfgClipBase').value = st.cliproxy_management_base || ''; $('cfgClipTimeout').value = st.cliproxy_probe_timeout_sec || '30'; + $('cfgSweepThreshold').value = st.cliproxy_sweeper_threshold || '3'; + $('cfgSweepMode').value = st.cliproxy_sweeper_run_mode || 'delete'; + $('cfgSweepNameFallback').checked = (st.cliproxy_sweeper_allow_name_fallback || '1') === '1'; $('cfgClipKey').value = ''; $('cfgClipKey').placeholder = st.cliproxy_management_key_set ? '已保存密钥(留空不改)' : '必填'; } @@ -472,6 +484,9 @@ codex_stats_oauth_dir: $('cfgStatsOauthDir').value.trim(), cliproxy_management_base: $('cfgClipBase').value.trim(), cliproxy_probe_timeout_sec: $('cfgClipTimeout').value, + cliproxy_sweeper_threshold: $('cfgSweepThreshold').value, + cliproxy_sweeper_run_mode: $('cfgSweepMode').value, + cliproxy_sweeper_allow_name_fallback: $('cfgSweepNameFallback').checked ? '1' : '0', }; const k = $('cfgClipKey').value; if (k) body.cliproxy_management_key = k; @@ -489,6 +504,16 @@ toast(j.message || '已排队'); refreshData(); }; + $('btnSweepFailedNow').onclick = async () => { + const r = await api('/api/tasks/sweep-failed-now', { method: 'POST', body: '{}' }); + if (!r) return; + const j = await r.json().catch(() => ({})); + if (r.status === 400) { toast(j.error || '配置不全'); return; } + if (r.status === 409) { toast(j.error || '忙'); return; } + if (!r.ok) { toast(j.error || '失败'); return; } + toast(j.message || '清理任务已排队'); + refreshData(); + }; $('btnManual').onclick = async () => { const r = await api('/api/tasks/manual', { method: 'POST', body: JSON.stringify({ cpa_id: parseInt($('manualCpa').value, 10), diff --git a/register.py b/register.py index f17487b..76d51c2 100644 --- a/register.py +++ b/register.py @@ -51,7 +51,7 @@ 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" + impersonate: str = "chrome" @dataclass @@ -69,13 +69,33 @@ class AccountRegister: self.config = config def _log(self, step: str, status: str, message: str = ""): - print(f"[register][{step}] {status}: {message}") + # 某些托管/守护进程环境下 stdout 可能瞬时不可写(Errno 5), + # 日志输出失败不应中断注册主流程。 + try: + print(f"[register][{step}] {status}: {message}") + except OSError: + pass 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 + candidates = [self.config.impersonate, "chrome", "chrome120"] + seen = set() + last_error: Optional[Exception] = None + for imp in candidates: + if not imp or imp in seen: + continue + seen.add(imp) + try: + session = cffi_requests.Session(impersonate=imp) + if self.config.proxy: + session.proxies = {"http": self.config.proxy, "https": self.config.proxy} + if imp != self.config.impersonate: + self._log("session", "warn", f"impersonate 回退: {self.config.impersonate} -> {imp}") + return session + except Exception as e: + last_error = e + continue + # 理论上不会到这里;若都失败,抛最后一个异常便于上层定位。 + raise last_error if last_error is not None else RuntimeError("session init failed") def _api_headers(self, referer: str = "https://auth.openai.com/create-account") -> dict: return { diff --git a/requirements.txt b/requirements.txt index acb4363..f54dc8b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,5 @@ curl_cffi>=0.7.0 requests>=2.31.0 flask>=3.0.0 -apscheduler>=3.10.0 \ No newline at end of file +apscheduler>=3.10.0 +playwright>=1.40.0 \ No newline at end of file diff --git a/run.py b/run.py index c95e6cf..bb1c0f3 100644 --- a/run.py +++ b/run.py @@ -21,7 +21,7 @@ from datetime import datetime, timezone, timedelta THREADS = 1 # 并行线程数 (1 = 单线程顺序执行) COUNT = 50 # 注册账号数量 SKIP_OAUTH = False # True = 只注册不做 OAuth 获取 token -PROXY = "http://127.0.0.1:7897" # 代理地址 +PROXY = "" # 代理地址 # ══════════════════════════════════════════════════════════