阶段十:完成 Go Adapter 注释基线清零
This commit is contained in:
1 parent
73a63eecce
commit
85369484d6
6 files changed
+357
-2463
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -633,3 +633,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-15 | 完成阶段 10 第七个 PR 切片“Go internal/engine 注释基线按领域清零” | 为账号运行时、连接循环、凭证作用域、消息分发、回复策略、AI、令牌缓存和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/engine` 注释基线清零;Engine 定向测试、`go test -race ./internal/engine`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/automation、internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
||||
| 2026-08-15 | 完成阶段 10 第八个 PR 切片“Go internal/automation 注释基线按领域清零” | 为自动化中心、账号任务、动作执行器、事件流水线、运行协调器、调度器、通知器及其测试补齐函数、变量、字段和常量中文注释;`internal/automation` 注释基线清零;Automation 定向测试、`go test -race ./internal/automation`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/account、internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
||||
| 2026-08-15 | 完成阶段 10 第九个 PR 切片“Go internal/account 注释基线按领域清零” | 为账号管理器、凭证作用域、运行时启动/停止和生命周期测试补齐函数、变量、字段及常量中文注释;`internal/account` 注释基线清零;Account 定向测试、`go test -race ./internal/account`、全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/adapter、internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
||||
| 2026-08-15 | 完成阶段 10 第十个 PR 切片“Go internal/adapter 注释基线按领域清零” | 为 adapter 装配、平台运行视图、远端 Token CAPTCHA 流程及其测试补齐函数、变量、字段和常量中文注释;`internal/adapter` 注释基线清零;Adapter 定向测试和全量 Go/React 门禁通过,合并为一个可回滚提交 | 阶段 10:继续清理 Go internal/renewal、internal/notify、internal/chat 等领域注释基线 |
|
||||
+113
-21
@@ -27,26 +27,32 @@ import (
|
||||
|
||||
// browserManager 只暴露风控验证能力。普通 Token、Cookie 续期、订单和
|
||||
// WebSocket 流程不得通过 Chromium 实现。
|
||||
// browserManager 保存浏览器Manager,供当前处理流程使用
|
||||
type browserManager interface {
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
// browserTokenCaptchaRecoverer 保存浏览器令牌CaptchaRecoverer,供当前处理流程使用
|
||||
type browserTokenCaptchaRecoverer interface {
|
||||
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
|
||||
}
|
||||
|
||||
// browserTokenCaptchaEngineRecoverer 保存浏览器令牌CaptchaEngineRecoverer,供当前处理流程使用
|
||||
type browserTokenCaptchaEngineRecoverer interface {
|
||||
TokenCaptchaRecoverWithEngine(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (cookies, engine string, err error)
|
||||
}
|
||||
|
||||
// browserTokenCaptchaSnapshotReader 保存浏览器令牌CaptchaSnapshotReader,供当前处理流程使用
|
||||
type browserTokenCaptchaSnapshotReader interface {
|
||||
TokenCaptchaCookieSnapshot(ctx context.Context, cookieID string, headless bool) (cookies string, snapshot []cookierefresh.BrowserCookie, err error)
|
||||
}
|
||||
|
||||
// tokenCaptchaRequester 保存令牌CaptchaRequester,供当前处理流程使用
|
||||
type tokenCaptchaRequester interface {
|
||||
RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error)
|
||||
}
|
||||
|
||||
// orderDetailClient 保存订单DetailClient,供当前处理流程使用
|
||||
type orderDetailClient interface {
|
||||
FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*mtop.OrderDetailResult, error)
|
||||
}
|
||||
@@ -56,6 +62,7 @@ type orderDetailClient interface {
|
||||
//
|
||||
// 自动发货只走 automation.Center;用户聊天消息由 Account 内部 ReplyService 处理,
|
||||
// 故 HandleChatMessage 为空实现。
|
||||
// Adapter 保存Adapter,供当前处理流程使用
|
||||
type Adapter struct {
|
||||
store *db.Store
|
||||
browser browserManager
|
||||
@@ -77,16 +84,19 @@ type Adapter struct {
|
||||
|
||||
// notifyNotifier 是 *notify.Notifier 的最小接口,避免 adapter 直接依赖 notify 包
|
||||
// (notify 包未来若反向引用 adapter 也不会形成循环)。
|
||||
// notifyNotifier 保存notifyNotifier,供当前处理流程使用
|
||||
type notifyNotifier interface {
|
||||
NotifyAccountAlert(cookieID, level, title, body string)
|
||||
}
|
||||
|
||||
// notifyEventNotifier 保存notifyEventNotifier,供当前处理流程使用
|
||||
type notifyEventNotifier interface {
|
||||
NotifyAccountEvent(cookieID, eventType, level, title, body string)
|
||||
}
|
||||
|
||||
// New 构造 Adapter。automation 与 notifier 通过 Set* 后期注入(因创建顺序存在循环:
|
||||
// mgr 依赖 adapter,automation 依赖 mgr,adapter 又依赖 automation)。
|
||||
// New 负责New相关处理。
|
||||
func New(store *db.Store, bm *browser.Manager, logger *slog.Logger) *Adapter {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
@@ -130,6 +140,7 @@ func (a *Adapter) SetOrderDetailClient(c orderDetailClient) { a.orderMTop = c }
|
||||
|
||||
// SetChatService installs the user-facing chat side channel. It persists and
|
||||
// broadcasts messages without changing the automatic reply path.
|
||||
// SetChatService 设置聊天Service。
|
||||
func (a *Adapter) SetChatService(service *chat.Service) { a.chat = service }
|
||||
|
||||
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
|
||||
@@ -143,6 +154,7 @@ func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMess
|
||||
if strings.TrimSuffix(message.SenderUserID, "@goofish") == strings.TrimSuffix(message.AccountID, "@goofish") {
|
||||
return nil
|
||||
}
|
||||
// err 保存err,供当前处理流程使用
|
||||
_, _, err := a.chat.RecordIncoming(ctx, chat.Incoming{
|
||||
AccountID: message.AccountID, ChatID: message.ChatID, BuyerID: message.SenderUserID,
|
||||
BuyerName: message.SenderName, Text: message.Text, ItemID: message.ItemID, Raw: message.Raw,
|
||||
@@ -152,10 +164,12 @@ func (a *Adapter) HandleChatMessage(ctx context.Context, message engine.ChatMess
|
||||
|
||||
// HandleOutgoingChatMessage records successful manual/automatic text sends as
|
||||
// a side channel; it never participates in platform delivery.
|
||||
// HandleOutgoingChatMessage 处理Outgoing聊天消息。
|
||||
func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.OutgoingChatMessage) error {
|
||||
if a.chat == nil {
|
||||
return nil
|
||||
}
|
||||
// err 保存err,供当前处理流程使用
|
||||
_, err := a.chat.RecordOutgoingSent(ctx, db.ChatSession{CookieID: message.AccountID, ChatID: message.ChatID,
|
||||
BuyerID: message.BuyerID}, message.MessageKey, message.Text)
|
||||
return err
|
||||
@@ -163,6 +177,7 @@ func (a *Adapter) HandleOutgoingChatMessage(ctx context.Context, message engine.
|
||||
|
||||
// OnAccountAlert 把账号告警(token 失效/自动恢复失败/风控验证等)转发给通知器,
|
||||
// 推送到该账号已绑定的通知渠道。
|
||||
// OnAccountAlert 负责On账号Alert相关处理。
|
||||
func (a *Adapter) OnAccountAlert(ctx context.Context, cookieID, level, title, body string) {
|
||||
a.OnAccountEvent(ctx, cookieID, classifyAccountAlertEvent(title, body), level, title, body)
|
||||
}
|
||||
@@ -173,14 +188,17 @@ func (a *Adapter) OnAccountEvent(_ context.Context, cookieID, eventType, level,
|
||||
a.logger.Warn("账号事件通知未发送:通知器未注入", "account", cookieID, "event_type", eventType, "level", level, "title", title)
|
||||
return
|
||||
}
|
||||
if n, ok := a.notifier.(notifyEventNotifier); ok {
|
||||
if // n、ok 保存n、ok,供当前处理流程使用
|
||||
n, ok := a.notifier.(notifyEventNotifier); ok {
|
||||
n.NotifyAccountEvent(cookieID, eventType, level, title, body)
|
||||
return
|
||||
}
|
||||
a.notifier.NotifyAccountAlert(cookieID, level, title, body)
|
||||
}
|
||||
|
||||
// classifyAccountAlertEvent 负责classify账号AlertEvent相关处理。
|
||||
func classifyAccountAlertEvent(title, body string) string {
|
||||
// msg 保存msg,供当前处理流程使用
|
||||
msg := strings.ToLower(title + " " + body)
|
||||
switch {
|
||||
case strings.Contains(msg, "风控"), strings.Contains(msg, "验证"),
|
||||
@@ -202,10 +220,13 @@ func classifyAccountAlertEvent(title, body string) string {
|
||||
|
||||
// OnTokenCaptchaVerification 处理 token 刷新触发的闲鱼滑块风控。
|
||||
func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cookieStr, verificationURL, deviceID string) (*mtop.RefreshResult, bool) {
|
||||
// start 保存开始,供当前处理流程使用
|
||||
start := time.Now()
|
||||
// logID 保存logID,供当前处理流程使用
|
||||
var logID int64
|
||||
if a.store != nil && a.store.RiskLogs != nil {
|
||||
if id, err := a.store.RiskLogs.Add(ctx, db.RiskControlLog{
|
||||
if // id、err 保存id、err,供当前处理流程使用
|
||||
id, err := a.store.RiskLogs.Add(ctx, db.RiskControlLog{
|
||||
CookieID: cookieID,
|
||||
EventType: "slider_captcha",
|
||||
EventDescription: "触发场景: Token刷新, URL: " + verificationURL,
|
||||
@@ -217,7 +238,9 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
}
|
||||
|
||||
// showBrowser 保存show浏览器,供当前处理流程使用
|
||||
showBrowser := false
|
||||
// metadataJSON 保存metadataJSON,供当前处理流程使用
|
||||
metadataJSON := ""
|
||||
if a.store == nil || a.store.Cookies == nil {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
@@ -225,15 +248,18 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if d, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID); err == nil {
|
||||
if // d、err 保存d、err,供当前处理流程使用
|
||||
d, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID); err == nil {
|
||||
showBrowser = d.ShowBrowser
|
||||
metadataJSON = d.MetadataJSON
|
||||
}
|
||||
|
||||
// provider 保存provider,供当前处理流程使用
|
||||
provider := func(runCtx context.Context, currentCookies string) (string, bool, string, error) {
|
||||
if a.captchaReq == nil {
|
||||
return "", false, "", nil
|
||||
}
|
||||
// res、err 保存res、err,供当前处理流程使用
|
||||
res, err := a.captchaReq.RequestFreshCaptchaURLContext(runCtx, currentCookies, deviceID)
|
||||
if err != nil || res == nil {
|
||||
return "", false, "", err
|
||||
@@ -241,12 +267,18 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
return res.VerificationURL, res.TokenOK, res.UpdatedCookies, nil
|
||||
}
|
||||
|
||||
// newCookies 保存newCookies,供当前处理流程使用
|
||||
newCookies := ""
|
||||
// captchaEngine 保存captchaEngine,供当前处理流程使用
|
||||
captchaEngine := "playwright"
|
||||
// remoteHandled 保存remoteHandled,供当前处理流程使用
|
||||
remoteHandled := false
|
||||
// captchaHeadless 保存captchaHeadless,供当前处理流程使用
|
||||
captchaHeadless := browser.ResolveHeadless(showBrowser)
|
||||
// err 保存err,供当前处理流程使用
|
||||
var err error
|
||||
if remoteConfig := a.loadRemoteCaptchaConfig(ctx); remoteConfig != nil {
|
||||
if // remoteConfig 保存remote配置,供当前处理流程使用
|
||||
remoteConfig := a.loadRemoteCaptchaConfig(ctx); remoteConfig != nil {
|
||||
newCookies, remoteHandled, err = solveRemoteCaptcha(
|
||||
ctx, newRemoteCaptchaHTTPClient(), *remoteConfig,
|
||||
cookieID, verificationURL, cookieStr, deviceID, provider,
|
||||
@@ -259,13 +291,15 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
}
|
||||
if !remoteHandled {
|
||||
// br、ok 保存br、ok,供当前处理流程使用
|
||||
br, ok := a.browser.(browserTokenCaptchaRecoverer)
|
||||
if a.browser == nil || !ok {
|
||||
a.OnAccountEvent(ctx, cookieID, engine.EventSecurityVerification, engine.AlertLevelWarn,
|
||||
"token 风控验证无法自动处理", "远程服务不可用且浏览器自动化未启用,无法自动完成 token 滑块验证。")
|
||||
return nil, false
|
||||
}
|
||||
if withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
if // withEngine、ok 保存withEngine、ok,供当前处理流程使用
|
||||
withEngine, ok := a.browser.(browserTokenCaptchaEngineRecoverer); ok {
|
||||
newCookies, captchaEngine, err = withEngine.TokenCaptchaRecoverWithEngine(
|
||||
ctx, cookieID, cookieStr, verificationURL, captchaHeadless, provider,
|
||||
)
|
||||
@@ -276,6 +310,7 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
// manualURL 保存manualURL,供当前处理流程使用
|
||||
manualURL := browser.TokenCaptchaManualVerificationURL(err)
|
||||
if strings.TrimSpace(manualURL) == "" {
|
||||
manualURL = verificationURL
|
||||
@@ -297,10 +332,14 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
if strings.TrimSpace(newCookies) == "" {
|
||||
return nil, false
|
||||
}
|
||||
// cookieSnapshot 保存登录凭证Snapshot,供当前处理流程使用
|
||||
var cookieSnapshot []cookierefresh.BrowserCookie
|
||||
// snapshotComplete 保存snapshotComplete,供当前处理流程使用
|
||||
snapshotComplete := false
|
||||
if !remoteHandled {
|
||||
if reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
if // reader、ok 保存reader、ok,供当前处理流程使用
|
||||
reader, ok := a.browser.(browserTokenCaptchaSnapshotReader); ok {
|
||||
// profileCookies、profileSnapshot、readErr 保存profileCookies、profileSnapshot、readErr,供当前处理流程使用
|
||||
profileCookies, profileSnapshot, readErr := reader.TokenCaptchaCookieSnapshot(ctx, cookieID, captchaHeadless)
|
||||
if readErr != nil {
|
||||
a.logger.Warn("读取滑块验证后完整 Cookie Jar 失败,回退 Go 快照合并", "account", cookieID, "err", readErr)
|
||||
@@ -315,16 +354,19 @@ func (a *Adapter) OnTokenCaptchaVerification(ctx context.Context, cookieID, cook
|
||||
}
|
||||
}
|
||||
if !snapshotComplete {
|
||||
if existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
if // existing、complete 保存existing、complete,供当前处理流程使用
|
||||
existing, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
|
||||
cookieSnapshot = cookierefresh.ReconcileSnapshotWithCookieString(existing, newCookies)
|
||||
snapshotComplete = true
|
||||
}
|
||||
}
|
||||
// updatedMetadata 保存updatedMetadata,供当前处理流程使用
|
||||
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 {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
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{
|
||||
@@ -369,13 +411,16 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
|
||||
|
||||
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时
|
||||
// 调用纯 Go MTOP 客户端,并将详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
|
||||
// FetchOrderDetail 负责Fetch订单Detail相关处理。
|
||||
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
if // detail、ok 保存detail、ok,供当前处理流程使用
|
||||
detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if a.orderMTop == nil {
|
||||
return nil, fmt.Errorf("订单详情 MTOP 客户端未配置")
|
||||
}
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
if err == nil || !mtop.IsSessionExpiredErr(err) {
|
||||
return detail, err
|
||||
@@ -388,6 +433,7 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
|
||||
return a.fetchOrderDetailAttempt(ctx, cookieID, orderID)
|
||||
}
|
||||
|
||||
// fetchOrderDetailAttempt 负责fetch订单Detail尝试次数相关处理。
|
||||
func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID string) (*automation.OrderDetail, error) {
|
||||
|
||||
a.orderFetchMu.Lock()
|
||||
@@ -396,7 +442,9 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
|
||||
return detail, nil
|
||||
}
|
||||
if remain := 3*time.Second - time.Since(a.lastOrderFetch); !a.lastOrderFetch.IsZero() && remain > 0 {
|
||||
if // remain 保存remain,供当前处理流程使用
|
||||
remain := 3*time.Second - time.Since(a.lastOrderFetch); !a.lastOrderFetch.IsZero() && remain > 0 {
|
||||
// timer 保存定时器,供当前处理流程使用
|
||||
timer := time.NewTimer(remain)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
@@ -406,6 +454,7 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
}
|
||||
}
|
||||
a.lastOrderFetch = time.Now()
|
||||
// credentialUnlock 保存credentialUnlock,供当前处理流程使用
|
||||
credentialUnlock := a.store.LockAccountCredentials(cookieID)
|
||||
defer credentialUnlock()
|
||||
platformData, err := a.store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) // platformData 只包含订单 MTOP 请求所需的 Cookie 与 metadata。
|
||||
@@ -415,22 +464,30 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
if strings.TrimSpace(platformData.Value) == "" && !hasCompleteCookieSnapshot(platformData.MetadataJSON) {
|
||||
return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
|
||||
}
|
||||
// cookieStr 保存登录凭证Str,供当前处理流程使用
|
||||
cookieStr := platformData.Value
|
||||
// requestCtx 保存请求Ctx,供当前处理流程使用
|
||||
var requestCtx context.Context
|
||||
// cookieSession 保存登录凭证会话,供当前处理流程使用
|
||||
var cookieSession *mtop.CookieSession
|
||||
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(platformData.MetadataJSON); complete {
|
||||
if // snapshot、complete 保存snapshot、complete,供当前处理流程使用
|
||||
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(platformData.MetadataJSON); complete {
|
||||
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
// detail、fetchErr 保存detail、fetchErr,供当前处理流程使用
|
||||
detail, fetchErr := a.orderMTop.FetchOrderDetail(requestCtx, cookieStr, orderID)
|
||||
// authoritativeCookies、authoritativeSnapshot、sessionChanged 保存authoritativeCookies、authoritativeSnapshot、sessionChanged,供当前处理流程使用
|
||||
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
|
||||
if sessionChanged {
|
||||
// metadata 保存metadata,供当前处理流程使用
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(platformData.MetadataJSON)
|
||||
if authoritativeSnapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(platformData.MetadataJSON, authoritativeSnapshot)
|
||||
}
|
||||
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
if // persistErr 保存persistErr,供当前处理流程使用
|
||||
persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
|
||||
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
|
||||
} else {
|
||||
cookieStr = authoritativeCookies
|
||||
@@ -444,8 +501,10 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
return nil, errors.New("订单详情 MTOP 接口返回空结果")
|
||||
}
|
||||
if !sessionChanged && authoritativeSnapshot == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
|
||||
// metadata 保存metadata,供当前处理流程使用
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(platformData.MetadataJSON)
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
|
||||
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
|
||||
}
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
@@ -456,22 +515,27 @@ func (a *Adapter) fetchOrderDetailAttempt(ctx context.Context, cookieID, orderID
|
||||
}, nil
|
||||
}
|
||||
|
||||
// wakeCredentialBlockedAutomation 负责wakeCredentialBlocked自动化相关处理。
|
||||
func (a *Adapter) wakeCredentialBlockedAutomation(ctx context.Context, cookieID string) {
|
||||
if a.store == nil || a.store.Automation == nil {
|
||||
return
|
||||
}
|
||||
if err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Automation.WakeCredentialBlocked(ctx, cookieID); err != nil {
|
||||
a.logger.Warn("Cookie 更新后唤醒自动化任务失败", "account", cookieID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// hasCompleteCookieSnapshot 负责hasComplete登录凭证Snapshot相关处理。
|
||||
func hasCompleteCookieSnapshot(metadata string) bool {
|
||||
// ok 保存ok,供当前处理流程使用
|
||||
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
|
||||
return ok
|
||||
}
|
||||
|
||||
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的 MTOP 请求。
|
||||
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
|
||||
// order、err 保存order、err,供当前处理流程使用
|
||||
order, err := a.store.Orders.Get(ctx, orderID)
|
||||
if err != nil || order == nil {
|
||||
return nil, false
|
||||
@@ -487,12 +551,15 @@ func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automa
|
||||
|
||||
// OnPasswordLoginRefresh 是 engine 的历史回调名。Go 客户端只执行协议级
|
||||
// auto-login 续期;失败后要求重新扫码,不得启动 Chromium 密码登录或页面校验。
|
||||
// OnPasswordLoginRefresh 负责On密码登录Refresh相关处理。
|
||||
func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) bool {
|
||||
// cooldown 保存cooldown,供当前处理流程使用
|
||||
cooldown := a.cooldown
|
||||
if cooldown == nil {
|
||||
cooldown = renewal.GlobalCooldown
|
||||
}
|
||||
if ok, remain, reason := cooldown.PasswordLoginAllowed(cookieID, engine.PasswordLoginMinGap); !ok {
|
||||
if // ok、remain、reason 保存ok、remain、reason,供当前处理流程使用
|
||||
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)))
|
||||
return false
|
||||
@@ -510,12 +577,14 @@ func (a *Adapter) OnPasswordLoginRefresh(ctx context.Context, cookieID string) b
|
||||
return false
|
||||
}
|
||||
|
||||
// renewed、renewErr 保存renewed、renewErr,供当前处理流程使用
|
||||
renewed, renewErr := a.tryProtocolCredentialRenew(ctx, &platformData)
|
||||
if renewed {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
a.recordPasswordLogin(ctx, cookieID, platformData.UserID, "success", "", "Go 协议续期成功")
|
||||
return true
|
||||
}
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := "Go 协议续期未恢复登录凭证,请重新扫码登录"
|
||||
if renewErr != nil {
|
||||
message += ":" + renewErr.Error()
|
||||
@@ -541,30 +610,35 @@ func (a *Adapter) OnTransportReady(ctx context.Context, cookieID string) {
|
||||
a.wakeCredentialBlockedAutomation(ctx, cookieID)
|
||||
}
|
||||
|
||||
// beginPasswordLogin 负责begin密码登录相关处理。
|
||||
func (a *Adapter) beginPasswordLogin(cookieID string) bool {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
if a.passwordProcessing == nil {
|
||||
a.passwordProcessing = make(map[string]struct{})
|
||||
}
|
||||
if _, ok := a.passwordProcessing[cookieID]; ok {
|
||||
if // ok 保存ok,供当前处理流程使用
|
||||
_, ok := a.passwordProcessing[cookieID]; ok {
|
||||
return false
|
||||
}
|
||||
a.passwordProcessing[cookieID] = struct{}{}
|
||||
return true
|
||||
}
|
||||
|
||||
// finishPasswordLogin 负责finish密码登录相关处理。
|
||||
func (a *Adapter) finishPasswordLogin(cookieID string) {
|
||||
a.passwordMu.Lock()
|
||||
defer a.passwordMu.Unlock()
|
||||
delete(a.passwordProcessing, cookieID)
|
||||
}
|
||||
|
||||
// recordPasswordLogin 负责record密码登录相关处理。
|
||||
func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, userID int64, status, failureReason, message string) {
|
||||
if a.store == nil || a.store.LoginLogs == nil {
|
||||
return
|
||||
}
|
||||
if err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.LoginLogs.Add(ctx, db.AccountLoginLog{
|
||||
CookieID: cookieID,
|
||||
UserID: userID,
|
||||
Method: "protocol",
|
||||
@@ -581,6 +655,7 @@ func (a *Adapter) recordPasswordLogin(ctx context.Context, cookieID string, user
|
||||
}
|
||||
}
|
||||
|
||||
// truncateMessage 负责truncate消息相关处理。
|
||||
func truncateMessage(s string, n int) string {
|
||||
if n <= 0 || len(s) <= n {
|
||||
return s
|
||||
@@ -588,32 +663,40 @@ func truncateMessage(s string, n int) string {
|
||||
return s[:n]
|
||||
}
|
||||
|
||||
// tryProtocolCredentialRenew 负责tryProtocolCredentialRenew相关处理。
|
||||
func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePlatformRuntimeData) (bool, error) {
|
||||
if d == nil {
|
||||
return false, nil
|
||||
}
|
||||
// current 保存current,供当前处理流程使用
|
||||
current := d.Value
|
||||
// api 保存api,供当前处理流程使用
|
||||
api := a.renewSvc
|
||||
// save 保存save,供当前处理流程使用
|
||||
save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
|
||||
if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
|
||||
return nil
|
||||
}
|
||||
// metadata 保存metadata,供当前处理流程使用
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
|
||||
if completeSnapshot != nil {
|
||||
// API 在完整 Jar 基础上得到的快照是权威结果,包含
|
||||
// 服务端删除和新的 Domain/Path/expiry 属性。
|
||||
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
|
||||
}
|
||||
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
|
||||
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
|
||||
return err
|
||||
}
|
||||
// valueChanged 保存值Changed,供当前处理流程使用
|
||||
valueChanged := cookieStr != current
|
||||
current = cookieStr
|
||||
d.Value = cookieStr
|
||||
d.MetadataJSON = metadata
|
||||
if valueChanged && a.store.Tokens != nil {
|
||||
if err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
|
||||
// Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
|
||||
// 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
|
||||
a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
|
||||
@@ -623,10 +706,13 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
}
|
||||
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
|
||||
// 决定是否调用 silentHasLogin。Go 客户端复刻该 HTTP 协议,不加载页面。
|
||||
// runCtx、cancel 保存运行Ctx、cancel,供当前处理流程使用
|
||||
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
|
||||
defer cancel()
|
||||
// res、err 保存res、err,供当前处理流程使用
|
||||
res, err := api.RenewAfterSessionExpired(runCtx, current, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
|
||||
if res != nil {
|
||||
// completeSnapshot 保存completeSnapshot,供当前处理流程使用
|
||||
var completeSnapshot []cookierefresh.BrowserCookie
|
||||
if res.CookieSnapshotComplete {
|
||||
completeSnapshot = res.CookieSnapshot
|
||||
@@ -634,14 +720,17 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
completeSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
if // saveErr 保存saveErr,供当前处理流程使用
|
||||
saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if res.HasPending() {
|
||||
// 恢复路径不能把“底层请求仍在进行”提前记为成功,否则上层会
|
||||
// 重置失败计数并继续使用未确认的旧凭证。这里等待最终响应;定时
|
||||
// 调度仍使用异步 watcher,不阻塞健康账号。
|
||||
// waitCtx、waitCancel 保存waitCtx、wait取消,供当前处理流程使用
|
||||
waitCtx, waitCancel := context.WithTimeout(ctx, 35*time.Second)
|
||||
// late、waitErr 保存late、waitErr,供当前处理流程使用
|
||||
late, waitErr := res.AwaitPending(waitCtx)
|
||||
waitCancel()
|
||||
if late == nil {
|
||||
@@ -650,6 +739,7 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
}
|
||||
return false, errors.New("协议续期底层响应未返回结果")
|
||||
}
|
||||
// lateSnapshot 保存lateSnapshot,供当前处理流程使用
|
||||
var lateSnapshot []cookierefresh.BrowserCookie
|
||||
if late.CookieSnapshotComplete {
|
||||
lateSnapshot = late.CookieSnapshot
|
||||
@@ -657,7 +747,8 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
lateSnapshot = []cookierefresh.BrowserCookie{}
|
||||
}
|
||||
}
|
||||
if saveErr := save(late.NewCookies, late.SetCookies, lateSnapshot); saveErr != nil {
|
||||
if // saveErr 保存saveErr,供当前处理流程使用
|
||||
saveErr := save(late.NewCookies, late.SetCookies, lateSnapshot); saveErr != nil {
|
||||
return false, saveErr
|
||||
}
|
||||
if waitErr != nil {
|
||||
@@ -667,6 +758,7 @@ func (a *Adapter) tryProtocolCredentialRenew(ctx context.Context, d *db.CookiePl
|
||||
a.logger.Info("Go 协议续期迟到响应成功", "account", d.ID)
|
||||
return true, nil
|
||||
}
|
||||
// message 保存消息,供当前处理流程使用
|
||||
message := strings.TrimSpace(late.Message)
|
||||
if message == "" {
|
||||
message = "协议续期未通过"
|
||||
|
||||
@@ -28,10 +28,12 @@ type fakeNotifier struct {
|
||||
events []struct{ cookieID, eventType, level, title, body string }
|
||||
}
|
||||
|
||||
// NotifyAccountAlert 负责Notify账号Alert相关处理。
|
||||
func (f *fakeNotifier) NotifyAccountAlert(cookieID, level, title, body string) {
|
||||
f.alerts = append(f.alerts, struct{ cookieID, level, title, body string }{cookieID, level, title, body})
|
||||
}
|
||||
|
||||
// NotifyAccountEvent 负责Notify账号Event相关处理。
|
||||
func (f *fakeNotifier) NotifyAccountEvent(cookieID, eventType, level, title, body string) {
|
||||
f.events = append(f.events, struct{ cookieID, eventType, level, title, body string }{cookieID, eventType, level, title, body})
|
||||
}
|
||||
@@ -57,6 +59,7 @@ type fakeBrowser struct {
|
||||
providerUpdated string
|
||||
}
|
||||
|
||||
// fakeSnapshotBrowser 保存fakeSnapshot浏览器,供当前处理流程使用
|
||||
type fakeSnapshotBrowser struct {
|
||||
fakeBrowser
|
||||
snapshotCookies string
|
||||
@@ -65,22 +68,30 @@ type fakeSnapshotBrowser struct {
|
||||
snapshotCalls int
|
||||
}
|
||||
|
||||
// TokenCaptchaCookieSnapshot 负责令牌Captcha登录凭证Snapshot相关处理。
|
||||
func (f *fakeSnapshotBrowser) TokenCaptchaCookieSnapshot(context.Context, string, bool) (string, []cookierefresh.BrowserCookie, error) {
|
||||
f.snapshotCalls++
|
||||
return f.snapshotCookies, f.snapshot, f.snapshotErr
|
||||
}
|
||||
|
||||
// FetchOrderDetail 负责Fetch订单Detail相关处理。
|
||||
func (f *fakeBrowser) FetchOrderDetail(_ context.Context, _, _, _ string, _ ...bool) (*browser.OrderDetail, error) {
|
||||
return f.fetchDetail, f.fetchErr
|
||||
}
|
||||
|
||||
// CookieRenew 负责登录凭证Renew相关处理。
|
||||
func (f *fakeBrowser) CookieRenew(_ context.Context, _, _ string, _ bool) (map[string]string, error) {
|
||||
f.renewCalls++
|
||||
return f.renewCookies, f.renewErr
|
||||
}
|
||||
|
||||
// PasswordLogin 负责密码登录相关处理。
|
||||
func (f *fakeBrowser) PasswordLogin(_ context.Context, _, _, _, _ string, _ bool) (map[string]string, error) {
|
||||
f.loginCalls++
|
||||
return f.loginCookies, f.loginErr
|
||||
}
|
||||
|
||||
// TokenCaptchaRecover 负责令牌CaptchaRecover相关处理。
|
||||
func (f *fakeBrowser) TokenCaptchaRecover(ctx context.Context, _ string, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error) {
|
||||
f.tokenCaptchaCalls++
|
||||
f.tokenCaptchaURL = verificationURL
|
||||
@@ -91,6 +102,7 @@ func (f *fakeBrowser) TokenCaptchaRecover(ctx context.Context, _ string, cookieS
|
||||
return f.tokenCaptchaResult, f.tokenCaptchaErr
|
||||
}
|
||||
|
||||
// fakeCaptchaRequester 保存fakeCaptchaRequester,供当前处理流程使用
|
||||
type fakeCaptchaRequester struct {
|
||||
result *mtop.FreshCaptchaResult
|
||||
err error
|
||||
@@ -99,12 +111,14 @@ type fakeCaptchaRequester struct {
|
||||
gotDeviceID string
|
||||
}
|
||||
|
||||
// fakeOrderDetailClient 保存fake订单DetailClient,供当前处理流程使用
|
||||
type fakeOrderDetailClient struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
calls int
|
||||
}
|
||||
|
||||
// scriptedOrderDetailClient 保存scripted订单DetailClient,供当前处理流程使用
|
||||
type scriptedOrderDetailClient struct {
|
||||
mu sync.Mutex
|
||||
results []struct {
|
||||
@@ -114,23 +128,27 @@ type scriptedOrderDetailClient struct {
|
||||
}
|
||||
}
|
||||
|
||||
// FetchOrderDetail 负责Fetch订单Detail相关处理。
|
||||
func (f *scriptedOrderDetailClient) FetchOrderDetail(_ context.Context, cookies, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
if len(f.results) == 0 {
|
||||
return nil, errors.New("unexpected order detail call")
|
||||
}
|
||||
// next 保存next,供当前处理流程使用
|
||||
next := f.results[0]
|
||||
f.results = f.results[1:]
|
||||
next.cookies = cookies
|
||||
return next.detail, next.err
|
||||
}
|
||||
|
||||
// FetchOrderDetail 负责Fetch订单Detail相关处理。
|
||||
func (f *fakeOrderDetailClient) FetchOrderDetail(_ context.Context, _, _ string) (*mtop.OrderDetailResult, error) {
|
||||
f.calls++
|
||||
return f.detail, f.err
|
||||
}
|
||||
|
||||
// RequestFreshCaptchaURLContext 负责请求FreshCaptchaURL上下文相关处理。
|
||||
func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context, cookiesStr, deviceID string) (*mtop.FreshCaptchaResult, error) {
|
||||
f.calls++
|
||||
f.gotCookies = cookiesStr
|
||||
@@ -138,23 +156,30 @@ func (f *fakeCaptchaRequester) RequestFreshCaptchaURLContext(_ context.Context,
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
// newAdapterTestStore 负责newAdapterTestStore相关处理。
|
||||
func newAdapterTestStore(t *testing.T) (*db.Store, func()) {
|
||||
t.Helper()
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "adapt.db"))
|
||||
if err != nil {
|
||||
t.Fatalf("Open: %v", err)
|
||||
}
|
||||
// s 保存s,供当前处理流程使用
|
||||
s := db.NewStore(d, db.DialectSQLite)
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
s.Users.Create(ctx, "admin", "a@e.com", "pw")
|
||||
// admin 保存admin,供当前处理流程使用
|
||||
admin, _ := s.Users.GetByUsername(ctx, "admin")
|
||||
s.Cookies.Save(ctx, "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc;", admin.ID)
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
return s, func() { d.Close() }
|
||||
}
|
||||
|
||||
// verifiedRenewService 负责verifiedRenewService相关处理。
|
||||
func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
t.Helper()
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/hasLogin.do":
|
||||
@@ -178,8 +203,10 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
}, srv.Close
|
||||
}
|
||||
|
||||
// unverifiedRenewService 负责unverifiedRenewService相关处理。
|
||||
func unverifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
t.Helper()
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/hasLogin.do", "/silentHasLogin.do", "/setLoginSettings.do":
|
||||
@@ -199,13 +226,16 @@ func unverifiedRenewService(t *testing.T) (xrenew.Service, func()) {
|
||||
|
||||
// TestOnAccountAlert_ForwardedToNotifier 注入 notifier 后告警被转发;未注入时不 panic。
|
||||
func TestOnAccountAlert_ForwardedToNotifier(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
|
||||
// 未注入 notifier:不应 panic,仅记录日志。
|
||||
a.OnAccountAlert(context.Background(), "cid", "warn", "t", "b")
|
||||
|
||||
// n 保存n,供当前处理流程使用
|
||||
n := &fakeNotifier{}
|
||||
a.SetNotifier(n)
|
||||
a.OnAccountAlert(context.Background(), "cid", "warn", "token 失效", "请重新登录")
|
||||
@@ -218,25 +248,34 @@ func TestOnAccountAlert_ForwardedToNotifier(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog 负责TestOn令牌CaptchaVerificationSavesCookiesAndRiskLog相关处理。
|
||||
func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{tokenCaptchaResult: "unb=1; _m_h5_tk=fresh; x5sec=ok;"}
|
||||
// req 保存req,供当前处理流程使用
|
||||
req := &fakeCaptchaRequester{result: &mtop.FreshCaptchaResult{
|
||||
VerificationURL: "https://fresh.example/captcha",
|
||||
UpdatedCookies: "unb=1; _m_h5_tk=fresh;",
|
||||
AccessToken: "fresh-access-token",
|
||||
TokenOK: true,
|
||||
}}
|
||||
// notifier 保存notifier,供当前处理流程使用
|
||||
notifier := &fakeNotifier{}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
a.SetTokenCaptchaRequester(req)
|
||||
a.SetNotifier(notifier)
|
||||
|
||||
// deviceID 保存deviceID,供当前处理流程使用
|
||||
const deviceID = "device-for-token-and-captcha"
|
||||
// result、ok 保存result、ok,供当前处理流程使用
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; _m_h5_tk=tk;", "https://old.example/captcha", deviceID)
|
||||
if !ok {
|
||||
t.Fatal("token captcha recovery should succeed")
|
||||
@@ -256,6 +295,7 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
if req.calls != 1 || req.gotDeviceID != deviceID {
|
||||
t.Fatalf("fresh captcha requester not called correctly: calls=%d device=%q", req.calls, req.gotDeviceID)
|
||||
}
|
||||
// saved、err 保存saved、err,供当前处理流程使用
|
||||
saved, err := store.Cookies.GetValue(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetValue: %v", err)
|
||||
@@ -263,8 +303,10 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
if !strings.Contains(saved, "x5sec=ok") {
|
||||
t.Fatalf("saved cookies should contain x5sec: %q", saved)
|
||||
}
|
||||
// status、engineName 保存status、engine名称,供当前处理流程使用
|
||||
var status, engineName string
|
||||
if err := store.DB.QueryRowContext(ctx,
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.DB.QueryRowContext(ctx,
|
||||
`SELECT processing_status, captcha_engine FROM risk_control_logs WHERE cookie_id='cid' ORDER BY id DESC LIMIT 1`).
|
||||
Scan(&status, &engineName); err != nil {
|
||||
t.Fatalf("query risk log: %v", err)
|
||||
@@ -277,35 +319,46 @@ func TestOnTokenCaptchaVerification_SavesCookiesAndRiskLog(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnTokenCaptchaVerificationPersistsExactBrowserJar 负责TestOn令牌CaptchaVerificationPersistsExact浏览器Jar相关处理。
|
||||
func TestOnTokenCaptchaVerificationPersistsExactBrowserJar(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// browserSnapshot 保存浏览器Snapshot,供当前处理流程使用
|
||||
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 保存fb,供当前处理流程使用
|
||||
fb := &fakeSnapshotBrowser{
|
||||
fakeBrowser: fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=fresh"},
|
||||
snapshotCookies: "unb=1; x5sec=fresh",
|
||||
snapshot: browserSnapshot,
|
||||
}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
a.SetTokenCaptchaRequester(&fakeCaptchaRequester{})
|
||||
// result、ok 保存result、ok,供当前处理流程使用
|
||||
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 保存detail、err,供当前处理流程使用
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// saved、complete 保存saved、complete,供当前处理流程使用
|
||||
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)
|
||||
}
|
||||
// exactX5 保存exactX5,供当前处理流程使用
|
||||
var exactX5 bool
|
||||
// cookie 表示当前遍历过程中的登录凭证
|
||||
for _, cookie := range saved {
|
||||
if cookie.Name == "x5sec" && cookie.HTTPOnly && cookie.Secure && cookie.Expires > 0 {
|
||||
exactX5 = true
|
||||
@@ -318,23 +371,29 @@ func TestOnTokenCaptchaVerificationPersistsExactBrowserJar(t *testing.T) {
|
||||
|
||||
// TestHandleSystemEvent_UninjectedSafe 未注入 automation 时安全返回 nil。
|
||||
func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
if err := a.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid"}); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := a.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid"}); err != nil {
|
||||
t.Fatalf("未注入 automation 应返回 nil: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_LocalHitShortCircuits 本地订单字段齐全时不启动浏览器。
|
||||
func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, cookie_id, spec_name, spec_value, quantity, amount) VALUES ('o-local','cid','套餐','30天','1','9.9')`)
|
||||
|
||||
// browser=nil,本地命中应短路;若误走浏览器分支会 panic。
|
||||
a := New(store, nil, nil)
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "o-local", "item-1", "buyer-1", "cookie")
|
||||
if err != nil {
|
||||
t.Fatalf("本地命中不应报错: %v", err)
|
||||
@@ -346,10 +405,13 @@ func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
|
||||
// TestFetchOrderDetail_MTopNilReturnsError 本地缺字段且 MTOP 客户端未配置时返回明确错误。
|
||||
func TestFetchOrderDetail_MTopNilReturnsError(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetOrderDetailClient(nil)
|
||||
// err 保存err,供当前处理流程使用
|
||||
_, err := a.FetchOrderDetail(context.Background(), "cid", "o-missing", "item-1", "buyer-1", "cookie")
|
||||
if err == nil {
|
||||
t.Fatal("MTOP=nil 且本地缺失应返回错误")
|
||||
@@ -358,9 +420,12 @@ func TestFetchOrderDetail_MTopNilReturnsError(t *testing.T) {
|
||||
|
||||
// TestFetchOrderDetail_GoMTop 本地缺失时调用 Go MTOP 并保存响应 Cookie。
|
||||
func TestFetchOrderDetail_GoMTop(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetOrderDetailClient(&fakeOrderDetailClient{
|
||||
detail: &mtop.OrderDetailResult{
|
||||
@@ -368,6 +433,7 @@ func TestFetchOrderDetail_GoMTop(t *testing.T) {
|
||||
UpdatedCookies: "unb=1; _m_h5_tk=newtoken;",
|
||||
},
|
||||
})
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "o-fallback", "item-1", "buyer-1", "old-cookie")
|
||||
if err != nil {
|
||||
t.Fatalf("Go MTOP 应成功: %v", err)
|
||||
@@ -382,40 +448,55 @@ func TestFetchOrderDetail_GoMTop(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_PersistsFlatGoMTopCookie 负责TestFetch订单DetailPersistsFlatGoMTop登录凭证相关处理。
|
||||
func TestFetchOrderDetail_PersistsFlatGoMTopCookie(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
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 {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
_, err := a.FetchOrderDetail(ctx, "cid", "o-jar", "item-1", "buyer-1", "old-cookie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// complete 保存complete,供当前处理流程使用
|
||||
_, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetailSessionExpiredRenewsAndRetries 负责TestFetch订单Detail会话ExpiredRenewsAndRetries相关处理。
|
||||
func TestFetchOrderDetailSessionExpiredRenewsAndRetries(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// now 保存now,供当前处理流程使用
|
||||
now := time.Now()
|
||||
// oldCookie 保存old登录凭证,供当前处理流程使用
|
||||
oldCookie := "unb=1; sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) +
|
||||
"; havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10) + "; havana_lgc2_77=old"
|
||||
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", oldCookie, `{}`, now.Unix()); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Cookies.UpdateRenewalCookie(ctx, "cid", oldCookie, `{}`, now.Unix()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{TaskKey: "blocked", CookieID: "cid", TriggerType: automation.TriggerOrderPaid, TaskJSON: `{}`, DueAt: now.Add(time.Hour).Unix(), ErrorMessage: "Session过期"}); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Automation.DeferTask(ctx, db.DeferredAutomationTask{TaskKey: "blocked", CookieID: "cid", TriggerType: automation.TriggerOrderPaid, TaskJSON: `{}`, DueAt: now.Add(time.Hour).Unix(), ErrorMessage: "Session过期"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := &scriptedOrderDetailClient{results: []struct {
|
||||
detail *mtop.OrderDetailResult
|
||||
err error
|
||||
@@ -424,33 +505,43 @@ func TestFetchOrderDetailSessionExpiredRenewsAndRetries(t *testing.T) {
|
||||
{err: errors.New("token API 返回非成功: FAIL_SYS_SESSION_EXPIRED::Session过期")},
|
||||
{detail: &mtop.OrderDetailResult{Quantity: "1", SpecName: "套餐", SpecValue: "续期版", Amount: "9.9"}},
|
||||
}}
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(renewSvc)
|
||||
a.SetOrderDetailClient(client)
|
||||
// detail、err 保存detail、err,供当前处理流程使用
|
||||
detail, err := a.FetchOrderDetail(ctx, "cid", "expired-order", "item", "buyer", "")
|
||||
if err != nil || detail == nil || detail.SpecValue != "续期版" {
|
||||
t.Fatalf("detail=%+v err=%v", detail, err)
|
||||
}
|
||||
// saved 保存saved,供当前处理流程使用
|
||||
saved, _ := store.Cookies.GetValue(ctx, "cid")
|
||||
if !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("renewed cookie not saved: %q", saved)
|
||||
}
|
||||
// dueAt 保存dueAt,供当前处理流程使用
|
||||
var dueAt int64
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='blocked'`).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.DB.QueryRowContext(ctx, `SELECT due_at FROM automation_pending_tasks WHERE task_key='blocked'`).Scan(&dueAt); err != nil || dueAt != 0 {
|
||||
t.Fatalf("credential-blocked task not woken: due_at=%d err=%v", dueAt, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc; havana_lgc_exp=9999999999999"); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; _m_h5_tk=tk; havana_lgc2_77=lgc; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -460,13 +551,16 @@ func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
|
||||
if !a.OnPasswordLoginRefresh(context.Background(), "cid") {
|
||||
t.Fatal("轻量续期成功不应启动密码登录冷却")
|
||||
}
|
||||
// saved 保存saved,供当前处理流程使用
|
||||
saved, _ := store.Cookies.GetValue(context.Background(), "cid")
|
||||
if !strings.Contains(saved, "havana_lgc2_77=verified") {
|
||||
t.Fatalf("接口续期 cookie 未保存: %q", saved)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefreshWaitsForPendingFinalResult 负责TestOn密码登录RefreshWaitsForPendingFinal结果相关处理。
|
||||
func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
// tt 表示当前遍历过程中的tt
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
body string
|
||||
@@ -477,26 +571,32 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
{name: "late business failure", body: `{"content":{"data":{"processFinished":true,"resultCode":500}}}`, want: false, wantCookie: true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
renewal.GlobalCooldown.Reset("cid")
|
||||
if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=1; havana_lgc_exp=9999999999999"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// srv 保存srv,供当前处理流程使用
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
http.SetCookie(w, &http.Cookie{Name: "late_cookie", Value: "saved", Path: "/"})
|
||||
_, _ = w.Write([]byte(tt.body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetRenewService(xrenew.Service{
|
||||
HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL,
|
||||
RetryDelay: -1, PromiseTimeout: 5 * time.Millisecond,
|
||||
})
|
||||
if got := a.OnPasswordLoginRefresh(context.Background(), "cid"); got != tt.want {
|
||||
if // got 保存got,供当前处理流程使用
|
||||
got := a.OnPasswordLoginRefresh(context.Background(), "cid"); got != tt.want {
|
||||
t.Fatalf("pending 最终恢复结果=%v want %v", got, tt.want)
|
||||
}
|
||||
// saved、err 保存saved、err,供当前处理流程使用
|
||||
saved, err := store.Cookies.GetValue(context.Background(), "cid")
|
||||
if err != nil || strings.Contains(saved, "late_cookie=saved") != tt.wantCookie {
|
||||
t.Fatalf("迟到 Cookie 保存异常: value=%q err=%v", saved, err)
|
||||
@@ -507,15 +607,19 @@ func TestOnPasswordLoginRefreshWaitsForPendingFinalResult(t *testing.T) {
|
||||
|
||||
// TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure 接口轻量续期也失败后才因浏览器不可用失败。
|
||||
func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
if a.OnPasswordLoginRefresh(context.Background(), "cid") {
|
||||
t.Fatal("browser=nil 且接口续期失败时应返回 false")
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(context.Background(), "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || logs[0].Method != "protocol" {
|
||||
t.Fatalf("协议续期失败应要求扫码: logs=%#v err=%v", logs, err)
|
||||
@@ -524,10 +628,14 @@ func TestOnPasswordLoginRefresh_BrowserNilReturnsFalseAfterAPIFailure(t *testing
|
||||
|
||||
// TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse 有浏览器但账号未配密码时返回 false 并停用账号。
|
||||
func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -538,6 +646,7 @@ func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
|
||||
if !store.Cookies.GetStatus(ctx, "cid") {
|
||||
t.Fatal("Go 客户端不得因未配置密码停用账号")
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
@@ -546,15 +655,21 @@ func TestOnPasswordLoginRefresh_NoCredentialsReturnsFalse(t *testing.T) {
|
||||
|
||||
// TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew 协议失败后不得调用浏览器续期。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", 9999999999); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", 9999999999); err != nil {
|
||||
t.Fatalf("保存旧 token: %v", err)
|
||||
}
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewCookies: map[string]string{"unb": "1", "_m_h5_tk": "renewed"}}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := verifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -568,6 +683,7 @@ func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls)
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
@@ -576,14 +692,19 @@ func TestOnPasswordLoginRefresh_DoesNotUseBrowserRenew(t *testing.T) {
|
||||
|
||||
// TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin 配好密码也不得启动 Chromium 登录。
|
||||
func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
// 配置账号用户名/密码。
|
||||
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginCookies: map[string]string{"unb": "1", "_m_h5_tk": "fresh"}}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -594,6 +715,7 @@ func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用 Chromium PasswordLogin,got %d", fb.loginCalls)
|
||||
}
|
||||
// d、err 保存d、err,供当前处理流程使用
|
||||
d, err := store.Cookies.GetDetails(ctx, "cid")
|
||||
if err != nil {
|
||||
t.Fatalf("GetDetails: %v", err)
|
||||
@@ -601,6 +723,7 @@ func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
if d.LoginMethod == "password" {
|
||||
t.Fatalf("不得标记密码登录: %+v", d)
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
@@ -609,13 +732,18 @@ func TestOnPasswordLoginRefresh_DoesNotUsePasswordLogin(t *testing.T) {
|
||||
|
||||
// TestOnPasswordLoginRefresh_LoginError 浏览器登录返回错误时返回 false 且不保存 cookie。
|
||||
func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("captcha required")}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -626,20 +754,27 @@ func TestOnPasswordLoginRefresh_LoginError(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("验证失败后的账密错误冷却期应返回 false")
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_BaxiaFailureReason 负责TestOn密码登录RefreshBaxiaFailure原因相关处理。
|
||||
func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("baxia-punish 风控图形验证")}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -647,6 +782,7 @@ func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
|
||||
if a.OnPasswordLoginRefresh(ctx, "cid") {
|
||||
t.Fatal("风控失败应返回 false")
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 1 || logs[0].FailureReason != "qr_login_required" || fb.loginCalls != 0 {
|
||||
t.Fatalf("不得调用密码登录,应要求扫码: logs=%#v err=%v", logs, err)
|
||||
@@ -656,14 +792,20 @@ func TestOnPasswordLoginRefresh_BaxiaFailureReason(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestOnPasswordLoginRefresh_DisablesFrozenAccountError 负责TestOn密码登录RefreshDisablesFrozen账号错误相关处理。
|
||||
func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginErr: errors.New("账号已被冻结")}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -676,9 +818,12 @@ func TestOnPasswordLoginRefresh_DisablesFrozenAccountError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPasswordLoginProcessingLock 负责Test密码登录Processing锁相关处理。
|
||||
func TestPasswordLoginProcessingLock(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
if !a.beginPasswordLogin("cid") {
|
||||
t.Fatal("首次获取 processing 锁应成功")
|
||||
@@ -694,13 +839,18 @@ func TestPasswordLoginProcessingLock(t *testing.T) {
|
||||
|
||||
// TestOnPasswordLoginRefresh_Cooldown 同一账号短时间内第二次刷新被冷却拒绝。
|
||||
func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
store.DB.ExecContext(ctx, `UPDATE cookies SET username='u', password='p' WHERE id='cid'`)
|
||||
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{renewErr: errors.New("quick enter unavailable"), loginCookies: map[string]string{"unb": "1"}}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// renewSvc、closeRenew 保存renewSvc、closeRenew,供当前处理流程使用
|
||||
renewSvc, closeRenew := unverifiedRenewService(t)
|
||||
defer closeRenew()
|
||||
a.SetRenewService(renewSvc)
|
||||
@@ -715,6 +865,7 @@ func TestOnPasswordLoginRefresh_Cooldown(t *testing.T) {
|
||||
if fb.loginCalls != 0 {
|
||||
t.Fatalf("任何一次都不应调用浏览器,got calls=%d", fb.loginCalls)
|
||||
}
|
||||
// logs、err 保存logs、err,供当前处理流程使用
|
||||
logs, err := store.LoginLogs.ListByCookie(ctx, "cid", 10)
|
||||
if err != nil || len(logs) != 2 || logs[0].FailureReason != "qr_login_required" {
|
||||
t.Fatalf("协议失败应记录重新扫码日志: logs=%#v err=%v", logs, err)
|
||||
|
||||
@@ -14,19 +14,23 @@ import (
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
// remoteCaptchaBrowserTimeout 保存remoteCaptcha浏览器Timeout,供当前处理流程使用
|
||||
const (
|
||||
remoteCaptchaBrowserTimeout = 20
|
||||
remoteCaptchaResponseLimit = 1 << 20
|
||||
)
|
||||
|
||||
// remoteCaptchaConfig 保存remoteCaptcha配置,供当前处理流程使用
|
||||
type remoteCaptchaConfig struct {
|
||||
URL string
|
||||
Secret string
|
||||
PassCookies bool
|
||||
}
|
||||
|
||||
// remoteCaptchaStatus 保存remoteCaptcha状态,供当前处理流程使用
|
||||
type remoteCaptchaStatus uint8
|
||||
|
||||
// remoteCaptchaFallback 保存remoteCaptchaFallback,供当前处理流程使用
|
||||
const (
|
||||
remoteCaptchaFallback remoteCaptchaStatus = iota
|
||||
remoteCaptchaOK
|
||||
@@ -34,21 +38,25 @@ const (
|
||||
remoteCaptchaURLExpired
|
||||
)
|
||||
|
||||
// remoteCaptchaResult 保存remoteCaptcha结果,供当前处理流程使用
|
||||
type remoteCaptchaResult struct {
|
||||
status remoteCaptchaStatus
|
||||
cookies map[string]string
|
||||
err error
|
||||
}
|
||||
|
||||
// loadRemoteCaptchaConfig 负责loadRemoteCaptcha配置相关处理。
|
||||
func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context) *remoteCaptchaConfig {
|
||||
if a.store == nil || a.store.Settings == nil {
|
||||
return nil
|
||||
}
|
||||
// urlValue、err 保存地址Value、err,供当前处理流程使用
|
||||
urlValue, err := a.store.Settings.Get(ctx, "captcha.remote_service_url")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块地址失败,回退本机逻辑", "err", err)
|
||||
return nil
|
||||
}
|
||||
// secret、err 保存secret、err,供当前处理流程使用
|
||||
secret, err := a.store.Settings.Get(ctx, "captcha.remote_secret_key")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块密钥失败,回退本机逻辑", "err", err)
|
||||
@@ -58,6 +66,7 @@ func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context) *remoteCaptchaCon
|
||||
if urlValue == "" || secret == "" {
|
||||
return nil
|
||||
}
|
||||
// passCookies、err 保存passCookies、err,供当前处理流程使用
|
||||
passCookies, err := a.store.Settings.Get(ctx, "captcha.remote_pass_cookies")
|
||||
if err != nil {
|
||||
a.logger.Warn("读取远程过滑块 Cookie 开关失败,按关闭处理", "err", err)
|
||||
@@ -69,7 +78,9 @@ func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context) *remoteCaptchaCon
|
||||
}
|
||||
}
|
||||
|
||||
// newRemoteCaptchaHTTPClient 负责newRemoteCaptchaHTTPClient相关处理。
|
||||
func newRemoteCaptchaHTTPClient() *http.Client {
|
||||
// dialer 保存dialer,供当前处理流程使用
|
||||
dialer := &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
@@ -86,7 +97,9 @@ func newRemoteCaptchaHTTPClient() *http.Client {
|
||||
}
|
||||
}
|
||||
|
||||
// callRemoteCaptcha 负责callRemoteCaptcha相关处理。
|
||||
func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptchaConfig, accountID, verificationURL, cookies, deviceID string) remoteCaptchaResult {
|
||||
// payload 保存请求载荷,供当前处理流程使用
|
||||
payload := map[string]any{
|
||||
"secret_key": cfg.Secret,
|
||||
"account_id": accountID,
|
||||
@@ -97,20 +110,24 @@ func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptc
|
||||
payload["cookies"] = cookies
|
||||
payload["device_id"] = deviceID
|
||||
}
|
||||
// raw、err 保存raw、err,供当前处理流程使用
|
||||
raw, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: err}
|
||||
}
|
||||
// req、err 保存req、err,供当前处理流程使用
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.URL, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: err}
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
// resp、err 保存resp、err,供当前处理流程使用
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFallback, err: err}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
// body、err 保存body、err,供当前处理流程使用
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, remoteCaptchaResponseLimit+1))
|
||||
if err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFallback, err: err}
|
||||
@@ -118,6 +135,7 @@ func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptc
|
||||
if len(body) > remoteCaptchaResponseLimit {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("远程响应超过 %d 字节", remoteCaptchaResponseLimit)}
|
||||
}
|
||||
// decoded 保存decoded,供当前处理流程使用
|
||||
var decoded struct {
|
||||
Success bool `json:"success"`
|
||||
Data struct {
|
||||
@@ -125,7 +143,8 @@ func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptc
|
||||
URLExpired bool `json:"url_expired"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &decoded); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := json.Unmarshal(body, &decoded); err != nil {
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("解析远程响应: %w", err)}
|
||||
}
|
||||
if decoded.Success && hasX5Cookies(decoded.Data.Cookies) {
|
||||
@@ -137,6 +156,7 @@ func callRemoteCaptcha(ctx context.Context, client *http.Client, cfg remoteCaptc
|
||||
return remoteCaptchaResult{status: remoteCaptchaFailed, err: fmt.Errorf("远程过滑块未通过(HTTP %d)", resp.StatusCode)}
|
||||
}
|
||||
|
||||
// solveRemoteCaptcha 负责solveRemoteCaptcha相关处理。
|
||||
func solveRemoteCaptcha(
|
||||
ctx context.Context,
|
||||
client *http.Client,
|
||||
@@ -144,9 +164,13 @@ func solveRemoteCaptcha(
|
||||
accountID, verificationURL, cookieStr, deviceID string,
|
||||
provider func(context.Context, string) (string, bool, string, error),
|
||||
) (cookies string, handled bool, err error) {
|
||||
// currentCookies 保存currentCookies,供当前处理流程使用
|
||||
currentCookies := cookieStr
|
||||
// currentURL 保存currentURL,供当前处理流程使用
|
||||
currentURL := verificationURL
|
||||
for refreshCount := 0; ; {
|
||||
for // refreshCount 保存refresh数量,供当前处理流程使用
|
||||
refreshCount := 0; ; {
|
||||
// result 保存结果,供当前处理流程使用
|
||||
result := callRemoteCaptcha(ctx, client, cfg, accountID, currentURL, currentCookies, deviceID)
|
||||
switch result.status {
|
||||
case remoteCaptchaFallback:
|
||||
@@ -160,6 +184,7 @@ func solveRemoteCaptcha(
|
||||
return "", true, fmt.Errorf("远程反馈验证链接已过期且无法重取")
|
||||
}
|
||||
refreshCount++
|
||||
// freshURL、tokenOK、updatedCookies、providerErr 保存freshURL、tokenOK、updatedCookies、providerErr,供当前处理流程使用
|
||||
freshURL, tokenOK, updatedCookies, providerErr := provider(ctx, currentCookies)
|
||||
if providerErr != nil {
|
||||
return "", true, fmt.Errorf("远程验证链接过期后重取失败: %w", providerErr)
|
||||
@@ -178,8 +203,11 @@ func solveRemoteCaptcha(
|
||||
}
|
||||
}
|
||||
|
||||
// hasX5Cookies 负责hasX5Cookies相关处理。
|
||||
func hasX5Cookies(cookies map[string]string) bool {
|
||||
// name、value 表示当前遍历过程中的name、value
|
||||
for name, value := range cookies {
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
lower := strings.ToLower(strings.TrimSpace(name))
|
||||
if strings.TrimSpace(value) != "" && (strings.HasPrefix(lower, "x5") || strings.Contains(lower, "x5sec")) {
|
||||
return true
|
||||
@@ -188,9 +216,13 @@ func hasX5Cookies(cookies map[string]string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// mergeX5Cookies 负责mergeX5Cookies相关处理。
|
||||
func mergeX5Cookies(original string, incoming map[string]string) string {
|
||||
// merged 保存merged,供当前处理流程使用
|
||||
merged := cookierefresh.ParseCookieString(original)
|
||||
// name、value 表示当前遍历过程中的name、value
|
||||
for name, value := range incoming {
|
||||
// lower 保存lower,供当前处理流程使用
|
||||
lower := strings.ToLower(strings.TrimSpace(name))
|
||||
if strings.HasPrefix(lower, "x5") || strings.Contains(lower, "x5sec") {
|
||||
merged[name] = value
|
||||
|
||||
@@ -11,20 +11,27 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestRemoteCaptchaSuccessWorksWithoutLocalBrowser 负责TestRemoteCaptchaSuccessWorksWithoutLocal浏览器相关处理。
|
||||
func TestRemoteCaptchaSuccessWorksWithoutLocalBrowser(t *testing.T) {
|
||||
// payload 保存请求载荷,供当前处理流程使用
|
||||
var payload map[string]any
|
||||
// remote 保存remote,供当前处理流程使用
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
|
||||
t.Errorf("decode payload: %v", err)
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"success":true,"data":{"cookies":{"x5sec":"fresh","other":"must-not-merge"}}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
if err := store.Settings.SetMany(ctx, map[string]string{
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.Settings.SetMany(ctx, map[string]string{
|
||||
"captcha.remote_service_url": remote.URL,
|
||||
"captcha.remote_secret_key": "remote-secret",
|
||||
"captcha.remote_pass_cookies": "false",
|
||||
@@ -32,7 +39,9 @@ func TestRemoteCaptchaSuccessWorksWithoutLocalBrowser(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
// result、ok 保存result、ok,供当前处理流程使用
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1; old=keep", "https://punish.example", "device-private")
|
||||
if !ok || result == nil || !strings.Contains(result.UpdatedCookies, "x5sec=fresh") {
|
||||
t.Fatalf("remote result=%+v ok=%v", result, ok)
|
||||
@@ -43,14 +52,18 @@ func TestRemoteCaptchaSuccessWorksWithoutLocalBrowser(t *testing.T) {
|
||||
if payload["secret_key"] != "remote-secret" || payload["account_id"] != "cid" || payload["browser_timeout"] != float64(20) {
|
||||
t.Fatalf("remote payload=%#v", payload)
|
||||
}
|
||||
if _, exists := payload["cookies"]; exists {
|
||||
if // exists 保存exists,供当前处理流程使用
|
||||
_, exists := payload["cookies"]; exists {
|
||||
t.Fatalf("关闭传递 Cookie 时不应发送账号 Cookie: %#v", payload)
|
||||
}
|
||||
if _, exists := payload["device_id"]; exists {
|
||||
if // exists 保存exists,供当前处理流程使用
|
||||
_, exists := payload["device_id"]; exists {
|
||||
t.Fatalf("关闭传递 Cookie 时不应发送设备 ID: %#v", payload)
|
||||
}
|
||||
// status、engineName 保存status、engine名称,供当前处理流程使用
|
||||
var status, engineName string
|
||||
if err := store.DB.QueryRowContext(ctx,
|
||||
if // err 保存err,供当前处理流程使用
|
||||
err := store.DB.QueryRowContext(ctx,
|
||||
`SELECT processing_status,captcha_engine FROM risk_control_logs WHERE cookie_id='cid' ORDER BY id DESC LIMIT 1`).
|
||||
Scan(&status, &engineName); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -60,12 +73,18 @@ func TestRemoteCaptchaSuccessWorksWithoutLocalBrowser(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost 负责TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost相关处理。
|
||||
func TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost(t *testing.T) {
|
||||
// calls 保存calls,供当前处理流程使用
|
||||
var calls int
|
||||
// gotURLs 保存gotURLs,供当前处理流程使用
|
||||
var gotURLs []string
|
||||
// gotCookies 保存gotCookies,供当前处理流程使用
|
||||
var gotCookies []string
|
||||
// remote 保存remote,供当前处理流程使用
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
// payload 保存请求载荷,供当前处理流程使用
|
||||
var payload map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&payload)
|
||||
gotURLs = append(gotURLs, payload["url"].(string))
|
||||
@@ -78,7 +97,9 @@ func TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost(t *testing.T) {
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
// providerCalls 保存providerCalls,供当前处理流程使用
|
||||
providerCalls := 0
|
||||
// provider 保存provider,供当前处理流程使用
|
||||
provider := func(_ context.Context, current string) (string, bool, string, error) {
|
||||
providerCalls++
|
||||
if current != "unb=1" {
|
||||
@@ -86,6 +107,7 @@ func TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost(t *testing.T) {
|
||||
}
|
||||
return "https://fresh.example", false, "unb=1; _m_h5_tk=fresh", nil
|
||||
}
|
||||
// cookies、handled、err 保存cookies、handled、err,供当前处理流程使用
|
||||
cookies, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret", PassCookies: true,
|
||||
}, "cid", "https://expired.example", "unb=1", "device-1", provider)
|
||||
@@ -100,14 +122,18 @@ func TestRemoteCaptchaURLExpiredRefreshesTwiceAtMost(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteCaptchaTokenAlreadyUsableReturnsUpdatedCookies 负责TestRemoteCaptcha令牌AlreadyUsableReturnsUpdatedCookies相关处理。
|
||||
func TestRemoteCaptchaTokenAlreadyUsableReturnsUpdatedCookies(t *testing.T) {
|
||||
// remote 保存remote,供当前处理流程使用
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":true}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
// provider 保存provider,供当前处理流程使用
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return "", true, "unb=1; _m_h5_tk=renewed", nil
|
||||
}
|
||||
// cookies、handled、err 保存cookies、handled、err,供当前处理流程使用
|
||||
cookies, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret",
|
||||
}, "cid", "https://expired.example", "unb=1", "device", provider)
|
||||
@@ -116,21 +142,28 @@ func TestRemoteCaptchaTokenAlreadyUsableReturnsUpdatedCookies(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteCaptchaExplicitFailureDoesNotFallbackToBrowser 负责TestRemoteCaptchaExplicitFailureDoesNotFallbackTo浏览器相关处理。
|
||||
func TestRemoteCaptchaExplicitFailureDoesNotFallbackToBrowser(t *testing.T) {
|
||||
// remote 保存remote,供当前处理流程使用
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":false}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
// store、cleanup 保存store、cleanup,供当前处理流程使用
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存ctx,供当前处理流程使用
|
||||
ctx := context.Background()
|
||||
_ = store.Settings.SetMany(ctx, map[string]string{
|
||||
"captcha.remote_service_url": remote.URL, "captcha.remote_secret_key": "secret",
|
||||
})
|
||||
// fb 保存fb,供当前处理流程使用
|
||||
fb := &fakeBrowser{tokenCaptchaResult: "unb=1; x5sec=local"}
|
||||
// a 保存a,供当前处理流程使用
|
||||
a := New(store, nil, nil)
|
||||
a.SetBrowser(fb)
|
||||
if result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://punish.example", "device"); ok || result != nil {
|
||||
if // result、ok 保存result、ok,供当前处理流程使用
|
||||
result, ok := a.OnTokenCaptchaVerification(ctx, "cid", "unb=1", "https://punish.example", "device"); ok || result != nil {
|
||||
t.Fatalf("明确远程失败应直接失败: result=%+v ok=%v", result, ok)
|
||||
}
|
||||
if fb.tokenCaptchaCalls != 0 {
|
||||
@@ -138,14 +171,19 @@ func TestRemoteCaptchaExplicitFailureDoesNotFallbackToBrowser(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// failingRoundTripper 保存failingRoundTripper,供当前处理流程使用
|
||||
type failingRoundTripper struct{}
|
||||
|
||||
// RoundTrip 负责RoundTrip相关处理。
|
||||
func (failingRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("network unavailable")
|
||||
}
|
||||
|
||||
// TestRemoteCaptchaNetworkErrorRequestsLocalFallback 负责TestRemoteCaptchaNetwork错误请求列表LocalFallback相关处理。
|
||||
func TestRemoteCaptchaNetworkErrorRequestsLocalFallback(t *testing.T) {
|
||||
// client 保存client,供当前处理流程使用
|
||||
client := &http.Client{Transport: failingRoundTripper{}}
|
||||
// handled、err 保存handled、err,供当前处理流程使用
|
||||
_, handled, err := solveRemoteCaptcha(context.Background(), client, remoteCaptchaConfig{
|
||||
URL: "https://remote.example", Secret: "secret",
|
||||
}, "cid", "https://punish.example", "unb=1", "device", nil)
|
||||
@@ -154,14 +192,18 @@ func TestRemoteCaptchaNetworkErrorRequestsLocalFallback(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemoteCaptchaProviderErrorIsHandledFailure 负责TestRemoteCaptchaProvider错误IsHandledFailure相关处理。
|
||||
func TestRemoteCaptchaProviderErrorIsHandledFailure(t *testing.T) {
|
||||
// remote 保存remote,供当前处理流程使用
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, `{"success":false,"data":{"url_expired":true}}`)
|
||||
}))
|
||||
defer remote.Close()
|
||||
// provider 保存provider,供当前处理流程使用
|
||||
provider := func(context.Context, string) (string, bool, string, error) {
|
||||
return "", false, "", errors.New("token request failed")
|
||||
}
|
||||
// handled、err 保存handled、err,供当前处理流程使用
|
||||
_, handled, err := solveRemoteCaptcha(context.Background(), remote.Client(), remoteCaptchaConfig{
|
||||
URL: remote.URL, Secret: "secret",
|
||||
}, "cid", "https://expired.example", "unb=1", "device", provider)
|
||||
|
||||
Reference in new issue
Block a user