修复登录续期与数据库验证回归

- 修复密码登录、续期和账号编辑链路的边界问题
- 补齐 dbverify、后端与前端单测
- 同步 Docker 与前端构建产物
This commit is contained in:
Christ committed 2026-07-09 16:08:16 +08:00
1 parent 3436acecdc
commit 25419c027f
87 files changed
+7485 -900

No files matched your search

+23 -11
View File
@@ -96,9 +96,12 @@ func (s *Server) listCookieDetails(w http.ResponseWriter, r *http.Request) {
"auto_confirm": d.AutoConfirm,
"remark": d.Remark,
"pause_duration": d.PauseDuration,
"show_browser": d.ShowBrowser,
"username": d.Username,
"nickname": cachedAccountNickname(d),
"avatar_url": d.AvatarURL,
"login_method": d.LoginMethod,
"last_login_at": d.LastLoginAt,
"profile_error": "",
"ai_enabled": false,
})
@@ -130,6 +133,8 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
"username": d.Username,
"nickname": cachedAccountNickname(d),
"avatar_url": d.AvatarURL,
"login_method": d.LoginMethod,
"last_login_at": d.LastLoginAt,
"profile_error": "",
"has_cookie": true,
})
@@ -162,8 +167,9 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
// addCookie 添加账号 cookie。
func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
var req struct {
ID string `json:"id"`
Value string `json:"value"`
ID string `json:"id"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil || req.ID == "" || req.Value == "" {
writeErr(w, http.StatusBadRequest, "缺少 id 或 value")
@@ -181,6 +187,11 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
loginMethod := normalizeLoginMethod(req.LoginMethod)
if loginMethod == "" {
loginMethod = loginMethodManual
}
s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功")
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
@@ -196,7 +207,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
Value string `json:"value"`
Value string `json:"value"`
LoginMethod string `json:"login_method"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
@@ -214,6 +226,9 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
if loginMethod := normalizeLoginMethod(req.LoginMethod); loginMethod != "" {
s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功")
}
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
@@ -225,7 +240,8 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
detail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
var req struct {
@@ -242,14 +258,10 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
if password == "" {
password = req.LoginPassword
}
sb := 0
if req.ShowBrowser {
sb = 1
if password == "" && detail != nil {
password = detail.Password
}
_, err := s.Store.DB.ExecContext(r.Context(),
`UPDATE cookies SET username=?, password=?, show_browser=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`,
req.Username, password, sb, cid)
if err != nil {
if err := s.Store.Cookies.UpdateLoginInfo(r.Context(), cid, req.Username, password, req.ShowBrowser); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
+133 -6
View File
@@ -93,6 +93,35 @@ func TestGetCookieDetails(t *testing.T) {
}
}
func TestListCookieDetailsIncludesShowBrowser(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Cookies.UpdateLoginInfo(ctx, "acc1", "login-user", "secret", true); err != nil {
t.Fatalf("UpdateLoginInfo: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodGet, "/cookies/details", 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 details []map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &details); err != nil {
t.Fatalf("decode details: %v", err)
}
if len(details) != 1 || details[0]["show_browser"] != true {
t.Fatalf("账号列表应返回 show_browser=true: %+v", details)
}
if _, ok := details[0]["login_password"]; ok {
t.Fatalf("账号列表不应返回登录密码: %+v", details[0])
}
}
// TestGetCookieDetailsBadCookie 无权账号 403。
func TestGetCookieDetailsBadCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -111,8 +140,9 @@ func TestGetCookieDetailsBadCookie(t *testing.T) {
// TestUpdateCookie 更新 cookie 值。
func TestUpdateCookie(t *testing.T) {
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
@@ -124,6 +154,50 @@ func TestUpdateCookie(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "" || d.LastLoginAt != 0 {
t.Fatalf("普通 Cookie 更新不应刷新登录审计字段: method=%q last=%d", d.LoginMethod, d.LastLoginAt)
}
}
func TestUpdateCookieQRLoginEnablesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"value":"unb=123; _m_h5_tk=qr_2;","login_method":"qr_scan"}`
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
}
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码登录成功后应重新启用账号")
}
var reason string
if err := store.DB.QueryRowContext(ctx, `SELECT disable_reason FROM cookie_status WHERE cookie_id='acc1'`).Scan(&reason); err != nil {
t.Fatalf("query disable_reason: %v", err)
}
if reason != "" {
t.Fatalf("扫码登录成功后应清空禁用原因,got %q", reason)
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应刷新登录审计字段: %+v", d)
}
}
// TestUpdateCookieBadJSON 非法 JSON 400。
@@ -144,8 +218,9 @@ func TestUpdateCookieBadJSON(t *testing.T) {
// TestUpdateCookieLoginInfo 更新登录信息。
func TestUpdateCookieLoginInfo(t *testing.T) {
srv, _, cleanup := newTestServer(t)
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
@@ -157,6 +232,29 @@ func TestUpdateCookieLoginInfo(t *testing.T) {
if rec.Code != 200 {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.Username != "u1" || d.Password != "p1" || !d.ShowBrowser {
t.Fatalf("登录信息未正确保存: %+v", d)
}
body = `{"username":"u2","login_password":"","show_browser":false}`
req = httptest.NewRequest(http.MethodPut, "/cookies/acc1/login-info", strings.NewReader(body))
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())
}
d, err = store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatalf("GetDetails after empty password: %v", err)
}
if d.Username != "u2" || d.Password != "p1" || d.ShowBrowser {
t.Fatalf("空密码更新应保留原密码并更新其他字段: %+v", d)
}
}
// TestUpdateCookieLoginInfoBadJSON 非法 JSON 400。
@@ -295,6 +393,35 @@ func TestAddCookieBad(t *testing.T) {
}
}
func TestAddCookieDefaultsManualLoginAudit(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
ctx := context.Background()
h := srv.Router()
cookie := loginHelper(t, h)
body := `{"id":"acc-manual","value":"unb=456; _m_h5_tk=manual_1;"}`
req := httptest.NewRequest(http.MethodPost, "/cookies", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("add status=%d body=%s", rec.Code, rec.Body.String())
}
d, err := store.Cookies.GetDetails(ctx, "acc-manual")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.LoginMethod != "manual" || d.LastLoginAt == 0 {
t.Fatalf("手动新增 Cookie 应记录 manual 登录审计字段: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(ctx, "acc-manual", 10)
if err != nil || len(logs) != 1 || logs[0].Method != "manual" || logs[0].TriggerReason != "手动Cookie录入" {
t.Fatalf("手动新增 Cookie 应记录登录日志: logs=%#v err=%v", logs, err)
}
}
// TestAddCookieBadJSON 非法 JSON 400。
func TestAddCookieBadJSON(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -347,10 +474,10 @@ func TestCachedAccountNickname(t *testing.T) {
// TestNormalizeProfileAvatarURL 头像 URL 归一。
func TestNormalizeProfileAvatarURL(t *testing.T) {
cases := map[string]string{
"": "",
"//img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"http://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"https://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"": "",
"//img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"http://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
"https://img.alicdn.com/x.jpg": "https://img.alicdn.com/x.jpg",
" https://img.alicdn.com/x.jpg ": "https://img.alicdn.com/x.jpg",
}
for in, want := range cases {
+116 -17
View File
@@ -273,7 +273,9 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
go func() {
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
s.registerPublishBatchCancel(batch.ID, cancel)
defer cancel()
defer s.unregisterPublishBatchCancel(batch.ID)
s.runItemPublishBatch(jobCtx, sess.UserID, batch.ID, false)
}()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batch.ID})
@@ -306,6 +308,9 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusInternalServerError, "取消任务失败")
return
}
s.cancelPublishBatch(batchID)
_ = s.Store.PublishBatches.MarkUnfinishedFailed(r.Context(), batchID, "任务已取消")
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
@@ -328,7 +333,9 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
// #nosec G118 -- 批处理必须在请求结束后继续,并由 30 分钟超时保证退出。
go func() {
jobCtx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
s.registerPublishBatchCancel(batchID, cancel)
defer cancel()
defer s.unregisterPublishBatchCancel(batchID)
s.runItemPublishBatch(jobCtx, sess.UserID, batchID, false)
}()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batchID})
@@ -374,36 +381,122 @@ func (s *Server) runItemPublishBatch(ctx context.Context, userID int64, batchID
}
client := s.mtopClient()
for idx, row := range rows {
status, err := s.Store.PublishBatches.BatchStatus(ctx, batchID)
if err != nil || status == "canceled" {
_ = s.Store.PublishBatches.Recount(ctx, batchID)
if ctx.Err() != nil {
s.finishInterruptedPublishBatch(ctx, userID, batchID)
return
}
_ = s.Store.PublishBatches.MarkRowRunning(ctx, row.ID)
if err := s.publishBatchRow(ctx, userID, client, row); err != nil {
_ = s.Store.PublishBatches.MarkRowFailed(ctx, row.ID, err.Error())
wctx, cancel := publishStatusContext(ctx)
status, err := s.Store.PublishBatches.BatchStatus(wctx, batchID)
cancel()
if err != nil || status == "canceled" {
wctx, cancel := publishStatusContext(ctx)
if status == "canceled" {
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务已取消")
}
_ = s.Store.PublishBatches.Recount(wctx, batchID)
cancel()
return
}
_ = s.Store.PublishBatches.Recount(ctx, batchID)
wctx, cancel = publishStatusContext(ctx)
_ = s.Store.PublishBatches.MarkRowRunning(wctx, row.ID)
cancel()
if err := s.publishBatchRow(ctx, userID, client, row); err != nil {
message := err.Error()
if status, _ := s.Store.PublishBatches.BatchStatus(context.Background(), batchID); status == "canceled" {
message = "任务已取消"
}
wctx, cancel := publishStatusContext(ctx)
_ = s.Store.PublishBatches.MarkRowFailed(wctx, row.ID, message)
cancel()
}
wctx, cancel = publishStatusContext(ctx)
_ = s.Store.PublishBatches.Recount(wctx, batchID)
cancel()
if idx < len(rows)-1 {
delay := time.Duration(10+idx%21) * time.Second
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
s.finishInterruptedPublishBatch(ctx, userID, batchID)
return
case <-timer.C:
}
}
}
_ = s.Store.PublishBatches.Recount(ctx, batchID)
batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID)
if err == nil && batch.Status != "canceled" {
finalStatus := "completed"
if batch.SuccessCount == 0 && batch.FailedCount > 0 {
finalStatus = "failed"
}
_ = s.Store.PublishBatches.SetBatchStatus(ctx, batchID, finalStatus)
s.finishPublishBatch(ctx, userID, batchID)
}
func (s *Server) registerPublishBatchCancel(batchID string, cancel context.CancelFunc) {
s.publishMu.Lock()
defer s.publishMu.Unlock()
if s.publishCancels == nil {
s.publishCancels = make(map[string]context.CancelFunc)
}
if old := s.publishCancels[batchID]; old != nil {
old()
}
s.publishCancels[batchID] = cancel
}
func (s *Server) unregisterPublishBatchCancel(batchID string) {
s.publishMu.Lock()
defer s.publishMu.Unlock()
delete(s.publishCancels, batchID)
}
func (s *Server) cancelPublishBatch(batchID string) {
s.publishMu.Lock()
cancel := s.publishCancels[batchID]
s.publishMu.Unlock()
if cancel != nil {
cancel()
}
}
func publishStatusContext(parent context.Context) (context.Context, context.CancelFunc) {
if parent != nil && parent.Err() == nil {
return context.WithTimeout(parent, 5*time.Second)
}
return context.WithTimeout(context.Background(), 5*time.Second)
}
func (s *Server) finishInterruptedPublishBatch(ctx context.Context, userID int64, batchID string) {
wctx, cancel := publishStatusContext(ctx)
defer cancel()
if status, _ := s.Store.PublishBatches.BatchStatus(wctx, batchID); status == "canceled" {
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务已取消")
_ = s.Store.PublishBatches.Recount(wctx, batchID)
return
}
_ = s.Store.PublishBatches.MarkUnfinishedFailed(wctx, batchID, "任务超时或已中断")
_ = s.Store.PublishBatches.Recount(wctx, batchID)
s.finishPublishBatch(wctx, userID, batchID)
}
func (s *Server) finishPublishBatch(ctx context.Context, userID int64, batchID string) {
wctx, cancel := publishStatusContext(ctx)
defer cancel()
_ = s.Store.PublishBatches.Recount(wctx, batchID)
batch, err := s.Store.PublishBatches.Get(wctx, userID, batchID)
if err != nil || batch.Status == "canceled" {
return
}
finalStatus := finalPublishBatchStatus(batch)
_ = s.Store.PublishBatches.SetBatchStatus(wctx, batchID, finalStatus)
}
func finalPublishBatchStatus(batch *db.ItemPublishBatch) string {
if batch == nil {
return "failed"
}
if batch.FailedCount > 0 {
if batch.SuccessCount > 0 {
return "partially_failed"
}
return "failed"
}
return "completed"
}
func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.Client, row db.ItemPublishBatchRow) error {
@@ -444,6 +537,12 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
}
return err
}
if ctx.Err() != nil {
return ctx.Err()
}
if status, _ := s.Store.PublishBatches.BatchStatus(ctx, row.BatchID); status == "canceled" {
return context.Canceled
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.Save(ctx, row.CookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("发布商品后保存刷新 cookie 失败", "cookie_id", row.CookieID, "err", err)
@@ -762,9 +861,9 @@ func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID
}
func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool {
var exists int
var exists bool
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
return err == nil && exists != 0
return err == nil && exists
}
func (s *Server) publishUploadRoot() string {
+39 -4
View File
@@ -6,6 +6,7 @@ import (
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountKeywordsReal 关键字端点。
@@ -98,11 +99,45 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
return
}
var req struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Keywords *[]struct {
Keyword string `json:"keyword"`
Reply string `json:"reply"`
ItemID string `json:"item_id"`
Type string `json:"type"`
ImageURL string `json:"image_url"`
} `json:"keywords"`
}
if err := decodeJSON(r, &req); err != nil || req.Keyword == "" {
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if req.Keywords != nil {
rows := make([]db.KeywordRow, 0, len(*req.Keywords))
for _, item := range *req.Keywords {
if item.Keyword == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
rows = append(rows, db.KeywordRow{
CookieID: cid,
Keyword: item.Keyword,
Reply: item.Reply,
ItemID: item.ItemID,
Type: item.Type,
ImageURL: item.ImageURL,
})
}
if err := s.Store.Keywords.ReplaceForCookie(r.Context(), cid, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
return
}
if req.Keyword == "" {
writeErr(w, http.StatusBadRequest, "keyword 必填")
return
}
+87
View File
@@ -0,0 +1,87 @@
package server
import (
"context"
"strings"
"time"
"xianyu-go/internal/db"
)
const (
loginMethodManual = "manual"
loginMethodPassword = "password"
loginMethodQRScan = "qr_scan"
loginStatusSuccess = "success"
loginStatusFailed = "failed"
)
func normalizeLoginMethod(method string) string {
switch strings.ToLower(strings.TrimSpace(method)) {
case "manual", "cookie", "manual_cookie":
return loginMethodManual
case "password", "password_login":
return loginMethodPassword
case "qr", "qr_login", "qr_scan":
return loginMethodQRScan
default:
return strings.ToLower(strings.TrimSpace(method))
}
}
func (s *Server) markSuccessfulLogin(ctx context.Context, cookieID string, userID int64, method, message string) {
method = normalizeLoginMethod(method)
if method == "" {
return
}
at := time.Now().Unix()
if err := s.Store.Cookies.MarkLogin(ctx, cookieID, method, at); err != nil {
if s.Logger != nil {
s.Logger.Warn("记录账号登录方式失败", "cookie_id", cookieID, "method", method, "err", err)
}
return
}
if method == loginMethodPassword || method == loginMethodQRScan {
if err := s.Store.Cookies.SetStatusWithReason(ctx, cookieID, true, ""); err != nil && s.Logger != nil {
s.Logger.Warn("成功登录后启用账号失败", "cookie_id", cookieID, "method", method, "err", err)
}
}
s.addLoginLog(ctx, cookieID, userID, method, loginStatusSuccess, "", message, at)
}
func (s *Server) addLoginLog(ctx context.Context, cookieID string, userID int64, method, status, failureReason, message string, at int64) {
if s.Store == nil || s.Store.LoginLogs == nil {
return
}
if at == 0 {
at = time.Now().Unix()
}
if err := s.Store.LoginLogs.Add(ctx, db.AccountLoginLog{
CookieID: cookieID,
UserID: userID,
OwnerID: userID,
AccountIdentifier: cookieID,
Method: normalizeLoginMethod(method),
Status: status,
Message: truncate(message, 500),
TriggerReason: loginTriggerReason(method),
FailureReason: failureReason,
ErrorMessage: truncate(message, 500),
CreatedAt: at,
}); err != nil && s.Logger != nil {
s.Logger.Warn("记录账号登录日志失败", "cookie_id", cookieID, "method", method, "status", status, "err", err)
}
}
func loginTriggerReason(method string) string {
switch normalizeLoginMethod(method) {
case loginMethodManual:
return "手动Cookie录入"
case loginMethodPassword:
return "账号密码登录"
case loginMethodQRScan:
return "扫码登录"
default:
return ""
}
}
+2 -2
View File
@@ -71,11 +71,11 @@ func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, cha
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
var exists int
var exists bool
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
channelID, sess.UserID).Scan(&exists)
if err != nil || exists == 0 {
if err != nil || !exists {
writeErr(w, http.StatusForbidden, "无权操作该通知渠道")
return false
}
+429
View File
@@ -0,0 +1,429 @@
package server
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"net/http"
"strings"
"time"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
)
type passwordLoginRunner interface {
PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
}
type passwordLoginEventRunner interface {
PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error)
}
const (
passwordLoginSessionMaxAge = time.Hour
passwordLoginProcessingTimeout = 5 * time.Minute
passwordLoginBaxiaPunishReason = "baxia_punish_captcha"
passwordLoginBaxiaPunishCooldown = 5
)
type passwordLoginSession struct {
ID string
AccountID string
Account string
UserID int64
Status string
Message string
Error string
Reason string
VerificationURL string
ScreenshotPath string
QRCodeURL string
CooldownHours int
IsNewAccount bool
CookieCount int
ShowBrowser bool
CreatedAt time.Time
cancel context.CancelFunc
}
func (s *Server) mountPasswordLogin(r chi.Router) {
r.Post("/password-login", s.startPasswordLogin)
r.Get("/password-login/check/{session_id}", s.checkPasswordLogin)
r.Delete("/password-login/cancel/{session_id}", s.cancelPasswordLogin)
}
func (s *Server) startPasswordLogin(w http.ResponseWriter, r *http.Request) {
var req struct {
AccountID string `json:"account_id"`
CookieID string `json:"cookie_id"`
Account string `json:"account"`
Username string `json:"username"`
Password string `json:"password"`
ShowBrowser bool `json:"show_browser"`
}
if err := decodeJSON(r, &req); err != nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "请求格式错误"})
return
}
accountID := firstNonEmpty(req.AccountID, req.CookieID)
account := firstNonEmpty(req.Account, req.Username)
accountID = strings.TrimSpace(accountID)
account = strings.TrimSpace(account)
if accountID == "" || account == "" || req.Password == "" {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "账号ID、登录账号和密码不能为空"})
return
}
if s.PasswordLogin == nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "浏览器登录服务不可用"})
return
}
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
if ok, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID); !ok {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": message})
return
}
s.cleanupExpiredPasswordLoginSessions()
if sid := s.currentPasswordLoginSession(accountID); sid != "" {
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"session_id": sid,
"status": "processing",
"message": "账号正在处理中,请稍候...",
})
return
}
sessionID, err := newPasswordSessionID()
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "创建登录会话失败"})
return
}
ctx, cancel := context.WithCancel(context.Background())
loginSession := &passwordLoginSession{
ID: sessionID,
AccountID: accountID,
Account: account,
UserID: sess.UserID,
Status: "processing",
Message: "登录处理中,请稍候...",
ShowBrowser: req.ShowBrowser,
CreatedAt: time.Now(),
cancel: cancel,
}
s.passwordMu.Lock()
s.passwordSessions[sessionID] = loginSession
s.passwordProcessing[accountID] = sessionID
s.passwordMu.Unlock()
go s.runPasswordLoginSession(ctx, loginSession, req.Password)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"session_id": sessionID,
"status": "processing",
"message": "登录任务已启动,请等待...",
})
}
func (s *Server) checkPasswordLogin(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
s.cleanupExpiredPasswordLoginSessions()
s.passwordMu.Lock()
session, ok := s.passwordSessions[sessionID]
if !ok {
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"status": "not_found", "message": "会话不存在或已过期"})
return
}
response := passwordSessionResponse(session)
if session.Status == "success" || session.Status == "failed" {
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
}
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, response)
}
func (s *Server) cancelPasswordLogin(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
s.passwordMu.Lock()
session, ok := s.passwordSessions[sessionID]
if !ok {
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"success": false, "code": 404, "message": "会话不存在", "data": nil})
return
}
if session.cancel != nil {
session.cancel()
}
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"success": true, "code": 200, "message": "登录会话已取消", "data": nil})
}
func (s *Server) runPasswordLoginSession(ctx context.Context, session *passwordLoginSession, password string) {
var (
cookies map[string]string
err error
)
headless := !session.ShowBrowser
if runner, ok := s.PasswordLogin.(passwordLoginEventRunner); ok {
cookies, err = runner.PasswordLoginWithEvents(ctx, session.Account, password, session.AccountID, "", headless, func(event browser.PasswordLoginEvent) {
s.applyPasswordLoginEvent(session, event)
})
} else {
cookies, err = s.PasswordLogin.PasswordLogin(ctx, session.Account, password, session.AccountID, "", headless)
}
if err != nil {
event := browser.PasswordLoginEventFromError(err)
status := event.Status
if status == "" {
status = "failed"
}
reason := passwordLoginReason(err)
s.failPasswordLoginSession(session, status, err.Error(), reason, event.CooldownHours)
s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, reason, err.Error(), 0)
return
}
accountID, isNew, err := s.savePasswordLoginCookies(ctx, session, password, cookies)
if err != nil {
s.failPasswordLoginSession(session, "failed", "保存登录结果失败: "+err.Error(), "", 0)
s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, "cookie_update_failed", err.Error(), 0)
return
}
s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
current.Status = "success"
current.Message = "账号 " + accountID + " 登录成功"
current.AccountID = accountID
current.IsNewAccount = isNew
current.CookieCount = len(cookies)
})
}
func (s *Server) savePasswordLoginCookies(ctx context.Context, session *passwordLoginSession, password string, cookies map[string]string) (string, bool, error) {
if len(cookies) == 0 {
return "", false, errors.New("浏览器未返回 cookie")
}
accountID := cookieAccountID(cookies, session.AccountID)
cookieValue := browser.MarshalCookies(cookies)
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return "", false, err
}
if err := s.Store.Cookies.Save(ctx, accountID, cookieValue, session.UserID); err != nil {
return "", false, err
}
if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
return "", false, err
}
s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
s.Logger.Warn("密码登录后重启账号失败", "cookie_id", accountID, "err", err)
}
}
return accountID, isNew, nil
}
func (s *Server) canStartPasswordLogin(ctx context.Context, userID int64, accountID string) (bool, string) {
d, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err == nil {
if d.UserID != userID {
return false, "无权限操作该账号"
}
if !s.Store.Cookies.GetStatus(ctx, accountID) {
return false, "账号已禁用,请先在账号管理中启用"
}
return true, ""
}
if errors.Is(err, db.ErrNotFound) {
return true, ""
}
return false, "查询账号失败"
}
func (s *Server) currentPasswordLoginSession(accountID string) string {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
return s.passwordProcessing[accountID]
}
func (s *Server) completePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
s.finishPasswordLoginSession(session, mutate)
}
func (s *Server) updatePasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) bool {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
current, ok := s.passwordSessions[session.ID]
if !ok || current != session {
return false
}
mutate(current)
return true
}
func (s *Server) finishPasswordLoginSession(session *passwordLoginSession, mutate func(*passwordLoginSession)) {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
current, ok := s.passwordSessions[session.ID]
if !ok || current != session {
return
}
originalAccountID := current.AccountID
mutate(current)
delete(s.passwordProcessing, originalAccountID)
delete(s.passwordProcessing, current.AccountID)
}
func (s *Server) applyPasswordLoginEvent(session *passwordLoginSession, event browser.PasswordLoginEvent) {
if event.Status == "" {
return
}
apply := func(current *passwordLoginSession) {
current.Status = event.Status
current.Message = firstNonEmpty(event.Message, current.Message)
current.Error = firstNonEmpty(event.Error, current.Error)
current.Reason = firstNonEmpty(event.Reason, current.Reason)
current.VerificationURL = firstNonEmpty(event.VerificationURL, current.VerificationURL)
current.ScreenshotPath = firstNonEmpty(event.ScreenshotPath, current.ScreenshotPath)
current.QRCodeURL = firstNonEmpty(event.QRCodeURL, current.QRCodeURL)
if event.CooldownHours > 0 {
current.CooldownHours = event.CooldownHours
}
}
if passwordLoginEventIsTerminal(event.Status) {
s.finishPasswordLoginSession(session, apply)
return
}
s.updatePasswordLoginSession(session, apply)
}
func (s *Server) failPasswordLoginSession(session *passwordLoginSession, status, message, reason string, cooldownHours int) {
s.completePasswordLoginSession(session, func(current *passwordLoginSession) {
current.Status = status
current.Message = message
current.Error = message
current.Reason = reason
current.CooldownHours = cooldownHours
})
}
func passwordLoginEventIsTerminal(status string) bool {
return status == "success" || status == browser.PasswordLoginStatusFailed
}
func (s *Server) cleanupExpiredPasswordLoginSessions() {
now := time.Now()
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
for sessionID, session := range s.passwordSessions {
age := now.Sub(session.CreatedAt)
if session.Status == "processing" && age > passwordLoginProcessingTimeout {
if session.cancel != nil {
session.cancel()
}
session.Status = "failed"
session.Message = "登录处理超时,请稍后重试"
session.Error = session.Message
delete(s.passwordProcessing, session.AccountID)
}
if age <= passwordLoginSessionMaxAge {
continue
}
if session.cancel != nil {
session.cancel()
}
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, session.AccountID)
}
}
func passwordSessionResponse(session *passwordLoginSession) map[string]any {
resp := map[string]any{
"status": session.Status,
"message": session.Message,
}
if session.Status == "success" {
resp["account_id"] = session.AccountID
resp["is_new_account"] = session.IsNewAccount
resp["cookie_count"] = session.CookieCount
}
if session.Status == "failed" {
resp["error"] = session.Error
if session.Reason != "" {
resp["reason"] = session.Reason
}
if session.CooldownHours > 0 {
resp["cooldown_hours"] = session.CooldownHours
}
}
if session.Status == "verification_required" {
resp["verification_url"] = session.VerificationURL
resp["screenshot_path"] = session.ScreenshotPath
resp["qr_code_url"] = session.QRCodeURL
resp["error"] = session.Error
if session.CooldownHours > 0 {
resp["cooldown_hours"] = session.CooldownHours
}
}
return resp
}
func newPasswordSessionID() (string, error) {
var b [18]byte
if _, err := rand.Read(b[:]); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b[:]), nil
}
func cookieAccountID(cookies map[string]string, fallback string) string {
for k, v := range cookies {
if strings.EqualFold(strings.TrimSpace(k), "unb") && strings.TrimSpace(v) != "" {
return strings.TrimSpace(v)
}
}
return fallback
}
func loginStatusForPasswordError(err error) string {
return browser.PasswordLoginEventFromError(err).Status
}
func passwordLoginReason(err error) string {
if err == nil {
return ""
}
msg := err.Error()
if strings.Contains(msg, "账密错误") || strings.Contains(msg, "账号密码错误") ||
strings.Contains(msg, "用户名或密码错误") || strings.Contains(msg, "密码错误") {
return "bad_credentials"
}
event := browser.PasswordLoginEventFromError(err)
if event.Reason != "" {
return event.Reason
}
if event.Status == browser.PasswordLoginStatusVerificationRequired {
return "verification_required"
}
return "other"
}
@@ -0,0 +1,384 @@
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
)
type fakePasswordLoginRunner struct {
mu sync.Mutex
cookies map[string]string
err error
block chan struct{}
events []browser.PasswordLoginEvent
calls int
lastAccount string
lastHeadless bool
}
func (f *fakePasswordLoginRunner) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
f.mu.Lock()
f.calls++
f.lastAccount = account
f.lastHeadless = headless
f.mu.Unlock()
if f.block != nil {
select {
case <-f.block:
case <-ctx.Done():
return nil, ctx.Err()
}
}
return f.cookies, f.err
}
func (f *fakePasswordLoginRunner) PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent browser.PasswordLoginEventHandler) (map[string]string, error) {
for _, event := range f.events {
onEvent(event)
}
return f.PasswordLogin(ctx, account, password, cookieID, userDataDir, headless)
}
func (f *fakePasswordLoginRunner) snapshot() (int, string, bool) {
f.mu.Lock()
defer f.mu.Unlock()
return f.calls, f.lastAccount, f.lastHeadless
}
func loginForPasswordTest(t *testing.T, h http.Handler) *http.Cookie {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(`{"username":"admin","password":"pw"}`))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || len(rec.Result().Cookies()) == 0 {
t.Fatalf("login status=%d body=%s", rec.Code, rec.Body.String())
}
return rec.Result().Cookies()[0]
}
func startPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, body string) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", rec.Code, rec.Body.String())
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("decode start: %v body=%s", err, rec.Body.String())
}
return out
}
func checkPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) map[string]any {
t.Helper()
req := httptest.NewRequest(http.MethodGet, "/password-login/check/"+sessionID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("check status=%d body=%s", rec.Code, rec.Body.String())
}
var out map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("decode check: %v body=%s", err, rec.Body.String())
}
return out
}
func cancelPasswordLoginForTest(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID string) {
t.Helper()
req := httptest.NewRequest(http.MethodDelete, "/password-login/cancel/"+sessionID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", rec.Code, rec.Body.String())
}
}
func waitPasswordLoginStatus(t *testing.T, h http.Handler, cookie *http.Cookie, sessionID, want string) map[string]any {
t.Helper()
var out map[string]any
for i := 0; i < 50; i++ {
out = checkPasswordLoginForTest(t, h, cookie, sessionID)
if out["status"] == want {
return out
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("status did not reach %q, last=%+v", want, out)
return nil
}
func waitLoginLogCount(t *testing.T, store *db.Store, cookieID string, want int) []db.AccountLoginLog {
t.Helper()
var logs []db.AccountLoginLog
var err error
for i := 0; i < 50; i++ {
logs, err = store.LoginLogs.ListByCookie(context.Background(), cookieID, 10)
if err == nil && len(logs) >= want {
return logs
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("login logs did not reach %d: logs=%#v err=%v", want, logs, err)
return nil
}
func TestPasswordLoginSessionSuccessSavesCookiesAndAudit(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
if err := store.Tokens.Save(context.Background(), "acc1", "did", "token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":false}`)
if start["success"] != true || start["status"] != "processing" {
t.Fatalf("start response=%+v", start)
}
sessionID, _ := start["session_id"].(string)
if sessionID == "" {
t.Fatalf("missing session_id: %+v", start)
}
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
if done["account_id"] != "acc1" || done["is_new_account"] != false {
t.Fatalf("success response=%+v", done)
}
calls, account, headless := fake.snapshot()
if calls != 1 || account != "login-user" || !headless {
t.Fatalf("PasswordLogin 调用异常: calls=%d account=%q headless=%v", calls, account, headless)
}
saved, _ := store.Cookies.GetValue(context.Background(), "acc1")
if !strings.Contains(saved, "_m_h5_tk=fresh") {
t.Fatalf("cookie 未保存: %q", saved)
}
d, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if d.Username != "login-user" || d.Password != "secret" || d.ShowBrowser || d.LoginMethod != "password" || d.LastLoginAt == 0 {
t.Fatalf("登录信息/审计字段异常: %+v", d)
}
if _, err := store.Tokens.Get(context.Background(), "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("密码登录成功应清 token,got %v", err)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
t.Fatalf("登录日志异常: logs=%#v err=%v", logs, err)
}
}
func TestPasswordLoginUnavailableWhenBrowserManagerNil(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if start["success"] != false || start["message"] != "浏览器登录服务不可用" {
t.Fatalf("nil 浏览器应返回不可用且不启动登录: %+v", start)
}
}
func TestPasswordLoginSessionShowBrowserRunsVisibleAndSavesPreference(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":true}`)
sessionID, _ := start["session_id"].(string)
if sessionID == "" {
t.Fatalf("missing session_id: %+v", start)
}
waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
calls, account, headless := fake.snapshot()
if calls != 1 || account != "login-user" || headless {
t.Fatalf("show_browser=true 应使用可视浏览器: calls=%d account=%q headless=%v", calls, account, headless)
}
d, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatalf("GetDetails: %v", err)
}
if !d.ShowBrowser {
t.Fatalf("show_browser=true 应按原请求落库: %+v", d)
}
}
func TestPasswordLoginDuplicateStartReturnsProcessingSession(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if first["session_id"] == "" || second["session_id"] != first["session_id"] || second["status"] != "processing" {
t.Fatalf("重复启动应返回同一 processing 会话: first=%+v second=%+v", first, second)
}
cancelPasswordLoginForTest(t, h, cookie, first["session_id"].(string))
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginVerificationRequiredKeepsProcessingLock(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{
block: make(chan struct{}),
events: []browser.PasswordLoginEvent{{
Status: browser.PasswordLoginStatusVerificationRequired,
Message: "需要人脸验证,请查看验证截图",
Error: "需要人脸验证",
ScreenshotPath: "/tmp/face.png",
}},
cookies: map[string]string{"unb": "acc1"},
}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := first["session_id"].(string)
waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if second["session_id"] != sessionID {
t.Fatalf("验证码等待期间应继续复用同一会话: first=%+v second=%+v", first, second)
}
if calls, _, _ := fake.snapshot(); calls != 1 {
t.Fatalf("验证码等待期间不应启动第二个浏览器任务,calls=%d", calls)
}
cancelPasswordLoginForTest(t, h, cookie, sessionID)
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginProcessingTimeoutReleasesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
first := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := first["session_id"].(string)
srv.passwordMu.Lock()
srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginProcessingTimeout + time.Second))
srv.passwordMu.Unlock()
second := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
if second["session_id"] == "" || second["session_id"] == sessionID {
t.Fatalf("processing 超时后应创建新会话: first=%+v second=%+v", first, second)
}
oldStatus := checkPasswordLoginForTest(t, h, cookie, sessionID)
if oldStatus["status"] != "failed" {
t.Fatalf("超时旧会话应标记 failed: %+v", oldStatus)
}
cancelPasswordLoginForTest(t, h, cookie, second["session_id"].(string))
waitLoginLogCount(t, store, "acc1", 2)
}
func TestPasswordLoginSessionExpiresAfterOneHour(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
srv.passwordMu.Lock()
srv.passwordSessions[sessionID].CreatedAt = time.Now().Add(-(passwordLoginSessionMaxAge + time.Second))
srv.passwordMu.Unlock()
done := checkPasswordLoginForTest(t, h, cookie, sessionID)
if done["status"] != "not_found" {
t.Fatalf("1小时后会话应过期: %+v", done)
}
waitLoginLogCount(t, store, "acc1", 1)
}
func TestPasswordLoginVerificationRequired(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{
events: []browser.PasswordLoginEvent{{
Status: browser.PasswordLoginStatusVerificationRequired,
Message: "需要人脸验证,请查看验证截图",
Error: "需要人脸验证",
ScreenshotPath: "/tmp/face.png",
}},
err: errors.New("需要人脸验证"),
}
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "verification_required")
if done["error"] == "" {
t.Fatalf("verification_required 应带 error: %+v", done)
}
if done["screenshot_path"] != "/tmp/face.png" {
t.Fatalf("verification_required 应带截图: %+v", done)
}
again := checkPasswordLoginForTest(t, h, cookie, sessionID)
if again["status"] != "verification_required" {
t.Fatalf("验证态会话应保留: %+v", again)
}
logs := waitLoginLogCount(t, store, "acc1", 1)
if logs[0].FailureReason != "verification_required" {
t.Fatalf("验证态应记录 failure_reason: %#v", logs)
}
}
func TestPasswordLoginBaxiaReason(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{err: errors.New("baxia-punish 风控图形验证")}
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID := start["session_id"].(string)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "failed")
if done["reason"] != "baxia_punish_captcha" || done["cooldown_hours"] != float64(5) {
t.Fatalf("baxia 错误应带 reason/cooldown: %+v", done)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
t.Fatalf("baxia 错误应记录专用 failure_reason: logs=%#v err=%v", logs, err)
}
}
+157 -6
View File
@@ -20,6 +20,25 @@ import (
// minimalPNG 是一张 1x1 PNG,供发布批次图片 zip 复用。
var minimalPNG = []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82}
func TestFinalPublishBatchStatus(t *testing.T) {
cases := []struct {
name string
in db.ItemPublishBatch
want string
}{
{name: "completed", in: db.ItemPublishBatch{SuccessCount: 2}, want: "completed"},
{name: "failed", in: db.ItemPublishBatch{FailedCount: 2}, want: "failed"},
{name: "partially failed", in: db.ItemPublishBatch{SuccessCount: 1, FailedCount: 1}, want: "partially_failed"},
}
for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
if got := finalPublishBatchStatus(&tt.in); got != tt.want {
t.Fatalf("got %q want %q", got, tt.want)
}
})
}
}
// buildImageZip 构造含一张图片的 zip 字节流。
func buildImageZip(t *testing.T) []byte {
t.Helper()
@@ -59,6 +78,33 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
return res["preview_id"].(string)
}
func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) string {
t.Helper()
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
_ = mw.WriteField("default_cookie_id", "acc1")
csvField, _ := mw.CreateFormFile("file", "products.csv")
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
zipField.Write(buildImageZip(t))
_ = mw.Close()
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
req.Header.Set("Content-Type", mw.FormDataContentType())
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("preview status=%d body=%s", rec.Code, rec.Body.String())
}
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["valid"].(float64) != 2 {
t.Fatalf("预检应 2 行有效,got %+v", res)
}
return res["preview_id"].(string)
}
// TestRunItemPublishBatch_FailureMarksRowFailed 启动批次后,mock mtop 对发布请求返回失败,
// 验证 runItemPublishBatch/publishBatchRow 把行标记为 failed。
func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
@@ -118,8 +164,83 @@ func TestRunItemPublishBatch_FailureMarksRowFailed(t *testing.T) {
h.ServeHTTP(rec, req)
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] == nil {
t.Fatalf("批次详情异常: %+v", got)
if got["status"] != "failed" {
t.Fatalf("status=%v want failed body=%+v", got["status"], got)
}
if got["failed"] != float64(1) {
t.Fatalf("failed=%v want 1 body=%+v", got["failed"], got)
}
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
row, _ := rows[0].(map[string]any)
if row["status"] != "failed" || row["error_message"] == "" {
t.Fatalf("row should be failed with error message: %+v", row)
}
}
func TestCancelItemPublishBatchMarksUnfinishedRowsFailed(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
select {
case <-req.Context().Done():
return nil, req.Context().Err()
case <-time.After(300 * time.Millisecond):
}
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"itemId":"late-item"}}`)),
Request: req,
}, nil
}))
h := srv.Router()
cookie := loginHelper(t, h)
batchID := previewTwoRowPublishBatch(t, h, cookie)
startReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches", strings.NewReader(`{"preview_id":"`+batchID+`"}`))
startReq.AddCookie(cookie)
startRec := httptest.NewRecorder()
h.ServeHTTP(startRec, startReq)
if startRec.Code != http.StatusOK {
t.Fatalf("start status=%d body=%s", startRec.Code, startRec.Body.String())
}
cancelReq := httptest.NewRequest(http.MethodPost, "/items/publish-batches/"+batchID+"/cancel", nil)
cancelReq.AddCookie(cookie)
cancelRec := httptest.NewRecorder()
h.ServeHTTP(cancelRec, cancelReq)
if cancelRec.Code != http.StatusOK {
t.Fatalf("cancel status=%d body=%s", cancelRec.Code, cancelRec.Body.String())
}
deadline := time.Now().Add(2 * time.Second)
var got map[string]any
for time.Now().Before(deadline) {
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
json.Unmarshal(rec.Body.Bytes(), &got)
if got["pending"] == float64(0) && got["running"] == float64(0) {
break
}
time.Sleep(20 * time.Millisecond)
}
if got["status"] != "canceled" {
t.Fatalf("status=%v want canceled body=%+v", got["status"], got)
}
if got["pending"] != float64(0) || got["running"] != float64(0) {
t.Fatalf("取消后不应残留 pending/running: %+v", got)
}
if got["failed"] != got["total"] {
t.Fatalf("取消后未完成行应全部失败: total=%v failed=%v body=%+v", got["total"], got["failed"], got)
}
}
@@ -129,10 +250,17 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
defer cleanup()
// 所有 mtop 调用返回 SUCCESS;发布调用返回 itemId。
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
body := `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","itemUrl":"https://x/item/123456"}}`
// 类目推荐接口需要返回 catId 才能继续后续步骤。
if strings.Contains(req.URL.RawQuery, "recommend") || strings.Contains(req.URL.RawQuery, "category") {
body = `{"ret":["SUCCESS::调用成功"],"data":{"catId":"100","categoryId":"100"}}`
u := req.URL.String()
body := `{"ret":["SUCCESS::调用成功"],"data":{}}`
switch {
case strings.Contains(u, "stream-upload.goofish.com"):
body = `{"object":{"url":"https://img.alicdn.com/published.png","pix":"800_800"}}`
case strings.Contains(u, "mtop.taobao.idle.local.poi.get"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"address":"北京"}]}}`
case strings.Contains(u, "mtop.taobao.idle.kgraph.property.recommend"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"100","catName":"数码"}}}`
case strings.Contains(u, "mtop.idle.pc.idleitem.publish"):
body = `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"123456","url":"https://x/item/123456","picUrl":"https://img.alicdn.com/published.png","categoryId":"100","categoryName":"数码","title":"商品A","priceText":"12.50","quantity":"5"}}`
}
return &http.Response{
StatusCode: http.StatusOK,
@@ -177,6 +305,29 @@ func TestRunItemPublishBatch_Success(t *testing.T) {
if status == "running" {
t.Fatal("批次应在 8s 内完成")
}
req := httptest.NewRequest(http.MethodGet, "/items/publish-batches/"+batchID, nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("detail status=%d body=%s", rec.Code, rec.Body.String())
}
var got map[string]any
json.Unmarshal(rec.Body.Bytes(), &got)
if got["status"] != "completed" {
t.Fatalf("status=%v want completed body=%+v", got["status"], got)
}
if got["success"] != float64(1) {
t.Fatalf("success=%v want 1 body=%+v", got["success"], got)
}
rows, _ := got["rows"].([]any)
if len(rows) != 1 {
t.Fatalf("rows=%+v want 1 row", got["rows"])
}
row, _ := rows[0].(map[string]any)
if row["status"] != "success" || row["item_id"] == "" {
t.Fatalf("row should be success with item_id: %+v", row)
}
}
// TestCreatePublishAutomationRules 覆盖自动化规则创建(通过成功发布路径间接覆盖)。
+125 -2
View File
@@ -1,15 +1,23 @@
package server
import (
"context"
"errors"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/protocol"
)
// mountQRLoginReal 扫码登录端点(纯 HTTP,不需要浏览器)。
func (s *Server) mountQRLoginReal(r chi.Router) {
r.Post("/qr-login/generate", s.generateQRLogin)
r.Get("/qr-login/check/{session_id}", s.checkQRLoginStatus)
r.Get("/qr-login/status/{session_id}", s.checkQRLoginStatusAndPersist)
r.Post("/qr-login/complete-verification/{session_id}", s.completeQRVerification)
}
@@ -42,6 +50,40 @@ func (s *Server) checkQRLoginStatus(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, result)
}
// checkQRLoginStatusAndPersist 兼容上游 /status 语义:扫码成功后由后端幂等保存账号。
func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
if sessionID == "" {
writeErr(w, http.StatusBadRequest, "缺少 session_id")
return
}
result := cloneQRStatus(s.QRLogin.GetSessionStatus(sessionID))
if qrStatus(result) != "success" {
writeJSON(w, http.StatusOK, result)
return
}
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
persisted, err := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result)
if err != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码登录结果失败", "session_id", sessionID, "err", err)
}
result["success"] = false
result["status"] = "error"
result["message"] = "保存扫码登录结果失败: " + err.Error()
writeJSON(w, http.StatusOK, result)
return
}
result["success"] = true
result["account_id"] = persisted.AccountID
result["is_new_account"] = persisted.IsNew
writeJSON(w, http.StatusOK, result)
}
// completeQRVerification 用户完成风控验证后调用,提取真实 cookie 并入库。
func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request) {
sessionID := chi.URLParam(r, "session_id")
@@ -58,9 +100,90 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
})
return
}
writeJSON(w, http.StatusOK, map[string]any{
resp := map[string]any{
"success": true,
"cookies": cookies,
"unb": unb,
})
}
sess := auth.SessionFromContext(r.Context())
if sess != nil {
persisted, persistErr := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
})
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
}
resp["success"] = false
resp["message"] = "保存扫码登录结果失败: " + persistErr.Error()
writeJSON(w, http.StatusOK, resp)
return
}
resp["account_id"] = persisted.AccountID
resp["is_new_account"] = persisted.IsNew
}
writeJSON(w, http.StatusOK, resp)
}
func (s *Server) persistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any) (qrLoginPersistence, error) {
s.qrMu.Lock()
defer s.qrMu.Unlock()
if s.qrPersisted == nil {
s.qrPersisted = make(map[string]qrLoginPersistence)
}
if persisted, ok := s.qrPersisted[sessionID]; ok {
return persisted, nil
}
cookies := qrString(result, "cookies")
accountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || accountID == "" {
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
}
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return qrLoginPersistence{}, err
}
if err := s.Store.Cookies.Save(ctx, accountID, cookies, userID); err != nil {
if errors.Is(err, db.ErrForbidden) {
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
}
return qrLoginPersistence{}, err
}
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
}
}
persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew}
s.qrPersisted[sessionID] = persisted
return persisted, nil
}
func cloneQRStatus(src map[string]any) map[string]any {
dst := make(map[string]any, len(src))
for k, v := range src {
dst[k] = v
}
return dst
}
func qrStatus(result map[string]any) string {
status, _ := result["status"].(string)
return status
}
func qrString(result map[string]any, key string) string {
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
+169
View File
@@ -3,16 +3,56 @@ package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"xianyu-go/internal/db"
)
type fakeQRLoginService struct {
status map[string]any
generateErr error
completeCookies string
completeUNB string
completeErr error
}
func (f *fakeQRLoginService) GenerateQRCode(context.Context) (string, string, error) {
if f.generateErr != nil {
return "", "", f.generateErr
}
return "qr-session", "data:image/png;base64,abc", nil
}
func (f *fakeQRLoginService) GetSessionStatus(sessionID string) map[string]any {
if sessionID == "no-such-session" {
return map[string]any{"status": "not_found"}
}
out := make(map[string]any, len(f.status)+1)
for k, v := range f.status {
out[k] = v
}
if _, ok := out["session_id"]; !ok {
out["session_id"] = sessionID
}
return out
}
func (f *fakeQRLoginService) CompleteVerification(context.Context, string) (string, string, error) {
if f.completeErr != nil {
return "", "", f.completeErr
}
return f.completeCookies, f.completeUNB, nil
}
// TestGenerateQRLogin 生成扫码登录二维码。
func TestGenerateQRLogin(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -34,6 +74,7 @@ func TestGenerateQRLogin(t *testing.T) {
func TestCheckQRLoginStatusEmptySession(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -52,6 +93,7 @@ func TestCheckQRLoginStatusEmptySession(t *testing.T) {
func TestCompleteQRVerificationBadSession(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("会话不存在")}
h := srv.Router()
cookie := loginHelper(t, h)
@@ -69,6 +111,88 @@ func TestCompleteQRVerificationBadSession(t *testing.T) {
}
}
func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
"status": "success",
"cookies": "unb=qr-new; _m_h5_tk=qr-token;",
"unb": "qr-new",
}}
h := srv.Router()
cookie := loginHelper(t, h)
for i := 0; i < 2; i++ {
req := httptest.NewRequest(http.MethodGet, "/qr-login/status/s1", 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 res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "qr-new" {
t.Fatalf("扫码状态保存响应异常: %+v", res)
}
}
d, err := store.Cookies.GetDetails(context.Background(), "qr-new")
if err != nil {
t.Fatalf("GetDetails qr-new: %v", err)
}
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
logs, err := store.LoginLogs.ListByCookie(context.Background(), "qr-new", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" || logs[0].Method != "qr_scan" {
t.Fatalf("重复轮询不应重复记录登录日志: logs=%#v err=%v", logs, err)
}
}
func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{
completeCookies: "unb=acc1; _m_h5_tk=qr-fresh;",
completeUNB: "acc1",
}
if err := store.Cookies.SetStatusWithReason(ctx, "acc1", false, "token 失效"); err != nil {
t.Fatalf("SetStatusWithReason: %v", err)
}
if err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/s1", 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 res map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("decode response: %v", err)
}
if res["success"] != true || res["account_id"] != "acc1" {
t.Fatalf("完成验证响应异常: %+v", res)
}
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码验证成功后应重新启用账号")
}
if _, err := store.Tokens.Get(ctx, "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("扫码验证成功后应清 token,got %v", err)
}
}
// TestKeywordsListAndDelete 关键字列表与删除(覆盖 listKeywords / listKeywordsWithItemID / listKeywordsWithType)。
func TestKeywordsListAndDelete(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -137,6 +261,51 @@ func TestAddKeywordBadJSON(t *testing.T) {
}
}
func TestReplaceKeywordsWithItemID(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginHelper(t, h)
postBatch := func(body string) []map[string]any {
req := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(body))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("replace status=%d body=%s", rec.Code, rec.Body.String())
}
listReq := httptest.NewRequest(http.MethodGet, "/keywords-with-item-id/acc1", nil)
listReq.AddCookie(cookie)
listRec := httptest.NewRecorder()
h.ServeHTTP(listRec, listReq)
if listRec.Code != http.StatusOK {
t.Fatalf("list status=%d body=%s", listRec.Code, listRec.Body.String())
}
var rows []map[string]any
if err := json.Unmarshal(listRec.Body.Bytes(), &rows); err != nil {
t.Fatal(err)
}
return rows
}
rows := postBatch(`{"keywords":[{"keyword":"在吗","reply":"在的","item_id":""},{"keyword":"价格","reply":"50","item_id":"it1"}]}`)
if len(rows) != 2 || rows[1]["item_id"] != "it1" {
t.Fatalf("批量新增异常: %+v", rows)
}
rows = postBatch(`{"keywords":[{"keyword":"在吗","reply":"稍等","item_id":""}]}`)
if len(rows) != 1 || rows[0]["reply"] != "稍等" {
t.Fatalf("批量覆盖编辑异常: %+v", rows)
}
rows = postBatch(`{"keywords":[]}`)
if len(rows) != 0 {
t.Fatalf("空数组应清空关键词: %+v", rows)
}
}
// TestDeleteKeywordNotFound 不存在关键字 404。
func TestDeleteKeywordNotFound(t *testing.T) {
srv, _, cleanup := newTestServer(t)
+61 -23
View File
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
@@ -28,20 +29,42 @@ import (
"xianyu-go/internal/xianyu/qrlogin"
)
type qrLoginService interface {
GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error)
GetSessionStatus(sessionID string) map[string]any
CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error)
}
type qrLoginPersistence struct {
AccountID string
IsNew bool
}
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
type Server struct {
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
Browser *browser.Manager
notifier *notify.Notifier
MTop mtop.Client
QRLogin *qrlogin.Manager
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
Browser *browser.Manager
PasswordLogin passwordLoginRunner
notifier *notify.Notifier
MTop mtop.Client
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
publishMu sync.Mutex
publishCancels map[string]context.CancelFunc
passwordMu sync.Mutex
passwordSessions map[string]*passwordLoginSession
passwordProcessing map[string]string
qrMu sync.Mutex
qrPersisted map[string]qrLoginPersistence
}
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
@@ -57,20 +80,33 @@ func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure
})
}
return &Server{
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
Browser: bm,
notifier: notifier,
MTop: mtop.NewClient(),
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
Browser: bm,
PasswordLogin: passwordLoginRunnerForBrowser(bm),
notifier: notifier,
MTop: mtop.NewClient(),
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
publishCancels: make(map[string]context.CancelFunc),
passwordSessions: make(map[string]*passwordLoginSession),
passwordProcessing: make(map[string]string),
qrPersisted: make(map[string]qrLoginPersistence),
}
}
func passwordLoginRunnerForBrowser(bm *browser.Manager) passwordLoginRunner {
if bm == nil {
return nil
}
return bm
}
// mtopClient 返回注入的 mtop 客户端;未注入时退回默认 HTTP 实现(保证零值可用)。
func (s *Server) mtopClient() mtop.Client {
if s.MTop != nil {
@@ -110,6 +146,8 @@ func (s *Server) Router() http.Handler {
s.mountCookies(r)
// 扫码登录
s.mountQRLoginReal(r)
// 密码登录
s.mountPasswordLogin(r)
// 订单
s.mountOrdersReal(r)
// 订单分析(仪表盘)
@@ -275,7 +313,7 @@ func isAPIPath(path string) bool {
"/system-settings", "/ai-reply", "/ai-models",
"/user-settings",
"/item-reply", "/itemReplays",
"/qr-login",
"/qr-login", "/password-login",
"/static/", // 静态资源(由 /static/* handler 处理,不进 catch-all)
}
for _, p := range apiPrefixes {
+4 -2
View File
@@ -331,8 +331,9 @@ func (s *Server) mountUserReal(r chi.Router) {
func (s *Server) listUserSettings(w http.ResponseWriter, r *http.Request) {
sess := authSess(r)
keyCol := db.DialectQuote(s.Store.Dialect, "key")
rows, err := s.Store.DB.QueryContext(r.Context(),
`SELECT key, value FROM user_settings WHERE user_id=?`, sess.UserID)
`SELECT `+keyCol+`, value FROM user_settings WHERE user_id=?`, sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
@@ -356,8 +357,9 @@ func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
sess := authSess(r)
key := chi.URLParam(r, "key")
var v string
keyCol := db.DialectQuote(s.Store.Dialect, "key")
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT value FROM user_settings WHERE user_id=? AND key=?`, sess.UserID, key).Scan(&v)
`SELECT value FROM user_settings WHERE user_id=? AND `+keyCol+`=?`, sess.UserID, key).Scan(&v)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"value": ""})
return