对齐闲鱼网页端登录续期与消息凭证流程
将扫码登录、人脸验证、Cookie 续期、MTOP Token 与 WebSocket 凭证更新按官网 JS 流程改为 Go 协议实现,Chromium 仅保留本机指纹读取和滑块验证用途。 补齐权威 Cookie Jar、重定向 Set-Cookie、滑块后快照、静默续期异步响应和并发写回处理,并完善相关回归测试。
This commit is contained in:
1 parent
de9c12196f
commit
421712e975
36 files changed
+1762
-2761
No files matched your search
+7
-8
@@ -8,8 +8,8 @@
|
||||
//
|
||||
// 首次使用可直接用本二进制初始化管理员,不再需要单独 init-admin。
|
||||
//
|
||||
// 浏览器自动化(扫码风控验证、密码登录、订单抓取)内置 playwright-go,
|
||||
// 首次使用时自动下载 Chromium。加 -no-browser 可禁用。
|
||||
// Chromium 仅用于读取本机浏览器指纹和处理 token 滑块,首次使用时由
|
||||
// playwright-go 准备运行环境。加 -no-browser 可禁用这两项能力。
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -32,7 +32,6 @@ import (
|
||||
"xianyu-go/internal/notify"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/server"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -41,7 +40,7 @@ func main() {
|
||||
addr := flag.String("addr", ":8080", "HTTP 监听地址")
|
||||
webDir := flag.String("web", "", "前端静态资源目录(含 index.html)")
|
||||
secure := flag.Bool("secure", false, "HTTPS 模式(Cookie 加 Secure)")
|
||||
noBrowser := flag.Bool("no-browser", false, "禁用内置浏览器自动化(扫码风控验证/密码登录/订单抓取将不可用)")
|
||||
noBrowser := flag.Bool("no-browser", false, "禁用 Chromium(本机浏览器指纹读取和 token 滑块自动处理将不可用)")
|
||||
verbose := flag.Bool("v", false, "调试日志")
|
||||
logLevel := flag.String("log-level", "", "日志等级:debug/info/warn/error;默认读取 LOG_LEVEL 或系统设置")
|
||||
logFormat := flag.String("log-format", "", "日志格式:text/json;默认读取 LOG_FORMAT")
|
||||
@@ -126,7 +125,8 @@ func main() {
|
||||
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
|
||||
}
|
||||
|
||||
// 2) 内置浏览器管理器(playwright-go,首运行自动下载 Chromium)。
|
||||
// 2) Chromium 只负责读取本机浏览器指纹和处理 token 滑块。
|
||||
// 扫码、人脸、续期、MTOP、Cookie 与 WebSocket 全部走 Go 协议实现。
|
||||
var bm *browser.Manager
|
||||
if !*noBrowser {
|
||||
bm = browser.NewManager(logger)
|
||||
@@ -134,7 +134,6 @@ func main() {
|
||||
logger.Error("初始化 Playwright Chromium 指纹失败", "err", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
mtop.SetDefaultTokenRequestExecutor(bm)
|
||||
}
|
||||
var mgr *account.Manager
|
||||
ap := adapter.New(store, bm, logger)
|
||||
@@ -150,10 +149,10 @@ func main() {
|
||||
logger.Error("启动账号引擎失败", "err", err)
|
||||
}
|
||||
go automation.NewScheduler(autoCenter).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, bm, ap, logger).Run(ctx)
|
||||
go renewal.NewScheduler(store, mgr, ap, logger).Run(ctx)
|
||||
|
||||
// 3) HTTP 服务。
|
||||
srv := server.New(store, mgr, bm, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
srv := server.New(store, mgr, *secure, *webDir, *addr, logger, autoCenter, notifier)
|
||||
go srv.RunPublishBatchRecovery(ctx)
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
logger.Error("HTTP 服务退出", "err", err)
|
||||
|
||||
+134
-285
@@ -1,7 +1,7 @@
|
||||
// Package adapter 是账号运行时与外部能力(浏览器自动化、通知、自动化中心)的装配层。
|
||||
// Package adapter 是账号运行时与外部能力(风控验证、通知、自动化中心)的装配层。
|
||||
//
|
||||
// 它实现 engine.Handler 与 automation.OrderDetailFetcher,把系统事件转发到自动化中心、
|
||||
// 把订单详情抓取/密码登录刷新接到浏览器、把账号告警推到通知器。业务逻辑集中在此,
|
||||
// 把订单详情抓取/凭证续期接到 Go 协议客户端、把账号告警推到通知器。业务逻辑集中在此,
|
||||
// cmd/server 只负责构造与接线。
|
||||
package adapter
|
||||
|
||||
@@ -24,24 +24,10 @@ import (
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
)
|
||||
|
||||
// browserManager 是 adapter 所需的浏览器能力最小契约。*browser.Manager 实现该接口;
|
||||
// 测试可注入桩实现,避免依赖 Chromium。
|
||||
// browserManager 只暴露风控验证能力。普通 Token、Cookie 续期、订单和
|
||||
// WebSocket 流程不得通过 Chromium 实现。
|
||||
type browserManager interface {
|
||||
FetchOrderDetail(ctx context.Context, orderID, cookieID, cookieValue string, requireSpec ...bool) (*browser.OrderDetail, error)
|
||||
CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error)
|
||||
PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error)
|
||||
}
|
||||
|
||||
type browserQuickRenewer interface {
|
||||
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
|
||||
}
|
||||
|
||||
type browserQuickSnapshotRenewer interface {
|
||||
BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
|
||||
}
|
||||
|
||||
type browserCookieSnapshotRenewer interface {
|
||||
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error)
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaRecoverer interface {
|
||||
@@ -52,12 +38,20 @@ type browserTokenCaptchaEngineRecoverer interface {
|
||||
TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (cookies, engine string, err error)
|
||||
}
|
||||
|
||||
type browserTokenCaptchaSnapshotReader interface {
|
||||
TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (cookies string, snapshot []cookierefresh.BrowserCookie, err error)
|
||||
}
|
||||
|
||||
type tokenCaptchaRequester interface {
|
||||
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
|
||||
}
|
||||
|
||||
type orderDetailClient interface {
|
||||
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
|
||||
}
|
||||
|
||||
// Adapter 实现 engine.Handler 与 automation.OrderDetailFetcher,
|
||||
// 把系统消息、订单详情抓取和密码登录刷新接到浏览器与自动化中心。
|
||||
// 把系统消息、订单详情抓取和协议级凭证续期接到 Go 客户端与自动化中心。
|
||||
//
|
||||
// 自动发货只走 automation.Center;用户聊天消息由 Account 内部 ReplyService 处理,
|
||||
// 故 HandleChatMessage 为空实现。
|
||||
@@ -70,6 +64,7 @@ type Adapter struct {
|
||||
renewSvc xrenew.Service
|
||||
cooldown *renewal.CooldownManager
|
||||
captchaReq tokenCaptchaRequester
|
||||
orderMTop orderDetailClient
|
||||
|
||||
orderFetchMu sync.Mutex
|
||||
lastOrderFetch time.Time
|
||||
@@ -100,6 +95,7 @@ func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
logger: logger,
|
||||
cooldown: renewal.GlobalCooldown,
|
||||
captchaReq: mtop.NewClient(),
|
||||
orderMTop: mtop.NewClient(),
|
||||
passwordProcessing: make(map[string]struct{}),
|
||||
}
|
||||
}
|
||||
@@ -127,50 +123,8 @@ func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
|
||||
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
|
||||
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
|
||||
|
||||
// RenewAccountStartup 复用真实 Chromium /im 页面执行官网 auto-login plugin。
|
||||
// engine 在账号首条 WebSocket 建立前调用一次;普通 reconnect 不会重复导航页面。
|
||||
func (a *Adapter) RenewAccountStartup(ctx context.Context, cookieID, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) (*xrenew.Result, error) {
|
||||
var snapshot []cookierefresh.BrowserCookie
|
||||
if len(snapshots) > 0 {
|
||||
snapshot = snapshots[0]
|
||||
}
|
||||
if br, ok := a.browser.(browserCookieSnapshotRenewer); ok {
|
||||
showBrowser := false
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if detail, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && detail != nil {
|
||||
showBrowser = detail.ShowBrowser
|
||||
}
|
||||
}
|
||||
newCookies, newSnapshot, reloaded, err := br.CookiesRefreshSnapshot(
|
||||
ctx, cookieID, cookieStr, snapshot, browser.ResolveHeadless(showBrowser),
|
||||
)
|
||||
message := "官网消息页未触发静默续期 reload"
|
||||
skipReason := "official_no_reload"
|
||||
if reloaded {
|
||||
message = "官网消息页静默续期成功并完成 reload"
|
||||
skipReason = ""
|
||||
}
|
||||
if err != nil {
|
||||
message = "官网消息页续期执行失败: " + err.Error()
|
||||
skipReason = ""
|
||||
}
|
||||
result := &xrenew.Result{
|
||||
Success: err == nil && reloaded,
|
||||
Skipped: err == nil && !reloaded,
|
||||
SkipReason: skipReason,
|
||||
RenewMethod: "browser_auto_login_plugin",
|
||||
NewCookies: newCookies,
|
||||
UpdatedCookieNames: cookierefresh.ChangedSnapshotLabels(snapshot, newSnapshot),
|
||||
CookieSnapshot: newSnapshot,
|
||||
CookieSnapshotComplete: newSnapshot != nil,
|
||||
Message: message,
|
||||
RequestCount: 1,
|
||||
}
|
||||
return result, err
|
||||
}
|
||||
// -no-browser 模式只能使用 HTTP 兼容实现;UA 仍由本地指纹统一生成。
|
||||
return a.renewSvc.RenewAPIFirst(ctx, cookieStr, snapshot)
|
||||
}
|
||||
// SetOrderDetailClient 覆盖纯 Go 订单详情客户端,便于测试隔离网络。
|
||||
func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
|
||||
@@ -260,6 +214,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
newCookies := ""
|
||||
captchaEngine := "playwright"
|
||||
remoteHandled := false
|
||||
captchaHeadless := browser.ResolveHeadless(showBrowser)
|
||||
var err error
|
||||
if remoteConfig := a.loadRemoteCaptchaConfig(ctx); remoteConfig != nil {
|
||||
newCookies, remoteHandled, err = solveRemoteCaptcha(
|
||||
@@ -282,11 +237,11 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
if withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
|
||||
ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider,
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
} else {
|
||||
newCookies, err = br.TokenCaptchaRecover(
|
||||
ctx, cookieID, cookieStr, verificationURL, browser.ResolveHeadless(showBrowser), provider,
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -308,7 +263,34 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, cookierefresh.MetadataWithoutSnapshot(metadataJSON), time.Now().Unix()); err != nil {
|
||||
var cookieSnapshot []cookierefresh.BrowserCookie
|
||||
snapshotComplete := false
|
||||
if !remoteHandled {
|
||||
if reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
|
||||
if readErr != nil {
|
||||
a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
|
||||
} else {
|
||||
cookieSnapshot = cookierefresh.NormalizeSnapshot(profileSnapshot)
|
||||
if cookieSnapshot == nil {
|
||||
cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
snapshotComplete = true
|
||||
newCookies = profileCookies
|
||||
}
|
||||
}
|
||||
}
|
||||
if !snapshotComplete {
|
||||
if existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
|
||||
snapshotComplete = true
|
||||
}
|
||||
}
|
||||
updatedMetadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
|
||||
if snapshotComplete {
|
||||
updatedMetadata = cookierefresh.MetadataWithSnapshot(metadataJSON, cookieSnapshot)
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, updatedMetadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存 token 风控恢复 Cookie 失败", "account", cookieID, "err", err)
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
_ = a.store.RiskLogs.Update(ctx, logID, db.RiskControlLog{
|
||||
@@ -334,7 +316,12 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelInfo,
|
||||
"token 风控验证已自动恢复", "系统已完成验证并更新登录凭证。")
|
||||
return &mtop.RefreshResult{UpdatedCookies: newCookies}, true
|
||||
return &mtop.RefreshResult{
|
||||
UpdatedCookies: newCookies,
|
||||
CookieSnapshot: cookieSnapshot,
|
||||
CookieSnapshotComplete: snapshotComplete,
|
||||
CookieStateChanged: newCookies != cookieStr || snapshotComplete,
|
||||
}, true
|
||||
}
|
||||
|
||||
// HandleSystemEvent 把系统卡片事件转发到自动化中心,由自动化规则决定是否执行。
|
||||
@@ -346,14 +333,14 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时启动浏览器,
|
||||
// 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
|
||||
// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if a.browser == nil {
|
||||
return nil, fmt.Errorf("订单缺少规格/数量信息且浏览器自动化未启用")
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
@@ -389,18 +376,9 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
detail, fetchErr := a.browser.FetchOrderDetail(requestCtx, orderID, cookieID, cookieStr, true)
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
authoritativeHandled := sessionChanged
|
||||
if detail != nil && detail.CookieSnapshotComplete {
|
||||
authoritativeCookies = detail.UpdatedCookies
|
||||
authoritativeSnapshot = detail.CookieSnapshot
|
||||
if authoritativeSnapshot == nil {
|
||||
authoritativeSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
authoritativeHandled = true
|
||||
}
|
||||
if authoritativeHandled {
|
||||
if sessionChanged {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, authoritativeSnapshot)
|
||||
@@ -415,10 +393,11 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
return nil, fetchErr
|
||||
}
|
||||
if detail == nil {
|
||||
return nil, errors.New("订单详情浏览器返回空结果")
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if !authoritativeHandled && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, cookieID, detail.UpdatedCookies); err != nil {
|
||||
if !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
}
|
||||
@@ -433,7 +412,7 @@ func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的浏览器抓取。
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
|
||||
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
|
||||
order, err := a.store.Orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
@@ -448,98 +427,44 @@ func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automa
|
||||
}, true
|
||||
}
|
||||
|
||||
// OnPasswordLoginRefresh 连续失败时恢复 Cookie。
|
||||
//
|
||||
// 恢复顺序是“轻量续期 -> 浏览器快速续期 -> 密码登录”。轻量续期/快速续期复用旧 Cookie
|
||||
// 刷新登录态;这比账号密码登录更轻,风控压力也更小。
|
||||
// 同一账号冷却 engine.PasswordLoginMinGap,避免短时间反复触发浏览器恢复。
|
||||
// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
|
||||
// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
|
||||
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
|
||||
a.logger.Warn("密码登录刷新冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("密码登录刷新冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
a.logger.Warn("协议续期冷却中", "account", cookieID, "remain", remain.Round(time.Second))
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "skipped_cooldown", reason, fmt.Sprintf("协议续期冷却中,还需等待 %s", remain.Round(time.Second)))
|
||||
return false
|
||||
}
|
||||
if !a.beginPasswordLogin(cookieID) {
|
||||
a.logger.Warn("密码登录刷新已在处理中", "account", cookieID)
|
||||
a.logger.Warn("协议续期已在处理中", "account", cookieID)
|
||||
return false
|
||||
}
|
||||
defer a.finishPasswordLogin(cookieID)
|
||||
|
||||
d, err := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if err != nil {
|
||||
a.logger.Warn("密码登录刷新失败:读取账号详情失败", "account", cookieID, "err", err)
|
||||
a.logger.Warn("协议续期失败:读取账号详情失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, 0, "failed", "account_lookup_failed", err.Error())
|
||||
return false
|
||||
}
|
||||
|
||||
lightRenewed, lightRenewErr := a.tryLightRenewBeforePassword(ctx, d)
|
||||
if lightRenewed {
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "密码登录前轻量续期成功")
|
||||
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, d)
|
||||
if renewed {
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
if errors.Is(lightRenewErr, browser.ErrSecurityVerification) {
|
||||
cooldown.MarkPasswordError(cookieID)
|
||||
message := "浏览器续期遇到闲鱼安全验证,已停止自动密码登录,请人工完成验证或重新扫码"
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn, "闲鱼要求安全验证", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "verification_required", message)
|
||||
return false
|
||||
message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
|
||||
if renewErr != nil {
|
||||
message += ":" + renewErr.Error()
|
||||
}
|
||||
|
||||
if latest, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && latest != nil && latest.Value != "" && latest.Value != d.Value {
|
||||
a.logger.Info("密码登录前检测到 DB Cookie 已被外部更新,跳过密码登录", "account", cookieID)
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "cookie_already_updated_externally", "数据库中的 Cookie 已被外部更新,跳过密码登录")
|
||||
return true
|
||||
}
|
||||
|
||||
if a.browser == nil {
|
||||
a.logger.Warn("密码登录刷新失败:浏览器自动化已禁用,接口轻量续期也未恢复", "account", cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "browser_disabled", "浏览器自动化已禁用,接口轻量续期未恢复")
|
||||
return false
|
||||
}
|
||||
|
||||
if strings.TrimSpace(d.Username) == "" || strings.TrimSpace(d.Password) == "" {
|
||||
msg := "账号已掉线且未配置账号密码"
|
||||
a.logger.Warn("密码登录刷新失败:账号未配置登录用户名或密码", "account", cookieID)
|
||||
if err := a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg); err != nil {
|
||||
a.logger.Warn("未配置账号密码时停用账号失败", "account", cookieID, "err", err)
|
||||
}
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "no_credentials", "no_credentials", msg)
|
||||
return false
|
||||
}
|
||||
cookies, err := a.browser.PasswordLogin(ctx, d.Username, d.Password, cookieID, "", browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
a.handlePasswordLoginError(ctx, cookieID, err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", passwordLoginFailureReason(err), err.Error())
|
||||
return false
|
||||
}
|
||||
cookieStr := browser.MarshalCookies(cookies)
|
||||
if strings.TrimSpace(cookieStr) == "" {
|
||||
a.logger.Warn("密码登录刷新失败:浏览器未返回 cookie", "account", cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "empty_cookies", "浏览器未返回 cookie")
|
||||
return false
|
||||
}
|
||||
// 参考实现只在真实密码登录拿到 Cookie 后启动 60 秒冷却。
|
||||
cooldown.MarkPasswordLogin(cookieID)
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, cookieID, cookieStr); err != nil {
|
||||
a.logger.Warn("密码登录刷新失败:保存 cookie 失败", "account", cookieID, "err", err)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "cookie_update_failed", err.Error())
|
||||
return false
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
_ = a.store.Cookies.MarkLogin(ctx, cookieID, "password", time.Now().Unix())
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "success", "", "账号密码登录刷新成功")
|
||||
a.logger.Info("密码登录刷新 cookie 成功", "account", cookieID)
|
||||
return true
|
||||
a.logger.Warn("协议续期未恢复账号", "account", cookieID, "err", renewErr)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountOffline, engine.AlertLevelWarn, "账号需要重新扫码", message)
|
||||
a.recordPasswordLogin(ctx, cookieID, d.UserID, "failed", "qr_login_required", message)
|
||||
return false
|
||||
}
|
||||
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
@@ -568,7 +493,7 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
|
||||
if err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
CookieID: cookieID,
|
||||
UserID: userID,
|
||||
Method: "password",
|
||||
Method: "protocol",
|
||||
Status: status,
|
||||
Message: truncateMessage(message, 500),
|
||||
TriggerReason: "令牌/Session过期",
|
||||
@@ -578,28 +503,10 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
|
||||
DurationMS: 0,
|
||||
CreatedAt: time.Now().Unix(),
|
||||
}); err != nil {
|
||||
a.logger.Warn("记录密码登录日志失败", "account", cookieID, "err", err)
|
||||
a.logger.Warn("记录协议续期日志失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func passwordLoginFailureReason(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
msg := err.Error()
|
||||
if isPasswordLoginBadCredentials(msg) {
|
||||
return "bad_credentials"
|
||||
}
|
||||
event := browser.PasswordLoginEventFromError(err)
|
||||
if event.Reason != "" {
|
||||
return event.Reason
|
||||
}
|
||||
if event.Status == browser.PasswordLoginStatusVerificationRequired {
|
||||
return "verification_required"
|
||||
}
|
||||
return "other"
|
||||
}
|
||||
|
||||
func truncateMessage(s string, n int) string {
|
||||
if n <= 0 || len(s) <= n {
|
||||
return s
|
||||
@@ -607,7 +514,7 @@ func truncateMessage(s string, n int) string {
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieDetail) (bool, error) {
|
||||
func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookieDetail) (bool, error) {
|
||||
if d == nil {
|
||||
return false, nil
|
||||
}
|
||||
@@ -619,7 +526,7 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
}
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
|
||||
if completeSnapshot != nil {
|
||||
// Chromium/API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// 服务端删除和新的 Domain/Path/expiry 属性。
|
||||
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
|
||||
}
|
||||
@@ -640,37 +547,11 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
}
|
||||
return nil
|
||||
}
|
||||
apiRenew := func(cookieStr string) (*xrenew.Result, error) {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
return api.RenewAPIFirst(runCtx, cookieStr, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
}
|
||||
browserRenew := func(cookieStr string) (string, []cookierefresh.BrowserCookie, error) {
|
||||
if a.browser == nil {
|
||||
return "", nil, fmt.Errorf("浏览器自动化未启用")
|
||||
}
|
||||
if br, ok := a.browser.(browserQuickSnapshotRenewer); ok {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
snapshot := cookierefresh.SnapshotFromMetadata(d.MetadataJSON)
|
||||
return br.BrowserQuickRenewSnapshot(runCtx, d.ID, cookieStr, snapshot, browser.ResolveHeadless(d.ShowBrowser))
|
||||
}
|
||||
if br, ok := a.browser.(browserQuickRenewer); ok {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
renewed, err := br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
return renewed, nil, err
|
||||
}
|
||||
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return browser.MarshalCookies(m), nil, nil
|
||||
}
|
||||
|
||||
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
|
||||
// 决定是否调用 silentHasLogin;不存在 havana_lgc2_77 浏览器优先分支。
|
||||
res, err := apiRenew(current)
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
res, err := api.RenewAPIFirst(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
@@ -682,90 +563,58 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
|
||||
if saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingProtocolRenew(d.ID, res)
|
||||
// 官网 Promise 超时只记录错误,不把当前登录态判定为失效。
|
||||
return true, nil
|
||||
}
|
||||
if err == nil && res.Success {
|
||||
a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
|
||||
a.logger.Info("Go 协议续期成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
browserInput := current
|
||||
if res != nil && strings.TrimSpace(res.NewCookies) != "" {
|
||||
browserInput = res.NewCookies
|
||||
}
|
||||
browserCookies, browserSnapshot, err := browserRenew(browserInput)
|
||||
browserSaved := false
|
||||
if browserSnapshot != nil {
|
||||
if saveErr := save(browserCookies, nil, browserSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
browserSaved = true
|
||||
}
|
||||
if err != nil || (browserCookies == "" && browserSnapshot == nil) {
|
||||
if errors.Is(err, browser.ErrSecurityVerification) {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if !browserSaved {
|
||||
if err := save(browserCookies, nil, browserSnapshot); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
|
||||
return true, nil
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (a *Adapter) handlePasswordLoginError(ctx context.Context, cookieID string, err error) {
|
||||
msg := err.Error()
|
||||
a.logger.Warn("密码登录刷新失败", "account", cookieID, "err", err)
|
||||
if isPasswordLoginDisableError(msg) {
|
||||
_ = a.store.Cookies.SetStatusWithReason(ctx, cookieID, false, msg)
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventAccountDisabled, engine.AlertLevelCritical, "账号已自动禁用", msg)
|
||||
if isPasswordLoginBadCredentials(msg) {
|
||||
a.markPasswordError(cookieID)
|
||||
}
|
||||
func (a *Adapter) watchPendingProtocolRenew(cookieID string, result *xrenew.Result) {
|
||||
if result == nil || !result.HasPending() || a.store == nil || a.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
if isPasswordLoginRetryableVerification(msg) {
|
||||
a.markPasswordError(cookieID)
|
||||
}
|
||||
}
|
||||
|
||||
func isPasswordLoginBadCredentials(msg string) bool {
|
||||
return strings.Contains(msg, "账密错误") ||
|
||||
strings.Contains(msg, "账号密码错误") ||
|
||||
strings.Contains(msg, "用户名或密码错误") ||
|
||||
strings.Contains(msg, "账号或密码错误") ||
|
||||
strings.Contains(msg, "密码错误")
|
||||
}
|
||||
|
||||
func isPasswordLoginDisableError(msg string) bool {
|
||||
return isPasswordLoginBadCredentials(msg) ||
|
||||
strings.Contains(msg, "账号不存在") ||
|
||||
strings.Contains(msg, "账号已被冻结") ||
|
||||
strings.Contains(msg, "账号被冻结") ||
|
||||
strings.Contains(msg, "账户被冻结") ||
|
||||
strings.Contains(msg, "账号已锁定") ||
|
||||
strings.Contains(msg, "账户已锁定") ||
|
||||
strings.Contains(msg, "操作过于频繁") ||
|
||||
strings.Contains(msg, "登录过于频繁") ||
|
||||
strings.Contains(msg, "暂时无法登录")
|
||||
}
|
||||
|
||||
func isPasswordLoginRetryableVerification(msg string) bool {
|
||||
event := browser.PasswordLoginEventFromMessage(msg)
|
||||
return event.Reason == "baxia_punish_captcha" ||
|
||||
event.Status == browser.PasswordLoginStatusVerificationRequired ||
|
||||
strings.Contains(msg, "人工验证") ||
|
||||
strings.Contains(msg, "人脸验证") ||
|
||||
strings.Contains(msg, "身份验证")
|
||||
}
|
||||
|
||||
func (a *Adapter) markPasswordError(cookieID string) {
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
cooldown.MarkPasswordError(cookieID)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("等待协议续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := a.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := xrenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
a.logger.Warn("保存协议续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
}
|
||||
if a.store.Tokens != nil {
|
||||
_ = a.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
a.logger.Info("已异步接收协议续期迟到 Cookie", "account", cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("协议续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// 编译期保证 *Adapter 同时实现 engine.Handler 与 automation.OrderDetailFetcher。
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/browser"
|
||||
@@ -54,6 +55,19 @@ type fakeBrowser struct {
|
||||
providerUpdated string
|
||||
}
|
||||
|
||||
type fakeSnapshotBrowser struct {
|
||||
fakeBrowser
|
||||
snapshotCookies string
|
||||
snapshot []cookierefresh.BrowserCookie
|
||||
snapshotErr error
|
||||
snapshotCalls int
|
||||
}
|
||||
|
||||
func (f *fakeSnapshotBrowser) TokenCaptchaCookieSnapshot(context.Context, string, bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
f.snapshotCalls++
|
||||
return f.snapshotCookies, f.snapshot, f.snapshotErr
|
||||
}
|
||||
|
||||
func (f *fakeBrowser) FetchOrderDetail(_ context.Context, _, _, _ string, _ ...bool) (*browser.OrderDetail, error) {
|
||||
return f.fetchDetail, f.fetchErr
|
||||
}
|
||||
@@ -83,6 +97,17 @@ type fakeCaptchaRequester struct {
|
||||
gotDeviceID string
|
||||
}
|
||||
|
||||
type fakeOrderDetailClient struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.calls++
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error) {
|
||||
f.calls++
|
||||
f.gotCookies = cookiesStr
|
||||
@@ -229,6 +254,45 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnTokenCaptchaVerificationPersistsExactBrowserJar(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
browserSnapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
|
||||
{Name: "x5sec", Value: "fresh", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true, Expires: float64(time.Now().Add(time.Hour).Unix())},
|
||||
}
|
||||
fb := &fakeSnapshotBrowser{
|
||||
fakeBrowser: fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=fresh"},
|
||||
snapshotCookies: "unb=1; x5sec=fresh",
|
||||
snapshot: browserSnapshot,
|
||||
}
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
a.SetTokenCaptchaRequester(&fakeCaptchaRequester{})
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://passport.goofish.com/punish", "device")
|
||||
if !ok || result == nil || !result.CookieSnapshotComplete || fb.snapshotCalls != 1 {
|
||||
t.Fatalf("result=%+v ok=%v snapshot_calls=%d", result, ok, fb.snapshotCalls)
|
||||
}
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if !complete || len(saved) != 2 || detail.Value != "unb=1; x5sec=fresh" {
|
||||
t.Fatalf("滑块完整 Jar 未保存: value=%q complete=%v snapshot=%+v", detail.Value, complete, saved)
|
||||
}
|
||||
var exactX5 bool
|
||||
for _, cookie := range saved {
|
||||
if cookie.Name == "x5sec" && cookie.HTTPOnly && cookie.Secure && cookie.Expires > 0 {
|
||||
exactX5 = true
|
||||
}
|
||||
}
|
||||
if !exactX5 {
|
||||
t.Fatalf("x5sec 属性被扁平化: %+v", saved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSystemEvent_UninjectedSafe 未注入 automation 时安全返回 nil。
|
||||
func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
@@ -257,32 +321,33 @@ func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_BrowserNilReturnsError 本地缺字段且浏览器未启用时返回明确错误。
|
||||
func TestFetchOrderDetail_BrowserNilReturnsError(t *testing.T) {
|
||||
// TestFetchOrderDetail_MTopNilReturnsError 本地缺字段且 MTOP 客户端未配置时返回明确错误。
|
||||
func TestFetchOrderDetail_MTopNilReturnsError(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
a := New(store, nil, nil)
|
||||
a.SetOrderDetailClient(nil)
|
||||
_, err := a.FetchOrderDetail(context.Background(), "cid", "o-missing", "item-1", "buyer-1", "cookie")
|
||||
if err == nil {
|
||||
t.Fatal("browser=nil 且本地缺失应返回错误")
|
||||
t.Fatal("MTOP=nil 且本地缺失应返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_BrowserFallback 本地缺失但有浏览器时调用浏览器抓取并保存刷新的 cookie。
|
||||
func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
|
||||
// TestFetchOrderDetail_GoMTop 本地缺失时调用 Go MTOP 并保存响应 Cookie。
|
||||
func TestFetchOrderDetail_GoMTop(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(&fakeBrowser{
|
||||
fetchDetail: &browser.OrderDetail{
|
||||
a.SetOrderDetailClient(&fakeOrderDetailClient{
|
||||
detail: &mtop.OrderDetailResult{
|
||||
Quantity: "2", SpecName: "套餐", SpecValue: "30天", Amount: "19.8",
|
||||
UpdatedCookies: "unb=1; _m_h5_tk=newtoken;",
|
||||
},
|
||||
})
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "o-fallback", "item-1", "buyer-1", "old-cookie")
|
||||
if err != nil {
|
||||
t.Fatalf("浏览器兜底应成功: %v", err)
|
||||
t.Fatalf("Go MTOP 应成功: %v", err)
|
||||
}
|
||||
if detail.SpecValue != "30天" || detail.Amount != "19.8" {
|
||||
t.Fatalf("detail=%+v", detail)
|
||||
@@ -294,18 +359,13 @@ func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchOrderDetail_PersistsAuthoritativeBrowserJar(t *testing.T) {
|
||||
func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/"},
|
||||
{Name: "api_only", Value: "scoped", Domain: "h5api.m.goofish.com", Path: "/h5", HTTPOnly: true, Secure: true},
|
||||
}
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(&fakeBrowser{fetchDetail: &browser.OrderDetail{
|
||||
Quantity: "1", Amount: "9.9", UpdatedCookies: "unb=1",
|
||||
CookieSnapshot: snapshot, CookieSnapshotComplete: true,
|
||||
a.SetOrderDetailClient(&fakeOrderDetailClient{detail: &mtop.OrderDetailResult{
|
||||
Quantity: "1", Amount: "9.9", UpdatedCookies: "unb=1; api_only=scoped",
|
||||
}})
|
||||
if _, err := a.FetchOrderDetail(ctx, "cid", "o-jar", "item-1", "buyer-1", "old-cookie"); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -314,9 +374,9 @@ func TestFetchOrderDetail_PersistsAuthoritativeBrowserJar(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if !complete || len(got) != 2 || detail.Value != "unb=1" {
|
||||
t.Fatalf("authoritative jar not persisted: value=%q complete=%v snapshot=%+v", detail.Value, complete, got)
|
||||
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
|
||||
if complete || detail.Value != "unb=1; api_only=scoped" {
|
||||
t.Fatalf("Go MTOP flat cookie not persisted: value=%q complete=%v", detail.Value, complete)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,8 +415,8 @@ func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing
|
||||
t.Fatal("browser=nil 且接口续期失败时应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(context.Background(), "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "browser_disabled" {
|
||||
t.Fatalf("浏览器不可用应记录 browser_disabled: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || logs[0].Method != "protocol" {
|
||||
t.Fatalf("协议续期失败应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -373,17 +433,17 @@ func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("账号未配用户名/密码应返回 false")
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("未配置账号密码应自动停用账号,避免持续重试")
|
||||
if !store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("Go 客户端不得因未配置密码停用账号")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "no_credentials" || logs[0].FailureReason != "no_credentials" {
|
||||
t.Fatalf("无凭据应记录 no_credentials 日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserRenewSuccess 无账密时旧 Cookie 仍可快速续期,应保存新 Cookie 并跳过密码登录。
|
||||
func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
|
||||
// TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew 协议失败后不得调用浏览器续期。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -397,30 +457,23 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("快速续期成功应返回 true")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
if fb.renewCalls != 1 {
|
||||
t.Fatalf("CookieRenew 应调用一次,got %d", fb.renewCalls)
|
||||
if fb.renewCalls != 0 {
|
||||
t.Fatalf("不得调用浏览器 CookieRenew,got %d", fb.renewCalls)
|
||||
}
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if !strings.Contains(saved, "_m_h5_tk=renewed") {
|
||||
t.Fatalf("快速续期 cookie 未保存: %q", saved)
|
||||
}
|
||||
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did-old" {
|
||||
t.Fatalf("Cookie 更新后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("快速续期应记录登录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_Success 配好凭据后浏览器登录成功,cookie 被保存。
|
||||
func TestOnPasswordLoginRefresh_Success(t *testing.T) {
|
||||
// TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin 配好密码也不得启动 Chromium 登录。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -433,26 +486,22 @@ func TestOnPasswordLoginRefresh_Success(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("登录成功应返回 true")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
if fb.loginCalls != 1 {
|
||||
t.Fatalf("PasswordLogin 应调用一次,got %d", fb.loginCalls)
|
||||
}
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if saved == "" {
|
||||
t.Fatal("刷新的 cookie 应已保存")
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用 Chromium PasswordLogin,got %d", fb.loginCalls)
|
||||
}
|
||||
d, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetDetails: %v", err)
|
||||
}
|
||||
if d.LoginMethod != "password" || d.LastLoginAt == 0 {
|
||||
t.Fatalf("密码登录成功后应标记登录审计字段: %+v", d)
|
||||
if d.LoginMethod == "password" {
|
||||
t.Fatalf("不得标记密码登录: %+v", d)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
|
||||
t.Fatalf("密码登录成功应记录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,8 +525,8 @@ func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
|
||||
t.Fatal("验证失败后的账密错误冷却期应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "password_error_cooldown" || logs[1].FailureReason != "verification_required" {
|
||||
t.Fatalf("密码登录失败应记录日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -497,8 +546,8 @@ func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
|
||||
t.Fatal("风控失败应返回 false")
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "baxia_punish_captcha" {
|
||||
t.Fatalf("baxia 风控应记录专用 failure_reason: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
if !store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("baxia 风控只应冷却,不应停用账号")
|
||||
@@ -520,8 +569,8 @@ func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("冻结账号登录失败应返回 false")
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("冻结账号登录错误应停用账号")
|
||||
if !store.Cookies.GetStatus(ctx, "cid") || fb.loginCalls != 0 {
|
||||
t.Fatal("未执行密码登录时不得按浏览器页面错误停用账号")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,18 +603,18 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetBrowser(fb)
|
||||
if !a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("首次应成功")
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("协议续期失败应返回 false")
|
||||
}
|
||||
// 第二次在冷却期内,应被拒绝且不调用浏览器。
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("冷却期内应返回 false")
|
||||
}
|
||||
if fb.loginCalls != 1 {
|
||||
t.Fatalf("冷却期内不应调用浏览器,got calls=%d", fb.loginCalls)
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("任何一次都不应调用浏览器,got calls=%d", fb.loginCalls)
|
||||
}
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 2 || logs[0].Status != "skipped_cooldown" || logs[0].FailureReason != "login_cooldown" {
|
||||
t.Fatalf("冷却拒绝应记录 skipped_cooldown 日志: logs=%#v err=%v", logs, err)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("协议失败应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
@@ -763,10 +763,11 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
var persistenceErrs []error
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
sessionHandled := false
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
// 完整 Jar 已接管时,即使响应没有 Cookie 变化,也不能因扁平字符串
|
||||
// 格式差异回退覆盖并清除 Jar。
|
||||
sessionHandled := snapshot != nil
|
||||
if changed {
|
||||
sessionHandled = true
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
|
||||
|
||||
@@ -147,7 +147,7 @@ func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentKeepsFlatMockFallbackWhenSessionUnchanged(t *testing.T) {
|
||||
func TestConfirmShipmentKeepsAuthoritativeSnapshotWhenSessionUnchanged(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
@@ -173,14 +173,50 @@ func TestConfirmShipmentKeepsFlatMockFallbackWhenSessionUnchanged(t *testing.T)
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if detail.Value != initial {
|
||||
t.Fatalf("完整 Jar 未变化时不得被扁平/mock 返回覆盖: %q", detail.Value)
|
||||
}
|
||||
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); !ok || len(snapshot) != 2 {
|
||||
t.Fatalf("完整 Jar 未变化时必须继续保留: ok=%v snapshot=%+v metadata=%s", ok, snapshot, detail.MetadataJSON)
|
||||
}
|
||||
if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
|
||||
t.Fatalf("保留 snapshot 时丢失其他 metadata: %s", detail.MetadataJSON)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 0 {
|
||||
t.Fatalf("被忽略的扁平/mock 返回不得同步运行实例: %+v", sender.cookieUpdates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfirmShipmentKeepsFlatMockFallbackWithoutSnapshot(t *testing.T) {
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
initial := "unb=123; _m_h5_tk=old_1;"
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, `{"preserved":true}`, 1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated := "unb=123; _m_h5_tk=mock_new_2;"
|
||||
sender := &testSender{}
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
|
||||
err := center.confirmShipment(ctx, Task{
|
||||
AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
|
||||
t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
|
||||
}
|
||||
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if detail.Value != updated {
|
||||
t.Fatalf("session 未 changed 时未保留扁平/mock 写回路径: %q", detail.Value)
|
||||
t.Fatalf("无完整 Jar 时未保留扁平/mock 写回路径: %q", detail.Value)
|
||||
}
|
||||
if _, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
|
||||
t.Fatalf("扁平 mock 结果不得伪装成权威 Jar: %s", detail.MetadataJSON)
|
||||
}
|
||||
if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
|
||||
t.Fatalf("清理旧 snapshot 时丢失其他 metadata: %s", detail.MetadataJSON)
|
||||
t.Fatalf("扁平写回时丢失其他 metadata: %s", detail.MetadataJSON)
|
||||
}
|
||||
if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != updated {
|
||||
t.Fatalf("扁平/mock 更新未同步运行实例: %+v", sender.cookieUpdates)
|
||||
|
||||
@@ -87,16 +87,3 @@ func TestSilentHasLoginURLMatcher(t *testing.T) {
|
||||
t.Fatal("ordinary hasLogin request must not be treated as silentHasLogin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenPageURLPatternIsLimitedToIMDocument(t *testing.T) {
|
||||
for _, rawURL := range []string{goofishIMURL, goofishIMURL + "?spm=test", goofishIMURL + "#messages"} {
|
||||
if !tokenPageURLPattern.MatchString(rawURL) {
|
||||
t.Fatalf("expected token page URL match: %s", rawURL)
|
||||
}
|
||||
}
|
||||
for _, rawURL := range []string{goofishHomeURL, goofishIMURL + "/other", "https://h5api.m.goofish.com/im"} {
|
||||
if tokenPageURLPattern.MatchString(rawURL) {
|
||||
t.Fatalf("unexpected token page URL match: %s", rawURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// TokenCaptchaCookieSnapshot 在滑块引擎退出并释放持久化 Profile 后,重新打开
|
||||
// 同一 Profile 读取最终 Cookie Jar。它不访问任何业务页面,只用于把滑块验证
|
||||
// 已经产生的精确 Domain/Path/HttpOnly/Expires 属性交回 Go 凭证层。
|
||||
func (m *Manager) TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, "", nil, quickRenewHeadless(headless), true)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
defer release()
|
||||
return readAuthoritativeCookieJar(bctx, goofishIMURL)
|
||||
}
|
||||
|
||||
// syncCredentialCookies 为 token 滑块上下文同步 Cookie。普通登录、
|
||||
// 续期、MTOP、Token 和 WebSocket 生产流程不得调用 Chromium。
|
||||
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
|
||||
if len(snapshots) > 0 && snapshots[0] != nil {
|
||||
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(preserved) == 0 {
|
||||
return nil
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
incoming := parseCookieStr(cookieStr)
|
||||
if len(incoming) == 0 {
|
||||
return fmt.Errorf("Cookie为空或格式错误")
|
||||
}
|
||||
existing, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
preserved := credentialCookieSnapshotForURL(cookieSnapshotFromPlaywright(existing), incoming, goofishIMURL)
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
|
||||
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
|
||||
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
|
||||
}
|
||||
|
||||
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
|
||||
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
|
||||
matched := make(map[string]bool, len(incoming))
|
||||
counts := make(map[string]int, len(existing))
|
||||
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
|
||||
counts[cookie.Name]++
|
||||
}
|
||||
for _, cookie := range existing {
|
||||
if !cookieScopeMatches(cookie, rawURL) {
|
||||
if value, ok := incoming[cookie.Name]; ok {
|
||||
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
|
||||
cookie.Value = value
|
||||
}
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
continue
|
||||
}
|
||||
value, ok := incoming[cookie.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if counts[cookie.Name] == 1 {
|
||||
cookie.Value = value
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
for name, value := range incoming {
|
||||
if matched[name] {
|
||||
continue
|
||||
}
|
||||
preserved = append(preserved, cookierefresh.BrowserCookie{
|
||||
Name: name, Value: value, Domain: goofishDot, Path: "/", Secure: true,
|
||||
})
|
||||
}
|
||||
return cookierefresh.NormalizeSnapshot(preserved)
|
||||
}
|
||||
|
||||
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
|
||||
return header != ""
|
||||
}
|
||||
|
||||
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
|
||||
return header
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
package browser
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/playwright-community/playwright-go"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
const tokenRequestTimeoutMS = 20000
|
||||
|
||||
var tokenPageURLPattern = regexp.MustCompile(`^https://www\.goofish\.com/im(?:[?#].*)?$`)
|
||||
|
||||
// ExecuteTokenRequest sends the signed token request from a real Chromium page
|
||||
// so TLS, UA, Client Hints, Origin, Referer and the browser cookie jar all agree.
|
||||
func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowserRequest) (*mtop.TokenBrowserResponse, error) {
|
||||
if strings.TrimSpace(req.URL) == "" || (strings.TrimSpace(req.Cookies) == "" && req.CookieSnapshot == nil) {
|
||||
return nil, fmt.Errorf("浏览器 token 请求参数不完整")
|
||||
}
|
||||
credentialCookies := req.Cookies
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(req.CookieSnapshot, goofishIMURL, "https://goofish.com", time.Now()); authoritative {
|
||||
credentialCookies = scoped
|
||||
}
|
||||
unb := protocol.TransCookies(credentialCookies)["unb"]
|
||||
if unb == "" {
|
||||
return nil, fmt.Errorf("浏览器 token 请求缺少 unb")
|
||||
}
|
||||
credentialID := "token_credential_" + unb
|
||||
lock := m.accountRenewLock(credentialID)
|
||||
lock.Lock()
|
||||
defer lock.Unlock()
|
||||
|
||||
page, bctx, releaseEntry, err := m.tokenRequestPage(ctx, credentialID, req.Cookies, req.CookieSnapshot)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer releaseEntry()
|
||||
m.touch(credentialID)
|
||||
value, err := page.Evaluate(`async ({url, body, timeout}) => {
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), timeout);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
signal: controller.signal,
|
||||
headers: {
|
||||
'accept': 'application/json',
|
||||
'content-type': 'application/x-www-form-urlencoded'
|
||||
},
|
||||
body
|
||||
});
|
||||
return {status: response.status, body: await response.text()};
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}`, map[string]any{"url": req.URL, "body": req.Body, "timeout": tokenRequestTimeoutMS})
|
||||
evalErr := err
|
||||
all, cookieErr := bctx.Cookies()
|
||||
if cookieErr != nil {
|
||||
return nil, errors.Join(wrapTokenBrowserEvalError(evalErr), fmt.Errorf("读取浏览器 token Cookie: %w", cookieErr))
|
||||
}
|
||||
snapshot := cookieSnapshotFromPlaywright(all)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
browserCookies := currentCookieHeader(snapshot, goofishIMURL)
|
||||
response := &mtop.TokenBrowserResponse{
|
||||
UpdatedCookies: browserCookies,
|
||||
CookieSnapshot: snapshot,
|
||||
CookieSnapshotComplete: true,
|
||||
}
|
||||
if evalErr != nil {
|
||||
return response, fmt.Errorf("浏览器执行 token fetch: %w", evalErr)
|
||||
}
|
||||
raw, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return response, err
|
||||
}
|
||||
var result struct {
|
||||
Status int `json:"status"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &result); err != nil {
|
||||
return response, fmt.Errorf("解析浏览器 token 响应: %w", err)
|
||||
}
|
||||
response.Status = result.Status
|
||||
response.Body = []byte(result.Body)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func wrapTokenBrowserEvalError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("浏览器执行 token fetch: %w", err)
|
||||
}
|
||||
|
||||
// tokenRequestPage keeps one inert /im document for each account credential.
|
||||
// Its URL and origin are identical to the official message page, so Chromium
|
||||
// supplies the same Referer/Origin/Cookie/Client-Hints context for token fetches.
|
||||
// The main document is fulfilled locally on first use: loading the full SPA on
|
||||
// every reconnect would start another official WebSocket and rerun auto-login,
|
||||
// neither of which happens for a normal reconnect in an already-open /im tab.
|
||||
func (m *Manager) tokenRequestPage(ctx context.Context, credentialID, cookieStr string, snapshot []cookierefresh.BrowserCookie) (playwright.Page, playwright.BrowserContext, func(), error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
if err := m.init(); err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
entry, err := m.acquireEntry(credentialID, cookieStr, true)
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
release := func() { m.releaseEntry(credentialID, entry) }
|
||||
if err := syncCredentialCookies(entry.context, cookieStr, snapshot); err != nil {
|
||||
release()
|
||||
m.evict(credentialID)
|
||||
return nil, nil, nil, fmt.Errorf("浏览器 token 请求同步 Cookie: %w", err)
|
||||
}
|
||||
for _, candidate := range entry.context.Pages() {
|
||||
if !candidate.IsClosed() && tokenPageURLPattern.MatchString(candidate.URL()) {
|
||||
return candidate, entry.context, release, nil
|
||||
}
|
||||
}
|
||||
|
||||
page, err := entry.context.NewPage()
|
||||
if err != nil {
|
||||
release()
|
||||
m.evict(credentialID)
|
||||
return nil, nil, nil, fmt.Errorf("浏览器 token 请求新建消息页: %w", err)
|
||||
}
|
||||
route := func(route playwright.Route) {
|
||||
request := route.Request()
|
||||
if request.IsNavigationRequest() && request.ResourceType() == "document" {
|
||||
_ = route.Fulfill(playwright.RouteFulfillOptions{
|
||||
Status: playwright.Int(200),
|
||||
ContentType: playwright.String("text/html; charset=utf-8"),
|
||||
Body: playwright.String("<!doctype html><html><head><meta charset=\"utf-8\"><title>Goofish IM</title></head><body></body></html>"),
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = route.Continue()
|
||||
}
|
||||
if err := page.Route(tokenPageURLPattern, route, 1); err != nil {
|
||||
_ = page.Close()
|
||||
release()
|
||||
m.evict(credentialID)
|
||||
return nil, nil, nil, fmt.Errorf("浏览器 token 请求初始化消息页路由: %w", err)
|
||||
}
|
||||
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
|
||||
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
|
||||
Timeout: playwright.Float(15000),
|
||||
}); err != nil {
|
||||
_ = page.Close()
|
||||
release()
|
||||
m.evict(credentialID)
|
||||
return nil, nil, nil, fmt.Errorf("浏览器 token 请求初始化消息页: %w", err)
|
||||
}
|
||||
return page, entry.context, release, nil
|
||||
}
|
||||
|
||||
// syncCredentialCookies updates a reused credential context without flattening
|
||||
// attributes already observed from Chromium. Unknown cookies use the narrow
|
||||
// goofish default only on their first import; later server updates retain their
|
||||
// real domain, path, expiry, SameSite, Secure and HttpOnly fields.
|
||||
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
|
||||
if len(snapshots) > 0 && snapshots[0] != nil {
|
||||
// A Chromium snapshot is the complete authoritative jar, including an
|
||||
// explicitly empty jar. Do not flatten it through cookieStr: doing so
|
||||
// loses scopes and can resurrect cookies Chromium already deleted.
|
||||
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(preserved) == 0 {
|
||||
return nil
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
incoming := parseCookieStr(cookieStr)
|
||||
if len(incoming) == 0 {
|
||||
return fmt.Errorf("Cookie为空或格式错误")
|
||||
}
|
||||
existing, err := bctx.Cookies()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
basis := cookieSnapshotFromPlaywright(existing)
|
||||
preserved := credentialCookieSnapshotForURL(basis, incoming, goofishIMURL)
|
||||
if err := bctx.ClearCookies(); err != nil {
|
||||
return err
|
||||
}
|
||||
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
|
||||
}
|
||||
|
||||
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
|
||||
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
|
||||
}
|
||||
|
||||
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
|
||||
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
|
||||
matched := make(map[string]bool, len(incoming))
|
||||
counts := make(map[string]int, len(existing))
|
||||
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
|
||||
counts[cookie.Name]++
|
||||
}
|
||||
for _, cookie := range existing {
|
||||
// A flat Cookie header only describes cookies applicable to its source
|
||||
// URL. Keep absent cookies for passport/other paths untouched; otherwise
|
||||
// a goofish header would silently erase the rest of Chromium's jar. When
|
||||
// the flat representation does carry the same name, update its value for
|
||||
// backward compatibility with historical all-domain flattened snapshots.
|
||||
if !cookieScopeMatches(cookie, rawURL) {
|
||||
if value, ok := incoming[cookie.Name]; ok {
|
||||
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
|
||||
cookie.Value = value
|
||||
}
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
continue
|
||||
}
|
||||
value, ok := incoming[cookie.Name]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// A flat string cannot identify which Domain/Path/PartitionKey owns a
|
||||
// value when the same name occurs more than once. Preserve those scoped
|
||||
// values instead of corrupting every variant with one ambiguous value.
|
||||
if counts[cookie.Name] == 1 {
|
||||
cookie.Value = value
|
||||
}
|
||||
preserved = append(preserved, cookie)
|
||||
matched[cookie.Name] = true
|
||||
}
|
||||
for name, value := range incoming {
|
||||
if matched[name] {
|
||||
continue
|
||||
}
|
||||
preserved = append(preserved, cookierefresh.BrowserCookie{
|
||||
Name: name, Value: value, Domain: goofishDot, Path: "/", Secure: true,
|
||||
})
|
||||
}
|
||||
return cookierefresh.NormalizeSnapshot(preserved)
|
||||
}
|
||||
|
||||
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
|
||||
return header != ""
|
||||
}
|
||||
|
||||
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
|
||||
return header
|
||||
}
|
||||
+94
-70
@@ -70,7 +70,8 @@ type Handler interface {
|
||||
// HandleSystemEvent 处理平台系统事件。系统卡片永远不进入 AI 回复链,
|
||||
// 这里只把事件交给自动化中心,由自动化规则决定是否执行。
|
||||
HandleSystemEvent(ctx context.Context, task automation.Task) error
|
||||
// OnPasswordLoginRefresh 连续失败时触发浏览器密码登录刷新;返回是否成功。
|
||||
// OnPasswordLoginRefresh 是历史接口名;连续失败时只触发 Go 协议续期,
|
||||
// 不得启动浏览器密码登录。
|
||||
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
|
||||
// OnAccountAlert 账号告警通知(token 失效/自动恢复失败/风控验证等)。
|
||||
// level 取 AlertLevel* 常量。实现方应把告警推送到该账号绑定的通知渠道。
|
||||
@@ -138,13 +139,12 @@ type Account struct {
|
||||
CookieStr string
|
||||
UserID string // unb(myid)
|
||||
|
||||
store *db.Store
|
||||
mtop mtop.Client
|
||||
renewer cookieRenewer
|
||||
startupRenewer accountStartupRenewer
|
||||
wsDialer WSDialer
|
||||
handler Handler
|
||||
logger *slog.Logger
|
||||
store *db.Store
|
||||
mtop mtop.Client
|
||||
renewer cookieRenewer
|
||||
wsDialer WSDialer
|
||||
handler Handler
|
||||
logger *slog.Logger
|
||||
|
||||
// 运行时状态(受 mu 保护)
|
||||
mu sync.Mutex
|
||||
@@ -229,12 +229,6 @@ type cookieRenewer interface {
|
||||
RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*renew.Result, error)
|
||||
}
|
||||
|
||||
// accountStartupRenewer 由装配层在 Chromium 可用时实现,让账号启动直接运行
|
||||
// 官网 /im 页面及其 auto-login plugin,而不是用 HTTP 猜测浏览器 Cookie 行为。
|
||||
type accountStartupRenewer interface {
|
||||
RenewAccountStartup(ctx context.Context, cookieID, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*renew.Result, error)
|
||||
}
|
||||
|
||||
type loginStatusChecker interface {
|
||||
CheckLoginStatusContext(ctx context.Context, cookiesStr string) (*mtop.LoginStatusResult, error)
|
||||
}
|
||||
@@ -279,10 +273,6 @@ func New(cfg Config) *Account {
|
||||
if renewer == nil && mtopWasNil {
|
||||
renewer = renew.Service{}
|
||||
}
|
||||
var startupRenewer accountStartupRenewer
|
||||
if cfg.Handler != nil {
|
||||
startupRenewer, _ = cfg.Handler.(accountStartupRenewer)
|
||||
}
|
||||
cookies := protocol.TransCookies(cfg.CookieStr)
|
||||
myid := cookies["unb"]
|
||||
wsDialer := cfg.WSDialer
|
||||
@@ -296,7 +286,6 @@ func New(cfg Config) *Account {
|
||||
store: cfg.Store,
|
||||
mtop: mtopClient,
|
||||
renewer: renewer,
|
||||
startupRenewer: startupRenewer,
|
||||
wsDialer: wsDialer,
|
||||
handler: cfg.Handler,
|
||||
logger: logger.With("account", cfg.CookieID),
|
||||
@@ -336,23 +325,17 @@ func (a *Account) Run(parent context.Context) error {
|
||||
a.logger.Info("账号在启动续期前已禁用")
|
||||
return nil
|
||||
}
|
||||
// 官网在 /im 页面启动时执行一次 auto-login plugin,成功后 reload 并重建
|
||||
// FishEngine。这里在首条 WebSocket 建立前完成等价续期;成功时只轮换
|
||||
// 页面级 device ID,UA 仍完全使用本地浏览器指纹实现。
|
||||
startupReloaded, startupErr := a.tryStartupAPIRenew(ctx)
|
||||
if startupErr != nil {
|
||||
// 官网 /im 启动时执行 auto-login plugin;成功后 location.reload() 会重建
|
||||
// FishEngine 和页面级 device ID。Go 客户端用 HTTP 复刻续期,并在成功时
|
||||
// 只重建这一本地运行时身份。续期失败不能用网页 DOM 阻断 token + WS;
|
||||
// Chromium 仅用于读取本机指纹和处理 token 滑块。
|
||||
if a.renewer != nil {
|
||||
if a.tryAPIRenew(ctx) {
|
||||
a.rotatePageDeviceID()
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
a.setRuntimeError(ctx, startupErr)
|
||||
if a.RuntimeStatus().State == RuntimeReconnecting {
|
||||
a.setRuntimeState(RuntimeAuthExpired, "消息页登录初始化失败,请重新登录")
|
||||
}
|
||||
a.notifyOffline(ctx, "消息页登录初始化失败:"+errString(startupErr))
|
||||
return startupErr
|
||||
}
|
||||
if startupReloaded {
|
||||
a.rotateDeviceID(a.currentCookieStr())
|
||||
}
|
||||
for {
|
||||
if ctx.Err() != nil {
|
||||
@@ -682,14 +665,14 @@ func (a *Account) beginTask() (context.Context, bool) {
|
||||
return ctx, true
|
||||
}
|
||||
|
||||
// handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。
|
||||
// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
|
||||
func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
credentialUnlock := func() {}
|
||||
if a.store != nil {
|
||||
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
|
||||
}
|
||||
defer credentialUnlock()
|
||||
a.logger.Warn("连续失败达上限,触发密码登录刷新", "failures", MaxConnectionFailures)
|
||||
a.logger.Warn("连续失败达上限,触发 Go 协议续期", "failures", MaxConnectionFailures)
|
||||
a.notifyRecoveringOffline(ctx, fmt.Sprintf("消息服务连续认证/连接失败 %d 次,开始自动恢复", MaxConnectionFailures))
|
||||
if a.handler != nil && a.handler.OnPasswordLoginRefresh(ctx, a.CookieID) {
|
||||
if d, err := a.store.Cookies.GetDetails(ctx, a.CookieID); err == nil && d != nil && d.Value != "" {
|
||||
@@ -697,7 +680,7 @@ func (a *Account) handleMaxFailures(ctx context.Context) error {
|
||||
a.clearCurrentToken()
|
||||
a.clearTokenCache(ctx)
|
||||
}
|
||||
a.logger.Info("密码登录刷新成功,重置失败计数")
|
||||
a.logger.Info("Go 协议续期成功,重置失败计数")
|
||||
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
|
||||
a.resetFailures()
|
||||
return sleepCtx(ctx, 2*time.Second)
|
||||
@@ -736,7 +719,7 @@ func (a *Account) notifyRecoveringOffline(ctx context.Context, reason string) {
|
||||
return
|
||||
}
|
||||
a.alertEvent(ctx, EventAccountOffline, AlertLevelWarn, "账号已掉线,正在自动恢复",
|
||||
fmt.Sprintf("账号 %s 出现登录凭证过期或认证掉线。原因:%s。系统会先发送本通知,再继续尝试轻量续期、浏览器续期或密码登录恢复。", a.CookieID, reason))
|
||||
fmt.Sprintf("账号 %s 出现登录凭证过期或认证掉线。原因:%s。系统会先发送本通知,再继续尝试 Go 协议续期;如仍失败则需要重新扫码登录。", a.CookieID, reason))
|
||||
}
|
||||
|
||||
func (a *Account) markOfflineNotified(reason string) bool {
|
||||
@@ -782,7 +765,7 @@ func formatTimeOrUnknown(t time.Time) string {
|
||||
}
|
||||
|
||||
// tryLoginStatusCheck 调用 mtop.taobao.idlemessage.pc.loginuser.get 做轻量登录态确认。
|
||||
// 这个接口的成本低于完整 token 刷新和浏览器动作,且可能顺手下发新的签名 Cookie;
|
||||
// 这个接口的成本低于完整 token 刷新,且可能顺手下发新的签名 Cookie;
|
||||
// 因此在 session 失效后、接口续期前先跑一遍,避免已实现的登录态检查能力闲置。
|
||||
func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResult {
|
||||
checker, ok := a.mtop.(loginStatusChecker)
|
||||
@@ -815,7 +798,7 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
|
||||
|
||||
// tryAPIRenew 是密码登录前的轻量恢复层,只执行官网 auto-login plugin 的
|
||||
// 单次 silentHasLogin 流程。如果只拿到部分 Cookie,仍先保存并清 token,
|
||||
// 但继续降级到浏览器/密码登录。
|
||||
// 但继续按 Go 协议执行后续恢复;仍失败时由上层要求重新扫码登录。
|
||||
func (a *Account) tryAPIRenew(ctx context.Context) bool {
|
||||
if a.renewer == nil {
|
||||
return false
|
||||
@@ -826,20 +809,6 @@ func (a *Account) tryAPIRenew(ctx context.Context) bool {
|
||||
return renewed
|
||||
}
|
||||
|
||||
func (a *Account) tryStartupAPIRenew(ctx context.Context) (bool, error) {
|
||||
if a.startupRenewer != nil {
|
||||
return a.tryAPIRenewUsing(ctx, func(runCtx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*renew.Result, error) {
|
||||
return a.startupRenewer.RenewAccountStartup(runCtx, a.CookieID, cookieStr, snapshot)
|
||||
})
|
||||
}
|
||||
if a.renewer == nil {
|
||||
return false, nil
|
||||
}
|
||||
return a.tryAPIRenewUsing(ctx, func(runCtx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*renew.Result, error) {
|
||||
return a.renewer.RenewAPIFirst(runCtx, cookieStr, snapshot)
|
||||
})
|
||||
}
|
||||
|
||||
func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Context, string, []cookierefresh.BrowserCookie) (*renew.Result, error)) (bool, error) {
|
||||
a.refreshMu.Lock()
|
||||
defer a.refreshMu.Unlock()
|
||||
@@ -879,6 +848,9 @@ func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Contex
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if res.HasPending() {
|
||||
a.watchPendingAPIRenew(res)
|
||||
}
|
||||
updated := false
|
||||
persisted := false
|
||||
if res.CookieSnapshotComplete && a.store != nil && a.store.Cookies != nil {
|
||||
@@ -887,12 +859,12 @@ func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Contex
|
||||
if detailErr == nil {
|
||||
detailErr = db.ErrNotFound
|
||||
}
|
||||
a.logger.Warn("保存浏览器续期 Cookie 快照失败", "err", detailErr)
|
||||
a.logger.Warn("保存续期 Cookie 快照失败", "err", detailErr)
|
||||
return false, detailErr
|
||||
}
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, res.CookieSnapshot)
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, res.NewCookies, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("保存浏览器续期 Cookie 快照失败", "err", err)
|
||||
a.logger.Warn("保存续期 Cookie 快照失败", "err", err)
|
||||
return false, err
|
||||
}
|
||||
persisted = true
|
||||
@@ -916,7 +888,7 @@ func (a *Account) tryAPIRenewUsing(ctx context.Context, call func(context.Contex
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
a.logger.Warn("接口续期失败,已保存浏览器最终 Cookie Jar", "err", err)
|
||||
a.logger.Warn("接口续期失败,已保存响应 Cookie", "err", err)
|
||||
return false, err
|
||||
}
|
||||
if res.Success {
|
||||
@@ -945,13 +917,65 @@ func (a *Account) persistRenewFlatCookie(ctx context.Context, newCookies string)
|
||||
}
|
||||
return db.ErrNotFound
|
||||
}
|
||||
// 没有浏览器权威 Jar 时,接口 Set-Cookie 只能更新兼容扁平值。不能把
|
||||
// 没有权威 Jar 时,接口 Set-Cookie 只能更新兼容扁平值。不能把
|
||||
// Domain/Path/HttpOnly/PartitionKey 均未知的 Cookie 伪造成完整快照。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
|
||||
return a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix())
|
||||
}
|
||||
|
||||
// adoptRecoveredCookie 统一接收“轻量检查/接口续期/浏览器恢复”拿到的新 Cookie。
|
||||
func (a *Account) watchPendingAPIRenew(result *renew.Result) {
|
||||
if result == nil || !result.HasPending() {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("等待静默续期底层响应失败", "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if persistErr := a.persistPendingRenewCookies(ctx, late); persistErr != nil {
|
||||
a.logger.Warn("保存静默续期迟到 Cookie 失败", "err", persistErr)
|
||||
return
|
||||
}
|
||||
if waitErr != nil {
|
||||
a.logger.Warn("静默续期底层响应失败,已保存响应 Cookie", "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (a *Account) persistPendingRenewCookies(ctx context.Context, result *renew.Result) error {
|
||||
if result == nil || len(result.SetCookies) == 0 || a.store == nil || a.store.Cookies == nil {
|
||||
return nil
|
||||
}
|
||||
a.refreshMu.Lock()
|
||||
defer a.refreshMu.Unlock()
|
||||
credentialUnlock := a.store.LockAccountCredentials(a.CookieID)
|
||||
defer credentialUnlock()
|
||||
detail, err := a.store.Cookies.GetDetails(ctx, a.CookieID)
|
||||
if err != nil || detail == nil {
|
||||
if err == nil {
|
||||
err = db.ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
newCookies, metadata, changed := renew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, result)
|
||||
if !changed {
|
||||
return nil
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, newCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
a.replaceCredentialState(newCookies, credentialStateFingerprint(newCookies, metadata))
|
||||
a.clearTokenCache(ctx)
|
||||
a.logger.Info("已异步接收官网静默续期迟到 Cookie", "updated", strings.Join(result.UpdatedCookieNames, ","))
|
||||
return nil
|
||||
}
|
||||
|
||||
// adoptRecoveredCookie 统一接收“轻量检查/接口续期”拿到的新 Cookie。
|
||||
// 官网页面在普通 Set-Cookie 更新后保持当前 FishEngine/device ID 与健康 WS;
|
||||
// 下一次重连才使用新 Cookie 获取新的连接级 accessToken。
|
||||
func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source string) bool {
|
||||
@@ -1258,13 +1282,13 @@ func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, device
|
||||
if !ok || result == nil || strings.TrimSpace(result.UpdatedCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
if a.store != nil && a.store.Cookies != nil {
|
||||
if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, result.UpdatedCookies); err != nil {
|
||||
a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", err)
|
||||
return nil, false
|
||||
}
|
||||
updatedCookies, persistErr := a.adoptTokenResponseCookies(ctx, cookieStr, result)
|
||||
if persistErr != nil {
|
||||
a.logger.Error("滑块验证后保存 cookie 失败", "cookie_id", a.CookieID, "err", persistErr)
|
||||
return nil, false
|
||||
}
|
||||
a.replaceCookieStr(result.UpdatedCookies)
|
||||
result.UpdatedCookies = updatedCookies
|
||||
a.replaceCookieStr(updatedCookies)
|
||||
a.clearTokenCache(ctx)
|
||||
a.setRuntimeState(RuntimeConnecting, tokenRiskRecoveryMessage)
|
||||
return result, true
|
||||
@@ -1554,13 +1578,13 @@ func (a *Account) replaceCredentialState(cookieStr, credentialFP string) {
|
||||
}
|
||||
}
|
||||
|
||||
// rotateDeviceID 仅在官网会执行 location.reload 的边界调用。普通 Cookie
|
||||
// Set-Cookie 更新和 WebSocket reconnect 都保持同一个页面级 device ID。
|
||||
func (a *Account) rotateDeviceID(cookieStr string) {
|
||||
userID := protocol.TransCookies(cookieStr)["unb"]
|
||||
// rotatePageDeviceID 对应官网 auto-login 成功后的 location.reload():
|
||||
// 新 FishEngine 使用新的 UUID-userID,普通 Set-Cookie 与自然重连不会调用它。
|
||||
func (a *Account) rotatePageDeviceID() {
|
||||
a.mu.Lock()
|
||||
userID := a.UserID
|
||||
if userID == "" {
|
||||
userID = a.UserID
|
||||
userID = protocol.TransCookies(a.CookieStr)["unb"]
|
||||
}
|
||||
a.deviceID = protocol.GenerateDeviceID(userID)
|
||||
a.mu.Unlock()
|
||||
@@ -1605,7 +1629,7 @@ func (a *Account) UpdateCookie(cookieStr string) {
|
||||
return
|
||||
}
|
||||
a.replaceCredentialState(cookieStr, credentialFP)
|
||||
// 浏览器 Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
|
||||
// Cookie Jar 的普通更新不会打断已经认证的 IMPaaS 连接。新 Cookie
|
||||
// 会在下一次自然重连前被重新读取并用于获取新的 accessToken。
|
||||
a.clearTokenCache(context.Background())
|
||||
}
|
||||
@@ -4,12 +4,15 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
@@ -359,6 +362,45 @@ func TestTryAPIRenewPersistsExplicitFlatCookieDeletionOnError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTryAPIRenewPersistsLatePromiseCookieWithoutRestart(t *testing.T) {
|
||||
acc, _, store, cleanup := newAccountForTest(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
oldFingerprint := xianyu.CurrentBrowserFingerprint()
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "Mozilla/5.0 (Macintosh) Chrome/999.0.0.0 Safari/537.36"})
|
||||
t.Cleanup(func() { xianyu.SetBrowserFingerprint(oldFingerprint) })
|
||||
initial := "unb=123; havana_lgc_exp=" + fmt.Sprint(time.Now().Add(time.Hour).UnixMilli())
|
||||
if err := store.Cookies.UpdateValueExisting(ctx, "cid", initial); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
acc.replaceCookieStr(initial)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: fmt.Sprint(time.Now().Add(time.Hour).UnixMilli()), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
acc.renewer = xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1,
|
||||
PromiseTimeout: 10 * time.Millisecond,
|
||||
}
|
||||
if acc.tryAPIRenew(ctx) {
|
||||
t.Fatal("Promise 超时不得伪装成同步续期成功")
|
||||
}
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err == nil && detail != nil && strings.Contains(detail.Value, "sdkSilent=") {
|
||||
if !strings.Contains(acc.currentCookieStr(), "sdkSilent=") {
|
||||
t.Fatalf("迟到 Cookie 已入库但未更新运行时: %q", acc.currentCookieStr())
|
||||
}
|
||||
return
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("迟到的 silentHasLogin Set-Cookie 未写回账号")
|
||||
}
|
||||
|
||||
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
|
||||
// 及告警去重逻辑(仅从非验证态进入验证态时告警一次)。
|
||||
func TestSetRuntimeError_AllBranches(t *testing.T) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
xrenew "xianyu-go/internal/xianyu/renew"
|
||||
"xianyu-go/internal/xianyu/ws"
|
||||
)
|
||||
|
||||
@@ -546,6 +547,78 @@ func TestRun_DisabledAccountExits(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_APIRenewFailureDoesNotBlockTokenAndWebSocket(t *testing.T) {
|
||||
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-after-renew-error"})
|
||||
defer cleanup()
|
||||
|
||||
renewer := &stubCookieRenewer{err: errors.New("startup API renewal failed")}
|
||||
acc.renewer = renewer
|
||||
conn := &fakeWSConn{recvBlock: true}
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
|
||||
waitForRegisteredToken(t, conn, "tok-after-renew-error")
|
||||
if renewer.calls != 1 {
|
||||
t.Fatalf("启动时协议续期调用次数=%d want=1", renewer.calls)
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run error=%v want context canceled", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Run did not stop after cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_APIRenewSuccessRebuildsOfficialPageDeviceID(t *testing.T) {
|
||||
tokenClient := &sequencedTokenMtop{}
|
||||
acc, _, _, cleanup := newRunAccount(t, tokenClient)
|
||||
defer cleanup()
|
||||
|
||||
acc.mu.Lock()
|
||||
initialDeviceID := acc.deviceID
|
||||
acc.mu.Unlock()
|
||||
acc.renewer = &stubCookieRenewer{result: &xrenew.Result{
|
||||
Success: true,
|
||||
RenewMethod: "auto_login_plugin",
|
||||
NewCookies: "unb=123; _m_h5_tk=tk_1;",
|
||||
}}
|
||||
conn := &fakeWSConn{recvBlock: true}
|
||||
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- acc.Run(ctx) }()
|
||||
|
||||
waitForRegisteredToken(t, conn, "fresh-1")
|
||||
conn.mu.Lock()
|
||||
registeredDeviceID := conn.registeredDID
|
||||
conn.mu.Unlock()
|
||||
if registeredDeviceID == initialDeviceID {
|
||||
t.Fatal("官网 auto-login 成功后的逻辑 reload 必须重建页面级 device ID")
|
||||
}
|
||||
tokenClient.mu.Lock()
|
||||
if len(tokenClient.devices) != 1 || tokenClient.devices[0] != registeredDeviceID {
|
||||
t.Fatalf("token 与 /reg 必须绑定同一新 device ID: token=%v reg=%q", tokenClient.devices, registeredDeviceID)
|
||||
}
|
||||
tokenClient.mu.Unlock()
|
||||
|
||||
cancel()
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("Run error=%v want context canceled", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("Run did not stop after cancellation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
|
||||
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
|
||||
defer cleanup()
|
||||
|
||||
+59
-211
@@ -7,13 +7,10 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/browser"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
@@ -21,17 +18,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
loginRenewInterval = 600 * time.Second
|
||||
cookiesRefreshInterval = 600 * time.Second
|
||||
apiCookieRenewInterval = 3600 * time.Second
|
||||
accountRequestInterval = time.Second
|
||||
browserInitialDelayMax = 30 * time.Minute
|
||||
browserSuccessDelayMin = 18 * time.Hour
|
||||
browserSuccessDelayRange = 6 * time.Hour
|
||||
disabledFailureLimit = 10
|
||||
sessionExpiredCooldown = 300 * time.Second
|
||||
passwordLoginCooldown = 300 * time.Second
|
||||
passwordErrorCooldown = 5 * time.Hour
|
||||
loginRenewInterval = 600 * time.Second
|
||||
cookiesRefreshInterval = 600 * time.Second
|
||||
apiCookieRenewInterval = 3600 * time.Second
|
||||
accountRequestInterval = time.Second
|
||||
sessionExpiredCooldown = 300 * time.Second
|
||||
passwordLoginCooldown = 300 * time.Second
|
||||
passwordErrorCooldown = 5 * time.Hour
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -51,11 +44,6 @@ type accountRestarter interface {
|
||||
Restart(ctx context.Context, cookieID string) error
|
||||
}
|
||||
|
||||
type BrowserRenewer interface {
|
||||
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
|
||||
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error)
|
||||
}
|
||||
|
||||
type PasswordRefresher interface {
|
||||
OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool
|
||||
}
|
||||
@@ -63,7 +51,6 @@ type PasswordRefresher interface {
|
||||
type Scheduler struct {
|
||||
store *db.Store
|
||||
starter AccountStarter
|
||||
browser BrowserRenewer
|
||||
refresher PasswordRefresher
|
||||
logger *slog.Logger
|
||||
mtop *mtop.ClientImpl
|
||||
@@ -71,14 +58,13 @@ type Scheduler struct {
|
||||
cooldown *CooldownManager
|
||||
}
|
||||
|
||||
func NewScheduler(store *db.Store, starter AccountStarter, browser BrowserRenewer, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
|
||||
func NewScheduler(store *db.Store, starter AccountStarter, refresher PasswordRefresher, logger *slog.Logger) *Scheduler {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Scheduler{
|
||||
store: store,
|
||||
starter: starter,
|
||||
browser: browserRenewerOrNil(browser),
|
||||
refresher: refresher,
|
||||
logger: logger,
|
||||
mtop: mtop.NewClient(),
|
||||
@@ -87,20 +73,6 @@ func NewScheduler(store *db.Store, starter AccountStarter, browser BrowserRenewe
|
||||
}
|
||||
}
|
||||
|
||||
func browserRenewerOrNil(browser BrowserRenewer) BrowserRenewer {
|
||||
if browser == nil {
|
||||
return nil
|
||||
}
|
||||
v := reflect.ValueOf(browser)
|
||||
switch v.Kind() {
|
||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
|
||||
if v.IsNil() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return browser
|
||||
}
|
||||
|
||||
func (s *Scheduler) Run(ctx context.Context) {
|
||||
if s == nil || s.store == nil {
|
||||
return
|
||||
@@ -109,7 +81,9 @@ func (s *Scheduler) Run(ctx context.Context) {
|
||||
// 官网静默插件只在页面/账号运行时启动时执行,不做每小时轮询。保留
|
||||
// 调度器入口供显式兼容配置使用,但默认关闭。
|
||||
go s.runFixed(ctx, "api_cookie_renew", apiCookieRenewEnabledSetting, apiCookieRenewIntervalSetting, false, apiCookieRenewInterval, s.executeAPICookieRenew)
|
||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeBrowserCookieRefresh)
|
||||
// 兼容原 cookies_refresh 配置名,但执行同一套 Go HTTP auto-login
|
||||
// 协议;Chromium 不参与普通 Cookie 续期。
|
||||
go s.runFixed(ctx, "cookies_refresh", cookiesRefreshEnabledSetting, cookiesRefreshIntervalSetting, false, cookiesRefreshInterval, s.executeAPICookieRenew)
|
||||
}
|
||||
|
||||
func (s *Scheduler) runFixed(ctx context.Context, name, settingKey, intervalKey string, defaultEnabled bool, defaultInterval time.Duration, fn func(context.Context)) {
|
||||
@@ -177,14 +151,15 @@ func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account d
|
||||
}
|
||||
res, callErr := s.mtop.CheckLoginStatusContext(mtopCtx, account.Value)
|
||||
|
||||
// Chromium 在收到响应头时就会应用 Set-Cookie。权威 session
|
||||
// 对齐浏览器在响应头到达时立即应用 Set-Cookie 的时序。权威 session
|
||||
// 因此必须在处理请求或解析错误之前持久化,否则下次请求会
|
||||
// 从数据库回滚到旧 Jar。
|
||||
updated := []string(nil)
|
||||
sessionHandled := false
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
// 完整 Jar 即使本轮没有变化也已经权威接管请求;不能因扁平 Cookie
|
||||
// 的顺序或尾分号不同回退写入并清掉快照。
|
||||
sessionHandled := snapshot != nil
|
||||
if changed {
|
||||
sessionHandled = true
|
||||
updated = cookierefresh.ChangedCookieNames(account.Value, value)
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
|
||||
if snapshot != nil {
|
||||
@@ -270,6 +245,9 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: message, RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
|
||||
return
|
||||
}
|
||||
if res.HasPending() {
|
||||
s.watchPendingAPIRenew(account.ID, res)
|
||||
}
|
||||
stepDetails := make([]string, 0, len(res.StepDetails)+1)
|
||||
for _, step := range res.StepDetails {
|
||||
stepDetails = append(stepDetails, fmt.Sprintf("%s: http=%d business_ok=%v set_cookie=%d", step.Name, step.HTTPStatus, step.BusinessOK, step.SetCookieCount))
|
||||
@@ -327,155 +305,53 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) {
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
batchID := newBatchID()
|
||||
accounts, err := s.store.Cookies.AllRenewalAccounts(ctx)
|
||||
if err != nil {
|
||||
s.logger.Warn("cookies_refresh 加载账号失败", "err", err)
|
||||
return
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
for _, account := range accounts {
|
||||
if !account.Enabled && account.DisableReason == db.DisableReasonManual {
|
||||
continue
|
||||
}
|
||||
if !account.Enabled && s.disabledAccountShouldSkip(ctx, account.ID) {
|
||||
continue
|
||||
}
|
||||
schedule, err := s.store.Renewal.GetCookieRefreshSchedule(ctx, account.ID)
|
||||
if err != nil {
|
||||
expireAt := now + int64(randomDuration(browserInitialDelayMax).Seconds())
|
||||
schedule = &db.CookieRefreshSchedule{CookieID: account.ID, ExpireAt: expireAt, LastStatus: "initialized"}
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, *schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: account.ID,
|
||||
Status: "initialized",
|
||||
Message: "首次初始化续期时间",
|
||||
NextExpireAt: expireAt,
|
||||
})
|
||||
continue
|
||||
}
|
||||
if schedule.Disabled || schedule.ExpireAt > now {
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: account.ID,
|
||||
Status: "success",
|
||||
Message: fmt.Sprintf("未到期,跳过,剩余 %d 秒", schedule.ExpireAt-now),
|
||||
NextExpireAt: schedule.ExpireAt,
|
||||
})
|
||||
continue
|
||||
}
|
||||
s.browserCookieRefreshOne(ctx, batchID, account, *schedule)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) {
|
||||
credentialUnlock := s.store.LockAccountCredentials(account.ID)
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
started := time.Now()
|
||||
latest, err := s.reloadRenewalAccount(ctx, account)
|
||||
if err != nil {
|
||||
s.logger.Warn("cookies_refresh 重读账号凭证失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
account = latest
|
||||
if !account.Enabled && account.DisableReason == db.DisableReasonManual {
|
||||
return
|
||||
}
|
||||
if s.browser == nil {
|
||||
schedule.LastStatus = "failed"
|
||||
schedule.LastErrorMessage = "浏览器自动化未启用"
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: schedule.LastErrorMessage, RenewMethod: "browser", StepDetails: "browser disabled", DurationMS: time.Since(started).Milliseconds()})
|
||||
return
|
||||
}
|
||||
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
|
||||
defer cancel()
|
||||
oldSnapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
|
||||
newCookies, newSnapshot, officialReload, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, browser.ResolveHeadless(account.ShowBrowser))
|
||||
if newSnapshot == nil && err == nil {
|
||||
err = errors.New("浏览器未返回权威 Cookie Jar")
|
||||
}
|
||||
if newSnapshot != nil {
|
||||
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("保存浏览器最终 Cookie Jar: %w", saveErr)
|
||||
} else {
|
||||
err = errors.Join(err, fmt.Errorf("保存浏览器最终 Cookie Jar: %w", saveErr))
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
schedule.ConsecutiveFailures++
|
||||
schedule.LastStatus = "failed"
|
||||
schedule.LastError = err.Error()
|
||||
schedule.LastErrorMessage = err.Error()
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v page_load=1 plugin_call=true", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 1})
|
||||
s.logger.Warn("cookies_refresh 失败", "account", account.ID, "err", err)
|
||||
return
|
||||
}
|
||||
updated := cookierefresh.ChangedSnapshotLabels(oldSnapshot, newSnapshot)
|
||||
if !account.Enabled {
|
||||
if err := s.store.Cookies.SetStatusWithReason(ctx, account.ID, true, ""); err != nil {
|
||||
s.logger.Warn("cookies_refresh 自动启用账号失败", "account", account.ID, "err", err)
|
||||
} else {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if s.starter != nil {
|
||||
if err := s.starter.Start(ctx, account.ID, newCookies); err != nil {
|
||||
s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if officialReload {
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if restarter, ok := s.starter.(accountRestarter); ok {
|
||||
if err := restarter.Restart(ctx, account.ID); err != nil {
|
||||
s.logger.Warn("cookies_refresh 重建消息连接失败", "account", account.ID, "err", err)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, RenewMethod: "browser", DurationMS: time.Since(started).Milliseconds(), RequestCount: 1})
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
nextExpire := time.Now().Add(browserSuccessDelay()).Unix()
|
||||
schedule.Disabled = false
|
||||
schedule.ConsecutiveFailures = 0
|
||||
schedule.LastError = ""
|
||||
schedule.LastStatus = "success"
|
||||
schedule.LastErrorMessage = ""
|
||||
schedule.LastRefreshAt = time.Now().Unix()
|
||||
schedule.ExpireAt = nextExpire
|
||||
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
|
||||
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{
|
||||
BatchID: batchID,
|
||||
CookieID: account.ID,
|
||||
Status: "success",
|
||||
Message: fmt.Sprintf("页面校验通过,全量获取到 %d 个浏览器Cookie", len(newSnapshot)),
|
||||
UpdatedCookieNames: updated,
|
||||
NextExpireAt: nextExpire,
|
||||
RenewMethod: "browser",
|
||||
StepDetails: fmt.Sprintf("snapshot=%v page_load=1 plugin_call=true", len(oldSnapshot) > 0),
|
||||
DurationMS: time.Since(started).Milliseconds(),
|
||||
RequestCount: 1,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*apirenew.Result, error) {
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
|
||||
}
|
||||
|
||||
func (s *Scheduler) watchPendingAPIRenew(cookieID string, result *apirenew.Result) {
|
||||
if result == nil || !result.HasPending() || s.store == nil || s.store.Cookies == nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second)
|
||||
defer cancel()
|
||||
late, waitErr := result.AwaitPending(ctx)
|
||||
if late == nil {
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("等待定时静默续期底层响应失败", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
unlock := s.store.LockAccountCredentials(cookieID)
|
||||
defer unlock()
|
||||
detail, getErr := s.store.Cookies.GetDetails(ctx, cookieID)
|
||||
if getErr != nil || detail == nil {
|
||||
if getErr == nil {
|
||||
getErr = db.ErrNotFound
|
||||
}
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 前读取账号失败", "account", cookieID, "err", getErr)
|
||||
return
|
||||
}
|
||||
newCookies, metadata, changed := apirenew.RebaseResponseCookies(detail.Value, detail.MetadataJSON, late)
|
||||
if changed {
|
||||
if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
|
||||
s.logger.Warn("保存定时静默续期迟到 Cookie 失败", "account", cookieID, "err", saveErr)
|
||||
return
|
||||
}
|
||||
if s.store.Tokens != nil {
|
||||
_ = s.store.Tokens.Clear(ctx, cookieID)
|
||||
}
|
||||
s.logger.Info("已异步接收定时静默续期迟到 Cookie", "account", cookieID)
|
||||
}
|
||||
if waitErr != nil {
|
||||
s.logger.Warn("定时静默续期底层响应失败,已保存响应 Cookie", "account", cookieID, "err", waitErr)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) (db.RenewalAccount, error) {
|
||||
detail, err := s.store.Cookies.GetDetails(ctx, account.ID)
|
||||
if err != nil || detail == nil {
|
||||
@@ -545,19 +421,6 @@ func (s *Scheduler) isSessionCooled(cookieID string) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *Scheduler) disabledAccountShouldSkip(ctx context.Context, cookieID string) bool {
|
||||
statuses, err := s.store.Renewal.RecentBrowserCookieRenewStatuses(ctx, cookieID, disabledFailureLimit)
|
||||
if err != nil || len(statuses) < disabledFailureLimit {
|
||||
return false
|
||||
}
|
||||
for _, status := range statuses {
|
||||
if status != "failed" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Scheduler) settingEnabled(ctx context.Context, key string, defaultEnabled bool) bool {
|
||||
if s.store == nil || s.store.Settings == nil {
|
||||
return defaultEnabled
|
||||
@@ -609,21 +472,6 @@ func (s *Scheduler) settingInt(ctx context.Context, key string, defaultValue int
|
||||
return n
|
||||
}
|
||||
|
||||
func browserSuccessDelay() time.Duration {
|
||||
return browserSuccessDelayMin + randomDuration(browserSuccessDelayRange)
|
||||
}
|
||||
|
||||
func randomDuration(max time.Duration) time.Duration {
|
||||
if max <= 0 {
|
||||
return 0
|
||||
}
|
||||
n, err := crand.Int(crand.Reader, big.NewInt(int64(max)))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(n.Int64())
|
||||
}
|
||||
|
||||
func newBatchID() string {
|
||||
var b [16]byte
|
||||
if _, err := crand.Read(b[:]); err != nil {
|
||||
|
||||
@@ -2,7 +2,6 @@ package renewal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -34,30 +33,6 @@ func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
|
||||
return db.NewStore(d, db.DialectSQLite), func() { d.Close() }
|
||||
}
|
||||
|
||||
type schedulerFakeBrowser struct {
|
||||
quickCookies string
|
||||
quickErr error
|
||||
quickCalls int
|
||||
quickInputs []string
|
||||
}
|
||||
|
||||
type schedulerRefreshBrowser struct {
|
||||
refreshCalls int
|
||||
officialReload bool
|
||||
}
|
||||
|
||||
func (f *schedulerRefreshBrowser) BrowserQuickRenew(context.Context, string, string, bool) (string, error) {
|
||||
return "", errors.New("not implemented")
|
||||
}
|
||||
|
||||
func (f *schedulerRefreshBrowser) CookiesRefreshSnapshot(_ context.Context, _ string, cookieStr string, snapshot []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, bool, error) {
|
||||
f.refreshCalls++
|
||||
if snapshot == nil {
|
||||
snapshot = cookierefresh.SnapshotFromCookieString(cookieStr, ".goofish.com")
|
||||
}
|
||||
return cookieStr, snapshot, f.officialReload, nil
|
||||
}
|
||||
|
||||
type schedulerFakeStarter struct {
|
||||
starts atomic.Int32
|
||||
restarts atomic.Int32
|
||||
@@ -73,16 +48,6 @@ func (f *schedulerFakeStarter) Restart(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *schedulerFakeBrowser) BrowserQuickRenew(_ context.Context, _ string, cookieStr string, _ bool) (string, error) {
|
||||
f.quickCalls++
|
||||
f.quickInputs = append(f.quickInputs, cookieStr)
|
||||
return f.quickCookies, f.quickErr
|
||||
}
|
||||
|
||||
func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ string, _ []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, bool, error) {
|
||||
return "", nil, false, errors.New("not implemented")
|
||||
}
|
||||
|
||||
type schedulerFakePasswordRefresher struct {
|
||||
calls atomic.Int32
|
||||
}
|
||||
@@ -165,7 +130,7 @@ func TestSchedulerDefaultsMatchUpstreamConfig(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
|
||||
if s.settingEnabled(ctx, loginRenewEnabledSetting, false) {
|
||||
t.Fatal("login_renew 未配置时应默认关闭")
|
||||
@@ -192,7 +157,7 @@ func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
s.mtop = &mtop.ClientImpl{HTTPClient: srv.Client(), LoginUserURL: srv.URL}
|
||||
s.loginRenewOne(ctx, "batch-login-renew", account)
|
||||
|
||||
@@ -236,7 +201,7 @@ func TestLoginRenewPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
s.mtop = &mtop.ClientImpl{HTTPClient: client, LoginUserURL: mtop.LoginUserAPI}
|
||||
s.loginRenewOne(ctx, "batch-login-session-error", account)
|
||||
|
||||
@@ -276,44 +241,11 @@ func TestLoginRenewPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowserCookieRefreshSkipsManuallyDisabledAccount(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
account := createSchedulerAccount(t, store, "cid-manual-disabled", "unb=1; cookie2=c2")
|
||||
if err := store.Cookies.SetStatusWithReason(ctx, account.ID, false, db.DisableReasonManual); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
accounts, err := store.Cookies.AllRenewalAccounts(ctx)
|
||||
if err != nil || len(accounts) != 1 {
|
||||
t.Fatalf("accounts=%+v err=%v", accounts, err)
|
||||
}
|
||||
if accounts[0].DisableReason != db.DisableReasonManual {
|
||||
t.Fatalf("disable reason=%q", accounts[0].DisableReason)
|
||||
}
|
||||
browser := &schedulerRefreshBrowser{}
|
||||
s := NewScheduler(store, nil, browser, nil, nil)
|
||||
s.executeBrowserCookieRefresh(ctx)
|
||||
if browser.refreshCalls != 0 {
|
||||
t.Fatalf("manual disabled account refreshed %d times", browser.refreshCalls)
|
||||
}
|
||||
if store.Cookies.GetStatus(ctx, account.ID) {
|
||||
t.Fatal("manual disabled account must remain disabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewSchedulerTreatsTypedNilBrowserAsDisabled(t *testing.T) {
|
||||
var typedNilBrowser *schedulerFakeBrowser
|
||||
if got := browserRenewerOrNil(typedNilBrowser); got != nil {
|
||||
t.Fatal("typed nil BrowserRenewer 应被规范化为 nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulerSettingEnabledOverrides(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
|
||||
if err := store.Settings.Set(ctx, loginRenewEnabledSetting, "enabled"); err != nil {
|
||||
t.Fatalf("Set enabled: %v", err)
|
||||
@@ -333,7 +265,7 @@ func TestSchedulerSettingIntervalOverrides(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
|
||||
if got := s.settingInterval(ctx, loginRenewIntervalSetting, loginRenewInterval); got != loginRenewInterval {
|
||||
t.Fatalf("未配置间隔应返回默认值: %s", got)
|
||||
@@ -362,7 +294,7 @@ func TestSchedulerSettingIntOverrides(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
|
||||
if got := s.settingInt(ctx, "missing_int", 10); got != 10 {
|
||||
t.Fatalf("missing setting=%d want 10", got)
|
||||
@@ -405,7 +337,7 @@ func TestRenewalCleanupLogsUsesRetentionDays(t *testing.T) {
|
||||
if err := store.Settings.Set(ctx, "renewal_log_retention_days", "10"); err != nil {
|
||||
t.Fatalf("set retention: %v", err)
|
||||
}
|
||||
s := NewScheduler(store, nil, nil, nil, nil)
|
||||
s := NewScheduler(store, nil, nil, nil)
|
||||
s.cleanupExpiredLogs(ctx)
|
||||
for _, table := range []string{
|
||||
"scheduled_cookies_refresh_log",
|
||||
@@ -430,13 +362,12 @@ func TestAPICookieRenewOneSkipsExpiredLongLoginWithoutEscalation(t *testing.T) {
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
account := createSchedulerAccount(t, store, "cid-expired", "unb=1; cookie2=c2")
|
||||
browser := &schedulerFakeBrowser{}
|
||||
refresher := &schedulerFakePasswordRefresher{}
|
||||
s := NewScheduler(store, nil, browser, refresher, nil)
|
||||
s := NewScheduler(store, nil, refresher, nil)
|
||||
s.apiCookieRenewOne(ctx, "batch-expired", account)
|
||||
|
||||
if browser.quickCalls != 0 || refresher.calls.Load() != 0 {
|
||||
t.Fatalf("proactive renewal escalated: browser=%d password=%d", browser.quickCalls, refresher.calls.Load())
|
||||
if refresher.calls.Load() != 0 {
|
||||
t.Fatalf("proactive renewal escalated to account recovery: %d", refresher.calls.Load())
|
||||
}
|
||||
log := lastAPIRenewLog(t, store, account.ID)
|
||||
if log.status != "skipped" || !strings.Contains(log.stepDetails, "long_login_expired") {
|
||||
@@ -450,7 +381,6 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
expire := strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)
|
||||
account := createSchedulerAccount(t, store, "cid-silent", "unb=1; cookie2=c2; havana_lgc_exp="+expire)
|
||||
browser := &schedulerFakeBrowser{}
|
||||
refresher := &schedulerFakePasswordRefresher{}
|
||||
starter := &schedulerFakeStarter{}
|
||||
var requests atomic.Int32
|
||||
@@ -461,12 +391,12 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
s := NewScheduler(store, starter, browser, refresher, nil)
|
||||
s := NewScheduler(store, starter, refresher, nil)
|
||||
s.api = schedulerRenewServiceFromServer(srv)
|
||||
s.apiCookieRenewOne(ctx, "batch-silent", account)
|
||||
|
||||
if requests.Load() != 1 || browser.quickCalls != 0 || refresher.calls.Load() != 0 {
|
||||
t.Fatalf("requests=%d browser=%d password=%d", requests.Load(), browser.quickCalls, refresher.calls.Load())
|
||||
if requests.Load() != 1 || refresher.calls.Load() != 0 {
|
||||
t.Fatalf("requests=%d recovery=%d", requests.Load(), refresher.calls.Load())
|
||||
}
|
||||
if starter.restarts.Load() != 1 || starter.starts.Load() != 0 {
|
||||
t.Fatalf("官网静默续期成功应模拟 reload 重建运行时: starts=%d restarts=%d", starter.starts.Load(), starter.restarts.Load())
|
||||
@@ -480,18 +410,3 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
|
||||
t.Fatalf("silent renewal log=%+v", log)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBrowserCookieRefreshRestartsOnlyAfterOfficialReload(t *testing.T) {
|
||||
store, cleanup := newSchedulerTestStore(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
account := createSchedulerAccount(t, store, "cid-browser-reload", "unb=1; havana_lgc_exp=1")
|
||||
starter := &schedulerFakeStarter{}
|
||||
browser := &schedulerRefreshBrowser{officialReload: true}
|
||||
s := NewScheduler(store, starter, browser, nil, nil)
|
||||
s.browserCookieRefreshOne(ctx, "batch-browser-reload", account, db.CookieRefreshSchedule{CookieID: account.ID})
|
||||
|
||||
if browser.refreshCalls != 1 || starter.restarts.Load() != 1 || starter.starts.Load() != 0 {
|
||||
t.Fatalf("refresh=%d starts=%d restarts=%d", browser.refreshCalls, starter.starts.Load(), starter.restarts.Load())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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", "member@example.com", "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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -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{
|
||||
|
||||
@@ -235,7 +235,10 @@ func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []s
|
||||
if domain == "" {
|
||||
domain = strings.ToLower(target.Hostname())
|
||||
} else {
|
||||
if !cookieDomainMatches(strings.ToLower(target.Hostname()), domain) {
|
||||
// Domain 属性无论是否带前导点都表示域 Cookie;前导点按
|
||||
// RFC 6265 应被忽略。不能复用已存 Cookie 的 host-only
|
||||
// 匹配规则,否则 Domain=goofish.com 会被错误拒绝。
|
||||
if !cookieDomainAttributeMatches(strings.ToLower(target.Hostname()), domain) {
|
||||
// Chromium rejects a Domain attribute unrelated to the response host.
|
||||
continue
|
||||
}
|
||||
@@ -302,6 +305,12 @@ func snapshotKey(cookie BrowserCookie) string {
|
||||
return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path + "\x00" + cookie.PartitionKey
|
||||
}
|
||||
|
||||
func cookieDomainAttributeMatches(host, domain string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
base := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(domain)), ".")
|
||||
return base != "" && (host == base || strings.HasSuffix(host, "."+base))
|
||||
}
|
||||
|
||||
func cookieDomainMatches(host, domain string) bool {
|
||||
host = strings.ToLower(strings.TrimSpace(host))
|
||||
domain = strings.ToLower(strings.TrimSpace(domain))
|
||||
|
||||
@@ -102,6 +102,18 @@ func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySetCookiesAcceptsDomainAttributeWithoutLeadingDot(t *testing.T) {
|
||||
updated := ApplySetCookies(nil, "https://passport.goofish.com/ivCheckLogin.htm", []string{
|
||||
"unb=777; Domain=goofish.com; Path=/; Secure; HttpOnly",
|
||||
}, time.Now(), "https://goofish.com")
|
||||
if len(updated) != 1 || updated[0].Domain != ".goofish.com" || !updated[0].Secure || !updated[0].HTTPOnly {
|
||||
t.Fatalf("Domain 属性未按域 Cookie 处理: %+v", updated)
|
||||
}
|
||||
if got := CookieHeaderForURL(updated, "https://www.goofish.com/im", time.Now()); got != "unb=777" {
|
||||
t.Fatalf("跨子域 Cookie header=%q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplySetCookiesMaxAgeOverridesExpires(t *testing.T) {
|
||||
now := time.Unix(1_800_000_000, 0)
|
||||
updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
@@ -69,46 +68,12 @@ type ClientImpl struct {
|
||||
SoldOrdersURL string
|
||||
ItemDetailURL string
|
||||
LoginUserURL string
|
||||
TokenExecutor TokenRequestExecutor
|
||||
}
|
||||
|
||||
type TokenBrowserRequest struct {
|
||||
URL string
|
||||
Body string
|
||||
Cookies string
|
||||
CookieSnapshot []cookierefresh.BrowserCookie
|
||||
}
|
||||
|
||||
type TokenBrowserResponse struct {
|
||||
Status int
|
||||
Body []byte
|
||||
UpdatedCookies string
|
||||
CookieSnapshot []cookierefresh.BrowserCookie
|
||||
CookieSnapshotComplete bool // true 表示 CookieSnapshot 是响应后的权威完整 Jar,空切片也代表全部删除
|
||||
CookieStateChanged bool // true 表示响应明确把不完整扁平 Cookie 更新或删除到了空值
|
||||
}
|
||||
|
||||
type TokenRequestExecutor interface {
|
||||
ExecuteTokenRequest(context.Context, TokenBrowserRequest) (*TokenBrowserResponse, error)
|
||||
}
|
||||
|
||||
var defaultTokenExecutor struct {
|
||||
sync.RWMutex
|
||||
value TokenRequestExecutor
|
||||
}
|
||||
|
||||
func SetDefaultTokenRequestExecutor(executor TokenRequestExecutor) {
|
||||
defaultTokenExecutor.Lock()
|
||||
defaultTokenExecutor.value = executor
|
||||
defaultTokenExecutor.Unlock()
|
||||
}
|
||||
|
||||
// NewClient 构造默认 HTTP 实现的非零 ClientImpl(调用方多为持有 Client 接口字段)。
|
||||
// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
|
||||
// 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。
|
||||
func NewClient() *ClientImpl {
|
||||
defaultTokenExecutor.RLock()
|
||||
executor := defaultTokenExecutor.value
|
||||
defaultTokenExecutor.RUnlock()
|
||||
return &ClientImpl{TokenExecutor: executor}
|
||||
return &ClientImpl{}
|
||||
}
|
||||
|
||||
// 编译期保证 *ClientImpl 实现 Client 接口。
|
||||
@@ -119,7 +84,7 @@ type RefreshResult struct {
|
||||
AccessToken string // 用于 WS /reg 注册
|
||||
AccessTokenExpireAt int64 // 服务端 accessTokenExpiredTime 归一化后的 Unix 秒
|
||||
UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
|
||||
CookieSnapshot []cookierefresh.BrowserCookie // 浏览器执行 token 请求后得到的完整 Cookie Jar
|
||||
CookieSnapshot []cookierefresh.BrowserCookie // token 请求后的完整 Cookie Jar
|
||||
CookieSnapshotComplete bool // true 表示快照权威完整;空切片代表 Cookie Jar 已被清空
|
||||
CookieStateChanged bool // true 表示本次响应明确更新或删除了 Cookie(包括更新后为空)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,12 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewClientUsesGoHTTPByDefault(t *testing.T) {
|
||||
if client := NewClient(); client == nil {
|
||||
t.Fatal("默认 MTOP 客户端为空")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenRetriesOnceWithUpdatedCookie(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -19,8 +19,8 @@ const (
|
||||
|
||||
type cookieSessionContextKey struct{}
|
||||
|
||||
// CookieSession carries an authoritative browser Cookie Jar through one MTOP
|
||||
// workflow. It lets direct Go HTTP calls reproduce the browser split between
|
||||
// CookieSession carries an authoritative Cookie Jar through one MTOP workflow.
|
||||
// It lets direct Go HTTP calls reproduce the browser split between
|
||||
// document cookies used for signing and cookies scoped to the request URL.
|
||||
// The same session absorbs every Set-Cookie before response-body processing,
|
||||
// so callers can persist rotations and deletions even when parsing later fails.
|
||||
@@ -45,9 +45,9 @@ func WithCookieSnapshot(ctx context.Context, snapshot []cookierefresh.BrowserCoo
|
||||
}
|
||||
|
||||
// WithFlatCookieSession carries a legacy flat Cookie header without claiming
|
||||
// that it is a complete browser Jar. Response Set-Cookie values are still
|
||||
// that it is a complete Cookie Jar. Response Set-Cookie values are still
|
||||
// observable and persistable, but callers must keep metadata snapshot-free
|
||||
// until Chromium supplies an authoritative Jar.
|
||||
// until a protocol flow supplies an authoritative Jar.
|
||||
func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) {
|
||||
session := &CookieSession{flat: cookies}
|
||||
return context.WithValue(ctx, cookieSessionContextKey{}, session), session
|
||||
@@ -77,8 +77,8 @@ func cookieSessionFromContext(ctx context.Context) *CookieSession {
|
||||
return session
|
||||
}
|
||||
|
||||
// CookieSessionFromContext exposes the operation-scoped session to browser
|
||||
// fallbacks that can replace it with Chromium's final authoritative Jar.
|
||||
// CookieSessionFromContext exposes the operation-scoped session to legacy
|
||||
// helpers that may replace it with a final authoritative Jar.
|
||||
func CookieSessionFromContext(ctx context.Context) *CookieSession {
|
||||
return cookieSessionFromContext(ctx)
|
||||
}
|
||||
@@ -92,8 +92,7 @@ func (s *CookieSession) Snapshot() []cookierefresh.BrowserCookie {
|
||||
return snapshot
|
||||
}
|
||||
|
||||
// ReplaceSnapshot records Chromium's final complete Jar, including an
|
||||
// explicitly empty one.
|
||||
// ReplaceSnapshot records a final complete Jar, including an explicitly empty one.
|
||||
func (s *CookieSession) ReplaceSnapshot(snapshot []cookierefresh.BrowserCookie) {
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
|
||||
@@ -21,7 +21,7 @@ const officialMTopMaxAttempts = 5
|
||||
|
||||
// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。
|
||||
// 遇到 mtop 签名 token 过期时,按官网 lib-mtop 2.7.3 的 H5 流程最多执行
|
||||
// 5 次请求(含首次),每次先吸收浏览器 Cookie Jar 再重新签名。
|
||||
// 5 次请求(含首次),每次先吸收 Go Cookie Jar 再重新签名。
|
||||
func (c *ClientImpl) RefreshToken(cookiesStr string) (*RefreshResult, error) {
|
||||
return c.RefreshTokenContext(context.Background(), cookiesStr)
|
||||
}
|
||||
@@ -39,8 +39,8 @@ func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookie
|
||||
return c.RefreshTokenWithCredentialContext(ctx, cookiesStr, deviceID, nil)
|
||||
}
|
||||
|
||||
// RefreshTokenWithCredentialContext 在浏览器执行器可用时同时传入完整 Cookie
|
||||
// 快照,避免把不同 Domain/Path 的同名 Cookie 压成一个值后再注入 Chromium。
|
||||
// RefreshTokenWithCredentialContext 使用完整 Cookie 快照执行纯 Go HTTP 请求,
|
||||
// 避免把不同 Domain/Path 的同名 Cookie 压成一个值。
|
||||
func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (*RefreshResult, error) {
|
||||
currentCookies := cookiesStr
|
||||
currentSnapshot := cookierefresh.NormalizeSnapshot(cookieSnapshot)
|
||||
@@ -60,7 +60,7 @@ func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cook
|
||||
currentSnapshotComplete = true
|
||||
} else if attemptChanged {
|
||||
// 只有扁平更新时无法把变化安全映射回既有 Domain/Path Jar;
|
||||
// 必须降级为非权威状态,等待 Chromium 下次提供完整快照。
|
||||
// 必须降级为非权威状态。
|
||||
currentSnapshot = nil
|
||||
currentSnapshotComplete = false
|
||||
}
|
||||
@@ -187,79 +187,43 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
|
||||
requestURL := tokenURL + "?" + query
|
||||
var raw []byte
|
||||
var status int
|
||||
updated := cookiesStr
|
||||
var updated string
|
||||
var snapshot []cookierefresh.BrowserCookie
|
||||
snapshotComplete := false
|
||||
stateChanged := false
|
||||
if c.TokenExecutor != nil {
|
||||
browserResp, execErr := c.TokenExecutor.ExecuteTokenRequest(ctx, TokenBrowserRequest{
|
||||
URL: requestURL, Body: body, Cookies: cookiesStr, CookieSnapshot: cookieSnapshot,
|
||||
})
|
||||
if browserResp != nil {
|
||||
raw, status = browserResp.Body, browserResp.Status
|
||||
stateChanged = browserResp.CookieStateChanged
|
||||
if browserResp.CookieStateChanged || browserResp.CookieSnapshotComplete || strings.TrimSpace(browserResp.UpdatedCookies) != "" {
|
||||
updated = browserResp.UpdatedCookies
|
||||
}
|
||||
if browserResp.CookieSnapshotComplete {
|
||||
snapshot = cookierefresh.NormalizeSnapshot(browserResp.CookieSnapshot)
|
||||
if snapshot == nil {
|
||||
snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
snapshotComplete = true
|
||||
updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
|
||||
}
|
||||
stateChanged = stateChanged || updated != cookiesStr || (snapshot != nil && !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot)))
|
||||
}
|
||||
if session := cookieSessionFromContext(ctx); session != nil && snapshot != nil {
|
||||
session.replace(snapshot)
|
||||
var sessionChanged bool
|
||||
updated, snapshot, sessionChanged = session.State()
|
||||
stateChanged = stateChanged || sessionChanged
|
||||
snapshotComplete = true
|
||||
}
|
||||
if execErr != nil {
|
||||
return "", 0, nil, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("浏览器 token API 请求失败: %w", execErr)
|
||||
}
|
||||
if browserResp == nil {
|
||||
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("浏览器 token API 返回空响应")
|
||||
}
|
||||
} else {
|
||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, cookiesStr, nil, "", 0, false, false, reqErr
|
||||
}
|
||||
setCommonHeaders(req, requestCookies)
|
||||
req.Header.Set("Referer", "https://www.goofish.com/im")
|
||||
resp, reqErr := hc.Do(req)
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("token API 请求失败: %w", reqErr)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Chromium applies Set-Cookie as soon as response headers arrive. Mirror
|
||||
// that ordering so a body read/parse failure cannot discard credential
|
||||
// rotation or deletion already issued by the server.
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
|
||||
var sessionChanged bool
|
||||
_, snapshot, sessionChanged = session.State()
|
||||
stateChanged = sessionChanged
|
||||
snapshotComplete = snapshot != nil
|
||||
} else if cookieSnapshot != nil {
|
||||
snapshot = cookierefresh.ApplySetCookies(cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), goofishTopSite)
|
||||
updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
|
||||
stateChanged = !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot))
|
||||
snapshotComplete = true
|
||||
} else {
|
||||
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
|
||||
stateChanged = updated != cookiesStr
|
||||
}
|
||||
raw, reqErr = readMTopBody(resp)
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, updated, snapshot, "", resp.StatusCode, snapshotComplete, stateChanged, reqErr
|
||||
}
|
||||
status = resp.StatusCode
|
||||
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, cookiesStr, nil, "", 0, false, false, reqErr
|
||||
}
|
||||
setCommonHeaders(req, requestCookies)
|
||||
req.Header.Set("Referer", "https://www.goofish.com/im")
|
||||
resp, reqErr := hc.Do(req)
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("token API 请求失败: %w", reqErr)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// Go CookieSession 在读取响应体前应用 Set-Cookie,避免解析失败时丢掉
|
||||
// 服务端已经下发的凭证轮换或删除。
|
||||
if session := cookieSessionFromContext(ctx); session != nil {
|
||||
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
|
||||
var sessionChanged bool
|
||||
_, snapshot, sessionChanged = session.State()
|
||||
stateChanged = sessionChanged
|
||||
snapshotComplete = snapshot != nil
|
||||
} else if cookieSnapshot != nil {
|
||||
snapshot = cookierefresh.ApplySetCookies(cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), goofishTopSite)
|
||||
updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
|
||||
stateChanged = !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot))
|
||||
snapshotComplete = true
|
||||
} else {
|
||||
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
|
||||
stateChanged = updated != cookiesStr
|
||||
}
|
||||
raw, reqErr = readMTopBody(resp)
|
||||
if reqErr != nil {
|
||||
return "", 0, nil, updated, snapshot, "", resp.StatusCode, snapshotComplete, stateChanged, reqErr
|
||||
}
|
||||
status = resp.StatusCode
|
||||
|
||||
var res struct {
|
||||
Ret []string `json:"ret"`
|
||||
|
||||
@@ -20,111 +20,6 @@ import (
|
||||
|
||||
const testCookiesWithUnb = "unb=123; _m_h5_tk=oldtoken_1;"
|
||||
|
||||
type recordingTokenExecutor struct {
|
||||
requests []TokenBrowserRequest
|
||||
responses []*TokenBrowserResponse
|
||||
}
|
||||
|
||||
func (e *recordingTokenExecutor) ExecuteTokenRequest(_ context.Context, req TokenBrowserRequest) (*TokenBrowserResponse, error) {
|
||||
e.requests = append(e.requests, req)
|
||||
if len(e.responses) == 0 {
|
||||
return nil, fmt.Errorf("unexpected token request")
|
||||
}
|
||||
response := e.responses[0]
|
||||
e.responses = e.responses[1:]
|
||||
return response, nil
|
||||
}
|
||||
|
||||
func TestRefreshTokenUsesBrowserExecutor(t *testing.T) {
|
||||
snapshot := []cookierefresh.BrowserCookie{{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true}}
|
||||
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"browser-token"}}`),
|
||||
UpdatedCookies: testCookiesWithUnb + " x5sec=fresh;",
|
||||
CookieSnapshot: snapshot,
|
||||
}}}
|
||||
client := &ClientImpl{TokenExecutor: executor}
|
||||
result, err := client.RefreshTokenWithDeviceIDContext(context.Background(), testCookiesWithUnb, "permanent-device")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.AccessToken != "browser-token" || !strings.Contains(result.UpdatedCookies, "x5sec=fresh") {
|
||||
t.Fatalf("result=%+v", result)
|
||||
}
|
||||
if result.CookieSnapshotComplete || result.CookieSnapshot != nil {
|
||||
t.Fatalf("未声明完整的浏览器快照不得冒充权威 Jar: %+v", result)
|
||||
}
|
||||
if len(executor.requests) != 1 {
|
||||
t.Fatalf("browser requests=%d", len(executor.requests))
|
||||
}
|
||||
req := executor.requests[0]
|
||||
if !strings.HasPrefix(req.URL, TokenAPI+"?") || !strings.Contains(req.Body, "permanent-device") || req.Cookies != testCookiesWithUnb {
|
||||
t.Fatalf("browser request=%+v", req)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenWithCredentialPassesBrowserSnapshot(t *testing.T) {
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "sid", Value: "scoped", Domain: "h5api.m.goofish.com", Path: "/h5", HTTPOnly: true, Secure: true},
|
||||
}
|
||||
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"scoped-token"}}`),
|
||||
UpdatedCookies: "unb=123; sid=scoped",
|
||||
CookieSnapshot: snapshot,
|
||||
}}}
|
||||
client := &ClientImpl{TokenExecutor: executor}
|
||||
result, err := client.RefreshTokenWithCredentialContext(context.Background(), testCookiesWithUnb, "device", snapshot)
|
||||
if err != nil || result.AccessToken != "scoped-token" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
if len(executor.requests) != 1 || len(executor.requests[0].CookieSnapshot) != 2 {
|
||||
t.Fatalf("完整 Cookie 快照未传给浏览器执行器: %+v", executor.requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenContextInheritsAndWritesCookieSession(t *testing.T) {
|
||||
initial := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "session-old_1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "api_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
|
||||
}
|
||||
refreshed := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "session-new_9", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "api_only", Value: "rotated", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
|
||||
}
|
||||
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"context-token"}}`),
|
||||
UpdatedCookies: "must-not-replace-authoritative-session=1",
|
||||
CookieSnapshot: refreshed,
|
||||
CookieSnapshotComplete: true,
|
||||
}}}
|
||||
ctx, session := WithCookieSnapshot(context.Background(), initial)
|
||||
explicitWrong := []cookierefresh.BrowserCookie{{Name: "unb", Value: "999", Domain: ".goofish.com", Path: "/", Secure: true}}
|
||||
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
|
||||
ctx, "unb=fallback; _m_h5_tk=fallback_1", "device", explicitWrong,
|
||||
)
|
||||
if err != nil || result.AccessToken != "context-token" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
if len(executor.requests) != 1 || len(executor.requests[0].CookieSnapshot) != len(initial) {
|
||||
t.Fatalf("executor did not inherit context snapshot: %+v", executor.requests)
|
||||
}
|
||||
if got := protocol.TransCookies(executor.requests[0].Cookies)["_m_h5_tk"]; got != "session-old_1" {
|
||||
t.Fatalf("executor flat cookies did not inherit context: %q", executor.requests[0].Cookies)
|
||||
}
|
||||
canonical, gotSnapshot, changed := session.State()
|
||||
if !changed || !strings.Contains(canonical, "_m_h5_tk=session-new_9") || len(gotSnapshot) != len(refreshed) {
|
||||
t.Fatalf("session was not written back: canonical=%q snapshot=%+v changed=%v", canonical, gotSnapshot, changed)
|
||||
}
|
||||
if !result.CookieSnapshotComplete || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=session-new_9") {
|
||||
t.Fatalf("result did not reflect authoritative context session: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
|
||||
initial := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
@@ -170,29 +65,6 @@ func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTokenAllowsSnapshotOnlyCredential(t *testing.T) {
|
||||
snapshot := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "_m_h5_tk", Value: "snapshot-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
}
|
||||
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"snapshot-only"}}`),
|
||||
UpdatedCookies: "unb=123; _m_h5_tk=snapshot-token_1",
|
||||
CookieSnapshot: snapshot,
|
||||
CookieSnapshotComplete: true,
|
||||
}}}
|
||||
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
|
||||
context.Background(), "", "device", snapshot,
|
||||
)
|
||||
if err != nil || result.AccessToken != "snapshot-only" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
if len(executor.requests) != 1 || executor.requests[0].Cookies != "" {
|
||||
t.Fatalf("snapshot-only request=%+v", executor.requests)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefreshTokenWithDeviceIDSuccessOnRetry: 首次返回 token 过期 + Set-Cookie,二次成功。
|
||||
func TestRefreshTokenWithDeviceIDSuccessOnRetry(t *testing.T) {
|
||||
var requests atomic.Int32
|
||||
@@ -347,25 +219,21 @@ func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
|
||||
{Name: "_m_h5_tk_enc", Value: "enc", Domain: ".m.goofish.com", Path: "/"},
|
||||
{Name: "_m_h5_tk", Value: "scoped", Domain: ".goofish.com", Path: "/im"},
|
||||
}
|
||||
responses := make([]*TokenBrowserResponse, officialMTopMaxAttempts)
|
||||
for i := range responses {
|
||||
responses[i] = &TokenBrowserResponse{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`),
|
||||
UpdatedCookies: "unb=123; _m_h5_c=c; _m_h5_tk=tk; _m_h5_tk_enc=enc; keep=yes",
|
||||
CookieSnapshot: snapshot,
|
||||
CookieSnapshotComplete: true,
|
||||
}
|
||||
}
|
||||
executor := &recordingTokenExecutor{responses: responses}
|
||||
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
|
||||
context.Background(), testCookiesWithUnb, "did", snapshot,
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
|
||||
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenWithCredentialContext(
|
||||
ctx, testCookiesWithUnb, "did", snapshot,
|
||||
)
|
||||
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
if len(executor.requests) != officialMTopMaxAttempts {
|
||||
t.Fatalf("requests=%d want %d", len(executor.requests), officialMTopMaxAttempts)
|
||||
if requests.Load() != officialMTopMaxAttempts {
|
||||
t.Fatalf("requests=%d want %d", requests.Load(), officialMTopMaxAttempts)
|
||||
}
|
||||
for _, name := range []string{"_m_h5_c=", "_m_h5_tk_enc="} {
|
||||
if strings.Contains(result.UpdatedCookies, name) {
|
||||
@@ -471,13 +339,15 @@ func TestRefreshTokenPreservesExplicitFlatDeletionOnParseError(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRefreshTokenSessionExpiredDoesNotUseTokenRetry(t *testing.T) {
|
||||
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
|
||||
Status: http.StatusOK,
|
||||
Body: []byte(`{"ret":["FAIL_SYS_SESSION_EXPIRED::会话过期"]}`),
|
||||
}}}
|
||||
_, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
|
||||
if err == nil || len(executor.requests) != 1 {
|
||||
t.Fatalf("err=%v requests=%d want 1", err, len(executor.requests))
|
||||
var requests atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
requests.Add(1)
|
||||
fmt.Fprint(w, `{"ret":["FAIL_SYS_SESSION_EXPIRED::会话过期"]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
_, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
|
||||
if err == nil || requests.Load() != 1 {
|
||||
t.Fatalf("err=%v requests=%d want 1", err, requests.Load())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+235
-202
@@ -1,4 +1,4 @@
|
||||
// Package qrlogin 实现闲鱼扫码登录;风控验证场景可通过浏览器提取真实 cookie。
|
||||
// Package qrlogin 使用纯 Go HTTP 复刻闲鱼扫码登录与人脸验证流程。
|
||||
package qrlogin
|
||||
|
||||
import (
|
||||
@@ -23,9 +23,15 @@ import (
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
const maxQRResponseBytes = 2 << 20
|
||||
const (
|
||||
maxQRResponseBytes = 2 << 20
|
||||
qrPollInterval = 2 * time.Second
|
||||
maxQRServerErrors = 5
|
||||
qrTopSite = "https://goofish.com"
|
||||
)
|
||||
|
||||
const (
|
||||
host = "https://passport.goofish.com"
|
||||
@@ -54,16 +60,17 @@ var qrHeaders = map[string]string{
|
||||
type Session struct {
|
||||
mu sync.RWMutex
|
||||
SessionID string `json:"session_id"`
|
||||
Status string `json:"status"` // waiting/scanned/success/expired/cancelled/verification_required
|
||||
Status string `json:"status"` // waiting/scanned/success/expired/cancelled/error/verification_required
|
||||
QRCodeURL string `json:"qr_code_url"`
|
||||
qrContent string
|
||||
cookies map[string]string
|
||||
cookieSnapshot []cookierefresh.BrowserCookie
|
||||
unb string
|
||||
createdTime time.Time
|
||||
expireTime time.Duration
|
||||
params map[string]string
|
||||
verificationURL string
|
||||
verificationScreenshot string // 最新截图 data URL,前端轮询时显示
|
||||
verificationScreenshot string // 历史兼容字段;纯 Go 人脸流程直接返回二维码
|
||||
faceQRURL string // 人脸验证二维码 data URL,优先展示给前端
|
||||
faceQRContent string // 人脸验证二维码原始内容,便于排查协议变化
|
||||
}
|
||||
@@ -77,6 +84,7 @@ func (s *Session) isExpired() bool {
|
||||
type sessionSnapshot struct {
|
||||
status string
|
||||
cookies map[string]string
|
||||
cookieSnapshot []cookierefresh.BrowserCookie
|
||||
unb string
|
||||
params map[string]string
|
||||
verificationURL string
|
||||
@@ -91,37 +99,19 @@ func (s *Session) snapshot() sessionSnapshot {
|
||||
defer s.mu.RUnlock()
|
||||
return sessionSnapshot{
|
||||
status: s.Status, cookies: cloneCookieMap(s.cookies), unb: s.unb,
|
||||
params: cloneCookieMap(s.params), verificationURL: s.verificationURL,
|
||||
cookieSnapshot: cloneCookieSnapshot(s.cookieSnapshot),
|
||||
params: cloneCookieMap(s.params), verificationURL: s.verificationURL,
|
||||
verificationScreenshot: s.verificationScreenshot, faceQRURL: s.faceQRURL,
|
||||
expireTime: s.expireTime, createdTime: s.createdTime,
|
||||
}
|
||||
}
|
||||
|
||||
// BrowserRefresher 由外部注入的浏览器刷新函数。
|
||||
// tmpCookies: 扫码临时 cookie;verificationURL: Chromium 打开后持有 session 等待验证。
|
||||
// onScreenshot: 每次截图时回调(data:image/png;base64,...),前端实时显示验证页画面。
|
||||
type BrowserRefresher func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (realCookies string, unb string, err error)
|
||||
|
||||
// Manager 扫码登录管理器。
|
||||
type Manager struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]*Session
|
||||
httpc *http.Client
|
||||
logger *slog.Logger
|
||||
browser BrowserRefresher // 可选:风控验证后用浏览器提取真实 cookie
|
||||
}
|
||||
|
||||
// SetBrowserRefresher 注入浏览器刷新函数(风控验证场景必需)。
|
||||
func (m *Manager) SetBrowserRefresher(f BrowserRefresher) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.browser = f
|
||||
}
|
||||
|
||||
func (m *Manager) browserRefresher() BrowserRefresher {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.browser
|
||||
}
|
||||
|
||||
// NewManager 构造。
|
||||
@@ -143,12 +133,13 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
|
||||
return "", "", fmt.Errorf("生成扫码会话 ID: %w", err)
|
||||
}
|
||||
sess := &Session{
|
||||
SessionID: sessionID,
|
||||
Status: "waiting",
|
||||
cookies: make(map[string]string),
|
||||
createdTime: time.Now(),
|
||||
expireTime: 5 * time.Minute,
|
||||
params: make(map[string]string),
|
||||
SessionID: sessionID,
|
||||
Status: "waiting",
|
||||
cookies: make(map[string]string),
|
||||
cookieSnapshot: []cookierefresh.BrowserCookie{},
|
||||
createdTime: time.Now(),
|
||||
expireTime: 5 * time.Minute,
|
||||
params: make(map[string]string),
|
||||
}
|
||||
|
||||
// 1. 获取 m_h5_tk。
|
||||
@@ -170,13 +161,16 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
|
||||
}
|
||||
req.URL.RawQuery = q.Encode()
|
||||
m.setHeaders(req)
|
||||
if cookieStr := sessionCookieHeader(sess, req.URL.String()); cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
|
||||
resp, err := m.httpc.Do(req)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("请求二维码接口失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
mergeSessionResponseCookies(sess, resp.Cookies())
|
||||
absorbSessionResponse(sess, apiGenerateQR, resp)
|
||||
body, err := readQRBody(resp.Body)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
@@ -255,6 +249,7 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
|
||||
}
|
||||
snapshot := sessionSnapshot{
|
||||
status: sess.Status, cookies: cloneCookieMap(sess.cookies), unb: sess.unb,
|
||||
cookieSnapshot: cloneCookieSnapshot(sess.cookieSnapshot),
|
||||
verificationURL: sess.verificationURL, verificationScreenshot: sess.verificationScreenshot,
|
||||
faceQRURL: sess.faceQRURL,
|
||||
}
|
||||
@@ -275,8 +270,14 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
|
||||
}
|
||||
}
|
||||
if snapshot.status == "success" && snapshot.cookies != nil && snapshot.unb != "" {
|
||||
result["cookies"] = cookieMarshal(snapshot.cookies)
|
||||
result["cookies"] = snapshotCookieHeader(snapshot, qrVerifyTargetURL)
|
||||
result["unb"] = snapshot.unb
|
||||
if snapshot.cookieSnapshot != nil {
|
||||
result["cookie_snapshot"] = cloneCookieSnapshot(snapshot.cookieSnapshot)
|
||||
}
|
||||
}
|
||||
if snapshot.status == "error" {
|
||||
result["message"] = "扫码登录接口连续返回异常,请刷新二维码重试"
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -299,6 +300,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
|
||||
maxWait := 5 * time.Minute
|
||||
start := time.Now()
|
||||
serverErrors := 0
|
||||
|
||||
for time.Since(start) < maxWait {
|
||||
select {
|
||||
@@ -317,24 +319,25 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
resp, err := m.pollQRCodeStatus(ctx, sess)
|
||||
if err != nil {
|
||||
m.logger.Error("轮询扫码状态异常", "err", err)
|
||||
if !waitQRRetry(ctx, 2*time.Second) {
|
||||
if !waitQRRetry(ctx, qrPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
absorbSessionResponse(sess, apiScanStatus, resp)
|
||||
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
|
||||
mergeSessionResponseCookies(sess, resp.Cookies())
|
||||
closeErr := resp.Body.Close()
|
||||
if readErr != nil || closeErr != nil {
|
||||
m.logger.Warn("读取扫码状态响应失败", "read_err", readErr, "close_err", closeErr)
|
||||
if !waitQRRetry(ctx, 800*time.Millisecond) {
|
||||
if !waitQRRetry(ctx, qrPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
var qrResult struct {
|
||||
Content struct {
|
||||
HasError bool `json:"hasError"`
|
||||
Content struct {
|
||||
Data struct {
|
||||
QRCodeStatus string `json:"qrCodeStatus"`
|
||||
IframeRedirect bool `json:"iframeRedirect"`
|
||||
@@ -344,11 +347,24 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
}
|
||||
if err := json.Unmarshal(body, &qrResult); err != nil {
|
||||
m.logger.Warn("解析扫码状态响应失败", "err", err)
|
||||
if !waitQRRetry(ctx, 800*time.Millisecond) {
|
||||
if !waitQRRetry(ctx, qrPollInterval) {
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if qrResult.HasError {
|
||||
serverErrors++
|
||||
if serverErrors >= maxQRServerErrors {
|
||||
sess.mu.Lock()
|
||||
sess.Status = "error"
|
||||
sess.mu.Unlock()
|
||||
m.logger.Warn("扫码登录接口连续返回异常", "session_id", sessionID, "failures", serverErrors)
|
||||
return
|
||||
}
|
||||
// 官网脚本对业务层 hasError 立即重试,最多五次。
|
||||
continue
|
||||
}
|
||||
serverErrors = 0
|
||||
|
||||
status := qrResult.Content.Data.QRCodeStatus
|
||||
switch status {
|
||||
@@ -364,9 +380,8 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
if sess.Status != "verification_required" {
|
||||
sess.Status = "verification_required"
|
||||
sess.verificationURL = qrResult.Content.Data.IframeRedirectURL
|
||||
for _, c := range resp.Cookies() {
|
||||
sess.cookies[c.Name] = c.Value
|
||||
}
|
||||
// 已有权威快照交给可导出的 Go Cookie Jar;它会继续吸收
|
||||
// 人脸跳转链每个重定向响应的 Set-Cookie。
|
||||
// 人脸验证会额外占用用户手机端操作时间。这里重置窗口,避免普通
|
||||
// 扫码 5 分钟窗口在用户扫人脸二维码时把会话误标为 expired。
|
||||
sess.createdTime = time.Now()
|
||||
@@ -375,12 +390,12 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
expireTime := sess.expireTime
|
||||
cookieCount := len(sess.cookies)
|
||||
sess.mu.Unlock()
|
||||
m.logger.Warn("扫码登录需要风控验证,交给浏览器保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
|
||||
m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
|
||||
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
|
||||
go func() {
|
||||
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
|
||||
defer cancel()
|
||||
m.runBrowserVerification(verifyCtx, sessionID, verURL)
|
||||
m.runGoVerification(verifyCtx, sessionID, verURL)
|
||||
}()
|
||||
} else {
|
||||
sess.mu.Unlock()
|
||||
@@ -389,12 +404,7 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.Status = "success"
|
||||
for _, c := range resp.Cookies() {
|
||||
sess.cookies[c.Name] = c.Value
|
||||
if c.Name == "unb" {
|
||||
sess.unb = c.Value
|
||||
}
|
||||
}
|
||||
finalizeSessionCredentialsLocked(sess)
|
||||
unb := sess.unb
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("扫码登录成功", "session_id", sessionID, "account_hash", logsafe.ID(unb))
|
||||
@@ -414,14 +424,23 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
m.logger.Info("二维码已扫描,等待确认", "session_id", sessionID)
|
||||
}
|
||||
sess.mu.Unlock()
|
||||
default:
|
||||
case "CANCELED":
|
||||
sess.mu.Lock()
|
||||
sess.Status = "cancelled"
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("用户取消登录", "session_id", sessionID)
|
||||
return
|
||||
case "ERROR":
|
||||
sess.mu.Lock()
|
||||
sess.Status = "error"
|
||||
sess.mu.Unlock()
|
||||
m.logger.Warn("扫码登录接口返回错误状态", "session_id", sessionID)
|
||||
return
|
||||
default:
|
||||
// 官网脚本对未识别状态按普通未扫码状态处理,等待下一轮,
|
||||
// 不能擅自推断成用户取消。
|
||||
}
|
||||
if !waitQRRetry(ctx, 800*time.Millisecond) {
|
||||
if !waitQRRetry(ctx, qrPollInterval) {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -434,62 +453,14 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) {
|
||||
sess.mu.Unlock()
|
||||
}
|
||||
|
||||
func (m *Manager) runBrowserVerification(ctx context.Context, sessionID, verificationURL string) {
|
||||
if strings.Contains(verificationURL, "/iv/") || strings.Contains(verificationURL, "identity_verify") {
|
||||
if err := m.runFaceVerification(ctx, sessionID, verificationURL); err == nil {
|
||||
return
|
||||
} else {
|
||||
m.logger.Warn("扫码人脸验证 HTTP 流程未完成,回退浏览器", "session_id", sessionID, "err", err)
|
||||
}
|
||||
}
|
||||
browser := m.browserRefresher()
|
||||
if browser == nil {
|
||||
m.logger.Warn("扫码验证需要浏览器支持,保持人工验证状态", "session_id", sessionID)
|
||||
func (m *Manager) runGoVerification(ctx context.Context, sessionID, verificationURL string) {
|
||||
if !strings.Contains(verificationURL, "/iv/") && !strings.Contains(verificationURL, "identity_verify") {
|
||||
m.logger.Warn("扫码验证地址不属于已支持的人脸流程,保持人工验证状态", "session_id", sessionID, "verification_url", logsafe.URL(verificationURL))
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
sess := m.sessions[sessionID]
|
||||
m.mu.Unlock()
|
||||
if sess == nil {
|
||||
return
|
||||
if err := m.runFaceVerification(ctx, sessionID, verificationURL); err != nil {
|
||||
m.logger.Warn("扫码人脸验证 Go HTTP 流程未完成,保持人工验证状态", "session_id", sessionID, "err", err)
|
||||
}
|
||||
state := sess.snapshot()
|
||||
realCookies, browserUNB, err := browser(ctx, cookieMarshal(state.cookies), verificationURL, func(dataURL string) {
|
||||
m.mu.Lock()
|
||||
current := m.sessions[sessionID]
|
||||
m.mu.Unlock()
|
||||
if current == nil {
|
||||
return
|
||||
}
|
||||
current.mu.Lock()
|
||||
current.verificationScreenshot = dataURL
|
||||
current.mu.Unlock()
|
||||
})
|
||||
if err != nil {
|
||||
m.logger.Warn("浏览器扫码验证未完成", "session_id", sessionID, "err", err)
|
||||
return
|
||||
}
|
||||
parsed := parseCookieStr(realCookies)
|
||||
if browserUNB == "" {
|
||||
browserUNB = parsed["unb"]
|
||||
}
|
||||
if len(parsed) == 0 || browserUNB == "" {
|
||||
m.logger.Warn("浏览器扫码验证未返回完整登录凭证", "session_id", sessionID)
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
sess = m.sessions[sessionID]
|
||||
m.mu.Unlock()
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.cookies = parsed
|
||||
sess.unb = browserUNB
|
||||
sess.Status = "success"
|
||||
sess.verificationScreenshot = ""
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("浏览器扫码验证成功", "session_id", sessionID, "account_hash", logsafe.ID(browserUNB), "cookie_count", len(parsed))
|
||||
}
|
||||
|
||||
func waitQRRetry(ctx context.Context, delay time.Duration) bool {
|
||||
@@ -503,8 +474,8 @@ func waitQRRetry(ctx context.Context, delay time.Duration) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// CompleteVerification 用户完成风控验证后调用:先用扫码临时 cookie 访问 goofish.com/im,
|
||||
// 必要时再使用浏览器提取真实 cookie(含 unb)。
|
||||
// CompleteVerification 用户完成风控验证后调用。整个凭证换取过程只使用
|
||||
// Go Cookie Jar;不得导航浏览器页面或通过 DOM 判断登录状态。
|
||||
func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (cookies string, unb string, err error) {
|
||||
m.mu.Lock()
|
||||
sess, ok := m.sessions[sessionID]
|
||||
@@ -517,96 +488,59 @@ func (m *Manager) CompleteVerification(ctx context.Context, sessionID string) (c
|
||||
return "", "", fmt.Errorf("无扫码临时 cookie")
|
||||
}
|
||||
if state.status == "success" && state.unb != "" {
|
||||
return cookieMarshal(state.cookies), state.unb, nil
|
||||
return snapshotCookieHeader(state, qrVerifyTargetURL), state.unb, nil
|
||||
}
|
||||
browser := m.browserRefresher()
|
||||
|
||||
m.logger.Info("开始用临时 cookie 换取真实 cookie", "session_id", sessionID, "tmp_cookie_count", len(state.cookies))
|
||||
|
||||
// 用带 cookie jar 的 client,访问 goofish.com/im 触发真实 cookie 下发。
|
||||
jarClient := &http.Client{Timeout: 30 * time.Second}
|
||||
targetURL := qrVerifyTargetURL
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
|
||||
m.setHeaders(req)
|
||||
req.Header.Set("Cookie", cookieMarshal(state.cookies))
|
||||
// im 页面 referer
|
||||
req.Header.Set("Referer", "https://www.goofish.com/")
|
||||
|
||||
seedURL := state.verificationURL
|
||||
if strings.TrimSpace(seedURL) == "" {
|
||||
seedURL = targetURL
|
||||
}
|
||||
jarClient, jar, err := m.faceHTTPClient(state.cookies, state.cookieSnapshot, seedURL, targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("创建登录 Cookie Jar: %w", err)
|
||||
}
|
||||
jarClient.Timeout = 30 * time.Second
|
||||
target, err := url.Parse(targetURL)
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("解析登录凭证换取地址: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
m.setDocumentHeaders(req)
|
||||
resp, err := jarClient.Do(req)
|
||||
if err != nil {
|
||||
if browser == nil {
|
||||
return "", "", fmt.Errorf("访问 goofish.com/im 失败: %w", err)
|
||||
}
|
||||
m.logger.Warn("纯 HTTP 访问 goofish.com/im 失败,改用浏览器提取", "session_id", sessionID, "err", err)
|
||||
} else {
|
||||
defer resp.Body.Close()
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return "", "", fmt.Errorf("读取验证响应失败: %w", err)
|
||||
}
|
||||
|
||||
// 收集 Set-Cookie。
|
||||
sess.mu.Lock()
|
||||
for _, c := range resp.Cookies() {
|
||||
sess.cookies[c.Name] = c.Value
|
||||
if c.Name == "unb" {
|
||||
sess.unb = c.Value
|
||||
}
|
||||
}
|
||||
sess.mu.Unlock()
|
||||
return "", "", fmt.Errorf("访问 goofish.com/im 换取登录凭证失败: %w", err)
|
||||
}
|
||||
|
||||
// 如果还没 unb 且没有浏览器刷新器,再访问 mtop token API 触发(有时需要额外请求)。
|
||||
// 有浏览器刷新器时直接走浏览器路径,避免在风控场景中重复纯 HTTP 请求。
|
||||
state = sess.snapshot()
|
||||
if state.unb == "" && browser == nil {
|
||||
m.logger.Info("首次访问未拿到 unb,尝试 mtop token API", "session_id", sessionID)
|
||||
if err := m.getMH5TK(ctx, sess); err != nil {
|
||||
m.logger.Warn("mtop token API 失败", "err", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return "", "", fmt.Errorf("读取登录凭证换取响应失败: %w", err)
|
||||
}
|
||||
|
||||
state = sess.snapshot()
|
||||
m.logger.Info("验证完成,提取 cookie", "session_id", sessionID, "cookie_count", len(state.cookies), "has_unb", state.unb != "")
|
||||
if state.unb != "" {
|
||||
sess.mu.Lock()
|
||||
sess.Status = "success"
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("纯 HTTP 提取 cookie 成功", "session_id", sessionID, "account_hash", logsafe.ID(state.unb))
|
||||
return cookieMarshal(state.cookies), state.unb, nil
|
||||
var responseURL *url.URL
|
||||
if resp.Request != nil {
|
||||
responseURL = resp.Request.URL
|
||||
}
|
||||
|
||||
// 纯 HTTP 拿不到 unb(闲鱼真实 cookie 由页面 JS 异步下发),
|
||||
// 风控验证后的 cookie 提取必须依赖浏览器。
|
||||
if browser == nil {
|
||||
return "", "", fmt.Errorf("风控验证后的 cookie 提取需要浏览器支持(请勿使用 -no-browser 启动)")
|
||||
}
|
||||
|
||||
m.logger.Info("纯 HTTP 未拿到 unb,调用浏览器提取", "session_id", sessionID)
|
||||
realCookies, browserUNB, err := browser(ctx, cookieMarshal(state.cookies), state.verificationURL, nil)
|
||||
if err != nil {
|
||||
m.logger.Error("浏览器提取失败", "err", err)
|
||||
return "", "", fmt.Errorf("浏览器提取 cookie 失败: %w", err)
|
||||
}
|
||||
parsedCookies := parseCookieStr(realCookies)
|
||||
if len(parsedCookies) == 0 {
|
||||
return "", "", fmt.Errorf("浏览器提取 cookie 失败: 未返回有效 cookie")
|
||||
finalCookies := collectJarCookies(jar, target, responseURL)
|
||||
finalUNB := finalCookies["unb"]
|
||||
if finalUNB == "" {
|
||||
return "", "", fmt.Errorf("纯 Go 登录凭证换取未获取到 unb,验证可能尚未完成或临时 Cookie 已失效")
|
||||
}
|
||||
sess.mu.Lock()
|
||||
sess.cookies = parsedCookies
|
||||
sess.unb = browserUNB
|
||||
if sess.unb == "" {
|
||||
sess.unb = sess.cookies["unb"]
|
||||
}
|
||||
if sess.unb == "" {
|
||||
sess.mu.Unlock()
|
||||
return "", "", fmt.Errorf("验证后仍未获取到 unb,可能验证未完成或临时 cookie 已失效")
|
||||
sess.cookies = finalCookies
|
||||
if finalSnapshot, complete := jar.Snapshot(); complete {
|
||||
sess.cookieSnapshot = finalSnapshot
|
||||
} else {
|
||||
sess.cookieSnapshot = nil
|
||||
}
|
||||
sess.unb = finalUNB
|
||||
sess.Status = "success"
|
||||
finalCookies := cloneCookieMap(sess.cookies)
|
||||
finalUNB := sess.unb
|
||||
sess.verificationScreenshot = ""
|
||||
sess.mu.Unlock()
|
||||
m.logger.Info("浏览器提取成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
|
||||
return cookieMarshal(finalCookies), finalUNB, nil
|
||||
m.logger.Info("纯 Go 提取登录凭证成功", "session_id", sessionID, "account_hash", logsafe.ID(finalUNB), "cookie_count", len(finalCookies))
|
||||
return snapshotCookieHeader(sess.snapshot(), qrVerifyTargetURL), finalUNB, nil
|
||||
}
|
||||
|
||||
// parseCookieStr 把 "k=v; k2=v2" 解析回 map。
|
||||
@@ -630,18 +564,11 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
absorbSessionResponse(sess, apiH5TK, resp)
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 合并 Set-Cookie。
|
||||
sess.mu.Lock()
|
||||
for _, c := range resp.Cookies() {
|
||||
sess.cookies[c.Name] = c.Value
|
||||
}
|
||||
|
||||
mH5TK := sess.cookies["_m_h5_tk"]
|
||||
sess.mu.Unlock()
|
||||
mH5TK := protocolCookieValue(sessionCookieHeader(sess, apiH5TK), "_m_h5_tk")
|
||||
token := ""
|
||||
if parts := strings.SplitN(mH5TK, "_", 2); len(parts) > 0 {
|
||||
token = parts[0]
|
||||
@@ -667,9 +594,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
req2, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiH5TK+"?"+params.Encode(), nil)
|
||||
m.setHeaders(req2)
|
||||
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
sess.mu.RLock()
|
||||
cookieStr := cookieMarshal(sess.cookies)
|
||||
sess.mu.RUnlock()
|
||||
cookieStr := sessionCookieHeader(sess, req2.URL.String())
|
||||
if cookieStr != "" {
|
||||
req2.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
@@ -679,7 +604,7 @@ func (m *Manager) getMH5TK(ctx context.Context, sess *Session) error {
|
||||
return err
|
||||
}
|
||||
defer resp2.Body.Close()
|
||||
mergeSessionResponseCookies(sess, resp2.Cookies())
|
||||
absorbSessionResponse(sess, req2.URL.String(), resp2)
|
||||
if _, err := io.Copy(io.Discard, resp2.Body); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -706,9 +631,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
|
||||
m.setHeaders(req)
|
||||
|
||||
// 带上已有 cookie。
|
||||
sess.mu.RLock()
|
||||
cookieStr := cookieMarshal(sess.cookies)
|
||||
sess.mu.RUnlock()
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
@@ -718,7 +641,7 @@ func (m *Manager) getLoginParams(ctx context.Context, sess *Session) (map[string
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
mergeSessionResponseCookies(sess, resp.Cookies())
|
||||
absorbSessionResponse(sess, req.URL.String(), resp)
|
||||
body, err := readQRBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -761,11 +684,22 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
|
||||
for k, v := range state.params {
|
||||
form.Set(k, v)
|
||||
}
|
||||
fingerprint := xianyu.CurrentBrowserFingerprint()
|
||||
// 对齐 havana-nlogin 二维码组件 query.do 的浏览器环境字段。
|
||||
// ua 是 AWSC/UAB 的可选结果;纯 Go 客户端在该值尚未生成时与官网
|
||||
// 脚本一样发送空值,不借助 Chromium 执行业务页面脚本。
|
||||
form.Set("ua", "")
|
||||
form.Set("navlanguage", "zh-CN")
|
||||
form.Set("navUserAgent", fingerprint.UserAgent)
|
||||
form.Set("navPlatform", navigatorPlatform(fingerprint.Platform))
|
||||
form.Set("isIframe", "true")
|
||||
form.Set("documentReferer", qrVerifyTargetURL)
|
||||
form.Set("defaultView", "qrcode")
|
||||
|
||||
req, _ := http.NewRequestWithContext(ctx, http.MethodPost, apiScanStatus, strings.NewReader(form.Encode()))
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
m.setHeaders(req)
|
||||
cookieStr := cookieMarshal(state.cookies)
|
||||
cookieStr := sessionCookieHeader(sess, req.URL.String())
|
||||
if cookieStr != "" {
|
||||
req.Header.Set("Cookie", cookieStr)
|
||||
}
|
||||
@@ -773,6 +707,23 @@ func (m *Manager) pollQRCodeStatus(ctx context.Context, sess *Session) (*http.Re
|
||||
return m.httpc.Do(req)
|
||||
}
|
||||
|
||||
func navigatorPlatform(secCHPlatform string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(secCHPlatform)) {
|
||||
case "windows":
|
||||
return "Win32"
|
||||
case "macos":
|
||||
return "MacIntel"
|
||||
case "linux":
|
||||
return "Linux x86_64"
|
||||
case "android":
|
||||
return "Linux armv8l"
|
||||
case "ios":
|
||||
return "iPhone"
|
||||
default:
|
||||
return strings.TrimSpace(secCHPlatform)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) setHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
for k, v := range qrHeaders {
|
||||
@@ -780,16 +731,62 @@ func (m *Manager) setHeaders(req *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func mergeSessionResponseCookies(sess *Session, cookies []*http.Cookie) {
|
||||
if sess == nil || len(cookies) == 0 {
|
||||
// setDocumentHeaders 复刻浏览器从闲鱼首页进入 /im 的文档请求头。这里只
|
||||
// 发送 HTTP 请求并接收 Set-Cookie,不加载或校验任何页面 DOM。
|
||||
func (m *Manager) setDocumentHeaders(req *http.Request) {
|
||||
xianyu.ApplyBrowserFingerprint(req.Header)
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Referer", "https://www.goofish.com/")
|
||||
req.Header.Set("Sec-Fetch-Dest", "document")
|
||||
req.Header.Set("Sec-Fetch-Mode", "navigate")
|
||||
req.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
req.Header.Set("Upgrade-Insecure-Requests", "1")
|
||||
}
|
||||
|
||||
func sessionCookieHeader(sess *Session, requestURL string) string {
|
||||
if sess == nil {
|
||||
return ""
|
||||
}
|
||||
return snapshotCookieHeader(sess.snapshot(), requestURL)
|
||||
}
|
||||
|
||||
func snapshotCookieHeader(state sessionSnapshot, requestURL string) string {
|
||||
if state.cookieSnapshot != nil {
|
||||
if value, authoritative := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
state.cookieSnapshot, requestURL, qrTopSite, time.Now(),
|
||||
); authoritative {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return cookieMarshal(state.cookies)
|
||||
}
|
||||
|
||||
func absorbSessionResponse(sess *Session, requestURL string, resp *http.Response) {
|
||||
if sess == nil || resp == nil {
|
||||
return
|
||||
}
|
||||
sess.mu.Lock()
|
||||
defer sess.mu.Unlock()
|
||||
for _, cookie := range cookies {
|
||||
if sess.cookieSnapshot != nil {
|
||||
sess.cookieSnapshot = cookierefresh.ApplySetCookies(
|
||||
sess.cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), qrTopSite,
|
||||
)
|
||||
if sess.cookieSnapshot == nil {
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
for _, cookie := range resp.Cookies() {
|
||||
if cookie == nil || cookie.Name == "" {
|
||||
continue
|
||||
}
|
||||
if cookie.MaxAge < 0 || (!cookie.Expires.IsZero() && !cookie.Expires.After(time.Now())) {
|
||||
delete(sess.cookies, cookie.Name)
|
||||
if cookie.Name == "unb" {
|
||||
sess.unb = ""
|
||||
}
|
||||
continue
|
||||
}
|
||||
sess.cookies[cookie.Name] = cookie.Value
|
||||
if cookie.Name == "unb" && cookie.Value != "" {
|
||||
sess.unb = cookie.Value
|
||||
@@ -797,6 +794,42 @@ func mergeSessionResponseCookies(sess *Session, cookies []*http.Cookie) {
|
||||
}
|
||||
}
|
||||
|
||||
func finalizeSessionCredentialsLocked(sess *Session) {
|
||||
if sess == nil {
|
||||
return
|
||||
}
|
||||
if sess.cookieSnapshot != nil {
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(
|
||||
sess.cookieSnapshot, qrVerifyTargetURL, qrTopSite, time.Now(),
|
||||
)
|
||||
sess.cookies = parseCookieStr(value)
|
||||
}
|
||||
if unb := sess.cookies["unb"]; unb != "" {
|
||||
sess.unb = unb
|
||||
}
|
||||
}
|
||||
|
||||
func cloneCookieSnapshot(in []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := cookierefresh.NormalizeSnapshot(in)
|
||||
if out == nil {
|
||||
return []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func protocolCookieValue(cookieHeader, name string) string {
|
||||
for _, part := range strings.Split(cookieHeader, ";") {
|
||||
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
if ok && key == name {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ---- 工具函数 ----
|
||||
|
||||
func md5hex(s string) string {
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
type failingReader struct{}
|
||||
@@ -54,7 +56,7 @@ func TestSessionStatusConcurrentSnapshot(t *testing.T) {
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
|
||||
func TestCompleteVerificationRequiresPureGoCredentialResult(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
oldTarget := qrVerifyTargetURL
|
||||
@@ -62,7 +64,7 @@ func TestCompleteVerificationRequiresBrowserWhenHTTPMissingUNB(t *testing.T) {
|
||||
defer func() { qrVerifyTargetURL = oldTarget }()
|
||||
|
||||
_, _, err := m.CompleteVerification(context.Background(), "s1")
|
||||
if err == nil || !strings.Contains(err.Error(), "需要浏览器支持") {
|
||||
if err == nil || !strings.Contains(err.Error(), "纯 Go 登录凭证换取未获取到 unb") {
|
||||
t.Fatalf("错误异常: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -81,50 +83,6 @@ func TestCompleteVerificationReturnsCompletedSessionWithoutAnotherRequest(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationBrowserSuccess(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
if !strings.Contains(tmpCookies, "tmp=1") {
|
||||
t.Fatalf("浏览器刷新器收到临时 cookie 异常: %q", tmpCookies)
|
||||
}
|
||||
return "unb=999; cookie2=abc", "999", nil
|
||||
})
|
||||
oldTarget := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = newEmptyCookieServer(t)
|
||||
defer func() { qrVerifyTargetURL = oldTarget }()
|
||||
|
||||
cookies, unb, err := m.CompleteVerification(context.Background(), "s1")
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteVerification: %v", err)
|
||||
}
|
||||
if unb != "999" || !strings.Contains(cookies, "unb=999") {
|
||||
t.Fatalf("返回异常: cookies=%q unb=%q", cookies, unb)
|
||||
}
|
||||
if m.sessions["s1"].Status != "success" {
|
||||
t.Fatalf("状态异常: %s", m.sessions["s1"].Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationBrowserUNBFromCookieMap(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s1"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "unb=888; cookie2=abc", "", nil
|
||||
})
|
||||
oldTarget := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = newEmptyCookieServer(t)
|
||||
defer func() { qrVerifyTargetURL = oldTarget }()
|
||||
|
||||
_, unb, err := m.CompleteVerification(context.Background(), "s1")
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteVerification: %v", err)
|
||||
}
|
||||
if unb != "888" {
|
||||
t.Fatalf("应从 cookie map 提取 unb,got %q", unb)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationMissingSession(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
_, _, err := m.CompleteVerification(context.Background(), "missing")
|
||||
@@ -203,6 +161,25 @@ func TestCollectJarCookies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFaceCookieJarExportsCrossDomainAttributes(t *testing.T) {
|
||||
jar := newFaceCookieJar(map[string]string{"tmp": "1"}, []cookierefresh.BrowserCookie{})
|
||||
passport, _ := url.Parse("https://passport.goofish.com/ivCheckLogin.htm")
|
||||
input := &http.Cookie{
|
||||
Name: "unb", Value: "777", Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true,
|
||||
}
|
||||
jar.SetCookies(passport, []*http.Cookie{input})
|
||||
www, _ := url.Parse("https://www.goofish.com/im")
|
||||
got := collectJarCookies(jar, www)
|
||||
if got["unb"] != "777" {
|
||||
snapshot, _ := jar.Snapshot()
|
||||
t.Fatalf("跨域 Cookie 未进入 /im: cookies=%v snapshot=%+v raw=%q", got, snapshot, input.String())
|
||||
}
|
||||
snapshot, complete := jar.Snapshot()
|
||||
if !complete || len(snapshot) != 1 || snapshot[0].Domain != ".goofish.com" || !snapshot[0].HTTPOnly || !snapshot[0].Secure {
|
||||
t.Fatalf("完整 Cookie 属性未保留: complete=%v snapshot=%+v", complete, snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func testVerificationSession() *Session {
|
||||
return &Session{
|
||||
SessionID: "s1",
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -16,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/xianyu"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// stubTransport 把所有请求转发到 httptest.Server,保留路径与查询,
|
||||
@@ -50,6 +52,35 @@ func newStubbedManager(t *testing.T, handler http.Handler) (*Manager, *httptest.
|
||||
return m, srv, tr
|
||||
}
|
||||
|
||||
func TestAbsorbSessionResponsePreservesCookieScope(t *testing.T) {
|
||||
sess := &Session{cookies: map[string]string{}, cookieSnapshot: []cookierefresh.BrowserCookie{}}
|
||||
resp := &http.Response{Header: http.Header{
|
||||
"Set-Cookie": {"_m_h5_tk=tok_1; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
|
||||
}}
|
||||
absorbSessionResponse(sess, apiH5TK, resp)
|
||||
if got := sessionCookieHeader(sess, apiGenerateQR); !strings.Contains(got, "_m_h5_tk=tok_1") {
|
||||
t.Fatalf("跨子域 Cookie 作用域丢失: header=%q snapshot=%+v", got, sess.cookieSnapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAbsorbSessionResponseDeletesExpiredFlatCookie(t *testing.T) {
|
||||
sess := &Session{
|
||||
cookies: map[string]string{"unb": "stale", "keep": "yes"},
|
||||
cookieSnapshot: []cookierefresh.BrowserCookie{},
|
||||
unb: "stale",
|
||||
}
|
||||
resp := &http.Response{Header: http.Header{
|
||||
"Set-Cookie": {"unb=; Domain=.goofish.com; Path=/; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT"},
|
||||
}}
|
||||
absorbSessionResponse(sess, apiScanStatus, resp)
|
||||
if _, exists := sess.cookies["unb"]; exists || sess.unb != "" {
|
||||
t.Fatalf("服务端删除 Cookie 后扁平兼容状态仍残留 unb: cookies=%v unb=%q", sess.cookies, sess.unb)
|
||||
}
|
||||
if sess.cookies["keep"] != "yes" {
|
||||
t.Fatalf("删除 unb 时不得丢失无关 Cookie: %v", sess.cookies)
|
||||
}
|
||||
}
|
||||
|
||||
// gzipBody 用 gzip 压缩输入字符串。
|
||||
func gzipBody(t *testing.T, raw string) []byte {
|
||||
t.Helper()
|
||||
@@ -254,9 +285,10 @@ func TestGetLoginParamsEmptyLoginFormData(t *testing.T) {
|
||||
|
||||
func TestGenerateQRCodeSuccess(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
var generateCookie string
|
||||
// getMH5TK 路径
|
||||
hc.handle("/h5/mtop.gaia.nodejs.gaia.idle.data.gw.v2.index.get/1.0/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tok_1717"})
|
||||
w.Header().Add("Set-Cookie", "_m_h5_tk=tok_1717; Domain=.goofish.com; Path=/; Secure; HttpOnly")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
// getLoginParams 路径
|
||||
@@ -265,6 +297,7 @@ func TestGenerateQRCodeSuccess(t *testing.T) {
|
||||
}))
|
||||
// generate.do 二维码接口
|
||||
hc.handle("/newlogin/qrcode/generate.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
generateCookie = r.Header.Get("Cookie")
|
||||
resp := map[string]any{
|
||||
"content": map[string]any{
|
||||
"success": true,
|
||||
@@ -304,6 +337,9 @@ func TestGenerateQRCodeSuccess(t *testing.T) {
|
||||
if sess.qrContent != "https://login/qr?token=xyz" {
|
||||
t.Fatalf("qrContent 异常: %q", sess.qrContent)
|
||||
}
|
||||
if !strings.Contains(generateCookie, "_m_h5_tk=tok_1717") {
|
||||
t.Fatalf("生成二维码请求未继承当前 Cookie: %q snapshot=%+v cookies=%v", generateCookie, sess.cookieSnapshot, sess.cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateQRCodeFailureResponse(t *testing.T) {
|
||||
@@ -406,9 +442,13 @@ func TestGetSessionStatusExpired(t *testing.T) {
|
||||
func TestGetSessionStatusSuccessWithCookies(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = &Session{
|
||||
SessionID: "s",
|
||||
Status: "success",
|
||||
cookies: map[string]string{"unb": "u1", "c": "v"},
|
||||
SessionID: "s",
|
||||
Status: "success",
|
||||
cookies: map[string]string{"unb": "u1", "c": "v"},
|
||||
cookieSnapshot: []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "u1", Domain: ".goofish.com", Path: "/", Secure: true, HTTPOnly: true},
|
||||
{Name: "scoped", Value: "v2", Domain: "www.goofish.com", Path: "/im", Secure: true},
|
||||
},
|
||||
unb: "u1",
|
||||
createdTime: time.Now(),
|
||||
expireTime: 5 * time.Minute,
|
||||
@@ -424,6 +464,28 @@ func TestGetSessionStatusSuccessWithCookies(t *testing.T) {
|
||||
if !strings.Contains(cookies, "unb=u1") {
|
||||
t.Fatalf("cookie 字符串异常: %q", cookies)
|
||||
}
|
||||
snapshot, ok := got["cookie_snapshot"].([]cookierefresh.BrowserCookie)
|
||||
if !ok || len(snapshot) != 2 {
|
||||
t.Fatalf("成功状态必须返回内部权威 Cookie Jar: ok=%v snapshot=%+v", ok, snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSessionStatusUsesAuthoritativeScopedCookieHeader(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = &Session{
|
||||
SessionID: "s", Status: "success", cookies: map[string]string{"unb": "u1", "same": "flat"}, unb: "u1",
|
||||
cookieSnapshot: []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "u1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "same", Value: "im", Domain: "www.goofish.com", Path: "/im", Secure: true},
|
||||
{Name: "same", Value: "root", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
},
|
||||
createdTime: time.Now(), expireTime: 5 * time.Minute,
|
||||
}
|
||||
got := m.GetSessionStatus("s")
|
||||
cookies, _ := got["cookies"].(string)
|
||||
if strings.Count(cookies, "same=") != 2 || strings.Index(cookies, "same=im") > strings.Index(cookies, "same=root") {
|
||||
t.Fatalf("同名不同 Path Cookie 被扁平化: %q", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetSessionStatusVerificationRequired(t *testing.T) {
|
||||
@@ -627,7 +689,7 @@ func TestMonitorQRStatusExpiredDoesNotKeepPolling(t *testing.T) {
|
||||
|
||||
func TestMonitorQRStatusCancelled(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
hc.handle("/newlogin/qrcode/query.do", statusHandler("REFUSED"))
|
||||
hc.handle("/newlogin/qrcode/query.do", statusHandler("CANCELED"))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
sess := newMonitorSession("waiting")
|
||||
m.sessions["s"] = sess
|
||||
@@ -641,6 +703,44 @@ func TestMonitorQRStatusCancelled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusServerHasErrorStopsAfterFiveImmediateRetries(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
var calls atomic.Int64
|
||||
hc.handle("/newlogin/qrcode/query.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
_, _ = w.Write([]byte(`{"hasError":true}`))
|
||||
}))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
sess := newMonitorSession("waiting")
|
||||
m.sessions["s"] = sess
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
m.monitorQRStatus(ctx, "s")
|
||||
|
||||
if sess.Status != "error" {
|
||||
t.Fatalf("连续业务错误应进入 error 状态: %s", sess.Status)
|
||||
}
|
||||
if got := calls.Load(); got != maxQRServerErrors {
|
||||
t.Fatalf("业务错误重试次数=%d, want %d", got, maxQRServerErrors)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusUnknownStatusKeepsPolling(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
hc.handle("/newlogin/qrcode/query.do", statusHandler("FUTURE_STATUS"))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
sess := newMonitorSession("waiting")
|
||||
m.sessions["s"] = sess
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
m.monitorQRStatus(ctx, "s")
|
||||
if sess.Status != "waiting" {
|
||||
t.Fatalf("未知状态不应被推断成取消: %s", sess.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testing.T) {
|
||||
hc := &handlerChain{}
|
||||
var queryCalls atomic.Int64
|
||||
@@ -669,13 +769,14 @@ func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testi
|
||||
_, _ = w.Write([]byte(`{"content":{"code":3,"url":"https://passport.goofish.com/ivCheckLogin.htm?ok=1"}}`))
|
||||
}))
|
||||
hc.handle("/ivCheckLogin.htm", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.SetCookie(w, &http.Cookie{Name: "unb", Value: "777", Path: "/"})
|
||||
http.SetCookie(w, &http.Cookie{Name: "cookie2", Value: "z", Path: "/"})
|
||||
http.SetCookie(w, &http.Cookie{Name: "unb", Value: "777", Domain: ".goofish.com", Path: "/", Secure: true, HttpOnly: true})
|
||||
http.SetCookie(w, &http.Cookie{Name: "cookie2", Value: "z", Domain: ".goofish.com", Path: "/", Secure: true})
|
||||
_, _ = w.Write([]byte(`ok`))
|
||||
}))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
|
||||
sess := newMonitorSession("waiting")
|
||||
sess.cookieSnapshot = []cookierefresh.BrowserCookie{}
|
||||
m.sessions["s"] = sess
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
@@ -704,6 +805,18 @@ func TestMonitorQRStatusVerificationRequiredStopsPollingAndRunsFaceFlow(t *testi
|
||||
if state.faceQRURL == "" {
|
||||
t.Fatal("人脸验证二维码未生成")
|
||||
}
|
||||
if state.cookieSnapshot == nil {
|
||||
t.Fatal("人脸验证跳转链必须保留权威 Cookie Jar")
|
||||
}
|
||||
var foundUNB bool
|
||||
for _, cookie := range state.cookieSnapshot {
|
||||
if cookie.Name == "unb" && cookie.Value == "777" && cookie.Domain == ".goofish.com" && cookie.HTTPOnly && cookie.Secure {
|
||||
foundUNB = true
|
||||
}
|
||||
}
|
||||
if !foundUNB {
|
||||
t.Fatalf("人脸验证 Cookie 属性丢失: %+v", state.cookieSnapshot)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorQRStatusMissingSession(t *testing.T) {
|
||||
@@ -784,13 +897,20 @@ func TestMonitorQRStatusSessionDeletedMidLoop(t *testing.T) {
|
||||
// ---- pollQRCodeStatus ----
|
||||
|
||||
func TestPollQRCodeStatusSetsHeadersAndCookie(t *testing.T) {
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua"})
|
||||
oldFingerprint := xianyu.CurrentBrowserFingerprint()
|
||||
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "playwright-native-ua", Platform: "macOS"})
|
||||
t.Cleanup(func() { xianyu.SetBrowserFingerprint(oldFingerprint) })
|
||||
hc := &handlerChain{}
|
||||
var gotUA, gotCookie, gotCT string
|
||||
var gotForm url.Values
|
||||
hc.handle("/newlogin/qrcode/query.do", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotUA = r.Header.Get("User-Agent")
|
||||
gotCookie = r.Header.Get("Cookie")
|
||||
gotCT = r.Header.Get("Content-Type")
|
||||
if err := r.ParseForm(); err != nil {
|
||||
t.Errorf("ParseForm: %v", err)
|
||||
}
|
||||
gotForm = r.PostForm
|
||||
_, _ = w.Write([]byte(`{}`))
|
||||
}))
|
||||
m, _, _ := newStubbedManager(t, hc)
|
||||
@@ -811,6 +931,20 @@ func TestPollQRCodeStatusSetsHeadersAndCookie(t *testing.T) {
|
||||
if gotCT != "application/x-www-form-urlencoded" {
|
||||
t.Fatalf("Content-Type 异常: %q", gotCT)
|
||||
}
|
||||
wantForm := map[string]string{
|
||||
"ua": "",
|
||||
"navlanguage": "zh-CN",
|
||||
"navUserAgent": "playwright-native-ua",
|
||||
"navPlatform": "MacIntel",
|
||||
"isIframe": "true",
|
||||
"documentReferer": qrVerifyTargetURL,
|
||||
"defaultView": "qrcode",
|
||||
}
|
||||
for key, want := range wantForm {
|
||||
if got := gotForm.Get(key); got != want {
|
||||
t.Errorf("轮询字段 %s=%q, want %q", key, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- gzip 解压(历史坑点)----
|
||||
@@ -888,74 +1022,47 @@ func TestCompleteVerificationHTTPSuccessWithUNB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationHTTPFailsWithBrowser(t *testing.T) {
|
||||
// 用一个会立即失败的 target URL(端口不存在)。
|
||||
func TestCompleteVerificationHTTPFailureDoesNotUseBrowser(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "unb=200; c=1", "200", nil
|
||||
})
|
||||
old := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = "http://127.0.0.1:0/im"
|
||||
defer func() { qrVerifyTargetURL = old }()
|
||||
|
||||
_, _, err := m.CompleteVerification(context.Background(), "s")
|
||||
if err == nil || !strings.Contains(err.Error(), "换取登录凭证失败") {
|
||||
t.Fatalf("错误异常: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationCarriesCookiesAcrossRedirects(t *testing.T) {
|
||||
var srv *httptest.Server
|
||||
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/start":
|
||||
http.SetCookie(w, &http.Cookie{Name: "redirect_anchor", Value: "1", Path: "/"})
|
||||
http.Redirect(w, r, srv.URL+"/done", http.StatusFound)
|
||||
case "/done":
|
||||
cookie, err := r.Cookie("redirect_anchor")
|
||||
if err != nil || cookie.Value != "1" {
|
||||
t.Fatalf("重定向未携带中间 Cookie: cookie=%v err=%v", cookie, err)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: "unb", Value: "redirect-account", Path: "/"})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = testVerificationSession()
|
||||
old := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = srv.URL + "/start"
|
||||
defer func() { qrVerifyTargetURL = old }()
|
||||
|
||||
cookies, unb, err := m.CompleteVerification(context.Background(), "s")
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteVerification: %v", err)
|
||||
}
|
||||
if unb != "200" {
|
||||
t.Fatalf("unb 异常: %q", unb)
|
||||
}
|
||||
if !strings.Contains(cookies, "unb=200") {
|
||||
t.Fatalf("cookies 异常: %q", cookies)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationBrowserReturnsEmptyCookies(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "noequalsign", "", nil // parseCookieStr 解析后为空 map
|
||||
})
|
||||
old := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = newEmptyCookieServer(t)
|
||||
defer func() { qrVerifyTargetURL = old }()
|
||||
|
||||
_, _, err := m.CompleteVerification(context.Background(), "s")
|
||||
if err == nil || !strings.Contains(err.Error(), "未返回有效 cookie") {
|
||||
t.Fatalf("错误异常: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationBrowserFails(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "", "", errors.New("browser boom")
|
||||
})
|
||||
old := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = newEmptyCookieServer(t)
|
||||
defer func() { qrVerifyTargetURL = old }()
|
||||
|
||||
_, _, err := m.CompleteVerification(context.Background(), "s")
|
||||
if err == nil || !strings.Contains(err.Error(), "浏览器提取 cookie 失败") {
|
||||
t.Fatalf("错误异常: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompleteVerificationBrowserNoUNBAnywhere(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
m.sessions["s"] = testVerificationSession()
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
return "cookie2=abc; cookie3=def", "", nil
|
||||
})
|
||||
old := qrVerifyTargetURL
|
||||
qrVerifyTargetURL = newEmptyCookieServer(t)
|
||||
defer func() { qrVerifyTargetURL = old }()
|
||||
|
||||
_, _, err := m.CompleteVerification(context.Background(), "s")
|
||||
if err == nil || !strings.Contains(err.Error(), "仍未获取到 unb") {
|
||||
t.Fatalf("错误异常: %v", err)
|
||||
if err != nil || unb != "redirect-account" || !strings.Contains(cookies, "redirect_anchor=1") {
|
||||
t.Fatalf("纯 Go 重定向 Cookie Jar 异常: cookies=%q unb=%q err=%v", cookies, unb, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1000,25 +1107,6 @@ func TestMd5hex(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetBrowserRefresher(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
if m.browser != nil {
|
||||
t.Fatal("初始 browser 应为 nil")
|
||||
}
|
||||
called := false
|
||||
m.SetBrowserRefresher(func(ctx context.Context, tmpCookies, verificationURL string, onScreenshot func(string)) (string, string, error) {
|
||||
called = true
|
||||
return "", "", nil
|
||||
})
|
||||
if m.browser == nil {
|
||||
t.Fatal("browser 未注入")
|
||||
}
|
||||
_, _, _ = m.browser(context.Background(), "", "", nil)
|
||||
if !called {
|
||||
t.Fatal("browser 未调用")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewManagerDefaultsLogger(t *testing.T) {
|
||||
m := NewManager(nil)
|
||||
if m.logger == nil {
|
||||
|
||||
@@ -7,16 +7,17 @@ import (
|
||||
"fmt"
|
||||
"html"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
qrcode "github.com/skip2/go-qrcode"
|
||||
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// runFaceVerification 参照闲鱼浏览器端风控跳转链,纯 HTTP 复现人脸验证流程。
|
||||
@@ -32,12 +33,13 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
|
||||
return fmt.Errorf("会话不存在")
|
||||
}
|
||||
m.mu.Unlock()
|
||||
initialCookies := sess.snapshot().cookies
|
||||
state := sess.snapshot()
|
||||
initialCookies := state.cookies
|
||||
if len(initialCookies) == 0 {
|
||||
return fmt.Errorf("无扫码临时 cookie")
|
||||
}
|
||||
|
||||
client, jar, err := m.faceHTTPClient(initialCookies, iframeURL)
|
||||
client, jar, err := m.faceHTTPClient(initialCookies, state.cookieSnapshot, iframeURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -88,15 +90,11 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
|
||||
return fmt.Errorf("请求 ivCheckLogin: %w", err)
|
||||
}
|
||||
|
||||
finalCookies := collectJarCookies(jar,
|
||||
mustParseURL(host),
|
||||
mustParseURL("https://www.goofish.com/"),
|
||||
mustParseURL(iframeURL),
|
||||
mustParseURL(ivCheckURL),
|
||||
)
|
||||
finalCookies := collectJarCookies(jar, mustParseURL(qrVerifyTargetURL))
|
||||
if finalCookies["unb"] == "" {
|
||||
return fmt.Errorf("人脸验证完成但未获取到 unb")
|
||||
}
|
||||
finalSnapshot, snapshotComplete := jar.Snapshot()
|
||||
|
||||
m.mu.Lock()
|
||||
s = m.sessions[sessionID]
|
||||
@@ -104,6 +102,11 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
|
||||
if s != nil {
|
||||
s.mu.Lock()
|
||||
s.cookies = finalCookies
|
||||
if snapshotComplete {
|
||||
s.cookieSnapshot = finalSnapshot
|
||||
} else {
|
||||
s.cookieSnapshot = nil
|
||||
}
|
||||
s.unb = finalCookies["unb"]
|
||||
s.Status = "success"
|
||||
s.mu.Unlock()
|
||||
@@ -112,20 +115,112 @@ func (m *Manager) runFaceVerification(ctx context.Context, sessionID, iframeURL
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) faceHTTPClient(cookies map[string]string, iframeURL string) (*http.Client, http.CookieJar, error) {
|
||||
jar, err := cookiejar.New(nil)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
setJarCookies(jar, mustParseURL(host), cookies)
|
||||
if u, err := url.Parse(iframeURL); err == nil {
|
||||
setJarCookies(jar, u, cookies)
|
||||
func (m *Manager) faceHTTPClient(cookies map[string]string, snapshot []cookierefresh.BrowserCookie, seedURLs ...string) (*http.Client, *faceCookieJar, error) {
|
||||
jar := newFaceCookieJar(cookies, snapshot)
|
||||
if snapshot == nil {
|
||||
setJarCookies(jar, mustParseURL(host), cookies)
|
||||
for _, rawURL := range seedURLs {
|
||||
if u, err := url.Parse(rawURL); err == nil {
|
||||
setJarCookies(jar, u, cookies)
|
||||
}
|
||||
}
|
||||
}
|
||||
hc := *m.httpc
|
||||
hc.Jar = jar
|
||||
return &hc, jar, nil
|
||||
}
|
||||
|
||||
// faceCookieJar 是人脸验证与登录凭证换取专用的 Go Cookie Jar。标准库
|
||||
// cookiejar 能正确发送 Cookie,但没有导出完整 Jar 的接口;这个实现直接以
|
||||
// BrowserCookie 为权威状态,使自动重定向中的每个 Set-Cookie 都能原样进入
|
||||
// 最终持久化快照。
|
||||
type faceCookieJar struct {
|
||||
mu sync.Mutex
|
||||
snapshot []cookierefresh.BrowserCookie
|
||||
authoritative bool
|
||||
}
|
||||
|
||||
func newFaceCookieJar(cookies map[string]string, snapshot []cookierefresh.BrowserCookie) *faceCookieJar {
|
||||
jar := &faceCookieJar{authoritative: snapshot != nil}
|
||||
if snapshot != nil {
|
||||
jar.snapshot = cookierefresh.NormalizeSnapshot(snapshot)
|
||||
if jar.snapshot == nil {
|
||||
jar.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
return jar
|
||||
}
|
||||
// 只有历史/异常会话才会走这里。推断快照仅用于维持 HTTP 会话,
|
||||
// authoritative=false 保证调用方不会把推断属性持久化成完整 Jar。
|
||||
jar.snapshot = cookierefresh.SnapshotFromCookieString(cookieMarshal(cookies), ".goofish.com")
|
||||
return jar
|
||||
}
|
||||
|
||||
func (j *faceCookieJar) Cookies(u *url.URL) []*http.Cookie {
|
||||
if j == nil || u == nil {
|
||||
return nil
|
||||
}
|
||||
j.mu.Lock()
|
||||
header, _ := cookierefresh.ScopedCookieHeaderForRequest(j.snapshot, u.String(), qrTopSite, time.Now())
|
||||
j.mu.Unlock()
|
||||
if header == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(header, ";")
|
||||
out := make([]*http.Cookie, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
|
||||
if !ok || name == "" {
|
||||
continue
|
||||
}
|
||||
out = append(out, &http.Cookie{Name: name, Value: value})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (j *faceCookieJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
|
||||
if j == nil || u == nil || len(cookies) == 0 {
|
||||
return
|
||||
}
|
||||
raw := make([]string, 0, len(cookies))
|
||||
for _, cookie := range cookies {
|
||||
if cookie == nil || strings.TrimSpace(cookie.Name) == "" {
|
||||
continue
|
||||
}
|
||||
line := strings.TrimSpace(cookie.Raw)
|
||||
if line == "" {
|
||||
line = cookie.String()
|
||||
}
|
||||
if line != "" {
|
||||
raw = append(raw, line)
|
||||
}
|
||||
}
|
||||
if len(raw) == 0 {
|
||||
return
|
||||
}
|
||||
j.mu.Lock()
|
||||
j.snapshot = cookierefresh.ApplySetCookies(j.snapshot, u.String(), raw, time.Now(), qrTopSite)
|
||||
if j.snapshot == nil {
|
||||
j.snapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
j.mu.Unlock()
|
||||
}
|
||||
|
||||
func (j *faceCookieJar) Snapshot() ([]cookierefresh.BrowserCookie, bool) {
|
||||
if j == nil {
|
||||
return nil, false
|
||||
}
|
||||
j.mu.Lock()
|
||||
defer j.mu.Unlock()
|
||||
if !j.authoritative {
|
||||
return nil, false
|
||||
}
|
||||
out := cookierefresh.NormalizeSnapshot(j.snapshot)
|
||||
if out == nil {
|
||||
out = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func (m *Manager) faceGetHTML(ctx context.Context, client *http.Client, targetURL, referer string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
|
||||
if err != nil {
|
||||
|
||||
@@ -42,6 +42,9 @@ type Service struct {
|
||||
SetLoginSettingsURL string
|
||||
DocumentReferer string
|
||||
RetryDelay time.Duration
|
||||
// PromiseTimeout 仅供测试缩短官网固定的 2 秒 Promise.race 窗口;
|
||||
// 生产零值始终使用 defaultRequestTimout。
|
||||
PromiseTimeout time.Duration
|
||||
}
|
||||
|
||||
type LongLoginSettings struct {
|
||||
@@ -267,6 +270,57 @@ type Result struct {
|
||||
ResponseText string
|
||||
NeedPasswordLogin bool
|
||||
RequestCount int
|
||||
pending <-chan pendingRenewResult
|
||||
responseCookieURL string
|
||||
}
|
||||
|
||||
type pendingRenewResult struct {
|
||||
result *Result
|
||||
err error
|
||||
}
|
||||
|
||||
// HasPending 表示官网 2 秒 Promise 已结束,但底层 fetch 仍在接收响应。
|
||||
func (r *Result) HasPending() bool { return r != nil && r.pending != nil }
|
||||
|
||||
// AwaitPending 等待底层 fetch 的最终响应。只能由一个持久化调用方消费一次。
|
||||
func (r *Result) AwaitPending(ctx context.Context) (*Result, error) {
|
||||
if r == nil || r.pending == nil {
|
||||
return nil, nil
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case outcome, ok := <-r.pending:
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return outcome.result, outcome.err
|
||||
}
|
||||
}
|
||||
|
||||
// RebaseResponseCookies 把续期响应的 Set-Cookie 应用到“当前最新”凭证状态。
|
||||
// 后台 fetch 可能晚于其他 MTOP 请求返回,必须重放响应头而不是覆盖成请求发起
|
||||
// 时计算出的旧快照。
|
||||
func RebaseResponseCookies(currentCookies, currentMetadata string, result *Result) (string, string, bool) {
|
||||
if result == nil || len(result.SetCookies) == 0 {
|
||||
return currentCookies, currentMetadata, false
|
||||
}
|
||||
requestURL := strings.TrimSpace(result.responseCookieURL)
|
||||
if requestURL == "" {
|
||||
requestURL = SilentHasLoginURL
|
||||
}
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(currentMetadata); complete {
|
||||
updated := cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), goofishTopSite)
|
||||
if updated == nil {
|
||||
updated = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
value, _ := cookierefresh.ScopedCookieHeaderForRequest(updated, goofishIMDocumentURL, goofishTopSite, time.Now())
|
||||
metadata := cookierefresh.MetadataWithSnapshot(currentMetadata, updated)
|
||||
return value, metadata, value != currentCookies || metadata != currentMetadata
|
||||
}
|
||||
value := MergeSetCookies(currentCookies, result.SetCookies)
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(currentMetadata)
|
||||
return value, metadata, value != currentCookies || metadata != currentMetadata
|
||||
}
|
||||
|
||||
// StepResult 是单个续期接口的执行结果,便于上层记录日志和定位失败点。
|
||||
@@ -317,8 +371,9 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
}
|
||||
}
|
||||
result := &Result{
|
||||
RenewMethod: "auto_login_plugin",
|
||||
NewCookies: newCookies,
|
||||
RenewMethod: "auto_login_plugin",
|
||||
NewCookies: newCookies,
|
||||
responseCookieURL: requestURL,
|
||||
}
|
||||
if authoritativeSnapshot {
|
||||
result.CookieSnapshot = make([]cookierefresh.BrowserCookie, len(snapshot))
|
||||
@@ -363,37 +418,77 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots
|
||||
}
|
||||
}
|
||||
call, err := s.callAutoLogin(ctx, requestCookies, mode)
|
||||
result.RequestCount = 1
|
||||
result.SetCookies = append([]string(nil), call.SetCookies...)
|
||||
result.ResponseText = string(call.Body)
|
||||
if strings.TrimSpace(call.Step.Name) != "" {
|
||||
result.StepDetails = []StepResult{call.Step}
|
||||
}
|
||||
if authoritativeSnapshot {
|
||||
updatedSnapshot := cookierefresh.ApplySetCookies(snapshot, requestURL, call.SetCookies, time.Now(), goofishTopSite)
|
||||
result.CookieSnapshot = updatedSnapshot
|
||||
result.CookieSnapshotComplete = true
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
|
||||
result.NewCookies = scoped
|
||||
populate := func(target *Result, finished callResult, callErr error, promiseTimedOut bool) (*Result, error) {
|
||||
target.RequestCount = 1
|
||||
target.SetCookies = append([]string(nil), finished.SetCookies...)
|
||||
target.ResponseText = string(finished.Body)
|
||||
if strings.TrimSpace(finished.Step.Name) != "" {
|
||||
target.StepDetails = []StepResult{finished.Step}
|
||||
}
|
||||
result.UpdatedCookieNames = cookierefresh.ChangedSnapshotLabels(snapshot, updatedSnapshot)
|
||||
} else {
|
||||
result.NewCookies = MergeSetCookies(cookiesStr, call.SetCookies)
|
||||
result.UpdatedCookieNames = ChangedCookieNames(cookiesStr, result.NewCookies)
|
||||
if authoritativeSnapshot {
|
||||
updatedSnapshot := cookierefresh.ApplySetCookies(snapshot, requestURL, finished.SetCookies, time.Now(), goofishTopSite)
|
||||
target.CookieSnapshot = updatedSnapshot
|
||||
target.CookieSnapshotComplete = true
|
||||
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
|
||||
target.NewCookies = scoped
|
||||
}
|
||||
target.UpdatedCookieNames = cookierefresh.ChangedSnapshotLabels(snapshot, updatedSnapshot)
|
||||
} else {
|
||||
target.NewCookies = MergeSetCookies(cookiesStr, finished.SetCookies)
|
||||
target.UpdatedCookieNames = ChangedCookieNames(cookiesStr, target.NewCookies)
|
||||
}
|
||||
if promiseTimedOut {
|
||||
target.Success = false
|
||||
target.NeedPasswordLogin = false
|
||||
target.Message = "官网静默续期 Promise 已超时"
|
||||
if len(finished.SetCookies) > 0 {
|
||||
target.Message += ";底层响应 Cookie 已接收"
|
||||
}
|
||||
return target, callErr
|
||||
}
|
||||
if callErr != nil {
|
||||
target.Message = callErr.Error()
|
||||
target.NeedPasswordLogin = true
|
||||
return target, callErr
|
||||
}
|
||||
message := "静默续期成功"
|
||||
if !finished.Step.BusinessOK {
|
||||
message = firstNonEmpty(finished.Step.Message, "静默续期未通过")
|
||||
}
|
||||
target.Success = finished.Step.BusinessOK
|
||||
target.Message = message
|
||||
target.NeedPasswordLogin = !finished.Step.BusinessOK
|
||||
return target, nil
|
||||
}
|
||||
if err != nil {
|
||||
result.Message = err.Error()
|
||||
result.NeedPasswordLogin = true
|
||||
return result, err
|
||||
if call.pending != nil {
|
||||
result.RequestCount = 1
|
||||
result.StepDetails = []StepResult{call.Step}
|
||||
result.Message = call.Step.Message
|
||||
result.NeedPasswordLogin = false
|
||||
pending := make(chan pendingRenewResult, 1)
|
||||
result.pending = pending
|
||||
go func() {
|
||||
outcome, ok := <-call.pending
|
||||
if !ok {
|
||||
close(pending)
|
||||
return
|
||||
}
|
||||
late := &Result{
|
||||
RenewMethod: "auto_login_plugin",
|
||||
NewCookies: newCookies,
|
||||
responseCookieURL: requestURL,
|
||||
}
|
||||
if authoritativeSnapshot {
|
||||
late.CookieSnapshot = append([]cookierefresh.BrowserCookie(nil), snapshot...)
|
||||
late.CookieSnapshotComplete = true
|
||||
}
|
||||
late, lateErr := populate(late, outcome.call, outcome.err, true)
|
||||
pending <- pendingRenewResult{result: late, err: lateErr}
|
||||
close(pending)
|
||||
}()
|
||||
return result, nil
|
||||
}
|
||||
message := "静默续期成功"
|
||||
if !call.Step.BusinessOK {
|
||||
message = firstNonEmpty(call.Step.Message, "静默续期未通过")
|
||||
}
|
||||
result.Success = call.Step.BusinessOK
|
||||
result.Message = message
|
||||
result.NeedPasswordLogin = !call.Step.BusinessOK
|
||||
return result, nil
|
||||
return populate(result, call, err, false)
|
||||
}
|
||||
|
||||
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
|
||||
@@ -467,6 +562,12 @@ type callResult struct {
|
||||
Step StepResult
|
||||
SetCookies []string
|
||||
Body []byte
|
||||
pending <-chan callOutcome
|
||||
}
|
||||
|
||||
type callOutcome struct {
|
||||
call callResult
|
||||
err error
|
||||
}
|
||||
|
||||
func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (callResult, error) {
|
||||
@@ -495,18 +596,46 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca
|
||||
}
|
||||
|
||||
func (s Service) doRenewRequest(req *http.Request, name string) (callResult, error) {
|
||||
result := callResult{Step: StepResult{Name: name}}
|
||||
hc := s.HTTPClient
|
||||
if hc == nil {
|
||||
hc = &http.Client{Timeout: backgroundFetchTimeout}
|
||||
}
|
||||
// 官网 2 秒超时只 reject 外层 Promise,不会 AbortController 取消 fetch。
|
||||
// 这里继续等待底层响应以吸收可能迟到的 Set-Cookie,但超过 2 秒后不再把
|
||||
// 业务成功解释成 location.reload。
|
||||
requestCtx, cancel := context.WithTimeout(req.Context(), backgroundFetchTimeout)
|
||||
defer cancel()
|
||||
req = req.Clone(requestCtx)
|
||||
startedAt := time.Now()
|
||||
// Promise.race 的计时器不能取消底层 fetch。使用 WithoutCancel 让 2 秒
|
||||
// 窗口结束后请求继续,但仍以 30 秒硬上限防止后台泄漏。
|
||||
requestCtx, cancel := context.WithTimeout(context.WithoutCancel(req.Context()), backgroundFetchTimeout)
|
||||
backgroundReq := req.Clone(requestCtx)
|
||||
done := make(chan callOutcome, 1)
|
||||
go func() {
|
||||
defer cancel()
|
||||
call, err := executeRenewRequest(hc, backgroundReq, name)
|
||||
done <- callOutcome{call: call, err: err}
|
||||
}()
|
||||
timer := time.NewTimer(s.promiseTimeout())
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-req.Context().Done():
|
||||
cancel()
|
||||
result := callResult{Step: StepResult{Name: name, Message: req.Context().Err().Error()}}
|
||||
return result, req.Context().Err()
|
||||
case outcome := <-done:
|
||||
return outcome.call, outcome.err
|
||||
case <-timer.C:
|
||||
return callResult{
|
||||
Step: StepResult{Name: name, Message: "官网静默续期 Promise 已超时;底层 fetch 继续接收 Cookie"},
|
||||
pending: done,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) promiseTimeout() time.Duration {
|
||||
if s.PromiseTimeout > 0 {
|
||||
return s.PromiseTimeout
|
||||
}
|
||||
return defaultRequestTimout
|
||||
}
|
||||
|
||||
func executeRenewRequest(hc *http.Client, req *http.Request, name string) (callResult, error) {
|
||||
result := callResult{Step: StepResult{Name: name}}
|
||||
resp, err := hc.Do(req)
|
||||
if err != nil {
|
||||
result.Step.Message = fmt.Sprintf("请求失败: %v", err)
|
||||
@@ -528,11 +657,9 @@ func (s Service) doRenewRequest(req *http.Request, name string) (callResult, err
|
||||
result.Step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
|
||||
return result, nil
|
||||
}
|
||||
result.Step.BusinessOK = time.Since(startedAt) <= defaultRequestTimout && renewBusinessOK(body)
|
||||
result.Step.BusinessOK = renewBusinessOK(body)
|
||||
if result.Step.BusinessOK {
|
||||
result.Step.Message = "业务成功"
|
||||
} else if time.Since(startedAt) > defaultRequestTimout {
|
||||
result.Step.Message = "官网静默续期 Promise 已超时;已保留底层响应 Cookie"
|
||||
} else {
|
||||
result.Step.Message = "业务结果未确认成功"
|
||||
}
|
||||
|
||||
@@ -490,6 +490,71 @@ func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewAPIFirstReturnsAtPromiseTimeoutAndKeepsLateCookies(t *testing.T) {
|
||||
useTestDesktopFingerprint(t)
|
||||
var completed atomic.Bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(80 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: futureMillis(time.Hour), Path: "/"})
|
||||
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
|
||||
completed.Store(true)
|
||||
}))
|
||||
defer srv.Close()
|
||||
svc := Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1,
|
||||
PromiseTimeout: 20 * time.Millisecond,
|
||||
}
|
||||
started := time.Now()
|
||||
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour))
|
||||
if err != nil || res == nil || !res.HasPending() {
|
||||
t.Fatalf("result=%+v err=%v", res, err)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed >= 70*time.Millisecond {
|
||||
t.Fatalf("外层 Promise 没有按时返回: %s", elapsed)
|
||||
}
|
||||
if completed.Load() || len(res.SetCookies) != 0 || res.Success || res.NeedPasswordLogin {
|
||||
t.Fatalf("超时瞬间不应伪造底层结果或要求重新登录: %+v completed=%v", res, completed.Load())
|
||||
}
|
||||
waitCtx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
late, lateErr := res.AwaitPending(waitCtx)
|
||||
if lateErr != nil || late == nil || len(late.SetCookies) != 1 || !strings.Contains(late.NewCookies, "sdkSilent=") {
|
||||
t.Fatalf("迟到响应 Cookie 丢失: result=%+v err=%v", late, lateErr)
|
||||
}
|
||||
if !completed.Load() || late.Success || late.NeedPasswordLogin {
|
||||
t.Fatalf("底层请求应完成,但不得在 Promise 超时后触发成功 reload/重新登录: %+v completed=%v", late, completed.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRebaseResponseCookiesUsesLatestAuthoritativeJar(t *testing.T) {
|
||||
current := []cookierefresh.BrowserCookie{
|
||||
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
{Name: "concurrent", Value: "kept", Domain: ".goofish.com", Path: "/", Secure: true},
|
||||
}
|
||||
metadata := cookierefresh.MetadataWithSnapshot(`{"note":"keep"}`, current)
|
||||
late := &Result{
|
||||
SetCookies: []string{"sdkSilent=9999999999999; Domain=goofish.com; Path=/; Secure; HttpOnly"},
|
||||
responseCookieURL: SilentHasLoginURL,
|
||||
}
|
||||
value, updatedMetadata, changed := RebaseResponseCookies("unb=1; concurrent=kept", metadata, late)
|
||||
if !changed || !strings.Contains(value, "concurrent=kept") || !strings.Contains(value, "sdkSilent=9999999999999") {
|
||||
t.Fatalf("迟到响应覆盖了并发 Cookie: value=%q changed=%v", value, changed)
|
||||
}
|
||||
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(updatedMetadata)
|
||||
if !complete {
|
||||
t.Fatalf("权威快照被降级: %s", updatedMetadata)
|
||||
}
|
||||
var found bool
|
||||
for _, cookie := range snapshot {
|
||||
if cookie.Name == "sdkSilent" && cookie.HTTPOnly && cookie.Domain == ".goofish.com" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found || !strings.Contains(updatedMetadata, `"note":"keep"`) {
|
||||
t.Fatalf("迟到 Cookie 属性或其他 metadata 丢失: %+v metadata=%s", snapshot, updatedMetadata)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenewBodyLimit(t *testing.T) {
|
||||
_, err := readRenewBody(strings.NewReader(strings.Repeat("x", maxRenewBodyBytes+1)))
|
||||
if err == nil || !strings.Contains(err.Error(), fmt.Sprint(maxRenewBodyBytes>>20)) {
|
||||
|
||||
Reference in new issue
Block a user