对齐闲鱼网页端登录续期与消息凭证流程

将扫码登录、人脸验证、Cookie 续期、MTOP Token 与 WebSocket 凭证更新按官网 JS 流程改为 Go 协议实现,Chromium 仅保留本机指纹读取和滑块验证用途。

补齐权威 Cookie Jar、重定向 Set-Cookie、滑块后快照、静默续期异步响应和并发写回处理,并完善相关回归测试。
This commit is contained in:
Christ committed 2026-07-23 15:36:11 +08:00
1 parent de9c12196f
commit 421712e975
36 files changed
+1762 -2761

No files matched your search

+6 -2
View File
@@ -36,8 +36,9 @@ func hasStoredCookieCredential(detail *db.CookieDetail) bool {
// persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。
// 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。
// handled 表示 session 已产生权威更新;此时即使保存失败,也不得再退回扁平
// UpdatedCookies 写回,否则会清除或覆盖完整 Jar。
// handled 表示本次请求由完整 Cookie Jar 接管,或 session 已产生可持久化更新;
// 此时即使 Jar 未变化,也不得因扁平 Cookie 的顺序/尾分号差异退回
// UpdatedCookies 写回,否则会把刚保存的完整 Jar 清掉。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *db.CookieDetail,
@@ -48,6 +49,9 @@ func (s *Server) persistMTopCookieSessionLocked(
}
value, snapshot, changed := session.State()
if !changed {
if snapshot != nil {
return detail.Value, false, true, nil
}
return "", false, false, nil
}
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
+30 -3
View File
@@ -82,7 +82,7 @@ func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T)
}
}
func TestRefreshAccountProfileKeepsFlatMockFallback(t *testing.T) {
func TestRefreshAccountProfileKeepsAuthoritativeSnapshotWithFlatMock(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
seedStaleCookieSnapshot(t, store, "acc1")
@@ -99,12 +99,39 @@ func TestRefreshAccountProfileKeepsFlatMockFallback(t *testing.T) {
}
srv.refreshAccountProfile(context.Background(), detail)
requireCookieSnapshotCleared(t, store, "acc1")
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
if strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
t.Fatalf("完整 Jar 不得被 mock 扁平 Cookie 覆盖: %q", updated.Value)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON); !complete {
t.Fatalf("完整 Jar 未发生变化时不得清除: %s", updated.MetadataJSON)
}
}
func TestRefreshAccountProfileKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
return &mtop.UserProfileResult{
Nickname: "mock-profile",
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
t.Fatalf("mock 扁平 Cookie 未沿用兼容写回: %q", updated.Value)
t.Fatalf("无完整 Jar 时 mock 扁平 Cookie 未沿用兼容写回: %q", updated.Value)
}
}
+42 -62
View File
@@ -25,6 +25,10 @@ type refreshTarget struct {
CurrentStatus string
}
type orderDetailMTop interface {
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
}
// mountOrders 订单端点(真实实现)。
func (s *Server) mountOrdersReal(r chi.Router) {
r.Get("/api/orders", s.listOrders)
@@ -263,13 +267,14 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
for _, targets := range ordersByCookie {
total += len(targets)
}
if s.Browser == nil {
detailFetcher, detailSupported := s.mtopClient().(orderDetailMTop)
if !detailSupported {
message := "订单列表同步完成"
if discovered > 0 {
message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
}
if total > 0 {
message += fmt.Sprintf(";浏览器自动化未启用,已跳过 %d 个订单的详情补全", total)
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failed == 0,
@@ -298,12 +303,6 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
updated, noChange := 0, 0
for cid, targets := range ordersByCookie {
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
orderIDs := make([]string, 0, len(chunk))
currentStatus := make(map[string]string, len(chunk))
for _, target := range chunk {
orderIDs = append(orderIDs, target.OrderID)
currentStatus[target.OrderID] = target.CurrentStatus
}
credentialUnlock := s.Store.LockAccountCredentials(cid)
latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
@@ -314,71 +313,59 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
batch, err := s.Browser.BatchRefreshOrders(mtopCtx, orderIDs, cid, latest.Value)
cancel()
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
err = errors.Join(err, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
}
credentialUnlock()
if persistErr == nil && valueChanged {
s.updateRunningCookie(r.Context(), cid, value)
}
if err != nil {
failed += len(chunk)
results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": err.Error()})
continue
}
rawOrders, _ := batch["orders"].([]map[string]any)
seen := make(map[string]struct{}, len(rawOrders))
for _, raw := range rawOrders {
orderID := stringFromAny(raw["order_id"])
if _, expected := currentStatus[orderID]; !expected {
continue
}
seen[orderID] = struct{}{}
if raw["success"] == false {
for _, target := range chunk {
detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
if fetchErr != nil || detail == nil {
failed++
message := "订单详情接口未返回结果"
if fetchErr != nil {
message = fetchErr.Error()
}
results = append(results, map[string]any{
"order_id": orderID,
"order_id": target.OrderID,
"success": false,
"error": stringFromAny(raw["error"]),
"error": message,
})
continue
}
newStatus := db.NormalizeOrderStatus(stringFromAny(raw["order_status"]))
newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(newStatus) {
newStatus = currentStatus[orderID]
newStatus = target.CurrentStatus
}
err := s.Store.Orders.Upsert(r.Context(), orderID, db.OrderUpsertOpts{
err := s.Store.Orders.Upsert(r.Context(), target.OrderID, db.OrderUpsertOpts{
CookieID: cid,
OrderStatus: newStatus,
SpecName: stringFromAny(raw["spec_name"]),
SpecValue: stringFromAny(raw["spec_value"]),
Quantity: stringFromAny(raw["quantity"]),
Amount: stringFromAny(raw["amount"]),
SpecName: detail.SpecName,
SpecValue: detail.SpecValue,
Quantity: detail.Quantity,
Amount: detail.Amount,
})
if err != nil {
failed++
results = append(results, map[string]any{"order_id": orderID, "success": false, "error": "更新数据库失败"})
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "error": "更新数据库失败"})
continue
}
changed := newStatus != "" && newStatus != currentStatus[orderID]
changed := newStatus != "" && newStatus != target.CurrentStatus
if changed {
updated++
} else {
noChange++
}
results = append(results, map[string]any{
"order_id": orderID,
"order_id": target.OrderID,
"success": true,
"old_status": currentStatus[orderID],
"old_status": target.CurrentStatus,
"new_status": newStatus,
})
}
for _, orderID := range missingRefreshTargetIDs(chunk, seen) {
cancel()
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
credentialUnlock()
if persistErr != nil {
failed++
results = append(results, map[string]any{"order_id": orderID, "success": false, "error": "浏览器未返回该订单的刷新结果"})
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "error": persistErr.Error()})
} else if valueChanged {
s.updateRunningCookie(r.Context(), cid, value)
}
}
}
@@ -493,15 +480,16 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
}
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
if s.Browser == nil {
writeErr(w, http.StatusServiceUnavailable, "浏览器自动化未启用,无法刷新订单")
return
}
orderID := chi.URLParam(r, "order_id")
order, ok := s.requireOrderOwner(w, r, orderID)
if !ok {
return
}
detailFetcher, ok := s.mtopClient().(orderDetailMTop)
if !ok {
writeErr(w, http.StatusServiceUnavailable, "当前 Go MTOP 客户端不支持订单详情接口")
return
}
cookieID := order.CookieID
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
credentialLocked := true
@@ -520,22 +508,13 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
detail, callErr := s.Browser.FetchOrderDetail(mtopCtx, orderID, cookieID, cookieValue, s.Store.Items.IsMultiSpec(mtopCtx, cookieID, order.ItemID))
detail, callErr := detailFetcher.FetchOrderDetail(mtopCtx, cookieValue, orderID)
if callErr == nil && detail == nil {
callErr = errors.New("订单详情接口未返回结果")
}
runtimeCookie := ""
runtimeCookieChanged := false
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if !handled && detail != nil && detail.CookieSnapshotComplete {
// 没有历史 snapshot 时不会创建 CookieSession;浏览器 fallback 返回的
// 完整 Jar 仍是权威结果,必须原子落库(包括空 Jar/空 flat)。
value = detail.UpdatedCookies
valueChanged = value != latest.Value
handled = true
metadata := cookierefresh.MetadataWithSnapshot(latest.MetadataJSON, detail.CookieSnapshot)
persistErr = s.Store.Cookies.UpdateRenewalCookie(r.Context(), cookieID, value, metadata, time.Now().Unix())
}
if persistErr != nil {
s.Logger.Error("保存订单详情响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
callErr = errors.Join(callErr, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
@@ -545,7 +524,8 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
runtimeCookieChanged = true
}
} else if callErr == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueExisting(r.Context(), cookieID, detail.UpdatedCookies); saveErr != nil {
metadata := cookierefresh.MetadataWithoutSnapshot(latest.MetadataJSON)
if saveErr := s.Store.Cookies.UpdateRenewalCookie(r.Context(), cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); saveErr != nil {
s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr)
} else {
runtimeCookie = detail.UpdatedCookies
+12 -4
View File
@@ -31,6 +31,10 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
`"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` +
`"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` +
@@ -65,10 +69,14 @@ func TestMissingRefreshResultsAreCounted(t *testing.T) {
}
}
// TestRefreshSingleOrderNoBrowser 单订单刷新无浏览器时 503。
func TestRefreshSingleOrderNoBrowser(t *testing.T) {
// TestRefreshSingleOrderUsesGoMTop 单订单刷新不依赖浏览器。
func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2","specName":"套餐","specValue":"30天"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
}))
ctx := context.Background()
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('ord-x','item1','acc1','2')`)
h := srv.Router()
@@ -78,8 +86,8 @@ func TestRefreshSingleOrderNoBrowser(t *testing.T) {
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("无浏览器应 503,got %d", rec.Code)
if rec.Code != http.StatusOK {
t.Fatalf("Go MTOP 刷新应成功,got %d body=%s", rec.Code, rec.Body.String())
}
}
+9 -459
View File
@@ -1,473 +1,23 @@
package server
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"strconv"
"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
AccountExisted bool
CookieCount int
ShowBrowser bool
CreatedAt time.Time
cancel context.CancelFunc
}
// mountPasswordLogin 保留历史 API 路径,避免旧前端收到 404。Go 客户端的
// 登录凭证只允许由扫码流程产生;这里永远不会调用 Chromium 密码登录。
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)
r.Post("/password-login", s.passwordLoginDisabled)
r.Get("/password-login/check/{session_id}", s.passwordLoginDisabled)
r.Delete("/password-login/cancel/{session_id}", s.passwordLoginDisabled)
}
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
}
allowed, accountExisted, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID)
if !allowed {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": message})
return
}
s.cleanupExpiredPasswordLoginSessions()
if sid := s.currentPasswordLoginSession(sess.UserID, 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.WithTimeout(s.lifecycleContext(), passwordLoginProcessingTimeout)
loginSession := &passwordLoginSession{
ID: sessionID,
AccountID: accountID,
Account: account,
UserID: sess.UserID,
Status: "processing",
Message: "登录处理中,请稍候...",
ShowBrowser: req.ShowBrowser,
AccountExisted: accountExisted,
CreatedAt: time.Now(),
cancel: cancel,
}
s.passwordMu.Lock()
s.passwordSessions[sessionID] = loginSession
s.passwordProcessing[passwordProcessingKey(sess.UserID, accountID)] = sessionID
s.passwordMu.Unlock()
workerDone := s.beginWorker()
go func() {
defer workerDone()
s.runPasswordLoginSession(ctx, loginSession, req.Password)
}()
func (s *Server) passwordLoginDisabled(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"session_id": sessionID,
"status": "processing",
"message": "登录任务已启动,请等待...",
"success": false,
"status": "disabled",
"message": "Go 客户端仅支持扫码登录,密码登录已禁用",
})
}
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
}
requestSession := auth.SessionFromContext(r.Context())
if requestSession == nil || session.UserID != requestSession.UserID {
s.passwordMu.Unlock()
writeJSON(w, http.StatusOK, map[string]any{"status": "not_found", "message": "会话不存在或已过期"})
return
}
response := passwordSessionResponse(session)
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
}
requestSession := auth.SessionFromContext(r.Context())
if requestSession == nil || session.UserID != requestSession.UserID {
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, passwordProcessingKey(session.UserID, 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 := browser.ResolveHeadless(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.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, reason, err.Error(), 0)
s.failPasswordLoginSession(session, status, err.Error(), reason, event.CooldownHours)
return
}
accountID, isNew, err := s.savePasswordLoginCookies(ctx, session, password, cookies)
if err != nil {
s.addLoginLog(context.Background(), session.AccountID, session.UserID, loginMethodPassword, loginStatusFailed, "cookie_update_failed", err.Error(), 0)
s.failPasswordLoginSession(session, "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)
if accountID != session.AccountID {
return "", false, fmt.Errorf("登录结果账号 %s 与正在编辑的账号 %s 不一致,已拒绝覆盖", accountID, session.AccountID)
}
cookieValue := browser.MarshalCookies(cookies)
isNew := false
credentialUnlock := s.Store.LockAccountCredentials(accountID)
saveErr := func() error {
defer credentialUnlock()
detail, err := s.Store.Cookies.GetDetails(ctx, accountID)
switch {
case errors.Is(err, db.ErrNotFound):
if session.AccountExisted {
return errors.New("账号已在登录期间删除,拒绝重新创建")
}
isNew = true
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookieValue, session.UserID); err != nil {
return err
}
case err != nil:
return err
case detail == nil:
return db.ErrNotFound
case detail.UserID != session.UserID:
return db.ErrForbidden
default:
if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookieValue); err != nil {
return err
}
}
if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
return err
}
s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
if s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(ctx, accountID); err != nil {
s.Logger.Warn("密码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
}
}
return nil
}()
if saveErr != nil {
return "", false, saveErr
}
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, bool, string) {
d, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err == nil {
if d.UserID != userID {
return false, true, "无权限操作该账号"
}
if !s.Store.Cookies.GetStatus(ctx, accountID) {
return false, true, "账号已禁用,请先在账号管理中启用"
}
return true, true, ""
}
if errors.Is(err, db.ErrNotFound) {
return true, false, ""
}
return false, false, "查询账号失败"
}
func passwordProcessingKey(userID int64, accountID string) string {
return strconv.FormatInt(userID, 10) + ":" + accountID
}
func (s *Server) currentPasswordLoginSession(userID int64, accountID string) string {
s.passwordMu.Lock()
defer s.passwordMu.Unlock()
return s.passwordProcessing[passwordProcessingKey(userID, 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, passwordProcessingKey(current.UserID, originalAccountID))
delete(s.passwordProcessing, passwordProcessingKey(current.UserID, 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, passwordProcessingKey(session.UserID, session.AccountID))
}
if age <= passwordLoginSessionMaxAge {
continue
}
if session.cancel != nil {
session.cancel()
}
delete(s.passwordSessions, sessionID)
delete(s.passwordProcessing, passwordProcessingKey(session.UserID, 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 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"
}
+21 -488
View File
@@ -1,504 +1,37 @@
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)
}
seedStaleCookieSnapshot(t, store, "acc1")
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 tk, err := store.Tokens.Get(context.Background(), "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("密码登录成功应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
requireCookieSnapshotCleared(t, store, "acc1")
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 TestPasswordLoginDoesNotRecreateAccountDeletedWhileBrowserRuns(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", "_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"}`)
sessionID := start["session_id"].(string)
for i := 0; i < 100; i++ {
if calls, _, _ := fake.snapshot(); calls == 1 {
break
}
if i == 99 {
t.Fatal("浏览器登录任务未启动")
}
time.Sleep(5 * time.Millisecond)
}
deleteReq := httptest.NewRequest(http.MethodDelete, "/cookies/acc1", nil)
deleteReq.AddCookie(cookie)
deleteRec := httptest.NewRecorder()
h.ServeHTTP(deleteRec, deleteReq)
if deleteRec.Code != http.StatusOK {
t.Fatalf("delete status=%d body=%s", deleteRec.Code, deleteRec.Body.String())
}
close(fake.block)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "failed")
if !strings.Contains(done["error"].(string), "登录期间删除") {
t.Fatalf("删除中的账号应明确拒绝复活: %+v", done)
}
if _, err := store.Cookies.GetDetails(context.Background(), "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("异步登录不得重建已删除账号: %v", err)
}
}
func TestPasswordLoginRejectsMismatchedReturnedAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{cookies: map[string]string{"unb": "other-account", "_m_h5_tk": "wrong"}}
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret"}`)
done := waitPasswordLoginStatus(t, h, cookie, start["session_id"].(string), "failed")
if !strings.Contains(done["error"].(string), "不一致") {
t.Fatalf("mismatch error=%+v", done)
}
if saved, err := store.Cookies.GetValue(context.Background(), "acc1"); err != nil || strings.Contains(saved, "wrong") {
t.Fatalf("target cookie must remain unchanged: value=%q err=%v", saved, err)
}
if _, err := store.Cookies.GetValue(context.Background(), "other-account"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("mismatched account must not be created: %v", err)
}
}
func TestPasswordLoginTerminalResultCanBePolledAgain(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.PasswordLogin = &fakePasswordLoginRunner{cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"}}
h := srv.Router()
cookie := loginHelper(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret"}`)
sessionID := start["session_id"].(string)
first := waitPasswordLoginStatus(t, h, cookie, sessionID, "success")
second := checkPasswordLoginForTest(t, h, cookie, sessionID)
if first["account_id"] != "acc1" || second["status"] != "success" || second["account_id"] != "acc1" {
t.Fatalf("terminal result must remain idempotently readable: first=%+v second=%+v", first, second)
}
}
func TestPasswordLoginUnavailableWhenBrowserManagerNil(t *testing.T) {
func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
h := srv.Router()
cookie := loginForPasswordTest(t, h)
authCookie := loginHelper(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 TestPasswordLoginSessionCannotBeCheckedOrCanceledByAnotherUser(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
if ok, err := store.Users.Create(context.Background(), "member", "[email protected]", "memberpw"); err != nil || !ok {
t.Fatalf("create member: ok=%v err=%v", ok, err)
}
fake := &fakePasswordLoginRunner{block: make(chan struct{}), cookies: map[string]string{"unb": "acc1"}}
srv.PasswordLogin = fake
h := srv.Router()
adminCookie := loginForPasswordTest(t, h)
memberCookie := loginAsHelper(t, h, "member", "memberpw")
start := startPasswordLoginForTest(t, h, adminCookie, `{"account_id":"acc1","account":"u","password":"p"}`)
sessionID, _ := start["session_id"].(string)
if sessionID == "" {
t.Fatalf("missing session: %+v", start)
}
checked := checkPasswordLoginForTest(t, h, memberCookie, sessionID)
if checked["status"] != "not_found" {
t.Fatalf("cross-user check exposed session: %+v", checked)
}
cancelReq := httptest.NewRequest(http.MethodDelete, "/password-login/cancel/"+sessionID, nil)
cancelReq.AddCookie(memberCookie)
cancelRec := httptest.NewRecorder()
h.ServeHTTP(cancelRec, cancelReq)
var canceled map[string]any
if err := json.Unmarshal(cancelRec.Body.Bytes(), &canceled); err != nil {
t.Fatal(err)
}
if canceled["success"] != false {
t.Fatalf("cross-user cancel should be hidden: %+v", canceled)
}
if owner := checkPasswordLoginForTest(t, h, adminCookie, sessionID); owner["status"] != "processing" {
t.Fatalf("owner session was canceled by another user: %+v", owner)
}
cancelPasswordLoginForTest(t, h, adminCookie, sessionID)
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)
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/password-login", strings.NewReader(`{"account_id":"acc1","account":"u","password":"p"}`)),
httptest.NewRequest(http.MethodGet, "/password-login/check/legacy", nil),
httptest.NewRequest(http.MethodDelete, "/password-login/cancel/legacy", nil),
}
for _, req := range requests {
req.AddCookie(authCookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("%s %s status=%d body=%s", req.Method, req.URL.Path, rec.Code, rec.Body.String())
}
var result map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result["success"] != false || result["status"] != "disabled" {
t.Fatalf("%s %s 应永久禁用: %+v", req.Method, req.URL.Path, result)
}
}
}
+39 -3
View File
@@ -12,6 +12,7 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
@@ -144,11 +145,17 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
}
sess := auth.SessionFromContext(r.Context())
if sess != nil {
persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, map[string]any{
result := map[string]any{
"status": "success",
"cookies": cookies,
"unb": unb,
}, req.TargetAccountID)
}
if current := s.QRLogin.GetSessionStatus(sessionID); current != nil {
if snapshot, ok := current["cookie_snapshot"]; ok {
result["cookie_snapshot"] = snapshot
}
}
persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
@@ -187,6 +194,7 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
}
s.qrMu.Unlock()
cookies := qrString(result, "cookies")
cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
if cookies == "" || scannedAccountID == "" {
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
@@ -212,6 +220,12 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID); err != nil {
return err
}
if snapshotComplete {
metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot)
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil {
return err
}
}
case err != nil:
return err
case detail == nil:
@@ -222,7 +236,12 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
}
return db.ErrForbidden
default:
if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
if snapshotComplete {
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot)
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil {
return err
}
} else if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
return err
}
}
@@ -319,6 +338,7 @@ func cloneQRStatus(src map[string]any) map[string]any {
func publicQRStatus(src map[string]any) map[string]any {
dst := cloneQRStatus(src)
delete(dst, "cookies")
delete(dst, "cookie_snapshot")
return dst
}
@@ -331,3 +351,19 @@ func qrString(result map[string]any, key string) string {
value, _ := result[key].(string)
return strings.TrimSpace(value)
}
func qrCookieSnapshot(result map[string]any) ([]cookierefresh.BrowserCookie, bool) {
raw, ok := result["cookie_snapshot"]
if !ok {
return nil, false
}
snapshot, ok := raw.([]cookierefresh.BrowserCookie)
if !ok || snapshot == nil {
return nil, false
}
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
return normalized, true
}
+15
View File
@@ -11,6 +11,7 @@ import (
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
)
type fakeQRLoginService struct {
@@ -113,6 +114,7 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{
"status": "success", "cookies": "unb=acc1; secret=value", "unb": "acc1",
"cookie_snapshot": []cookierefresh.BrowserCookie{{Name: "secret", Value: "value", Domain: ".goofish.com", Path: "/"}},
}}
ownQRSession(t, srv, store, "redacted")
h := srv.Router()
@@ -133,6 +135,9 @@ func TestQRLoginStatusNeverExposesCookies(t *testing.T) {
if _, exists := res["cookies"]; exists {
t.Fatalf("%s must redact cookies: %+v", path, res)
}
if _, exists := res["cookie_snapshot"]; exists {
t.Fatalf("%s must redact cookie snapshot: %+v", path, res)
}
}
}
@@ -208,7 +213,14 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
"status": "success",
"cookies": "unb=qr-new; _m_h5_tk=qr-token;",
"unb": "qr-new",
"cookie_snapshot": []cookierefresh.BrowserCookie{
{Name: "unb", Value: "qr-new", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "qr-token", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
},
}}
if snapshot, ok := qrCookieSnapshot(srv.QRLogin.GetSessionStatus("s1")); !ok || len(snapshot) != 2 {
t.Fatalf("测试扫码 Cookie 快照异常: ok=%v snapshot=%+v", ok, snapshot)
}
ownQRSession(t, srv, store, "s1")
h := srv.Router()
cookie := loginHelper(t, h)
@@ -237,6 +249,9 @@ func TestQRLoginStatusPersistsSuccessIdempotently(t *testing.T) {
if d.LoginMethod != "qr_scan" || d.LastLoginAt == 0 {
t.Fatalf("扫码登录应标记登录审计字段: %+v", d)
}
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(d.MetadataJSON); !ok || len(snapshot) != 2 {
t.Fatalf("纯 Go 扫码完整 Cookie Jar 未持久化: ok=%v snapshot=%+v metadata=%s", ok, snapshot, d.MetadataJSON)
}
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)
+29 -52
View File
@@ -21,7 +21,6 @@ import (
"xianyu-go/internal/account"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/browser"
"xianyu-go/internal/db"
"xianyu-go/internal/notify"
"xianyu-go/internal/webui"
@@ -56,19 +55,17 @@ type publishBatchWorker struct {
// Server 聚合 HTTP 服务依赖。Automation 与 Notifier 由构造函数注入,
// 不再允许外部直接改字段,避免运行时被替换成 nil。
type Server struct {
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
Browser *browser.Manager
PasswordLogin passwordLoginRunner
notifier *notify.Notifier
MTop mtop.Client
CookieRenew xrenew.Service
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
Store *db.Store
Auth *auth.Service
Manager *account.Manager
automation *automation.Center
notifier *notify.Notifier
MTop mtop.Client
CookieRenew xrenew.Service
QRLogin qrLoginService
Logger *slog.Logger
WebDir string // 前端静态资源目录(含 index.html)
Addr string
publishMu sync.Mutex
publishCancels map[string]publishBatchWorker
@@ -78,10 +75,6 @@ type Server struct {
lifecycleMu sync.RWMutex
lifecycleCtx context.Context
passwordMu sync.Mutex
passwordSessions map[string]*passwordLoginSession
passwordProcessing map[string]string
qrMu sync.Mutex
qrPersisted map[string]qrLoginPersistence
qrOwners map[string]qrLoginOwner
@@ -93,49 +86,33 @@ type Server struct {
// New 构造。autoCenter/notifier 由调用方完成创建后注入(创建顺序:
// adapter → manager → automation → notifier → server)。
func New(store *db.Store, manager *account.Manager, bm *browser.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
func New(store *db.Store, manager *account.Manager, secure bool, webDir, addr string, logger *slog.Logger, autoCenter *automation.Center, notifier *notify.Notifier) *Server {
if logger == nil {
logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
}
qrMgr := qrlogin.NewManager(logger)
if bm != nil {
qrMgr.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
return bm.QRCookieRefresh(ctx, tmpCookies, verificationURL, onScreenshot)
})
}
return &Server{
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(),
CookieRenew: xrenew.Service{},
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
Store: store,
Auth: &auth.Service{Store: store, Logger: logger, Secure: secure},
Manager: manager,
automation: autoCenter,
notifier: notifier,
MTop: mtop.NewClient(),
CookieRenew: xrenew.Service{},
QRLogin: qrMgr,
Logger: logger,
WebDir: webDir,
Addr: addr,
publishCancels: make(map[string]publishBatchWorker),
workersDone: closedSignal(),
lifecycleCtx: context.Background(),
passwordSessions: make(map[string]*passwordLoginSession),
passwordProcessing: make(map[string]string),
qrPersisted: make(map[string]qrLoginPersistence),
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
publishCancels: make(map[string]publishBatchWorker),
workersDone: closedSignal(),
lifecycleCtx: context.Background(),
qrPersisted: make(map[string]qrLoginPersistence),
qrOwners: make(map[string]qrLoginOwner),
loginLimiter: newLoginFailureLimiter(),
}
}
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 {
+1 -1
View File
@@ -32,7 +32,7 @@ func newTestServer(t *testing.T) (*Server, *db.Store, func()) {
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)
srv := New(store, mgr, false, "", ":0", nil, nil, nil)
mtopClient := mtop.NewClient()
mtopClient.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{