From 9a5b20d18901602b548a22b406c37a36305a35ef Mon Sep 17 00:00:00 2001 From: Christ Date: Tue, 14 Jul 2026 21:03:32 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E6=96=87=E6=A1=A3=EF=BC=9A=E5=86=BB?= =?UTF-8?q?=E7=BB=93=E6=BB=91=E5=9D=97=E8=AE=A4=E8=AF=81=E9=80=BB=E8=BE=91?= =?UTF-8?q?=E5=B9=B6=E5=AE=8C=E5=96=84=E9=A1=B9=E7=9B=AE=E7=9B=AE=E5=BD=95?= =?UTF-8?q?=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增仓库级 AGENTS.md,将滑块认证设为最高级别生产冻结区域,明确受保护文件、禁止的直接与间接变更,以及仅限用户当次明确授权的例外流程。 新增滑块认证冻结规范,完整记录标准 NC DOM 选择器、300px 减 42px 等于 258px 的精确距离、Playwright 主引擎轨迹与严格 x5sec 成功条件、失败重试和页面重载恢复、直接 Chromium/CDP 备用引擎、持久化 profile、诊断日志及必须保留的回归测试。 扩展 README 项目目录树,补充命令行工具、后端模块、前端、文档、脚本与本地数据目录职责,并增加冻结规范入口。 提交范围仅包含文档;README 中其他既有工作区改动未暂存。格式验证:git diff --cached --check 通过。 --- AGENTS.md | 133 ++++++++++++++ README.md | 35 +++- docs/slider-captcha-frozen-spec.md | 285 +++++++++++++++++++++++++++++ 3 files changed, 447 insertions(+), 6 deletions(-) create mode 100644 AGENTS.md create mode 100644 docs/slider-captcha-frozen-spec.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..74c0215 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,133 @@ +# AGENTS.md + +## Repository shape + +The active application contains: + +- `cmd/server/` — server entrypoint, administrator bootstrap (`-init-admin`), and HTTP server. +- `cmd/init-admin/` — interactive administrator initialization CLI. +- `cmd/dbverify/` — migration + core CRUD verification tool across SQLite/MySQL/Postgres. +- `internal/server/` — chi HTTP API and SPA serving. +- `internal/adapter/` — wiring layer that implements `engine.Handler` and `automation.OrderDetailFetcher` (system events → automation center, order-detail fetch / password-login refresh → browser, account alerts → notifier). +- `internal/account/` — enabled-account supervisor. +- `internal/engine/` — per-account runtime, replies, and delivery behavior. +- `internal/automation/` — unified automation center (paid delivery, review gifts, review requests) + scheduler. +- `internal/xianyu/` — MTOP, WebSocket, QR login, and protocol code. +- `internal/browser/` — in-process Chromium automation through playwright-go. +- `internal/db/` — multi-database access (SQLite/MySQL/Postgres) with embedded Goose migrations per dialect. +- `frontend/` — active React/Vite source. +- `internal/webui/static/` — embedded frontend build output. + +## Common commands + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-go + +make build # go build ./cmd/server +make test # go test ./... +make vet # go vet ./... +make lint # golangci-lint run ./... (0 issues baseline) +make check # vet + lint + test +make frontend # build frontend into internal/webui/static +``` + +Run the server (SQLite by default; MySQL/Postgres via `-db-url` or `DATABASE_URL`): + +```bash +go run ./cmd/server -db data/xianyu_data.db -addr :8080 +DATABASE_URL="mysql://user:pass@tcp(host:3306)/db" go run ./cmd/server -addr :8080 +``` + +Disable browser automation when Chromium is unavailable: + +```bash +go run ./cmd/server -db data/xianyu_data.db -addr :8080 -no-browser +``` + +Initialize or reset the administrator: + +```bash +go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '...' +``` + +Verify a database (migration + CRUD across dialects): + +```bash +go run ./cmd/dbverify "mysql://user:pass@tcp(host:3306)/db" +``` + +Run a focused test: + +```bash +go test ./internal/server -run TestName -v +go test ./internal/db -run TestMigrate -v +``` + +Cross-database regression (requires Docker containers or external DBs): + +```bash +TEST_MYSQL_URL="mysql://root:pass@tcp(host:3306)/db" \ +TEST_POSTGRES_URL="postgres://user:pass@host:5432/db" \ +go test ./internal/db -run TestMultiDB -v +``` + +Build the frontend: + +```bash +cd /Users/christ/Workspace/git/xianyu/xianyu-go/frontend +npm install +npm run build +``` + +Run the frontend development server: + +```bash +npm run dev +``` + +Vite proxies backend routes to `localhost:8080`. Production builds are written to `internal/webui/static/` and embedded by the Go server. + +## Architecture + +`cmd/server/main.go` opens the database (SQLite/MySQL/Postgres by URL scheme), constructs the adapter + account manager + automation center + notifier, starts enabled account runtimes, initializes the optional in-process browser manager, and starts the HTTP server. Business logic does not live in `main.go` — it delegates to `internal/adapter` (Handler/OrderDetailFetcher wiring), `internal/engine`, `internal/account`, `internal/automation`, and domain-specific server handlers. + +`internal/xianyu` owns lower-level platform integration: + +- `mtop` for signed HTTP calls (interface `mtop.Client` allows test mocking). +- `ws` for WebSocket transport. +- `qrlogin` for QR login. +- `protocol` for cookies, signing, decoding, and message IDs. + +Browser-backed verification, password login refresh, and order-detail fallbacks live in `internal/browser`. Keep the browser contract and its server/engine callers aligned. + +## Frozen slider CAPTCHA logic — DO NOT MODIFY + +The current slider CAPTCHA implementation is production-frozen. Its authoritative behavior is documented in `docs/slider-captcha-frozen-spec.md`. + +Unless the user explicitly requests a slider CAPTCHA behavior change in the current task, agents MUST NOT: + +- edit, refactor, optimize, rename, move, delete, or reformat the protected slider implementation or its tests; +- change selectors or selector priority, same-frame visibility checks, the exact `300px - 42px = 258px` standard NC distance, trajectories, point counts, timing, mouse-event order, or main-engine no-overshoot behavior; +- change fresh-`x5sec` success criteria, punish/captcha URL checks, retry selectors, retry text checks, origin checks, reload recovery, retry counts, or timeouts; +- change Playwright-first / direct-Chromium-CDP-fallback ordering, persistent-profile reuse and locking, verification-URL refresh timing, Cookie merge behavior, browser flags, environment defaults, or engine result labels; +- weaken, skip, delete, or rewrite slider tests to permit different behavior; +- modify a caller or shared helper in another file when that would indirectly change any frozen behavior above. + +Directly protected files are: + +- `internal/browser/slider.go` +- `internal/browser/slider_test.go` +- `internal/browser/token_captcha.go` +- `internal/browser/token_captcha_test.go` +- `internal/browser/token_captcha_fallback.go` +- `internal/browser/token_captcha_fallback_integration_test.go` +- `internal/browser/token_captcha_orchestrator_test.go` + +Only an explicit user instruction in the current task can authorize a change. When authorized, update the implementation, tests, and frozen specification together, and run every verification required by the specification. Do not treat one authorization as permission for later tasks. + +## Editing notes + +- Preserve unrelated working-tree changes. +- Update `frontend/vite.config.ts` if API route prefixes change. +- Rebuild the frontend after source changes so embedded assets stay current. +- Keep protocol and database behavior covered by focused tests. diff --git a/README.md b/README.md index 0f302f3..7b1a469 100644 --- a/README.md +++ b/README.md @@ -4,14 +4,37 @@ ```text xianyu-go/ - cmd/server/ Go 服务入口(含 -init-admin 非交互初始化) - cmd/init-admin/ 交互式初始化管理员 CLI - cmd/dbverify/ 三库迁移 + 核心 CRUD 验证工具 - internal/ Go 后端代码 - frontend/ 当前活跃 React 前端源码 - internal/webui/static/ 前端构建产物,Go 会内置并提供给浏览器 + cmd/ + server/ 服务入口、依赖装配、管理员非交互初始化 + init-admin/ 交互式管理员初始化 CLI + dbverify/ SQLite/MySQL/Postgres 迁移与 CRUD 验证 + dbseed/ Docker 功能测试所需的脱敏数据种子工具 + spike/ debug/tools 构建标签下的协议链路探针 + internal/ + account/ 已启用账号监督与生命周期管理 + adapter/ engine/automation 与浏览器、通知器的接线层 + auth/ 管理端会话认证与安全 Cookie + automation/ 发货、评价赠送、邀评自动化与调度器 + browser/ Playwright/Chromium 登录、风控验证、订单抓取 + db/ 三种数据库方言、模型、存储与嵌入式迁移 + engine/ 单账号运行时、消息处理、回复和发货行为 + logging/ 进程级结构化日志配置 + logsafe/ 敏感 ID 与 URL 的日志脱敏 + netguard/ 出站网络目标校验与 DNS rebinding 防护 + notify/ 账号告警和通知渠道 + renewal/ 登录态续期调度与冷却控制 + server/ chi HTTP API、鉴权和 SPA 服务 + webui/static/ 前端构建产物,由 Go 二进制嵌入 + xianyu/ MTOP、WebSocket、扫码登录和协议实现 + frontend/ 当前活跃 React/Vite 前端源码 + docs/ 运行、功能与不可变行为规范 + scripts/ Docker、持久化和功能回归脚本 + data/ 本地运行数据(不作为源码维护) ``` +目录职责以根目录 `AGENTS.md` 为准。滑块认证属于冻结逻辑,完整契约见 +[`docs/slider-captcha-frozen-spec.md`](docs/slider-captcha-frozen-spec.md);没有用户在当前任务中的明确授权,不得修改其实现、测试或任何会间接改变其行为的调用链。 + ## 数据库支持 支持三种数据库,由连接 URL 的 scheme 决定: diff --git a/docs/slider-captcha-frozen-spec.md b/docs/slider-captcha-frozen-spec.md new file mode 100644 index 0000000..911f375 --- /dev/null +++ b/docs/slider-captcha-frozen-spec.md @@ -0,0 +1,285 @@ +# 滑块认证冻结规范 + +> **冻结级别:最高。当前滑块认证逻辑是已验证的生产行为,不得修改。** +> +> 除非用户在当前任务中明确要求修改滑块认证,否则任何开发者或自动化代理都不得编辑、重构、优化、重命名、移动或删除本规范保护的实现和测试,也不得通过修改调用方、浏览器配置或共享工具间接改变其行为。 + +本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。 + +## 1. 保护范围 + +以下文件为直接保护对象: + +- `internal/browser/slider.go` +- `internal/browser/slider_test.go` +- `internal/browser/token_captcha.go` +- `internal/browser/token_captcha_test.go` +- `internal/browser/token_captcha_fallback.go` +- `internal/browser/token_captcha_fallback_integration_test.go` +- `internal/browser/token_captcha_orchestrator_test.go` + +下列行为即使位于其他文件中,也属于冻结范围: + +- `TokenCaptchaRecover` / `TokenCaptchaRecoverWithEngine` 的调用顺序、参数和返回语义。 +- 账号级持久化 Chromium profile 的目录解析、互斥、复用和释放时机。 +- 验证链接的获取、过期判断、重新获取时机和重试次数。 +- Cookie 注入、旧 `x5sec` 快照、新 `x5sec` 判定、合并和持久化。 +- Playwright 主引擎与直接 Chromium/CDP 备用引擎的启用条件和先后顺序。 +- 滑块 DOM 选择器及其优先级、同 frame 可见性要求、距离计算、轨迹、时序、成功判定、失败恢复和日志诊断。 + +禁止以“格式化”“去重”“抽取公共函数”“升级 Playwright”“增强兼容性”“提高成功率”“清理测试”等名义绕过冻结规则。 + +## 2. 标准 DOM 契约 + +当前无验证码(NC)页面的标准元素为: + +| 角色 | 首选选择器 | 标准尺寸 | +| --- | --- | --- | +| 滑块按钮 | `#nc_1_n1z` | 宽 `42px` | +| 滑轨 | `#nc_1_n1t` | 宽 `300px` | + +标准滑动距离固定按可用轨道宽度计算: + +```text +distance = track.width - button.width + = 300px - 42px + = 258px +``` + +不可把 `300px` 当作标准拖动距离,不可增加超调补偿。主引擎标准 NC 拖动的最终 X 必须精确落在 `258px`。 + +查找顺序和约束固定如下: + +1. 在主 frame 和所有 iframe 中,优先查找同一 frame 内同时可见的 `#nc_1_n1z` 与 `#nc_1_n1t`。 +2. 仅在精确选择器组合未找到时,才按现有顺序使用宽松选择器。 +3. 按钮与轨道必须同时可见且位于同一 frame;不可跨 frame 拼接元素。 + +主引擎按钮选择器顺序: + +```text +#nc_1_n1z +.nc_iconfont +.btn_slide +#scratch-captcha-btn +.scratch-captcha-slider .button +``` + +主引擎轨道选择器顺序: + +```text +#nc_1_n1t +.nc_scale +.nc_1_n1t +``` + +备用引擎必须精确等待可见的 `#nc_1_n1z`。轨道选择器顺序为: + +```text +#nc_1_n1t +.nc_scale +#nc_1__scale_text +.nc-lang-cnt +#nc_1_wrapper +.nc_wrapper +``` + +刮刮乐验证码继续通过 `scratch-captcha`、`scratch-captcha-btn` 或 `scratch-captcha-slider` 标记识别,并只滑标准距离的 `25%–35%`。不得把这条降级兼容逻辑用于标准 NC DOM。 + +## 3. 主引擎行为 + +主引擎使用 Playwright 和账号现有的持久化浏览器上下文,最多执行 3 次滑块尝试。 + +### 3.1 页面准备 + +- 浏览器总生命周期上限为 `45s`。 +- 页面导航等待 `domcontentloaded`,导航超时为 `10s`;导航异常只记录告警并继续检查页面。 +- 页面加载后随机等待 `0.3–0.8s`,移动鼠标到 `(640, 360)`,滚动 `200–500px`,并保留现有短暂停顿。 +- 页面包含“抱歉,页面访问出现了问题”时,判定验证链接过期。 +- 页面包含 `STATUS_BREAKPOINT` 或“崩溃”时,判定验证页崩溃。 +- 拖动前必须保存所有域上的旧 `x5sec` 值,供严格成功判定使用。 + +### 3.2 距离计算 + +距离计算顺序固定为: + +1. 用 DOM `getBoundingClientRect()` 计算 `track.width - button.width`。 +2. DOM 计算不可用时,用 Playwright bounding box 计算同一差值。 +3. 两者均不可用时,主引擎保留 `220–259px` 的现有降级距离。 +4. 仅刮刮乐场景再乘 `0.25–0.35`。 + +标准 NC 几何信息存在时,必须使用精确差值,不得随机化距离。 + +### 3.3 拖动轨迹 + +主引擎轨迹冻结为以下行为: + +- 按钮按下前,从按钮左侧附近自然接近,再悬停、对准按钮中心并停顿。 +- 按下后使用恰好 6 个高层轨迹点。 +- 轨迹分为加速、匀速、减速三段;带小幅 Y 轴抖动。 +- X 轴不超调,最后一个点强制等于计算出的精确距离。 +- 保留每个点的短随机计划延时,同时按真实墙钟时间补偿,使移动阶段处于 `480–900ms` 目标窗口。 +- 顺序固定为 `mouse down → 分段移动 → mouse up → 兼容性 click 事件`。 +- 标准 NC 不得添加尾部超调、回拉或额外轨迹点。 + +拖动完成后保留 `800ms` 等待,再进入严格成功检查。 + +## 4. 严格成功条件 + +Token 风控滑块只有同时满足以下两个条件才算成功: + +1. 浏览器上下文出现相对拖动前快照全新的、非空的 `x5sec`;旧值不得重复计为成功。 +2. 当前页面已经离开 punish/captcha URL。 + +以下 URL 标记任一存在时,仍视为停留在验证页: + +```text +punish +x5step=2 +action=captcha +purecaptcha +/captcha +``` + +`.nc-container` 消失、滑块隐藏、成功图标出现或 frame 断开都不能单独证明 Token 风控成功。严格路径必须以“新 `x5sec` + 离开验证 URL”为准。 + +严格检查期间,只要出现明确失败控件就立即按失败处理。主引擎拖动后最多等待 `5s` 进行严格确认;完成拖动后还会以 `250ms` 间隔等待新 Cookie,最长 `15s`。成功后收集浏览器上下文当前的 `x5*` Cookie,确保合并的是新签发的 `x5sec`,再合并回原 Cookie 字符串。 + +非 Token 场景调用通用 `solveSlider` 时,继续保留现有的可见成功标记或 `.nc-container` 消失判定;不得把该宽松判定用于 Token 风控路径。 + +## 5. 失败识别与恢复 + +明确失败控件固定为以下前三项: + +```text +#nc_1_refresh1 +.nc_iconfont.btn_refresh +.errloading +``` + +点击恢复时按以下优先级查找: + +```text +#nc_1_refresh1 +.nc_iconfont.btn_refresh +.errloading +[class*='refresh'] +``` + +`.nc-container` 只能在其文本包含下列失败/重试词之一时点击: + +```text +重试 刷新 失败 retry refresh failed +``` + +禁止无条件点击初始 `.nc-container`,因为这可能误触发拖动。 + +恢复状态机固定如下: + +1. 优先点击可见的失败/刷新控件。 +2. 控件可能延迟出现,首次未找到时按现有逻辑最多短暂等待 `800ms` 并轮询。 +3. 点击后最多等待 `4s`,确认按钮和轨道重新出现,且按钮回到轨道起点 `±3px` 内。 +4. 点击恢复失败或滑块未归位时,重载原页面。 +5. 重载等待 `domcontentloaded`,单次超时最多 `8s`;重载后最多等待 `5s` 确认滑块归位。 +6. 主引擎两次尝试之间保留 `1–2s` 随机等待;总尝试次数保持 3 次。 + +不得用“元素重新出现”替代“元素重新出现且按钮回到原点”的确认。 + +## 6. 引擎编排 + +固定执行顺序为: + +```text +Playwright 主引擎 + → 链接过期时,关闭当前持久化上下文后重新获取链接并重试主引擎 + → 主引擎发生非链接过期失败时,按配置进入直接 Chromium/CDP 备用引擎 + → 备用引擎仍必须取得新的 x5sec 才能成功 +``` + +约束如下: + +- 获取新验证链接的 provider 不得在主引擎持有同账号持久化 profile 锁时调用,避免同账号锁死。 +- 过期链接最多触发现有的 2 次链接刷新;最终仍过期时直接失败,不把过期 URL 交给备用引擎重放。 +- 进入备用引擎前可再获取一次新链接和更新后的 Cookie。 +- `CAPTCHA_REAL_MOUSE=true` 在当前 Go/Docker 实现中只记录物理鼠标不可用,并继续备用逻辑;不得假装已启用物理鼠标。 +- `CAPTCHA_DRISSIONPAGE_FALLBACK_ENABLED` 默认为启用。 +- 备用引擎成功返回的引擎标识保持为 `drissionpage`,虽然底层实现是直接 Chromium + CDP。 + +## 7. 备用引擎行为 + +备用引擎直接启动 Chromium,通过 `DevToolsActivePort` 连接 CDP,不改用 Playwright 的常规 launch 流程。它必须: + +- 与主引擎使用同一账号持久化 profile 目录。 +- 保持账号级互斥和全局续期槽位控制。 +- 启动前清理现有 singleton 文件和 `DevToolsActivePort`,退出后再次清理 singleton 文件。 +- 保留 `--remote-debugging-port=0`、`--window-size=1920,1080`、`--lang=zh-CN`、`--disable-blink-features=AutomationControlled` 等现有启动参数。 +- headless 时使用 `--headless=new`。 +- 默认总超时为 `25s`,可由现有环境变量控制;导航超时为 `15s`。 + +备用距离规则固定如下: + +1. 按钮和轨道 bounding box 都存在时,精确使用 `track.width - button.width`;标准 DOM 必须得到 `258px`。 +2. 仅轨道宽度可用时,保留基于轨道宽度的 `70%–90%` 加 `-20–20px` 偏移,并限制在 `200–600px`。 +3. 轨道几何信息不可用时,才按 viewport 宽度使用现有随机范围。 + +备用引擎保留 3 种尝试模式: + +| 尝试 | 计划移动时间 | 轨迹点数 | 特征 | +| --- | --- | --- | --- | +| 第 1 次 | `1.5–4s` | `60–150` | 常规 | +| 第 2 次 | `0.9–1.3s` | `30–60` | 急促,按下/释放等待更短 | +| 第 3 次 | `1–2s` | `50–90` | 常规 | + +备用轨迹保留现有加速、匀速、减速、犹豫、Y 轴趋势与抖动、偶发轻微超调及回正、清洗和重采样行为。这个行为与主引擎“不得超调”的规则不同,不得相互替换。每次失败后复用第 5 节的恢复流程,最多尝试 3 次;成功仍要求新的 `x5sec` 且已经离开 punish/captcha URL。 + +## 8. 诊断日志 + +以下诊断字段属于冻结行为,不得删除或降级: + +- 页面 URL 和 frame URL,且必须去掉 query 与 fragment,避免日志泄露验证参数。 +- 按钮、轨道 bounding box 和 class。 +- 计算出的滑动距离。 +- 轨迹点数、计划时长/延时、目标移动时长、真实移动时长和总耗时。 +- 最终 `left`、最终 class 或最终 X 偏移。 +- 失败时的按钮 style/class、轨道 class、可见重试选择器和重试文本。 +- 恢复方式是 `click` 还是 `reload`、所用选择器以及是否重新归位。 + +页面可能被浏览器扩展注入大量无关 DOM。当前仅把下列注入作为诊断信息记录,不允许它们改变滑块定位、距离或成功判定: + +| 工具 | DOM 标记 | +| --- | --- | +| Requestly | `rq-implicit-test-rule-widget` | +| PikPak | `#__PIKPAK_EXTENSION__` | +| DeepL | `deepl-input-controller` | +| 沉浸式翻译 | `#immersive-translate-browser-popup` | + +## 9. 必须保留的验证 + +任何获得用户明确授权的滑块改动,都必须至少保持以下验证通过: + +```bash +go test ./internal/browser +go test ./internal/engine ./internal/account ./internal/server +go build ./cmd/server +go vet ./internal/browser ./internal/engine ./internal/account ./internal/server ./cmd/server +``` + +同时必须保留直接 Chromium 集成场景: + +- 主引擎首次滑动成功。 +- 主引擎首次失败并隐藏滑块,点击 `.errloading` 恢复后第二次成功。 +- 直接 Chromium/CDP 备用引擎使用同一恢复流程后成功。 +- 标准 `300px` 轨道与 `42px` 按钮得到精确 `258px`。 +- 旧 `x5sec` 不得判成功,新 `x5sec` 才能判成功。 + +不得删除、跳过、弱化或改写断言来让行为变化通过测试。 + +## 10. 唯一变更流程 + +只有用户在当前任务中明确点名要求修改滑块认证时,才允许触碰冻结范围。获得授权后也必须在同一个变更中: + +1. 说明要改变本文哪一条冻结契约及原因。 +2. 同步更新实现、单元测试、真实 Chromium 集成测试和本文。 +3. 完成第 9 节验证并报告结果。 +4. 不得把一次授权推定为后续任务的持续授权。 + +没有上述明确授权时,遇到与滑块相关的需求或测试失败,应停止修改滑块代码,保留现场并向用户说明冲突。 From 16d63dc7c9d0e061438a368b5e3259be47ce4c20 Mon Sep 17 00:00:00 2001 From: Christ Date: Tue, 14 Jul 2026 21:20:22 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?=E5=8F=AF=E9=9D=A0=E6=80=A7=E3=80=81=E7=99=BB=E5=BD=95=E9=A3=8E?= =?UTF-8?q?=E6=8E=A7=E4=B8=8E=E8=B7=A8=E6=95=B0=E6=8D=AE=E5=BA=93=E5=9B=9E?= =?UTF-8?q?=E5=BD=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。 登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。 安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。 自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。 前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。 测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。 验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。 --- .gitignore | 1 + Dockerfile.browser-test | 13 + Dockerfile.debian13 | 2 - Dockerfile.test | 5 +- README.md | 13 +- cmd/dbseed/main.go | 23 + cmd/dbseed/main_test.go | 4 + cmd/server/main.go | 13 + docker-compose.functional.yml | 107 ++- frontend/components/AccountList.tsx | 469 ++++++++---- frontend/components/CardList.tsx | 14 +- frontend/components/Dashboard.tsx | 93 ++- frontend/components/ItemList.tsx | 132 +++- frontend/components/Notifications.tsx | 30 +- frontend/components/OrderList.tsx | 164 +++-- .../components/RiskVerificationPanel.test.tsx | 16 + frontend/components/RiskVerificationPanel.tsx | 41 ++ frontend/components/Rules.tsx | 208 +++++- frontend/components/Settings.tsx | 61 ++ frontend/components/SquareQRCode.test.tsx | 12 + frontend/components/SquareQRCode.tsx | 15 + frontend/components/accountPause.test.ts | 17 + frontend/components/accountPause.ts | 9 + .../components/accountRuntimeState.test.ts | 62 ++ frontend/components/accountRuntimeState.ts | 27 + .../components/automationIssueState.test.ts | 43 ++ frontend/components/automationIssueState.ts | 37 + .../components/itemPublishBatchState.test.ts | 10 + frontend/components/itemPublishBatchState.ts | 7 + frontend/components/latestRequest.test.ts | 11 + frontend/components/latestRequest.ts | 12 + frontend/components/orderImportState.test.ts | 18 + frontend/components/orderImportState.ts | 26 + frontend/components/qrPolling.test.ts | 58 +- frontend/components/qrPolling.ts | 34 +- frontend/package-lock.json | 29 + frontend/package.json | 3 + frontend/request.test.ts | 23 +- frontend/request.ts | 85 ++- frontend/routing.test.ts | 36 +- frontend/services/api.test.ts | 207 +++++- frontend/services/api.ts | 249 ++++--- frontend/smtpSettings.test.ts | 7 + frontend/smtpSettings.ts | 17 +- frontend/tsconfig.json | 5 +- frontend/types.ts | 11 +- frontend/vite.config.ts | 12 + frontend/viteConfig.test.ts | 12 + internal/account/manager.go | 6 +- internal/account/manager_extra_test.go | 15 +- internal/adapter/adapter.go | 124 ++-- internal/adapter/adapter_test.go | 21 +- internal/adapter/token_captcha_remote.go | 200 ++++++ internal/adapter/token_captcha_remote_test.go | 171 +++++ internal/automation/center.go | 558 ++++++++++---- internal/automation/center_mock_mtop_test.go | 42 +- internal/automation/center_test.go | 428 ++++++++++- internal/automation/events.go | 9 +- internal/automation/scheduler.go | 163 ++++- internal/automation/scheduler_test.go | 56 +- internal/browser/cookierenew.go | 276 ++++--- internal/browser/cookies.go | 75 +- internal/browser/cookies_test.go | 36 +- internal/browser/lifecycle.go | 88 ++- internal/browser/passwordlogin.go | 129 ++-- internal/browser/passwordlogin_detect_test.go | 65 +- internal/browser/pure_extra_test.go | 12 - internal/browser/qrrefresh.go | 25 +- internal/browser/slider.go | 680 ++++++++++++++++-- internal/browser/slider_test.go | 108 ++- internal/browser/stealth.go | 312 +------- internal/browser/token_captcha.go | 313 ++++++-- internal/browser/token_captcha_fallback.go | 610 ++++++++++++++++ ...token_captcha_fallback_integration_test.go | 233 ++++++ .../token_captcha_orchestrator_test.go | 246 +++++++ internal/browser/token_captcha_test.go | 142 ++++ internal/browser/token_request.go | 78 ++ internal/browser/user_data_dir.go | 30 + internal/browser/user_data_dir_test.go | 67 ++ internal/db/account_tokens.go | 71 +- internal/db/account_tokens_test.go | 85 ++- internal/db/ai_reply.go | 10 +- internal/db/automation.go | 597 ++++++++++++++- internal/db/automation_test.go | 341 ++++++++- internal/db/cookies.go | 379 ++++++++-- internal/db/cookies_concurrency_test.go | 133 ++++ internal/db/cookies_settings_test.go | 62 ++ internal/db/db.go | 56 +- internal/db/db_url_test.go | 22 +- internal/db/delivery.go | 131 ++-- internal/db/dialect.go | 1 + internal/db/extras.go | 130 +++- internal/db/extras_test.go | 62 +- internal/db/item_publish_batches.go | 560 ++++++++++++++- .../db/item_publish_batches_lease_test.go | 41 ++ internal/db/migrate_test.go | 7 +- .../mysql/00017_reliability_and_pause.sql | 22 + .../mysql/00018_automation_run_recovery.sql | 14 + .../mysql/00019_deferred_automation_tasks.sql | 20 + .../00020_automation_action_checkpoint.sql | 9 + .../mysql/00021_notification_outbox.sql | 20 + .../postgres/00017_reliability_and_pause.sql | 22 + .../00018_automation_run_recovery.sql | 12 + .../00019_deferred_automation_tasks.sql | 19 + .../00020_automation_action_checkpoint.sql | 9 + .../postgres/00021_notification_outbox.sql | 19 + .../sqlite/00017_reliability_and_pause.sql | 22 + .../sqlite/00018_automation_run_recovery.sql | 12 + .../00019_deferred_automation_tasks.sql | 20 + .../00020_automation_action_checkpoint.sql | 9 + .../sqlite/00021_notification_outbox.sql | 20 + internal/db/models.go | 1 + internal/db/multidb_test.go | 200 +++++- internal/db/notification_outbox_test.go | 62 ++ internal/db/notifications.go | 119 ++- internal/db/orders.go | 259 +++++-- internal/db/orders_concurrency_test.go | 69 ++ internal/db/orders_delivery_test.go | 159 +++- internal/db/orders_ext.go | 29 +- internal/db/pgx_compat.go | 2 +- internal/db/publish_batches_test.go | 326 +++++++++ internal/db/renewal.go | 11 +- internal/db/reply.go | 21 +- internal/db/reply_state_test.go | 2 +- internal/db/secrets.go | 238 ++++++ internal/db/secrets_test.go | 131 ++++ internal/db/store.go | 11 +- internal/db/users.go | 54 +- internal/engine/account.go | 680 +++++++++++------- internal/engine/account_extra_test.go | 236 +++--- internal/engine/ai.go | 15 +- internal/engine/dispatch.go | 24 +- internal/engine/dispatch_extra_test.go | 47 ++ internal/engine/engine_test.go | 12 +- internal/engine/http_client_test.go | 13 + internal/engine/keepalive_test.go | 328 +++++++-- internal/engine/run_test.go | 80 ++- internal/netguard/http.go | 120 ++++ internal/netguard/http_test.go | 82 +++ internal/notify/http_client_test.go | 16 + internal/notify/notifier.go | 205 +++++- internal/notify/notifier_channels_test.go | 13 + internal/notify/notifier_dispatch_test.go | 36 +- internal/notify/smtp_guard_test.go | 45 ++ internal/renewal/cooldown.go | 31 +- internal/renewal/cooldown_test.go | 38 + internal/renewal/scheduler.go | 107 +-- internal/renewal/scheduler_test.go | 74 ++ internal/server/admin_handlers.go | 7 + internal/server/analytics_handlers.go | 207 ++++-- internal/server/analytics_handlers_test.go | 136 +++- internal/server/auth_handlers.go | 14 + internal/server/automation_extra_test.go | 68 ++ internal/server/automation_handlers.go | 88 +++ internal/server/card_handlers.go | 15 + internal/server/cookie_handlers.go | 142 +++- internal/server/cookie_handlers_test.go | 85 +++ internal/server/endpoint_test.go | 15 +- internal/server/extras_test.go | 27 + internal/server/handler_errors_test.go | 3 + internal/server/helpers.go | 27 +- internal/server/helpers_test.go | 21 + internal/server/http_client_test.go | 13 + internal/server/item_handlers.go | 87 ++- internal/server/item_handlers_test.go | 50 ++ .../server/item_publish_batch_handlers.go | 583 ++++++++++++--- internal/server/item_publish_images.go | 43 +- internal/server/keyword_handlers.go | 138 +++- internal/server/login_limiter.go | 101 +++ internal/server/login_limiter_test.go | 37 + internal/server/order_handlers.go | 361 +++++++--- internal/server/order_handlers_extra_test.go | 270 ++++++- internal/server/parser_test.go | 2 +- internal/server/password_login_handlers.go | 57 +- .../server/password_login_handlers_test.go | 82 ++- internal/server/publish_batch_run_test.go | 182 ++++- internal/server/publish_batch_test.go | 114 +++ internal/server/qrlogin_handlers.go | 125 +++- internal/server/qrlogin_keyword_test.go | 165 ++++- internal/server/run_test.go | 22 + internal/server/security_endpoint_test.go | 24 +- internal/server/server.go | 91 ++- internal/server/server_test.go | 33 +- internal/server/settings_extra_test.go | 32 + internal/server/settings_handlers.go | 42 +- ...r-6fuKcPoR.js => icons-vendor-BhUPp6x7.js} | 139 ++-- .../webui/static/assets/index-2Xnmtmdh.js | 19 + .../webui/static/assets/index-CK7Gki1b.css | 1 - .../webui/static/assets/index-CaW5oMkx.js | 19 - .../webui/static/assets/index-D0gOrWMZ.css | 1 + internal/webui/static/index.html | 6 +- internal/xianyu/mtop/client.go | 41 +- internal/xianyu/mtop/client_test.go | 6 +- internal/xianyu/mtop/publish.go | 3 +- internal/xianyu/mtop/publish_extra_test.go | 10 +- internal/xianyu/mtop/token.go | 69 +- internal/xianyu/mtop/token_test.go | 69 +- internal/xianyu/protocol/decrypt_test.go | 10 +- internal/xianyu/qrlogin/client.go | 151 +++- internal/xianyu/qrlogin/coverage_test.go | 99 ++- internal/xianyu/qrlogin/face_verification.go | 52 +- internal/xianyu/renew/service.go | 168 ++++- internal/xianyu/renew/service_test.go | 467 ++++-------- internal/xianyu/ua.go | 70 +- internal/xianyu/ua_test.go | 44 +- internal/xianyu/ws/client.go | 89 ++- internal/xianyu/ws/client_test.go | 9 + internal/xianyu/ws/dial_test.go | 11 +- scripts/docker-full-test.sh | 29 +- scripts/docker-functional-test.sh | 46 +- scripts/docker-persistence-test.sh | 66 ++ 211 files changed, 16449 insertions(+), 3408 deletions(-) create mode 100644 Dockerfile.browser-test create mode 100644 frontend/components/RiskVerificationPanel.test.tsx create mode 100644 frontend/components/RiskVerificationPanel.tsx create mode 100644 frontend/components/SquareQRCode.test.tsx create mode 100644 frontend/components/SquareQRCode.tsx create mode 100644 frontend/components/accountPause.test.ts create mode 100644 frontend/components/accountPause.ts create mode 100644 frontend/components/accountRuntimeState.test.ts create mode 100644 frontend/components/accountRuntimeState.ts create mode 100644 frontend/components/automationIssueState.test.ts create mode 100644 frontend/components/automationIssueState.ts create mode 100644 frontend/components/itemPublishBatchState.test.ts create mode 100644 frontend/components/itemPublishBatchState.ts create mode 100644 frontend/components/latestRequest.test.ts create mode 100644 frontend/components/latestRequest.ts create mode 100644 frontend/components/orderImportState.test.ts create mode 100644 frontend/components/orderImportState.ts create mode 100644 frontend/viteConfig.test.ts create mode 100644 internal/adapter/token_captcha_remote.go create mode 100644 internal/adapter/token_captcha_remote_test.go create mode 100644 internal/browser/token_captcha_fallback.go create mode 100644 internal/browser/token_captcha_fallback_integration_test.go create mode 100644 internal/browser/token_captcha_orchestrator_test.go create mode 100644 internal/browser/token_captcha_test.go create mode 100644 internal/browser/token_request.go create mode 100644 internal/browser/user_data_dir.go create mode 100644 internal/browser/user_data_dir_test.go create mode 100644 internal/db/cookies_concurrency_test.go create mode 100644 internal/db/cookies_settings_test.go create mode 100644 internal/db/item_publish_batches_lease_test.go create mode 100644 internal/db/migrations/mysql/00017_reliability_and_pause.sql create mode 100644 internal/db/migrations/mysql/00018_automation_run_recovery.sql create mode 100644 internal/db/migrations/mysql/00019_deferred_automation_tasks.sql create mode 100644 internal/db/migrations/mysql/00020_automation_action_checkpoint.sql create mode 100644 internal/db/migrations/mysql/00021_notification_outbox.sql create mode 100644 internal/db/migrations/postgres/00017_reliability_and_pause.sql create mode 100644 internal/db/migrations/postgres/00018_automation_run_recovery.sql create mode 100644 internal/db/migrations/postgres/00019_deferred_automation_tasks.sql create mode 100644 internal/db/migrations/postgres/00020_automation_action_checkpoint.sql create mode 100644 internal/db/migrations/postgres/00021_notification_outbox.sql create mode 100644 internal/db/migrations/sqlite/00017_reliability_and_pause.sql create mode 100644 internal/db/migrations/sqlite/00018_automation_run_recovery.sql create mode 100644 internal/db/migrations/sqlite/00019_deferred_automation_tasks.sql create mode 100644 internal/db/migrations/sqlite/00020_automation_action_checkpoint.sql create mode 100644 internal/db/migrations/sqlite/00021_notification_outbox.sql create mode 100644 internal/db/notification_outbox_test.go create mode 100644 internal/db/orders_concurrency_test.go create mode 100644 internal/db/secrets.go create mode 100644 internal/db/secrets_test.go create mode 100644 internal/engine/http_client_test.go create mode 100644 internal/netguard/http.go create mode 100644 internal/netguard/http_test.go create mode 100644 internal/notify/http_client_test.go create mode 100644 internal/notify/smtp_guard_test.go create mode 100644 internal/renewal/cooldown_test.go create mode 100644 internal/server/helpers_test.go create mode 100644 internal/server/http_client_test.go create mode 100644 internal/server/login_limiter.go create mode 100644 internal/server/login_limiter_test.go rename internal/webui/static/assets/{icons-vendor-6fuKcPoR.js => icons-vendor-BhUPp6x7.js} (80%) create mode 100644 internal/webui/static/assets/index-2Xnmtmdh.js delete mode 100644 internal/webui/static/assets/index-CK7Gki1b.css delete mode 100644 internal/webui/static/assets/index-CaW5oMkx.js create mode 100644 internal/webui/static/assets/index-D0gOrWMZ.css create mode 100755 scripts/docker-persistence-test.sh diff --git a/.gitignore b/.gitignore index ca884cc..4446f46 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,7 @@ # Runtime data /data/ +/browser_data/ *.db *.db-shm *.db-wal diff --git a/Dockerfile.browser-test b/Dockerfile.browser-test new file mode 100644 index 0000000..b679863 --- /dev/null +++ b/Dockerfile.browser-test @@ -0,0 +1,13 @@ +FROM golang:1.26-trixie AS go-toolchain + +# 复用生产运行镜像中已经安装并验证过的 Chromium、Node 和 Playwright driver, +# 只补 Go 工具链来执行真实浏览器集成测试。 +FROM xianyu-go:functional +ENV PATH=/usr/local/go/bin:${PATH} +ENV CGO_ENABLED=0 +WORKDIR /src +COPY --from=go-toolchain /usr/local/go /usr/local/go +COPY go.mod go.sum ./ +RUN go mod download +COPY . . +CMD ["go", "test", "-timeout=2m", "./internal/browser", "-run", "TestTokenCaptchaCDPFallbackBrowserIntegration", "-v", "-count=1"] diff --git a/Dockerfile.debian13 b/Dockerfile.debian13 index 44f66bf..6e8e7da 100644 --- a/Dockerfile.debian13 +++ b/Dockerfile.debian13 @@ -1,5 +1,3 @@ -# syntax=docker/dockerfile:1.7 - FROM node:22-trixie AS frontend WORKDIR /src/frontend COPY frontend/package*.json ./ diff --git a/Dockerfile.test b/Dockerfile.test index 99c5cf2..a1c8729 100644 --- a/Dockerfile.test +++ b/Dockerfile.test @@ -1,4 +1,5 @@ -# syntax=docker/dockerfile:1.7 +FROM alpine:3.22 AS sqlite-tools +RUN apk add --no-cache sqlite FROM node:22-trixie AS frontend-assets WORKDIR /src/frontend @@ -28,4 +29,4 @@ WORKDIR /src/frontend COPY frontend/package*.json ./ RUN npm ci COPY frontend/ ./ -CMD ["sh", "-c", "npm test && npm run build"] +CMD ["sh", "-c", "npm run typecheck && npm test && npm run build"] diff --git a/README.md b/README.md index 7b1a469..8c07f5f 100644 --- a/README.md +++ b/README.md @@ -178,6 +178,16 @@ XIANYU_UPLOAD_DIR=/app/data/uploads 外置 MySQL/Postgres 时改用 `DATABASE_URL` 环境变量。 +生产环境建议同时设置稳定且仅由服务进程可读的 `XIANYU_DATA_KEY`。启用后,Cookie、 +账号登录密码、设备/访问令牌、AI/SMTP 密钥和通知渠道配置会使用 AES-256-GCM 加密 +后落库;首次启动会自动升级历史明文。该密钥必须随数据卷一同备份,丢失或更换后 +已有凭证无法解密。 + +管理员配置的 OpenAI 兼容 AI Base URL 不限制目标网络,可使用 `0.0.0.0`、loopback、 +Docker 服务名、RFC1918 私网、Tailscale/CGNAT、IPv6 ULA 或公网地址,便于连接任意部署 +位置的 Ollama、vLLM、LocalAI 或兼容网关。通知 Webhook、远程图片等非管理员可信目标 +继续只允许公网地址。 + ## 常用参数 | 参数 | 说明 | @@ -185,6 +195,7 @@ XIANYU_UPLOAD_DIR=/app/data/uploads | `-db` | SQLite 数据库路径,默认 `data/xianyu_data.db`(向后兼容) | | `-db-url` | 数据库连接 URL(`sqlite://` / `mysql://` / `postgres://`),优先级高于 `-db` | | `DATABASE_URL` | 环境变量,优先级最高 | +| `XIANYU_DATA_KEY` | 敏感字段加密主密钥;生产环境应固定配置并安全备份 | | `-addr` | HTTP 监听地址,默认 `:8080` | | `-web` | 外部前端静态资源目录;不传则用内置前端 | | `-init-admin` | 初始化或重置管理员后退出 | @@ -225,7 +236,7 @@ MySQL 8.4 与 PostgreSQL 17 API 功能及重启持久化): 测试编排使用命名卷 `mysql8_data`、`postgres17_data` 和 `sqlite_seed`。 本地 `data/xianyu_data.db` 只会抽取少量商品、订单和卡密元数据,写入外置库前会替换 -Cookie、买家 ID 和卡密内容。测试应用分别监听 `18081`(MySQL)与 `18082` +Cookie、买家 ID 和卡密内容。测试应用分别监听 `28081`(MySQL)与 `28082` (PostgreSQL),测试账号为 `docker_fixture / docker_fixture_password`。 测试管理员为 `docker_admin / docker_admin_password`。 diff --git a/cmd/dbseed/main.go b/cmd/dbseed/main.go index e68db30..1309d4b 100644 --- a/cmd/dbseed/main.go +++ b/cmd/dbseed/main.go @@ -111,6 +111,24 @@ func seedFromSQLite(ctx context.Context, source *sql.DB, target *db.Store, optio if err != nil { return result, err } + // 保留一条历史脏金额,用于验证三种数据库下统计接口都能安全跳过而不是 500。 + fixtureItemID := "" + for _, id := range itemMap { + fixtureItemID = id + break + } + if fixtureItemID != "" { + if err := target.Orders.Upsert(ctx, "docker-invalid-amount", db.OrderUpsertOpts{ + CookieID: accountID, ItemID: fixtureItemID, BuyerID: "docker-buyer-invalid", + Quantity: "1", OrderStatus: "completed", + }); err != nil { + return result, err + } + // 直接写入一条模拟升级前遗留的脏数据;正常仓储写入口会拒绝该金额。 + if _, err := target.DB.ExecContext(ctx, `UPDATE orders SET amount='not-a-number' WHERE order_id='docker-invalid-amount'`); err != nil { + return result, err + } + } result.Cards, err = seedCards(ctx, source, target, user.ID, options.Limit) return result, err } @@ -229,6 +247,11 @@ func seedOrders(ctx context.Context, source *sql.DB, target *db.Store, accountID if !ok { continue } + if normalized, valid := db.NormalizeOrderAmount(amount); valid { + amount = normalized + } else { + amount = "" + } if err := target.Orders.Upsert(ctx, "docker-order-"+shortHash(sourceOrderID), db.OrderUpsertOpts{ CookieID: accountID, ItemID: itemID, BuyerID: "docker-buyer", Quantity: quantity, Amount: amount, OrderStatus: status, SpecName: specName, SpecValue: specValue, diff --git a/cmd/dbseed/main_test.go b/cmd/dbseed/main_test.go index c6e9f28..8734fe1 100644 --- a/cmd/dbseed/main_test.go +++ b/cmd/dbseed/main_test.go @@ -51,6 +51,10 @@ func TestSeedFromSQLiteCopiesMetadataAndSanitizesSecrets(t *testing.T) { if len(cards) != 1 || strings.Contains(cards[0].DataContent, "SECRET-CODE") { t.Fatalf("source card secret leaked: %+v", cards) } + invalidOrder, err := target.Orders.Get(ctx, "docker-invalid-amount") + if err != nil || invalidOrder.Amount != "not-a-number" { + t.Fatalf("invalid amount fixture missing: order=%+v err=%v", invalidOrder, err) + } second, err := seedFromSQLite(ctx, sourceDB, target, options) if err != nil { diff --git a/cmd/server/main.go b/cmd/server/main.go index a9080bf..3d44e28 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -32,6 +32,7 @@ import ( "xianyu-go/internal/notify" "xianyu-go/internal/renewal" "xianyu-go/internal/server" + "xianyu-go/internal/xianyu/mtop" ) func main() { @@ -92,6 +93,10 @@ func main() { } logger.Info("数据库已就绪", "dialect", dialect) store := db.NewStore(database, dialect) + if err := store.EncryptLegacySecrets(ctx); err != nil { + logger.Error("校验或升级数据库敏感字段失败", "err", err) + os.Exit(1) + } defer database.Close() if !explicitLogLevel { if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" { @@ -125,6 +130,11 @@ func main() { var bm *browser.Manager if !*noBrowser { bm = browser.NewManager(logger) + if err := bm.Initialize(); err != nil { + logger.Error("初始化 Playwright Chromium 指纹失败", "err", err) + os.Exit(1) + } + mtop.SetDefaultTokenRequestExecutor(bm) } var mgr *account.Manager ap := adapter.New(store, bm, logger) @@ -132,6 +142,7 @@ func main() { autoCenter := automation.New(store, mgr, logger) autoCenter.SetOrderDetailFetcher(ap) notifier := notify.New("", store, logger) + notifier.Start(ctx) autoCenter.SetNotifier(notifier) ap.SetAutomation(autoCenter) ap.SetNotifier(notifier) @@ -143,6 +154,7 @@ func main() { // 3) HTTP 服务。 srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier) + go srv.RunPublishBatchRecovery(ctx) if err := srv.Run(ctx); err != nil { logger.Error("HTTP 服务退出", "err", err) // 即便出错也尝试清理已启动的账号与浏览器。 @@ -157,6 +169,7 @@ func main() { if bm != nil { _ = bm.Close() } + notifier.Wait() } // handlerAdapter 已下沉到 internal/adapter 包;本文件只负责装配。 diff --git a/docker-compose.functional.yml b/docker-compose.functional.yml index 6e9a681..de0ff8f 100644 --- a/docker-compose.functional.yml +++ b/docker-compose.functional.yml @@ -1,7 +1,8 @@ name: xianyu-functional -x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=Local -x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable +x-mysql-url: &mysql-url mysql://root:xianyu_root_password@tcp(mysql:3306)/xianyu?parseTime=true&loc=UTC +x-postgres-url: &postgres-url postgres://xianyu:xianyu_postgres_password@postgres:5432/xianyu?sslmode=disable&timezone=UTC +x-data-key: &data-key docker-functional-data-key-v1 services: mysql: @@ -12,8 +13,8 @@ services: MYSQL_DATABASE: xianyu MYSQL_USER: xianyu MYSQL_PASSWORD: xianyu_mysql_password - TZ: Asia/Shanghai - command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_0900_ai_ci"] + TZ: UTC + command: ["--character-set-server=utf8mb4", "--collation-server=utf8mb4_0900_ai_ci", "--default-time-zone=+00:00"] ports: - "13306:3306" volumes: @@ -31,7 +32,8 @@ services: POSTGRES_DB: xianyu POSTGRES_USER: xianyu POSTGRES_PASSWORD: xianyu_postgres_password - TZ: Asia/Shanghai + TZ: UTC + command: ["postgres", "-c", "timezone=UTC", "-c", "log_timezone=UTC"] ports: - "15432:5432" volumes: @@ -43,7 +45,10 @@ services: retries: 30 sqlite-seed-copy: - image: alpine:3.22 + build: + context: . + dockerfile: Dockerfile.test + target: sqlite-tools restart: "no" volumes: - ./data:/source:ro @@ -53,9 +58,11 @@ services: - -ec - | rm -f /seed/xianyu_data.db /seed/xianyu_data.db-wal /seed/xianyu_data.db-shm - cp /source/xianyu_data.db /seed/xianyu_data.db - test ! -f /source/xianyu_data.db-wal || cp /source/xianyu_data.db-wal /seed/xianyu_data.db-wal - test ! -f /source/xianyu_data.db-shm || cp /source/xianyu_data.db-shm /seed/xianyu_data.db-shm + test -f /source/xianyu_data.db + sqlite3 -readonly /source/xianyu_data.db ".timeout 30000" ".backup '/seed/xianyu_data.db'" + test -s /seed/xianyu_data.db + test "$(sqlite3 /seed/xianyu_data.db 'PRAGMA journal_mode=DELETE;')" = "delete" + sqlite3 /seed/xianyu_data.db "PRAGMA quick_check" | grep -qx ok seed-mysql: image: xianyu-go:functional @@ -70,8 +77,26 @@ services: condition: service_completed_successfully volumes: - sqlite_seed:/seed:ro + environment: + XIANYU_DATA_KEY: *data-key command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *mysql-url, "-limit", "20"] + seed-sqlite: + image: xianyu-go:functional + build: + context: . + dockerfile: Dockerfile.debian13 + restart: "no" + depends_on: + sqlite-seed-copy: + condition: service_completed_successfully + environment: + XIANYU_DATA_KEY: *data-key + volumes: + - sqlite_seed:/seed:ro + - app_sqlite_data:/app/data + command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", "/app/data/xianyu-functional.db", "-limit", "20"] + seed-postgres: image: xianyu-go:functional restart: "no" @@ -82,6 +107,8 @@ services: condition: service_completed_successfully volumes: - sqlite_seed:/seed:ro + environment: + XIANYU_DATA_KEY: *data-key command: ["/app/xianyu-dbseed", "-source", "/seed/xianyu_data.db", "-target", *postgres-url, "-limit", "20"] app-mysql: @@ -92,12 +119,36 @@ services: condition: service_completed_successfully environment: DATABASE_URL: *mysql-url + XIANYU_DATA_KEY: *data-key TZ: Asia/Shanghai command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] ports: - - "18081:8080" + - "28081:8080" volumes: - app_mysql_data:/app/data + - app_mysql_browser_data:/app/browser_data + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] + interval: 5s + timeout: 5s + retries: 30 + + app-sqlite: + image: xianyu-go:functional + restart: unless-stopped + depends_on: + seed-sqlite: + condition: service_completed_successfully + environment: + DATABASE_URL: sqlite:///app/data/xianyu-functional.db + XIANYU_DATA_KEY: *data-key + TZ: Asia/Shanghai + command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] + ports: + - "28080:8080" + volumes: + - app_sqlite_data:/app/data + - app_sqlite_browser_data:/app/browser_data healthcheck: test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] interval: 5s @@ -112,12 +163,14 @@ services: condition: service_completed_successfully environment: DATABASE_URL: *postgres-url + XIANYU_DATA_KEY: *data-key TZ: Asia/Shanghai command: ["/app/xianyu-server", "-addr", ":8080", "-no-browser"] ports: - - "18082:8080" + - "28082:8080" volumes: - app_postgres_data:/app/data + - app_postgres_browser_data:/app/browser_data healthcheck: test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8080/health >/dev/null"] interval: 5s @@ -139,6 +192,15 @@ services: TEST_POSTGRES_URL: *postgres-url command: ["go", "test", "-race", "-timeout=20m", "./..."] + browser-integration-test: + build: + context: . + dockerfile: Dockerfile.browser-test + environment: + RUN_BROWSER_INTEGRATION: "1" + BROWSER_HEADLESS: "true" + command: ["go", "test", "-timeout=2m", "./internal/browser", "-run", "TestTokenCaptchaCDPFallbackBrowserIntegration", "-v", "-count=1"] + go-vet: build: context: . @@ -158,26 +220,40 @@ services: context: . dockerfile: Dockerfile.test target: frontend-test - command: ["sh", "-c", "npm test && npm run build"] + command: ["sh", "-c", "npm run typecheck && npm test && npm run build"] dbverify-mysql: image: xianyu-go:functional depends_on: mysql: condition: service_healthy + environment: + XIANYU_DATA_KEY: *data-key command: ["/app/xianyu-dbverify", *mysql-url] + dbverify-sqlite: + image: xianyu-go:functional + environment: + XIANYU_DATA_KEY: *data-key + volumes: + - sqlite_verify_data:/app/data + command: ["/app/xianyu-dbverify", "/app/data/verify.db"] + dbverify-postgres: image: xianyu-go:functional depends_on: postgres: condition: service_healthy + environment: + XIANYU_DATA_KEY: *data-key command: ["/app/xianyu-dbverify", *postgres-url] functional-test: - image: curlimages/curl:8.16.0 + image: xianyu-go:functional restart: "no" depends_on: + app-sqlite: + condition: service_healthy app-mysql: condition: service_healthy app-postgres: @@ -190,5 +266,10 @@ volumes: mysql8_data: postgres17_data: sqlite_seed: + sqlite_verify_data: + app_sqlite_data: app_mysql_data: app_postgres_data: + app_mysql_browser_data: + app_postgres_browser_data: + app_sqlite_browser_data: diff --git a/frontend/components/AccountList.tsx b/frontend/components/AccountList.tsx index f1778fb..fd95e19 100644 --- a/frontend/components/AccountList.tsx +++ b/frontend/components/AccountList.tsx @@ -9,27 +9,30 @@ import { generateQRLogin, checkQRLoginStatus, completeQRVerification, - updateAccountRemark, - updateAccountAutoConfirm, updateAccountPauseDuration, - updateAccountCookie, refreshAccountProfile, - updateAccountLoginInfo, + updateAccountSettings, + passwordLogin, + checkPasswordLoginStatus, + cancelPasswordLogin, updateAccountAISettings, getAllAISettings, getAccountAISettings, getNotificationChannels, getAccountBindings, - setAccountBindings, } from '../services/api'; +import { shouldUpdateAccountPause } from './accountPause'; import { Plus, Power, Edit2, Trash2, QrCode, X, Check, Loader2, RefreshCw, Save, User, Clock, MessageCircle, - Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, ExternalLink, Bell + Upload, Key, Eye, EyeOff, Bot, Settings, AlertCircle, Bell } from 'lucide-react'; import { buildAccountLoginInfoUpdate } from './accountEdit'; import { shouldSaveNotificationBindings } from './accountBindings'; -import { createQRLoginPoller } from './qrPolling'; +import { mergeAccountRuntimeStatuses } from './accountRuntimeState'; +import { createLatestRequestGate, createQRLoginPoller } from './qrPolling'; +import { RiskVerificationPanel } from './RiskVerificationPanel'; +import { SquareQRCode } from './SquareQRCode'; type ModalType = 'edit' | 'ai-settings' | null; @@ -41,10 +44,8 @@ const AccountList: React.FC = () => { const [showQRModal, setShowQRModal] = useState(false); const [qrCodeUrl, setQrCodeUrl] = useState(''); const [qrStatus, setQrStatus] = useState('pending'); - const [verificationUrl, setVerificationUrl] = useState(''); const [verificationScreenshot, setVerificationScreenshot] = useState(''); const [faceQrUrl, setFaceQrUrl] = useState(''); - const [qrSessionId, setQrSessionId] = useState(''); const [qrReauthTarget, setQrReauthTarget] = useState(null); const [activeModal, setActiveModal] = useState(null); const [editingAccount, setEditingAccount] = useState(null); @@ -79,11 +80,34 @@ const AccountList: React.FC = () => { custom_prompts: '', }); const [saving, setSaving] = useState(false); + const [passwordLoginView, setPasswordLoginView] = useState<{ + sessionId: string; + status: 'idle' | 'processing' | 'verification_required' | 'success' | 'failed'; + message: string; + qrCodeUrl: string; + }>({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' }); const qrPollerRef = useRef | null>(null); - const qrCloseTimerRef = useRef | null>(null); + const qrRequestGateRef = useRef | null>(null); + const accountLoadGateRef = useRef | null>(null); + const bindingsLoadGateRef = useRef | null>(null); + const aiLoadGateRef = useRef | null>(null); + const accountLoadAbortRef = useRef(null); + const bindingsLoadAbortRef = useRef(null); + const aiLoadAbortRef = useRef(null); + const qrGenerateAbortRef = useRef(null); + const passwordPollAbortRef = useRef(null); + const qrCloseTimerRef = useRef(null); + const passwordPollTimerRef = useRef(null); + const passwordPollGenerationRef = useRef(0); if (qrPollerRef.current === null) { qrPollerRef.current = createQRLoginPoller(); } + if (qrRequestGateRef.current === null) { + qrRequestGateRef.current = createLatestRequestGate(); + } + if (accountLoadGateRef.current === null) accountLoadGateRef.current = createLatestRequestGate(); + if (bindingsLoadGateRef.current === null) bindingsLoadGateRef.current = createLatestRequestGate(); + if (aiLoadGateRef.current === null) aiLoadGateRef.current = createLatestRequestGate(); const clearQRCloseTimer = () => { if (qrCloseTimerRef.current !== null) { @@ -92,11 +116,20 @@ const AccountList: React.FC = () => { } }; + const clearPasswordPollTimer = () => { + if (passwordPollTimerRef.current !== null) { + window.clearTimeout(passwordPollTimerRef.current); + passwordPollTimerRef.current = null; + } + }; + const stopQRPolling = () => { qrPollerRef.current?.stop(); }; const closeQRModal = () => { + qrGenerateAbortRef.current?.abort(); + qrRequestGateRef.current?.cancel(); stopQRPolling(); clearQRCloseTimer(); setShowQRModal(false); @@ -111,37 +144,20 @@ const AccountList: React.FC = () => { }, 1000); }; - const refreshRuntimeStatuses = async () => { - try { - const statuses = await getAccountRuntimeStatuses(); - setAccounts(current => current.map(account => { - const status = statuses[account.id]; - if (!status) return account; - return { - ...account, - runtime_state: status.state, - runtime_message: status.message || '', - runtime_connected: status.connected, - runtime_updated_at: status.updated_at, - }; - })); - } catch (error) { - console.error('Failed to load account runtime statuses:', error); - } - }; - const loadAccounts = async () => { + const generation = accountLoadGateRef.current!.next(); + accountLoadAbortRef.current?.abort(); + const controller = new AbortController(); + accountLoadAbortRef.current = controller; setLoading(true); try { - const data = await getAccountDetails(); - - // 获取所有账号的AI设置 - let allAISettings: Record = {}; - try { - allAISettings = await getAllAISettings(); - } catch (e) { - console.error('Failed to load AI settings:', e); - } + const options = { signal: controller.signal }; + const [detailsResult, aiResult] = await Promise.allSettled([getAccountDetails(options), getAllAISettings(options)]); + if (!accountLoadGateRef.current?.isCurrent(generation)) return; + if (detailsResult.status === 'rejected') throw detailsResult.reason; + const data = detailsResult.value; + const allAISettings = aiResult.status === 'fulfilled' ? aiResult.value : {}; + if (aiResult.status === 'rejected') console.error('Failed to load AI settings:', aiResult.reason); // 合并AI设置到账号数据 const accountsWithAI = data.map(account => ({ @@ -153,25 +169,62 @@ const AccountList: React.FC = () => { custom_prompts: allAISettings[account.id]?.custom_prompts ?? '', })); - setAccounts(accountsWithAI); - window.setTimeout(refreshRuntimeStatuses, 0); + if (accountLoadGateRef.current?.isCurrent(generation)) setAccounts(accountsWithAI); } catch (error) { - console.error('Failed to load accounts:', error); + if (accountLoadGateRef.current?.isCurrent(generation) && !controller.signal.aborted) { + console.error('Failed to load accounts:', error); + } } finally { - setLoading(false); + if (accountLoadGateRef.current?.isCurrent(generation)) setLoading(false); } }; useEffect(() => { - loadAccounts(); - const timer = window.setInterval(refreshRuntimeStatuses, 10_000); - return () => window.clearInterval(timer); + let cancelled = false; + let timer: number | null = null; + const runtimeController = new AbortController(); + + const pollRuntimeStatuses = async () => { + try { + const statuses = await getAccountRuntimeStatuses({ signal: runtimeController.signal, timeoutMs: 10_000 }); + if (!cancelled) { + setAccounts(current => mergeAccountRuntimeStatuses(current, statuses)); + } + } catch (error) { + if (!cancelled) console.error('Failed to load account runtime statuses:', error); + } finally { + if (!cancelled) { + // 运行时状态只读取本地内存;短轮询让风控恢复提示在约 2 秒内收敛。 + timer = window.setTimeout(() => void pollRuntimeStatuses(), 2_000); + } + } + }; + + void loadAccounts().finally(() => { + if (!cancelled) void pollRuntimeStatuses(); + }); + return () => { + cancelled = true; + runtimeController.abort(); + if (timer !== null) window.clearTimeout(timer); + }; }, []); useEffect(() => { return () => { stopQRPolling(); + qrRequestGateRef.current?.cancel(); + accountLoadGateRef.current?.cancel(); + bindingsLoadGateRef.current?.cancel(); + aiLoadGateRef.current?.cancel(); + accountLoadAbortRef.current?.abort(); + bindingsLoadAbortRef.current?.abort(); + aiLoadAbortRef.current?.abort(); + qrGenerateAbortRef.current?.abort(); + passwordPollAbortRef.current?.abort(); clearQRCloseTimer(); + passwordPollGenerationRef.current += 1; + clearPasswordPollTimer(); }; }, []); @@ -228,14 +281,19 @@ const AccountList: React.FC = () => { }; const loadNotificationBindings = async (accountId: string) => { + const generation = bindingsLoadGateRef.current!.next(); + bindingsLoadAbortRef.current?.abort(); + const controller = new AbortController(); + bindingsLoadAbortRef.current = controller; setBindingsLoading(true); setBindingsLoaded(false); setBindingsDirty(false); setBindingsLoadError(''); const [channelsResult, bindingsResult] = await Promise.allSettled([ - getNotificationChannels(), - getAccountBindings(accountId), + getNotificationChannels({ signal: controller.signal }), + getAccountBindings(accountId, { signal: controller.signal }), ]); + if (!bindingsLoadGateRef.current?.isCurrent(generation)) return; if (channelsResult.status === 'fulfilled') { setNotifChannels(channelsResult.value.data || []); } else { @@ -253,6 +311,10 @@ const AccountList: React.FC = () => { }; const openEditModal = async (account: AccountDetail) => { + passwordPollGenerationRef.current += 1; + passwordPollAbortRef.current?.abort(); + clearPasswordPollTimer(); + setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' }); setEditingAccount(account); setEditForm({ remark: account.remark || account.note || '', @@ -270,10 +332,16 @@ const AccountList: React.FC = () => { }; const openAIModal = async (account: AccountDetail) => { + const generation = aiLoadGateRef.current!.next(); + aiLoadAbortRef.current?.abort(); + const controller = new AbortController(); + aiLoadAbortRef.current = controller; setEditingAccount(account); + setActiveModal('ai-settings'); setSaving(true); try { - const settings = await getAccountAISettings(account.id); + const settings = await getAccountAISettings(account.id, { signal: controller.signal }); + if (!aiLoadGateRef.current?.isCurrent(generation)) return; setAiSettings({ ai_enabled: settings.ai_enabled ?? false, max_discount_percent: settings.max_discount_percent ?? 10, @@ -282,11 +350,10 @@ const AccountList: React.FC = () => { custom_prompts: settings.custom_prompts ?? '', }); } catch (e) { - console.error('Failed to load AI settings:', e); + if (aiLoadGateRef.current?.isCurrent(generation)) console.error('Failed to load AI settings:', e); } finally { - setSaving(false); + if (aiLoadGateRef.current?.isCurrent(generation)) setSaving(false); } - setActiveModal('ai-settings'); }; const handleSaveEdit = async () => { @@ -294,40 +361,40 @@ const AccountList: React.FC = () => { setSaving(true); try { - const promises: Promise[] = []; + const payload: Parameters[1] = {}; // 更新备注 if (editForm.remark !== (editingAccount.remark || editingAccount.note || '')) { - promises.push(updateAccountRemark(editingAccount.id, editForm.remark)); + payload.remark = editForm.remark; } // 更新Cookie if (editForm.cookie && editForm.cookie !== (editingAccount.cookie || editingAccount.value || '')) { - promises.push(updateAccountCookie(editingAccount.id, editForm.cookie)); + payload.cookie = editForm.cookie; } // 更新自动确认 if (editForm.auto_confirm !== editingAccount.auto_confirm) { - promises.push(updateAccountAutoConfirm(editingAccount.id, editForm.auto_confirm)); + payload.auto_confirm = editForm.auto_confirm; } // 更新暂停时长 - if (editForm.pause_duration !== (editingAccount.pause_duration || 0)) { - promises.push(updateAccountPauseDuration(editingAccount.id, editForm.pause_duration)); - } + if (shouldUpdateAccountPause(editForm.pause_duration, editingAccount)) { + payload.pause_duration = editForm.pause_duration; + } // 更新登录信息 const loginInfo = buildAccountLoginInfoUpdate(editingAccount, editForm); if (loginInfo) { - promises.push(updateAccountLoginInfo(editingAccount.id, loginInfo)); + Object.assign(payload, loginInfo); } // 只有成功加载且用户确实改动后才覆盖,避免加载失败被误解释成解绑全部。 if (shouldSaveNotificationBindings(bindingsLoaded, bindingsDirty)) { - promises.push(setAccountBindings(editingAccount.id, selectedChannelIds)); + payload.channel_ids = selectedChannelIds; } - await Promise.all(promises); + if (Object.keys(payload).length > 0) await updateAccountSettings(editingAccount.id, payload); setActiveModal(null); loadAccounts(); } catch (error) { @@ -338,6 +405,25 @@ const AccountList: React.FC = () => { } }; + const handleRestartPause = async () => { + if (!editingAccount || editForm.pause_duration <= 0) return; + setSaving(true); + try { + const result = await updateAccountPauseDuration(editingAccount.id, editForm.pause_duration); + setEditingAccount({ + ...editingAccount, + pause_duration: editForm.pause_duration, + paused: result?.paused === true, + paused_until: Number(result?.paused_until || 0), + }); + await loadAccounts(); + } catch (error) { + alert(error instanceof Error ? error.message : '重新暂停失败'); + } finally { + setSaving(false); + } + }; + const handleSaveAISettings = async () => { if (!editingAccount) return; setSaving(true); @@ -354,13 +440,122 @@ const AccountList: React.FC = () => { } }; - const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => { - let res = await completeQRVerification(sessionId, target?.id); - if (res.requires_confirmation) { - const confirmed = confirm(`扫码返回的账号ID是 ${res.scanned_account_id || '未知'},确认覆盖 ${target?.id || '当前账号'} 的授权吗?`); - if (!confirmed) return ''; - res = await completeQRVerification(sessionId, target?.id, true); + const pollPasswordLogin = async (sessionId: string, generation: number) => { + passwordPollAbortRef.current?.abort(); + const controller = new AbortController(); + passwordPollAbortRef.current = controller; + try { + const result = await checkPasswordLoginStatus(sessionId, controller.signal); + if (generation !== passwordPollGenerationRef.current) return; + if (result.status === 'success') { + clearPasswordPollTimer(); + setPasswordLoginView({ + sessionId, + status: 'success', + message: result.message || '账号密码登录成功,授权信息已更新', + qrCodeUrl: '', + }); + setEditForm(current => ({ ...current, login_password: '', showLoginPassword: false })); + await loadAccounts(); + return; + } + if (result.status === 'processing' || result.status === 'verification_required') { + setPasswordLoginView({ + sessionId, + status: result.status, + message: result.message || (result.status === 'verification_required' ? '账号触发风控,需要完成人脸识别' : '登录处理中'), + qrCodeUrl: result.qr_code_url || '', + }); + clearPasswordPollTimer(); + passwordPollTimerRef.current = window.setTimeout(() => void pollPasswordLogin(sessionId, generation), 1500); + return; + } + clearPasswordPollTimer(); + setPasswordLoginView({ + sessionId, + status: 'failed', + message: result.error || result.message || '密码登录失败,请检查账号信息后重试', + qrCodeUrl: '', + }); + } catch (error) { + if (generation !== passwordPollGenerationRef.current) return; + clearPasswordPollTimer(); + setPasswordLoginView({ + sessionId, + status: 'failed', + message: error instanceof Error ? error.message : '查询密码登录状态失败', + qrCodeUrl: '', + }); } + }; + + const handlePasswordLogin = async () => { + if (!editingAccount) return; + const account = editForm.username.trim(); + if (!account || !editForm.login_password) { + alert('请先填写登录账号和本次登录密码'); + return; + } + clearPasswordPollTimer(); + passwordPollAbortRef.current?.abort(); + const generation = ++passwordPollGenerationRef.current; + setPasswordLoginView({ sessionId: '', status: 'processing', message: '正在启动密码登录…', qrCodeUrl: '' }); + try { + const result = await passwordLogin({ + account_id: editingAccount.id, + account, + password: editForm.login_password, + show_browser: editForm.show_browser, + }); + if (generation !== passwordPollGenerationRef.current) return; + if (!result.success || !result.session_id) { + throw new Error(result.message || '无法启动密码登录'); + } + setPasswordLoginView({ sessionId: result.session_id, status: 'processing', message: result.message || '登录处理中', qrCodeUrl: '' }); + await pollPasswordLogin(result.session_id, generation); + } catch (error) { + if (generation !== passwordPollGenerationRef.current) return; + setPasswordLoginView({ + sessionId: '', + status: 'failed', + message: error instanceof Error ? error.message : '启动密码登录失败', + qrCodeUrl: '', + }); + } + }; + + const handleCancelPasswordLogin = async () => { + const sessionId = passwordLoginView.sessionId; + passwordPollGenerationRef.current += 1; + passwordPollAbortRef.current?.abort(); + clearPasswordPollTimer(); + if (sessionId) { + try { + await cancelPasswordLogin(sessionId); + } catch (error) { + console.error('取消密码登录失败', error); + } + } + setPasswordLoginView({ sessionId: '', status: 'idle', message: '', qrCodeUrl: '' }); + }; + + const closeEditModal = async () => { + bindingsLoadGateRef.current?.cancel(); + bindingsLoadAbortRef.current?.abort(); + if (passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') { + await handleCancelPasswordLogin(); + } + setActiveModal(null); + }; + + const closeAIModal = () => { + aiLoadGateRef.current?.cancel(); + aiLoadAbortRef.current?.abort(); + setActiveModal(null); + }; + + const completeAndPersistQRSession = async (sessionId: string, target?: AccountDetail | null) => { + const res = await completeQRVerification(sessionId, target?.id); if (!res.success || !res.account_id) { throw new Error(res.message || '保存扫码授权失败'); } @@ -369,27 +564,30 @@ const AccountList: React.FC = () => { const startQRLogin = async (target?: AccountDetail) => { stopQRPolling(); + qrGenerateAbortRef.current?.abort(); + const controller = new AbortController(); + qrGenerateAbortRef.current = controller; + const requestGeneration = qrRequestGateRef.current!.next(); clearQRCloseTimer(); const targetAccount = target || null; setQrReauthTarget(targetAccount); setShowQRModal(true); setQrStatus('loading'); setQrCodeUrl(''); - setQrSessionId(''); - setVerificationUrl(''); setVerificationScreenshot(''); setFaceQrUrl(''); try { - const res = await generateQRLogin(); + const res = await generateQRLogin({ signal: controller.signal }); + if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return; if (res.success && res.qr_code_url && res.session_id) { + const generatedSessionID = res.session_id; setQrCodeUrl(res.qr_code_url); - setQrSessionId(res.session_id); setQrStatus('waiting'); - qrPollerRef.current?.start(res.session_id, checkQRLoginStatus, { + qrPollerRef.current?.start(generatedSessionID, checkQRLoginStatus, { onSuccess: async () => { try { - const accountId = await completeAndPersistQRSession(res.session_id, targetAccount); + const accountId = await completeAndPersistQRSession(generatedSessionID, targetAccount); if (!accountId) { setQrStatus('error'); return; @@ -414,7 +612,6 @@ const AccountList: React.FC = () => { }, onVerificationRequired: (statusRes) => { setQrStatus('verification'); - setVerificationUrl(statusRes.verification_url || ''); if (statusRes.face_qr_url) { setFaceQrUrl(statusRes.face_qr_url); } @@ -425,29 +622,11 @@ const AccountList: React.FC = () => { }); } } catch (e) { + if (!qrRequestGateRef.current?.isCurrent(requestGeneration)) return; setQrStatus('error'); } }; - // 用户完成风控验证后,点"我已完成验证"调用后端提取真实 cookie。 - const handleCompleteVerification = async () => { - if (!qrSessionId) return; - setQrStatus('loading'); - try { - const accountId = await completeAndPersistQRSession(qrSessionId, qrReauthTarget); - if (accountId) { - stopQRPolling(); - setQrStatus('success'); - scheduleQRModalClose(); - } else { - setQrStatus('verification'); - } - } catch (e) { - setQrStatus('verification'); - alert('处理失败:' + (e instanceof Error ? e.message : String(e))); - } - }; - if (loading) return
; const filteredAccounts = accounts.filter(account => { @@ -555,7 +734,7 @@ const AccountList: React.FC = () => { )}
{account.auto_confirm && 自动确认发货} - {account.pause_duration > 0 && 暂停{account.pause_duration}分钟} + {account.paused && 暂停处理中}
@@ -626,7 +805,7 @@ const AccountList: React.FC = () => { {/* QR Code Modal */} {showQRModal && createPortal(
-
+
-
- )} - {qrStatus === 'verification' && ( -
- 需要安全验证 - - {faceQrUrl - ? '请用手机闲鱼扫描下方二维码完成人脸验证,验证通过后将自动登录。' - : '正在准备验证二维码,请保持页面打开。'} - - {faceQrUrl ? ( - 人脸验证二维码 - ) : verificationScreenshot ? ( - 验证页面 - ) : ( -
- -
- )} - {verificationUrl && ( - - 打开安全验证页面 - - )} - - 验证完成后点击确认,系统会提取并保存登录状态。 -
- )} + {qrStatus === 'error' && ( +
+ 二维码获取失败 + 请关闭窗口后重新发起扫码登录。 +
+ )} + {qrStatus === 'verification' && ( + + )}
-

二维码有效期为5分钟,请尽快扫码。

+ {qrStatus !== 'verification' &&

二维码有效期为5分钟,请尽快扫码。

}
@@ -710,7 +864,7 @@ const AccountList: React.FC = () => {

{editingAccount.nickname || editingAccount.remark || editingAccount.id}

+ )} {/* 登录信息 */} @@ -859,6 +1023,39 @@ const AccountList: React.FC = () => { /> +
+
+
+
立即执行账号密码登录
+
需要在上方重新输入本次登录密码;成功后后端会更新 Cookie 和保存的登录信息。
+
+ {(passwordLoginView.status === 'processing' || passwordLoginView.status === 'verification_required') ? ( + + ) : ( + + )} +
+ {passwordLoginView.message && ( +
+ {passwordLoginView.message} +
+ )} + {passwordLoginView.status === 'verification_required' && ( +
+
账号已触发平台风控,需要完成人脸识别
+
请在闲鱼 App 或已打开的登录浏览器中按提示完成验证。本页面不会提供可直接打开的风控链接。
+ {passwordLoginView.qrCodeUrl && ( +
+ +
+ )} +
+ )} +
@@ -918,7 +1115,7 @@ const AccountList: React.FC = () => {
+ {recentBatch && !['running', 'canceling'].includes(recentBatch.status) && ( + + )}
@@ -734,7 +812,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => {

批量铺货

上传商品表格和图片 zip,先预检,再逐条发布到闲鱼。

- @@ -855,14 +933,14 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { ['邮费模式', '可以留空', '留空表示包邮;包邮填 free,固定邮费填 fixed'], ['邮费', '邮费模式填 fixed 时填写', '只填数字,例如 8.00'], ['图片', '每个商品都要填', '填写 zip 内图片路径或图片网址;多张图片用英文分号隔开'], - ['付款后自动发货', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'], - ['付款后发送的卡密', '“付款后自动发货”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'], - ['评价后发送赠品', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'], - ['评价后发送的卡密', '“评价后发送赠品”填“是”时填写', '格式和付款后发送的卡密相同,也可以同时发送多个卡密组'], - ['超时未评价时提醒', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'], - ['发货几小时后提醒', '“超时未评价时提醒”填“是”时填写', '填写等待小时数;留空按 72 小时处理'], - ['提醒内容', '“超时未评价时提醒”填“是”时填写', '填写要发送给买家的求评价消息'], - ['最多提醒几次', '可以留空', '留空只提醒 1 次'], + ['付款发货启用', '需要付款后自动发货时填写', '填“是”表示开启;不需要时填“否”或留空'], + ['付款发货内容', '“付款发货启用”填“是”时填写', '从“卡密库存”页面取得卡密组 ID,按上方示例填写'], + ['评价赠品启用', '需要评价赠品时填写', '填“是”表示开启;不需要时填“否”或留空'], + ['评价赠品内容', '“评价赠品启用”填“是”时填写', '格式和付款发货内容相同,也可以同时发送多个卡密组'], + ['求评价启用', '需要自动求评价时填写', '填“是”表示开启;不需要时填“否”或留空'], + ['求评价等待小时', '“求评价启用”填“是”时填写', '填写等待小时数;留空按 72 小时处理'], + ['求评价文案', '“求评价启用”填“是”时填写', '填写要发送给买家的求评价消息'], + ['求评价最多次数', '可以留空', '留空只提醒 1 次'], ].map(([name, when, desc]) => ( {name} @@ -995,7 +1073,7 @@ const ItemList: React.FC = ({ onConfigureDelivery }) => { )} {batchPhase === 'preview' && batchPreview && (
- + ) : batchDetail.status === 'canceling' ? ( + ) : ( )} - {batchDetail.failed > 0 && batchDetail.status !== 'running' && ( + {batchDetail.retryable > 0 && !['running', 'canceling'].includes(batchDetail.status) && ( )} - {batchDetail.status !== 'running' && ( + {!['running', 'canceling'].includes(batchDetail.status) && ( diff --git a/frontend/components/Notifications.tsx b/frontend/components/Notifications.tsx index 85e8c79..f862e0d 100644 --- a/frontend/components/Notifications.tsx +++ b/frontend/components/Notifications.tsx @@ -228,6 +228,8 @@ const Notifications: React.FC = ({ isAdmin = false }) => { smtp_password: smtp.smtp_password || '', smtp_from_name: smtp.smtp_from_name || '', smtp_from_address: smtp.smtp_from_address || smtp.smtp_user || '', + smtp_use_tls: smtp.smtp_use_tls !== false, + smtp_use_ssl: smtp.smtp_use_ssl === true, }); showToast('success', 'SMTP 配置已保存'); } catch (e: any) { @@ -344,8 +346,9 @@ const Notifications: React.FC = ({ isAdmin = false }) => {

通知设置

配置通知渠道,账号异常时主动推送告警

-
-
- + - @@ -839,7 +861,7 @@ const OrderList: React.FC = () => { setEditingOrder({ ...editingOrder, amount: parseFloat(e.target.value) })} + onChange={(e) => setEditingOrder({ ...editingOrder, amount: e.target.value })} className="w-full ios-input px-4 py-3 rounded-xl" /> diff --git a/frontend/components/RiskVerificationPanel.test.tsx b/frontend/components/RiskVerificationPanel.test.tsx new file mode 100644 index 0000000..cca79ee --- /dev/null +++ b/frontend/components/RiskVerificationPanel.test.tsx @@ -0,0 +1,16 @@ +import React from 'react'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { expect, test } from 'vitest'; +import { RiskVerificationPanel } from './RiskVerificationPanel'; + +test('risk verification panel explains automatic refresh without manual controls', () => { + const html = renderToStaticMarkup( + , + ); + expect(html).toContain('需要完成安全风控验证'); + expect(html).toContain('系统会自动检测并刷新登录状态'); + expect(html).toContain('max-h-[min(64vh,28rem)]'); + expect(html).not.toContain(' = ({ + faceQrUrl, + verificationScreenshot, +}) => ( +
+
+
+

+ 需要完成安全风控验证 +

+

+ 当前账号触发了闲鱼平台风控。请使用手机闲鱼 App 扫描下方二维码,并按 App 提示完成人脸识别。 +

+ +
+ {faceQrUrl ? ( + 闲鱼安全风控验证二维码 + ) : verificationScreenshot ? ( + 闲鱼风控验证页面 + ) : ( +
+
+ )} +
+ +

+ 请勿在浏览器中打开验证链接。完成验证后系统会自动检测并刷新登录状态,无需手动确认。 +

+
+); diff --git a/frontend/components/Rules.tsx b/frontend/components/Rules.tsx index d1c70ab..74f0a11 100644 --- a/frontend/components/Rules.tsx +++ b/frontend/components/Rules.tsx @@ -1,4 +1,4 @@ -import React, { useCallback, useEffect, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { createPortal } from 'react-dom'; import { AccountDetail, @@ -21,11 +21,16 @@ import { getDefaultReplies, getDefaultReply, getItems, + getAutomationIssues, getReplyRules, getShippingRules, updateDefaultReply, updateReplyRule, updateShippingRule, + resolveAutomationRun, + resolveDeferredAutomationTask, + AutomationRunIssue, + DeferredAutomationIssue, } from '../services/api'; import { AlertCircle, @@ -45,6 +50,13 @@ import { X, Zap, } from 'lucide-react'; +import { + automationIssueKindLabel, + canResolveAutomationIssue, + filterAutomationIssues, + loadAutomationPageData, +} from './automationIssueState'; +import { commitIfLatest } from './latestRequest'; type RulesTab = 'automation' | 'reply' | 'default'; @@ -128,6 +140,7 @@ const buildReviewConfig = (raw?: string, patch: Record = {}) => const current = parseJSONObject(raw); return JSON.stringify({ after_shipped_hours: Number(current.after_shipped_hours || 72), + repeat_interval_hours: Number(current.repeat_interval_hours || 24), max_attempts: Number(current.max_attempts || 1), ...patch, }); @@ -199,6 +212,7 @@ const boolFlag = (value: unknown): boolean => value === true || value === 1 || v const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHandled }) => { const [activeTab, setActiveTab] = useState('automation'); const [automationRules, setAutomationRules] = useState([]); + const [automationIssues, setAutomationIssues] = useState<{ runs: AutomationRunIssue[]; pending_tasks: DeferredAutomationIssue[] }>({ runs: [], pending_tasks: [] }); const [replyRules, setReplyRules] = useState([]); const [defaultReplies, setDefaultReplies] = useState>({}); const [accounts, setAccounts] = useState([]); @@ -206,6 +220,9 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa const [items, setItems] = useState([]); const [loading, setLoading] = useState(false); const [selectedAccountId, setSelectedAccountId] = useState(''); + const replyRulesRequest = useRef(0); + const selectedAccountRef = useRef(''); + selectedAccountRef.current = selectedAccountId; const [showAutomationModal, setShowAutomationModal] = useState(false); const [showReplyModal, setShowReplyModal] = useState(false); @@ -236,15 +253,25 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa }, []); const loadAutomationRules = useCallback(async () => { - setAutomationRules(await getShippingRules()); + await loadAutomationPageData({ + loadRules: getShippingRules, + loadIssues: getAutomationIssues, + onRules: setAutomationRules, + onIssues: setAutomationIssues, + onIssuesError: error => console.warn('加载自动化异常列表失败,不阻断规则展示', error), + }); }, []); const loadReplyRules = useCallback(async () => { - if (!selectedAccountId) { - setReplyRules([]); - return; - } - setReplyRules(await getReplyRules(selectedAccountId)); + const cookieID = selectedAccountId; + if (cookieID !== selectedAccountRef.current) return; + const requestID = ++replyRulesRequest.current; + setReplyRules([]); + if (!cookieID) { + return; + } + const rules = await getReplyRules(cookieID); + commitIfLatest(requestID, replyRulesRequest.current, cookieID, selectedAccountRef.current, rules, setReplyRules); }, [selectedAccountId]); const loadDefaultReplies = useCallback(async () => { @@ -267,11 +294,11 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa }, [activeTab, loadAutomationRules, loadDefaultReplies, loadReplyRules]); useEffect(() => { - void loadReferenceData(); + void loadReferenceData().catch(error => console.error('加载规则参考数据失败', error)); }, [loadReferenceData]); useEffect(() => { - void refresh(); + void refresh().catch(error => console.error('刷新规则页面失败', error)); }, [refresh]); const visibleAutomationRules = useMemo( @@ -279,6 +306,11 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa [automationRules, selectedAccountId], ); + const visibleAutomationIssues = useMemo( + () => filterAutomationIssues(automationIssues, selectedAccountId), + [automationIssues, selectedAccountId], + ); + const visibleDefaultAccounts = useMemo( () => accounts.filter(account => !selectedAccountId || account.id === selectedAccountId), [accounts, selectedAccountId], @@ -565,6 +597,31 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa } }; + const handleResolveRunIssue = async (id: number, resolution: 'continue' | 'retry' | 'cancel') => { + const prompt = resolution === 'continue' + ? '确认外部动作已经执行成功,并跳到下一步吗?' + : resolution === 'retry' + ? '确认外部动作没有执行,可以安全重试吗?错误判断可能造成重复发送。' + : '确认终止该自动化运行吗?'; + if (!confirm(prompt)) return; + try { + await resolveAutomationRun(id, resolution); + await loadAutomationRules(); + } catch (error) { + alert('处理失败:' + (error as Error).message); + } + }; + + const handleResolveDeferredIssue = async (id: number, resolution: 'retry' | 'dismiss') => { + if (!confirm(resolution === 'retry' ? '确认重新执行该任务吗?' : '确认忽略并删除该异常任务吗?')) return; + try { + await resolveDeferredAutomationTask(id, resolution); + await loadAutomationRules(); + } catch (error) { + alert('处理失败:' + (error as Error).message); + } + }; + const handleAddReplyRule = () => { if (!selectedAccountId) { alert('请先选择账号'); @@ -573,6 +630,9 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa setEditingReplyRule({ keyword: '', reply_content: '', + image_url: '', + item_id: '', + type: 'text', match_type: 'fuzzy', enabled: true, }); @@ -581,7 +641,9 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa const handleSaveReplyRule = async () => { if (!editingReplyRule || !selectedAccountId) return; - const hasReplyContent = Boolean(editingReplyRule.reply_content?.trim() || editingReplyRule.image_url?.trim()); + const hasReplyContent = editingReplyRule.type === 'image' + ? Boolean(editingReplyRule.image_url?.trim()) + : Boolean(editingReplyRule.reply_content?.trim()); if (!editingReplyRule.keyword?.trim() || !hasReplyContent) { alert('请填写关键词和回复内容'); return; @@ -744,6 +806,46 @@ const Rules: React.FC = ({ initialDeliveryTarget, onDeliveryTargetHa })} + {activeTab === 'automation' && (visibleAutomationIssues.runs.length > 0 || visibleAutomationIssues.pending_tasks.length > 0) && ( +
+
+ +
+

需要人工处理的自动化任务

+

请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。

+
+
+
+ {visibleAutomationIssues.runs.map(issue => ( +
+
+
账号 {issue.cookie_id} · 订单 {issue.order_id || '-'} · 已记录发送 {issue.sent_count} 条
+
{automationIssueKindLabel(issue.issue_kind)}
+
{issue.error_message}
+
+
+ {canResolveAutomationIssue(issue, 'continue') && } + {canResolveAutomationIssue(issue, 'retry') && } + {canResolveAutomationIssue(issue, 'cancel') && } +
+
+ ))} + {visibleAutomationIssues.pending_tasks.map(issue => ( +
+
+
账号 {issue.cookie_id} · 延迟任务重试已达 {issue.attempt_count} 次
+
{issue.error_message}
+
+
+ + +
+
+ ))} +
+
+ )} + {activeTab === 'automation' && (
-
+
= ({ initialDeliveryTarget, onDeliveryTargetHa className="w-full ios-input px-4 py-3 rounded-xl" />
+
+ + setEditingAutomationRule({ + ...editingAutomationRule, + config_json: buildReviewConfig(editingAutomationRule.config_json, { + repeat_interval_hours: Math.max(1, Number(event.target.value) || 24), + }), + })} + className="w-full ios-input px-4 py-3 rounded-xl" + /> +
= ({ initialDeliveryTarget, onDeliveryTargetHa className="w-full ios-input px-4 py-3 rounded-xl" />
-
+