From 16d63dc7c9d0e061438a368b5e3259be47ce4c20 Mon Sep 17 00:00:00 2001 From: Christ Date: Tue, 14 Jul 2026 21:20:22 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=B3=BB=E7=BB=9F=E5=8F=AF?= =?UTF-8?q?=E9=9D=A0=E6=80=A7=E3=80=81=E7=99=BB=E5=BD=95=E9=A3=8E=E6=8E=A7?= =?UTF-8?q?=E4=B8=8E=E8=B7=A8=E6=95=B0=E6=8D=AE=E5=BA=93=E5=9B=9E=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" />
-
+