可靠性与数据一致性:为 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 包通过,失败现状随本次既有工作区一并提交。
342 lines
11 KiB
Go
342 lines
11 KiB
Go
package server
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"path/filepath"
|
||
"strings"
|
||
"testing"
|
||
|
||
"xianyu-go/internal/account"
|
||
"xianyu-go/internal/automation"
|
||
"xianyu-go/internal/db"
|
||
"xianyu-go/internal/engine"
|
||
"xianyu-go/internal/xianyu/mtop"
|
||
)
|
||
|
||
func newTestServer(t *testing.T) (*Server, *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")
|
||
store.Users.SetAdmin(context.Background(), "admin")
|
||
// 一个账号。
|
||
admin, _ := store.Users.GetByUsername(context.Background(), "admin")
|
||
store.Cookies.Save(context.Background(), "acc1", "unb=123; _m_h5_tk=tk1_1;", admin.ID)
|
||
|
||
mgr := account.NewManager(store, noopHandler{}, nil)
|
||
srv := New(store, mgr, nil, false, "", ":0", nil, nil, nil)
|
||
mtopClient := mtop.NewClient()
|
||
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||
return &http.Response{
|
||
StatusCode: http.StatusOK,
|
||
Header: make(http.Header),
|
||
Body: io.NopCloser(strings.NewReader(
|
||
`{"ret":["SUCCESS::调用成功"],"data":{"module":{"base":{"displayName":"测试账号","avatar":"https://img.alicdn.com/test-avatar.jpg"}}}}`,
|
||
)),
|
||
Request: req,
|
||
}, nil
|
||
})}
|
||
srv.MTop = mtopClient
|
||
return srv, store, func() {
|
||
mgr.StopAll()
|
||
_ = d.Close()
|
||
}
|
||
}
|
||
|
||
type roundTripFunc func(*http.Request) (*http.Response, error)
|
||
|
||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||
return f(req)
|
||
}
|
||
|
||
type noopHandler struct{}
|
||
|
||
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
|
||
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
|
||
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||
func (noopHandler) OnAccountAlert(context.Context, string, string, string, string) {}
|
||
|
||
// TestLoginVerifyLogout 登录→verify→登出 全链路。
|
||
func TestLoginVerifyLogout(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
// 1) 登录(用户名密码)。
|
||
body := `{"username":"admin","password":"pw"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var lr loginResponse
|
||
json.Unmarshal(rec.Body.Bytes(), &lr)
|
||
if !lr.Success || !lr.IsAdmin {
|
||
t.Fatalf("登录响应异常: %+v", lr)
|
||
}
|
||
cookie := rec.Result().Cookies()[0]
|
||
if cookie.Name != "session" || cookie.Value == "" || !cookie.HttpOnly {
|
||
t.Fatalf("Cookie 异常: %+v", cookie)
|
||
}
|
||
|
||
// 2) verify 带 cookie 应 authenticated。
|
||
req2 := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||
req2.AddCookie(cookie)
|
||
rec2 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec2, req2)
|
||
var v map[string]any
|
||
json.Unmarshal(rec2.Body.Bytes(), &v)
|
||
if v["authenticated"] != true || v["initialized"] != true {
|
||
t.Fatalf("verify 异常: %+v", v)
|
||
}
|
||
|
||
// 3) 无 cookie verify 应未认证。
|
||
req3 := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||
rec3 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec3, req3)
|
||
json.Unmarshal(rec3.Body.Bytes(), &v)
|
||
if v["authenticated"] == true {
|
||
t.Fatal("无 cookie 应未认证")
|
||
}
|
||
|
||
// 4) 登出。
|
||
req4 := httptest.NewRequest(http.MethodPost, "/logout", nil)
|
||
req4.AddCookie(cookie)
|
||
rec4 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec4, req4)
|
||
// 登出后 cookie 应被清除(MaxAge=-1)。
|
||
dc := rec4.Result().Cookies()
|
||
cleared := false
|
||
for _, c := range dc {
|
||
if c.Name == "session" && c.MaxAge < 0 {
|
||
cleared = true
|
||
}
|
||
}
|
||
if !cleared {
|
||
t.Fatal("登出应清除 cookie")
|
||
}
|
||
}
|
||
|
||
// TestLoginWrongPassword 错误密码。
|
||
func TestLoginWrongPassword(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
body := `{"username":"admin","password":"wrong"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
var lr loginResponse
|
||
json.Unmarshal(rec.Body.Bytes(), &lr)
|
||
if lr.Success {
|
||
t.Fatal("错误密码不应成功")
|
||
}
|
||
}
|
||
|
||
func TestUpdateCredentialsRenamesUserAndRevokesSessions(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
|
||
loginRec := httptest.NewRecorder()
|
||
h.ServeHTTP(loginRec, loginReq)
|
||
sessionCookie := loginRec.Result().Cookies()[0]
|
||
|
||
updateReq := httptest.NewRequest(http.MethodPut, "/account/credentials", strings.NewReader(
|
||
`{"current_password":"pw","new_username":"operator","new_password":"newpassword"}`,
|
||
))
|
||
updateReq.AddCookie(sessionCookie)
|
||
updateRec := httptest.NewRecorder()
|
||
h.ServeHTTP(updateRec, updateReq)
|
||
if updateRec.Code != http.StatusOK {
|
||
t.Fatalf("update status=%d body=%s", updateRec.Code, updateRec.Body.String())
|
||
}
|
||
var updateResult map[string]any
|
||
json.Unmarshal(updateRec.Body.Bytes(), &updateResult)
|
||
if updateResult["success"] != true || updateResult["requires_relogin"] != true {
|
||
t.Fatalf("update result=%+v", updateResult)
|
||
}
|
||
|
||
verifyReq := httptest.NewRequest(http.MethodGet, "/verify", nil)
|
||
verifyReq.AddCookie(sessionCookie)
|
||
verifyRec := httptest.NewRecorder()
|
||
h.ServeHTTP(verifyRec, verifyReq)
|
||
var verifyResult map[string]any
|
||
json.Unmarshal(verifyRec.Body.Bytes(), &verifyResult)
|
||
if verifyResult["authenticated"] == true || verifyResult["initialized"] != true {
|
||
t.Fatalf("旧会话应失效且系统仍已初始化: %+v", verifyResult)
|
||
}
|
||
|
||
oldLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
|
||
oldLoginRec := httptest.NewRecorder()
|
||
h.ServeHTTP(oldLoginRec, oldLoginReq)
|
||
var oldLogin loginResponse
|
||
json.Unmarshal(oldLoginRec.Body.Bytes(), &oldLogin)
|
||
if oldLogin.Success {
|
||
t.Fatal("旧用户名不应继续登录")
|
||
}
|
||
|
||
newLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"operator","password":"newpassword"}`))
|
||
newLoginRec := httptest.NewRecorder()
|
||
h.ServeHTTP(newLoginRec, newLoginReq)
|
||
var newLogin loginResponse
|
||
json.Unmarshal(newLoginRec.Body.Bytes(), &newLogin)
|
||
if !newLogin.Success {
|
||
t.Fatalf("新凭据登录失败: %s", newLoginRec.Body.String())
|
||
}
|
||
}
|
||
|
||
// TestCookiesDetailsRequiresAuth 未登录访问受保护端点应 401。
|
||
func TestCookiesDetailsRequiresAuth(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
req := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusUnauthorized {
|
||
t.Fatalf("未登录应 401,got %d", rec.Code)
|
||
}
|
||
}
|
||
|
||
// TestCookiesDetailsWithAuth 登录后能取账号详情。
|
||
func TestCookiesDetailsWithAuth(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
// 登录拿 cookie。
|
||
body := `{"username":"admin","password":"pw"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
cookie := rec.Result().Cookies()[0]
|
||
|
||
// 取详情。
|
||
req2 := httptest.NewRequest(http.MethodGet, "/cookies/details", nil)
|
||
req2.AddCookie(cookie)
|
||
rec2 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec2, req2)
|
||
if rec2.Code != 200 {
|
||
t.Fatalf("status=%d body=%s", rec2.Code, rec2.Body.String())
|
||
}
|
||
var arr []map[string]any
|
||
json.Unmarshal(rec2.Body.Bytes(), &arr)
|
||
if len(arr) != 1 || arr[0]["id"] != "acc1" {
|
||
t.Fatalf("账号详情异常: %+v", arr)
|
||
}
|
||
// 不应返回 cookie 明文(安全基线)。
|
||
if _, has := arr[0]["value"]; has {
|
||
t.Fatal("不应返回 cookie 明文")
|
||
}
|
||
if arr[0]["has_cookie"] != true {
|
||
t.Fatal("应 has_cookie=true")
|
||
}
|
||
}
|
||
|
||
func TestCookieRuntimeStatusWithAuth(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
loginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
|
||
loginRec := httptest.NewRecorder()
|
||
h.ServeHTTP(loginRec, loginReq)
|
||
cookie := loginRec.Result().Cookies()[0]
|
||
|
||
req := httptest.NewRequest(http.MethodGet, "/cookies/runtime-status", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var statuses map[string]engine.RuntimeStatus
|
||
if err := json.Unmarshal(rec.Body.Bytes(), &statuses); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if statuses["acc1"].State != engine.RuntimeError {
|
||
t.Fatalf("未启动账号应返回 error,got %+v", statuses["acc1"])
|
||
}
|
||
}
|
||
|
||
// TestAddAndDeleteCookie 添加/删除账号。
|
||
func TestAddAndDeleteCookie(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
body := `{"username":"admin","password":"pw"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(body))
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
cookie := rec.Result().Cookies()[0]
|
||
|
||
// 添加。
|
||
addBody := `{"id":"acc2","value":"unb=456; _m_h5_tk=tk2_2;"}`
|
||
req2 := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(addBody))
|
||
req2.AddCookie(cookie)
|
||
rec2 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec2, req2)
|
||
if rec2.Code != 200 {
|
||
t.Fatalf("add status=%d body=%s", rec2.Code, rec2.Body.String())
|
||
}
|
||
|
||
// 删除。
|
||
req3 := httptest.NewRequest(http.MethodDelete, "/cookies/acc2", nil)
|
||
req3.AddCookie(cookie)
|
||
rec3 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec3, req3)
|
||
if rec3.Code != 200 {
|
||
t.Fatalf("delete status=%d body=%s", rec3.Code, rec3.Body.String())
|
||
}
|
||
}
|
||
|
||
// TestHealth 健康检查无需认证。
|
||
func TestHealth(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
|
||
req := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("health status=%d", rec.Code)
|
||
}
|
||
}
|
||
|
||
func TestHealthReportsUnavailableDatabase(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
if err := store.DB.Close(); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
h := srv.Router()
|
||
req := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusServiceUnavailable {
|
||
t.Fatalf("health status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var response map[string]any
|
||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if response["status"] != "degraded" || response["database"] != "unavailable" {
|
||
t.Fatalf("health response=%+v", response)
|
||
}
|
||
}
|