Kaynağa Gözat

refactor: migrate cloud config fetching to VSCloudApi and unify plugin error types and utilities

jerry 2 ay önce
ebeveyn
işleme
5c27acff2a

+ 388 - 0
README.md

@@ -0,0 +1,388 @@
+# Coordinate 签证预约自动化系统
+
+Coordinate 是一个高并发、插件化的多国签证预约与监控自动化系统。支持通过声明式状态机与拟人化浏览器自动化(DrissionPage / curl_cffi / 大模型视觉识别 / CapSolver 等)完成反爬穿透、会话建立、号源实时监控与自动占位预约。
+
+---
+
+## 目录
+- [插件测试工具 (PluginTester) 全指南](#插件测试工具-plugintester-全指南)
+  - [7 步标准化测试流水线](#7-步标准化测试流水线)
+  - [CLI 命令行常用方法与示例](#cli-命令行常用方法与示例)
+  - [命令行全量参数速查表](#命令行全量参数速查表)
+  - [测试配置文件说明 (`config/test_conf.json`)](#测试配置文件说明-configtest_confjson)
+  - [诊断报告解读与排错](#诊断报告解读与排错)
+  - [Python 代码内嵌调用方式](#python-代码内嵌调用方式)
+- [系统架构与模块组成](#系统架构与模块组成)
+- [已支持插件列表](#已支持插件列表)
+- [通用大模型验证码识别器 (CaptchaBreaker)](#通用大模型验证码识别器-captchabreaker)
+- [项目目录结构](#项目目录结构)
+- [环境搭建与快速开始](#环境搭建与快速开始)
+- [单元测试](#单元测试)
+
+---
+
+## 插件测试工具 (PluginTester) 全指南
+
+Coordinate 提供了全功能的插件测试脚手架 [`tools/plugin_tester.py`](file:///Users/hujiarui/workspace/coordinate/tools/plugin_tester.py),用于在不启动分布式任务调度的情况下,对任意签证插件进行孤立、可复现的完整生命周期测试、反爬连通性验证与号源查询调试。
+
+### 7 步标准化测试流水线
+
+`PluginTester` 按照以下生命周期顺序执行契约测试:
+
+```mermaid
+graph LR
+    Step1[1. test_init<br>插件实例化与配置注入] --> Step2[2. test_create_session<br>反爬穿透与会话建立]
+    Step2 --> Step3[3. test_health_check<br>会话心跳与保活验证]
+    Step3 --> Step4[4. test_status<br>运行时指标与健康度]
+    Step4 --> Step5[5. test_query<br>可预约时段与日历抓取]
+    Step5 --> Step6[6. test_book<br>锁定号源与提交 - 可选]
+    Step6 --> Step7[7. test_cleanup<br>浏览器销毁与临时文件清理]
+```
+
+1. **`test_init`**: 通过插件工厂动态加载目标插件,验证其继承自 `IVSPlg`,并注入 `VSPlgConfig` 与日志记录器。
+2. **`test_create_session`**: 启动指纹隔离的 Chromium 实例,通过反爬盾挑战(如 Cloudflare Turnstile、AWS WAF、KBA 密保回答),完成登录获取会话凭据(Cookie / JWT / SessionId)。
+3. **`test_health_check`**: 触发心跳检查(`health_check()`),验证会话存活状态与页面响应能力。
+4. **`test_status`**: 抓取插件的运行时指标对象 `PluginStatus`(含会话存活时长、关联代理、账号标识、URL 状态等)。
+5. **`test_query`**: 导航至号源日历页面,结合 OCR/大模型识别输入验证码,查询预约号源并输出规范化 `VSQueryResult`(`AvailabilityStatus`、最早已开放日期 `earliest_date` 等)。
+6. **`test_book`** *(可选)*: 当附加 `--book` 参数时执行,根据 `user_inputs` 填报申请人资料、上传护照文档、选择时间槽并锁定预约。
+7. **`test_cleanup`**: 验证 `cleanup()` 函数能够安全退出浏览器进程,并彻底清除隔离工作区数据(`data/temp_browser_data/`)。
+
+---
+
+### CLI 命令行常用方法与示例
+
+#### 1. 运行单个插件的查询流水线 (推荐最常用)
+```bash
+# 测试波兰 e-konsulat 插件
+python3 tools/plugin_tester.py --plugin pol_plugin
+
+# 测试 VFS 全球签证插件
+python3 tools/plugin_tester.py --plugin vfs_plugin
+
+# 也支持直接使用位置参数
+python3 tools/plugin_tester.py tls_plugin
+```
+
+#### 2. 发生错误时保留浏览器现场 (`--keep-on-error` 调试利器)
+如果插件在挑战反爬、找选择器或解析日历时发生异常,默认会自动销毁浏览器。添加 `--keep-on-error` 参数后,**测试器将保留浏览器窗口和 DevTools 现场不退出**,方便人工在页面上审查元素、排查原因:
+```bash
+python3 tools/plugin_tester.py --plugin pol_plugin --keep-on-error
+python3 tools/plugin_tester.py --plugin vfs_plugin --keep-on-error
+```
+
+#### 3. 测试结束保留浏览器窗口 (`--no-cleanup`)
+用于在测试完全成功后仍想人工查看最终页面状态的场景:
+```bash
+python3 tools/plugin_tester.py --plugin vfs_plugin --no-cleanup
+```
+
+#### 4. 包含预约提交流程测试 (`--book`)
+默认测试只会执行到 `query` 查询步骤,若需验证选时间与提交申请逻辑,追加 `--book`:
+```bash
+python3 tools/plugin_tester.py --plugin vfs_plugin --book
+```
+
+#### 5. 快速检查插件工厂配置与实例化 (`--only-init`)
+毫秒级校验插件能否被工厂识别并成功装载配置,不启动真实浏览器:
+```bash
+# 检查单个插件
+python3 tools/plugin_tester.py --plugin vfs_plugin --only-init
+
+# 检查所有插件
+python3 tools/plugin_tester.py --plugin all --only-init
+```
+
+#### 6. 命令行即时覆盖账号密码与代理
+无需修改配置文件,直接通过命令行临时传入特定的账号或独立代理:
+```bash
+python3 tools/plugin_tester.py --plugin pol_plugin \
+  -u "myuser@example.com" \
+  -pwd "MySecretPass123" \
+  --proxy "http://127.0.0.1:7890"
+```
+
+#### 7. 指定特定配置文件
+默认自动加载 `config/test_conf.json`,可通过 `-c` 指定自定义配置文件:
+```bash
+python3 tools/plugin_tester.py --plugin vfs_plugin -c "config/staging_conf.json"
+```
+
+#### 8. 全量批量回归测试
+```bash
+python3 tools/plugin_tester.py --plugin all
+```
+
+---
+
+### 命令行全量参数速查表
+
+| 参数 / 简写 | 类型 | 默认值 | 详细说明 |
+| :--- | :--- | :--- | :--- |
+| `plugin_pos` / `--plugin` / `-p` | string | `None` | 目标插件标识(如 `vfs_plugin`、`pol_plugin`、`tls_plugin` 或 `'all'`) |
+| `--keep-on-error` | flag | `False` | **出错时保留浏览器不退出**,极大便利人工复现与审查页面错误 |
+| `--no-cleanup` | flag | `False` | 测试结束后不自动执行 `cleanup()`,保持浏览器打开 |
+| `--book` | flag | `False` | 是否执行预约提交流程(`test_book`),默认仅执行到查询步骤 |
+| `--only-init` | flag | `False` | 仅验证插件类装载与配置注入后立即退出 |
+| `--config` / `-c` | string | `config/test_conf.json` | 指定自定义 JSON 测试配置文件路径 |
+| `--group` / `-g` | string | `None` | 覆盖插件分组标识 `group_id` |
+| `--user` / `-u` | string | `None` | 覆盖测试账号用户名 / 邮箱 |
+| `--password` / `-pwd` | string | `None` | 覆盖测试账号密码 |
+| `--proxy` | string | `None` | 覆盖代理网络(格式如 `http://user:pass@ip:port`) |
+
+---
+
+### 测试配置文件说明 (`config/test_conf.json`)
+
+配置文件集中管理各签证中心的站点参数、测试账号及申请人信息:
+
+```json
+{
+  "default": {
+    "account": {
+      "username": "tester@example.com",
+      "password": "SamplePassword123!"
+    },
+    "proxy": {
+      "proto": "http",
+      "ip": "127.0.0.1",
+      "port": 7890,
+      "username": "",
+      "password": ""
+    },
+    "session_max_life": 3600,
+    "debug": true
+  },
+  "plugins": {
+    "vfs_plugin": {
+      "group_id": "vfs.cn.at",
+      "account": {
+        "username": "cn_at_wfvl5y@text.skin",
+        "password": "SamplePassword$"
+      },
+      "appointment_types": [
+        {
+          "city": "Beijing",
+          "country": "Austria",
+          "visa_type": "Tourist",
+          "routing_key": "slot.bjs.at.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "language": "en",
+        "country_code": "chn",
+        "mission_code": "aut",
+        "apt_configs": {
+          "slot.bjs.at.tourist": {
+            "vac_code": "Bei",
+            "category_code": "VTC",
+            "subcategory_code": "TR"
+          }
+        }
+      },
+      "user_inputs": {
+        "first_name": "San",
+        "last_name": "Zhang",
+        "email": "applicant@example.com",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "pol_plugin": {
+      "group_id": "pol.dublin",
+      "free_config": {
+        "query_url": "https://secure.e-konsulat.gov.pl/placowki/151/wiza-schengen/wizyty/weryfikacja-obrazkowa",
+        "service_type": "Wiza Schengen",
+        "location": "Dublin"
+      }
+    }
+  }
+}
+```
+
+---
+
+### 诊断报告解读与排错
+
+每次测试结束时,控制台将输出格式化的执行时间与状态诊断表格:
+
+```text
+=================================================================
+📊 [Test Report Summary] Plugin: pol_plugin (Group: pol.dublin)
+=================================================================
+Step Name            | Status     | Duration (s) | Details
+-----------------------------------------------------------------
+test_init            | ✅ PASS     | 0.49         | {'name': 'pol_plugin', 'version': '1.0.0'}
+test_create_session  | ✅ PASS     | 7.09         | 
+test_health_check    | ✅ PASS     | 0.00         | True
+test_status          | ✅ PASS     | 0.00         | PluginStatus(instance_id='a7418055', is_healthy=True...)
+test_query           | ✅ PASS     | 26.55        | success=False, status=AvailabilityStatus.NoneAvailable
+test_status          | ✅ PASS     | 0.00         | PluginStatus(instance_id='a7418055', is_healthy=True...)
+test_cleanup         | ✅ PASS     | 1.29         | 
+-----------------------------------------------------------------
+Overall Result: 🎉 ALL TESTS PASSED | Total Time: 35.42s
+=================================================================
+```
+
+- **PASS**: 步骤完全符合接口契约并正常完成;
+- **FAIL**: 步骤抛出异常或返回结果未达到断言要求,日志中会打印完整 Traceback;
+- **排错建议**: 遇到失败时,第一时间使用 `--keep-on-error` 重跑,查看浏览器所停留在的网页界面(例如是否被 Cloudflare 拦截、验证码识别错误提示、或是账号被锁定)。
+
+---
+
+### Python 代码内嵌调用方式
+
+`PluginTester` 也可以作为 Python 库直接被你的脚本或集成测试脚本导入:
+
+```python
+from tools.plugin_tester import PluginTester
+
+# 从配置文件自动加载并运行
+tester = PluginTester.from_json_config(
+    plugin_name="pol_plugin",
+    config_path="config/test_conf.json"
+)
+all_passed = tester.run_pipeline(test_book=False, keep_on_error=True)
+
+# 动态自定义配置测试
+custom_config = PluginTester.create_default_config(
+    username="custom_user@example.com",
+    password="Password123!",
+    proxy_url="http://127.0.0.1:7890"
+)
+tester = PluginTester(plugin_name="vfs_plugin", group_id="vfs.custom", config=custom_config)
+tester.test_init()
+tester.test_create_session()
+query_result = tester.test_query()
+print("号源结果:", query_result.availability_status)
+tester.test_cleanup()
+```
+
+---
+
+## 系统架构与模块组成
+
+系统分为 **巡检层 (Sentinel)**、**预约层 (Booker)** 与 **插件层 (Plugins)**:
+
+- **Sentinel (`sentinel.py`)**: 高频轮询任务,负责维护池化会话并进行号源日历巡检。一旦发现有效号源,立刻写入号源队列并触发通知。
+- **Booker (`booker.py`)**: 专职预约执行层,监听抢号任务队列,接收来自 Sentinel 的实时空闲 Slot,迅速填报申请人资料并锁定预约。
+- **Standalone (`standalone.py`)**: 独立模式,集查询、监控、预约于一体的单机作业进程。
+- **Flow Engine (`utils/flow_engine.py`)**: 声明式状态机,以规则装饰器驱动多步骤拟人化交互(如动态表单跳转、错误弹窗拦截、Turnstile 盾穿透)。
+
+---
+
+## 已支持插件列表
+
+| 插件标识 (`plugin_name`) | 签证中心 / 平台 | 核心技术方案 | 验证码与反爬对策 |
+| :--- | :--- | :--- | :--- |
+| `vfs_plugin` | VFS Global 全球签证 | DrissionPage + JS Fetch 注入、JWT 会话保持 | Cloudflare Turnstile 自动穿透、大模型 OTP 识别 |
+| `pol_plugin` | 波兰 e-konsulat | DrissionPage 浏览器自动化、日历下拉遍历 | **通用大模型验证码识别器 (`CaptchaBreaker`)** |
+| `tls_plugin` | TLSContact 欧洲多国 | 声明式 Flow 状态机、贝塞尔拟人化鼠标轨迹 | Cloudflare 5秒盾旁路、动态 Cookie 同步 |
+| `usa_plugin` | 美签 USVisaScheduling | 声明式 Flow 状态机、网络封包拦截、日历漫游 | KBA 密保问答自动补全、防并发锁控制 |
+| `ita_plugin` | 意大利 Prenot@Mi | 声明式 Flow 状态机、多领区调度 | PingID 多因素认证、OTP 自动读取 |
+| `bel_plugin` | 比利时 Visa On Web | 新标签页日历提取与会话绑定 | CapSolver hCaptcha 破解 |
+| `de_plugin` | 德国 Visametric | 动态 CSRF 提取、Stripe 支付链接捕获 | Visametric 专用字符识别模型 |
+| `bls_plugin` | 西班牙 BLS | 动态表单解析、护照图片 Multipart 提交 | 字符算术验证码识别 |
+| `grc_plugin` | 希腊 GVCW | 复杂表单步进控制与材料校验 | 字符验证码识别与会话保活 |
+| `prt_plugin` | 葡萄牙签证中心 | 流程步进与预约日历提取 | 基础反爬挑战绕过 |
+
+---
+
+## 通用大模型验证码识别器 (CaptchaBreaker)
+
+坐标库中提供了全新的通用大模型视觉识别模块 [`toolkit/captcha_breaker.py`](file:///Users/hujiarui/workspace/coordinate/toolkit/captcha_breaker.py),支持任意基于 OpenAI 兼容协议的多模态模型(如通义千问 Qwen-VL、GPT-4o、DeepSeek-VL、OneAPI 代理等)。
+
+### 1. 特性
+- **多输入格式归一化**:自动兼容本地文件路径、原始二进制字节(`bytes`)、`io.BytesIO`、Base64 字符串以及标准 Data URL。
+- **动态清理**:自动剥离大模型返回的 Markdown 代码块标记(```` ``` ````)与常见前后引号。
+- **即时配置感知**:在模块顶部静态载入配置,缺省时自动回退读取环境变量;未配置 API Key 访问客户端时抛出结构化 `CaptchaBreakerError`。
+
+### 2. 配置方式 ([configure.py](file:///Users/hujiarui/workspace/coordinate/configure.py))
+```python
+CAPTCHA_LLM_CONFIG = {
+    "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
+    "api_key": "sk-your-api-key",
+    "model": "qwen-vl-max", # 或 gpt-4o, deepseek-vl 等
+    "timeout": 30.0,
+}
+```
+*注:若 `CAPTCHA_LLM_CONFIG = None`,系统将自动读取环境变量 `CAPTCHA_LLM_API_KEY`、`CAPTCHA_LLM_BASE_URL`、`CAPTCHA_LLM_MODEL`。*
+
+### 3. 代码中使用
+```python
+from toolkit.captcha_breaker import CaptchaBreaker
+
+breaker = CaptchaBreaker()
+
+# 支持直接传入图片字节、Base64 或文件路径
+captcha_code = breaker.break_captcha("data:image/png;base64,iVBORw0KGgo...")
+
+# 也支持自定义业务场景的 Prompt(例如 VFS 指向型验证码)
+custom_prompt = "图片中有多组验证码,其中OTP箭头指向的验证码为真,其余为假。只输出真实验证码的内容。"
+otp_code = breaker.break_captcha(image_data, prompt=custom_prompt)
+```
+
+---
+
+## 项目目录结构
+
+```text
+coordinate/
+├── config/                  # 运行时与测试配置目录
+│   ├── test_conf.json       # PluginTester 全插件测试参数集
+│   ├── config_booker.json   # 抢号预约进程配置
+│   └── config_sentinel.json # 巡检监控进程配置
+├── configure.py             # 核心系统配置(Redis、大模型 API、Mihomo 等)
+├── plugins/                 # 签证中心业务插件 (实现 IVSPlg 规范)
+│   ├── vfs_plugin.py        # VFS 插件
+│   ├── pol_plugin.py        # 波兰插件 (已接入 CaptchaBreaker)
+│   ├── tls_plugin.py        # TLS 插件
+│   └── ...
+├── toolkit/                 # 通用底层工具库
+│   ├── captcha_breaker.py   # 通用多模态大模型验证码识别器
+│   ├── mihomo_tunnel.py     # 智能代理隧道与节点管理
+│   ├── backoff.py           # 指数退避重试器
+│   └── vs_cloud_api.py      # 云端邮箱验证码与配置同步
+├── tools/                   # 运维与开发工具
+│   └── plugin_tester.py     # 插件标准生命周期测试器
+├── utils/                   # 辅助机制 (状态机、反爬绕过、指纹配置)
+│   ├── flow_engine.py       # 声明式状态机引擎
+│   ├── plugin_utils.py      # 浏览器初始化与环境清理
+│   └── cloudflare_bypass_for_scraping.py # Cloudflare 穿透工具
+└── test/                    # 单元测试与测试用例集
+    └── test_captcha_breaker.py
+```
+
+---
+
+## 环境搭建与快速开始
+
+### 1. 安装依赖
+建议使用 Python 3.10+ 虚拟环境:
+```bash
+python3 -m venv venv
+source venv/bin/activate
+pip install -r requirements.txt
+```
+
+### 2. 检查浏览器支持
+系统基于 DrissionPage 驱动 Chromium 浏览器。推荐系统预装 Google Chrome 或 Ungoogled Chromium。若需要指定路径,可在 `configure.py` 中配置 `CHROME_PATH`。
+
+### 3. 执行插件自检
+```bash
+python3 tools/plugin_tester.py --plugin pol_plugin
+```
+
+---
+
+## 单元测试
+
+运行项目内置的自动化单元测试集:
+
+```bash
+# 运行 CaptchaBreaker 通用大模型识别测试套件 (13 项测试)
+./venv/bin/python -m unittest test/test_captcha_breaker.py
+
+# 发现并运行全部测试
+./venv/bin/python -m unittest discover -s test -p "test_*.py"
+```

Dosya farkı çok büyük olduğundan ihmal edildi
+ 428 - 278
config/config_booker.json


Dosya farkı çok büyük olduğundan ihmal edildi
+ 461 - 245
config/config_sentinel.json


+ 95 - 95
config/config_standalone.json

@@ -1,4 +1,99 @@
 [
 [
+  {
+    "id": 3,
+    "node_id": "yecaoyun",
+    "order_id": null,
+    "identifier": "vfs",
+    "enable": 0,
+    "debug": 1,
+    "plugin_config": {
+      "lib_path": "plugins",
+      "plugin_bin": "vfs_plugin.py",
+      "plugin_name": "vfs_plugin",
+      "plugin_proto": "IVSPlg"
+    },
+    "account": {
+      "password": "Visafly@111",
+      "username": "italyvisa888@text.skin"
+    },
+    "proxy_pool": [
+      "proxy-cheap"
+    ],
+    "query_wait": {
+      "mode": "Random",
+      "fixed_wait": 10,
+      "random_max": 180,
+      "random_min": 120
+    },
+    "login_interval": 7200,
+    "session_max_life": 1800,
+    "active_time_start": "00:00",
+    "active_time_end": "23:30",
+    "appointment_types": [
+      {
+        "city": "Changsha",
+        "weight": 0,
+        "country": "Italy",
+        "visa_type": "Tourist",
+        "routing_key": "slot.csx.it.tourist"
+      },
+      {
+        "city": "Beijing",
+        "weight": 10,
+        "country": "Italy",
+        "visa_type": "Tourist",
+        "routing_key": "slot.bjs.it.tourist"
+      }
+    ],
+    "user_preferences": {
+      "email": "italyvisa666@text.skin",
+      "phone": "019074224604",
+      "gender": "female",
+      "birthday": "1997-09-09",
+      "last_name": "ZHAO",
+      "first_name": "LINJIE",
+      "nationality": "China",
+      "passport_no": "EE4571001",
+      "expected_end_date": "2026-07-03",
+      "passport_image_url": "data/passport.jpg",
+      "phone_country_code": "86",
+      "expected_start_date": "2026-06-12",
+      "passport_expiry_date": "2028-10-08",
+      "social_media_account": "13370148298"
+    },
+    "free_config": {
+      "language": "en",
+      "apt_configs": {
+        "slot.bjs.it.tourist": {
+          "address": "East 101, Floor B1, Block C, Guanghua Lu SOHO II, No. 9 Guanghua Lu, Chaoyang District",
+          "vac_code": "BJII",
+          "center_name": "Italy Visa Application Center, Beijing",
+          "category_code": "Beijing Italy",
+          "category_name": "Beijing Italy",
+          "subcategory_code": "BJ Italy Standard",
+          "subcategory_name": "Standard Beijing Italy"
+        },
+        "slot.csx.it.tourist": {
+          "address": "1F, Changsha Rongchuang Steigenberger Hotel, No. 3-9, Xueyuan Road, Changsha County, Changsha City",
+          "vac_code": "CGA",
+          "center_name": "Italy Visa Application Center, Changsha",
+          "category_code": "Schengen Visa",
+          "category_name": "SchengenVisa",
+          "subcategory_code": "Schengen ",
+          "subcategory_name": "C visa / Schengen visa"
+        }
+      },
+      "country_code": "chn",
+      "country_name": "China",
+      "culture_code": "en-US",
+      "mission_code": "ita",
+      "mission_name": "Italy"
+    },
+    "version": 3,
+    "updated_by": "769858626@qq.com",
+    "created_at": "2026-08-23T15:08:28",
+    "updated_at": "2026-08-24T13:50:12"
+  },
   {
   {
     "id": 1,
     "id": 1,
     "node_id": "yecaoyun",
     "node_id": "yecaoyun",
@@ -125,100 +220,5 @@
     "updated_by": "769858626@qq.com",
     "updated_by": "769858626@qq.com",
     "created_at": "2026-08-23T15:08:27",
     "created_at": "2026-08-23T15:08:27",
     "updated_at": "2026-08-23T16:16:36"
     "updated_at": "2026-08-23T16:16:36"
-  },
-  {
-    "id": 3,
-    "node_id": "yecaoyun",
-    "order_id": null,
-    "identifier": "vfs",
-    "enable": 1,
-    "debug": 1,
-    "plugin_config": {
-      "lib_path": "plugins",
-      "plugin_bin": "vfs_plugin.py",
-      "plugin_name": "vfs_plugin",
-      "plugin_proto": "IVSPlg"
-    },
-    "account": {
-      "password": "Visafly@111",
-      "username": "italyvisa888@text.skin"
-    },
-    "proxy_pool": [
-      "proxy-cheap"
-    ],
-    "query_wait": {
-      "mode": "Random",
-      "fixed_wait": 10,
-      "random_max": 180,
-      "random_min": 120
-    },
-    "login_interval": 7200,
-    "session_max_life": 1800,
-    "active_time_start": "00:00",
-    "active_time_end": "23:30",
-    "appointment_types": [
-      {
-        "city": "Changsha",
-        "weight": 0,
-        "country": "Italy",
-        "visa_type": "Tourist",
-        "routing_key": "slot.csx.it.tourist"
-      },
-      {
-        "city": "Beijing",
-        "weight": 10,
-        "country": "Italy",
-        "visa_type": "Tourist",
-        "routing_key": "slot.bjs.it.tourist"
-      }
-    ],
-    "user_preferences": {
-      "email": "italyvisa666@text.skin",
-      "phone": "019074224604",
-      "gender": "female",
-      "birthday": "1997-09-09",
-      "last_name": "ZHAO",
-      "first_name": "LINJIE",
-      "nationality": "China",
-      "passport_no": "EE4571001",
-      "expected_end_date": "2026-07-03",
-      "passport_image_url": "data/passport.jpg",
-      "phone_country_code": "86",
-      "expected_start_date": "2026-06-12",
-      "passport_expiry_date": "2028-10-08",
-      "social_media_account": "13370148298"
-    },
-    "free_config": {
-      "language": "en",
-      "apt_configs": {
-        "slot.bjs.it.tourist": {
-          "address": "East 101, Floor B1, Block C, Guanghua Lu SOHO II, No. 9 Guanghua Lu, Chaoyang District",
-          "vac_code": "BJII",
-          "center_name": "Italy Visa Application Center, Beijing",
-          "category_code": "Beijing Italy",
-          "category_name": "Beijing Italy",
-          "subcategory_code": "BJ Italy Standard",
-          "subcategory_name": "Standard Beijing Italy"
-        },
-        "slot.csx.it.tourist": {
-          "address": "1F, Changsha Rongchuang Steigenberger Hotel, No. 3-9, Xueyuan Road, Changsha County, Changsha City",
-          "vac_code": "CGA",
-          "center_name": "Italy Visa Application Center, Changsha",
-          "category_code": "Schengen Visa",
-          "category_name": "SchengenVisa",
-          "subcategory_code": "Schengen ",
-          "subcategory_name": "C visa / Schengen visa"
-        }
-      },
-      "country_code": "chn",
-      "country_name": "China",
-      "culture_code": "en-US",
-      "mission_code": "ita",
-      "mission_name": "Italy"
-    },
-    "version": 2,
-    "updated_by": "769858626@qq.com",
-    "created_at": "2026-08-23T15:08:28",
-    "updated_at": "2026-08-23T16:16:29"
   }
   }
 ]
 ]

+ 368 - 0
config/test_conf.json

@@ -0,0 +1,368 @@
+{
+  "default": {
+    "account": {
+      "username": "tester@example.com",
+      "password": "SamplePassword123!"
+    },
+    "proxy": {
+      "proto": "http",
+      "ip": "127.0.0.1",
+      "port": 7890,
+      "username": "",
+      "password": ""
+    },
+    "session_max_life": 3600,
+    "debug": true
+  },
+  "plugins": {
+    "vfs_plugin": {
+      "group_id": "vfs.cn.at",
+      "account": {
+        "username": "cn_at_wfvl5y@text.skin",
+        "password": "u3eSBxsYQFZ$"
+      },
+      "appointment_types": [
+        {
+          "city": "Beijing",
+          "country": "Austria",
+          "visa_type": "Tourist",
+          "routing_key": "slot.bjs.at.tourist",
+          "weight": 10
+        },
+        {
+          "city": "Shanghai",
+          "country": "Austria",
+          "visa_type": "Tourist",
+          "routing_key": "slot.sha.at.tourist",
+          "weight": 10
+        },
+        {
+          "city": "Guangzhou",
+          "country": "Austria",
+          "visa_type": "Tourist",
+          "routing_key": "slot.can.at.tourist",
+          "weight": 10
+        },
+        {
+          "city": "Shenzhen",
+          "country": "Austria",
+          "visa_type": "Tourist",
+          "routing_key": "slot.szx.at.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "language": "en",
+        "country_code": "chn",
+        "country_name": "China",
+        "culture_code": "en-US",
+        "mission_code": "aut",
+        "mission_name": "Austria",
+        "apt_configs": {
+          "slot.bjs.at.tourist": {
+            "address": "7/F, GAL Tower, No. 78, Pazhou Avenue, Haizhu District",
+            "vac_code": "Bei",
+            "center_name": "Austria Visa Application Center, Beijing",
+            "category_code": "VTC",
+            "category_name": "Visa Type C-Schengen",
+            "subcategory_code": "TR",
+            "subcategory_name": "Tourism (90 days)"
+          },
+          "slot.can.at.tourist": {
+            "address": "7/F, GAL Tower, No. 78, Pazhou Avenue, Haizhu District",
+            "vac_code": "Gua",
+            "center_name": "Austria Visa Application Center, Guangzhou",
+            "category_code": "VTC",
+            "category_name": "Visa Type C-Schengen",
+            "subcategory_code": "TR",
+            "subcategory_name": "Tourism (90 days)"
+          },
+          "slot.sha.at.tourist": {
+            "address": "3F, Jiushi Commercial Building, No. 213, Middle Sichuan Road, Huangpu District",
+            "vac_code": "Shaa",
+            "center_name": "Austria Visa Application Center, Shanghai",
+            "category_code": "TT",
+            "category_name": "Visa Type C - Tourism Visa",
+            "subcategory_code": "VTCT",
+            "subcategory_name": "Visa Type C - Tourism Visa"
+          },
+          "slot.szx.at.tourist": {
+            "address": "Unit 2303, Floor 23, East Tower, C Future City, No. 9285 Binhe Avenue, Futian District",
+            "vac_code": "ASSZA",
+            "center_name": "Austria Visa Application Center, Shenzhen",
+            "category_code": "VTC",
+            "category_name": "Visa Type C-Schengen",
+            "subcategory_code": "TR",
+            "subcategory_name": "Tourism (90 days)"
+          }
+        }
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "gender": "male",
+        "birthday": "1995-05-15",
+        "nationality": "China",
+        "passport_no": "EE1234567",
+        "passport_expiry_date": "2032-05-14",
+        "passport_image_url": "data/passport.jpg",
+        "phone_country_code": "86",
+        "phone": "13800138000",
+        "email": "applicant@example.com",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "tls_plugin": {
+      "group_id": "tls.cn.sha.fr",
+      "account": {
+        "username": "hujiarui8@text.skin",
+        "password": "Visafly@111"
+      },
+      "appointment_types": [
+        {
+          "city": "Shanghai",
+          "country": "France",
+          "visa_type": "Tourist",
+          "routing_key": "slot.sha.fr.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "tls_url": "https://visas-fr.tlscontact.com/en-us/country/cn/vac/cnSHA2fr",
+        "location": "Shanghai",
+        "capsolver_key": "CAP-5441DD341DD3CC2FAEF0BE6FE493EE9A",
+        "login_captcha": {
+          "task": "ReCaptchaV2TaskProxyLess",
+          "page_url": "https://i2-auth.visas-fr.tlscontact.com",
+          "site_key": "6LcDpXcfAAAAAM7wOEsF_38DNsL20tTvPTKxpyn0",
+          "solve_advance": false
+        }
+      },
+      "user_inputs": {
+        "support_pta": false,
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "usa_plugin": {
+      "group_id": "usa.guangzhou",
+      "account": {
+        "username": "xiaoyi1996",
+        "password": "Abc147258??"
+      },
+      "appointment_types": [
+        {
+          "city": "Guangzhou",
+          "country": "USA",
+          "visa_type": "Tourist",
+          "routing_key": "slot.can.us.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "usa_url": "https://www.usvisascheduling.com",
+        "location": "Guangzhou",
+        "applicant": "xiaoyi jin",
+        "security": {
+          "1": "1",
+          "2": "2",
+          "3": "3"
+        }
+      },
+      "user_inputs": {
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "bls_plugin": {
+      "group_id": "bls.ie.es",
+      "account": {
+        "username": "ireland_bls@example.com",
+        "password": "BlsPassword123!"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Spain",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.es.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "domain": "ireland.blsspainglobal.com",
+        "ocr_model": "data/ctc.pth",
+        "apt_configs": {
+          "slot.dub.es.tourist": {
+            "location": "Dublin",
+            "visa_type": "Schengen Visa/ Short Term Visa",
+            "jurisdiction": null,
+            "mission_code": "EMBASSY_DUBLIN",
+            "visa_subtype": "Tourist Visa",
+            "appointment_type": "Individual",
+            "appointment_category": "Normal"
+          }
+        }
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "gender": "male",
+        "birthday": "1995-05-15",
+        "nationality": "China",
+        "passport_no": "EE1234567",
+        "passport_expiry_date": "2032-05-14",
+        "passport_image_url": "data/passport.jpg",
+        "phone_country_code": "86",
+        "phone": "13800138000",
+        "email": "applicant@example.com",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "grc_plugin": {
+      "group_id": "greekemba.ie.gr",
+      "account": {
+        "username": "hujiarui8@gmail.com",
+        "password": "Visafly@111"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Greece",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.gr.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "website": "https://www.supersaas.com/schedule/GreekEmbassyInDublin/Visas"
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "passport_no": "EE1234567",
+        "phone_country_code": "353",
+        "phone": "088888888",
+        "address": "Dublin, Ireland",
+        "nationality": "Chinese",
+        "visa_reason": "tourism",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "pol_plugin": {
+      "group_id": "pol.dublin",
+      "account": {
+        "username": "pol_user@example.com",
+        "password": "PolPassword123!"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Poland",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.pl.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "location": "Dublin",
+        "query_url": "https://secure.e-konsulat.gov.pl/placowki/151/wiza-schengen/wizyty/weryfikacja-obrazkowa",
+        "service_type": "Wiza Schengen"
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "passport_no": "EE1234567",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "ita_plugin": {
+      "group_id": "ita.dublin",
+      "account": {
+        "username": "ita_user@example.com",
+        "password": "ItaPassword123!"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Italy",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.it.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "website": "https://prenotami.esteri.it/Home",
+        "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "email": "ita_user@example.com",
+        "citizen": "China",
+        "address": "Dublin",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "bel_plugin": {
+      "group_id": "bel.dublin",
+      "account": {
+        "username": "bel_user@example.com",
+        "password": "BelPassword123!"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Belgium",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.be.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "website": "https://visaonweb.diplomatie.be/en",
+        "capsolver_key": "CAP-5441DD341DD3CC2FAEF0BE6FE493EE9A"
+      },
+      "user_inputs": {
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "passport_no": "EE1234567",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    },
+    "de_plugin": {
+      "group_id": "de.dublin",
+      "account": {
+        "username": "de_user@example.com",
+        "password": "DePassword123!"
+      },
+      "appointment_types": [
+        {
+          "city": "Dublin",
+          "country": "Germany",
+          "visa_type": "Tourist",
+          "routing_key": "slot.dub.de.tourist",
+          "weight": 10
+        }
+      ],
+      "free_config": {
+        "base_url": "https://ie-appointment.visametric.com",
+        "consularid": 1
+      },
+      "user_inputs": {
+        "email": "applicant@example.com",
+        "first_name": "SAN",
+        "last_name": "ZHANG",
+        "passport_no": "EE1234567",
+        "expected_start_date": "2026-09-01",
+        "expected_end_date": "2026-11-30"
+      }
+    }
+  }
+}

+ 12 - 1
configure.py

@@ -1,3 +1,14 @@
+import os
+
+# 大模型通用验证码识别配置 (支持 Qwen、OpenAI、DeepSeek 等兼容接口)
+CAPTCHA_LLM_CONFIG = None
+CAPTCHA_LLM_CONFIG = {
+    "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
+    "api_key": "sk-893e895724c6403d81374e515ffaf427",
+    "model": "qwen-vl-max",
+    "timeout": 30.0,
+}
+
 # 测试任务,这里配置以后任务轮转函数直接使用这个任务
 # 测试任务,这里配置以后任务轮转函数直接使用这个任务
 REDIS_CFG = {
 REDIS_CFG = {
     "host": "text.skin",
     "host": "text.skin",
@@ -76,7 +87,7 @@ CHROME_PATH = None
 
 
 # Mohomo bin 的路径, 这个优先级最高,其次MIHOMO_BIN 的环境变量,最后系统默认值
 # Mohomo bin 的路径, 这个优先级最高,其次MIHOMO_BIN 的环境变量,最后系统默认值
 MIHOMO_BIN_PATH = None
 MIHOMO_BIN_PATH = None
-# MIHOMO_BIN_PATH = 'downloads/mihomo'
+MIHOMO_BIN_PATH = 'downloads/mihomo'
 
 
 
 
 # proxy tunnel 中继节点, 列表中随机选择
 # proxy tunnel 中继节点, 列表中随机选择

+ 70 - 192
plugins/bel_plugin.py

@@ -4,47 +4,36 @@ import random
 import re
 import re
 import os
 import os
 import uuid
 import uuid
-import shutil
-import base64
-import socket
-import requests
 from datetime import datetime
 from datetime import datetime
 from typing import List, Dict, Optional, Any, Callable
 from typing import List, Dict, Optional, Any, Callable
-from urllib.parse import urljoin, urlparse, urlencode
-
-# DrissionPage 核心
-from DrissionPage import ChromiumPage, ChromiumOptions
-
+from DrissionPage import ChromiumPage
 
 
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
-from toolkit.vs_cloud_api import VSCloudApi
-from toolkit.proxy_tunnel import ProxyTunnel
-
-
-class BrowserResponse:
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-    def json(self):
-        if self._json is None:
-            if not self.text: return {}
-            try: self._json = json.loads(self.text)
-            except: self._json = {}
-        return self._json
-
-def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
-    dt = datetime.strptime(data_str, date_str_format)
-    return dt.strftime("%Y-%m-%d")
+from vs_types import (
+    VSPlgConfig, 
+    AppointmentType, 
+    VSQueryResult, 
+    VSBookResult, 
+    AvailabilityStatus, 
+    TimeSlot, 
+    DateAvailability, 
+    NotFoundError, 
+    PermissionDeniedError, 
+    RateLimiteddError, 
+    SessionExpiredOrInvalidError, 
+    BizLogicError, 
+    PluginStatus, 
+    utc_now_str
+)
+from utils.plugin_utils import (
+    BrowserResponse,
+    init_chromium_options,
+    perform_browser_fetch,
+    filter_dates_in_range,
+    solve_capsolver_hcaptcha,
+    cleanup_browser_workspace
+)
 
 
-def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
-    if "@" not in email: raise ValueError(f"Invalid email: {email}")
-    local_part, _ = email.rsplit("@", 1)
-    return f"{local_part}@{new_domain}"
 
 
 class BelPlugin(IVSPlg):
 class BelPlugin(IVSPlg):
     """
     """
@@ -73,7 +62,7 @@ class BelPlugin(IVSPlg):
             
             
         self.applicants = []
         self.applicants = []
         
         
-        self.tunnel = None # 代理隧道
+        self.tunnel = None  # 代理隧道
         self.is_healthy = True
         self.is_healthy = True
         self.session_create_time: float = 0
         self.session_create_time: float = 0
     
     
@@ -82,9 +71,9 @@ class BelPlugin(IVSPlg):
         
         
     def _log(self, message): 
     def _log(self, message): 
         if self.logger:
         if self.logger:
-            self.logger(f'[BelPlugin] [{self.group_id}] {message}')
+            self.logger(f'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
         else:
-            print(f'[BelPlugin] [{self.group_id}] {message}')
+            print(f'[BelPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         
         
     def set_config(self, config: VSPlgConfig):
     def set_config(self, config: VSPlgConfig):
         self.config = config
         self.config = config
@@ -94,14 +83,12 @@ class BelPlugin(IVSPlg):
         pass
         pass
 
 
     def health_check(self) -> bool:
     def health_check(self) -> bool:
-        if not self.is_healthy:
-            return False
-        if not self.page:
+        if not self.is_healthy or not self.page:
             return False
             return False
         try:
         try:
             if not self.page.run_js("return 1;"):
             if not self.page.run_js("return 1;"):
                 return False
                 return False
-        except:
+        except Exception:
             return False
             return False
         if self.config.session_max_life > 0:
         if self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
             if time.time() - self.session_create_time > self.config.session_max_life:
@@ -111,40 +98,17 @@ class BelPlugin(IVSPlg):
 
 
     def create_session(self):
     def create_session(self):
         """
         """
-        创建会话:启动浏览器 -> 代理隧道 -> 提取 Captcha -> 本地识别 -> 提交 -> 获取 Context
+        创建会话:启动浏览器 -> 代理隧道 -> 登录 -> 获取申请人列表
         """
         """
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._log(f"Initializing Session (ID: {self.instance_id})...")
-        co = ChromiumOptions()
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0)); return s.getsockname()[1]
-        co.set_local_port(get_free_port())
-        
-        co.set_user_data_path(self.user_data_path)
-        chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-            
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Tunnel for {p.ip}...")
-                self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
-
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-gpu')
-        co.set_argument('--disable-dev-shm-usage') 
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         co.set_argument('--ignore-certificate-errors')
         co.set_argument('--ignore-certificate-errors')
 
 
         try:
         try:
@@ -166,7 +130,7 @@ class BelPlugin(IVSPlg):
             self.page.listen.stop()
             self.page.listen.stop()
             resp_body = packet.response.body
             resp_body = packet.response.body
             for dat in resp_body.get('data', []):
             for dat in resp_body.get('data', []):
-                if dat.get('St') == 'Submitted':
+               if dat.get('St') == 'Submitted':
                     applicant = {
                     applicant = {
                         "id": dat.get('Id'),
                         "id": dat.get('Id'),
                         "first_name": dat.get('FName'),
                         "first_name": dat.get('FName'),
@@ -182,7 +146,6 @@ class BelPlugin(IVSPlg):
             self._log("Session created successfully.")
             self._log("Session created successfully.")
         except Exception as e:
         except Exception as e:
             self._log(f"Session Create Failed: {e}")
             self._log(f"Session Create Failed: {e}")
-            time.sleep(3600)
             self.cleanup()
             self.cleanup()
             raise e
             raise e
 
 
@@ -296,126 +259,37 @@ class BelPlugin(IVSPlg):
         """
         """
         if not api_key:
         if not api_key:
             api_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
             api_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
-        if not api_key:
-            raise BizLogicError(message="Capsolver API key missing in free_config or environment")
-
-        payload = {
-            "clientKey": api_key,
-            "task": {
-                "type": "HCaptchaTaskProxyLess",
-                "websiteKey": site_key,
-                "websiteURL": site_url
-            }
-        }
-        
-        self._log("Submitting hCaptcha task to Capsolver...")
-        with requests.Session() as session:
-            res = session.post("https://api.capsolver.com/createTask", json=payload, timeout=20)
-            res_json = res.json()
-            if res_json.get("errorId", 0) != 0:
-                raise BizLogicError(message=f"Failed to create Capsolver task: {res.text}")
-
-            task_id = res_json.get("taskId")
-            if not task_id:
-                raise BizLogicError(message=f"No taskId returned from Capsolver: {res.text}")
-            
-            self._log(f"Waiting for hCaptcha solution (TaskId: {task_id})...")
-            start_time = time.time()
-            while time.time() - start_time < 120:
-                time.sleep(3)
-                res = session.post(
-                    "https://api.capsolver.com/getTaskResult",
-                    json={"clientKey": api_key, "taskId": task_id},
-                    timeout=20
-                )
-                result = res.json()
-                status = result.get("status")
-                if status == "ready":
-                    solution = result.get("solution", {})
-                    token = solution.get("gRecaptchaResponse") or solution.get("token") or solution.get("response")
-                    self._log("✅ hCaptcha solved successfully.")
-                    return token
-                if status == "failed":
-                    raise BizLogicError(message=f"hCaptcha solve failed: {res.text}")
-
-            raise BizLogicError(message="Capsolver task timed out (120s)")
+        return solve_capsolver_hcaptcha(
+            api_token=api_key,
+            site_key=site_key,
+            page_url=site_url,
+            proxy=self.config.proxy if self.config else None,
+            logger=self._log
+        )
 
 
-    def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
+    def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
         res = VSBookResult()
         return res
         return res
     
     
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
+        """在浏览器上下文中注入执行 Fetch"""
         if not self.page:
         if not self.page:
-            raise BizLogicError("Browser not init")
-        
-        req_url = url
-        if params:
-            sep = '&' if '?' in req_url else '?'
-            req_url += sep + urlencode(params)
-            
-        fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
-        
-        if json_data:
-            fetch_opts['body'] = json.dumps(json_data)
-            fetch_opts['headers']['Content-Type'] = 'application/json'
-        elif data:
-            if isinstance(data, dict):
-                fetch_opts['body'] = urlencode(data)
-                fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
-            else:
-                fetch_opts['body'] = data
-
-        js = f"""
-        return fetch("{req_url}", {json.dumps(fetch_opts)})
-        .then(async r => {{
-            const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
-            return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
-        }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-        """
-        
-        resp = BrowserResponse(self.page.run_js(js, timeout=60))
-        
-        if resp.status_code == 200:
-            return resp
-        elif resp.status_code == 403:
-            if "Just a moment" in resp.text and retry_count < 2:
-                self._log("Cloudflare 403. Refreshing...")
-                if self._refresh_firewall_session():
-                    return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
-            raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
-        elif resp.status_code == 429:
-            self.is_healthy = False
-            raise RateLimiteddError()
-        elif resp.status_code in [401, 419]:
-            self.is_healthy = False
-            raise SessionExpiredOrInvalidError()
-        else:
-            raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
-
-    def _filter_dates(self, dates, start, end):
-        if not start or not end: return dates
-        valid = []
-        s = datetime.strptime(start[:10], "%Y-%m-%d")
-        e = datetime.strptime(end[:10], "%Y-%m-%d")
-        for d in dates:
-            c = datetime.strptime(d, "%Y-%m-%d")
-            if s <= c <= e: valid.append(d)
-        random.shuffle(valid)
-        return valid
+            raise BizLogicError("Browser not initialized")
+        return perform_browser_fetch(
+            self.page, 
+            method=method, 
+            url=url, 
+            headers=headers, 
+            data=data, 
+            json_data=json_data, 
+            params=params
+        )
 
 
     def cleanup(self):
     def cleanup(self):
-        if self.page:
-            try: self.page.quit()
-            except: pass
-            self.page = None
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try: time.sleep(0.2); shutil.rmtree(self.root_workspace, ignore_errors=True); break
-                except: time.sleep(0.5)
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
         
         
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""
@@ -427,18 +301,22 @@ class BelPlugin(IVSPlg):
             except Exception:
             except Exception:
                 pass
                 pass
 
 
+        session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
 
 
         return PluginStatus(
         return PluginStatus(
-            instance_id=getattr(self, "instance_id", self.group_id),
-            is_healthy=getattr(self, "is_healthy", True),
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
             state=state,
             state=state,
             current_url=current_url,
             current_url=current_url,
             account=account_name,
             account=account_name,
             proxy=proxy_info,
             proxy=proxy_info,
-            session_age_sec=0,
+            session_age_sec=session_age,
             last_active_at=utc_now_str(),
             last_active_at=utc_now_str(),
         )
         )
 
 
     def __del__(self):
     def __del__(self):
+        """
+        析构函数:当对象被垃圾回收时自动调用
+        """
         self.cleanup()
         self.cleanup()

+ 3 - 3
plugins/bls_plugin.py

@@ -1019,9 +1019,9 @@ class BlsPlugin(IVSPlg):
         提取 cookies, local_storage, 存入 VSCloudApi
         提取 cookies, local_storage, 存入 VSCloudApi
         """
         """
         cookies_dict = {}
         cookies_dict = {}
-        # 方式 1: curl_cffi 的 cookies 对象通常支持 get_dict()
-        if hasattr(self.session.cookies, "get_dict"):
-            cookies_dict = self.session.cookies.get_dict()
+        get_dict_fn = getattr(self.session.cookies, "get_dict", None)
+        if callable(get_dict_fn):
+            cookies_dict = get_dict_fn()
         else:
         else:
             # 方式 2: 迭代 (兼容标准 CookieJar)
             # 方式 2: 迭代 (兼容标准 CookieJar)
             for c in self.session.cookies:
             for c in self.session.cookies:

+ 98 - 167
plugins/de_plugin.py

@@ -4,48 +4,47 @@ import random
 import re
 import re
 import os
 import os
 import uuid
 import uuid
-import shutil
 import base64
 import base64
-import socket
 from datetime import datetime
 from datetime import datetime
 from typing import List, Dict, Optional, Any, Callable
 from typing import List, Dict, Optional, Any, Callable
-from urllib.parse import urljoin, urlparse, urlencode
-
-# DrissionPage 核心
-from DrissionPage import ChromiumPage, ChromiumOptions
+from DrissionPage import ChromiumPage
 
 
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
+from vs_types import (
+    VSPlgConfig, 
+    AppointmentType, 
+    VSQueryResult, 
+    VSBookResult, 
+    AvailabilityStatus, 
+    TimeSlot, 
+    DateAvailability, 
+    NotFoundError, 
+    PermissionDeniedError, 
+    RateLimiteddError, 
+    SessionExpiredOrInvalidError, 
+    BizLogicError, 
+    PluginStatus, 
+    utc_now_str
+)
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.vs_cloud_api import VSCloudApi
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
-from toolkit.proxy_tunnel import ProxyTunnel
 from toolkit.ocr_engine import DddOcrEngine
 from toolkit.ocr_engine import DddOcrEngine
+from utils.plugin_utils import (
+    BrowserResponse,
+    init_chromium_options,
+    perform_browser_fetch,
+    filter_dates_in_range,
+    cleanup_browser_workspace
+)
 
 
 
 
-class BrowserResponse:
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-    def json(self):
-        if self._json is None:
-            if not self.text: return {}
-            try: self._json = json.loads(self.text)
-            except: self._json = {}
-        return self._json
-
-def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
-    dt = datetime.strptime(data_str, date_str_format)
-    return dt.strftime("%Y-%m-%d")
-
 def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
 def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
-    if "@" not in email: raise ValueError(f"Invalid email: {email}")
+    if "@" not in email:
+        raise ValueError(f"Invalid email: {email}")
     local_part, _ = email.rsplit("@", 1)
     local_part, _ = email.rsplit("@", 1)
     return f"{local_part}@{new_domain}"
     return f"{local_part}@{new_domain}"
 
 
+
 class DePlugin(IVSPlg):
 class DePlugin(IVSPlg):
     """
     """
     Germany (Visametric) 签证预约插件 (Browser + Tunnel Mode)
     Germany (Visametric) 签证预约插件 (Browser + Tunnel Mode)
@@ -71,7 +70,7 @@ class DePlugin(IVSPlg):
         if not os.path.exists(self.root_workspace):
         if not os.path.exists(self.root_workspace):
             os.makedirs(self.root_workspace)
             os.makedirs(self.root_workspace)
             
             
-        self.tunnel = None # 代理隧道
+        self.tunnel = None  # 代理隧道
         self.is_healthy = True
         self.is_healthy = True
         self.session_create_time: float = 0
         self.session_create_time: float = 0
         
         
@@ -89,9 +88,9 @@ class DePlugin(IVSPlg):
         
         
     def _log(self, message): 
     def _log(self, message): 
         if self.logger:
         if self.logger:
-            self.logger(f'[DePlugin] [{self.group_id}] {message}')
+            self.logger(f'[DePlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
         else:
-            print(f'[DePlugin] [{self.group_id}] {message}')
+            print(f'[DePlugin] [{self.group_id}] [{self.instance_id}] {message}')
         
         
     def set_config(self, config: VSPlgConfig):
     def set_config(self, config: VSPlgConfig):
         self.config = config
         self.config = config
@@ -103,14 +102,12 @@ class DePlugin(IVSPlg):
         pass
         pass
 
 
     def health_check(self) -> bool:
     def health_check(self) -> bool:
-        if not self.is_healthy:
-            return False
-        if not self.page:
+        if not self.is_healthy or not self.page:
             return False
             return False
         try:
         try:
             if not self.page.run_js("return 1;"):
             if not self.page.run_js("return 1;"):
                 return False
                 return False
-        except:
+        except Exception:
             return False
             return False
         if self.config.session_max_life > 0:
         if self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
             if time.time() - self.session_create_time > self.config.session_max_life:
@@ -124,41 +121,15 @@ class DePlugin(IVSPlg):
         """
         """
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self.ocr_engine = DddOcrEngine()
         self.ocr_engine = DddOcrEngine()
-        co = ChromiumOptions()
-        # 端口分配 (Docker 适配)
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0)); return s.getsockname()[1]
-        co.set_local_port(get_free_port())
-        
-        # 路径与隔离
-        co.set_user_data_path(self.user_data_path)
-        chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-            
-        # 代理隧道
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Tunnel for {p.ip}...")
-                self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
-
-        # Docker 核心参数
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-gpu')
-        co.set_argument('--disable-dev-shm-usage') 
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
+        
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         co.set_argument('--ignore-certificate-errors')
         co.set_argument('--ignore-certificate-errors')
 
 
         try:
         try:
@@ -170,18 +141,15 @@ class DePlugin(IVSPlg):
             self.page.get(url_home)
             self.page.get(url_home)
             
             
             # 2. Cloudflare 过盾
             # 2. Cloudflare 过盾
-            cf = CloudflareBypasser(self.page, log=self.config.debug)
+            cf = CloudflareBypasser(self.page, log=self.config.debug if self.config else False)
             if not cf.bypass(max_retry=15):
             if not cf.bypass(max_retry=15):
                 if "access denied" in self.page.title.lower():
                 if "access denied" in self.page.title.lower():
                     raise BizLogicError("Cloudflare Access Denied")
                     raise BizLogicError("Cloudflare Access Denied")
                 raise BizLogicError("Cloudflare bypass timeout")
                 raise BizLogicError("Cloudflare bypass timeout")
 
 
             # 3. 提取 CSRF 和 验证码
             # 3. 提取 CSRF 和 验证码
-            # 等待页面加载
             meta_ele = self.page.ele('xpath://meta[@name="csrf-token"]', timeout=30)
             meta_ele = self.page.ele('xpath://meta[@name="csrf-token"]', timeout=30)
-                
             if not meta_ele:
             if not meta_ele:
-                # 截图调试,看看是不是还在 Cloudflare 或者加载失败
                 self.page.get_screenshot(path='csrf_not_found.jpg')
                 self.page.get_screenshot(path='csrf_not_found.jpg')
                 raise NotFoundError("CSRF Token meta tag not found (Page load failed?)")
                 raise NotFoundError("CSRF Token meta tag not found (Page load failed?)")
             
             
@@ -191,7 +159,6 @@ class DePlugin(IVSPlg):
             html = self.page.html
             html = self.page.html
             match = re.search(r'"data:image/png;base64,"\s*\+\s*"(.*?)"', html)
             match = re.search(r'"data:image/png;base64,"\s*\+\s*"(.*?)"', html)
             if not match:
             if not match:
-                # 尝试直接找 img
                 try:
                 try:
                     img_ele = self.page.ele('xpath://img[contains(@src, "data:image")]')
                     img_ele = self.page.ele('xpath://img[contains(@src, "data:image")]')
                     if img_ele:
                     if img_ele:
@@ -199,11 +166,12 @@ class DePlugin(IVSPlg):
                         captcha_b64 = b64_src.split(',')[1]
                         captcha_b64 = b64_src.split(',')[1]
                     else:
                     else:
                         raise NotFoundError("Captcha image not found")
                         raise NotFoundError("Captcha image not found")
-                except:
+                except Exception:
                     raise NotFoundError("Captcha image not found (Regex failed)")
                     raise NotFoundError("Captcha image not found (Regex failed)")
             else:
             else:
                 captcha_b64 = match.group(1)
                 captcha_b64 = match.group(1)
             image_bytes = base64.b64decode(captcha_b64)
             image_bytes = base64.b64decode(captcha_b64)
+
             # 4. 识别验证码 (本地 OCR 服务)
             # 4. 识别验证码 (本地 OCR 服务)
             captcha_code = self.ocr_engine.inference_captcha(image_bytes)
             captcha_code = self.ocr_engine.inference_captcha(image_bytes)
 
 
@@ -218,7 +186,7 @@ class DePlugin(IVSPlg):
             self.cleanup()
             self.cleanup()
             raise e
             raise e
 
 
-    def _submit_captcha(self, code):
+    def _submit_captcha(self, code: str):
         """
         """
         提交验证码,获取 personalinfo 和 emailValControl
         提交验证码,获取 personalinfo 和 emailValControl
         """
         """
@@ -229,28 +197,26 @@ class DePlugin(IVSPlg):
             'mailConfirmCode': code
             'mailConfirmCode': code
         }
         }
         
         
-        # 使用 Fetch 提交 (Form-UrlEncoded)
         resp = self._perform_request('POST', url, data=payload, headers={
         resp = self._perform_request('POST', url, data=payload, headers={
             'X-Requested-With': 'XMLHttpRequest'
             'X-Requested-With': 'XMLHttpRequest'
         })
         })
         
         
-        # 解析返回的 HTML 片段
         html = resp.text
         html = resp.text
         
         
-        # 提取 personalinfo
         match_pi = re.search(r"personalinfo:\s*'([^']*)'", html)
         match_pi = re.search(r"personalinfo:\s*'([^']*)'", html)
-        if match_pi: self.personal_info_val = match_pi.group(1)
+        if match_pi:
+            self.personal_info_val = match_pi.group(1)
         
         
-        # 提取 emailValControl
         match_ev = re.search(r"emailValControl:\s*'([^']*)'", html)
         match_ev = re.search(r"emailValControl:\s*'([^']*)'", html)
-        if match_ev: self.email_val_control = match_ev.group(1)
+        if match_ev:
+            self.email_val_control = match_ev.group(1)
             
             
         if not self.personal_info_val:
         if not self.personal_info_val:
             raise NotFoundError(message="Personalinfo not found in captcha response")
             raise NotFoundError(message="Personalinfo not found in captcha response")
         
         
-        # 更新 CSRF (如果返回了新的)
         m = re.search(r'name="csrf-token" content="([^"]+)"', html)
         m = re.search(r'name="csrf-token" content="([^"]+)"', html)
-        if m: self.csrf_token = m.group(1)
+        if m:
+            self.csrf_token = m.group(1)
 
 
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
         res = VSQueryResult()
         res = VSQueryResult()
@@ -295,9 +261,9 @@ class DePlugin(IVSPlg):
 
 
         return res
         return res
 
 
-    def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
+    def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
         res = VSBookResult()
-        available_dates = [da.date for da in slot_info.availability]
+        user_inputs = user_inputs or {}
         exp_start = user_inputs.get('expected_start_date', '')
         exp_start = user_inputs.get('expected_start_date', '')
         exp_end = user_inputs.get('expected_end_date', '')
         exp_end = user_inputs.get('expected_end_date', '')
         
         
@@ -306,7 +272,7 @@ class DePlugin(IVSPlg):
             for da in slot_info.availability
             for da in slot_info.availability
         ]
         ]
         
         
-        valid_dates = self._filter_dates(available_dates, exp_start, exp_end)
+        valid_dates = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True)
         if not valid_dates:
         if not valid_dates:
             raise NotFoundError("No dates match constraints")
             raise NotFoundError("No dates match constraints")
         
         
@@ -317,7 +283,7 @@ class DePlugin(IVSPlg):
         time_slot = self._get_slot_time(target_date)
         time_slot = self._get_slot_time(target_date)
         
         
         # 2. 发送邮件流程
         # 2. 发送邮件流程
-        alias_email = get_alias_email(user_inputs.get("email"), new_domain='text.skin')
+        alias_email = get_alias_email(user_inputs.get("email", ""), new_domain='text.skin')
         self._send_email_step1(alias_email)
         self._send_email_step1(alias_email)
         self._send_email_step2("0")
         self._send_email_step2("0")
         
         
@@ -333,8 +299,6 @@ class DePlugin(IVSPlg):
         match = re.search(r'https:\/\/checkout\.stripe\.com\/c\/pay\/[^\s"]+', book_res_html)
         match = re.search(r'https:\/\/checkout\.stripe\.com\/c\/pay\/[^\s"]+', book_res_html)
         
         
         res.success = True
         res.success = True
-        res.fee_amount = 3000
-        res.fee_currency = 'EUR'
         res.book_date = target_date
         res.book_date = target_date
         res.book_time = time_slot['time']
         res.book_time = time_slot['time']
         
         
@@ -344,40 +308,20 @@ class DePlugin(IVSPlg):
             
             
         return res
         return res
 
 
-    # ---------------------------------------------------------
-    # 辅助方法
-    # ---------------------------------------------------------
-    
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
+        """在浏览器上下文中注入执行 Fetch"""
         if not self.page:
         if not self.page:
-            raise BizLogicError("Browser not init")
-        
-        req_url = url
-        if params:
-            sep = '&' if '?' in req_url else '?'
-            req_url += sep + urlencode(params)
-            
-        fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
-        
-        if json_data:
-            fetch_opts['body'] = json.dumps(json_data)
-            fetch_opts['headers']['Content-Type'] = 'application/json'
-        elif data:
-            if isinstance(data, dict):
-                fetch_opts['body'] = urlencode(data)
-                fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
-            else:
-                fetch_opts['body'] = data
-
-        js = f"""
-        return fetch("{req_url}", {json.dumps(fetch_opts)})
-        .then(async r => {{
-            const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
-            return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
-        }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-        """
-        
-        resp = BrowserResponse(self.page.run_js(js, timeout=60))
+            raise BizLogicError("Browser not initialized")
+        
+        resp = perform_browser_fetch(
+            self.page, 
+            method=method, 
+            url=url, 
+            headers=headers, 
+            data=data, 
+            json_data=json_data, 
+            params=params
+        )
         
         
         if resp.status_code == 200:
         if resp.status_code == 200:
             return resp
             return resp
@@ -390,20 +334,21 @@ class DePlugin(IVSPlg):
         elif resp.status_code == 429:
         elif resp.status_code == 429:
             self.is_healthy = False
             self.is_healthy = False
             raise RateLimiteddError()
             raise RateLimiteddError()
-        elif resp.status_code in [401, 419]:
+        elif resp.status_code in (401, 419):
             self.is_healthy = False
             self.is_healthy = False
             raise SessionExpiredOrInvalidError()
             raise SessionExpiredOrInvalidError()
         else:
         else:
             raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
             raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
 
 
-    def _refresh_firewall_session(self):
+    def _refresh_firewall_session(self) -> bool:
         try:
         try:
             self.page.refresh()
             self.page.refresh()
-            cf = CloudflareBypasser(self.page, log=self.config.debug)
+            cf = CloudflareBypasser(self.page, log=self.config.debug if self.config else False)
             return cf.bypass(max_retry=10)
             return cf.bypass(max_retry=10)
-        except: return False
+        except Exception:
+            return False
 
 
-    def _get_slot_time(self, date) -> Dict:
+    def _get_slot_time(self, date: str) -> Dict:
         url = f"{self.base_url}/en/senddate"
         url = f"{self.base_url}/en/senddate"
         dt_m = datetime.strptime(date, "%Y-%m-%d")
         dt_m = datetime.strptime(date, "%Y-%m-%d")
         converted_date = dt_m.strftime("%d-%m-%Y")
         converted_date = dt_m.strftime("%d-%m-%Y")
@@ -419,44 +364,46 @@ class DePlugin(IVSPlg):
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         resp = self._perform_request('POST', url, data=payload, headers=headers)
         resp = self._perform_request('POST', url, data=payload, headers=headers)
         
         
-        # 使用 Regex 提取 Slot
         times = []
         times = []
-        # pattern: data-id="123" ... <i>09:00</i>
         for m in re.finditer(r'data-id="([^"]+)"[^>]*data-all="([^"]+)"[^>]*>.*?<i>(.*?)</i>', resp.text, re.DOTALL):
         for m in re.finditer(r'data-id="([^"]+)"[^>]*data-all="([^"]+)"[^>]*>.*?<i>(.*?)</i>', resp.text, re.DOTALL):
             times.append({'data_id': m.group(1), 'data_all': m.group(2), 'time': m.group(3).strip()})
             times.append({'data_id': m.group(1), 'data_all': m.group(2), 'time': m.group(3).strip()})
             
             
-        if not times: raise NotFoundError("No time slots")
+        if not times:
+            raise NotFoundError("No time slots")
         return random.choice(times)
         return random.choice(times)
 
 
-    def _send_email_step1(self, email):
+    def _send_email_step1(self, email: str):
         url = f"{self.base_url}/en/jky45fgd"
         url = f"{self.base_url}/en/jky45fgd"
-        payload = { "emailCheck": email, "personalinfo": self.personal_info_val }
+        payload = {"emailCheck": email, "personalinfo": self.personal_info_val}
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         self._perform_request('POST', url, data=payload, headers=headers)
         self._perform_request('POST', url, data=payload, headers=headers)
 
 
-    def _send_email_step2(self, code_val):
+    def _send_email_step2(self, code_val: str):
         url = f"{self.base_url}/en/confirmCodeSendMail"
         url = f"{self.base_url}/en/confirmCodeSendMail"
-        payload = { "confirmCode": code_val, "emailValControl": self.email_val_control }
+        payload = {"confirmCode": code_val, "emailValControl": self.email_val_control}
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         headers = {'X-CSRF-TOKEN': self.csrf_token, 'X-Requested-With': 'XMLHttpRequest'}
         self._perform_request('POST', url, data=payload, headers=headers)
         self._perform_request('POST', url, data=payload, headers=headers)
 
 
-    def _read_otp_email(self, recipient) -> str:
+    def _read_otp_email(self, recipient: str) -> str:
         master_email = "hujiarui8@gmail.com"
         master_email = "hujiarui8@gmail.com"
         sender = 'Visametric - verify at visametric.com'
         sender = 'Visametric - verify at visametric.com'
         now_utc = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
         now_utc = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
-        for i in range(12):
+        for _ in range(12):
             c = VSCloudApi.Instance().fetch_mail_content(master_email, sender, recipient, 'Verification Code', 'Verification code', now_utc, 300)
             c = VSCloudApi.Instance().fetch_mail_content(master_email, sender, recipient, 'Verification Code', 'Verification code', now_utc, 300)
             if c:
             if c:
                 m = re.search(r'\b\d{6}\b', c)
                 m = re.search(r'\b\d{6}\b', c)
-                if m: return m.group(0)
+                if m:
+                    return m.group(0)
             time.sleep(5)
             time.sleep(5)
         raise NotFoundError("OTP timeout")
         raise NotFoundError("OTP timeout")
 
 
     def _confirm_appointment(self, date, slot_data, user_inputs, otp, alias_email):
     def _confirm_appointment(self, date, slot_data, user_inputs, otp, alias_email):
         url = f"{self.base_url}/en/personal/appointment/create"
         url = f"{self.base_url}/en/personal/appointment/create"
         def _get_dob(d):
         def _get_dob(d):
-            try: return datetime.strptime(d[:10], "%Y-%m-%d")
-            except: return datetime.now()
+            try:
+                return datetime.strptime(d[:10], "%Y-%m-%d")
+            except Exception:
+                return datetime.now()
         dob = _get_dob(user_inputs.get('birthday', ''))
         dob = _get_dob(user_inputs.get('birthday', ''))
         
         
         payload = {
         payload = {
@@ -494,7 +441,6 @@ class DePlugin(IVSPlg):
             "personalapproveTerms": "1"
             "personalapproveTerms": "1"
         }
         }
         
         
-        # 补全空字段 (Person 2-4)
         for i in range(2, 5):
         for i in range(2, 5):
             payload.update({
             payload.update({
                 f"name{i}": "", f"surname{i}": "", f"nationality{i}": "0", f"birthday{i}": "0", f"birthmonth{i}": "0", f"birthyear{i}": "0", f"passport{i}": "", f"passportExpirationDate{i}": "", f"email{i}": alias_email, f"phone{i}": user_inputs.get('phone_no'), f"alternativephone{i}": ""
                 f"name{i}": "", f"surname{i}": "", f"nationality{i}": "0", f"birthday{i}": "0", f"birthmonth{i}": "0", f"birthyear{i}": "0", f"passport{i}": "", f"passportExpirationDate{i}": "", f"email{i}": alias_email, f"phone{i}": user_inputs.get('phone_no'), f"alternativephone{i}": ""
@@ -503,30 +449,11 @@ class DePlugin(IVSPlg):
         headers = {'X-Requested-With': 'XMLHttpRequest'}
         headers = {'X-Requested-With': 'XMLHttpRequest'}
         return self._perform_request('POST', url, data=payload, headers=headers).text
         return self._perform_request('POST', url, data=payload, headers=headers).text
 
 
-    def _filter_dates(self, dates, start, end):
-        if not start or not end: return dates
-        valid = []
-        s = datetime.strptime(start[:10], "%Y-%m-%d")
-        e = datetime.strptime(end[:10], "%Y-%m-%d")
-        for d in dates:
-            c = datetime.strptime(d, "%Y-%m-%d")
-            if s <= c <= e: valid.append(d)
-        random.shuffle(valid)
-        return valid
-
     def cleanup(self):
     def cleanup(self):
-        if self.page:
-            try: self.page.quit()
-            except: pass
-            self.page = None
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try: time.sleep(0.2); shutil.rmtree(self.root_workspace, ignore_errors=True); break
-                except: time.sleep(0.5)
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
         
         
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""
@@ -538,18 +465,22 @@ class DePlugin(IVSPlg):
             except Exception:
             except Exception:
                 pass
                 pass
 
 
+        session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
 
 
         return PluginStatus(
         return PluginStatus(
-            instance_id=getattr(self, "instance_id", self.group_id),
-            is_healthy=getattr(self, "is_healthy", True),
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
             state=state,
             state=state,
             current_url=current_url,
             current_url=current_url,
             account=account_name,
             account=account_name,
             proxy=proxy_info,
             proxy=proxy_info,
-            session_age_sec=0,
+            session_age_sec=session_age,
             last_active_at=utc_now_str(),
             last_active_at=utc_now_str(),
         )
         )
 
 
     def __del__(self):
     def __del__(self):
+        """
+        析构函数:当对象被垃圾回收时自动调用
+        """
         self.cleanup()
         self.cleanup()

+ 15 - 3
plugins/grc_plugin.py

@@ -5,11 +5,23 @@ import re
 import os
 import os
 from datetime import datetime, timezone, timedelta
 from datetime import datetime, timezone, timedelta
 from typing import List, Dict, Any, Callable, Optional, Set, Tuple
 from typing import List, Dict, Any, Callable, Optional, Set, Tuple
-
 from curl_cffi import requests, const
 from curl_cffi import requests, const
-
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
+from vs_types import (
+    VSPlgConfig,
+    AppointmentType,
+    VSQueryResult,
+    VSBookResult,
+    DateAvailability,
+    AvailabilityStatus,
+    NotFoundError,
+    PermissionDeniedError,
+    RateLimiteddError,
+    SessionExpiredOrInvalidError,
+    BizLogicError,
+    PluginStatus,
+    utc_now_str
+)
 
 
 MODERN_BROWSERS: List[str] = [
 MODERN_BROWSERS: List[str] = [
     "chrome",
     "chrome",

+ 243 - 455
plugins/ita_plugin.py

@@ -1,47 +1,161 @@
 import time
 import time
 import json
 import json
 import random
 import random
-import socket
-import uuid
-import shutil
 import re
 import re
 import os
 import os
+import uuid
 import base64
 import base64
-from concurrent.futures import ThreadPoolExecutor
 from datetime import datetime
 from datetime import datetime
 from typing import List, Dict, Optional, Any, Callable
 from typing import List, Dict, Optional, Any, Callable
-from urllib.parse import urlencode, urlparse
-
-from DrissionPage import ChromiumPage, ChromiumOptions
+from DrissionPage import ChromiumPage
 
 
-import configure
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
-from toolkit.mihomo_tunnel import MihomoTunnel
+from vs_types import (
+    VSPlgConfig, 
+    AppointmentType, 
+    VSQueryResult, 
+    VSBookResult, 
+    AvailabilityStatus, 
+    TimeSlot, 
+    DateAvailability, 
+    NotFoundError, 
+    PermissionDeniedError, 
+    RateLimiteddError, 
+    SessionExpiredOrInvalidError, 
+    BizLogicError, 
+    PluginStatus, 
+    utc_now_str
+)
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.vs_cloud_api import VSCloudApi
+from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from utils.mouse import HumanMouse
 from utils.mouse import HumanMouse
 from utils.keyboard import HumanKeyboard
 from utils.keyboard import HumanKeyboard
-from utils.fingerprint_utils import FingerprintGenerator
-
-
-class BrowserResponse:
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-    def json(self):
-        if self._json is None:
-            if not self.text: return {}
-            try: self._json = json.loads(self.text)
-            except: self._json = {}
-        return self._json
-
-# ==========================================
-# 2. ItaPlugin 核心逻辑
-# ==========================================
+from utils.flow_engine import BaseFlow, on, guard, done, fatal
+from utils.plugin_utils import (
+    BrowserResponse,
+    init_chromium_options,
+    perform_browser_fetch,
+    filter_dates_in_range,
+    cleanup_browser_workspace
+)
+
+
+class ItaLoginFlow(BaseFlow):
+    """
+    基于 BaseFlow 注解状态机驱动的意大利 Prenot@Mi 会话创建与自动导航流
+    """
+    def __init__(self, page, plugin: 'ItaPlugin', interval: float = 1.0):
+        super().__init__(
+            page=page, 
+            config=plugin.config, 
+            context={"plugin": plugin}, 
+            interval=interval, 
+            logger=plugin._log, 
+            cf_bypasser=CloudflareBypasser(page, log=plugin.config.debug if plugin.config else False)
+        )
+        self.plugin = plugin
+        self.has_submitted_login = False
+
+    # --- 异常守卫与自愈 (Priority 5~7) ---
+    @guard(text="502 Bad Gateway", priority=5)
+    @guard(text="503 Service Temporarily Unavailable", priority=5)
+    @guard(text="error 1020", priority=5)
+    def on_server_network_error(self):
+        self.log("[WARN] 检测到服务器网络错误 (502/503/1020),等待并刷新自愈...", level="warning")
+        self.plugin._random_sleep(10, 15)
+        self.page.refresh()
+        try:
+            self.page.wait.doc_loaded()
+        except Exception:
+            pass
+
+    @guard(text="Sorry, you have been blocked", priority=6)
+    @guard(text="You are being rate limited", priority=6)
+    @guard(text="Cloudflare Ray ID", priority=6)
+    @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
+    def on_cloudflare_blocked(self):
+        pass
+
+    @guard(title="just a moment", priority=7)
+    def on_cloudflare_turnstile_challenge(self):
+        self.log("🛡️ 检测到 Cloudflare 5秒盾挑战,正在尝试穿透...")
+        if self.cf_bypasser.bypass(max_retry=3):
+            self.plugin._random_sleep(3, 5)
+            self.cf_bypasser.handle_waiting_room()
+
+    @guard(title="waitting room", priority=7)
+    def on_cloudflare_waiting_room(self):
+        self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...")
+        self.cf_bypasser.handle_waiting_room()
+        time.sleep(2)
+
+    # --- 状态流转与表单处理 (Priority 35~45) ---
+    @on(ele="#pingid-button", priority=45)
+    def handle_initial_landing_page(self):
+        self.log("[State] Initial Landing Page detected. Clicking login button...")
+        login_btn = self.page.ele('#pingid-button')
+        if login_btn:
+            self.plugin.mouse.human_click_ele(login_btn)
+        self.log("Redirecting to PingID...")
+        self.plugin._random_sleep(3, 5)
+
+    @on(ele="@name=callback_1", priority=40)
+    def handle_pingid_login_form(self):
+        if self.has_submitted_login:
+            return
+        self.log("[State] PingID Login Form detected. Submitting credentials...")
+        username = self.plugin.config.account.username
+        password = self.plugin.config.account.password
+
+        self.log("Entering username...")
+        user_input = self.page.ele('@name=callback_1')
+        self.plugin.mouse.human_click_ele(user_input)
+        user_input.input(username, clear=True)
+        time.sleep(1)
+
+        self.log("Entering password...")
+        pwd_input = self.page.ele('@type=password')
+        self.plugin.mouse.human_click_ele(pwd_input)
+        pwd_input.input(password, clear=True)
+        time.sleep(1)
+
+        self.log("Clicking submit login button...")
+        submit_btn = self.page.ele('tag:button@type=submit') 
+        if submit_btn:
+            self.plugin.mouse.human_click_ele(submit_btn)
+        
+        self.has_submitted_login = True
+        self.log("Login form submitted. Waiting for dashboard to load...")
+        self.plugin._random_sleep(5, 7)
+
+    @on(ele=".app-menu", priority=35)
+    def handle_dashboard_menu(self):
+        self.log("[State] Dashboard Menu detected.")
+        switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2', timeout=0.5)
+        if switch_en_btn:
+            self.log("Found 'English' language switch button. Clicking to change language...")
+            self.plugin.mouse.human_click_ele(switch_en_btn)
+            self.plugin._random_sleep(4, 6)
+            return
+
+        book_btn = self.page.ele('@href=/Services', timeout=0.5)
+        if book_btn:
+            self.log("Found 'Book' menu element. Clicking to proceed to reservation...")
+            self.plugin.mouse.human_click_ele(book_btn)
+            self.plugin._random_sleep(4, 6)
+            return
+
+        self.log("[WARN] On Dashboard, but neither 'English' nor 'Book' button was found. Waiting...")
+        time.sleep(2)
+
+    # --- 成功终态到达 (Priority 10) ---
+    @on(url="/Services", ele=".app-menu", priority=10)
+    @done
+    def on_reached_services_page(self):
+        self.plugin.session_create_time = time.time()
+        self.log("🎉 Successfully reached the Booking Services page! Session created successfully!")
+
+
 class ItaPlugin(IVSPlg):
 class ItaPlugin(IVSPlg):
     name = "ita_plugin"
     name = "ita_plugin"
     version = "1.0.0"
     version = "1.0.0"
@@ -58,6 +172,7 @@ class ItaPlugin(IVSPlg):
         # Prenotami 特有配置
         # Prenotami 特有配置
         self._service_id = 0 
         self._service_id = 0 
         self.ita_url = 'https://prenotami.esteri.it'
         self.ita_url = 'https://prenotami.esteri.it'
+        self._host = self.ita_url
         
         
         self.instance_id = uuid.uuid4().hex[:8]
         self.instance_id = uuid.uuid4().hex[:8]
         self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
         self.root_workspace = os.path.abspath(os.path.join("data/temp_browser_data", f"{self.group_id}.{self.instance_id}"))
@@ -73,9 +188,13 @@ class ItaPlugin(IVSPlg):
         
         
     def _log(self, message): 
     def _log(self, message): 
         if self.logger:
         if self.logger:
-            self.logger(f'[ItaPlugin] [{self.group_id}] {message}')
+            self.logger(f'[ItaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
         else:
-            print(f'[ItaPlugin] [{self.group_id}] {message}')
+            print(f'[ItaPlugin] [{self.group_id}] [{self.instance_id}] {message}')
+
+    def _random_sleep(self, min_sec=3, max_sec=5):
+        sleep_time = random.uniform(min_sec, max_sec)
+        time.sleep(sleep_time)
         
         
     def set_config(self, config: VSPlgConfig): 
     def set_config(self, config: VSPlgConfig): 
         self.config = config
         self.config = config
@@ -92,7 +211,7 @@ class ItaPlugin(IVSPlg):
         try:
         try:
             if not self.page.run_js("return 1;"):
             if not self.page.run_js("return 1;"):
                 return False
                 return False
-        except:
+        except Exception:
             return False
             return False
         if self.config.session_max_life > 0:
         if self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
             if time.time() - self.session_create_time > self.config.session_max_life:
@@ -105,388 +224,131 @@ class ItaPlugin(IVSPlg):
         全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
         全浏览器会话创建:过盾 -> JS注入登录 -> 状态机自动路由导航 -> 到达目标页
         """
         """
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._log(f"Initializing Session (ID: {self.instance_id})...")
-        co = ChromiumOptions()
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0))
-                return s.getsockname()[1]
-        
-        debug_port = get_free_port()
-        self._log(f"Assigned Debug Port: {debug_port}")
-        self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
-    
-        co.set_local_port(debug_port)       
-        co.set_user_data_path(self.user_data_path)
-        
-        chrome_path = configure.CHROME_PATH
-        if not chrome_path:
-            chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-        
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Proxy Tunnel for {p.ip}...")
-                exit_node = {
-                    "name": "ExitNode",
-                    "type": p.proto,
-                    "server": p.ip,
-                    "port": p.port,
-                    "username": p.username,
-                    "password": p.password
-                }
-                relay_node = None
-                if configure.MIHOMO_RELAY_NODES:
-                    relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
-                mihomo_path = configure.MIHOMO_BIN_PATH
-                if not mihomo_path:
-                    mihomo_path = os.getenv("MIHOMO_BIN")
-                if not mihomo_path:
-                    raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
-                self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
-
-        specific_fp = FingerprintGenerator().generate(self.config.account.username)
-        fp_seed = specific_fp.get("seed")
-        fp_platform = specific_fp.get("platform")
-        fp_brand = specific_fp.get("brand")
-        self._log(f'browser fingerprint seed={fp_seed}')
-
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-dev-shm-usage')
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
-        co.set_argument(f"--fingerprint={fp_seed}")
-        co.set_argument(f"--fingerprint-platform={fp_platform}")
-        co.set_argument(f"--fingerprint-brand={fp_brand}")
+        self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}")
+
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         
         
-        self.page = ChromiumPage(co)
-        if self.config.debug:
-            self.page.get('https://example.com')
-            js_script = """
-            function getFingerprint() {
-                let webglVendor = 'Unknown';
-                let webglRenderer = 'Unknown';
-                try {
-                    let canvas = document.createElement('canvas');
-                    let gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
-                    if (gl) {
-                        let debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
-                        if (debugInfo) {
-                            webglVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
-                            webglRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
-                        }
-                    }
-                } catch(e) {}
-
-                return {
-                    "User-Agent": navigator.userAgent,
-                    "Platform": navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform,
-                    "Brands": navigator.userAgentData ? navigator.userAgentData.brands.map(b => b.brand).join(', ') : 'Not Supported',
-                    "CPU Cores": navigator.hardwareConcurrency,
-                    "Language": navigator.language,
-                    "Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone,
-                    "WebGL Vendor": webglVendor,
-                    "WebGL Renderer": webglRenderer
-                };
-            }
-            return getFingerprint();
-            """
-            fp_data = self.page.run_js(js_script)
-            self._log("================ 预检浏览器指纹数据 ================")
-            self._log(json.dumps(fp_data, indent=4, ensure_ascii=False))
-            self._log("====================================================")
-            
         self.page = ChromiumPage(co)
         self.page = ChromiumPage(co)
         ita_url = self.ita_url
         ita_url = self.ita_url
         self._log(f"Navigating to {ita_url}")
         self._log(f"Navigating to {ita_url}")
         self.page.get(ita_url)
         self.page.get(ita_url)
         
         
         self._log("Init humanize tools...")
         self._log("Init humanize tools...")
-        self.mouse = HumanMouse(self.page, debug=True)
+        self.mouse = HumanMouse(self.page, debug=False)
         self.keyboard = HumanKeyboard(self.page)
         self.keyboard = HumanKeyboard(self.page)
-        self._log("Random mouse start position...")
+        
         viewport_width = self.page.rect.viewport_size[0]
         viewport_width = self.page.rect.viewport_size[0]
         viewport_height = self.page.rect.viewport_size[1]
         viewport_height = self.page.rect.viewport_size[1]
         init_x = random.randint(10, viewport_width - 10)
         init_x = random.randint(10, viewport_width - 10)
         init_y = random.randint(10, viewport_height - 10)
         init_y = random.randint(10, viewport_height - 10)
         self.mouse.move(init_x, init_y) 
         self.mouse.move(init_x, init_y) 
-        
-        switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2')
-        self.mouse.human_click_ele(switch_en_btn)
-        self.page.wait.load_start() 
-        time.sleep(5)
-
-        max_steps = 15
-        stuck_counter = 0
-        last_url = ""
-        session_created = False
-        has_submitted_login = False
-        
-        username = self.config.account.username
-        password = self.config.account.password
-        
-        for step in range(max_steps):
-            self.page.wait.doc_loaded()
-            time.sleep(1)
-            
-            current_url = self.page.url
-            current_title = self.page.title.lower()
-            current_html_content = self.page.html
-            self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
-            
-            # --- [异常处理与反爬对抗层] ---
-            if current_url == last_url:
-                stuck_counter += 1
-            else:
-                last_url = current_url
-                stuck_counter = 0
-                
-            if stuck_counter >= 3:
-                self._log("[WARN] Page stucked, try to refresh...")
-                self.page.refresh()
-                self._random_sleep(5, 8)
-                stuck_counter = 0
-                continue
-            
-            server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable", "error 1020"]
-            if any(err in current_html_content for err in server_error_indicators):
-                self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
-                self.page.refresh()
-                self._random_sleep(10, 15)
-                continue
-            
-            # Cloudflare 拦截
-            cloudflare_blocked_indicators = [
-                "Sorry, you have been blocked",
-                "You are being rate limited",
-                "Cloudflare Ray ID"
-            ]
-            if any(indicator in current_html_content for indicator in cloudflare_blocked_indicators):
-                raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
-            
-            # 遇到五秒盾先绕盾 (保留你原有的逻辑)
-            if "just a moment" in current_title or "cloudflare" in current_title:
-                # 假设你有 cf_bypasser 实例
-                # if not cf_bypasser.bypass(max_retry=3): continue
-                self._log("[State] CF 5-second shield detected. Waiting...")
-                time.sleep(5)
-                continue
-            
-            # 状态 0: 成功到达目标预约页面 (Target Page)
-            if "/Services" in current_url and self.page.ele('.app-menu', timeout=1):
-                self._log("🎉 Successfully reached the Booking Services page! Session created successfully!")                
-                self.session_create_time = time.time()
-                session_created = True
-                break
-
-            # 状态 1: 登录前的初始首页
-            elif self.page.ele('#pingid-button', timeout=1):
-                self._log("[State] Initial Landing Page detected. Clicking login button...")
-                login_btn = self.page.ele('#pingid-button')
-                self.mouse.human_click_ele(login_btn)
-                self._log("Redirecting to PingID...")
-                self._random_sleep(3, 5) # 替代 time.sleep(5)
-                continue
-
-            # 状态 2: 真正的表单登录页 (PingID)
-            elif self.page.ele('@name=callback_1', timeout=1):
-                self._log("[State] PingID Login Form detected. Submitting credentials...")
-                
-                self._log("Entering username...")
-                user_input = self.page.ele('@name=callback_1')
-                self.mouse.human_click_ele(user_input)
-                user_input.input(username, clear=True)
-                time.sleep(1) # 模拟人手停顿
-                
-                self._log("Entering password...")
-                pwd_input = self.page.ele('@type=password')
-                self.mouse.human_click_ele(pwd_input)
-                pwd_input.input(password, clear=True)
-                time.sleep(1)
-                
-                self._log("Clicking submit login button...")
-                submit_btn = self.page.ele('tag:button@type=submit') 
-                self.mouse.human_click_ele(submit_btn)
-                
-                has_submitted_login = True
-                self._log("Login form submitted. Waiting for dashboard to load...")
-                self._random_sleep(5, 7)
-                continue
-
-            # 状态 3: 登录成功后的主控制台 (导航栏页面)
-            elif self.page.ele('.app-menu', timeout=1):
-                self._log("[State] Dashboard Menu detected.")
-                
-                switch_en_btn = self.page.ele('tag:a@@href=/Language/ChangeLanguage?lang=2', timeout=0.5)
-                if switch_en_btn:
-                    self._log("Found 'English' language switch button. Clicking to change language...")
-                    self.mouse.human_click_ele(switch_en_btn)
-                    self._random_sleep(4, 6)
-                    continue
-                
-                # 动作 B: 如果没有英文切换按钮(说明已经是英文或不存在),则查找并点击 Book 按钮
-                book_btn = self.page.ele('@href=/Services', timeout=0.5)
-                if book_btn:
-                    self._log("Found 'Book' menu element. Clicking to proceed to reservation...")
-                    self.mouse.human_click_ele(book_btn)
-                    self._random_sleep(4, 6)
-                    continue
-                
-                self._log("[WARN] On Dashboard, but neither 'English' nor 'Book' button was found. Waiting...")
-                time.sleep(2)
-                continue
-
-            else:
-                self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
-                time.sleep(2)
-                
-        if not session_created:
-            raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
-
-    # -------------------------------------------------------------
-    # 2. Query Availability
-    # -------------------------------------------------------------
+
+        # 启动 ItaLoginFlow 注解流状态机
+        login_flow = ItaLoginFlow(
+            self.page, 
+            plugin=self, 
+            interval=1.0
+        )
+        login_flow.run(max_steps=20)
+        self.session_create_time = time.time()
+        self._log("🎉 ItaLoginFlow completed successfully. Session created.")
+
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
         res = VSQueryResult()
         res = VSQueryResult()
         res.success = False
         res.success = False
         res.availability_status = AvailabilityStatus.NoneAvailable
         res.availability_status = AvailabilityStatus.NoneAvailable
         
         
-        # 假设要预约的服务和到访原因
-        TARGET_SERVICE = "National and Schengen Visas"
-        REASON_FOR_VISIT = "Tourism" # 对应 value 42 的选项文本
+        TARGET_SERVICE = self.free_config.get('target_service', "National and Schengen Visas")
+        REASON_FOR_VISIT = self.free_config.get('reason_for_visit', "Tourism")
 
 
-        # ==========================================
         # 步骤 1:在服务列表中寻找并点击目标服务的 Book
         # 步骤 1:在服务列表中寻找并点击目标服务的 Book
-        # ==========================================
         self._log("Waiting for service list to load...")
         self._log("Waiting for service list to load...")
         self.page.wait.eles_loaded('@aria-controls=dataTableServices', timeout=10)
         self.page.wait.eles_loaded('@aria-controls=dataTableServices', timeout=10)
 
 
         self._log(f"Searching for [{TARGET_SERVICE}] Book button...")
         self._log(f"Searching for [{TARGET_SERVICE}] Book button...")
-        # 使用 XPath:找包含 TARGET_SERVICE 文本的行(tr),再找该行里包含 Book 的超链接(a)
         target_book_btn_xpath = f'xpath://tr[contains(., "{TARGET_SERVICE}")]//a[contains(text(), "Book")]'
         target_book_btn_xpath = f'xpath://tr[contains(., "{TARGET_SERVICE}")]//a[contains(text(), "Book")]'
         book_btn = self.page.ele(target_book_btn_xpath)
         book_btn = self.page.ele(target_book_btn_xpath)
 
 
         if not book_btn:
         if not book_btn:
             self._log(f"Target [{TARGET_SERVICE}] Book button not found, currently no slots available.")
             self._log(f"Target [{TARGET_SERVICE}] Book button not found, currently no slots available.")
-            # 这里可以根据你的逻辑 return 或者 raise Exception
-        else:
-            self.mouse.human_click_ele(book_btn)
-            self.page.wait.load_start()
-            time.sleep(3)
+            return res
 
 
+        self.mouse.human_click_ele(book_btn)
+        self.page.wait.load_start()
+        time.sleep(3)
 
 
-        # ==========================================
         # 步骤 2:填写预约表单
         # 步骤 2:填写预约表单
-        # ==========================================
         self._log("Waiting for booking form to load...")
         self._log("Waiting for booking form to load...")
         self.page.wait.eles_loaded('#bookingForm', timeout=10)
         self.page.wait.eles_loaded('#bookingForm', timeout=10)
 
 
         self._log("Selecting booking type & reason...")
         self._log("Selecting booking type & reason...")
         typeofbooking_ddl = self.page.ele('#typeofbookingddl')
         typeofbooking_ddl = self.page.ele('#typeofbookingddl')
-        # DrissionPage select 方法直接按文本选中,会自动触发网页的 JS 联动
-        typeofbooking_ddl.select('Individual booking')
-        time.sleep(1)
+        if typeofbooking_ddl:
+            typeofbooking_ddl.select('Individual booking')
+            time.sleep(1)
 
 
         reason_ddl = self.page.ele('#ddls_0')
         reason_ddl = self.page.ele('#ddls_0')
-        reason_ddl.select(REASON_FOR_VISIT)
-        time.sleep(1)
+        if reason_ddl:
+            reason_ddl.select(REASON_FOR_VISIT)
+            time.sleep(1)
 
 
         notes_input = self.page.ele('#BookingNotes')
         notes_input = self.page.ele('#BookingNotes')
-        notes_input.clear()
-        notes_input.input('N/A') # 选填,填入 N/A 或者留空
-        time.sleep(1)
+        if notes_input:
+            notes_input.clear()
+            notes_input.input('N/A')
+            time.sleep(1)
 
 
-        # ==========================================
         # 步骤 3:处理 OTP 验证码
         # 步骤 3:处理 OTP 验证码
-        # ==========================================
         self._log("Sending OTP code...")
         self._log("Sending OTP code...")
         otp_send_btn = self.page.ele('#otp-send')
         otp_send_btn = self.page.ele('#otp-send')
-        self.mouse.human_click_ele(otp_send_btn)
-
-        # 这是一个 AJAX 请求,会转圈圈。我们需要等待成功提示出现
-        self.page.wait.ele_displayed('#IdOtpSent', timeout=15) # 等待绿字 "New code sent!" 显示
-        self._log("OTP code sent successfully.")
+        if otp_send_btn:
+            self.mouse.human_click_ele(otp_send_btn)
+            self.page.wait.ele_displayed('#IdOtpSent', timeout=15)
+            self._log("OTP code sent successfully.")
 
 
         otp_input = self.page.ele('#otp-input')
         otp_input = self.page.ele('#otp-input')
-        self.mouse.human_click_ele(otp_input)
-        otp_input.input('123456')
-        time.sleep(1)
+        if otp_input:
+            self.mouse.human_click_ele(otp_input)
+            otp_input.input('123456')
+            time.sleep(1)
 
 
-        # ==========================================
         # 步骤 4:勾选隐私政策并提交
         # 步骤 4:勾选隐私政策并提交
-        # ==========================================
         privacy_checkbox = self.page.ele('#PrivacyCheck')
         privacy_checkbox = self.page.ele('#PrivacyCheck')
-        # 判断一下如果没勾上才去点,防止重复点击取消了
-        if not privacy_checkbox.states.is_checked:
+        if privacy_checkbox and not privacy_checkbox.states.is_checked:
             self.mouse.human_click_ele(privacy_checkbox)
             self.mouse.human_click_ele(privacy_checkbox)
         time.sleep(1)
         time.sleep(1)
 
 
         self._log("Submitting forward form...")
         self._log("Submitting forward form...")
         forward_btn = self.page.ele('#btnAvanti')
         forward_btn = self.page.ele('#btnAvanti')
-        self.mouse.human_click_ele(forward_btn)
+        if forward_btn:
+            self.mouse.human_click_ele(forward_btn)
 
 
-        # 提交后页面会跳转,等待加载开始
         self.page.wait.load_start()
         self.page.wait.load_start()
         self._log(f"Form submitted. Current page: {self.page.url}")
         self._log(f"Form submitted. Current page: {self.page.url}")
+        time.sleep(3)
 
 
-        time.sleep(5)
-
-        valid_dates = []
-            
-        if valid_dates:
-            res.success = True
-            res.availability_status = AvailabilityStatus.Available
-            earliest_date = valid_dates[0]
-            earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
-            res.earliest_date = earliest_dt
-            for day in valid_days:
-                # 查询具体 Slot
-                slot_url = f"{self._host}/BookingCalendar/RetrieveTimeSlots"
-                slot_payload = {
-                    "selectedDay": day, # YYYY-MM-DD
-                    "idService": str(self._service_id)
-                }
-                resp_slot = self._perform_request("POST", slot_url, json_data=slot_payload)
-                
-                time_slots = self._parse_time_slots(resp_slot.text)
-                ts_list = []
-                if time_slots:
-                    # 转换结构
-                    for ts in time_slots:
-                        # ts: {'id': 123, 'start': '10:00', 'end': '10:30', 'remain': 1}
-                        ts_list.append(TimeSlot(
-                            time=f"{ts['start']} - {ts['end']}",
-                            label=str(ts['id']) # 将 ID 存入 label 以便 book 使用
-                        ))
-                res.availability.append(DateAvailability(date=datetime.strptime(day, "%d-%m-%Y"), times=ts_list))
         return res
         return res
 
 
-    # -------------------------------------------------------------
-    # 3. Book
-    # -------------------------------------------------------------
     def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
     def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
         res = VSBookResult()
         res.success = False
         res.success = False
+        user_inputs = user_inputs or {}
         
         
         if not slot_info.availability:
         if not slot_info.availability:
             raise NotFoundError("No slots to book")
             raise NotFoundError("No slots to book")
             
             
         target_dt = slot_info.availability[0].date
         target_dt = slot_info.availability[0].date
-        target_date = target_dt.strftime("%Y-%m-%d")
-        # 取第一个时间段
-        target_slot = slot_info.availability[0].times[0]
-        slot_id = target_slot.label # 我们在 query 里把 ID 存在了 label
-        slot_text = target_slot.time # "10:00 - 10:30"
+        target_date = target_dt.strftime("%Y-%m-%d") if target_dt else ""
+        target_slot = slot_info.availability[0].times[0] if slot_info.availability[0].times else None
+        slot_id = target_slot.label if target_slot else ""
+        slot_text = target_slot.time if target_slot else ""
         
         
         # 1. 获取 OTP (GenerateOTP)
         # 1. 获取 OTP (GenerateOTP)
         self._log("Requesting OTP...")
         self._log("Requesting OTP...")
@@ -495,9 +357,8 @@ class ItaPlugin(IVSPlg):
         
         
         # 2. 等待并读取邮件
         # 2. 等待并读取邮件
         self._log("Waiting for email code...")
         self._log("Waiting for email code...")
-        time.sleep(10) # 稍微等一下发信
-        email_account = self.config.account.email
-        # 使用 CloudAPI 读取 (假设已配置)
+        time.sleep(10)
+        email_account = self.config.account.username if self.config and self.config.account else ""
         otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
         otp_code = VSCloudApi.Instance().get_email_verify_code(email_account)
         
         
         if not otp_code:
         if not otp_code:
@@ -505,47 +366,34 @@ class ItaPlugin(IVSPlg):
         self._log(f"Got OTP: {otp_code}")
         self._log(f"Got OTP: {otp_code}")
 
 
         # 3. 提交详细信息 (Fill User Info)
         # 3. 提交详细信息 (Fill User Info)
-        # 这是最复杂的一步,涉及文件上传 (Multipart)
         self._log("Submitting User Details & Files...")
         self._log("Submitting User Details & Files...")
-        
-        # 准备文件 (转 Base64 传给 JS)
         passport_pdf_path = user_inputs.get('passport_pdf_path')
         passport_pdf_path = user_inputs.get('passport_pdf_path')
         irp_pdf_path = user_inputs.get('irp_pdf_path')
         irp_pdf_path = user_inputs.get('irp_pdf_path')
         
         
         def file_to_b64(path):
         def file_to_b64(path):
-            if not path or not os.path.exists(path): return ""
+            if not path or not os.path.exists(path):
+                return ""
             with open(path, "rb") as f:
             with open(path, "rb") as f:
                 return base64.b64encode(f.read()).decode('utf-8')
                 return base64.b64encode(f.read()).decode('utf-8')
 
 
         ppt_b64 = file_to_b64(passport_pdf_path)
         ppt_b64 = file_to_b64(passport_pdf_path)
         irp_b64 = file_to_b64(irp_pdf_path)
         irp_b64 = file_to_b64(irp_pdf_path)
         
         
-        # 构造 JS FormData 提交脚本
-        # 注意:这里需要根据 Service ID (Dublin/Canton) 动态调整字段 ID
-        # 下面以 Dublin (1321) 的字段为例,如果是 Canton 需要修改 _Id 和 _TipoDatoAddizionale
-        # 为了通用性,这里演示 Dublin 的结构,请根据实际 Service ID 调整 mapping
-        
-        # 假设是 Dublin (根据提供的源码分析)
-        boundary = '----WebKitFormBoundaryRandomString'
         submit_url = f"{self._host}/Services/Booking/{self._service_id}"
         submit_url = f"{self._host}/Services/Booking/{self._service_id}"
         
         
-        # 注入 JS 执行
         js_submit = f"""
         js_submit = f"""
         const url = "{submit_url}";
         const url = "{submit_url}";
         const fd = new FormData();
         const fd = new FormData();
         
         
-        // 基础字段
         fd.append('ServizioDescrizione', 'D Visa Application');
         fd.append('ServizioDescrizione', 'D Visa Application');
         fd.append('MessaggioRassicuranteWaitingList', 'True');
         fd.append('MessaggioRassicuranteWaitingList', 'True');
         fd.append('isWaitingListEnabled', 'False');
         fd.append('isWaitingListEnabled', 'False');
         fd.append('IDServizioConsolare', '35');
         fd.append('IDServizioConsolare', '35');
         fd.append('IDServizioErogato', '{self._service_id}');
         fd.append('IDServizioErogato', '{self._service_id}');
-        fd.append('IdTipoPrenotazione', '1'); // Single
+        fd.append('IdTipoPrenotazione', '1');
         fd.append('NumMaxAccompagnatori', '3');
         fd.append('NumMaxAccompagnatori', '3');
         fd.append('NumAccompagnatoriSelected', '0');
         fd.append('NumAccompagnatoriSelected', '0');
         
         
-        // 动态字段 (Dublin 示例)
-        // [0] Other citizenship -> User Input
         fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
         fd.append('DatiAddizionaliPrenotante[0]._Descrizione', 'Other citizenship/s');
         fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
         fd.append('DatiAddizionaliPrenotante[0]._testo', '{user_inputs.get("citizen", "China")}');
         fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
         fd.append('DatiAddizionaliPrenotante[0]._Obbligatorio', 'False');
@@ -553,7 +401,6 @@ class ItaPlugin(IVSPlg):
         fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
         fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale', '26');
         fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
         fd.append('DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo', '2');
         
         
-        // [1] Full address -> User Input
         fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
         fd.append('DatiAddizionaliPrenotante[1]._Descrizione', 'Full residence address');
         fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
         fd.append('DatiAddizionaliPrenotante[1]._testo', '{user_inputs.get("address", "")}');
         fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
         fd.append('DatiAddizionaliPrenotante[1]._Obbligatorio', 'True');
@@ -561,7 +408,6 @@ class ItaPlugin(IVSPlg):
         fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
         fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoDatoAddizionale', '25');
         fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
         fd.append('DatiAddizionaliPrenotante[1]._TipoDatoAddizionale.IDTipoControllo', '2');
 
 
-        // [2] Passport Num
         fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
         fd.append('DatiAddizionaliPrenotante[2]._Descrizione', 'Passport number');
         fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
         fd.append('DatiAddizionaliPrenotante[2]._testo', '{user_inputs.get("passport", "")}');
         fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
         fd.append('DatiAddizionaliPrenotante[2]._Obbligatorio', 'True');
@@ -569,23 +415,16 @@ class ItaPlugin(IVSPlg):
         fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
         fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoDatoAddizionale', '2');
         fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
         fd.append('DatiAddizionaliPrenotante[2]._TipoDatoAddizionale.IDTipoControllo', '2');
 
 
-        // [3] Reason (Select)
         fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
         fd.append('DatiAddizionaliPrenotante[3]._Descrizione', 'Reason for visit');
         fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
         fd.append('DatiAddizionaliPrenotante[3]._Obbligatorio', 'True');
         fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
         fd.append('DatiAddizionaliPrenotante[3]._Id', '61741');
         fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
         fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoDatoAddizionale', '34');
         fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
         fd.append('DatiAddizionaliPrenotante[3]._TipoDatoAddizionale.IDTipoControllo', '3');
-        fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42'); // 42 = Tourism? Need verify
+        fd.append('DatiAddizionaliPrenotante[3]._idSelezionato', '42');
 
 
-        // OTP
         fd.append('otp-input', '{otp_code}');
         fd.append('otp-input', '{otp_code}');
         fd.append('PrivacyCheck', 'true');
         fd.append('PrivacyCheck', 'true');
         
         
-        // 文件处理 (Base64 -> Blob -> FormData)
-        // 注意:这里假设页面上有文件上传的对应 ID,或者我们直接硬编码 FormData
-        // 原始抓包并未显示文件字段名,通常是 File_0, File_1
-        // 我们需要将 base64 转 blob
-        
         async function addFile(b64, name, filename) {{
         async function addFile(b64, name, filename) {{
             if(!b64) return;
             if(!b64) return;
             const res = await fetch(`data:application/pdf;base64,${{b64}}`);
             const res = await fetch(`data:application/pdf;base64,${{b64}}`);
@@ -593,13 +432,11 @@ class ItaPlugin(IVSPlg):
             fd.append(name, blob, filename);
             fd.append(name, blob, filename);
         }}
         }}
         
         
-        // 并行处理文件
         await Promise.all([
         await Promise.all([
-            addFile('{ppt_b64}', 'File_0', 'passport.pdf'), // 假设 File_0 是护照
-            addFile('{irp_b64}', 'File_1', 'irp.pdf')       // 假设 File_1 是 IRP
+            addFile('{ppt_b64}', 'File_0', 'passport.pdf'),
+            addFile('{irp_b64}', 'File_1', 'irp.pdf')
         ]);
         ]);
 
 
-        // 发送 POST
         return fetch(url, {{
         return fetch(url, {{
             method: 'POST',
             method: 'POST',
             body: fd
             body: fd
@@ -615,10 +452,9 @@ class ItaPlugin(IVSPlg):
             self._log("User Info Submitted Successfully.")
             self._log("User Info Submitted Successfully.")
         else:
         else:
             self._log(f"User Info Submit Failed: {resp.text[:100]}")
             self._log(f"User Info Submit Failed: {resp.text[:100]}")
-            # 如果 OTP 错误,页面会返回特定错误信息
             if "Codice errato" in resp.text:
             if "Codice errato" in resp.text:
                 raise BizLogicError("Invalid OTP Code")
                 raise BizLogicError("Invalid OTP Code")
-            return res # Fail
+            return res
 
 
         # 4. 最终确认预约 (InsertNewBooking)
         # 4. 最终确认预约 (InsertNewBooking)
         self._log("Finalizing Booking...")
         self._log("Finalizing Booking...")
@@ -626,9 +462,8 @@ class ItaPlugin(IVSPlg):
         final_payload = {
         final_payload = {
             "idCalendarioGiornaliero": slot_id,
             "idCalendarioGiornaliero": slot_id,
             "selectedDay": target_date,
             "selectedDay": target_date,
-            "selectedHour": slot_text # "10:00 - 10:30(2)"
+            "selectedHour": slot_text
         }
         }
-        # 这里用 Form-UrlEncoded
         resp_final = self._perform_request("POST", final_url, data=final_payload)
         resp_final = self._perform_request("POST", final_url, data=final_payload)
         
         
         if resp_final.status_code == 200:
         if resp_final.status_code == 200:
@@ -642,54 +477,34 @@ class ItaPlugin(IVSPlg):
         return res
         return res
     
     
     def _perform_request(self, method, url, headers=None, data=None, json_data=None):
     def _perform_request(self, method, url, headers=None, data=None, json_data=None):
-        """JS Fetch Wrapper"""
-        if not self.page: raise BizLogicError("Browser not init")
-        
-        fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
-        if json_data:
-            fetch_opts['body'] = json.dumps(json_data)
-            fetch_opts['headers']['Content-Type'] = 'application/json; charset=UTF-8'
-        elif data:
-            if isinstance(data, dict):
-                from urllib.parse import urlencode
-                fetch_opts['body'] = urlencode(data)
-                fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
-            else:
-                fetch_opts['body'] = data
-
-        js = f"""
-        return fetch("{url}", {json.dumps(fetch_opts)})
-        .then(async r => {{
-            const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
-            return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
-        }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-        """
-        return BrowserResponse(self.page.run_js(js, timeout=60)) # 文件上传可能较慢,给60s
+        """在浏览器上下文中注入执行 Fetch"""
+        if not self.page:
+            raise BizLogicError("Browser not initialized")
+        return perform_browser_fetch(
+            self.page, 
+            method=method, 
+            url=url, 
+            headers=headers, 
+            data=data, 
+            json_data=json_data
+        )
 
 
-    def _parse_valid_days(self, text):
-        # 提取 DateLibere (YYYY-MM-DD)
-        # 格式: {"DateLibere":"22/10/2024 00:00:00","SlotLiberi":1,"SlotRimanenti":1}
-        # 原始正则: r'{"DateLibere":"(.*?)","SlotLiberi":\d+,"SlotRimanenti":(-?\d+)}'
+    def _parse_valid_days(self, text: str) -> List[str]:
         days = []
         days = []
         try:
         try:
             matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
             matches = re.findall(r'{"DateLibere":"(.*?)".*?"SlotRimanenti":(-?\d+)}', text)
             for d_str, rem in matches:
             for d_str, rem in matches:
                 if int(rem) != -1:
                 if int(rem) != -1:
-                    # 22/10/2024 -> 2024-10-22
                     dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
                     dt = datetime.strptime(d_str[:10], "%d/%m/%Y")
                     days.append(dt.strftime("%Y-%m-%d"))
                     days.append(dt.strftime("%Y-%m-%d"))
-        except: pass
+        except Exception:
+            pass
         return days
         return days
 
 
-    def _parse_time_slots(self, text):
-        # 提取 IDCalendarioServizioGiornaliero, StartTime, EndTime, Remain
+    def _parse_time_slots(self, text: str) -> List[Dict[str, Any]]:
         slots = []
         slots = []
         try:
         try:
-            # 原始逻辑比较复杂,这里简化正则
-            # 查找 SlotRimanenti > 0 的记录
-            # 关键是 IDCalendarioServizioGiornaliero
             raw_list = json.loads(text)
             raw_list = json.loads(text)
-            # Prenotami 返回的是一个 JSON 列表字符串
             for item in raw_list:
             for item in raw_list:
                 remain = item.get('SlotRimanenti', -1)
                 remain = item.get('SlotRimanenti', -1)
                 if remain > 0:
                 if remain > 0:
@@ -703,43 +518,15 @@ class ItaPlugin(IVSPlg):
                         'end': e_time,
                         'end': e_time,
                         'remain': remain
                         'remain': remain
                     })
                     })
-        except: pass
+        except Exception:
+            pass
         return slots
         return slots
-    
-    # --- 资源清理核心方法 ---
+
     def cleanup(self):
     def cleanup(self):
-        """
-        销毁浏览器并彻底删除临时文件
-        """
-        # 1. 关闭浏览器
-        if self.page:
-            try:
-                self.page.quit() # 这会关闭 Chrome 进程
-            except Exception:
-                pass # 忽略已关闭的错误
-            self.page = None
-        
-        # 2. 删除文件
-        # 注意:Chrome 关闭后可能需要几百毫秒释放文件锁,稍微等待
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try:
-                    time.sleep(0.2)
-                    shutil.rmtree(self.root_workspace, ignore_errors=True)
-                    break
-                except Exception as e:
-                    # 如果删除失败(通常是Windows文件占用),重试
-                    self._log(f"Cleanup retry: {e}")
-                    time.sleep(0.5)
-            
-            # 如果依然存在,打印警告(虽然 ignore_errors=True 会掩盖报错,但可以 check exists)
-            if os.path.exists(self.root_workspace):
-                 self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
-        # 3. [新增] 关闭代理隧道
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
                  
                  
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""
@@ -751,6 +538,7 @@ class ItaPlugin(IVSPlg):
             except Exception:
             except Exception:
                 pass
                 pass
 
 
+        session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
         state = "running" if self.is_healthy else "unhealthy"
         state = "running" if self.is_healthy else "unhealthy"
 
 
         return PluginStatus(
         return PluginStatus(
@@ -760,7 +548,7 @@ class ItaPlugin(IVSPlg):
             current_url=current_url,
             current_url=current_url,
             account=account_name,
             account=account_name,
             proxy=proxy_info,
             proxy=proxy_info,
-            session_age_sec=0,
+            session_age_sec=session_age,
             last_active_at=utc_now_str(),
             last_active_at=utc_now_str(),
         )
         )
 
 

+ 86 - 148
plugins/pol_plugin.py

@@ -4,46 +4,38 @@ import random
 import re
 import re
 import os
 import os
 import uuid
 import uuid
-import shutil
 import base64
 import base64
-import socket
-import easyocr
 from datetime import datetime
 from datetime import datetime
 from typing import List, Dict, Optional, Any, Callable
 from typing import List, Dict, Optional, Any, Callable
-from urllib.parse import urljoin, urlparse, urlencode
-
-# DrissionPage 核心
-from DrissionPage import ChromiumPage, ChromiumOptions
+from DrissionPage import ChromiumPage
 
 
+from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
 
 
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
+from vs_types import (
+    VSPlgConfig, 
+    AppointmentType, 
+    VSQueryResult, 
+    VSBookResult, 
+    AvailabilityStatus, 
+    DateAvailability, 
+    NotFoundError, 
+    PermissionDeniedError, 
+    RateLimiteddError, 
+    SessionExpiredOrInvalidError, 
+    BizLogicError, 
+    PluginStatus, 
+    utc_now_str
+)
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.vs_cloud_api import VSCloudApi
-from toolkit.proxy_tunnel import ProxyTunnel
-
-class BrowserResponse:
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-    def json(self):
-        if self._json is None:
-            if not self.text: return {}
-            try: self._json = json.loads(self.text)
-            except: self._json = {}
-        return self._json
-
-def to_yyyymmdd(data_str: str, date_str_format: str, target_format: str="%Y-%m-%d"):
-    dt = datetime.strptime(data_str, date_str_format)
-    return dt.strftime("%Y-%m-%d")
+from utils.plugin_utils import (
+    BrowserResponse,
+    init_chromium_options,
+    perform_browser_fetch,
+    filter_dates_in_range,
+    cleanup_browser_workspace
+)
 
 
-def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
-    if "@" not in email: raise ValueError(f"Invalid email: {email}")
-    local_part, _ = email.rsplit("@", 1)
-    return f"{local_part}@{new_domain}"
 
 
 class PolPlugin(IVSPlg):
 class PolPlugin(IVSPlg):
     """
     """
@@ -70,9 +62,9 @@ class PolPlugin(IVSPlg):
         if not os.path.exists(self.root_workspace):
         if not os.path.exists(self.root_workspace):
             os.makedirs(self.root_workspace)
             os.makedirs(self.root_workspace)
             
             
-        self.reader = easyocr.Reader(['en'], gpu=False)
+        self.captcha_breaker = CaptchaBreaker()
         
         
-        self.tunnel = None # 代理隧道
+        self.tunnel = None  # 代理隧道
         self.is_healthy = True
         self.is_healthy = True
         self.session_create_time: float = 0
         self.session_create_time: float = 0
     
     
@@ -81,9 +73,9 @@ class PolPlugin(IVSPlg):
         
         
     def _log(self, message): 
     def _log(self, message): 
         if self.logger:
         if self.logger:
-            self.logger(f'[PolPlugin] [{self.group_id}] {message}')
+            self.logger(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         else:
         else:
-            print(f'[PolPlugin] [{self.group_id}] {message}')
+            print(f'[PolPlugin] [{self.group_id}] [{self.instance_id}] {message}')
         
         
     def set_config(self, config: VSPlgConfig):
     def set_config(self, config: VSPlgConfig):
         self.config = config
         self.config = config
@@ -100,7 +92,7 @@ class PolPlugin(IVSPlg):
         try:
         try:
             if not self.page.run_js("return 1;"):
             if not self.page.run_js("return 1;"):
                 return False
                 return False
-        except:
+        except Exception:
             return False
             return False
         if self.config.session_max_life > 0:
         if self.config.session_max_life > 0:
             if time.time() - self.session_create_time > self.config.session_max_life:
             if time.time() - self.session_create_time > self.config.session_max_life:
@@ -110,40 +102,18 @@ class PolPlugin(IVSPlg):
 
 
     def create_session(self):
     def create_session(self):
         """
         """
-        创建会话:启动浏览器 -> 代理隧道 -> 提取 Captcha -> 本地识别 -> 提交 -> 获取 Context
+        创建会话:启动浏览器 -> 配置代理隧道 -> 导航至首页
         """
         """
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._log(f"Initializing Session (ID: {self.instance_id})...")
-        co = ChromiumOptions()
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0)); return s.getsockname()[1]
-        co.set_local_port(get_free_port())
-        
-        co.set_user_data_path(self.user_data_path)
-        chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-            
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Tunnel for {p.ip}...")
-                self.tunnel = ProxyTunnel(p.ip, p.port, p.username, p.password)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         
         
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-gpu')
-        co.set_argument('--disable-dev-shm-usage') 
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
         try:
         try:
             self.page = ChromiumPage(co)
             self.page = ChromiumPage(co)
             url_home = "https://secure.e-konsulat.gov.pl"
             url_home = "https://secure.e-konsulat.gov.pl"
@@ -171,15 +141,17 @@ class PolPlugin(IVSPlg):
         time.sleep(3)
         time.sleep(3)
         img_ele = self.page.ele(captcha_image_selector)
         img_ele = self.page.ele(captcha_image_selector)
         img_src = img_ele.attr('src')
         img_src = img_ele.attr('src')
-        base64_data = img_src.split(',')[1]            
-        image_bytes = base64.b64decode(base64_data)
 
 
-        result = self.reader.readtext(image_bytes)
-        captcha_code = result[0][-2] if result else ""
-        self._log(f"Captcha code={captcha_code}")
+        try:
+            captcha_code = self.captcha_breaker.break_captcha(img_src)
+            self._log(f"Captcha code={captcha_code}")
+        except CaptchaBreakerError as e:
+            self._log(f"Solve captcha error: {e}")
+            raise BizLogicError(message=f"Solve captcha failed: {e}") from e
 
 
         if not captcha_code:
         if not captcha_code:
-            BizLogicError(message="Solve captcha failed")
+            raise BizLogicError(message="Solve captcha failed")
+            
         input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
         input_ele = self.page.ele('t:input@aria-label=Znaki z obrazka')
         input_ele.clear()
         input_ele.clear()
         input_ele.input(captcha_code)
         input_ele.input(captcha_code)
@@ -193,11 +165,11 @@ class PolPlugin(IVSPlg):
             raise BizLogicError(message=f"Captcha verify error={error_msg}")
             raise BizLogicError(message=f"Captcha verify error={error_msg}")
 
 
         if not self._select_mat_option('Rodzaj usługi', service_type):
         if not self._select_mat_option('Rodzaj usługi', service_type):
-            raise BizLogicError(message=f'Process select box failed')
+            raise BizLogicError(message='Process select box failed (service_type)')
         if not self._select_mat_option('Lokalizacja', location):
         if not self._select_mat_option('Lokalizacja', location):
-            raise BizLogicError(message=f'Process select box failed')
+            raise BizLogicError(message='Process select box failed (location)')
         if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
         if not self._select_mat_option('Chcę zarezerwować termin dla', '1 osob'):
-            raise BizLogicError(message=f'Process select box failed')
+            raise BizLogicError(message='Process select box failed (person count)')
         
         
         available_dates = []
         available_dates = []
         self._log("Wait Query Slot...")
         self._log("Wait Query Slot...")
@@ -215,7 +187,7 @@ class PolPlugin(IVSPlg):
                         if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
                         if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
                             try:
                             try:
                                 termin_select.click()
                                 termin_select.click()
-                            except:
+                            except Exception:
                                 termin_select.click(by_js=True)
                                 termin_select.click(by_js=True)
                             
                             
                             time.sleep(0.5)
                             time.sleep(0.5)
@@ -232,6 +204,7 @@ class PolPlugin(IVSPlg):
             except Exception as e:
             except Exception as e:
                 self._log(f"Query loop exception: {e}")                
                 self._log(f"Query loop exception: {e}")                
             time.sleep(0.5)
             time.sleep(0.5)
+            
         if available_dates:
         if available_dates:
             selected_date = random.choice(available_dates)
             selected_date = random.choice(available_dates)
             self._log(f"🎲 Random select date: {selected_date}...")
             self._log(f"🎲 Random select date: {selected_date}...")
@@ -259,7 +232,7 @@ class PolPlugin(IVSPlg):
             res.availability = []
             res.availability = []
         return res
         return res
     
     
-    def _lock_slot(self, lock_date):
+    def _lock_slot(self, lock_date: str) -> bool:
         slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
         slot_selector = f'xpath://span[contains(@class, "mat-option-text") and contains(text(), "{lock_date}")]'
         slot_ele = self.page.ele(slot_selector, timeout=1)
         slot_ele = self.page.ele(slot_selector, timeout=1)
         if not slot_ele:
         if not slot_ele:
@@ -269,7 +242,7 @@ class PolPlugin(IVSPlg):
                 if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
                 if termin_select and 'mat-select-disabled' not in str(termin_select.attr('class')):
                     try:
                     try:
                         termin_select.click()
                         termin_select.click()
-                    except:
+                    except Exception:
                         termin_select.click(by_js=True)
                         termin_select.click(by_js=True)
                     time.sleep(0.5)
                     time.sleep(0.5)
         slot_ele = self.page.ele(slot_selector, timeout=3)
         slot_ele = self.page.ele(slot_selector, timeout=3)
@@ -278,7 +251,7 @@ class PolPlugin(IVSPlg):
             return False
             return False
         try:
         try:
             slot_ele.click() 
             slot_ele.click() 
-        except:
+        except Exception:
             slot_ele.click(by_js=True)
             slot_ele.click(by_js=True)
         self._log(f"✅ Clicked date: {lock_date}")
         self._log(f"✅ Clicked date: {lock_date}")
         time.sleep(1)
         time.sleep(1)
@@ -289,12 +262,12 @@ class PolPlugin(IVSPlg):
             return False
             return False
         try:
         try:
             next_btn.click()
             next_btn.click()
-        except:
+        except Exception:
             next_btn.click(by_js=True)
             next_btn.click(by_js=True)
         self._log("✅ Clicked Dalej, locking slot...")
         self._log("✅ Clicked Dalej, locking slot...")
         return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
         return self.page.wait.url_change('weryfikacja-obrazkowa', exclude=True, timeout=15)
     
     
-    def _select_mat_option(self, label_text, option_text):
+    def _select_mat_option(self, label_text: str, option_text: str) -> bool:
         self._log(f"choose: {label_text} -> {option_text}")
         self._log(f"choose: {label_text} -> {option_text}")
         label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
         label = self.page.ele(f'tag:mat-label@@text():{label_text}', timeout=5)
         if not label:
         if not label:
@@ -320,19 +293,19 @@ class PolPlugin(IVSPlg):
             self._log(f"Can't find option: {option_text}")
             self._log(f"Can't find option: {option_text}")
             return False
             return False
 
 
-    def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
+    def book(self, slot_info: VSQueryResult, user_inputs: Dict = None) -> VSBookResult:
         res = VSBookResult()
         res = VSBookResult()
         return res
         return res
     
     
-    def _save_browser_session(self):
-        self._log("Abstract browser session env...")
+    def _save_browser_session(self) -> str:
+        self._log("Extracting browser session environment...")
         cookies_dict = self.page.cookies(all_domains=True, all_info=True)
         cookies_dict = self.page.cookies(all_domains=True, all_info=True)
         cookies_str = cookies_dict.as_json()
         cookies_str = cookies_dict.as_json()
         local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
         local_storage_str = self.page.run_js('return JSON.stringify(window.localStorage) || "{}"')
         session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
         session_storage_str = self.page.run_js('return JSON.stringify(window.sessionStorage) || "{}"')
-        proxy_str = ""
-        if hasattr(self, 'config') and hasattr(self.config, 'proxy') and self.config.proxy.ip:
-            p = self.config.proxy
+        proxy = getattr(getattr(self, 'config', None), 'proxy', None)
+        if proxy and getattr(proxy, 'ip', None):
+            p = proxy
             if p.username and p.password:
             if p.username and p.password:
                 proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
                 proxy_str = f"{p.proto}://{p.username}:{p.password}@{p.ip}:{p.port}"
             else:
             else:
@@ -346,80 +319,41 @@ class PolPlugin(IVSPlg):
             page=self.page.url,
             page=self.page.url,
             proxy=proxy_str
             proxy=proxy_str
         )
         )
-        return session_data.get('session_id')
+        return session_data.get('session_id', '')
     
     
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
     def _perform_request(self, method, url, headers=None, data=None, json_data=None, params=None, retry_count=0):
+        """在浏览器上下文中注入执行 Fetch"""
         if not self.page:
         if not self.page:
-            raise BizLogicError("Browser not init")
-        
-        req_url = url
-        if params:
-            sep = '&' if '?' in req_url else '?'
-            req_url += sep + urlencode(params)
-            
-        fetch_opts = { "method": method.upper(), "headers": headers or {}, "credentials": "include" }
-        
-        if json_data:
-            fetch_opts['body'] = json.dumps(json_data)
-            fetch_opts['headers']['Content-Type'] = 'application/json'
-        elif data:
-            if isinstance(data, dict):
-                fetch_opts['body'] = urlencode(data)
-                fetch_opts['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
-            else:
-                fetch_opts['body'] = data
-
-        js = f"""
-        return fetch("{req_url}", {json.dumps(fetch_opts)})
-        .then(async r => {{
-            const h = {{}}; r.headers.forEach((v, k) => h[k] = v);
-            return {{ status: r.status, body: await r.text(), headers: h, url: r.url }};
-        }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-        """
+            raise BizLogicError("Browser not initialized")
         
         
-        resp = BrowserResponse(self.page.run_js(js, timeout=60))
+        resp = perform_browser_fetch(
+            self.page, 
+            method=method, 
+            url=url, 
+            headers=headers, 
+            data=data, 
+            json_data=json_data, 
+            params=params
+        )
         
         
         if resp.status_code == 200:
         if resp.status_code == 200:
             return resp
             return resp
         elif resp.status_code == 403:
         elif resp.status_code == 403:
-            if "Just a moment" in resp.text and retry_count < 2:
-                self._log("Cloudflare 403. Refreshing...")
-                if self._refresh_firewall_session():
-                    return self._perform_request(method, url, headers, data, json_data, params, retry_count+1)
             raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
             raise PermissionDeniedError(f"HTTP 403: {resp.text[:100]}")
         elif resp.status_code == 429:
         elif resp.status_code == 429:
             self.is_healthy = False
             self.is_healthy = False
             raise RateLimiteddError()
             raise RateLimiteddError()
-        elif resp.status_code in [401, 419]:
+        elif resp.status_code in (401, 419):
             self.is_healthy = False
             self.is_healthy = False
             raise SessionExpiredOrInvalidError()
             raise SessionExpiredOrInvalidError()
         else:
         else:
             raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
             raise BizLogicError(f"HTTP {resp.status_code}: {resp.text[:100]}")
 
 
-    def _filter_dates(self, dates, start, end):
-        if not start or not end: return dates
-        valid = []
-        s = datetime.strptime(start[:10], "%Y-%m-%d")
-        e = datetime.strptime(end[:10], "%Y-%m-%d")
-        for d in dates:
-            c = datetime.strptime(d, "%Y-%m-%d")
-            if s <= c <= e: valid.append(d)
-        random.shuffle(valid)
-        return valid
-
     def cleanup(self):
     def cleanup(self):
-        if self.page:
-            try: self.page.quit()
-            except: pass
-            self.page = None
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try: time.sleep(0.2); shutil.rmtree(self.root_workspace, ignore_errors=True); break
-                except: time.sleep(0.5)
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
         
         
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""
@@ -431,18 +365,22 @@ class PolPlugin(IVSPlg):
             except Exception:
             except Exception:
                 pass
                 pass
 
 
+        session_age = int(time.time() - self.session_create_time) if getattr(self, "session_create_time", 0) > 0 else 0
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
         state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
 
 
         return PluginStatus(
         return PluginStatus(
-            instance_id=getattr(self, "instance_id", self.group_id),
-            is_healthy=getattr(self, "is_healthy", True),
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
             state=state,
             state=state,
             current_url=current_url,
             current_url=current_url,
             account=account_name,
             account=account_name,
             proxy=proxy_info,
             proxy=proxy_info,
-            session_age_sec=0,
+            session_age_sec=session_age,
             last_active_at=utc_now_str(),
             last_active_at=utc_now_str(),
         )
         )
 
 
     def __del__(self):
     def __del__(self):
+        """
+        析构函数:当对象被垃圾回收时自动调用
+        """
         self.cleanup()
         self.cleanup()

+ 15 - 2
plugins/prt_plugin.py

@@ -1,6 +1,19 @@
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, PluginStatus, utc_now_str
-
+from vs_types import (
+    VSPlgConfig,
+    AppointmentType,
+    VSQueryResult,
+    VSBookResult,
+    DateAvailability,
+    AvailabilityStatus,
+    NotFoundError,
+    PermissionDeniedError,
+    RateLimiteddError,
+    SessionExpiredOrInvalidError,
+    BizLogicError,
+    PluginStatus,
+    utc_now_str
+)
 
 
 class PrtPlugin(IVSPlg):
 class PrtPlugin(IVSPlg):
     """
     """

Dosya farkı çok büyük olduğundan ihmal edildi
+ 406 - 545
plugins/tls_plugin.py


+ 370 - 359
plugins/usa_plugin.py

@@ -4,43 +4,255 @@ import random
 import re
 import re
 import os
 import os
 import uuid
 import uuid
-import shutil
-import socket
-from datetime import date, datetime
+from datetime import datetime
 from typing import List, Dict, Optional, Any, Callable
 from typing import List, Dict, Optional, Any, Callable
-from urllib.parse import urljoin, urlparse, urlencode, parse_qs
-from concurrent.futures import ThreadPoolExecutor
-from DrissionPage import ChromiumPage, ChromiumOptions
+from DrissionPage import ChromiumPage
 
 
-import configure
 from vs_plg import IVSPlg
 from vs_plg import IVSPlg
+from vs_types import (
+    VSPlgConfig, 
+    AppointmentType, 
+    VSQueryResult, 
+    VSBookResult, 
+    AvailabilityStatus, 
+    DateAvailability, 
+    NotFoundError, 
+    PermissionDeniedError, 
+    RateLimiteddError, 
+    SessionExpiredOrInvalidError, 
+    BizLogicError, 
+    PluginStatus, 
+    utc_now_str
+)
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
-from toolkit.mihomo_tunnel import MihomoTunnel
 from utils.mouse import HumanMouse
 from utils.mouse import HumanMouse
 from utils.keyboard import HumanKeyboard
 from utils.keyboard import HumanKeyboard
-from utils.fingerprint_utils import FingerprintGenerator
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
-
-
-class BrowserResponse:
-    """模拟 requests.Response"""
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-
-    def json(self):
-        if self._json is None:
-            if not self.text:
-                return {}
-            try:
-                self._json = json.loads(self.text)
-            except:
-                self._json = {}
-        return self._json
+from utils.flow_engine import BaseFlow, on, guard, done, fatal
+from utils.plugin_utils import (
+    init_chromium_options,
+    filter_dates_in_range,
+    cleanup_browser_workspace,
+    save_screenshot
+)
+
+
+class UsaLoginFlow(BaseFlow):
+    """
+    基于 BaseFlow 注解状态机驱动的美签 USVisaScheduling 会话创建与自动导航流
+    """
+    def __init__(self, page, plugin: 'UsaPlugin', interval: float = 1.0):
+        super().__init__(
+            page=page, 
+            config=plugin.config, 
+            context={"plugin": plugin}, 
+            interval=interval, 
+            logger=plugin._log, 
+            cf_bypasser=CloudflareBypasser(page, log=True, logger=plugin._log),
+            max_stuck_cycles=30
+        )
+        self.plugin = plugin
+        self.has_submitted_login = False
+
+    # --- 异常守卫与自愈 (Priority 5~7) ---
+    @guard(text="502 Bad Gateway", priority=5)
+    @guard(text="503 Service Temporarily Unavailable", priority=5)
+    def on_server_network_error(self):
+        self.log("[WARN] 检测到服务器网络错误 (502/503),等待并刷新自愈...", level="warning")
+        self.plugin._random_sleep(30, 40)
+        self.page.refresh()
+        try:
+            self.page.wait.doc_loaded()
+        except Exception:
+            pass
+
+    @guard(text="Sorry, you have been blocked", priority=6)
+    @guard(text="You are being rate limited", priority=6)
+    @guard(text="Cloudflare Ray ID", priority=6)
+    @fatal("Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
+    def on_cloudflare_blocked(self):
+        pass
+
+    @guard(title="just a moment", priority=7)
+    @guard(title="请稍候", priority=7)
+    @guard(title="attention required", priority=7)
+    @guard(title="security check", priority=7)
+    @guard(title="cloudflare", priority=7)
+    @guard(ele="@src:challenges.cloudflare.com", priority=7)
+    @guard(ele="#challenge-stage", priority=7)
+    @guard(ele="#challenge-form", priority=7)
+    @guard(predicate=lambda flow: flow.cf_bypasser and not flow.cf_bypasser.is_bypassed(), priority=7)
+    def on_cloudflare_turnstile_challenge(self):
+        self.log("🛡️ 检测到 Cloudflare 5秒盾/Turnstile挑战,正在尝试穿透...")
+        if self.cf_bypasser.bypass(max_retry=8):
+            self.log("✅ Cloudflare 挑战通过!")
+            self.plugin._random_sleep(2, 4)
+            self.cf_bypasser.handle_waiting_room()
+        else:
+            self.log("[WARN] 本周期未完全通过 Cloudflare,将在下一周期继续尝试...")
+
+    @guard(title="waitting room", priority=7)
+    @guard(title="waiting room", priority=7)
+    def on_cloudflare_waiting_room(self):
+        self.log("🛡️ 检测到 Cloudflare 等候室,正在等待自动排队刷新...")
+        self.cf_bypasser.handle_waiting_room()
+        time.sleep(2)
+
+    # --- 状态流转与表单处理 (Priority 35~50) ---
+    @on(ele="#signInName", priority=50)
+    def handle_login_form(self):
+        if self.has_submitted_login:
+            return
+        self.log("[State] Login page detected. Submitting credentials...")
+        username = self.plugin.config.account.username
+        password = self.plugin.config.account.password
+
+        username_input = self.page.ele('#signInName')
+        self.plugin.mouse.human_click_ele(username_input)
+        username_input.clear()
+        self.plugin.keyboard.type_text(username, humanize=True)
+        self.plugin._random_sleep(3, 5)
+
+        password_input = self.page.ele('#password')
+        self.plugin.mouse.human_click_ele(password_input)
+        password_input.clear()
+        self.plugin.keyboard.type_text(password, humanize=True)
+        self.plugin._random_sleep(3, 5)
+
+        continue_btn = self.page.ele('#continue')
+        if continue_btn:
+            self.plugin.mouse.human_click_ele(continue_btn)
+        self.has_submitted_login = True
+        self.log("Login form submitted. Waiting for the next step to load...")
+        self.plugin._random_sleep(30, 40)
+
+    def _extract_security_answer(self, security: Any, q_num: str) -> Optional[str]:
+        if not security:
+            return None
+        
+        # 1. 列表格式: ["ans1", "ans2", "ans3"]
+        if isinstance(security, list):
+            idx = int(q_num) - 1
+            if 0 <= idx < len(security):
+                return str(security[idx])
+            return None
+
+        # 2. 字典格式
+        if isinstance(security, dict):
+            # 极简键格式: {"1": "ans1", "2": "ans2"} 或 {1: "ans1", 2: "ans2"}
+            if q_num in security:
+                val = security[q_num]
+                return str(val.get('a', '')) if isinstance(val, dict) else str(val)
+            if q_num.isdigit() and int(q_num) in security:
+                val = security[int(q_num)]
+                return str(val.get('a', '')) if isinstance(val, dict) else str(val)
+            
+            # 旧版嵌套键格式: {"1_quest": {"a": "ans1"}} 或 {"1_quest": "ans1"}
+            config_key = f"{q_num}_quest"
+            if config_key in security:
+                val = security[config_key]
+                return str(val.get('a', '')) if isinstance(val, dict) else str(val)
+
+        return None
+
+    @on(ele="xpath://input[starts-with(@id, 'kba') and contains(@id, '_response')]", priority=45)
+    def handle_kba_security_questions(self):
+        self.log("[State] Security question verification detected. Filling in answers...")
+        security = self.plugin.free_config.get('security')
+        answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
+        
+        if not security:
+            save_screenshot(self.page, self.plugin.instance_id, "kba_security_missing", logger=self.log)
+            err_msg = "美签登录触发了 KBA 密保问题验证,但在 free_config 中未配置 'security' 答案,无法继续登录。"
+            self.log(f"[ERROR] {err_msg}", level="error")
+            raise BizLogicError(err_msg)
+
+        for ans_ele in answer_eles:
+            ele_id = ans_ele.attr('id')
+            match = re.search(r'kba(\d+)_response', ele_id)
+            if match:
+                q_num = match.group(1)
+                ans_text = self._extract_security_answer(security, q_num)
+                if ans_text is None:
+                    save_screenshot(self.page, self.plugin.instance_id, f"kba_q{q_num}_missing", logger=self.log)
+                    err_msg = f"美签登录触发了第 {q_num} 道密保问题,但配置中未提供对应答案(当前配置: {security})。"
+                    self.log(f"[ERROR] {err_msg}", level="error")
+                    raise BizLogicError(err_msg)
+                
+                self.plugin.mouse.human_click_ele(ans_ele)
+                ans_ele.clear()
+                self.plugin.keyboard.type_text(ans_text, humanize=True)
+                self.log(f"-> Found input {ele_id}, successfully filled in answer for question {q_num}.")
+
+        continue_btn = self.page.ele('#continue')
+        if continue_btn:
+            self.plugin.mouse.human_click_ele(continue_btn)
+        self.log("Security answers submitted. Waiting for redirection...")
+        self.plugin._random_sleep(30, 40)
+
+    @on(ele="#continue_application", priority=30)
+    def handle_continue_application(self):
+        self.log("Found '#continue_application' (安排预约), clicking to proceed...")
+        schedule_btn = self.page.ele('#continue_application')
+        if schedule_btn:
+            self.plugin.mouse.human_click_ele(schedule_btn)
+        self.plugin._random_sleep(15, 25)
+
+    @on(ele="#atlas-sidebar", priority=35)
+    def handle_dashboard_sidebar(self):
+        self.log("[State] At the main booking dashboard. Looking for navigation button...")
+
+        # 1. 优先检查继续/安排预约按钮 (#continue_application)
+        continue_btn = self.page.ele('#continue_application', timeout=0.5)
+        if continue_btn:
+            self.log("Found '#continue_application' (安排预约), clicking to proceed...")
+            self.plugin.mouse.human_click_ele(continue_btn)
+            self.plugin._random_sleep(15, 25)
+            return
+
+        # 2. 检查重新安排预约按钮 (#reschedule_appointment)
+        reschedule_btn = self.page.ele('#reschedule_appointment', timeout=0.5)
+        if reschedule_btn:
+            self.log("Currently in rescheduling mode ('#reschedule_appointment'), clicking to proceed...")
+            self.plugin.mouse.human_click_ele(reschedule_btn)
+            self.plugin._random_sleep(15, 25)
+            return
+
+        # 3. 检查首次预约按钮 (#schedule_appointment)
+        schedule_btn = self.page.ele('#schedule_appointment', timeout=0.5)
+        if schedule_btn:
+            self.log("Currently in first-time booking mode ('#schedule_appointment'), clicking to proceed...")
+            self.plugin.mouse.human_click_ele(schedule_btn)
+            self.plugin._random_sleep(15, 25)
+            return
+
+        # 4. 检查动态注入的 admin_link 安排预约
+        admin_link = self.page.ele('#admin_link', timeout=0.5)
+        if admin_link:
+            self.log("Found '#admin_link' (安排预约), clicking to proceed...")
+            self.plugin.mouse.human_click_ele(admin_link)
+            self.plugin._random_sleep(15, 25)
+            return
+
+        # 5. 兜底匹配侧边栏内部包含 href='/schedule/' 或文本为 '安排预约' 的链接
+        fallback_link = (
+            self.page.ele('css:#atlas-sidebar a[href*="schedule"]', timeout=0.5)
+            or self.page.ele('xpath://*[@id="atlas-sidebar"]//a[contains(text(), "安排预约") or contains(text(), "Schedule")]', timeout=0.5)
+        )
+        if fallback_link:
+            self.log(f"Found sidebar booking link (text='{fallback_link.text}'), clicking to proceed...")
+            self.plugin.mouse.human_click_ele(fallback_link)
+            self.plugin._random_sleep(15, 25)
+            return
+
+        self.log("Not found schedule or reschedule button. The page may still be loading...")
+        time.sleep(2)
+
+    # --- 成功终态到达 (Priority 10) ---
+    @on(ele="#post_select", priority=10)
+    @done
+    def on_reached_slot_search_page(self):
+        self.plugin.session_create_time = time.time()
+        self.log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")
 
 
 
 
 class UsaPlugin(IVSPlg):
 class UsaPlugin(IVSPlg):
@@ -49,6 +261,8 @@ class UsaPlugin(IVSPlg):
     description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)"
     description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)"
     
     
     LOCATIONS = {
     LOCATIONS = {
+        "BEIJING": {"name": "BEIJING", "id": "106bf614-b0db-ec11-a7b4-001dd80234f6"},
+        "GUANGZHOU": {"name": "GUANGZHOU", "id": "a26af614-b0db-ec11-a7b4-001dd80234f6"},
         "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
         "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
         "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
         "WUHAN": {"name": "WUHAN", "id": "7b6af614-b0db-ec11-a7b4-001dd80234f6"},
         "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
         "SHENYANG": {"name": "SHENYANG", "id": "0f6bf614-b0db-ec11-a7b4-001dd80234f6"},
@@ -89,11 +303,6 @@ class UsaPlugin(IVSPlg):
         self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
         self._log(f"Anti-Rate-Limit: Sleeping for {sleep_time:.2f} seconds...")
         time.sleep(sleep_time)
         time.sleep(sleep_time)
 
 
-    def _get_free_port(self):
-        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-            s.bind(('', 0))
-            return s.getsockname()[1]
-
     def set_config(self, config: VSPlgConfig):
     def set_config(self, config: VSPlgConfig):
         """设置 API 的配置信息"""
         """设置 API 的配置信息"""
         self.config = config
         self.config = config
@@ -121,108 +330,25 @@ class UsaPlugin(IVSPlg):
             current_time = time.time()
             current_time = time.time()
             elapsed_time = current_time - self.session_create_time
             elapsed_time = current_time - self.session_create_time
             if elapsed_time > self.config.session_max_life:
             if elapsed_time > self.config.session_max_life:
-                self._log(f"Session expired.")
+                self._log("Session expired.")
                 return False
                 return False
         return True
         return True
-    
-    def _save_screenshot(self, name_prefix):
-        try:
-            timestamp = int(time.time())
-            filename = f"{self.instance_id}_{name_prefix}_{timestamp}.jpg"
-            save_path = os.path.join("data", filename)
-            os.makedirs("data", exist_ok=True)
-            self.page.get_screenshot(path=save_path, full_page=False)
-            self._log(f"Screenshot saved to {save_path}")
-        except Exception as e:
-            self._log(f"Failed to save screenshot: {e}")
 
 
     def create_session(self) -> None:
     def create_session(self) -> None:
         """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
         """创建一个新的会话 (包含初始化浏览器、过CF验证和执行登录)"""
-        
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._log(f"Initializing Session (ID: {self.instance_id})...")
-
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0))
-                return s.getsockname()[1]
-        
-        co = ChromiumOptions()
-        debug_port = get_free_port()
-        self._log(f"Assigned Debug Port: {debug_port}")
-        self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
-        
-        co.set_local_port(debug_port)       
-        co.set_user_data_path(self.user_data_path)
-        
-        chrome_path = configure.CHROME_PATH
-        if not chrome_path:
-            chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-        
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Proxy Tunnel for {p.ip}...")
-                exit_node = {
-                    "name": "ExitNode",
-                    "type": p.proto,
-                    "server": p.ip,
-                    "port": p.port,
-                    "username": p.username,
-                    "password": p.password
-                }
-                relay_node = None
-                if configure.MIHOMO_RELAY_NODES:
-                    relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
-                mihomo_path = configure.MIHOMO_BIN_PATH
-                if not mihomo_path:
-                    mihomo_path = os.getenv("MIHOMO_BIN")
-                if not mihomo_path:
-                    raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
-                self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
-
-        specific_fp = FingerprintGenerator().generate(self.config.account.username)
-        fp_seed = specific_fp.get("seed")
-        fp_platform = specific_fp.get("platform")
-        fp_brand = specific_fp.get("brand")
-        self._log(f'browser fingerprint seed={fp_seed}')
-        
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-dev-shm-usage')
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
-        co.set_argument(f"--fingerprint={fp_seed}")
-        co.set_argument(f"--fingerprint-platform={fp_platform}")
-        co.set_argument(f"--fingerprint-brand={fp_brand}")
-        
+        self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id if self.config and self.config.proxy else 'None'}")
+
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         self.page = ChromiumPage(co)
         self.page = ChromiumPage(co)
-        # 获取基础 URL
-        usa_url = self.free_config.get('usa_url', '') 
-        self._log(f"Navigating: {usa_url}")
-        self.page.get(usa_url)
-        self._random_sleep(3, 5)
-        
-        if 'Attention Required! | Cloudflare' in self.page.title and 'Sorry, you have been blocked' in self.page.html:
-            self._log(f'Block by cloudflare, try refresh...')
-            self.page.refresh()
-            self.page.wait.doc_loaded()
-        
-        cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
-        if not cf_bypasser.bypass(max_retry=6):
-            raise BizLogicError("Cloudflare bypass timeout")
-        self._random_sleep(3, 5) 
-        cf_bypasser.handle_waiting_room()
-        
+
         self._log("Init humanize tools...")
         self._log("Init humanize tools...")
         self.mouse = HumanMouse(self.page, debug=False)
         self.mouse = HumanMouse(self.page, debug=False)
         self.keyboard = HumanKeyboard(self.page)
         self.keyboard = HumanKeyboard(self.page)
@@ -232,218 +358,138 @@ class UsaPlugin(IVSPlg):
         init_x = random.randint(10, viewport_width - 10)
         init_x = random.randint(10, viewport_width - 10)
         init_y = random.randint(10, viewport_height - 10)
         init_y = random.randint(10, viewport_height - 10)
         self.mouse.move(init_x, init_y) 
         self.mouse.move(init_x, init_y) 
-        
-        username = self.config.account.username
-        password = self.config.account.password
-        security = self.free_config.get('security', {})
-
-        max_steps = 15 # 由于状态多,步数可以稍微调大一点
-        stuck_counter = 0
-        last_url = ""
-        session_created = False
-        has_submitted_login = False
-        
-        for step in range(max_steps):
-            self.page.wait.doc_loaded()
-            time.sleep(1) # 这个用于等待页面DOM渲染,保留短时,因为不是发请求
-            
-            current_url = self.page.url
-            current_title = self.page.title.lower()
-            current_html_content = self.page.html
-            self._log(f"--- [Router Step {step+1}] Current URL: {current_url} ---")
-            
-            # --- [异常处理层] ---
-            if current_url == last_url:
-                stuck_counter += 1
-            else:
-                last_url = current_url
-                stuck_counter = 0
-            if stuck_counter >= 3:
-                self._log("[WARN] Page stucked, try to refresh...")
-                self.page.refresh()
-                self._random_sleep(30, 40)
-                stuck_counter = 0
-                continue
-            
-            # 网络出现故障,直接重试
-            server_error_indicators = ["502 Bad Gateway", "503 Service Temporarily Unavailable"]
-            if any(err in current_html_content for err in server_error_indicators):
-                self._log(f"[WARN] Server network error, try to refresh (Step: {step})...")
-                self.page.refresh()
-                self._random_sleep(30, 40)
-                continue
-            
-            cloudflare_blocked_indicators = [
-                "Sorry, you have been blocked" in current_html_content,
-                "You are being rate limited" in current_html_content,
-                "Cloudflare Ray ID" in current_html_content
-            ]
-            if any(cloudflare_blocked_indicators):
-                raise BizLogicError(message="Blocked by Cloudflare WAF. Need to change IP or browser fingerprint.")
-            
-            # 遇到五秒盾先绕盾
-            if "just a moment" in current_title:
-                if not cf_bypasser.bypass(max_retry=3):
-                    continue
-                self._random_sleep(3, 5)
-                cf_bypasser.handle_waiting_room()
-                continue
-            
-            if self.page.ele('#post_select', timeout=1):
-                self._log("🎉 Successfully reached the Slot Search page (Target Page). Session created successfully!")                
-                self.session_create_time = time.time()
-                session_created = True
-                break
-
-            # 状态 2: 密保问题页面
-            elif self.page.ele('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]', timeout=1):
-                self._log("[State] Security question verification detected. Filling in answers...")
-                answer_eles = self.page.eles('xpath://input[starts-with(@id, "kba") and contains(@id, "_response")]')
-                for ans_ele in answer_eles:
-                    ele_id = ans_ele.attr('id')
-                    match = re.search(r'kba(\d+)_response', ele_id)
-                    if match:
-                        q_num = match.group(1)
-                        config_key = f"{q_num}_quest"
-                        q_data = security.get(config_key)
-                        ans_text = q_data.get('a')
-                        self.mouse.human_click_ele(ans_ele)
-                        self.keyboard.type_text(ans_text, humanize=True)
-                        self._log(f"-> Find input {ele_id}, successfully filled in the answer for question {q_num}.")
-                        
-                continue_btn = self.page.ele('#continue')
-                self.mouse.human_click_ele(continue_btn)
-                self._log("Security answers submitted. Waiting for redirection...")
-                self._random_sleep(30, 40) 
-                continue
-
-            # 状态 1: 登录页面
-            elif self.page.ele('#signInName', timeout=1):
-                self._log("[State] Login page detected. Submitting credentials...")
-                username_selector = '#signInName'
-                username_input = self.page.ele(username_selector)
-                self.mouse.human_click_ele(username_input)
-                username_input.clear()
-                self.keyboard.type_text(username, humanize=True)
-                self._random_sleep(3, 5) 
-                
-                password_selector = '#password'
-                password_input = self.page.ele(password_selector)
-                self.mouse.human_click_ele(password_input)
-                password_input.clear()
-                self.keyboard.type_text(password, humanize=True)
-                self._random_sleep(3, 5) 
-                
-                continue_btn_selector = '#continue'
-                continue_btn = self.page.ele(continue_btn_selector)
-                self.mouse.human_click_ele(continue_btn)                
-                has_submitted_login = True
-                self._log("Login form submitted. Waiting for the next step to load...")
-                self._random_sleep(30, 40)
-                continue
-            
-            elif self.page.ele('#continue_application', timeout=1):
-                schedule_btn = self.page.ele('#continue_application', timeout=0.5)
-                self._log("Currently in first-time booking mode, clicking to proceed...")
-                self.mouse.human_click_ele(schedule_btn)
-                self._random_sleep(30, 40)
-            
 
 
-            # 状态 3: 预约主页(控制台) -> 选择首签或改签
-            elif self.page.ele('#atlas-sidebar', timeout=1):
-                self._log("[State] At the main booking dashboard. Looking for navigation button...")
-                reschedule_btn_selector = '#reschedule_appointment'
-                schedule_btn_selector = '#schedule_appointment'
-                reschedule_btn = self.page.ele(reschedule_btn_selector, timeout=0.5)
-                if reschedule_btn:
-                    self._log("Currently in rescheduling mode, clicking to proceed...")
-                    self.mouse.human_click_ele(reschedule_btn)
-                    self._random_sleep(30, 40)
-                else:
-                    schedule_btn = self.page.ele(schedule_btn_selector, timeout=0.5)
-                    if schedule_btn:
-                        self._log("Currently in first-time booking mode, clicking to proceed...")
-                        self.mouse.human_click_ele(schedule_btn)
-                        self._random_sleep(30, 40)
-                    else:
-                        self._log("Not found schedule or reschedule button. The page may still be loading...")
-                        time.sleep(2)
-                continue
-
-            else:
-                self._log("[State] In unknown or transitional state. Waiting for next polling cycle...")
-                time.sleep(2)
-                
-        if not session_created:
-            raise BizLogicError(f"Failed to reach appointment-booking after {max_steps} navigation steps. Stuck at: {self.page.url}")
+        usa_url = self.free_config.get('usa_url', '') 
+        if usa_url:
+            self._log(f"Navigating: {usa_url}")
+            self.page.get(usa_url)
+
+        # 启动 UsaLoginFlow 注解流状态机
+        login_flow = UsaLoginFlow(
+            self.page, 
+            plugin=self, 
+            interval=1.0
+        )
+        login_flow.run(max_steps=100, timeout=600.0)
+        self.session_create_time = time.time()
+        self._log("🎉 UsaLoginFlow completed successfully. Session created.")
 
 
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
         """查询可用的签证预约信息"""
         """查询可用的签证预约信息"""
         self._log("Querying available slots...")
         self._log("Querying available slots...")
         res = VSQueryResult()
         res = VSQueryResult()
         res.success = False
         res.success = False
-        
-        self.page.refresh()
-        
-        if "just a moment" in self.page.title:
-            cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
+
+        current_url = (getattr(self.page, "url", "") or "").lower()
+        if "schedule" not in current_url:
+            self._log(f"Current url '{current_url}' not on schedule page, navigating...")
+            schedule_url = f"{self.free_config.get('usa_url', 'https://www.usvisascheduling.com').rstrip('/')}/zh-CN/schedule/"
+            self.page.get(schedule_url)
+            self._random_sleep(3, 5)
+        else:
+            self._log("Already on schedule page, waiting for dynamic elements to finish loading...")
+
+        if "just a moment" in (getattr(self.page, "title", "") or "").lower():
+            cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug if self.config else False, logger=self._log)
             if not cf_bypasser.bypass(max_retry=5):
             if not cf_bypasser.bypass(max_retry=5):
                 raise BizLogicError("Cloudflare bypass timeout")
                 raise BizLogicError("Cloudflare bypass timeout")
             self._random_sleep(3, 5)
             self._random_sleep(3, 5)
             cf_bypasser.handle_waiting_room()
             cf_bypasser.handle_waiting_room()
-        
-        current_url = self.page.url.lower()
+
+        current_url = (getattr(self.page, "url", "") or "").lower()
         if 'auth' in current_url or 'login' in current_url:
         if 'auth' in current_url or 'login' in current_url:
             self.is_healthy = False
             self.is_healthy = False
             raise SessionExpiredOrInvalidError()
             raise SessionExpiredOrInvalidError()
-        
-        applicant = self.free_config.get('applicant')
-        location_name = self.free_config.get('location')
-        location_id = self.LOCATIONS.get(location_name.upper(), {}).get('id')
 
 
-        # 2. 等待页面元素
-        self.page.ele(f"xpath://label[text()='{applicant}']", timeout=60)
-        post_select = self.page.ele('#post_select', timeout=60)
-        
-        # ==================== 新增:网络监听逻辑 ====================
-        
+        # 1. 等待申请人列表加载(从 page1 空列表异步加载到 page2)
+        self._log("Waiting for applicant list (#gm_select) to populate...")
+        self.page.ele("css:#gm_select label", timeout=30)
+
+        # 2. 等待领事馆下拉框选项加载完成(从 page1 仅空 option 异步加载到 page2 包含各领事馆 option)
+        self._log("Waiting for consular post options to populate in #post_select...")
+        post_select = self.page.ele('#post_select', timeout=30)
+        if not post_select:
+            raise BizLogicError("Element #post_select not found.")
+
+        # 等待至少出现一个有效选项
+        self.page.ele("css:#post_select option:not([value=''])", timeout=30)
+
+        # 获取所有已加载的领事馆 options
+        all_options = post_select.eles("tag:option")
+        available_options = [opt for opt in all_options if (getattr(opt, "attrs", {}).get("value") or "").strip()]
+        opts_summary = [f"{opt.text} ({getattr(opt, 'attrs', {}).get('value')})" for opt in available_options]
+        self._log(f"Available consular posts: {opts_summary}")
+
+        # 3. 匹配目标领事馆
+        location_name = (self.free_config.get('location') or "").strip()
+        matched_id = None
+
+        # 策略 A: 优先检查 LOCATIONS 字典
+        known_info = self.LOCATIONS.get(location_name.upper())
+        if known_info:
+            target_id = known_info["id"]
+            if any(opt.attrs.get("value") == target_id for opt in available_options):
+                matched_id = target_id
+
+        # 策略 B: 按文本包含匹配(例如 "GUANGZHOU" 或 "广州")
+        if not matched_id:
+            for opt in available_options:
+                opt_text = (getattr(opt, "text", "") or "").upper()
+                if location_name.upper() in opt_text:
+                    matched_id = opt.attrs.get("value")
+                    break
+
+        # 策略 C: 针对当前申请锁定特定城市(如账号当前仅有广州选项)自适应兜底
+        if not matched_id and available_options:
+            fallback_opt = available_options[0]
+            matched_id = fallback_opt.attrs.get("value")
+            self._log(f"[WARN] Configured location '{location_name}' not available. Auto-selecting active consular post: '{fallback_opt.text}' ({matched_id})")
+
+        if not matched_id:
+            raise BizLogicError(f"No matching consular post found for location '{location_name}'. Available: {[opt.text for opt in available_options]}")
+
         # 开启监听目标 API
         # 开启监听目标 API
         target_api = 'get-family-consular-schedule-days'
         target_api = 'get-family-consular-schedule-days'
         self.page.listen.start(target_api)
         self.page.listen.start(target_api)
-        
-        # 3. 选择领事馆 (此操作会触发上述 API 的 AJAX 请求)
-        self.page.ele(f"xpath://select[@id='post_select']/option[@value='{location_id}']", timeout=60)
-        post_select.select.by_value(location_id) 
-        
-        # 4. 等待拦截 API 响应 (设置超时时间)
+
+        # 4. 选择领事馆并触发 change 事件 (此操作会触发上述 API 的 AJAX 请求)
+        self._log(f"Selecting consular post ID: {matched_id}...")
+        post_select.select.by_value(matched_id)
+        try:
+            self.page.run_js('$("#post_select").val(arguments[0]).trigger("change");', matched_id)
+        except Exception as e:
+            self._log(f"[DEBUG] Triggering change event via JS: {e}")
+
+        # 5. 等待拦截 API 响应 (设置超时时间)
         self._log("Waiting for schedule dates API response...")
         self._log("Waiting for schedule dates API response...")
         packet = self.page.listen.wait(timeout=30)
         packet = self.page.listen.wait(timeout=30)
         self.page.listen.stop()
         self.page.listen.stop()
-        
+
         if not packet:
         if not packet:
             raise BizLogicError("Timeout waiting for schedule API response")
             raise BizLogicError("Timeout waiting for schedule API response")
-            
+
         status_code = packet.response.status
         status_code = packet.response.status
-        raw_resp = packet.response.raw_body
+        body = packet.response.body
+        if isinstance(body, bytes):
+            body = body.decode("utf-8", errors="ignore")
         self._log(f"API Response Status: {status_code}")
         self._log(f"API Response Status: {status_code}")
-        
+
         # 处理 HTTP 返回码不是200的情况
         # 处理 HTTP 返回码不是200的情况
         if status_code != 200:
         if status_code != 200:
+            err_text = str(body)[:512]
             if status_code == 403:
             if status_code == 403:
-                raise PermissionDeniedError(f"HTTP 403: {raw_resp[:512]}")
+                raise PermissionDeniedError(f"HTTP 403: {err_text}")
             if status_code == 429:
             if status_code == 429:
                 self.is_healthy = False
                 self.is_healthy = False
-                raise RateLimiteddError(f"HTTP 429: {raw_resp[:512]}")
-            raise BizLogicError(f"HTTP {status_code} error. resp={raw_resp[0:512]}")
+                raise RateLimiteddError(f"HTTP 429: {err_text}")
+            raise BizLogicError(f"HTTP {status_code} error. resp={err_text}")
 
 
-        # 5. 解析返回的数据
+        # 6. 解析返回的数据
         available_dates = []
         available_dates = []
-        match = re.search(r'(\{.*\})', raw_resp, re.DOTALL)
-        if match:
-            json_str = match.group(1)
-            data = json.loads(json_str)
-        else:
-            data = json.loads(raw_resp)
+        data = body if isinstance(body, dict) else None
+        if not data:
+            match = re.search(r'(\{.*\})', str(body), re.DOTALL)
+            data = json.loads(match.group(1)) if match else json.loads(str(body))
 
 
         schedule_days = data.get("ScheduleDays", [])
         schedule_days = data.get("ScheduleDays", [])
         if schedule_days:
         if schedule_days:
@@ -452,11 +498,9 @@ class UsaPlugin(IVSPlg):
                 if date_str:
                 if date_str:
                     available_dates.append(date_str)
                     available_dates.append(date_str)
 
 
-        # 6. 处理最终结果 (保持与你原有返回结构一致)
+        # 6. 处理最终结果
         if available_dates:
         if available_dates:
-            # 确保日期是有序的
             available_dates.sort()
             available_dates.sort()
-            
             res.success = True
             res.success = True
             res.availability_status = AvailabilityStatus.Available
             res.availability_status = AvailabilityStatus.Available
             earliest_date = available_dates[0]
             earliest_date = available_dates[0]
@@ -481,12 +525,12 @@ class UsaPlugin(IVSPlg):
         exp_start = user_inputs.get('expected_date_start', '')
         exp_start = user_inputs.get('expected_date_start', '')
         exp_end = user_inputs.get('expected_date_end', '')
         exp_end = user_inputs.get('expected_date_end', '')
 
 
-        available_dates_str =[
+        available_dates_str = [
             da.date.strftime("%Y-%m-%d")
             da.date.strftime("%Y-%m-%d")
             for da in slot_info.availability if da.date
             for da in slot_info.availability if da.date
         ]
         ]
         
         
-        valid_dates_list = self._filter_dates(available_dates_str, exp_start, exp_end)
+        valid_dates_list = filter_dates_in_range(available_dates_str, exp_start, exp_end, shuffle=True)
         if not valid_dates_list:
         if not valid_dates_list:
             raise NotFoundError(message="No dates match user constraints")
             raise NotFoundError(message="No dates match user constraints")
         
         
@@ -519,7 +563,7 @@ class UsaPlugin(IVSPlg):
         
         
         target_date_cell = self.page.ele(target_cell_selector, timeout=10)
         target_date_cell = self.page.ele(target_cell_selector, timeout=10)
         if not target_date_cell:
         if not target_date_cell:
-             raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.")
+            raise BizLogicError(f"Target date element not found for {selected_slot_date} after navigating.")
              
              
         self.mouse.human_click_ele(target_date_cell)
         self.mouse.human_click_ele(target_date_cell)
         
         
@@ -551,48 +595,15 @@ class UsaPlugin(IVSPlg):
         res.book_time = selected_slot_time
         res.book_time = selected_slot_time
         res.account = self.config.account.username
         res.account = self.config.account.username
         return res
         return res
-            
-    def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
-        if not start_str or not end_str:
-            return dates
-        valid_dates = []
-        s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
-        e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
-        for date_str in dates:
-            curr_date = datetime.strptime(date_str, "%Y-%m-%d")
-            if s_date <= curr_date <= e_date:
-                valid_dates.append(date_str)
-        random.shuffle(valid_dates)
-        return valid_dates
-    
-    # --- 资源清理核心方法 ---
+
     def cleanup(self):
     def cleanup(self):
-        """
-        销毁浏览器并彻底删除临时文件
-        """
-        if self.page:
-            try:
-                self.page.quit(force=True)
-            except Exception:
-                pass
-            self.page = None
-        
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try:
-                    time.sleep(0.2)
-                    shutil.rmtree(self.root_workspace, ignore_errors=True)
-                    break
-                except Exception as e:
-                    self._log(f"Cleanup retry: {e}")
-                    time.sleep(0.5)
-            
-            if os.path.exists(self.root_workspace):
-                 self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        if getattr(self, "keep_browser_on_error", False):
+            self._log("[DEBUG] keep_browser_on_error 生效,跳过浏览器清理并保留窗口供分析。")
+            return
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
         
         
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""
@@ -604,7 +615,7 @@ class UsaPlugin(IVSPlg):
             except Exception:
             except Exception:
                 pass
                 pass
 
 
-        session_age = int(time.time() - self.session_create_time) if hasattr(self, "session_create_time") and self.session_create_time > 0 else 0
+        session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
         state = "running" if self.is_healthy else "unhealthy"
         state = "running" if self.is_healthy else "unhealthy"
 
 
         return PluginStatus(
         return PluginStatus(

+ 101 - 295
plugins/vfs_plugin.py

@@ -6,9 +6,7 @@ import json
 import random
 import random
 import base64
 import base64
 import uuid
 import uuid
-import shutil
 import re
 import re
-import socket
 import urllib.parse
 import urllib.parse
 from datetime import datetime
 from datetime import datetime
 from typing import Dict, Any, Optional, List, Tuple, Callable
 from typing import Dict, Any, Optional, List, Tuple, Callable
@@ -18,12 +16,24 @@ from cryptography.hazmat.primitives import serialization, hashes
 from cryptography.hazmat.primitives.asymmetric import padding
 from cryptography.hazmat.primitives.asymmetric import padding
 from cryptography.hazmat.backends import default_backend
 from cryptography.hazmat.backends import default_backend
 
 
-import configure
 from vs_plg import IVSPlg 
 from vs_plg import IVSPlg 
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
+from vs_types import (
+    VSPlgConfig,
+    AppointmentType,
+    VSQueryResult,
+    VSBookResult,
+    DateAvailability,
+    AvailabilityStatus,
+    NotFoundError,
+    PermissionDeniedError,
+    RateLimiteddError,
+    SessionExpiredOrInvalidError,
+    BizLogicError,
+    PluginStatus,
+    utc_now_str
+)
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.vs_cloud_api import VSCloudApi
-from toolkit.mihomo_tunnel import MihomoTunnel
-from toolkit.captcha_breaker import recognize_vfs_captcha_with_qwen
+from toolkit.captcha_breaker import CaptchaBreaker, CaptchaBreakerError
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 
 
 
 
@@ -89,29 +99,15 @@ def get_alias_email(email: str, new_domain: str = "text.skin") -> str:
     local_part, _ = email.rsplit("@", 1)
     local_part, _ = email.rsplit("@", 1)
     return f"{local_part}@{new_domain}"
     return f"{local_part}@{new_domain}"
 
 
-# --- 模拟 Requests Response 对象 ---
-class BrowserResponse:
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-        self._json = None
-
-    def json(self):
-        if self._json is None:
-            if not self.text:
-                return {}
-            try:
-                self._json = json.loads(self.text)
-            except:
-                self._json = {}
-        return self._json
+from utils.plugin_utils import (
+    BrowserResponse,
+    init_chromium_options,
+    perform_browser_fetch,
+    filter_dates_in_range,
+    handle_cookie_consent,
+    cleanup_browser_workspace
+)
 
 
-    @property
-    def content(self):
-        return self.text.encode('utf-8')
 
 
 class VfsPlugin(IVSPlg):
 class VfsPlugin(IVSPlg):
     name = "vfs_plugin"
     name = "vfs_plugin"
@@ -151,6 +147,7 @@ class VfsPlugin(IVSPlg):
             
             
         self.tunnel = None
         self.tunnel = None
         self.session_create_time: float = 0
         self.session_create_time: float = 0
+        self.captcha_breaker = CaptchaBreaker()
 
 
     def set_config(self, config: VSPlgConfig):
     def set_config(self, config: VSPlgConfig):
         self.config = config
         self.config = config
@@ -206,62 +203,14 @@ class VfsPlugin(IVSPlg):
         3. 自动过盾并提取 Token (集成 CloudflareBypasser)
         3. 自动过盾并提取 Token (集成 CloudflareBypasser)
         4. JS fetch 登录
         4. JS fetch 登录
         """
         """
-        self._log(f"Initializing Session (ID: {self.instance_id})...")
-        co = ChromiumOptions()
-        
-        def get_free_port():
-            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-                s.bind(('', 0))
-                return s.getsockname()[1]
-        
-        debug_port = get_free_port()
-        self._log(f"Assigned Debug Port: {debug_port}")
-        self._log(f"Account id={self.config.account.id}, proxy id={self.config.proxy.id}")
-        co.set_local_port(debug_port)
-        co.set_user_data_path(self.user_data_path)
-        
-        chrome_path = configure.CHROME_PATH
-        if not chrome_path:
-            chrome_path = os.getenv("CHROME_BIN")
-        if chrome_path and os.path.exists(chrome_path):
-            co.set_paths(browser_path=chrome_path)
-        
-        if self.config.proxy and self.config.proxy.ip:
-            p = self.config.proxy
-            if p.username and p.password:
-                self._log(f"Starting Proxy Tunnel for {p.ip}...")
-                exit_node = {
-                    "name": "ExitNode",
-                    "type": p.proto,
-                    "server": p.ip,
-                    "port": p.port,
-                    "username": p.username,
-                    "password": p.password
-                }
-                relay_node = None
-                if configure.MIHOMO_RELAY_NODES:
-                    relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
-                mihomo_path = configure.MIHOMO_BIN_PATH
-                if not mihomo_path:
-                    mihomo_path = os.getenv("MIHOMO_BIN")
-                if not mihomo_path:
-                    raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
-                self.tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
-                local_proxy = self.tunnel.start()
-                self._log(f"Tunnel started at {local_proxy}")
-                co.set_argument(f'--proxy-server={local_proxy}')
-            else:
-                proxy_str = f"{p.proto}://{p.ip}:{p.port}"
-                co.set_argument(f'--proxy-server={proxy_str}')
-        else:
-            self._log("[WARN] No proxy configured!")
-            
-        co.headless(False) 
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-gpu')
-        co.set_argument('--disable-dev-shm-usage') 
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
+        co, self.tunnel = init_chromium_options(
+            user_data_path=self.user_data_path,
+            username_seed=self.config.account.username if self.config and self.config.account else None,
+            proxy=self.config.proxy if self.config else None,
+            headless=False,
+            window_size="1920,1080",
+            logger=self._log
+        )
         self.page = ChromiumPage(co)
         self.page = ChromiumPage(co)
         mission = self.free_config.get("mission_code", "")
         mission = self.free_config.get("mission_code", "")
         country = self.free_config.get("country_code", "")
         country = self.free_config.get("country_code", "")
@@ -286,43 +235,10 @@ class VfsPlugin(IVSPlg):
         time.sleep(random.uniform(3, 5))
         time.sleep(random.uniform(3, 5))
         cf_bypasser.handle_waiting_room()
         cf_bypasser.handle_waiting_room()
         
         
-        cf_token = ""
-        form_logged = False
-        for i in range(40):
-            time.sleep(1)
-            self._handle_cookie_banner()
-            try:
-                ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
-                if ele and ele.value:
-                    cf_token = ele.value
-                    self._log("Cloudflare Turnstile token extracted.")
-                    break
-            except:
-                pass
-            
-            if i > 2:
-                try:
-                    use_dfs = False
-                    cf_bypasser.click_verification_button(use_dfs)
-                except Exception as e:
-                    pass
-            
-            if self.page.ele('tag:form', timeout=0.5) or self.page.ele('#mat-input-0', timeout=0.5):
-                if not form_logged:
-                    self._log("Login form detected.")
-                    form_logged = True
-                if i > 10 and not cf_token and not form_logged:
-                    self._log("Form visible but token not found yet...")
-
-        if not cf_token:
-            try:
-                cf_token = self.page.ele('@name=cf-turnstile-response').value
-            except:
-                pass
-        
+        cf_token = self._extract_turnstile_token(timeout_sec=40, reset_first=False)
         if not cf_token:
         if not cf_token:
             self._log("[WARN] Could not extract Turnstile token.")
             self._log("[WARN] Could not extract Turnstile token.")
-            raise BizLogicError(f"Could not extract Turnstile token.")
+            raise BizLogicError("Could not extract Turnstile token.")
 
 
         email = self.config.account.username
         email = self.config.account.username
         password = self.config.account.password
         password = self.config.account.password
@@ -402,91 +318,35 @@ class VfsPlugin(IVSPlg):
         if not self.page:
         if not self.page:
             raise BizLogicError("Browser session not initialized")
             raise BizLogicError("Browser session not initialized")
 
 
-        req_url = url
-        if params:
-            sep = '&' if '?' in req_url else '?'
-            req_url += sep + urllib.parse.urlencode(params)
-
-        final_headers = headers or {}
-        
-        fetch_options = {
-            "method": method.upper(),
-            "headers": final_headers,
-            "credentials": "include" # 关键:带上浏览器 Cookie
-        }
-        
-        log_body = "None"
-
-        if json_data:
-            json_str = json.dumps(json_data)
-            fetch_options['body'] = json_str
-            fetch_options['headers']['Content-Type'] = 'application/json'
-            log_body = json_str
-        elif data:
-            if isinstance(data, dict):
-                encoded_data = urllib.parse.urlencode(data)
-                fetch_options['body'] = encoded_data
-                fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
-                log_body = encoded_data
-            else:
-                fetch_options['body'] = data
-                log_body = str(data)
-
         if self.config.debug:
         if self.config.debug:
-            self._log(f"┌── [TRAFFIC REQUEST] {method} {req_url}")
-            self._log(f"├── Headers: {json.dumps(final_headers)}")
-            self._log(f"└── Body: {log_body}")
+            self._log(f"┌── [TRAFFIC REQUEST] {method} {url}")
+            self._log(f"├── Headers: {json.dumps(headers or {})}")
+            self._log(f"└── Body: {json_data if json_data is not None else data}")
         else:
         else:
-            self._log(f"[TRAFFIC REQUEST] {method} {req_url}")
+            self._log(f"[TRAFFIC REQUEST] {method} {url}")
 
 
-        js_script = f"""
-        const url = "{req_url}";
-        const options = {json.dumps(fetch_options)};
-        
-        const startTime = Date.now();
-        
-        return fetch(url, options)
-            .then(async response => {{
-                const text = await response.text();
-                const headers = {{}};
-                response.headers.forEach((value, key) => headers[key] = value);
-                const endTime = Date.now();
-                
-                return {{
-                    status: response.status,
-                    body: text,
-                    headers: headers,
-                    url: response.url,
-                    duration: endTime - startTime
-                }};
-            }})
-            .catch(error => {{
-                return {{
-                    status: 0,
-                    body: error.toString(),
-                    headers: {{}},
-                    url: url,
-                    duration: Date.now() - startTime
-                }};
-            }});
-        """
-        
         try:
         try:
-            res_dict = self.page.run_js(js_script, timeout=60)
+            resp = perform_browser_fetch(
+                self.page, 
+                method=method, 
+                url=url, 
+                headers=headers, 
+                data=data, 
+                json_data=json_data, 
+                params=params, 
+                timeout=60
+            )
         except Exception as e:
         except Exception as e:
             self._log(f"[TRAFFIC ERROR] JS Execution failed: {e}")
             self._log(f"[TRAFFIC ERROR] JS Execution failed: {e}")
             raise BizLogicError(f"Browser JS Execution Error: {e}")
             raise BizLogicError(f"Browser JS Execution Error: {e}")
-
-        resp = BrowserResponse(res_dict)
         
         
-        duration = res_dict.get('duration', 0)
         resp_preview = resp.text[:1000] + "..." if len(resp.text) > 1000 else resp.text
         resp_preview = resp.text[:1000] + "..." if len(resp.text) > 1000 else resp.text
         
         
         if self.config.debug:
         if self.config.debug:
-            self._log(f"┌── [TRAFFIC RESPONSE] Status: {resp.status_code} | Time: {duration}ms")
+            self._log(f"┌── [TRAFFIC RESPONSE] Status: {resp.status_code}")
             self._log(f"└── Body: {resp_preview}")
             self._log(f"└── Body: {resp_preview}")
         else:
         else:
-            self._log(f"[TRAFFIC RESPONSE] {method} {req_url} -> Status: {resp.status_code} ({duration}ms)")
+            self._log(f"[TRAFFIC RESPONSE] {method} {url} -> Status: {resp.status_code}")
 
 
         if resp.status_code == 200:
         if resp.status_code == 200:
             return resp
             return resp
@@ -525,33 +385,6 @@ class VfsPlugin(IVSPlg):
             
             
             raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
             raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
 
 
-    def _handle_cookie_banner(self):
-        """
-        处理 OneTrust Cookie 遮挡
-        策略:尝试点击“接受所有”,如果点不到就直接移除 DOM
-        """
-        try:
-            js = """
-            try {
-                var acceptBtn = document.getElementById('onetrust-accept-btn-handler');
-                if (acceptBtn) {
-                    acceptBtn.click();
-                    return true;
-                }
-                
-                var banner = document.getElementById('onetrust-banner-sdk');
-                if (banner) {
-                    banner.style.display = 'none';
-                    banner.remove();
-                    return true;
-                }
-            } catch(e) {}
-            return false;
-            """
-            self.page.run_js(js)
-        except:
-            pass
-    
     def _get_realnetwork_ip(self):
     def _get_realnetwork_ip(self):
         """
         """
         通过新建标签页获取 IP
         通过新建标签页获取 IP
@@ -730,10 +563,14 @@ class VfsPlugin(IVSPlg):
                 self._log("OTP not found in text, trying LLM image recognition...")
                 self._log("OTP not found in text, trying LLM image recognition...")
                 target_image_b64 = image_urls[0]
                 target_image_b64 = image_urls[0]
                 
                 
-                otp_code = recognize_vfs_captcha_with_qwen(target_image_b64)
-                if otp_code:
-                    self._log(f"Successfully extracted OTP from image: {otp_code}")
-                    return otp_code
+                vfs_otp_prompt = "图片中有多组验证码,其中OTP箭头指向的验证码为真,其余为假。只输出真实验证码的内容,不要任何多余的汉字或标点符号。"
+                try:
+                    otp_code = self.captcha_breaker.break_captcha(target_image_b64, prompt=vfs_otp_prompt)
+                    if otp_code:
+                        self._log(f"Successfully extracted OTP from image: {otp_code}")
+                        return otp_code
+                except CaptchaBreakerError as e:
+                    self._log(f"LLM OTP extraction failed: {e}")
         raise BizLogicError(message="OTP code not found")
         raise BizLogicError(message="OTP code not found")
 
 
 
 
@@ -780,46 +617,54 @@ class VfsPlugin(IVSPlg):
         error_desc = resp_json.get("description", resp.text)
         error_desc = resp_json.get("description", resp.text)
         raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
         raise PermissionDeniedError(message=f"OTP Login Failed: {error_desc}")
     
     
-    def _refresh_turnstile_token(self) -> str:
+    def _extract_turnstile_token(self, timeout_sec: int = 40, reset_first: bool = False) -> str:
         """
         """
-        强制刷新 Cloudflare Turnstile 并获取新 Token (集成 CloudflareBypasser 版)
+        统一提取或重置刷新 Cloudflare Turnstile Token
         """
         """
-        self._log("Refreshing Cloudflare Turnstile token...")
-        
-        js_reset = """
-        try {
-            var input = document.querySelector('input[name="cf-turnstile-response"]');
-            if (input) input.value = "";
-            window.turnstile.reset(); 
-        } catch(e) {
-            console.log("Turnstile reset error:", e);
-        }
-        """
-        self.page.run_js(js_reset)
-        
+        if reset_first:
+            self._log("Resetting Cloudflare Turnstile...")
+            js_reset = """
+            try {
+                var input = document.querySelector('input[name="cf-turnstile-response"]');
+                if (input) input.value = "";
+                if (window.turnstile && window.turnstile.reset) {
+                    window.turnstile.reset();
+                }
+            } catch(e) {}
+            """
+            self.page.run_js(js_reset)
+
         cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
         cf_bypasser = CloudflareBypasser(self.page, log=self.config.debug)
+        total_cycles = int(timeout_sec * 2)
 
 
-        for i in range(60): 
+        for i in range(total_cycles):
             time.sleep(0.5)
             time.sleep(0.5)
-            
+            handle_cookie_consent(self.page, logger=self._log)
             try:
             try:
-                ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
+                ele = self.page.ele('@name=cf-turnstile-response', timeout=0.5)
                 if ele and ele.value:
                 if ele and ele.value:
-                    self._log("Turnstile token refreshed successfully.")
+                    self._log("Cloudflare Turnstile token extracted successfully.")
                     return ele.value
                     return ele.value
-            except:
+            except Exception:
                 pass
                 pass
-            
-            if i > 4: 
-                self._handle_cookie_banner()
-                
+
+            if i > 4:
                 try:
                 try:
-                    use_dfs = False
-                    cf_bypasser.click_verification_button(use_dfs)
-                except Exception as e:
+                    cf_bypasser.click_verification_button(is_dfs=False)
+                except Exception:
                     pass
                     pass
-        
-        raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
+
+        return ""
+
+    def _refresh_turnstile_token(self) -> str:
+        """
+        强制刷新 Cloudflare Turnstile 并获取新 Token
+        """
+        self._log("Refreshing Cloudflare Turnstile token...")
+        token = self._extract_turnstile_token(timeout_sec=30, reset_first=True)
+        if not token:
+            raise BizLogicError("Failed to refresh Cloudflare Turnstile token (Timeout)")
+        return token
 
 
     def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
     def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
         """
         """
@@ -927,7 +772,7 @@ class VfsPlugin(IVSPlg):
             
             
             for _ in range(3):
             for _ in range(3):
                 avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
                 avail_candidates = [d for d in list(all_ads) if d not in forbidden_dates]
-                sel_dates = self._filter_dates(avail_candidates, expected_start, expected_end)
+                sel_dates = filter_dates_in_range(avail_candidates, expected_start, expected_end, shuffle=True)
                 
                 
                 if not sel_dates:
                 if not sel_dates:
                     break
                     break
@@ -1362,22 +1207,6 @@ class VfsPlugin(IVSPlg):
         resp = self._perform_request("POST", url, headers=headers, json_data=data)
         resp = self._perform_request("POST", url, headers=headers, json_data=data)
         return resp.json().get("isConfirmed", False)
         return resp.json().get("isConfirmed", False)
 
 
-    def _filter_dates(self, dates: List[str], start_str: str, end_str: str) -> List[str]:
-        if not start_str or not end_str:
-            return dates
-        valid_dates = []
-        try:
-            s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
-            e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
-            for date_str in dates:
-                curr_date = datetime.strptime(date_str, "%Y-%m-%d")
-                if s_date <= curr_date <= e_date:
-                    valid_dates.append(date_str)
-            random.shuffle(valid_dates)
-            return valid_dates
-        except:
-            return dates
-
     def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
     def _get_filtered_covered_months(self, start_date, end_date, from_date) -> List[str]:
         fmt = "%Y-%m-%d"
         fmt = "%Y-%m-%d"
         try:
         try:
@@ -1405,33 +1234,10 @@ class VfsPlugin(IVSPlg):
         return months
         return months
     
     
     def cleanup(self):
     def cleanup(self):
-        """
-        销毁浏览器并彻底删除临时文件
-        """
-        if self.page:
-            try:
-                self.page.quit()
-            except Exception:
-                pass
-            self.page = None
-        
-        if os.path.exists(self.root_workspace):
-            for _ in range(3):
-                try:
-                    time.sleep(0.2)
-                    shutil.rmtree(self.root_workspace, ignore_errors=True)
-                    break
-                except Exception as e:
-                    self._log(f"Cleanup retry: {e}")
-                    time.sleep(0.5)
-            
-            if os.path.exists(self.root_workspace):
-                 self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
-                 
-        if self.tunnel:
-            try: self.tunnel.stop()
-            except: pass
-            self.tunnel = None
+        """销毁浏览器并彻底删除临时文件"""
+        cleanup_browser_workspace(self.page, self.root_workspace, self.tunnel, self._log)
+        self.page = None
+        self.tunnel = None
                  
                  
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         account_name = self.config.account.username if self.config and self.config.account else ""
         account_name = self.config.account.username if self.config and self.config.account else ""

+ 94 - 0
robotics (副本)/README.md

@@ -0,0 +1,94 @@
+# TLScontact 签证预约自动化系统 (DrissionPage 注解流驱动)
+
+本项目基于 **DrissionPage** 与 **声明式注解状态机(Annotation-Driven Flow)** 架构,专为 TLScontact 等复杂多步骤、带 Cloudflare 挑战与动态页面流转的签证预约场景设计。
+
+---
+
+## 🌟 核心特性
+
+1. **声明式注解架构**:
+   - `@on(url=..., title=..., ele=..., not_ele=..., priority=...)`:声明页面状态与触发动作。
+   - `@guard(...)`:高优先级异常守卫(处理 502/504、Cloudflare Challenge、Session 过期)。
+   - `@fatal(...)`:命中特定错误(如未添加申请人、账号锁定)时立即终止。
+   - `@done`:命中成功终态时自动提交并成功退出。
+2. **Cloudflare 自动穿透**:
+   - 自动识别 Cloudflare Turnstile / 5秒盾挑战,穿透 iframe 与 DOM 节点进行拟人化点击,带人工兜底。
+3. **开箱即用内置 Chromium**:
+   - 自动优先检测并加载项目目录自带的 `ungoogled-chromium-148.0.7778.215-1-x86_64_linux/chrome`,无需复杂安装。
+4. **内置 Mock 模拟测试**:
+   - 提供内置轻量 Mock 服务,一键进行全链路离线模拟测试,验证各状态转移与规则调度。
+5. **健壮防卡死自愈**:
+   - 内置步数扫描、停滞检测与页面自愈刷新机制。
+
+---
+
+## 📁 目录结构
+
+```
+.
+├── config.yaml          # 运行时主配置文件
+├── config.example.yaml  # 配置文件模板
+├── flow_annotated.py    # 注解流驱动核心引擎 (BaseFlow, @on, @guard, @done, @fatal)
+├── cf_bypasser.py       # Cloudflare Turnstile / 5秒盾自动绕过模块
+├── tls_flow.py          # TLScontact 业务流程状态机实现 (TlsContactFlow)
+├── mock_server.py       # 本地离线 Mock 服务端
+├── main.py              # 主程序命令行启动入口
+├── requirements.txt     # Python 依赖清单
+└── ungoogled-chromium-* # 内置免安装 Chromium 浏览器
+```
+
+---
+
+## 🚀 快速开始
+
+### 1. 安装依赖
+
+```bash
+pip install -r requirements.txt
+```
+
+### 2. 一键离线 Mock 模拟测试 (推荐优先尝试)
+
+无需配置真实账号或连接外部网络,运行本地模拟测试:
+
+```bash
+# 无头模式快速测试
+python main.py --mock --headless
+
+# 有头模式可视化测试 (观察浏览器真实点击与跳转)
+python main.py --mock
+```
+
+### 3. 正式生产环境运行
+
+编辑 `config.yaml` 填写您的实际信息:
+
+```yaml
+auth:
+  username: "your_email@example.com"
+  password: "your_secure_password"
+
+target:
+  url: "https://visas-de.tlscontact.com/visa/gb/gbLON2de/home"
+  login_url: "https://visas-de.tlscontact.com/visa/gb/gbLON2de/login"
+
+flow:
+  interval: 1.0
+  max_steps: 45
+  preferred_dates:
+    - "2026-09"
+```
+
+启动正式流程:
+
+```bash
+python main.py
+```
+
+### 4. 命令行参数支持
+
+- `--mock` / `--test`:启动本地 Mock 服务进行端到端测试。
+- `--headless`:强制使用无头模式运行。
+- `--config <path>`:指定自定义配置文件路径(默认 `config.yaml`)。
+- `--username <user>` / `--password <pwd>`:命令行覆盖账号密码。
+- `--url <url>`:命令行覆盖目标入口 URL。

+ 123 - 0
robotics (副本)/cf_bypasser.py

@@ -0,0 +1,123 @@
+"""
+cf_bypasser.py - Cloudflare Turnstile / 5秒盾 自动识别与穿透辅助工具
+支持 DrissionPage iframe / Shadow DOM 拟人化穿透与人工兜底机制
+"""
+
+import time
+from typing import Optional, Callable
+
+
+class CloudflareBypasser:
+    def __init__(self, page, logger=None, max_wait_sec: int = 15):
+        """
+        :param page: DrissionPage 的 ChromiumPage 实例
+        :param logger: 日志记录器
+        :param max_wait_sec: 最大等待绕过时间(秒)
+        """
+        self.page = page
+        self.max_wait_sec = max_wait_sec
+        self._raw_logger = logger
+
+    def log(self, msg: str, level: str = "info"):
+        if self._raw_logger:
+            if callable(self._raw_logger):
+                try:
+                    self._raw_logger(msg, level=level)
+                except TypeError:
+                    self._raw_logger(msg)
+            else:
+                log_fn = getattr(self._raw_logger, level.lower(), getattr(self._raw_logger, "info", print))
+                log_fn(msg)
+        else:
+            print(f"[CloudflareBypasser] {msg}")
+
+    def is_challenge_present(self) -> bool:
+        """检查当前页面是否存在 Cloudflare 挑战盾"""
+        try:
+            title = (getattr(self.page, "title", "") or "").lower()
+            if any(t in title for t in ["just a moment", "cloudflare", "attention required", "security check"]):
+                return True
+
+            # 检查是否有 CF 相关的特征元素或 iframe
+            if self.page.ele("@src:challenges.cloudflare.com", timeout=0.2):
+                return True
+            if self.page.ele(".cf-turnstile", timeout=0.2) or self.page.ele("@class:cf-turnstile", timeout=0.2):
+                return True
+            if self.page.ele("#challenge-running", timeout=0.2) or self.page.ele("#challenge-stage", timeout=0.2):
+                return True
+        except Exception:
+            pass
+        return False
+
+    def _click_turnstile_checkbox(self) -> bool:
+        """尝试穿透 iframe 和 shadow DOM 点击 Turnstile 验证框"""
+        # 1. 寻找 challenges.cloudflare.com 的 iframe
+        try:
+            cf_iframes = self.page.eles("@src:challenges.cloudflare.com", timeout=0.5)
+            for iframe in cf_iframes:
+                try:
+                    btn = iframe.ele("tag:input@type=checkbox", timeout=0.5) or \
+                          iframe.ele(".mark", timeout=0.5) or \
+                          iframe.ele("@class:spacer", timeout=0.5) or \
+                          iframe.ele("tag:body", timeout=0.5)
+                    if btn:
+                        self.log("🔍 检测到 Turnstile 验证框 iframe,正在执行拟人化点击...")
+                        time.sleep(0.6)
+                        btn.click()
+                        time.sleep(1.0)
+                        return True
+                except Exception as e:
+                    self.log(f"尝试穿透 iframe 元素点击失败: {e}")
+        except Exception:
+            pass
+
+        # 2. 检查本页直接挂载的 Turnstile / Challenge 元素
+        try:
+            turnstile_container = self.page.ele(".cf-turnstile", timeout=0.5) or \
+                                  self.page.ele("@class:cf-turnstile", timeout=0.5) or \
+                                  self.page.ele("#turnstile-box", timeout=0.5) or \
+                                  self.page.ele("@id:turnstile", timeout=0.5)
+            if turnstile_container:
+                self.log("🔍 检测到本页 Turnstile 容器,尝试直接点击...")
+                turnstile_container.click()
+                time.sleep(1.0)
+                return True
+        except Exception:
+            pass
+
+        return False
+
+    def bypass(self) -> bool:
+        """
+        执行穿透挑战流程
+        :return: 是否成功通过
+        """
+        self.log("🛡️ 检测到 Cloudflare 挑战页面,启动自动穿透流程...")
+        start_time = time.time()
+
+        # 先稍作等待,部分挑战是纯 JS 静默计算
+        time.sleep(0.8)
+
+        while time.time() - start_time < self.max_wait_sec:
+            if not self.is_challenge_present():
+                self.log("✅ Cloudflare 挑战已成功通过!")
+                return True
+
+            # 尝试查找并点击
+            clicked = self._click_turnstile_checkbox()
+            if clicked:
+                self.log("🖱️ 已触发点击验证框,等待验证结果...")
+                time.sleep(1.5)
+                if not self.is_challenge_present():
+                    self.log("✅ Cloudflare 挑战已成功通过!")
+                    return True
+
+            time.sleep(0.8)
+
+        # 超时后再次检查
+        if not self.is_challenge_present():
+            self.log("✅ Cloudflare 挑战已通过!")
+            return True
+
+        self.log("⚠️ 自动穿透超时,若处于有头浏览器模式,请在窗口中手动完成验证...", level="warning")
+        return False

+ 162 - 0
robotics (副本)/tls_flow.py

@@ -0,0 +1,162 @@
+"""
+tls_flow.py - TLScontact 签证预约业务流程状态机
+基于 BaseFlow 声明式注解,实现异常自愈、登录、申请人流转与时段监控
+"""
+
+import time
+from flow_annotated import BaseFlow, on, done, fatal, guard
+from cf_bypasser import CloudflareBypasser
+
+
+class TlsContactFlow(BaseFlow):
+    def __init__(self, page, config=None, interval=1.0, logger=None, cf_bypasser=None):
+        super().__init__(page, config=config, interval=interval, logger=logger, cf_bypasser=cf_bypasser)
+        if self.cf_bypasser is None:
+            self.cf_bypasser = CloudflareBypasser(page, logger=self.log)
+        self.preferred_dates = self.config.get("preferred_dates", [])
+
+    # -----------------------------------------------------------------------
+    # 1. 异常守卫注解 (高优先级 priority=1~20)
+    # -----------------------------------------------------------------------
+    @guard(text="502 Bad Gateway", priority=5)
+    def on_502_error(self):
+        self.log("[WARN] 检测到 502 网关错误,等待 3 秒后刷新重试...", level="warning")
+        time.sleep(3)
+        self.page.refresh()
+
+    @guard(text="504 Gateway Time-out", priority=5)
+    def on_504_error(self):
+        self.log("[WARN] 检测到 504 网关超时,等待 3 秒后刷新重试...", level="warning")
+        time.sleep(3)
+        self.page.refresh()
+
+    @guard(title="just a moment", priority=6)
+    def on_cloudflare_challenge_title(self):
+        self.log("🛡️ 命中 Cloudflare Challenge 守卫 (Title 匹配)...")
+        self.cf_bypasser.bypass()
+
+    @guard(ele="@src:challenges.cloudflare.com", priority=6)
+    def on_cloudflare_challenge_iframe(self):
+        self.log("🛡️ 命中 Cloudflare Turnstile 守卫 (Iframe 匹配)...")
+        self.cf_bypasser.bypass()
+
+    @guard(text="Session Expired", priority=8)
+    def on_session_expired(self):
+        self.log("[WARN] 会话已过期,重新跳转至登录入口...", level="warning")
+        login_url = self.config.get("login_url") or self.config.get("target_url")
+        if login_url:
+            self.page.get(login_url)
+
+    # -----------------------------------------------------------------------
+    # 2. 致命错误注解 (直接中断)
+    # -----------------------------------------------------------------------
+    @on(text="You have not yet added an applicant", priority=15)
+    @fatal("未找到申请人,请先在官网完善申请人基本信息后再次执行!")
+    def on_no_applicant(self):
+        pass
+
+    @on(text="Account locked", priority=15)
+    @fatal("账号已被锁定,请稍后再试或联系 TLScontact 客服!")
+    def on_account_locked(self):
+        pass
+
+    # -----------------------------------------------------------------------
+    # 3. 业务表单操作 (登录、分组、概览、预约时段)
+    # -----------------------------------------------------------------------
+    @on(ele="tag:label@text():Email", priority=50)
+    def handle_login_by_label(self):
+        self.log("正在填写登录表单 (通过 Label 查找)...")
+        username = self.config.get("username", "")
+        password = self.config.get("password", "")
+        
+        email_input = self.page.ele('tag:label@text():Email').next('tag:input') or self.page.ele('tag:input@type=email') or self.page.ele('@name=email')
+        if email_input:
+            email_input.clear()
+            email_input.input(username)
+        
+        pwd_input = self.page.ele('tag:label@text():Password').next('tag:input') or self.page.ele('tag:input@type=password') or self.page.ele('@name=password')
+        if pwd_input:
+            pwd_input.clear()
+            pwd_input.input(password)
+
+        time.sleep(0.5)
+        login_btn = self.page.ele('tag:button@text():Login') or self.page.ele('tag:button@type=submit')
+        if login_btn:
+            login_btn.click()
+
+    @on(url="/login", ele="tag:input@type=email", priority=51)
+    def handle_login_by_url(self):
+        self.log("正在填写登录页面...")
+        username = self.config.get("username", "")
+        password = self.config.get("password", "")
+        
+        self.page.ele('tag:input@type=email').input(username)
+        self.page.ele('tag:input@type=password').input(password)
+        time.sleep(0.5)
+        self.page.ele('tag:button@type=submit').click()
+
+    @on(url="travel-groups", priority=60)
+    def handle_travel_groups(self):
+        self.log("正在选择行程/申请人分组...")
+        btn = self.page.ele('tag:button@name=formGroupId') or \
+              self.page.ele('tag:button@text():Select') or \
+              self.page.ele('.group-btn') or \
+              self.page.ele('tag:a@text():View')
+        if btn:
+            btn.click()
+        else:
+            self.log("[WARN] 未找到分组按钮,尝试点击列表首项...")
+            card = self.page.ele('.group-card')
+            if card:
+                card.click()
+
+    @on(url="application-summary", priority=70)
+    def handle_change_booking(self):
+        self.log("正在处理申请人摘要页 (application-summary)...")
+        change_btn = self.page.ele('tag:button@text():Change') or self.page.ele('tag:button@text():Book')
+        if change_btn:
+            change_btn.click()
+            time.sleep(0.5)
+        
+        # 确认弹窗
+        yes_btn = self.page.ele('tag:button@text():Yes') or self.page.ele('tag:button@text():Confirm')
+        if yes_btn:
+            yes_btn.click()
+
+    @on(url="appointment-booking", ele=".available-slot", priority=80)
+    def handle_slot_selection(self):
+        self.log("📅 发现可用预约时段,正在选择最优时段...")
+        slots = self.page.eles(".available-slot") or self.page.eles(".slot-btn")
+        if slots:
+            selected_slot = slots[0]
+            for slot in slots:
+                slot_text = slot.text
+                if any(pref in slot_text for pref in self.preferred_dates):
+                    selected_slot = slot
+                    self.log(f"🎯 命中首选日期时段: {slot_text}")
+                    break
+            
+            selected_slot.click()
+            time.sleep(0.5)
+            
+            confirm_btn = self.page.ele("tag:button@text():Confirm Slot") or self.page.ele("tag:button@text():Continue")
+            if confirm_btn:
+                confirm_btn.click()
+
+    # -----------------------------------------------------------------------
+    # 4. 成功终态注解 (Done)
+    # -----------------------------------------------------------------------
+    @on(url="appointment-booking", ele="tag:button@text():Book your appointment", priority=30)
+    @done
+    def on_booking_button_submit(self):
+        self.log("🎯 点击最终预约提交按钮...")
+        btn = self.page.ele("tag:button@text():Book your appointment")
+        if btn:
+            btn.click()
+        self.log("✅ 抢号/预约流程提交完成!")
+
+    @on(url="appointment-confirmation", priority=25)
+    @on(text="Appointment Confirmed", priority=25)
+    @done
+    def on_booking_success_confirmed(self):
+        self.log("🎉 页面已跳转至预约成功确认页!预约成功!")

+ 156 - 0
test/test_captcha_breaker.py

@@ -0,0 +1,156 @@
+import os
+import io
+import base64
+import tempfile
+import unittest
+from unittest.mock import MagicMock
+
+from toolkit.captcha_breaker import (
+    CaptchaBreaker,
+    CaptchaBreakerError,
+    normalize_image_to_data_url,
+)
+
+class TestNormalizeImageToDataUrl(unittest.TestCase):
+    def test_bytes_input(self):
+        raw_bytes = b"fake-image-bytes"
+        expected_b64 = base64.b64encode(raw_bytes).decode("utf-8")
+        result = normalize_image_to_data_url(raw_bytes)
+        self.assertEqual(result, f"data:image/png;base64,{expected_b64}")
+
+    def test_bytesio_input(self):
+        bio = io.BytesIO(b"fake-bytesio-data")
+        expected_b64 = base64.b64encode(b"fake-bytesio-data").decode("utf-8")
+        result = normalize_image_to_data_url(bio)
+        self.assertEqual(result, f"data:image/png;base64,{expected_b64}")
+
+    def test_already_data_url(self):
+        data_url = "data:image/jpeg;base64,123456"
+        result = normalize_image_to_data_url(data_url)
+        self.assertEqual(result, data_url)
+
+    def test_raw_base64_string(self):
+        raw_b64 = "ABCD1234EFGH"
+        result = normalize_image_to_data_url(raw_b64)
+        self.assertEqual(result, f"data:image/png;base64,{raw_b64}")
+
+    def test_file_path_input(self):
+        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
+            tmp.write(b"jpeg-content")
+            tmp_path = tmp.name
+        try:
+            result = normalize_image_to_data_url(tmp_path)
+            expected_b64 = base64.b64encode(b"jpeg-content").decode("utf-8")
+            self.assertEqual(result, f"data:image/jpeg;base64,{expected_b64}")
+        finally:
+            if os.path.exists(tmp_path):
+                os.remove(tmp_path)
+
+    def test_invalid_type_raises(self):
+        with self.assertRaises(ValueError):
+            normalize_image_to_data_url(12345)  # type: ignore
+
+
+class TestCaptchaBreaker(unittest.TestCase):
+    def test_config_precedence_explicit_args(self):
+        breaker = CaptchaBreaker(
+            api_key="explicit_key",
+            base_url="https://api.openai.com/v1",
+            model="gpt-4o",
+            timeout=15.0
+        )
+        self.assertEqual(breaker.api_key, "explicit_key")
+        self.assertEqual(breaker.base_url, "https://api.openai.com/v1")
+        self.assertEqual(breaker.model, "gpt-4o")
+        self.assertEqual(breaker.timeout, 15.0)
+
+    def test_missing_api_key_raises_on_client_access(self):
+        from unittest.mock import patch
+        with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None):
+            with patch.dict(os.environ, {}, clear=True):
+                breaker = CaptchaBreaker()
+                with self.assertRaises(CaptchaBreakerError) as ctx:
+                    _ = breaker.client
+                self.assertIn("API Key is not configured", str(ctx.exception))
+
+                with self.assertRaises(CaptchaBreakerError) as ctx2:
+                    breaker.break_captcha(b"dummy")
+                self.assertIn("API Key is not configured", str(ctx2.exception))
+
+    def test_fallback_to_env_when_config_is_none(self):
+        from unittest.mock import patch
+        with patch("toolkit.captcha_breaker.CAPTCHA_LLM_CONFIG", None):
+            with patch.dict(os.environ, {
+                "CAPTCHA_LLM_API_KEY": "env-key-123",
+                "CAPTCHA_LLM_MODEL": "gpt-4o-mini",
+                "CAPTCHA_LLM_BASE_URL": "https://custom.api/v1",
+                "CAPTCHA_LLM_TIMEOUT": "20.0"
+            }):
+                mock_client = MagicMock()
+                breaker = CaptchaBreaker(client=mock_client)
+                self.assertEqual(breaker.api_key, "env-key-123")
+                self.assertEqual(breaker.model, "gpt-4o-mini")
+                self.assertEqual(breaker.base_url, "https://custom.api/v1")
+                self.assertEqual(breaker.timeout, 20.0)
+
+    def test_clean_result(self):
+        breaker = CaptchaBreaker(api_key="test-key")
+        self.assertEqual(breaker._clean_result("   123456   "), "123456")
+        self.assertEqual(breaker._clean_result('"ABCD"'), "ABCD")
+        self.assertEqual(breaker._clean_result("'XYZW'"), "XYZW")
+        markdown_wrapped = "```\n987654\n```"
+        self.assertEqual(breaker._clean_result(markdown_wrapped), "987654")
+        codeblock_wrapped = "```text\nK8W2\n```"
+        self.assertEqual(breaker._clean_result(codeblock_wrapped), "K8W2")
+
+    def test_break_captcha_with_mock_client(self):
+        mock_client = MagicMock()
+        mock_choice = MagicMock()
+        mock_choice.message.content = "  884210  "
+        mock_client.chat.completions.create.return_value.choices = [mock_choice]
+
+        breaker = CaptchaBreaker(
+            api_key="test-key",
+            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
+            model="qwen-vl-max",
+            client=mock_client
+        )
+
+        res = breaker.break_captcha(b"sample-image", prompt="识别验证码")
+        self.assertEqual(res, "884210")
+
+        mock_client.chat.completions.create.assert_called_once()
+        call_kwargs = mock_client.chat.completions.create.call_args[1]
+        self.assertEqual(call_kwargs["model"], "qwen-vl-max")
+        self.assertEqual(call_kwargs["temperature"], 0.0)
+        messages = call_kwargs["messages"]
+        self.assertEqual(messages[0]["role"], "user")
+        self.assertEqual(messages[0]["content"][0]["text"], "识别验证码")
+        self.assertTrue(messages[0]["content"][1]["image_url"]["url"].startswith("data:image/png;base64,"))
+
+    def test_api_exception_wrapped_in_captchabreakererror(self):
+        mock_client = MagicMock()
+        mock_client.chat.completions.create.side_effect = RuntimeError("Connection timed out")
+
+        breaker = CaptchaBreaker(
+            api_key="test-key",
+            client=mock_client
+        )
+
+        with self.assertRaises(CaptchaBreakerError) as ctx:
+            breaker.break_captcha(b"sample-image")
+        self.assertIn("Connection timed out", str(ctx.exception))
+
+    def test_callable_instance(self):
+        mock_client = MagicMock()
+        mock_choice = MagicMock()
+        mock_choice.message.content = "ABC9"
+        mock_client.chat.completions.create.return_value.choices = [mock_choice]
+
+        breaker = CaptchaBreaker(api_key="test-key", client=mock_client)
+        res = breaker(b"sample-image")
+        self.assertEqual(res, "ABC9")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 64 - 80
test/test_cloud_config.py

@@ -1,51 +1,19 @@
 import os
 import os
 import json
 import json
-import time
 import tempfile
 import tempfile
-import threading
 import unittest
 import unittest
-from http.server import HTTPServer, BaseHTTPRequestHandler
+from unittest.mock import patch, MagicMock
 
 
 from utils.cloud_config import (
 from utils.cloud_config import (
     compute_config_hash,
     compute_config_hash,
-    fetch_remote_config,
+    fetch_cloud_config,
     save_local_cache,
     save_local_cache,
     load_local_config,
     load_local_config,
     load_remote_or_cache,
     load_remote_or_cache,
 )
 )
 
 
 
 
-class MockConfigHTTPHandler(BaseHTTPRequestHandler):
-    config_payload = [{"identifier": "test_group", "enable": True}]
-    status_code = 200
-
-    def do_GET(self):
-        self.send_response(self.status_code)
-        self.send_header("Content-Type", "application/json")
-        self.end_headers()
-        response_data = json.dumps(self.config_payload).encode("utf-8")
-        self.wfile.write(response_data)
-
-    def log_message(self, format, *args):
-        pass  # 禁用标准输出日志,保持测试输出简洁
-
-
 class TestCloudConfig(unittest.TestCase):
 class TestCloudConfig(unittest.TestCase):
-    @classmethod
-    def setUpClass(cls):
-        # 启动本地 Mock HTTP 服务器
-        cls.server = HTTPServer(("127.0.0.1", 0), MockConfigHTTPHandler)
-        cls.port = cls.server.server_address[1]
-        cls.server_thread = threading.Thread(target=cls.server.serve_forever)
-        cls.server_thread.daemon = True
-        cls.server_thread.start()
-        cls.url = f"http://127.0.0.1:{cls.port}/config.json"
-
-    @classmethod
-    def tearDownClass(cls):
-        cls.server.shutdown()
-        cls.server.server_close()
-
     def test_compute_config_hash(self):
     def test_compute_config_hash(self):
         data1 = {"b": 2, "a": 1}
         data1 = {"b": 2, "a": 1}
         data2 = {"a": 1, "b": 2}
         data2 = {"a": 1, "b": 2}
@@ -53,52 +21,68 @@ class TestCloudConfig(unittest.TestCase):
         self.assertEqual(compute_config_hash(data1), compute_config_hash(data2))
         self.assertEqual(compute_config_hash(data1), compute_config_hash(data2))
         self.assertNotEqual(compute_config_hash(data1), compute_config_hash(data3))
         self.assertNotEqual(compute_config_hash(data1), compute_config_hash(data3))
 
 
-    def test_fetch_remote_config_success(self):
-        MockConfigHTTPHandler.config_payload = [{"identifier": "group_a", "enable": True}]
-        MockConfigHTTPHandler.status_code = 200
-
-        data = fetch_remote_config(self.url)
-        self.assertEqual(data, [{"identifier": "group_a", "enable": True}])
-
-    def test_fetch_remote_config_http_error(self):
-        MockConfigHTTPHandler.status_code = 500
-        with self.assertRaises(RuntimeError):
-            fetch_remote_config(self.url)
-
-    def test_load_remote_or_cache_success_and_save(self):
-        MockConfigHTTPHandler.config_payload = [{"identifier": "group_remote", "enable": True}]
-        MockConfigHTTPHandler.status_code = 200
-
-        with tempfile.TemporaryDirectory() as tmp_dir:
-            cache_path = os.path.join(tmp_dir, "cache.json")
-            data, hash_val, loaded_remote = load_remote_or_cache(
-                remote_url=self.url,
-                local_cache_path=cache_path
-            )
-
-            self.assertTrue(loaded_remote)
-            self.assertEqual(data, [{"identifier": "group_remote", "enable": True}])
-            self.assertTrue(os.path.exists(cache_path))
-
-            # 验证本地缓存是否被写入
-            cached_data = load_local_config(cache_path)
-            self.assertEqual(cached_data, [{"identifier": "group_remote", "enable": True}])
-
-    def test_load_remote_or_cache_fallback_to_local(self):
-        MockConfigHTTPHandler.status_code = 500  # 模拟云端 API 失败
-
-        with tempfile.TemporaryDirectory() as tmp_dir:
-            cache_path = os.path.join(tmp_dir, "cache.json")
-            # 预先存入本地缓存
-            save_local_cache(cache_path, [{"identifier": "group_cached", "enable": True}])
-
-            data, hash_val, loaded_remote = load_remote_or_cache(
-                remote_url=self.url,
-                local_cache_path=cache_path
-            )
-
-            self.assertFalse(loaded_remote)
-            self.assertEqual(data, [{"identifier": "group_cached", "enable": True}])
+    def test_fetch_cloud_config_success(self):
+        with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst:
+            mock_inst = MagicMock()
+            mock_inst.get_node_configurations.return_value = {
+                "items": [{"identifier": "group_a", "enable": True}]
+            }
+            mock_api_inst.return_value = mock_inst
+
+            data = fetch_cloud_config(role="sentinel", node_id="node-1")
+            self.assertEqual(data, [{"identifier": "group_a", "enable": True}])
+
+    def test_fetch_cloud_config_failure(self):
+        with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst:
+            mock_inst = MagicMock()
+            mock_inst.get_node_configurations.side_effect = Exception("API down")
+            mock_api_inst.return_value = mock_inst
+
+            data = fetch_cloud_config(role="sentinel", node_id="node-1")
+            self.assertIsNone(data)
+
+    def test_load_cloud_or_cache_success_and_save(self):
+        with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst:
+            mock_inst = MagicMock()
+            mock_inst.get_node_configurations.return_value = {
+                "items": [{"identifier": "group_remote", "enable": True}]
+            }
+            mock_api_inst.return_value = mock_inst
+
+            with tempfile.TemporaryDirectory() as tmp_dir:
+                cache_path = os.path.join(tmp_dir, "cache.json")
+                data, hash_val, loaded_cloud = load_remote_or_cache(
+                    role="sentinel",
+                    node_id="node-1",
+                    local_cache_path=cache_path
+                )
+
+                self.assertTrue(loaded_cloud)
+                self.assertEqual(data, [{"identifier": "group_remote", "enable": True}])
+                self.assertTrue(os.path.exists(cache_path))
+
+                # 验证本地缓存是否被写入
+                cached_data = load_local_config(cache_path)
+                self.assertEqual(cached_data, [{"identifier": "group_remote", "enable": True}])
+
+    def test_load_cloud_or_cache_fallback_to_local(self):
+        with patch("toolkit.vs_cloud_api.VSCloudApi.Instance") as mock_api_inst:
+            mock_inst = MagicMock()
+            mock_inst.get_node_configurations.side_effect = Exception("API down")
+            mock_api_inst.return_value = mock_inst
+
+            with tempfile.TemporaryDirectory() as tmp_dir:
+                cache_path = os.path.join(tmp_dir, "cache.json")
+                save_local_cache(cache_path, [{"identifier": "group_cached", "enable": True}])
+
+                data, hash_val, loaded_cloud = load_remote_or_cache(
+                    role="sentinel",
+                    node_id="node-1",
+                    local_cache_path=cache_path
+                )
+
+                self.assertFalse(loaded_cloud)
+                self.assertEqual(data, [{"identifier": "group_cached", "enable": True}])
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 0 - 781
test/tls_standalone.py

@@ -1,781 +0,0 @@
-import time
-import json
-import random
-import re
-import os
-import uuid
-import socket
-import shutil
-import requests
-import threading
-import select
-import base64
-from datetime import datetime
-from urllib.parse import urlencode
-
-# DrissionPage 核心
-from DrissionPage import ChromiumPage, ChromiumOptions
-
-
-class BrowserResponse:
-    """模拟 requests.Response 的轻量级对象"""
-    def __init__(self, result_dict):
-        result_dict = result_dict or {}
-        self.status_code = result_dict.get('status', 0)
-        self.text = result_dict.get('body', '')
-        self.headers = result_dict.get('headers', {})
-        self.url = result_dict.get('url', '')
-
-class TlsAutoBot:
-    def __init__(self, config: dict):
-        """
-        config 包含: proxy, account, capsolver_key, apt_config (code, country, city), target_dates 等
-        """
-        self.config = config
-        self.instance_id = uuid.uuid4().hex[:8]
-        self.workspace = os.path.abspath(os.path.join("data", f"tls_session_{self.instance_id}"))
-        self.page = None
-        self.travel_group = None
-
-    def _log(self, msg):
-        print(f"[TLS-Bot-{self.instance_id}] {msg}")
-
-    def _get_free_port(self):
-        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
-            s.bind(('', 0))
-            return s.getsockname()[1]
-
-    def init_browser(self):
-        self._log("Initializing browser...")
-        co = ChromiumOptions()
-        
-        # 1. 端口与路径隔离
-        port = self._get_free_port()
-        co.set_local_port(port)
-        co.set_user_data_path(self.workspace)
-        
-        # 2. 代理配置
-        proxy_cfg = self.config.get('proxy', {})
-
-        proxy_str = f"{proxy_cfg.get('proto')}://{proxy_cfg.get('ip')}:{proxy_cfg.get('port')}"
-        print(f'set proxy={proxy_str}')
-        co.set_argument(f'--proxy-server={proxy_str}')
-
-        # 3. 反爬配置
-        co.headless(False)
-        co.set_argument('--no-sandbox')
-        co.set_argument('--disable-gpu')
-        co.set_argument('--disable-dev-shm-usage')
-        co.set_argument('--window-size=1920,1080')
-        co.set_argument('--disable-blink-features=AutomationControlled')
-
-        self.page = ChromiumPage(co)
-
-    def solve_captcha(self, page_url: str, task_type: str, site_key: str, use_proxy = False, action: str = None, api_domain: str = None) -> str:
-        """通用解决验证码 (同步 User-Agent 防止被盾识别为高风险)"""
-        capsolver_key = self.config.get('capsolver_key')
-        if not capsolver_key:
-            raise ValueError("Capsolver API key missing")
-
-        task = {
-            "type": task_type,
-            "websiteURL": page_url,
-            "websiteKey": site_key,
-        }
-        
-        if api_domain:
-            task["apiDomain"] = api_domain
-            
-        if use_proxy:
-            proxy = self.config['proxy']
-            task["proxyType"] = proxy.get('proto', 'http')
-            task["proxyAddress"] = proxy.get('ip')
-            task["proxyPort"] = int(proxy.get('port'))
-            if proxy.get('username'):
-                task["proxyLogin"] = proxy.get('username')
-                task["proxyPassword"] = proxy.get('password')
-                
-        if action:
-            task["pageAction"] = action
-
-        payload = {"clientKey": capsolver_key, "task": task}
-        res = requests.post("https://api.capsolver.com/createTask", json=payload, timeout=20)
-        if res.status_code != 200 or res.json().get("errorId") != 0:
-            raise Exception(f"Failed to create capsolver task: {res.text}")
-
-        task_id = res.json().get("taskId")
-        self._log(f"Task created: {task_id}. Waiting for solution...")
-
-        for _ in range(30):
-            r = requests.post(
-                "https://api.capsolver.com/getTaskResult", 
-                json={"clientKey": capsolver_key, "taskId": task_id}, 
-                timeout=20
-            )
-            data = r.json()
-            if data.get("status") == "ready":
-                self._log("Captcha solved successfully!")
-                return data["solution"].get("gRecaptchaResponse") or data["solution"].get("token")
-            time.sleep(3)
-        raise Exception("Capsolver task timeout")
-
-    def login(self):
-        """执行自动登录流程并提取 Group ID"""
-        self.init_browser()
-        
-        apt_config = self.config['apt_config']
-        login_url = "https://visas-fr.tlscontact.com/en-us/login"
-        params = {
-            "issuerId": apt_config["code"],
-            "country": apt_config["country"],
-            "vac": apt_config["code"],
-            "redirect": f"/en-us/country/{apt_config['country']}/vac/{apt_config['code']}"
-        }
-        full_login_url = f"{login_url}?{urlencode(params)}"
-        
-        self._log(f"Navigating to login: {full_login_url}")
-        self.page.get(full_login_url)
-        time.sleep(3)
-        wait_start = time.time()
-        while True:
-            # 获取页面 HTML,转小写
-            # 注意:如果此处报错 "页面被刷新",是 DrissionPage 的机制问题,
-            # 但你要求先不处理复杂错误,所以这里保持最简单的写法。
-            html = self.page.html.lower()
-            
-            # 检查是否在排队室 (法语或英语)
-            if "file d'attente" in html or "waiting room" in html:
-                # 如果等太久(比如1小时),就强制停止
-                if time.time() - wait_start > 6 * 60:
-                    self._log("Waiting room timeout (1h).")
-                    break
-                    
-                self._log("In Waiting Room... Waiting for auto-refresh.")
-                time.sleep(30) # 截图说页面会自动刷新,所以这里只sleep,不动浏览器
-            else:
-                # 页面里没有“等候室”的字了,说明出来了
-                break
-
-        if not self.page.ele('#email-input-field'):
-            self._log("Form not found, reloading...")
-            self.page.get(full_login_url)
-            self.page.wait.ele_displayed('#email-input-field', timeout=15)
-
-        self._log("Waiting 3 seconds for Captcha scripts to load...")
-        time.sleep(3)
-
-        g_token = ""
-        # 判断登录页是否有 ReCaptcha
-        if self.page.ele('.g-recaptcha') or self.page.ele('xpath://iframe[contains(@src, "recaptcha")]'):
-            self._log("Login ReCaptcha detected, solving...")
-            # 登录页通常是 V2
-            g_token = self.solve_captcha(
-                page_url=self.page.url,
-                task_type="ReCaptchaV2TaskProxyLess",
-                site_key="6LcDpXcfAAAAAM7wOEsF_38DNsL20tTvPTKxpyn0"
-            )
-
-        account = self.config['account']
-        js_login = f"""
-        var u = document.getElementById('email-input-field');
-        if(u) {{ u.value = "{account['username']}"; u.dispatchEvent(new Event('input', {{bubbles:true}})); }}
-        
-        var p = document.getElementById('password-input-field');
-        if(p) {{ p.value = "{account['password']}"; p.dispatchEvent(new Event('input', {{bubbles:true}})); }}
-        
-        var g = document.getElementById('g-recaptcha-response');
-        if(g) {{ g.value = "{g_token}"; }}
-        
-        var btn = document.getElementById('btn-login');
-        if(btn) {{ btn.click(); return true; }} else {{ return false; }}
-        """
-        
-        self._log("Submitting Login via JS...")
-        self.page.run_js(js_login)
-
-        self._log("Waiting for dashboard redirect...")
-        self.page.wait.url_change('login-actions', exclude=True, timeout=45)
-        time.sleep(4)
-
-        if "login-actions" in self.page.url or "auth" in self.page.url:
-            raise Exception("Login Failed! Invalid credentials or Captcha rejected.")
-
-        self._log("Waiting for dashboard...")
-        self.page.wait.load_start()
-        time.sleep(5)
-
-        # 解析 Dashboard 提取 Group ID
-        self._log("Parsing Dashboard for Travel Group...")
-        html = self.page.html
-        js_pattern = r'\\"travelGroups\\":\s*(\[.*?\]),\\"availableCountriesToCreateGroups'
-        js_match = re.search(js_pattern, html, re.DOTALL)
-        
-        groups = []
-        if js_match:
-            json_str = js_match.group(1).replace(r'\"', '"')
-            groups = json.loads(json_str)
-
-        target_city = apt_config['city'].lower()
-        for g in groups:
-            if g.get('vacName', '').lower() == target_city:
-                self.travel_group = g
-                break
-        
-        if not self.travel_group:
-            raise Exception(f"Travel Group not found for city: {target_city}")
-        
-        formgroup_id = self.travel_group.get('formGroupId')
-        self._log(f"Waiting for group button to render: {formgroup_id}")
-        
-        # 隐患修复:确保按钮渲染出来后再点,防止 JS 找不到元素
-        btn_selector = f'tag:button@@name=formGroupId@@value={formgroup_id}'
-        self.page.wait.ele_displayed(btn_selector, timeout=15)
-        
-        self._log(f"Select group_id={formgroup_id} via JS...")
-        # 替代繁琐的 run_js,直接用内置的 by_js=True 触发
-        self.page.ele(btn_selector).click(by_js=True)
-        
-        self._log("Waiting for service-level redirect...")
-        self.page.wait.url_change('travel-groups', exclude=True, timeout=45)
-        time.sleep(2) # 页面跳转后给个短缓冲
-
-        if "travel-groups" in self.page.url or "auth" in self.page.url:
-            raise Exception("Redirect to service-level Failed!")
-
-        # ==========================================
-        # 2. 点击进入 Appointment Booking
-        # ==========================================
-        self._log("Waiting for book-appointment button to render...")
-        
-        # 隐患修复:同样必须等待 Continue 按钮渲染完成
-        self.page.wait.ele_displayed('#book-appointment-btn', timeout=15)
-        
-        self._log("Clicking 'Continue' to appointment booking via JS...")
-        self.page.ele('#book-appointment-btn').click(by_js=True)
-
-        self._log("Waiting for appointment-booking redirect...")
-        self.page.wait.url_change('service-level', exclude=True, timeout=45)
-        time.sleep(2)
-
-        if "service-level" in self.page.url or "auth" in self.page.url:
-            raise Exception("Redirect to appointment-booking Failed!")
-
-        self._log("Waiting for appointment-booking page to fully load...")
-        self.page.wait.load_start()
-        time.sleep(3)
-
-        self._log(f"✅ Login & Navigation Success! Target Group ID: {formgroup_id}")
-
-    def query_slots(self) -> list:
-        """根据当前 UI 状态自动判断路由,并使用高鲁棒性特征提取 Slot"""
-        group_num = self.travel_group['formGroupId']
-        apt_config = self.config['apt_config']
-        interest_month = self.config.get("interest_month", time.strftime("%m-%Y"))
-        
-        # 转换工具
-        target_date_obj = datetime.strptime(interest_month, "%m-%Y")
-        target_month_text = target_date_obj.strftime("%B %Y")
-        target_year = target_date_obj.year
-        target_month_num = target_date_obj.month
-        
-        slots = []
-
-        # 获取选中的月份:通过 data-testid 找到当前月份按钮并提取文本
-        # 注意:这里改用 data-testid 寻找当前月份,更稳健
-        current_selected_ele = self.page.ele('@data-testid=btn-current-month-available')
-        current_month_text = current_selected_ele.text.strip() if current_selected_ele else ""
-
-        is_on_target_month = (current_month_text.lower() == target_month_text.lower())
-
-        if not is_on_target_month:
-            # ==========================================
-            # 模式 A: 不在目标月份 (UI 路由 + HTML 强鲁棒性解析)
-            # ==========================================
-            self._log(f"Current is '{current_month_text}', navigating to '{target_month_text}'...")
-            
-            for _ in range(12):
-                target_btn_xpath = f'xpath://a[contains(@href, "month={interest_month}")]'
-                target_btn = self.page.ele(target_btn_xpath)
-                
-                if target_btn:
-                    target_btn.click(by_js=True)
-                    time.sleep(3) 
-                    break
-                
-                next_btn = self.page.ele('@data-testid=btn-next-month-available')
-                if next_btn:
-                    next_btn.click(by_js=True)
-                    time.sleep(2) 
-                else:
-                    self._log("Warning: Cannot find target month or 'Next Month' button.")
-                    break
-
-            self._log("Extracting slots from DOM using robust data-testid features...")
-            
-            # 【高鲁棒性提取】
-            # 特征定义:寻找所有的“日期块”。
-            # 什么是一个日期块?它是一个 div,里面直接包含一个 p 标签(放日期),
-            # 且同时包含另一个 div,其内部有带有 'slot' 字样的按钮。
-            day_blocks_xpath = '//div[p and div//button[contains(@data-testid, "slot")]]'
-            day_blocks = self.page.eles(f'xpath:{day_blocks_xpath}')
-            
-            for block in day_blocks:
-                # 1. 提取日期:只要是这个 block 下的 p 标签,必定是 "Mon 01" 这种
-                p_ele = block.ele('tag:p')
-                if not p_ele: continue
-                
-                # 直接从 p 标签的纯文本里抽取出数字,忽略前面的字母
-                day_match = re.search(r'\d+', p_ele.text)
-                if not day_match: continue
-                day_str = day_match.group()
-                
-                full_date = f"{target_year}-{target_month_num:02d}-{int(day_str):02d}"
-                
-                # 2. 提取可用按钮:利用 data-testid 前缀匹配
-                # 完美过滤掉 btn-unavailable-slot (灰色的不可用按钮)
-                available_btns = block.eles('xpath:.//button[starts-with(@data-testid, "btn-available-slot")]')
-                
-                for btn in available_btns:
-                    # 提取时间:无视内部各种 span 的变动,只要 html 里有 00:00 这种格式就被截取
-                    time_match = re.search(r'\d{2}:\d{2}', btn.html)
-                    if not time_match: continue
-                    time_str = time_match.group()
-                    
-                    # 提取 Label:完全依赖测试工程师留下的 testid
-                    test_id = btn.attr('data-testid') or ""
-                    if 'prime' in test_id and 'weekend' in test_id:
-                        lbl = 'ptaw'
-                    elif 'prime' in test_id:
-                        lbl = 'pta'
-                    else:
-                        lbl = '' 
-                        
-                    slots.append({
-                        'date': full_date,
-                        'time': time_str,
-                        'label': lbl
-                    })
-
-        else:
-            # ==========================================
-            # 模式 B: 已经在目标月份 (JS Fetch + 正则 JSON 解析)
-            # ==========================================
-            self._log(f"Already on '{target_month_text}'. Executing silent JS fetch...")
-            
-            base_url = f'https://visas-fr.tlscontact.com/en-us/{group_num}/workflow/appointment-booking'
-            params = {'location': apt_config["code"], 'month': interest_month}
-            query_url = f"{base_url}?{urlencode(params)}"
-            
-            js_script = f"""
-            return fetch("{query_url}", {{ credentials: "include" }})
-                .then(async r => {{ return {{ status: r.status, body: await r.text() }}; }})
-                .catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-            """
-            res_dict = self.page.run_js(js_script)
-            resp = BrowserResponse(res_dict)
-
-            if resp.status_code != 200:
-                raise Exception(f"Silent Query Failed: {resp.status_code}")
-            
-            self._log("Extracting slots from JSON response...")
-            pattern = r'"availableAppointments\\":\s*(\[.*?\]),\\"showFlexiAppointment'
-            match = re.search(pattern, resp.text, re.DOTALL)
-            
-            if match:
-                json_str = match.group(1).replace(r'\"', '"')
-                data = json.loads(json_str)
-                for day in data:
-                    d_str = day.get('day')
-                    for s in day.get('slots', []):
-                        labels = s.get('labels', [])
-                        if not labels: continue 
-                        
-                        lbl = ""
-                        if 'pta' in labels: lbl = 'pta'
-                        elif 'ptaw' in labels: lbl = 'ptaw'
-                        elif '' in labels: lbl = ''
-                        
-                        slots.append({
-                            'date': d_str,
-                            'time': s.get('time'),
-                            'label': lbl
-                        })
-
-        self._log(f"Found {len(slots)} valid slots.")
-        return slots
-
-    def _filter_dates(self, available_dates: list, start_str: str, end_str: str) -> list:
-        if not start_str or not end_str:
-            return available_dates
-        valid = []
-        s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
-        e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
-        for d in available_dates:
-            curr = datetime.strptime(d, "%Y-%m-%d")
-            if s_date <= curr <= e_date:
-                valid.append(d)
-        return valid
-    
-    def book(self, all_slots: list) -> bool:
-        """执行预定流程"""
-        if not all_slots:
-            self._log("No slots provided to book.")
-            return False
-
-        # 1. 过滤日期 & 筛选标签
-        target_labels = self.config.get('target_labels', [''])
-        exp_start = self.config.get('expected_start_date', '')
-        exp_end = self.config.get('expected_end_date', '')
-
-        unique_dates = list(set([s['date'] for s in all_slots]))
-        valid_dates = self._filter_dates(unique_dates, exp_start, exp_end)
-        
-        possible_slots =[
-            s for s in all_slots 
-            if s['date'] in valid_dates and s['label'] in target_labels
-        ]
-
-        if not possible_slots:
-            self._log("No slots match target dates and labels.")
-            return False
-
-        # 2. 随机选择一个 Slot
-        selected = random.choice(possible_slots)
-        sel_date = selected['date']
-        sel_time = selected['time']
-        sel_label = selected['label']
-        
-        self._log(f"Selected Slot -> Date: {sel_date}, Time: {sel_time}, Label: {sel_label or 'standard'}")
-
-        group_num = self.travel_group['formGroupId']
-        apt_config = self.config['apt_config']
-        current_url = self.page.url
-        router_state = f'%5B%22%22%2C%7B%22children%22%3A%5B%5B%22lang%22%2C%22en-us%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%5B%22groupId%22%2C%22{group_num}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22workflow%22%2C%7B%22children%22%3A%5B%22appointment-booking%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D'
-
-        # 3. 获取金额 (Basket Cost) 
-        # self._log("Fetching basket cost...")
-        # cost_payload =[{"groupId": str(group_num), "lang": "en-us", "labels": [sel_label]}]
-        # cost_body_json = json.dumps(cost_payload)
-        
-        # js_cost = f"""
-        # return fetch("{current_url}", {{
-        #     method: 'POST',
-        #     headers: {{
-        #         'Next-Action': '40124cc90acef520d4fd2daf60ad3c8e21fc2c11d8',
-        #         'Next-Router-State-Tree': '{router_state}',
-        #         'Accept': 'text/x-component',
-        #         'Content-Type': 'text/plain;charset=UTF-8'
-        #     }},
-        #     body: `{cost_body_json}`
-        # }}).then(async r => {{ return {{ status: r.status, body: await r.text() }}; }})
-        #   .catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-        # """
-        # cost_res = BrowserResponse(self.page.run_js(js_cost))
-        # if cost_res.status_code != 200:
-        #     self._log(f"Basket cost check failed: {cost_res.status_code}")
-        #     return False
-
-        # 4. 解决 ReCaptcha V3
-        # self._log("Solving Booking ReCaptcha V3...")
-        # g_token = self.solve_captcha(
-        #     page_url=current_url,
-        #     task_type="ReCaptchaV3TaskProxyLess",
-        #     site_key="6LcTpXcfAAAAAM3VojNhyV-F1z92ADJIvcSZ39Y9",
-        #     use_proxy=False,
-        #     action="book",
-        #     api_domain="recaptcha.net"
-        # )
-
-        # 5. 注入 Hook 并点击表单
-        # self._log("Injecting reCAPTCHA hook and modifying form...")
-        
-        # # 5.1 注入你提供的劫持 JS
-        # hook_js = f"""
-        #     // 1. 填充可能存在的标准隐藏域
-        #     var input = document.getElementById('g-recaptcha-response');
-        #     if(input) {{
-        #         input.value = "{g_token}";
-        #         // 派发React识别的事件
-        #         input.dispatchEvent(new Event('input', {{ bubbles: true }}));
-        #         input.dispatchEvent(new Event('change', {{ bubbles: true }}));
-        #     }}
-
-        #     // 2. 劫持 grecaptcha.execute
-        #     var mockExecute = function() {{
-        #         console.log("[Hook] Recaptcha execution intercepted!");
-        #         return Promise.resolve("{g_token}");
-        #     }};
-
-        #     // 无论网页是否已加载完毕,保证对象存在并被劫持
-        #     if (!window.grecaptcha) {{
-        #         window.grecaptcha = {{}};
-        #     }}
-        #     window.grecaptcha.execute = mockExecute;
-            
-        #     if (!window.grecaptcha.enterprise) {{
-        #         window.grecaptcha.enterprise = {{}};
-        #     }}
-        #     window.grecaptcha.enterprise.execute = mockExecute;
-        # """
-        # self.page.run_js(hook_js)
-
-        # 5.2 注入表单数据并原样点击
-        js_inject_and_click = f"""
-        try {{
-            const form = document.querySelector('form');
-            if (!form) return 'Form not found';
-
-            function setReactValue(input, value) {{
-                if (!input) return;
-                input.value = value;
-                input.dispatchEvent(new Event('input', {{ bubbles: true }}));
-                input.dispatchEvent(new Event('change', {{ bubbles: true }}));
-            }}
-
-            // 填入抢单日期、时间、标签
-            setReactValue(form.querySelector('input[name="date"]'), '2026-06-01');
-            setReactValue(form.querySelector('input[name="time"]'), '12:00');
-            setReactValue(form.querySelector('input[name="appointmentLabel"]'), '{sel_label}');
-
-            // 解禁并点击 Submit 按钮
-            const submitBtn = form.querySelector('button[type="submit"]');
-            if (submitBtn) {{
-                submitBtn.removeAttribute('disabled');
-                submitBtn.classList.remove('opacity-50', 'cursor-not-allowed'); 
-                submitBtn.click();
-                return 'clicked';
-            }} else {{
-                return 'Submit button not found';
-            }}
-        }} catch (e) {{
-            return e.toString();
-        }}
-        """
-        
-        inject_res = self.page.run_js(js_inject_and_click)
-        self._log(f"Form submission triggered: {inject_res}")
-        
-        if inject_res != 'clicked':
-            self._log("❌ Failed to inject form or click the submit button.")
-            return False
-
-        # 6. 验证是否抢单成功 (轮询页面跳转)
-        self._log("Waiting for Next.js to process the form submission...")
-        
-        for _ in range(15):
-            time.sleep(1.0)
-            current_page_url = self.page.url
-            
-            # Next.js 跳转进入确认页
-            if "appointment-confirmation" in current_page_url:
-                self._log(f"✅ BOOKING SUCCESS! Redirected to: {current_page_url}")
-                return True
-                
-            try:
-                body_text = str(self.page.run_js("return document.body.innerText || '';"))
-                if "APPOINTMENT_LIMIT_REACHED" in body_text or "appointment limit" in body_text.lower():
-                    self._log("❌ BOOKING FAILED! Reason: Appointment Limit Reached")
-                    return False
-            except Exception:
-                pass 
-                
-        self._log("❌ BOOKING FAILED! Timeout waiting for redirect confirmation.")
-        return False
-
-    # def book(self, all_slots: list) -> bool:
-    #     """执行预定流程"""
-    #     if not all_slots:
-    #         self._log("No slots provided to book.")
-    #         return False
-
-    #     # 1. 过滤日期 & 筛选标签
-    #     target_labels = self.config.get('target_labels', [''])
-    #     exp_start = self.config.get('expected_start_date', '')
-    #     exp_end = self.config.get('expected_end_date', '')
-
-    #     # 提取唯一的可用日期列表
-    #     unique_dates = list(set([s['date'] for s in all_slots]))
-    #     valid_dates = self._filter_dates(unique_dates, exp_start, exp_end)
-        
-    #     possible_slots = [
-    #         s for s in all_slots 
-    #         if s['date'] in valid_dates and s['label'] in target_labels
-    #     ]
-
-    #     if not possible_slots:
-    #         self._log("No slots match target dates and labels.")
-    #         return False
-
-    #     # 2. 随机选择一个 Slot
-    #     selected = random.choice(possible_slots)
-    #     sel_date = selected['date']
-    #     sel_time = selected['time']
-    #     sel_label = selected['label']
-        
-    #     self._log(f"Selected Slot -> Date: {sel_date}, Time: {sel_time}, Label: {sel_label or 'standard'}")
-
-    #     group_num = self.travel_group['formGroupId']
-    #     apt_config = self.config['apt_config']
-        
-    #     current_url = self.page.url
-    #     router_state = f'%5B%22%22%2C%7B%22children%22%3A%5B%5B%22lang%22%2C%22en-us%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%5B%22groupId%22%2C%22{group_num}%22%2C%22d%22%5D%2C%7B%22children%22%3A%5B%22workflow%22%2C%7B%22children%22%3A%5B%22appointment-booking%22%2C%7B%22children%22%3A%5B%22__PAGE__%22%2C%7B%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%5D%7D%2Cnull%2Cnull%2Ctrue%5D%7D%2Cnull%2Cnull%5D'
-
-    #     # 3. 获取金额 (Basket Cost)
-    #     self._log("Fetching basket cost...")
-    #     cost_payload = [{"groupId": str(group_num), "lang": "en-us", "labels": [sel_label]}]
-    #     cost_body_json = json.dumps(cost_payload)
-        
-    #     js_cost = f"""
-    #     return fetch("{current_url}", {{
-    #         method: 'POST',
-    #         headers: {{
-    #             'Next-Action': '40124cc90acef520d4fd2daf60ad3c8e21fc2c11d8',
-    #             'Next-Router-State-Tree': '{router_state}',
-    #             'Accept': 'text/x-component',
-    #             'Content-Type': 'text/plain;charset=UTF-8'
-    #         }},
-    #         body: `{cost_body_json}`
-    #     }}).then(async r => {{ return {{ status: r.status, body: await r.text() }}; }})
-    #       .catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-    #     """
-    #     cost_res = BrowserResponse(self.page.run_js(js_cost))
-    #     if cost_res.status_code != 200:
-    #         self._log(f"Basket cost check failed: {cost_res.status_code}")
-    #         return False
-
-    #     # 4. 解决 ReCaptcha V3
-    #     self._log("Solving Booking ReCaptcha V3...")
-    #     g_token = self.solve_captcha(
-    #         page_url=current_url,
-    #         task_type="ReCaptchaV3M1TaskProxyLess",
-    #         site_key="6LcTpXcfAAAAAM3VojNhyV-F1z92ADJIvcSZ39Y9",
-    #         use_proxy=False,
-    #         action="book",
-    #         api_domain="recaptcha.net"
-    #     )
-
-    #     # 5. 提交 Booking
-    #     self._log("Submitting final booking request...")
-    #     js_book = f"""
-    #     const formData = new FormData();
-    #     formData.append('1_formGroupId', '{group_num}');
-    #     formData.append('1_lang', 'en-us');
-    #     formData.append('1_process', 'APPOINTMENT');
-    #     formData.append('1_location', '{apt_config["code"]}');
-    #     formData.append('1_date', '{sel_date}');
-    #     formData.append('1_time', '{sel_time}');
-    #     formData.append('1_appointmentLabel', '{sel_label}');
-    #     formData.append('1_captchaToken', '{g_token}');
-    #     formData.append('0', '[{{"status":"IDLE"}},"$K1"]');
-        
-    #     return fetch("{current_url}", {{
-    #         method: 'POST',
-    #         headers: {{
-    #             'Next-Action': '6043cfd107081bc817cbb11a8c0db17d3a063401be',
-    #             'Next-Router-State-Tree': '{router_state}',
-    #             'Accept': 'text/x-component'
-    #         }},
-    #         body: formData
-    #     }}).then(async r => {{
-    #         const hdrs = {{}};
-    #         r.headers.forEach((v, k) => hdrs[k] = v);
-    #         return {{ status: r.status, body: await r.text(), headers: hdrs, url: r.url }};
-    #     }}).catch(e => {{ return {{ status: 0, body: e.toString() }}; }});
-    #     """
-        
-    #     book_res_dict = self.page.run_js(js_book)
-    #     book_resp = BrowserResponse(book_res_dict)
-        
-    #     # 6. 解析结果 (判定 Next.js 跳转)
-    #     headers_lower = {str(k).lower(): v for k, v in book_resp.headers.items()}
-    #     action_redirect = headers_lower.get('x-action-redirect', '')
-
-    #     is_success = (
-    #         book_resp.status_code == 303 or 
-    #         (book_resp.status_code == 200 and ("appointment-confirmation" in action_redirect or "appointment-confirmation" in book_resp.url))
-    #     )
-
-    #     if is_success:
-    #         self._log(f"✅ BOOKING SUCCESS! Redirected to: {action_redirect or book_resp.url}")
-    #         return True
-    #     else:
-    #         self._log(f"❌ BOOKING FAILED! Status: {book_resp.status_code}")
-    #         if "APPOINTMENT_LIMIT_REACHED" in book_resp.text:
-    #             self._log("-> Reason: Appointment Limit Reached")
-    #         else:
-    #             self._log(f"-> Response Body: {book_resp.text[:300]}")
-    #         return False
-
-    def cleanup(self):
-        self._log("Cleaning up resources...")
-        if self.page:
-            try: self.page.quit()
-            except: pass
-        if os.path.exists(self.workspace):
-            time.sleep(1)
-            shutil.rmtree(self.workspace, ignore_errors=True)
-
-# =====================================================================
-# 运行主逻辑
-# =====================================================================
-if __name__ == "__main__":
-    
-    # 填写你的账号配置
-    MY_CONFIG = {
-        # 账号信息
-        "account": {
-            "username": "mayun06@text.skin",
-            "password": "Visafly@111"
-        },
-        # 目标签证中心信息 (例如广州 TLS: cnCNG2fr)
-        "apt_config": {
-            "country": "cn",
-            "city": "Chengdu",     
-            "code": "cnCNG2fr" 
-        },
-        # 代理配置
-        "proxy": {
-            "proto": "http",
-            "ip": "127.0.0.1",   
-            "port": "7890",      
-            "username": "",      
-            "password": ""
-        },
-        # Capsolver API Key
-        "capsolver_key": "CAP-5441DD341DD3CC2FAEF0BE6FE493EE9A",
-        
-        # 查询的月份 (格式: MM-YYYY)
-        "interest_month": "06-2026",
-        
-        # 期望的日期范围
-        "expected_start_date": "2026-06-01",
-        "expected_end_date": "2026-06-30",
-        
-        # 目标标签: '' 是普通号, 'pta' 是 Prime 黄金时间号
-        "target_labels": [""] 
-    }
-
-    bot = TlsAutoBot(config=MY_CONFIG)
-    
-    try:
-        # 1. 登录
-        bot.login()
-        
-        # 2. 检查是否有号
-        slots = bot.query_slots()
-        
-        if slots:
-            bot._log(f"Found {len(slots)} total available slots in this month.")
-            # 3. 尝试预订
-            success = bot.book(slots)
-            if success:
-                print("\n🎉 Congratulations! Slot booked successfully!")
-            else:
-                print("\n⚠️ Failed to book the slot.")
-        else:
-            bot._log("No available slots found for the requested criteria.")
-        time.sleep(3600)
-    except Exception as e:
-        bot._log(f"Error occurred during execution: {str(e)}")
-    finally:
-        bot.cleanup()

+ 173 - 76
toolkit/captcha_breaker.py

@@ -1,84 +1,181 @@
-import base64
 import os
 import os
+import io
+import mimetypes
+import base64
+from typing import Union, Optional, Any
 from openai import OpenAI
 from openai import OpenAI
 
 
-QWEN_API_KEY = "sk-893e895724c6403d81374e515ffaf427"
-
-def encode_image_to_base64(image_path):
-    with open(image_path, "rb") as image_file:
-        return base64.b64encode(image_file.read()).decode('utf-8')
-
-def recognize_captcha_with_qwen(image_path, api_key):
-    # 利用 OpenAI 的包,调用阿里云的兼容 API 接口
-    client = OpenAI(
-        api_key=api_key,
-        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
-    )
-    
-    base64_image = encode_image_to_base64(image_path)
-    
-    prompt = "你是一个精确的OCR机器人。请识别图片中的验证码字符。只输出验证码本身的内容,不要任何多余的汉字或标点符号。"
-
-    try:
-        response = client.chat.completions.create(
-            model="qwen-vl-max", # 也可以用更便宜的 qwen-vl-plus
-            messages=[
-                {
-                    "role": "user",
-                    "content":[
-                        {"type": "text", "text": prompt},
-                        {
-                            "type": "image_url",
-                            "image_url": {
-                                "url": f"data:image/png;base64,{base64_image}"
-                            }
-                        }
-                    ]
-                }
-            ],
-            temperature=0.0
+from configure import CAPTCHA_LLM_CONFIG
+
+class CaptchaBreakerError(Exception):
+    """验证码识别异常基类"""
+    pass
+
+def normalize_image_to_data_url(
+    image_input: Union[str, bytes, io.BytesIO],
+    default_mime_type: str = "image/png"
+) -> str:
+    """
+    将多种图片输入形式(文件路径、字节数据、BytesIO、Base64字符串、Data URL)
+    标准化为可供多模态模型接收的 Data URL (data:<mime-type>;base64,<data>)
+    """
+    if isinstance(image_input, (bytes, bytearray)):
+        b64_str = base64.b64encode(image_input).decode("utf-8")
+        return f"data:{default_mime_type};base64,{b64_str}"
+
+    if isinstance(image_input, io.BytesIO):
+        b64_str = base64.b64encode(image_input.getvalue()).decode("utf-8")
+        return f"data:{default_mime_type};base64,{b64_str}"
+
+    if isinstance(image_input, str):
+        # 已经是标准 Data URL
+        if image_input.startswith("data:image/"):
+            return image_input
+
+        # 如果是本地存在的文件路径
+        if os.path.isfile(image_input):
+            mime_type, _ = mimetypes.guess_type(image_input)
+            mime_type = mime_type or default_mime_type
+            with open(image_input, "rb") as f:
+                b64_str = base64.b64encode(f.read()).decode("utf-8")
+            return f"data:{mime_type};base64,{b64_str}"
+
+        # 尝试作为纯 Base64 字符串处理
+        clean_b64 = image_input.strip()
+        return f"data:{default_mime_type};base64,{clean_b64}"
+
+    raise ValueError(f"Unsupported image input type: {type(image_input)}")
+
+
+class CaptchaBreaker:
+    """
+    通用大模型验证码识别器
+    支持基于 OpenAI 兼容协议的多模态大模型端点(如 Qwen-VL, GPT-4o, DeepSeek-VL, OneAPI 等)
+    """
+    DEFAULT_PROMPT = "你是一个精确的OCR机器人。请识别图片中的验证码字符。只输出验证码本身的内容,不要任何多余的汉字或标点符号。"
+
+    def __init__(
+        self,
+        api_key: Optional[str] = None,
+        base_url: Optional[str] = None,
+        model: Optional[str] = None,
+        timeout: Optional[float] = None,
+        client: Optional[OpenAI] = None
+    ):
+        # 配置读取逻辑:
+        # 1. 优先使用构造函数传入的参数
+        # 2. 如果 CAPTCHA_LLM_CONFIG 是字典,从中读取
+        # 3. 如果 CAPTCHA_LLM_CONFIG 为 None 或未提供,从环境变量读取
+        cfg = CAPTCHA_LLM_CONFIG if isinstance(CAPTCHA_LLM_CONFIG, dict) else {}
+
+        self.api_key = api_key or cfg.get("api_key") or os.getenv("CAPTCHA_LLM_API_KEY")
+        self.base_url = (
+            base_url
+            or cfg.get("base_url")
+            or os.getenv("CAPTCHA_LLM_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
+        )
+        self.model = (
+            model
+            or cfg.get("model")
+            or os.getenv("CAPTCHA_LLM_MODEL", "qwen-vl-max")
         )
         )
-        return response.choices[0].message.content.strip()
-    except Exception as e:
-        print(f"Qwen 识别错误: {e}")
-        return None
-    
-def recognize_vfs_captcha_with_qwen(base64_image):
-    # 利用 OpenAI 的包,调用阿里云的兼容 API 接口
-    client = OpenAI(
-        api_key=QWEN_API_KEY,
-        base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
-    )
         
         
-    prompt = "图片中有多组验证码,其中OTP箭头指向的验证码为真,其余为假。只输出真实验证码的内容,不要任何多余的汉字或标点符号。"
-
-    try:
-        response = client.chat.completions.create(
-            model="qwen-vl-max", # 也可以用更便宜的 qwen-vl-plus
-            messages=[
-                {
-                    "role": "user",
-                    "content":[
-                        {"type": "text", "text": prompt},
-                        {
-                            "type": "image_url",
-                            "image_url": {
-                                "url": base64_image
+        timeout_val = timeout or cfg.get("timeout") or os.getenv("CAPTCHA_LLM_TIMEOUT")
+        self.timeout = float(timeout_val) if timeout_val is not None else 30.0
+
+        self._client = client
+
+    @property
+    def client(self) -> OpenAI:
+        """获取或延迟初始化 OpenAI 客户端"""
+        if self._client is None:
+            if not self.api_key:
+                raise CaptchaBreakerError(
+                    "API Key is not configured for CaptchaBreaker. "
+                    "CAPTCHA_LLM_CONFIG is None and CAPTCHA_LLM_API_KEY environment variable is not set."
+                )
+            self._client = OpenAI(
+                api_key=self.api_key,
+                base_url=self.base_url,
+                timeout=self.timeout
+            )
+        return self._client
+
+    def _clean_result(self, text: str) -> str:
+        """清理大模型返回的验证码文本,去除 markdown 代码块标记与前后符号"""
+        result = text.strip()
+        # 移除 markdown 代码块包裹 (如 ``` 或 ```text ... ```)
+        if result.startswith("```"):
+            lines = result.splitlines()
+            if len(lines) >= 2 and lines[-1].strip() == "```":
+                result = "\n".join(lines[1:-1]).strip()
+        # 去除首尾常见的引号
+        if (result.startswith('"') and result.endswith('"')) or (result.startswith("'") and result.endswith("'")):
+            result = result[1:-1].strip()
+        return result
+
+    def break_captcha(
+        self,
+        image: Union[str, bytes, io.BytesIO],
+        prompt: Optional[str] = None,
+        temperature: float = 0.0,
+        **kwargs: Any
+    ) -> str:
+        """
+        识别验证码
+        :param image: 图片输入,支持文件路径、二进制字节、BytesIO 或 Base64 / Data URL 字符串
+        :param prompt: 提示词,默认使用通用字符 OCR 提示词
+        :param temperature: 采样温度,默认为 0.0 以保证确定性
+        :param kwargs: 透传给 chat.completions.create 的额外参数
+        :return: 识别出的验证码文本
+        :raises CaptchaBreakerError: 调用失败或无法解析时抛出
+        """
+        data_url = normalize_image_to_data_url(image)
+        used_prompt = prompt or self.DEFAULT_PROMPT
+
+        try:
+            response = self.client.chat.completions.create(
+                model=self.model,
+                messages=[
+                    {
+                        "role": "user",
+                        "content": [
+                            {"type": "text", "text": used_prompt},
+                            {
+                                "type": "image_url",
+                                "image_url": {
+                                    "url": data_url
+                                }
                             }
                             }
-                        }
-                    ]
-                }
-            ],
-            temperature=0.0
-        )
-        return response.choices[0].message.content.strip()
-    except Exception as e:
-        print(f"Qwen 识别错误: {e}")
-        return None
+                        ]
+                    }
+                ],
+                temperature=temperature,
+                **kwargs
+            )
+            raw_content = response.choices[0].message.content or ""
+            return self._clean_result(raw_content)
+        except CaptchaBreakerError:
+            raise
+        except Exception as e:
+            raise CaptchaBreakerError(f"Captcha recognition failed [{self.model}]: {e}") from e
+
+    def __call__(
+        self,
+        image: Union[str, bytes, io.BytesIO],
+        prompt: Optional[str] = None,
+        **kwargs: Any
+    ) -> str:
+        """支持将实例作为函数直接调用"""
+        return self.break_captcha(image, prompt=prompt, **kwargs)
 
 
-if __name__ == "__main__":
-    # 填入阿里云百炼 (DashScope) 的 API-KEY
 
 
-    IMAGE_PATH = "/home/jerry/workspace/coordinator/data/275c31f009e612b65eb92cb52bb1d98.png"
-    
-    print(f"Qwen-VL 识别结果: {recognize_vfs_captcha_with_qwen(IMAGE_PATH, QWEN_API_KEY)}")
+if __name__ == "__main__":
+    import sys
+    print("CaptchaBreaker initialized.")
+    if len(sys.argv) > 1:
+        test_path = sys.argv[1]
+        breaker = CaptchaBreaker()
+        print(f"Testing recognition on: {test_path}")
+        res = breaker.break_captcha(test_path)
+        print(f"Result: {res}")

+ 675 - 0
tools/plugin_tester.py

@@ -0,0 +1,675 @@
+import os
+import sys
+import json
+import time
+import argparse
+from typing import Optional, Dict, Any, List, Callable
+from dataclasses import dataclass, field
+from datetime import datetime
+
+project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+if project_root not in sys.path:
+    sys.path.insert(0, project_root)
+
+from vs_plg import IVSPlg
+from vs_plg_factory import VSPlgFactory
+from vs_types import (
+    VSPlgConfig, 
+    VSAccount, 
+    VSProxy, 
+    AppointmentType, 
+    AvailabilityStatus, 
+    VSQueryResult, 
+    VSBookResult, 
+    PluginStatus
+)
+
+# 默认插件注册映射表
+DEFAULT_PLUGIN_MAP = {
+    "tls_plugin": ("plugins/tls_plugin.py", "TlsPlugin"),
+    "vfs_plugin": ("plugins/vfs_plugin.py", "VfsPlugin"),
+    "usa_plugin": ("plugins/usa_plugin.py", "UsaPlugin"),
+    "pol_plugin": ("plugins/pol_plugin.py", "PolPlugin"),
+    "ita_plugin": ("plugins/ita_plugin.py", "ItaPlugin"),
+    "bel_plugin": ("plugins/bel_plugin.py", "BelPlugin"),
+    "de_plugin": ("plugins/de_plugin.py", "DePlugin"),
+    "bls_plugin": ("plugins/bls_plugin.py", "BlsPlugin"),
+    "grc_plugin": ("plugins/grc_plugin.py", "GrcPlugin"),
+}
+
+
+@dataclass
+class StepResult:
+    name: str
+    success: bool
+    duration_sec: float
+    message: str = ""
+    data: Any = None
+    error: Optional[Exception] = None
+
+
+class PluginTester:
+    """
+    通用签证插件测试类
+    """
+    def __init__(
+        self,
+        plugin_name: str,
+        group_id: str = "test.group",
+        config: Optional[VSPlgConfig] = None,
+        user_inputs: Optional[Dict[str, Any]] = None,
+        appointment_types: Optional[List[AppointmentType]] = None,
+        custom_module_path: Optional[str] = None,
+        custom_class_name: Optional[str] = None,
+        logger: Optional[Callable[[str], None]] = None
+    ):
+        self.plugin_name = plugin_name
+        self.group_id = group_id
+        self.config = config or self.create_default_config()
+        self.user_inputs = user_inputs or {}
+        self.appointment_types = appointment_types or []
+        self.custom_module_path = custom_module_path
+        self.custom_class_name = custom_class_name
+        self.custom_logger = logger
+        
+        self.factory = VSPlgFactory()
+        self._register_plugins()
+        
+        self.plugin: Optional[IVSPlg] = None
+        self.results: List[StepResult] = []
+
+    def _log(self, message: str, level: str = "INFO"):
+        tag = f"[PluginTester][{self.plugin_name}][{level}]"
+        formatted_msg = f"{tag} {message}"
+        if self.custom_logger:
+            self.custom_logger(formatted_msg)
+        else:
+            print(formatted_msg)
+
+    def _register_plugins(self):
+        for name, (mod_path, cls_name) in DEFAULT_PLUGIN_MAP.items():
+            full_path = os.path.join(project_root, mod_path)
+            if os.path.exists(full_path):
+                self.factory.register_plugin(name, full_path, cls_name)
+        if self.custom_module_path and self.custom_class_name:
+            self.factory.register_plugin(self.plugin_name, self.custom_module_path, self.custom_class_name)
+
+    @staticmethod
+    def parse_proxy_url(proxy_url: str) -> VSProxy:
+        """从字符串格式代理地址解析 VSProxy 对象"""
+        from urllib.parse import urlparse
+        parsed = urlparse(proxy_url if "://" in proxy_url else f"http://{proxy_url}")
+        return VSProxy(
+            id=1,
+            proto=parsed.scheme or "http",
+            ip=parsed.hostname or "127.0.0.1",
+            port=parsed.port or 8080,
+            username=parsed.username or "",
+            password=parsed.password or ""
+        )
+
+    @staticmethod
+    def create_default_config(
+        username: str = "test_user@example.com",
+        password: str = "TestPassword123!",
+        proxy_url: Optional[str] = None,
+        free_config: Optional[Dict[str, Any]] = None,
+        debug: bool = True
+    ) -> VSPlgConfig:
+        """快速构建 VSPlgConfig 配置对象"""
+        account = VSAccount(
+            id=1,
+            username=username,
+            password=password
+        )
+        proxy = VSProxy()
+        if proxy_url:
+            proxy = PluginTester.parse_proxy_url(proxy_url)
+
+        return VSPlgConfig(
+            account=account,
+            proxy=proxy,
+            free_config=free_config or {},
+            session_max_life=3600,
+            debug=debug
+        )
+
+    @classmethod
+    def from_json_config(
+        cls, 
+        plugin_name: str, 
+        config_path: str, 
+        group_id: Optional[str] = None,
+        user_override: Optional[str] = None,
+        password_override: Optional[str] = None,
+        proxy_override: Optional[str] = None
+    ) -> 'PluginTester':
+        """
+        从 JSON 配置文件加载并初始化测试器
+        支持单个插件配置或复合 test_conf.json (带 "default" 与 "plugins" 结构)
+        """
+        with open(config_path, "r", encoding="utf-8") as f:
+            root_data = json.load(f)
+        
+        default_data = root_data.get("default", {})
+        plugin_data = {}
+
+        if "plugins" in root_data and isinstance(root_data["plugins"], dict):
+            plugin_data = root_data["plugins"].get(plugin_name, {})
+        elif plugin_name in root_data and isinstance(root_data[plugin_name], dict):
+            plugin_data = root_data[plugin_name]
+        else:
+            plugin_data = root_data
+
+        # 1. 账号解析 (优先使用 plugin 独立配置,回退到 default,再应用 CLI override)
+        account_data = plugin_data.get("account") or default_data.get("account") or {}
+        username = user_override or account_data.get("username", "")
+        password = password_override or account_data.get("password", "")
+        account = VSAccount(
+            id=account_data.get("id", 1),
+            username=username,
+            password=password
+        )
+        
+        # 2. 代理解析 (CLI override > plugin 独立配置 > default)
+        if proxy_override:
+            proxy = cls.parse_proxy_url(proxy_override)
+        else:
+            proxy_data = plugin_data.get("proxy") or default_data.get("proxy")
+            proxy = VSProxy()
+            if proxy_data:
+                proxy = VSProxy(
+                    id=proxy_data.get("id", 1),
+                    proto=proxy_data.get("proto", "http"),
+                    ip=proxy_data.get("ip", ""),
+                    port=int(proxy_data.get("port", 8080)),
+                    username=proxy_data.get("username", ""),
+                    password=proxy_data.get("password", "")
+                )
+            
+        free_config = plugin_data.get("free_config", {})
+        session_max_life = plugin_data.get("session_max_life", default_data.get("session_max_life", 3600))
+        debug = plugin_data.get("debug", default_data.get("debug", True))
+
+        config = VSPlgConfig(
+            account=account,
+            proxy=proxy,
+            free_config=free_config,
+            session_max_life=session_max_life,
+            debug=debug
+        )
+
+        resolved_group_id = group_id or plugin_data.get("group_id") or "test.group"
+        user_inputs = plugin_data.get("user_inputs", {})
+
+        # 3. 预约类型列表解析
+        raw_apts = plugin_data.get("appointment_types", [])
+        appointment_types = []
+        for apt in raw_apts:
+            if isinstance(apt, dict):
+                appointment_types.append(AppointmentType(
+                    routing_key=apt.get("routing_key", ""),
+                    city=apt.get("city", ""),
+                    country=apt.get("country", ""),
+                    visa_type=apt.get("visa_type", ""),
+                    weight=apt.get("weight", 10)
+                ))
+
+        return cls(
+            plugin_name=plugin_name, 
+            group_id=resolved_group_id, 
+            config=config,
+            user_inputs=user_inputs,
+            appointment_types=appointment_types
+        )
+
+    @classmethod
+    def load_all_from_json(cls, config_path: str) -> List['PluginTester']:
+        """从复合配置文件加载全部已定义的插件测试实例"""
+        with open(config_path, "r", encoding="utf-8") as f:
+            root_data = json.load(f)
+
+        testers = []
+        plugins_dict = root_data.get("plugins")
+        if not plugins_dict or not isinstance(plugins_dict, dict):
+            # 尝试直接检查顶层键
+            plugins_dict = {k: v for k, v in root_data.items() if k != "default" and isinstance(v, dict)}
+
+        for plg_name in plugins_dict.keys():
+            tester = cls.from_json_config(plugin_name=plg_name, config_path=config_path)
+            testers.append(tester)
+
+        return testers
+
+    # =========================================================================
+    # 单步测试阶段 (Step Runners)
+    # =========================================================================
+
+    def test_init(self) -> StepResult:
+        """测试 1: 实例化插件并设置配置与日志"""
+        t0 = time.time()
+        self._log("▶ [Step 1/7] Initializing plugin instance and configuration...")
+        try:
+            self.plugin = self.factory.create(self.group_id, self.plugin_name)
+            if not self.plugin:
+                raise RuntimeError(f"Factory failed to create instance for plugin '{self.plugin_name}'")
+            
+            self.plugin.set_config(self.config)
+            self.plugin.set_log(self._log)
+            
+            info = self.plugin.get_plugin_info()
+            self._log(f"✅ Plugin successfully initialized: {info}")
+            res = StepResult(name="test_init", success=True, duration_sec=time.time() - t0, data=info)
+        except Exception as e:
+            self._log(f"❌ test_init failed: {e}", level="ERROR")
+            res = StepResult(name="test_init", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_create_session(self) -> StepResult:
+        """测试 2: 建立会话并执行登录/绕过反爬"""
+        t0 = time.time()
+        self._log("▶ [Step 2/7] Testing create_session()...")
+        if not self.plugin:
+            res = StepResult(name="test_create_session", success=False, duration_sec=0, message="Plugin not initialized")
+            self.results.append(res)
+            return res
+
+        try:
+            self.plugin.create_session()
+            self._log("✅ create_session() executed successfully.")
+            res = StepResult(name="test_create_session", success=True, duration_sec=time.time() - t0)
+        except Exception as e:
+            self._log(f"❌ create_session() failed: {e}", level="ERROR")
+            res = StepResult(name="test_create_session", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_health_check(self) -> StepResult:
+        """测试 3: 检查会话健康状态"""
+        t0 = time.time()
+        self._log("▶ [Step 3/7] Testing health_check()...")
+        if not self.plugin:
+            res = StepResult(name="test_health_check", success=False, duration_sec=0, message="Plugin not initialized")
+            self.results.append(res)
+            return res
+
+        try:
+            is_healthy = self.plugin.health_check()
+            self._log(f"✅ health_check() returned: {is_healthy}")
+            res = StepResult(name="test_health_check", success=is_healthy, duration_sec=time.time() - t0, data=is_healthy)
+        except Exception as e:
+            self._log(f"❌ health_check() failed: {e}", level="ERROR")
+            res = StepResult(name="test_health_check", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_query(self, routing_key: Optional[str] = None) -> StepResult:
+        """测试 4: 查询预约号源"""
+        t0 = time.time()
+        self._log("▶ [Step 4/7] Testing query()...")
+        if not self.plugin:
+            res = StepResult(name="test_query", success=False, duration_sec=0, message="Plugin not initialized")
+            self.results.append(res)
+            return res
+
+        try:
+            # 根据 appointment_types 或 free_config 智能构建 AppointmentType
+            if routing_key:
+                apt_type = AppointmentType(
+                    routing_key=routing_key,
+                    country=self.config.free_config.get("country_code", "CHN"),
+                    city=self.config.free_config.get("center_code", "SHA"),
+                    visa_type="Tourist"
+                )
+            elif self.appointment_types:
+                apt_type = self.appointment_types[0]
+            else:
+                apt_configs = self.config.free_config.get("apt_configs", {})
+                first_key = list(apt_configs.keys())[0] if apt_configs else f"{self.group_id}.default"
+                apt_type = AppointmentType(
+                    routing_key=first_key,
+                    country=self.config.free_config.get("country_code", "CHN"),
+                    city=self.config.free_config.get("center_code", "SHA"),
+                    visa_type="Tourist"
+                )
+
+            query_result: VSQueryResult = self.plugin.query(apt_type)
+            self._log(f"✅ query() returned success={query_result.success}, status={query_result.availability_status}")
+            if query_result.earliest_date:
+                self._log(f"📅 Earliest Available Date: {query_result.earliest_date.strftime('%Y-%m-%d')}")
+            
+            res = StepResult(name="test_query", success=True, duration_sec=time.time() - t0, data=query_result)
+        except Exception as e:
+            self._log(f"❌ query() failed: {e}", level="ERROR")
+            res = StepResult(name="test_query", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_book(self, slot_info: Optional[VSQueryResult] = None, user_inputs: Optional[Dict] = None) -> StepResult:
+        """测试 5: 执行预约锁定"""
+        t0 = time.time()
+        self._log("▶ [Step 5/7] Testing book()...")
+        if not self.plugin:
+            res = StepResult(name="test_book", success=False, duration_sec=0, message="Plugin not initialized")
+            self.results.append(res)
+            return res
+
+        if not slot_info:
+            target_apt = self.appointment_types[0] if self.appointment_types else AppointmentType(routing_key=f"{self.group_id}.default")
+            slot_info = VSQueryResult(
+                success=True,
+                availability_status=AvailabilityStatus.Available,
+                earliest_date=datetime.now(),
+                apt_type=target_apt
+            )
+
+        inputs = user_inputs or self.user_inputs or {
+            "first_name": "San",
+            "last_name": "Zhang",
+            "passport_no": "E12345678",
+            "email": self.config.account.username if self.config and self.config.account else "test@example.com"
+        }
+
+        try:
+            book_res: VSBookResult = self.plugin.book(slot_info=slot_info, user_inputs=inputs)
+            self._log(f"✅ book() returned: success={book_res.success}, urn={book_res.urn}, date={book_res.book_date} {book_res.book_time}")
+            res = StepResult(name="test_book", success=book_res.success, duration_sec=time.time() - t0, data=book_res)
+        except Exception as e:
+            self._log(f"❌ book() failed: {e}", level="ERROR")
+            res = StepResult(name="test_book", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_status(self) -> StepResult:
+        """测试 6: 获取插件当前状态与指标"""
+        t0 = time.time()
+        self._log("▶ [Step 6/7] Testing get_plugin_status()...")
+        if not self.plugin:
+            res = StepResult(name="test_status", success=False, duration_sec=0, message="Plugin not initialized")
+            self.results.append(res)
+            return res
+
+        try:
+            status: PluginStatus = self.plugin.get_plugin_status()
+            self._log(f"✅ get_plugin_status(): is_healthy={status.is_healthy}, account={status.account}, age={status.session_age_sec}s")
+            res = StepResult(name="test_status", success=True, duration_sec=time.time() - t0, data=status)
+        except Exception as e:
+            self._log(f"❌ get_plugin_status() failed: {e}", level="ERROR")
+            res = StepResult(name="test_status", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    def test_cleanup(self) -> StepResult:
+        """测试 7: 销毁浏览器与释放临时文件资源"""
+        t0 = time.time()
+        self._log("▶ [Step 7/7] Testing cleanup()...")
+        if not self.plugin:
+            res = StepResult(name="test_cleanup", success=True, duration_sec=0, message="Plugin was not initialized")
+            self.results.append(res)
+            return res
+
+        try:
+            self.plugin.cleanup()
+            self._log("✅ cleanup() executed successfully.")
+            res = StepResult(name="test_cleanup", success=True, duration_sec=time.time() - t0)
+        except Exception as e:
+            self._log(f"❌ cleanup() failed: {e}", level="ERROR")
+            res = StepResult(name="test_cleanup", success=False, duration_sec=time.time() - t0, error=e, message=str(e))
+        
+        self.results.append(res)
+        return res
+
+    # =========================================================================
+    # Pipeline 流水线全自动执行
+    # =========================================================================
+
+    def run_pipeline(
+        self,
+        test_book: bool = False,
+        user_inputs: Optional[Dict] = None,
+        auto_cleanup: bool = True,
+        keep_on_error: bool = False
+    ) -> bool:
+        """
+        顺序执行完整流水线测试并打印汇总诊断报告
+        """
+        self.results.clear()
+        self._log("=" * 60)
+        self._log(f"🚀 Starting Full Test Pipeline for [{self.plugin_name}]")
+        self._log("=" * 60)
+
+        all_passed = True
+        slot_info = None
+
+        try:
+            # 1. Init
+            r = self.test_init()
+            if not r.success:
+                all_passed = False
+                if keep_on_error and getattr(self, "plugin", None):
+                    self.plugin.keep_browser_on_error = True
+                return False
+
+            # 2. Create Session
+            r = self.test_create_session()
+            if not r.success:
+                all_passed = False
+                if keep_on_error and getattr(self, "plugin", None):
+                    self.plugin.keep_browser_on_error = True
+                return False
+
+            # 3. Health Check
+            r = self.test_health_check()
+            if not r.success:
+                all_passed = False
+                if keep_on_error and getattr(self, "plugin", None):
+                    self.plugin.keep_browser_on_error = True
+
+            # 4. Status Check
+            r = self.test_status()
+            if not r.success:
+                all_passed = False
+                if keep_on_error and getattr(self, "plugin", None):
+                    self.plugin.keep_browser_on_error = True
+
+            # 5. Query
+            r = self.test_query()
+            if not r.success:
+                all_passed = False
+                if keep_on_error and getattr(self, "plugin", None):
+                    self.plugin.keep_browser_on_error = True
+            else:
+                slot_info = r.data
+
+            # 6. Book (Optional)
+            if test_book:
+                inputs = user_inputs or self.user_inputs
+                r = self.test_book(slot_info=slot_info, user_inputs=inputs)
+                if not r.success:
+                    all_passed = False
+                    if keep_on_error and getattr(self, "plugin", None):
+                        self.plugin.keep_browser_on_error = True
+
+            # 7. Final Status
+            self.test_status()
+
+        except Exception as e:
+            all_passed = False
+            if keep_on_error and getattr(self, "plugin", None):
+                self.plugin.keep_browser_on_error = True
+            self._log(f"💥 Pipeline 发生未捕获异常: {e}", level="ERROR")
+        finally:
+            if not all_passed and keep_on_error:
+                self._log("[PluginTester] ⚠️ 测试发生失败/异常且指定了 --keep-on-error,保留浏览器窗口以便排查分析(跳过 cleanup)。", level="WARN")
+            elif auto_cleanup:
+                self.test_cleanup()
+            self._print_report()
+
+        return all_passed
+
+    def _print_report(self):
+        """打印格式化测试结果报告"""
+        print("\n" + "=" * 65)
+        print(f"📊 [Test Report Summary] Plugin: {self.plugin_name} (Group: {self.group_id})")
+        print("=" * 65)
+        print(f"{'Step Name':<20} | {'Status':<10} | {'Duration (s)':<12} | {'Details'}")
+        print("-" * 65)
+
+        total_duration = 0.0
+        all_ok = True
+
+        for res in self.results:
+            total_duration += res.duration_sec
+            status_str = "✅ PASS" if res.success else "❌ FAIL"
+            if not res.success:
+                all_ok = False
+            details = res.message or ""
+            if res.data and not details:
+                details = str(res.data)[:40]
+            print(f"{res.name:<20} | {status_str:<10} | {res.duration_sec:<12.2f} | {details}")
+
+        print("-" * 65)
+        overall_status = "🎉 ALL TESTS PASSED" if all_ok else "💥 SOME TESTS FAILED"
+        print(f"Overall Result: {overall_status} | Total Time: {total_duration:.2f}s")
+        print("=" * 65 + "\n")
+
+
+# =============================================================================
+# CLI 命令行入口
+# =============================================================================
+
+def resolve_config_path(config_arg: Optional[str]) -> Optional[str]:
+    """
+    智能解析配置文件路径:
+    1. 传入路径存在则直接使用
+    2. 检查相对于 project_root 的路径
+    3. 检查 project_root/config/ 下同名文件
+    4. 回退到 project_root/config/test_conf.json 或 test_conf.json
+    """
+    if config_arg:
+        candidates = [
+            config_arg,
+            os.path.join(project_root, config_arg),
+            os.path.join(project_root, "config", config_arg),
+            os.path.join(project_root, "config", os.path.basename(config_arg)),
+        ]
+        for c in candidates:
+            if c and os.path.exists(c) and os.path.isfile(c):
+                return os.path.abspath(c)
+
+    # 默认搜索位置
+    defaults = [
+        os.path.join(project_root, "config", "test_conf.json"),
+        os.path.join(project_root, "test_conf.json"),
+        os.path.join(os.getcwd(), "config", "test_conf.json"),
+        os.path.join(os.getcwd(), "test_conf.json")
+    ]
+    for d in defaults:
+        if os.path.exists(d) and os.path.isfile(d):
+            return os.path.abspath(d)
+    return None
+
+
+def main():
+    parser = argparse.ArgumentParser(description="Universal Plugin Test Runner (PluginTester)")
+    parser.add_argument("plugin_pos", nargs="?", default=None, help="Plugin identifier (positional, e.g. vfs_plugin, tls_plugin)")
+    parser.add_argument("--plugin", "-p", help="Plugin identifier (e.g., vfs_plugin, tls_plugin, or 'all')")
+    parser.add_argument("--group", "-g", help="Group identifier override")
+    parser.add_argument("--config", "-c", default=None, help="Path to JSON configuration file (default: config/test_conf.json)")
+    parser.add_argument("--user", "-u", help="Username / Email credential override")
+    parser.add_argument("--password", "-pwd", help="Password credential override")
+    parser.add_argument("--proxy", help="Proxy URL override (e.g. http://user:pass@ip:port)")
+    parser.add_argument("--book", action="store_true", help="Run booking test step")
+    parser.add_argument("--no-cleanup", action="store_true", help="Do not automatically cleanup browser on finish")
+    parser.add_argument("--keep-on-error", action="store_true", default=False, help="Do not close browser if any error/exception occurs during test (default: False)")
+    parser.add_argument("--only-init", action="store_true", help="Only test initialization and exit")
+    
+    args = parser.parse_args()
+
+    target_plugin = args.plugin or args.plugin_pos
+    config_path = resolve_config_path(args.config)
+
+    if config_path:
+        print(f"[PluginTester] Using configuration file: {config_path}")
+    elif args.config:
+        print(f"[PluginTester] Error: Specified config file '{args.config}' not found.")
+        sys.exit(1)
+
+    # 如果指定了单个 plugin
+    if target_plugin and target_plugin.lower() != "all":
+        if config_path:
+            tester = PluginTester.from_json_config(
+                plugin_name=target_plugin, 
+                config_path=config_path, 
+                group_id=args.group,
+                user_override=args.user,
+                password_override=args.password,
+                proxy_override=args.proxy
+            )
+        else:
+            print("[PluginTester] Warning: No test_conf.json found, using basic default config.")
+            cfg = PluginTester.create_default_config(
+                username=args.user or "test_user@example.com",
+                password=args.password or "TestPassword123!",
+                proxy_url=args.proxy
+            )
+            tester = PluginTester(plugin_name=target_plugin, group_id=args.group or "test.group", config=cfg)
+
+        if args.only_init:
+            res = tester.test_init()
+            sys.exit(0 if res.success else 1)
+
+        passed = tester.run_pipeline(
+            test_book=args.book,
+            auto_cleanup=not args.no_cleanup,
+            keep_on_error=args.keep_on_error
+        )
+        sys.exit(0 if passed else 1)
+
+    # 如果未指定 plugin 或 target_plugin == all,且存在配置文件,则遍历执行所有插件
+    elif config_path:
+        testers = PluginTester.load_all_from_json(config_path)
+        if not testers:
+            print(f"[PluginTester] No plugins found in {config_path}")
+            sys.exit(1)
+
+        overall_passed = True
+        for tester in testers:
+            if args.group:
+                tester.group_id = args.group
+            if args.user:
+                tester.config.account.username = args.user
+            if args.password:
+                tester.config.account.password = args.password
+            if args.proxy:
+                tester.config.proxy = PluginTester.parse_proxy_url(args.proxy)
+
+            if args.only_init:
+                res = tester.test_init()
+                if not res.success:
+                    overall_passed = False
+            else:
+                passed = tester.run_pipeline(
+                    test_book=args.book,
+                    auto_cleanup=not args.no_cleanup,
+                    keep_on_error=args.keep_on_error
+                )
+                if not passed:
+                    overall_passed = False
+
+        sys.exit(0 if overall_passed else 1)
+    else:
+        print("[PluginTester] Error: Please specify --plugin or provide a valid --config JSON file.")
+        parser.print_help()
+        sys.exit(1)
+
+
+if __name__ == "__main__":
+    main()

+ 233 - 85
utils/cloudflare_bypass_for_scraping.py

@@ -1,122 +1,270 @@
+"""
+Cloudflare 挑战自动化穿透工具模块。
+
+针对 Cloudflare Turnstile / 5秒盾(Managed Challenge)提供高效、稳定的穿透能力。
+核心设计理念:
+1. 快速精准定位:定向穿透隐藏 turnstile input 对应的 shadow_root 宿主容器及嵌套 iframe,
+   无需遍历全局 DOM,执行耗时 < 0.2s。
+2. 异常自愈回退:提供可控深度的 DFS 备用探测策略。
+3. 等待室自适应排队:支持 Waiting Room 自动轮询处理。
+4. 代码风格标准:严格遵循 Pythonic 规范,杜绝使用 hasattr,保证属性访问安全与可维护性。
+"""
+
 import time
 import time
-from DrissionPage import ChromiumPage 
+from typing import Optional, Callable
+from DrissionPage import ChromiumPage
+from DrissionPage._elements.chromium_element import ChromiumElement
 
 
 
 
 class CloudflareBypasser:
 class CloudflareBypasser:
-    def __init__(self, driver: ChromiumPage, log=False, logger=None):
+    """
+    Cloudflare 页面挑战识别与穿透处理器
+    """
+
+    def __init__(
+        self,
+        driver: ChromiumPage,
+        log: bool = False,
+        logger: Optional[Callable[[str], None]] = None
+    ) -> None:
         self.driver = driver
         self.driver = driver
         self.log = log
         self.log = log
         self.logger = logger
         self.logger = logger
+
+    def log_message(self, message: str) -> None:
+        """统一日志输出辅助方法"""
+        if not self.log:
+            return
+        formatted = f"[CF-Bypass] {message}"
+        if self.logger:
+            if callable(self.logger):
+                try:
+                    self.logger(formatted)
+                except TypeError:
+                    self.logger(message)
+            else:
+                log_fn = getattr(self.logger, "info", print)
+                log_fn(formatted)
+        else:
+            print(formatted)
+
+    def _extract_turnstile_button_from_host(self, host_ele: Optional[ChromiumElement]) -> Optional[ChromiumElement]:
+        """
+        从挂载 Shadow Root 的宿主容器元素中提取 Turnstile 复选框按钮。
         
         
-    def log_message(self, message):
-        if self.log:
-            if self.logger:
-                self.logger(f"[CF-Bypass] {message}")
-    
-    def search_recursively_shadow_root_with_iframe(self, ele, depth=0, max_depth=3):
-        if depth > max_depth:
+        DOM 层级链路:
+        Host Element (div)
+          └─ shadow_root
+              └─ child (iframe)
+                  └─ body
+                      └─ shadow_root
+                          └─ input[type=checkbox]
+        """
+        if not host_ele:
             return None
             return None
 
 
         try:
         try:
-            if ele.shadow_root:
-                child = ele.shadow_root.child()
-                if child and child.tag == "iframe":
-                    return child
-            else:
-                for child in ele.children():
-                    result = self.search_recursively_shadow_root_with_iframe(child, depth + 1, max_depth)
-                    if result:
-                        return result
-        except Exception:
-            pass 
-        return None
+            host_sr = getattr(host_ele, "shadow_root", None)
+            if not host_sr:
+                return None
 
 
-    def search_recursively_shadow_root_with_cf_input(self, ele):
-        if ele.shadow_root:
-            if ele.shadow_root.ele("tag:input"):
-                return ele.shadow_root.ele("tag:input")
-        else:
-            for child in ele.children():
-                result = self.search_recursively_shadow_root_with_cf_input(child)
-                if result:
-                    return result
-        return None
-    
-    def locate_cf_button(self, dfs=False):
+            iframe = host_sr.child()
+            if not iframe:
+                return None
+
+            body = iframe("tag:body")
+            if not body:
+                return None
+
+            body_sr = getattr(body, "shadow_root", None)
+            if not body_sr:
+                return None
+
+            return body_sr("tag:input")
+        except Exception as e:
+            self.log_message(f"Error extracting button from host element: {e}")
+            return None
+
+    def locate_cf_button(self, dfs: bool = False) -> Optional[ChromiumElement]:
+        """
+        定位 Cloudflare 验证复选框按钮。
+        
+        策略 1(主路径,毫秒级):扫描主文档中的 'cf-turnstile-response' 隐藏 input,
+        其父级容器或同级兄弟 div 即为真实 shadow_root 宿主,直接提取目标按钮。
+        
+        策略 2(备用路径):若主路径未命中且显式开启 dfs=True,则从 body 递归搜索。
+        """
         try:
         try:
-            button = None
+            # --- 策略 1: 基于隐藏 Turnstile input 的定向穿透 ---
             eles = self.driver.eles("tag:input")
             eles = self.driver.eles("tag:input")
             for ele in eles:
             for ele in eles:
-                attrs = ele.attrs
-                if "name" in attrs and "type" in attrs:
-                    if "turnstile" in attrs["name"] and attrs["type"] == "hidden":
-                        if ele.parent() and ele.parent().shadow_root:
-                            button = ele.parent().shadow_root.child()("tag:body").shadow_root("tag:input")
-                            break
-
-            if button:
-                return button
-            else:
-                if dfs:
-                    ele = self.driver.ele("tag:body")
-                    iframe = self.search_recursively_shadow_root_with_iframe(ele)
+                attrs = getattr(ele, "attrs", {})
+                name = attrs.get("name", "")
+                inp_type = attrs.get("type", "")
+
+                if "turnstile" in name and inp_type == "hidden":
+                    parent = ele.parent()
+                    if not parent:
+                        continue
+
+                    # 兼容不同版本 Turnstile 容器结构:
+                    # A. parent 本身挂载 shadow_root
+                    # B. parent 内部的前置同级 <div> 挂载 shadow_root
+                    host_candidates = [parent]
+                    sibling_div = parent.ele("tag:div", timeout=0.3)
+                    if sibling_div:
+                        host_candidates.append(sibling_div)
+
+                    for candidate in host_candidates:
+                        button = self._extract_turnstile_button_from_host(candidate)
+                        if button:
+                            self.log_message("Target verification button located via Turnstile host div.")
+                            return button
+
+            # --- 策略 2: 备用递归深度搜索 (DFS) ---
+            if dfs:
+                self.log_message("Basic search missed. Initiating fallback DFS...")
+                body = self.driver.ele("tag:body")
+                if body:
+                    iframe = self.search_recursively_shadow_root_with_iframe(body)
                     if iframe:
                     if iframe:
-                        return self.search_recursively_shadow_root_with_cf_input(iframe("tag:body"))
+                        iframe_body = iframe("tag:body")
+                        if iframe_body:
+                            return self.search_recursively_shadow_root_with_cf_input(iframe_body)
+
             return None
             return None
 
 
         except Exception as e:
         except Exception as e:
-            if self.log:
-                self.log_message(f"Error locating verification button: {e}")
+            self.log_message(f"Error locating verification button: {e}")
             return None
             return None
-    
-    def click_verification_button(self, is_dfs):
+
+    def search_recursively_shadow_root_with_iframe(
+        self, ele: Optional[ChromiumElement], depth: int = 0, max_depth: int = 3
+    ) -> Optional[ChromiumElement]:
+        """递归检索挂载在 shadow_root 下的 iframe"""
+        if depth > max_depth or not ele:
+            return None
+
+        try:
+            sr = getattr(ele, "shadow_root", None)
+            if sr:
+                child = sr.child()
+                if child and getattr(child, "tag", "") == "iframe":
+                    return child
+            else:
+                children = getattr(ele, "children", None)
+                if callable(children):
+                    for child in children():
+                        result = self.search_recursively_shadow_root_with_iframe(child, depth + 1, max_depth)
+                        if result:
+                            return result
+        except Exception:
+            pass
+        return None
+
+    def search_recursively_shadow_root_with_cf_input(
+        self, ele: Optional[ChromiumElement]
+    ) -> Optional[ChromiumElement]:
+        """递归检索挂载在 shadow_root 下的目标 input 按钮"""
+        if not ele:
+            return None
+
+        try:
+            sr = getattr(ele, "shadow_root", None)
+            if sr:
+                inp = sr.ele("tag:input")
+                if inp:
+                    return inp
+            else:
+                children = getattr(ele, "children", None)
+                if callable(children):
+                    for child in children():
+                        result = self.search_recursively_shadow_root_with_cf_input(child)
+                        if result:
+                            return result
+        except Exception:
+            pass
+        return None
+
+    def click_verification_button(self, is_dfs: bool = False) -> bool:
+        """
+        定位并执行点击 Cloudflare 验证按钮。
+        :return: 是否成功点击
+        """
         try:
         try:
             button = self.locate_cf_button(dfs=is_dfs)
             button = self.locate_cf_button(dfs=is_dfs)
-            if button:
-                self.log_message("Verification button found. Attempting to click.")
-                if button.states.is_displayed and button.states.is_enabled:
-                    button.click()
-                    time.sleep(1)
-                else:
-                    self.log_message("Button is not clickable.")
+            if not button:
+                self.log_message("Verification button not found.")
+                return False
+
+            states = getattr(button, "states", None)
+            displayed = getattr(states, "is_displayed", False) if states else False
+            enabled = getattr(states, "is_enabled", False) if states else False
+
+            if displayed and enabled:
+                self.log_message("Verification button clickable. Executing click...")
+                button.click()
+                time.sleep(1.0)
+                self.log_message("Click executed successfully.")
+                return True
+            else:
+                self.log_message(f"Button found (<{button.tag}>) but unclickable (displayed={displayed}, enabled={enabled}).")
+                return False
+
         except Exception as e:
         except Exception as e:
-            if self.log:
-                self.log_message(f"Error clicking verification button: {e}")
+            self.log_message(f"Error clicking verification button: {e}")
+            return False
 
 
-    def is_bypassed(self):
+    def is_bypassed(self) -> bool:
+        """
+        根据当前页面标题判断是否已经脱离 Cloudflare 挑战页面。
+        """
         try:
         try:
-            title = self.driver.title.lower()
+            title = (getattr(self.driver, "title", "") or "").lower()
             return "just a moment" not in title and "请稍候" not in title
             return "just a moment" not in title and "请稍候" not in title
         except Exception as e:
         except Exception as e:
-            if self.log:
-                self.log_message(f"Error checking page title: {e}")
-        return False
+            self.log_message(f"Error checking page title: {e}")
+            return False
 
 
-    def bypass(self, max_retry=5):
+    def bypass(self, max_retry: int = 5, use_dfs: bool = False) -> bool:
+        """
+        执行穿透循环直至挑战通过或达到最大重试次数。
+        """
         for i in range(max_retry):
         for i in range(max_retry):
             if self.is_bypassed():
             if self.is_bypassed():
+                self.log_message("Cloudflare challenge bypassed successfully.")
                 return True
                 return True
-            self.log_message(f"Verification page detected. Trying to bypass times={i}...")
-            self.click_verification_button(False)
-            time.sleep(2)
-        return self.is_bypassed()
-    
-    def handle_waiting_room(self):
+
+            self.log_message(f"Verification page detected. Attempting bypass (try {i + 1}/{max_retry})...")
+            self.click_verification_button(is_dfs=use_dfs)
+            time.sleep(2.0)
+
+        final_bypassed = self.is_bypassed()
+        if final_bypassed:
+            self.log_message("Cloudflare challenge bypassed on final check.")
+        else:
+            self.log_message(f"[WARN] Failed to clear challenge after {max_retry} attempts.")
+        return final_bypassed
+
+    def handle_waiting_room(self, max_wait_sec: int = 3600) -> bool:
+        """
+        检测并等待 Cloudflare 等候室(Waiting Room)自动刷新放行。
+        """
         wait_start = time.time()
         wait_start = time.time()
-        while True:
+        while time.time() - wait_start < max_wait_sec:
             try:
             try:
-                html = self.driver.html.lower()
+                html = (getattr(self.driver, "html", "") or "").lower()
                 if "cloudflare" not in html:
                 if "cloudflare" not in html:
-                    break
-                if "file d'attente" in html or "waitting room" in html:
-                    if time.time() - wait_start > 60 * 60:
-                        self.log_message("Waiting room timeout (1h).")
-                        break
-                    self.log_message("In Waiting Room... Waiting for auto-refresh.")
-                    time.sleep(10)
+                    return True
+
+                if any(w in html for w in ["file d'attente", "waitting room", "waiting room"]):
+                    self.log_message("In Waiting Room... Waiting for queue to refresh (sleeping 10s)...")
+                    time.sleep(10.0)
                 else:
                 else:
-                    break
+                    return True
             except Exception as e:
             except Exception as e:
-                if self.log:
-                    self.log_message(f"Error checking html: {e}")
+                self.log_message(f"Error checking html in waiting room: {e}")
+                break
+
+        return True
             
             

+ 278 - 0
utils/flow_engine.py

@@ -0,0 +1,278 @@
+"""
+flow_engine.py - 极简声明式注解流引擎 (基于 DrissionPage 原生 API)
+"""
+
+import time
+from typing import Optional, Callable, Dict, Any, Type
+from vs_types import BizLogicError
+
+
+def on(url: Optional[str] = None, 
+       title: Optional[str] = None, 
+       text: Optional[str] = None, 
+       ele: Optional[str] = None, 
+       not_ele: Optional[str] = None, 
+       predicate: Optional[Callable[['BaseFlow'], bool]] = None,
+       priority: int = 100):
+    """主匹配注解:页面满足条件时触发对应动作方法(支持同一方法堆叠多个注解,形成 OR 关系)"""
+    def decorator(func: Callable):
+        rule_spec = {
+            "url": url, 
+            "title": title, 
+            "text": text, 
+            "ele": ele, 
+            "not_ele": not_ele, 
+            "predicate": predicate,
+            "priority": priority,
+            "is_done": getattr(func, "_is_done", False),
+            "fatal_msg": getattr(func, "_fatal_msg", None),
+            "exception_cls": getattr(func, "_exception_cls", BizLogicError)
+        }
+        rules = getattr(func, "_flow_rules", None)
+        if rules is None:
+            rules = []
+            func._flow_rules = rules
+        rules.append(rule_spec)
+        func._flow_rule = rule_spec
+        return func
+    return decorator
+
+
+def done(func: Callable):
+    """终态注解:执行完后退出并标记成功"""
+    func._is_done = True
+    for r in getattr(func, "_flow_rules", []):
+        r["is_done"] = True
+    return func
+
+
+def fatal(error_msg: str, exception_cls: Type[Exception] = BizLogicError):
+    """致命错误注解:命中时抛出异常终止流程"""
+    def decorator(func: Callable):
+        func._fatal_msg = error_msg
+        func._exception_cls = exception_cls
+        for r in getattr(func, "_flow_rules", []):
+            r["fatal_msg"] = error_msg
+            r["exception_cls"] = exception_cls
+        return func
+    return decorator
+
+
+def guard(url: Optional[str] = None, 
+          title: Optional[str] = None, 
+          text: Optional[str] = None, 
+          ele: Optional[str] = None, 
+          not_ele: Optional[str] = None, 
+          predicate: Optional[Callable[['BaseFlow'], bool]] = None,
+          priority: int = 10):
+    """高优先级异常守卫注解"""
+    return on(url=url, title=title, text=text, ele=ele, not_ele=not_ele, predicate=predicate, priority=priority)
+
+
+class BaseFlow:
+    """
+    轻量注解状态机驱动引擎
+    """
+    def __init__(self, 
+                 page, 
+                 config: Optional[Dict[str, Any]] = None, 
+                 context: Optional[Dict[str, Any]] = None, 
+                 interval: float = 1.0, 
+                 logger: Optional[Callable[[str], None]] = None, 
+                 cf_bypasser=None,
+                 max_stuck_cycles: Optional[int] = 30):
+        self.page = page
+        self.config = config or {}
+        self.context = context if context is not None else {}
+        self.result = None
+        self.interval = interval
+        self.cf_bypasser = cf_bypasser
+        self._logger = logger
+        
+        self.last_url = ""
+        self.stuck_count = 0
+        self.max_stuck_cycles = max_stuck_cycles
+        
+        # 收集注解方法并按 priority 升序排序
+        self._rules = []
+        for attr_name in dir(self):
+            try:
+                method = getattr(self, attr_name)
+                if callable(method):
+                    for r in getattr(method, "_flow_rules", []):
+                        rule = r.copy()
+                        rule["is_done"] = getattr(method, "_is_done", rule.get("is_done", False))
+                        rule["fatal_msg"] = getattr(method, "_fatal_msg", rule.get("fatal_msg", None))
+                        rule["exception_cls"] = getattr(method, "_exception_cls", rule.get("exception_cls", BizLogicError))
+                        rule["method"] = method
+                        rule["name"] = attr_name
+                        self._rules.append(rule)
+            except Exception:
+                continue
+
+        self._rules.sort(key=lambda r: r["priority"])
+
+    def log(self, msg: str, level: str = "info"):
+        if self._logger is not None:
+            log_fn = getattr(self._logger, level.lower(), getattr(self._logger, "info", None))
+            if callable(log_fn):
+                log_fn(f"[{self.__class__.__name__}] {msg}")
+            elif callable(self._logger):
+                self._logger(f"[{self.__class__.__name__}] {msg}")
+            else:
+                print(f"[{self.__class__.__name__}] [{level.upper()}] {msg}")
+        else:
+            print(f"[{self.__class__.__name__}] [{level.upper()}] {msg}")
+
+    def _matches(self, rule: Dict[str, Any]) -> bool:
+        """根据 URL、Title、Text、Ele 及自定义 Predicate 判定是否命中规则"""
+        # 防呆机制:如果没有任何匹配条件,直接视为不匹配,防止无条件空转造成死循环
+        if not any([
+            rule.get("url"),
+            rule.get("title"),
+            rule.get("text"),
+            rule.get("ele"),
+            rule.get("not_ele"),
+            rule.get("predicate"),
+        ]):
+            return False
+
+        curr_url = getattr(self.page, "url", "") or ""
+        curr_title = getattr(self.page, "title", "") or ""
+
+        if rule["url"] and rule["url"] not in curr_url:
+            return False
+
+        if rule["title"] and rule["title"].lower() not in curr_title.lower():
+            return False
+
+        if rule["text"]:
+            try:
+                curr_html = getattr(self.page, "html", "") or ""
+                if rule["text"] not in curr_html:
+                    return False
+            except Exception:
+                return False
+
+        if rule["ele"]:
+            try:
+                if not self.page.ele(rule["ele"], timeout=0.2):
+                    return False
+            except Exception:
+                return False
+
+        if rule["not_ele"]:
+            try:
+                if self.page.ele(rule["not_ele"], timeout=0.2):
+                    return False
+            except Exception:
+                pass
+
+        if rule.get("predicate"):
+            try:
+                if not rule["predicate"](self):
+                    return False
+            except Exception as e:
+                self.log(f"[WARN] 规则 @{rule.get('name', 'unknown')} 的 predicate 执行异常: {e}", level="warning")
+                return False
+
+        return True
+
+    def run(self, 
+            max_steps: Optional[int] = None, 
+            timeout: Optional[float] = None, 
+            max_stuck_cycles: Optional[int] = None) -> Any:
+        """
+        执行扫描调度循环,支持步数与超时时间双重限制
+        :param max_steps: 最大循环步数限制,为 None 时表示不限制步数
+        :param timeout: 最大执行超时时间(秒),为 None 时表示不限制时间
+        :param max_stuck_cycles: 页面停滞自愈刷新周期,若提供则覆盖实例配置,为 None 则关闭停滞刷新
+        """
+        if max_stuck_cycles is not None:
+            self.max_stuck_cycles = max_stuck_cycles
+
+        start_time = time.time()
+        step = 0
+
+        # 构建展示信息
+        limits_desc = []
+        if max_steps is not None:
+            limits_desc.append(f"max_steps={max_steps}")
+        if timeout is not None:
+            limits_desc.append(f"timeout={timeout}s")
+        limits_str = f" (限制: {', '.join(limits_desc)})" if limits_desc else " (无限制模式)"
+
+        self.log(f"🚀 启动流程状态机,加载了 {len(self._rules)} 条规则{limits_str}")
+
+        while True:
+            step += 1
+            elapsed = time.time() - start_time
+
+            # 1. 检查步数限制
+            if max_steps is not None and step > max_steps:
+                raise BizLogicError(
+                    f"流程步数耗尽(已执行 {step - 1} 步 / 上限 {max_steps} 步,耗时 {elapsed:.1f}s),最后停留在: {getattr(self.page, 'url', '')}"
+                )
+
+            # 2. 检查超时限制
+            if timeout is not None and elapsed > timeout:
+                raise BizLogicError(
+                    f"流程执行超时(已耗时 {elapsed:.1f}s / 上限 {timeout:.1f}s,已执行 {step - 1} 步),最后停留在: {getattr(self.page, 'url', '')}"
+                )
+
+            # 格式化步骤标识前缀
+            if max_steps is not None and timeout is not None:
+                step_prefix = f"[{step}/{max_steps} | {elapsed:.1f}s/{timeout:.1f}s]"
+            elif max_steps is not None:
+                step_prefix = f"[{step}/{max_steps} | {elapsed:.1f}s]"
+            elif timeout is not None:
+                step_prefix = f"[Step {step} | {elapsed:.1f}s/{timeout:.1f}s]"
+            else:
+                step_prefix = f"[Step {step} | {elapsed:.1f}s]"
+
+            try:
+                self.page.wait.doc_loaded(timeout=5)
+            except Exception:
+                pass
+
+            time.sleep(self.interval)
+
+            curr_url = getattr(self.page, "url", "")
+            # 停滞检测与刷新自愈(若启用)
+            if self.max_stuck_cycles is not None and self.max_stuck_cycles > 0:
+                if curr_url and curr_url == self.last_url:
+                    self.stuck_count += 1
+                    if self.stuck_count >= self.max_stuck_cycles:
+                        self.log(f"{step_prefix} [WARN] 页面停滞达 {self.stuck_count} 周期,执行刷新自愈...", level="warning")
+                        try:
+                            self.page.refresh()
+                            self.page.wait.load_start(timeout=5)
+                        except Exception as e:
+                            self.log(f"[ERROR] 刷新页面失败: {e}", level="error")
+                        self.stuck_count = 0
+                        continue
+                else:
+                    self.last_url, self.stuck_count = curr_url, 0
+
+            # 按优先级匹配规则
+            matched_rule = None
+            for rule in self._rules:
+                if self._matches(rule):
+                    matched_rule = rule
+                    self.log(f"{step_prefix} 🎯 命中规则: @{rule['name']} (priority={rule['priority']})")
+                    
+                    if rule["fatal_msg"]:
+                        self.log(f"💥 触发致命错误中断: {rule['fatal_msg']}", level="error")
+                        exc_cls = rule.get("exception_cls", BizLogicError)
+                        raise exc_cls(rule["fatal_msg"])
+                    
+                    rule["method"]()
+                    
+                    if rule["is_done"]:
+                        self.log(f"✨ 目标达成,流程完成!(耗时 {time.time() - start_time:.1f}s,共执行 {step} 步)")
+                        return self.result if self.result is not None else True
+                    
+                    break
+
+            if not matched_rule:
+                self.log(f"{step_prefix} ⏳ 未匹配到注解规则 (URL: {curr_url}),等待下一周期...")

+ 489 - 0
utils/plugin_utils.py

@@ -0,0 +1,489 @@
+"""
+plugin_utils.py - 签证插件通用基础工具模块
+提供浏览器响应封装、Options/隧道初始化、JS Fetch 注入、截图、日期筛选、验证码求解及 Cookie 弹窗处理等通用函数
+"""
+
+import os
+import json
+import time
+import socket
+import random
+import shutil
+from datetime import datetime
+from typing import List, Dict, Optional, Any, Callable, Tuple
+from urllib.parse import urlencode
+
+import configure
+from vs_types import BizLogicError, NotFoundError
+from toolkit.mihomo_tunnel import MihomoTunnel
+from utils.fingerprint_utils import FingerprintGenerator
+from DrissionPage import ChromiumOptions
+
+
+# ---------------------------------------------------------------------------
+# 1. 响应封装类
+# ---------------------------------------------------------------------------
+
+class BrowserResponse:
+    """封装在浏览器上下文内执行 JS Fetch 返回的响应对象"""
+    def __init__(self, result_dict: Optional[Dict[str, Any]] = None):
+        result_dict = result_dict or {}
+        self.status_code = result_dict.get('status', 0)
+        self.text = result_dict.get('body', '')
+        self.headers = result_dict.get('headers', {})
+        self.url = result_dict.get('url', '')
+        self._json = None
+
+    def json(self) -> Dict[str, Any]:
+        if self._json is None:
+            if not self.text:
+                return {}
+            try:
+                self._json = json.loads(self.text)
+            except Exception:
+                self._json = {}
+        return self._json
+
+    @property
+    def content(self) -> bytes:
+        return self.text.encode('utf-8')
+
+
+# ---------------------------------------------------------------------------
+# 2. 网络端口与浏览器启动选项
+# ---------------------------------------------------------------------------
+
+def get_free_port() -> int:
+    """获取本地随机空闲 TCP 端口"""
+    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
+        s.bind(('', 0))
+        return s.getsockname()[1]
+
+
+def init_chromium_options(
+    user_data_path: str,
+    username_seed: Optional[str] = None,
+    proxy: Optional[Any] = None,
+    headless: bool = False,
+    window_size: str = "1920,1080",
+    debug_port: Optional[int] = None,
+    logger: Optional[Callable[[str], None]] = None
+) -> Tuple[ChromiumOptions, Optional[MihomoTunnel]]:
+    """
+    配置并返回 ChromiumOptions 以及(若启用了中转)创建好的 MihomoTunnel 实例
+    
+    :param user_data_path: 浏览器用户数据存储目录
+    :param username_seed: 用于生成确定性指纹的账号特征种子
+    :param proxy: 代理配置对象(含 ip, port, proto, username, password)
+    :param headless: 是否使用无头模式
+    :param window_size: 初始窗口尺寸 (宽,高)
+    :param debug_port: 本地调试端口,不传则自动获取
+    :param logger: 日志回调函数
+    :return: (co, tunnel)
+    """
+    def _log(msg: str):
+        if logger:
+            logger(msg)
+
+    co = ChromiumOptions()
+    port = debug_port if debug_port is not None else get_free_port()
+    co.set_local_port(port)
+    co.set_user_data_path(user_data_path)
+    
+    chrome_path = configure.CHROME_PATH or os.getenv("CHROME_BIN")
+    if chrome_path and os.path.exists(chrome_path):
+        co.set_paths(browser_path=chrome_path)
+
+    tunnel = None
+    if proxy and getattr(proxy, 'ip', None):
+        if getattr(proxy, 'username', None) and getattr(proxy, 'password', None):
+            _log(f"Starting Proxy Tunnel for {proxy.ip}:{proxy.port}...")
+            exit_node = {
+                "name": "ExitNode",
+                "type": proxy.proto,
+                "server": proxy.ip,
+                "port": proxy.port,
+                "username": proxy.username,
+                "password": proxy.password
+            }
+            relay_node = None
+            if configure.MIHOMO_RELAY_NODES:
+                relay_node = random.choice(configure.MIHOMO_RELAY_NODES)
+            mihomo_path = configure.MIHOMO_BIN_PATH or os.getenv("MIHOMO_BIN")
+            if not mihomo_path:
+                raise BizLogicError(message='Mihomo path is null, You need set mihomo bin path in configure or os env')
+            tunnel = MihomoTunnel(mihomo_path, exit_node=exit_node, relay_node=relay_node)
+            local_proxy = tunnel.start()
+            _log(f"Tunnel started at {local_proxy}")
+            co.set_argument(f'--proxy-server={local_proxy}')
+        else:
+            proxy_str = f"{proxy.proto}://{proxy.ip}:{proxy.port}"
+            co.set_argument(f'--proxy-server={proxy_str}')
+    else:
+        _log("[WARN] No proxy configured!")
+
+    seed = username_seed or "default"
+    specific_fp = FingerprintGenerator().generate(seed)
+    fp_seed = specific_fp.get("seed")
+    fp_platform = specific_fp.get("platform")
+    fp_brand = specific_fp.get("brand")
+    _log(f'Browser fingerprint seed={fp_seed}, platform={fp_platform}')
+
+    co.headless(headless)
+    co.set_argument('--no-sandbox')
+    co.set_argument('--disable-dev-shm-usage')
+    co.set_argument(f'--window-size={window_size}')
+    co.set_argument('--disable-blink-features=AutomationControlled')
+    co.set_argument(f"--fingerprint={fp_seed}")
+    co.set_argument(f"--fingerprint-platform={fp_platform}")
+    co.set_argument(f"--fingerprint-brand={fp_brand}")
+
+    return co, tunnel
+
+
+# ---------------------------------------------------------------------------
+# 3. 浏览器内 JS Fetch 注入请求
+# ---------------------------------------------------------------------------
+
+def perform_browser_fetch(
+    page,
+    method: str,
+    url: str,
+    headers: Optional[Dict[str, str]] = None,
+    data: Optional[Any] = None,
+    json_data: Optional[Any] = None,
+    params: Optional[Dict[str, Any]] = None,
+    timeout: int = 30
+) -> BrowserResponse:
+    """
+    在 DrissionPage 浏览器页面上下文内注入并执行原生 fetch 请求
+    """
+    if not page:
+        raise BizLogicError("Browser page is not initialized")
+
+    if params:
+        query_str = urlencode(params)
+        url += ('&' if '?' in url else '?') + query_str
+
+    fetch_options: Dict[str, Any] = {
+        "method": method.upper(),
+        "headers": headers or {},
+        "credentials": "include"
+    }
+
+    if json_data is not None:
+        fetch_options['body'] = json.dumps(json_data)
+        fetch_options['headers']['Content-Type'] = 'application/json'
+    elif data is not None:
+        if isinstance(data, dict):
+            fetch_options['body'] = urlencode(data)
+            fetch_options['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
+        else:
+            fetch_options['body'] = str(data)
+
+    js_script = f"""
+    const url = "{url}";
+    const options = {json.dumps(fetch_options)};
+    
+    return fetch(url, options)
+        .then(async response => {{
+            const text = await response.text();
+            const headers = {{}};
+            response.headers.forEach((value, key) => headers[key] = value);
+            return {{
+                status: response.status,
+                body: text,
+                headers: headers,
+                url: response.url
+            }};
+        }})
+        .catch(error => {{
+            return {{
+                status: 0,
+                body: error.toString(),
+                headers: {{}},
+                url: url
+            }};
+        }});
+    """
+
+    res_dict = page.run_js(js_script, timeout=timeout)
+    return BrowserResponse(res_dict)
+
+
+# ---------------------------------------------------------------------------
+# 4. 辅助工具(截图、日期过滤、验证码求解、Cookie处理)
+# ---------------------------------------------------------------------------
+
+def save_screenshot(
+    page,
+    instance_id: str,
+    name_prefix: str,
+    save_dir: str = "data",
+    full_page: bool = False,
+    logger: Optional[Callable[[str], None]] = None
+) -> Optional[str]:
+    """保存页面截图至本地目录"""
+    if not page:
+        return None
+    try:
+        timestamp = int(time.time())
+        filename = f"{instance_id}_{name_prefix}_{timestamp}.jpg"
+        save_path = os.path.join(save_dir, filename)
+        os.makedirs(save_dir, exist_ok=True)
+        page.get_screenshot(path=save_path, full_page=full_page)
+        if logger:
+            logger(f"Screenshot saved to {save_path}")
+        return save_path
+    except Exception as e:
+        if logger:
+            logger(f"Failed to save screenshot: {e}")
+        return None
+
+
+def filter_dates_in_range(
+    dates: List[str],
+    start_str: Optional[str] = None,
+    end_str: Optional[str] = None,
+    shuffle: bool = True
+) -> List[str]:
+    """
+    按起止日期范围筛选日期列表(格式: YYYY-MM-DD)
+    """
+    if not start_str or not end_str:
+        return list(dates)
+    
+    valid_dates = []
+    s_date = datetime.strptime(start_str[:10], "%Y-%m-%d")
+    e_date = datetime.strptime(end_str[:10], "%Y-%m-%d")
+    for date_str in dates:
+        try:
+            curr_date = datetime.strptime(date_str[:10], "%Y-%m-%d")
+            if s_date <= curr_date <= e_date:
+                valid_dates.append(date_str)
+        except Exception:
+            continue
+
+    if shuffle:
+        random.shuffle(valid_dates)
+    return valid_dates
+
+
+def solve_capsolver_recaptcha(
+    api_token: str,
+    site_key: str,
+    page_url: str,
+    proxy: Optional[Any] = None,
+    task_type: str = "ReCaptchaV2TaskProxyLess",
+    action: Optional[str] = None
+) -> str:
+    """
+    调用 Capsolver API 异步求解 ReCaptchaV2
+    """
+    if not api_token:
+        raise NotFoundError("Api-token required for capsolver")
+
+    import requests as req
+    submit_url = "https://api.capsolver.com/createTask"
+    task: Dict[str, Any] = {
+        "type": task_type,
+        "websiteURL": page_url,
+        "websiteKey": site_key,
+    }
+    if action:
+        task["pageAction"] = action
+
+    if proxy and proxy.ip and not task_type.endswith("ProxyLess"):
+        task["proxyType"] = proxy.proto
+        task["proxyAddress"] = proxy.ip
+        task["proxyPort"] = proxy.port
+        if getattr(proxy, 'username', None):
+            task["proxyLogin"] = proxy.username
+            task["proxyPassword"] = proxy.password
+
+    payload = {"clientKey": api_token, "task": task}
+    r = req.post(submit_url, json=payload, timeout=20)
+    if r.status_code != 200:
+        raise BizLogicError(message="Failed to submit capsolver task")
+
+    task_id = r.json().get("taskId")
+    for _ in range(20):
+        res = req.post("https://api.capsolver.com/getTaskResult", json={"clientKey": api_token, "taskId": task_id}, timeout=20)
+        if res.status_code == 200:
+            d = res.json()
+            if d.get("status") == "ready":
+                return d["solution"]["gRecaptchaResponse"]
+        time.sleep(3)
+
+    raise BizLogicError(message="Capsolver task timeout")
+
+
+def solve_capsolver_hcaptcha(
+    api_token: str,
+    site_key: str,
+    page_url: str,
+    proxy: Optional[Any] = None,
+    task_type: str = "HCaptchaTaskProxyLess",
+    logger: Optional[Callable[[str], None]] = None
+) -> str:
+    """
+    调用 Capsolver API 异步求解 hCaptcha
+    """
+    if not api_token:
+        raise NotFoundError("Capsolver API key is required")
+
+    def _log(msg: str):
+        if logger:
+            logger(msg)
+
+    import requests as req
+    submit_url = "https://api.capsolver.com/createTask"
+    task: Dict[str, Any] = {
+        "type": task_type,
+        "websiteURL": page_url,
+        "websiteKey": site_key,
+    }
+
+    if proxy and getattr(proxy, 'ip', None):
+        task["proxyType"] = proxy.proto
+        task["proxyAddress"] = proxy.ip
+        task["proxyPort"] = proxy.port
+        if getattr(proxy, 'username', None):
+            task["proxyLogin"] = proxy.username
+            task["proxyPassword"] = proxy.password
+
+    payload = {"clientKey": api_token, "task": task}
+    _log("Submitting hCaptcha task to Capsolver...")
+    r = req.post(submit_url, json=payload, timeout=20)
+    if r.status_code != 200:
+        raise BizLogicError(message=f"Failed to create Capsolver task: {r.text}")
+
+    res_json = r.json()
+    if res_json.get("errorId", 0) != 0:
+        raise BizLogicError(message=f"Failed to create Capsolver task: {r.text}")
+
+    task_id = res_json.get("taskId")
+    if not task_id:
+        raise BizLogicError(message=f"No taskId returned from Capsolver: {r.text}")
+
+    _log(f"Waiting for hCaptcha solution (TaskId: {task_id})...")
+    start_time = time.time()
+    while time.time() - start_time < 120:
+        time.sleep(3)
+        res = req.post(
+            "https://api.capsolver.com/getTaskResult",
+            json={"clientKey": api_token, "taskId": task_id},
+            timeout=20
+        )
+        if res.status_code == 200:
+            result = res.json()
+            status = result.get("status")
+            if status == "ready":
+                solution = result.get("solution", {})
+                token = solution.get("gRecaptchaResponse") or solution.get("token") or solution.get("response")
+                _log("✅ hCaptcha solved successfully.")
+                return str(token)
+            if status == "failed":
+                raise BizLogicError(message=f"hCaptcha solve failed: {res.text}")
+
+    raise BizLogicError(message="Capsolver task timed out (120s)")
+
+
+def handle_cookie_consent(
+    page,
+    mouse=None,
+    timeout: int = 3,
+    logger: Optional[Callable[[str], None]] = None
+) -> bool:
+    """
+    通用 Cookie Consent 弹窗识别与自动处理(支持 OneTrust、Osano 等常见弹窗)
+    """
+    if not page:
+        return False
+    
+    # 1. 优先尝试 OneTrust 策略 (VFS 等站点)
+    try:
+        onetrust_js = """
+        try {
+            var acceptBtn = document.getElementById('onetrust-accept-btn-handler');
+            if (acceptBtn) {
+                acceptBtn.click();
+                return 'clicked';
+            }
+            var banner = document.getElementById('onetrust-banner-sdk');
+            if (banner) {
+                banner.style.display = 'none';
+                banner.remove();
+                return 'removed';
+            }
+        } catch(e) {}
+        return 'none';
+        """
+        ot_res = page.run_js(onetrust_js)
+        if ot_res in ('clicked', 'removed'):
+            if logger:
+                logger(f"Handled OneTrust cookie banner ({ot_res}).")
+            return True
+    except Exception:
+        pass
+
+    # 2. 尝试 Osano 及 ARIA 属性弹窗 (TLS 等站点)
+    try:
+        dialog = page.ele('@aria-label=Cookie Consent Banner', timeout=timeout)
+        if dialog:
+            target_btn = dialog.ele('tag:button@text():Save') or dialog.ele('tag:button@text():Accept') or dialog.ele('tag:button@text():Accept all')
+            if target_btn:
+                if mouse:
+                    mouse.human_click_ele(target_btn)
+                else:
+                    target_btn.click()
+                if logger:
+                    logger("Handled cookie consent dialog successfully.")
+                return True
+    except Exception as e:
+        if logger:
+            logger(f"Exception handling cookie dialog: {e}")
+
+    return False
+
+
+def cleanup_browser_workspace(
+    page=None,
+    root_workspace: Optional[str] = None,
+    tunnel=None,
+    logger: Optional[Callable[[str], None]] = None
+) -> None:
+    """
+    统一安全销毁浏览器实例、删除本地临时 workspace 目录并停止代理隧道
+    """
+    def _log(msg: str):
+        if logger:
+            logger(msg)
+
+    # 1. 销毁浏览器
+    if page:
+        try:
+            page.quit(force=True)
+        except Exception:
+            pass
+
+    # 2. 清理临时用户数据目录 (带多次重试与容错)
+    if root_workspace and os.path.exists(root_workspace):
+        for _ in range(3):
+            try:
+                time.sleep(0.2)
+                shutil.rmtree(root_workspace, ignore_errors=True)
+                break
+            except Exception as e:
+                _log(f"Cleanup workspace retry: {e}")
+                time.sleep(0.5)
+
+        if os.path.exists(root_workspace):
+            _log(f"[WARN] Failed to fully remove workspace: {root_workspace}")
+
+    # 3. 停止代理隧道
+    if tunnel:
+        try:
+            tunnel.stop()
+        except Exception:
+            pass

+ 1 - 1
utils/safe_redis_cli.py

@@ -25,7 +25,7 @@ class SafeRedisClient:
         try:
         try:
             return func(*args, **kwargs)
             return func(*args, **kwargs)
         except Exception as e:
         except Exception as e:
-            func_name = func.__name__ if hasattr(func, '__name__') else 'operation'
+            func_name = getattr(func, '__name__', 'operation')
             self._log(f"Attempt 1 failed ({func_name}): {e}. Retrying in 0.5s...")
             self._log(f"Attempt 1 failed ({func_name}): {e}. Retrying in 0.5s...")
             time.sleep(0.5)
             time.sleep(0.5)
             try:
             try:

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor