可靠性与数据一致性:为 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 包通过,失败现状随本次既有工作区一并提交。
319 lines
10 KiB
Go
319 lines
10 KiB
Go
package engine
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"path/filepath"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"xianyu-go/internal/automation"
|
|
"xianyu-go/internal/db"
|
|
)
|
|
|
|
// recordingHandler 记录收到的聊天消息,用于断言防抖与去重行为。
|
|
type recordingHandler struct {
|
|
mu sync.Mutex
|
|
chats []ChatMessage
|
|
refresh int
|
|
}
|
|
|
|
func (h *recordingHandler) HandleChatMessage(_ context.Context, m ChatMessage) error {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
h.chats = append(h.chats, m)
|
|
return nil
|
|
}
|
|
func (h *recordingHandler) HandleSystemEvent(_ context.Context, task automation.Task) error {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
_ = task
|
|
return nil
|
|
}
|
|
func (h *recordingHandler) OnPasswordLoginRefresh(_ context.Context, _ string) bool {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
h.refresh++
|
|
return true
|
|
}
|
|
func (h *recordingHandler) OnAccountAlert(_ context.Context, _, _, _, _ string) {}
|
|
|
|
func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, func()) {
|
|
t.Helper()
|
|
dbPath := filepath.Join(t.TempDir(), "test.db")
|
|
d, _, err := db.Open(context.Background(), dbPath)
|
|
if err != nil {
|
|
t.Fatalf("Open: %v", err)
|
|
}
|
|
store := db.NewStore(d, db.DialectSQLite)
|
|
store.Users.Create(context.Background(), "admin", "a@e.com", "pw")
|
|
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
|
|
store.Cookies.Save(context.Background(), "cid", "unb=123; _m_h5_tk=tk_1;", admin.ID)
|
|
store.Cookies.SetStatus(context.Background(), "cid", true)
|
|
|
|
h := &recordingHandler{}
|
|
acc := New(Config{
|
|
CookieID: "cid",
|
|
CookieStr: "unb=123; _m_h5_tk=tk_1;",
|
|
Store: store,
|
|
Handler: h,
|
|
})
|
|
return acc, h, store, func() { d.Close() }
|
|
}
|
|
|
|
// TestExtractChatMessage_RealSample 用真实抓包样本验证消息字段提取。
|
|
func TestExtractChatMessage_RealSample(t *testing.T) {
|
|
decrypted := mustDecryptGoldenSample(t)
|
|
chat := extractChatMessage(decrypted, "cid", "cookie")
|
|
if chat == nil {
|
|
t.Fatal("应为聊天消息")
|
|
}
|
|
if chat.ChatID != "47983389009" {
|
|
t.Errorf("ChatID=%q want 47983389009", chat.ChatID)
|
|
}
|
|
if chat.Text != "[我已拍下,待付款]" {
|
|
t.Errorf("Text=%q want [我已拍下,待付款]", chat.Text)
|
|
}
|
|
if chat.ItemID != "900052644277" {
|
|
t.Errorf("ItemID=%q want 900052644277", chat.ItemID)
|
|
}
|
|
}
|
|
|
|
func TestExtractChatMessage_FiltersContentType14Notice(t *testing.T) {
|
|
decrypted := mustContentType14Notice(t)
|
|
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
|
t.Fatalf("contentType=14 系统提示不应进入聊天回复: %+v", chat)
|
|
}
|
|
}
|
|
|
|
func TestExtractChatMessage_FiltersRefundTradeCard(t *testing.T) {
|
|
decrypted := mustRefundTradeCard(t)
|
|
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
|
t.Fatalf("退款交易卡片不应进入聊天回复: %+v", chat)
|
|
}
|
|
}
|
|
|
|
func TestExtractChatMessage_FiltersPaidDeliveryCardFromChat(t *testing.T) {
|
|
decrypted := mustPaidDeliveryCard(t)
|
|
if chat := extractChatMessage(decrypted, "cid", "cookie"); chat != nil {
|
|
t.Fatalf("付款待发货系统卡片不应进入聊天回复链: %+v", chat)
|
|
}
|
|
task := automation.ExtractTaskFromWS("cid", "cookie", decrypted)
|
|
if task == nil || task.TriggerType != automation.TriggerOrderPaid {
|
|
t.Fatalf("付款待发货卡片应进入自动化中心: %+v", task)
|
|
}
|
|
}
|
|
|
|
// TestDedup_SkipsDuplicateWithinExpiry 同一消息 ID 1 小时内只处理一次。
|
|
func TestDedup_SkipsDuplicateWithinExpiry(t *testing.T) {
|
|
acc, h, _, cleanup := newAccountForTest(t)
|
|
defer cleanup()
|
|
defer acc.Stop()
|
|
|
|
decrypted := mustDecryptGoldenSample(t)
|
|
chat := extractChatMessage(decrypted, "cid", "cookie")
|
|
|
|
// 首次:标记并应继续。
|
|
if !acc.markAndCheckDedup(decrypted, chat) {
|
|
t.Fatal("首次应允许处理")
|
|
}
|
|
// 第二次同一消息 ID:应跳过。
|
|
if acc.markAndCheckDedup(decrypted, chat) {
|
|
t.Fatal("重复消息应被去重跳过")
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if len(h.chats) != 0 {
|
|
t.Errorf("去重阶段不应投递消息,got %d", len(h.chats))
|
|
}
|
|
}
|
|
|
|
// TestDebounce_CoalescesRapidMessages 连续消息只投递最后一条。
|
|
func TestDebounce_CoalescesRapidMessages(t *testing.T) {
|
|
acc, h, _, cleanup := newAccountForTest(t)
|
|
defer cleanup()
|
|
defer acc.Stop()
|
|
|
|
decrypted := mustDecryptGoldenSample(t)
|
|
chat := extractChatMessage(decrypted, "cid", "cookie")
|
|
// 修改文本模拟连续多条。
|
|
chat1 := *chat
|
|
chat1.Text = "第一条"
|
|
chat2 := *chat
|
|
chat2.Text = "第二条"
|
|
chat3 := *chat
|
|
chat3.Text = "第三条"
|
|
|
|
// 用不同 decrypted(不同 msgID)触发防抖,验证同一 chat_id 合并。
|
|
acc.scheduleDebouncedReply(chat1)
|
|
acc.scheduleDebouncedReply(chat2)
|
|
acc.scheduleDebouncedReply(chat3)
|
|
|
|
// 等待防抖延迟 + 余量。
|
|
time.Sleep(MessageDebounceDelay + 200*time.Millisecond)
|
|
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
if len(h.chats) != 1 {
|
|
t.Fatalf("防抖应只投递最后一条,got %d", len(h.chats))
|
|
}
|
|
if h.chats[0].Text != "第三条" {
|
|
t.Errorf("应投递最后一条,got %q", h.chats[0].Text)
|
|
}
|
|
}
|
|
|
|
// TestExtractItemID reminderUrl 中提取 itemId。
|
|
func TestExtractItemID(t *testing.T) {
|
|
cases := map[string]string{
|
|
"fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063": "900052644277",
|
|
"noitemid": "",
|
|
"fleamarket://x?itemId=ABC123": "ABC123",
|
|
}
|
|
for in, want := range cases {
|
|
if got := extractItemID(in); got != want {
|
|
t.Errorf("extractItemID(%q)=%q want %q", in, got, want)
|
|
}
|
|
}
|
|
}
|
|
|
|
// mustDecryptGoldenSample 复用 protocol 包的真实样本:直接硬编码一条最小解密结构,
|
|
// 避免循环依赖。这里构造一个等价的最小消息用于字段提取测试。
|
|
func mustDecryptGoldenSample(t *testing.T) map[string]any {
|
|
t.Helper()
|
|
// 真实样本关键字段(来自 protocol golden test 解密输出):
|
|
// message["1"]["2"]="47983389009@goofish", ["1"]["10"]["reminderContent"]="[我已拍下,待付款]",
|
|
// ["1"]["10"]["reminderUrl"] 含 itemId=900052644277
|
|
s := `{
|
|
"1": {
|
|
"2": "47983389009@goofish",
|
|
"10": {
|
|
"reminderContent": "[我已拍下,待付款]",
|
|
"senderNick": "买家昵称",
|
|
"senderUserId": "3149637063",
|
|
"reminderUrl": "fleamarket://message_chat?itemId=900052644277&peerUserId=3149637063"
|
|
}
|
|
},
|
|
"3": {
|
|
"redReminder": "等待买家付款",
|
|
"userId": "3149637063"
|
|
}
|
|
}`
|
|
var m map[string]any
|
|
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
return m
|
|
}
|
|
|
|
func mustContentType14Notice(t *testing.T) map[string]any {
|
|
t.Helper()
|
|
s := "{" +
|
|
"\"1\":{" +
|
|
"\"2\":\"63107041124@goofish\"," +
|
|
"\"10\":{" +
|
|
"\"extJson\":\"{\\\"contentType\\\":\\\"14\\\",\\\"messageId\\\":\\\"d050b73332b94d5a8901cff78519483a\\\"}\"," +
|
|
"\"reminderContent\":\"[不想宝贝被砍价?设置不砍价回复 ]\"," +
|
|
"\"senderUserId\":\"2222315258815\"," +
|
|
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
|
|
"}," +
|
|
"\"6\":{\"3\":{\"4\":14,\"5\":\"{\\\"contentType\\\":14,\\\"tip\\\":{\\\"argInfo\\\":{\\\"arg1\\\":\\\"NoBargainGuide\\\"}}}\"}}" +
|
|
"}" +
|
|
"}"
|
|
var m map[string]any
|
|
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
return m
|
|
}
|
|
|
|
func mustRefundTradeCard(t *testing.T) map[string]any {
|
|
t.Helper()
|
|
s := "{" +
|
|
"\"1\":{" +
|
|
"\"2\":\"63107041124@goofish\"," +
|
|
"\"10\":{" +
|
|
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:eeg858GGuju9\\\",\\\"taskName\\\":\\\"发起退款申请_卖家-新逆向url\\\"}\"," +
|
|
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"3a03978b7a374da898b3d7a084cbedb6\\\"}\"," +
|
|
"\"redReminder\":\"买家申请退款\"," +
|
|
"\"reminderContent\":\"[我发起了退款申请]\"," +
|
|
"\"senderUserId\":\"2222315258815\"," +
|
|
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
|
|
"}," +
|
|
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
|
|
"}" +
|
|
"}"
|
|
var m map[string]any
|
|
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
return m
|
|
}
|
|
|
|
func mustPaidDeliveryCard(t *testing.T) map[string]any {
|
|
t.Helper()
|
|
s := "{" +
|
|
"\"1\":{" +
|
|
"\"2\":\"63107041124@goofish\"," +
|
|
"\"10\":{" +
|
|
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:4Ytd4BSQKIiz\\\",\\\"taskName\\\":\\\"付款完成待发货_卖家-正向升级\\\"}\"," +
|
|
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\"}\"," +
|
|
"\"redReminder\":\"等待卖家发货\"," +
|
|
"\"reminderContent\":\"[我已付款,等待你发货]\"," +
|
|
"\"senderUserId\":\"2222315258815\"," +
|
|
"\"reminderUrl\":\"fleamarket://message_chat?itemId=1063177864132&peerUserId=2222315258815\"" +
|
|
"}," +
|
|
"\"6\":{\"3\":{\"4\":26,\"5\":\"{\\\"contentType\\\":26}\"}}" +
|
|
"}" +
|
|
"}"
|
|
var m map[string]any
|
|
if err := json.Unmarshal([]byte(s), &m); err != nil {
|
|
t.Fatalf("unmarshal: %v", err)
|
|
}
|
|
return m
|
|
}
|
|
|
|
// TestRetryDelay 复刻 _calculate_retry_delay 的分段逻辑。
|
|
func TestRetryDelay(t *testing.T) {
|
|
acc, _, _, cleanup := newAccountForTest(t)
|
|
defer cleanup()
|
|
defer acc.Stop()
|
|
|
|
acc.connFailures = 1
|
|
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 2*time.Second)
|
|
acc.connFailures = 10
|
|
expectDelayRange(t, acc.retryDelay("no close frame received or sent"), 30*time.Second)
|
|
acc.connFailures = 2
|
|
expectDelayRange(t, acc.retryDelay("connection refused"), 8*time.Second)
|
|
acc.connFailures = 10
|
|
expectDelayRange(t, acc.retryDelay("connection refused"), 90*time.Second)
|
|
acc.connFailures = 1
|
|
expectDelayRange(t, acc.retryDelay("some other error"), 2*time.Second)
|
|
}
|
|
|
|
func expectDelayRange(t *testing.T, got, base time.Duration) {
|
|
t.Helper()
|
|
max := base + base*3/10
|
|
if got < base || got > max {
|
|
t.Fatalf("retryDelay=%v want in [%v,%v]", got, base, max)
|
|
}
|
|
}
|
|
|
|
func TestRuntimeStatusClassifiesAuthenticationFailures(t *testing.T) {
|
|
acc, _, _, cleanup := newAccountForTest(t)
|
|
defer cleanup()
|
|
|
|
acc.setRuntimeError(context.Background(), fmt.Errorf("token API 登录凭证已失效: FAIL_SYS_TOKEN_EXOIRED"))
|
|
status := acc.RuntimeStatus()
|
|
if status.State != RuntimeAuthExpired || status.Connected {
|
|
t.Fatalf("status=%+v", status)
|
|
}
|
|
|
|
acc.setRuntimeError(context.Background(), fmt.Errorf("FAIL_SYS_USER_VALIDATE: captcha required"))
|
|
status = acc.RuntimeStatus()
|
|
if status.State != RuntimeVerificationRequired {
|
|
t.Fatalf("status=%+v", status)
|
|
}
|
|
}
|