修复 Cookie 续期终态与账号恢复链路

This commit is contained in:
Christ committed 2026-07-28 11:57:48 +08:00
1 parent 50d09eb47a
commit 5f4d199231
11 files changed
+430 -77

No files matched your search

+58 -2
View File
@@ -695,6 +695,18 @@ func (a *Account) beginTask() (context.Context, bool) {
// handleMaxFailures 是历史兼容恢复入口;只尝试 Go 协议续期,不执行密码登录。
func (a *Account) handleMaxFailures(ctx context.Context) error {
// 先执行低成本登录态检查。它可能仅凭 loginuser.get 响应头恢复签名
// Cookie,也能在进入静默续期前准确识别风控状态。
loginStatus := a.tryLoginStatusCheck(ctx)
if loginStatus.riskRequired {
return fmt.Errorf("账号 %s 需要完成安全验证", a.CookieID)
}
if loginStatus.recovered {
a.logger.Info("登录态检查已恢复 Cookie,重置失败计数")
a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接")
a.resetFailures()
return sleepCtx(ctx, 2*time.Second)
}
credentialUnlock := func() {}
if a.store != nil {
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
@@ -800,10 +812,54 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
if !ok {
return loginStatusCheckResult{}
}
credentialUnlock := func() {}
if a.store != nil {
credentialUnlock = a.store.LockAccountCredentials(a.CookieID)
}
defer credentialUnlock()
a.mu.Lock()
cookieStr := a.CookieStr
a.mu.Unlock()
res, err := checker.CheckLoginStatusContext(ctx, cookieStr)
requestCtx := ctx
var cookieSession *mtop.CookieSession
metadataJSON := ""
if a.store != nil && a.store.Cookies != nil {
detail, detailErr := a.store.Cookies.GetDetails(ctx, a.CookieID)
if detailErr != nil || detail == nil {
if detailErr == nil {
detailErr = db.ErrNotFound
}
a.logger.Warn("登录态检查前读取最新 Cookie 失败", "err", detailErr)
return loginStatusCheckResult{}
}
cookieStr = detail.Value
metadataJSON = detail.MetadataJSON
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
} else {
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
}
}
res, err := checker.CheckLoginStatusContext(requestCtx, cookieStr)
if cookieSession != nil {
value, snapshot, changed := cookieSession.State()
if changed {
metadata := cookierefresh.MetadataWithoutSnapshot(metadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(metadataJSON, snapshot)
}
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, a.CookieID, value, metadata, time.Now().Unix()); persistErr != nil {
a.logger.Warn("登录态检查保存响应 Cookie Jar 失败", "err", persistErr)
return loginStatusCheckResult{}
}
a.replaceCredentialState(value, credentialStateFingerprint(value, metadata))
a.clearTokenCache(ctx)
if err != nil {
a.logger.Warn("登录态检查失败,已保存响应 Cookie", "err", err)
}
return loginStatusCheckResult{recovered: res != nil && res.Status == mtop.LoginStatusTokenRefreshed}
}
}
if err != nil {
a.logger.Warn("登录态检查失败", "err", err)
return loginStatusCheckResult{}
@@ -816,7 +872,7 @@ func (a *Account) tryLoginStatusCheck(ctx context.Context) loginStatusCheckResul
a.logger.Warn("登录态检查命中风控验证", "ret", strings.Join(res.Ret, ","), "verification_url", res.VerificationURL)
return loginStatusCheckResult{riskRequired: true, verificationURL: res.VerificationURL}
}
if a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
if res.Status == mtop.LoginStatusTokenRefreshed && len(cookierefresh.ChangedCookieNames(cookieStr, res.UpdatedCookies)) > 0 && a.adoptRecoveredCookie(ctx, res.UpdatedCookies, "登录态检查") {
a.logger.Info("登录态检查刷新了 Cookie", "status", res.Status, "message", res.Message)
return loginStatusCheckResult{recovered: true}
}
+3
View File
@@ -60,6 +60,9 @@ func newAccountForTest(t *testing.T) (*Account, *recordingHandler, *db.Store, fu
Store: store,
Handler: h,
})
// 通用账号测试默认不启用 loginuser.get;需要验证登录态恢复的用例会
// 显式注入 statusMtop,避免单元测试访问真实网络。
acc.mtop = &fakeRunMtop{token: "test-token"}
return acc, h, store, func() { d.Close() }
}
+31
View File
@@ -264,6 +264,37 @@ func TestTryLoginStatusCheck_RiskRequired(t *testing.T) {
}
}
func TestHandleMaxFailuresRunsLoginStatusCheckBeforeProtocolRenew(t *testing.T) {
newCookie := "unb=123; _m_h5_tk=loginuser_recovered; sgcookie=abc"
mtopClient := &statusMtop{
fakeRunMtop: fakeRunMtop{token: "tok-1"},
result: &mtop.LoginStatusResult{
Status: mtop.LoginStatusTokenRefreshed,
UpdatedCookies: newCookie,
Message: "令牌已刷新",
},
}
acc, handler, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
acc.mu.Lock()
acc.connFailures = MaxConnectionFailures
acc.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
if err := acc.handleMaxFailures(ctx); err != ctx.Err() {
t.Fatalf("登录态恢复后的等待应响应上下文取消: %v", err)
}
if handler.refresh != 0 {
t.Fatalf("loginuser.get 已恢复时不应继续协议续期,calls=%d", handler.refresh)
}
if got := acc.currentCookieStr(); got != newCookie {
t.Fatalf("登录态检查恢复 Cookie=%q want %q", got, newCookie)
}
if acc.connFailures != 0 {
t.Fatalf("登录态恢复后失败计数=%d want 0", acc.connFailures)
}
}
// TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache DB cookie 变更时采纳新 cookie 并清旧 token 缓存。
func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})