From 3cc1d4094d1dae3b7e496c795f2c516f96d20ae8 Mon Sep 17 00:00:00 2001 From: Christ Date: Wed, 15 Jul 2026 09:03:20 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20token=20=E4=B8=8E=20Cookie?= =?UTF-8?q?=20=E7=BB=91=E5=AE=9A=E5=B9=B6=E5=AE=8C=E5=96=84=E8=AE=A4?= =?UTF-8?q?=E8=AF=81=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/adapter/adapter_test.go | 10 +- internal/browser/cookierenew.go | 4 - internal/browser/token_request.go | 58 ++- internal/browser/token_request_test.go | 32 ++ internal/db/account_tokens.go | 37 +- internal/db/account_tokens_test.go | 12 +- internal/db/migrate_test.go | 8 +- .../mysql/00022_token_cookie_binding.sql | 5 + .../postgres/00022_token_cookie_binding.sql | 5 + .../sqlite/00022_token_cookie_binding.sql | 5 + internal/db/multidb_test.go | 6 +- internal/db/store.go | 72 ++-- internal/engine/account.go | 353 ++++++++---------- internal/engine/account_extra_test.go | 33 +- internal/engine/keepalive_test.go | 226 ++--------- internal/engine/run_test.go | 88 ++++- internal/engine/token_cache.go | 58 ++- internal/engine/token_cache_test.go | 44 +-- internal/renewal/scheduler.go | 39 +- internal/renewal/scheduler_test.go | 224 ++--------- internal/xianyu/mtop/client.go | 16 +- internal/xianyu/mtop/token.go | 66 +++- internal/xianyu/mtop/token_test.go | 28 ++ internal/xianyu/protocol/cookies.go | 12 +- internal/xianyu/protocol/cookies_test.go | 7 +- internal/xianyu/qrlogin/client.go | 12 - internal/xianyu/renew/service.go | 183 --------- internal/xianyu/ws/auth_error.go | 94 +++++ internal/xianyu/ws/client.go | 134 ++++++- internal/xianyu/ws/dial_test.go | 117 ++++-- 30 files changed, 990 insertions(+), 998 deletions(-) create mode 100644 internal/browser/token_request_test.go create mode 100644 internal/db/migrations/mysql/00022_token_cookie_binding.sql create mode 100644 internal/db/migrations/postgres/00022_token_cookie_binding.sql create mode 100644 internal/db/migrations/sqlite/00022_token_cookie_binding.sql create mode 100644 internal/xianyu/ws/auth_error.go diff --git a/internal/adapter/adapter_test.go b/internal/adapter/adapter_test.go index bd51af5..8036164 100644 --- a/internal/adapter/adapter_test.go +++ b/internal/adapter/adapter_test.go @@ -108,7 +108,10 @@ func verifiedRenewService(t *testing.T) (xrenew.Service, func()) { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { - case "/hasLogin.do", "/silentHasLogin.do": + case "/hasLogin.do": + _, _ = w.Write([]byte(`{"content":{"success":true}}`)) + case "/silentHasLogin.do": + http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"}) _, _ = w.Write([]byte(`{"content":{"success":true}}`)) case "/setLoginSettings.do": http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "verified"}) @@ -295,6 +298,9 @@ func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) { store, cleanup := newAdapterTestStore(t) defer cleanup() 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 { + t.Fatal(err) + } renewSvc, closeRenew := verifiedRenewService(t) defer closeRenew() a.SetRenewService(renewSvc) @@ -374,7 +380,7 @@ func TestOnPasswordLoginRefresh_BrowserRenewSuccess(t *testing.T) { t.Fatalf("快速续期成功后不应密码登录,got %d", fb.loginCalls) } saved, _ := store.Cookies.GetValue(ctx, "cid") - if !strings.Contains(saved, "_m_h5_tk=renewed") || !strings.Contains(saved, "havana_lgc2_77=verified") { + 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" { diff --git a/internal/browser/cookierenew.go b/internal/browser/cookierenew.go index a339d3c..824cfdf 100644 --- a/internal/browser/cookierenew.go +++ b/internal/browser/cookierenew.go @@ -237,10 +237,6 @@ var quickEnterSelectors = []string{ `.fn-button:has-text("快速进入")`, } -func checkAlreadyLoggedIn(page playwright.Page) bool { - return verifyHomeLoginState(page) == nil -} - func verifyHomeLoginState(page playwright.Page) error { if pageHasSecurityVerification(page) { return ErrSecurityVerification diff --git a/internal/browser/token_request.go b/internal/browser/token_request.go index 34d7e96..60d202b 100644 --- a/internal/browser/token_request.go +++ b/internal/browser/token_request.go @@ -23,16 +23,21 @@ func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowser if unb == "" { return nil, fmt.Errorf("浏览器 token 请求缺少 unb") } - bctx, release, err := m.newPersistentRenewContext(ctx, unb, req.Cookies, nil, true, true) + credentialID := "token_credential_" + unb + lock := m.accountRenewLock(credentialID) + lock.Lock() + defer lock.Unlock() + + page, release, err := m.newPage(ctx, credentialID, req.Cookies, true) if err != nil { return nil, err } defer release() - page, err := bctx.NewPage() - if err != nil { - return nil, fmt.Errorf("浏览器 token 请求新建页面: %w", err) + bctx := page.Context() + if err := syncCredentialCookies(bctx, req.Cookies); err != nil { + m.evict(credentialID) + return nil, fmt.Errorf("浏览器 token 请求同步 Cookie: %w", err) } - defer func() { _ = page.Close() }() if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{ WaitUntil: playwright.WaitUntilStateDomcontentloaded, Timeout: playwright.Float(15000), @@ -76,3 +81,46 @@ func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowser UpdatedCookies: cookierefresh.MergeOriginalFields(req.Cookies, browserCookies), }, 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) error { + incoming := parseCookieStr(cookieStr) + if len(incoming) == 0 { + return fmt.Errorf("Cookie为空或格式错误") + } + existing, err := bctx.Cookies() + if err != nil { + return err + } + preserved := credentialCookieSnapshot(cookieSnapshotFromPlaywright(existing), incoming) + if err := bctx.ClearCookies(); err != nil { + return err + } + return bctx.AddCookies(snapshotToOptionalCookies(preserved)) +} + +func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie { + preserved := make([]cookierefresh.BrowserCookie, 0, len(incoming)) + matched := make(map[string]bool, len(incoming)) + for _, cookie := range existing { + value, ok := incoming[cookie.Name] + if !ok { + continue + } + 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: "/", + }) + } + return cookierefresh.NormalizeSnapshot(preserved) +} diff --git a/internal/browser/token_request_test.go b/internal/browser/token_request_test.go new file mode 100644 index 0000000..405b4d6 --- /dev/null +++ b/internal/browser/token_request_test.go @@ -0,0 +1,32 @@ +package browser + +import ( + "testing" + + "xianyu-go/internal/xianyu/cookierefresh" +) + +func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) { + existing := []cookierefresh.BrowserCookie{ + {Name: "cookie2", Value: "old", Domain: ".taobao.com", Path: "/", Expires: 12345, HTTPOnly: true, Secure: true, SameSite: "None"}, + {Name: "stale", Value: "remove", Domain: ".goofish.com", Path: "/"}, + } + got := credentialCookieSnapshot(existing, map[string]string{"cookie2": "new", "unb": "1"}) + if len(got) != 2 { + t.Fatalf("snapshot length=%d want=2: %+v", len(got), got) + } + byName := map[string]cookierefresh.BrowserCookie{} + for _, cookie := range got { + byName[cookie.Name] = cookie + } + cookie2 := byName["cookie2"] + if cookie2.Value != "new" || cookie2.Domain != ".taobao.com" || cookie2.Expires != 12345 || !cookie2.HTTPOnly || !cookie2.Secure || cookie2.SameSite != "None" { + t.Fatalf("preserved cookie=%+v", cookie2) + } + if unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" { + t.Fatalf("new cookie defaults=%+v", unb) + } + if _, ok := byName["stale"]; ok { + t.Fatal("cookie absent from current snapshot must be removed") + } +} diff --git a/internal/db/account_tokens.go b/internal/db/account_tokens.go index 80f2006..431aad5 100644 --- a/internal/db/account_tokens.go +++ b/internal/db/account_tokens.go @@ -13,10 +13,11 @@ import ( // - device_id 跨进程重启复用,避免每次重启换新设备 ID 触发阿里端设备绑定/风控; // - accessToken 缓存后,短重启可复用、瞬时 mtop 失败可回退到上次有效 token,不掉线。 type AccountToken struct { - CookieID string - DeviceID string - AccessToken string - ExpireAt int64 // unix 秒,0 表示无有效 token + CookieID string + DeviceID string + AccessToken string + ExpireAt int64 // unix 秒,0 表示无有效 token + CookieFingerprint string } // AccountTokens 读写 account_tokens 表。 @@ -31,8 +32,8 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken, var tk AccountToken tk.CookieID = cookieID err := t.DB.QueryRowContext(ctx, - `SELECT device_id, access_token, expire_at FROM account_tokens WHERE cookie_id=?`, - cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt) + `SELECT device_id, access_token, expire_at, cookie_fingerprint FROM account_tokens WHERE cookie_id=?`, + cookieID).Scan(&tk.DeviceID, &tk.AccessToken, &tk.ExpireAt, &tk.CookieFingerprint) if err != nil { if errors.Is(err, sql.ErrNoRows) { return AccountToken{}, ErrNotFound @@ -52,6 +53,13 @@ func (t *AccountTokens) Get(ctx context.Context, cookieID string) (AccountToken, // Save upsert 缓存的 device_id + accessToken + expire_at。 func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64) error { + return t.SaveBound(ctx, cookieID, deviceID, accessToken, expireAt, "") +} + +// SaveBound persists an access token together with the canonical Cookie state +// from which it was issued. The binding lets a later reconnect reject a stale +// token after an independent Cookie renewal without rotating device_id. +func (t *AccountTokens) SaveBound(ctx context.Context, cookieID, deviceID, accessToken string, expireAt int64, cookieFingerprint string) error { // device_id is an account identity, not part of the expiring token cache. // Once stored, token refreshes must never replace it. if existing, err := t.Get(ctx, cookieID); err == nil && existing.DeviceID != "" { @@ -68,15 +76,16 @@ func (t *AccountTokens) Save(ctx context.Context, cookieID, deviceID, accessToke return err } _, err = t.DB.ExecContext(ctx, - `INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, updated_at) - VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)`+ + `INSERT INTO account_tokens (cookie_id, device_id, access_token, expire_at, cookie_fingerprint, updated_at) + VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)`+ dialectUpsert(t.Dialect, []string{"cookie_id"}, map[string]string{ - "device_id": "excluded.device_id", - "access_token": "excluded.access_token", - "expire_at": "excluded.expire_at", - "updated_at": "CURRENT_TIMESTAMP", + "device_id": "excluded.device_id", + "access_token": "excluded.access_token", + "expire_at": "excluded.expire_at", + "cookie_fingerprint": "excluded.cookie_fingerprint", + "updated_at": "CURRENT_TIMESTAMP", }), - cookieID, encryptedDeviceID, encryptedToken, expireAt) + cookieID, encryptedDeviceID, encryptedToken, expireAt, cookieFingerprint) if err != nil { return fmt.Errorf("保存 account_tokens: %w", err) } @@ -123,7 +132,7 @@ func (t *AccountTokens) Clear(ctx context.Context, cookieID string) error { return err } _, err = t.DB.ExecContext(ctx, - `UPDATE account_tokens SET access_token=?, expire_at=0, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`, + `UPDATE account_tokens SET access_token=?, expire_at=0, cookie_fingerprint='', updated_at=CURRENT_TIMESTAMP WHERE cookie_id=?`, encryptedToken, cookieID) return err } diff --git a/internal/db/account_tokens_test.go b/internal/db/account_tokens_test.go index a7093af..a15d26d 100644 --- a/internal/db/account_tokens_test.go +++ b/internal/db/account_tokens_test.go @@ -26,25 +26,25 @@ func TestAccountTokens_CRUD(t *testing.T) { t.Fatalf("不存在应返回 ErrNotFound,got %v", err) } - // Save(首次写入)。 + // SaveBound(首次写入)。 expire := time.Now().Add(time.Hour).Unix() - if err := store.Tokens.Save(ctx, "cid", "dev-1", "tok-1", expire); err != nil { + if err := store.Tokens.SaveBound(ctx, "cid", "dev-1", "tok-1", expire, "cookie-hash-1"); err != nil { t.Fatalf("Save: %v", err) } tk, err := store.Tokens.Get(ctx, "cid") if err != nil { t.Fatalf("Get: %v", err) } - if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire { + if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-1" || tk.ExpireAt != expire || tk.CookieFingerprint != "cookie-hash-1" { t.Fatalf("Get 返回不匹配: %+v", tk) } // 再次 Save 更新 token,但永久 device ID 不允许覆盖。 - if err := store.Tokens.Save(ctx, "cid", "dev-2", "tok-2", expire+1); err != nil { + if err := store.Tokens.SaveBound(ctx, "cid", "dev-2", "tok-2", expire+1, "cookie-hash-2"); err != nil { t.Fatalf("Save upsert: %v", err) } tk, _ = store.Tokens.Get(ctx, "cid") - if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 { + if tk.DeviceID != "dev-1" || tk.AccessToken != "tok-2" || tk.ExpireAt != expire+1 || tk.CookieFingerprint != "cookie-hash-2" { t.Fatalf("upsert 后字段应更新: %+v", tk) } @@ -53,7 +53,7 @@ func TestAccountTokens_CRUD(t *testing.T) { t.Fatalf("Clear: %v", err) } tk, err = store.Tokens.Get(ctx, "cid") - if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 { + if err != nil || tk.DeviceID != "dev-1" || tk.AccessToken != "" || tk.ExpireAt != 0 || tk.CookieFingerprint != "" { t.Fatalf("Clear 后 device ID 应保留且 token 清空: tk=%+v err=%v", tk, err) } diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go index 06595db..df63dfa 100644 --- a/internal/db/migrate_test.go +++ b/internal/db/migrate_test.go @@ -125,8 +125,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { t.Fatalf("goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - // 依次回滚 21 到 14,再整体升级。 - for i := 0; i < 8; i++ { + // 依次回滚 22 到 14,再整体升级。 + for i := 0; i < 9; i++ { if err := goose.Down(d, "migrations/sqlite"); err != nil { t.Fatalf("down migration #%d: %v", i+1, err) } @@ -140,6 +140,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { if columnExists(t, d, "default_reply_records", "status") { t.Fatal("default_reply_records.status should be removed after migration 16 down") } + if columnExists(t, d, "account_tokens", "cookie_fingerprint") { + t.Fatal("account_tokens.cookie_fingerprint should be removed after migration 22 down") + } if err := goose.Up(d, "migrations/sqlite"); err != nil { t.Fatalf("up after down: %v", err) @@ -156,6 +159,7 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { {"risk_control_logs", "processing_status"}, {"default_reply_records", "status"}, {"default_reply_records", "text_sent"}, + {"account_tokens", "cookie_fingerprint"}, } { if !columnExists(t, d, c.table, c.col) { t.Fatalf("column missing after re-up: %s.%s", c.table, c.col) diff --git a/internal/db/migrations/mysql/00022_token_cookie_binding.sql b/internal/db/migrations/mysql/00022_token_cookie_binding.sql new file mode 100644 index 0000000..f2dc711 --- /dev/null +++ b/internal/db/migrations/mysql/00022_token_cookie_binding.sql @@ -0,0 +1,5 @@ +-- +goose Up +ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint VARCHAR(64) NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint; diff --git a/internal/db/migrations/postgres/00022_token_cookie_binding.sql b/internal/db/migrations/postgres/00022_token_cookie_binding.sql new file mode 100644 index 0000000..639cf41 --- /dev/null +++ b/internal/db/migrations/postgres/00022_token_cookie_binding.sql @@ -0,0 +1,5 @@ +-- +goose Up +ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint; diff --git a/internal/db/migrations/sqlite/00022_token_cookie_binding.sql b/internal/db/migrations/sqlite/00022_token_cookie_binding.sql new file mode 100644 index 0000000..639cf41 --- /dev/null +++ b/internal/db/migrations/sqlite/00022_token_cookie_binding.sql @@ -0,0 +1,5 @@ +-- +goose Up +ALTER TABLE account_tokens ADD COLUMN cookie_fingerprint TEXT NOT NULL DEFAULT ''; + +-- +goose Down +ALTER TABLE account_tokens DROP COLUMN cookie_fingerprint; diff --git a/internal/db/multidb_test.go b/internal/db/multidb_test.go index 119c2f8..060ad37 100644 --- a/internal/db/multidb_test.go +++ b/internal/db/multidb_test.go @@ -641,7 +641,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { t.Fatalf("set goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - for i := 0; i < 8; i++ { + for i := 0; i < 9; i++ { if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil { t.Fatalf("migration down #%d: %v", i+1, err) } @@ -655,6 +655,9 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { if columnExistsForDialect(t, tg.store.DB, tg.dialect, "default_reply_records", "status") { t.Fatal("default_reply_records.status should be removed after down") } + if columnExistsForDialect(t, tg.store.DB, tg.dialect, "account_tokens", "cookie_fingerprint") { + t.Fatal("account_tokens.cookie_fingerprint should be removed after down") + } if err := goose.Up(tg.store.DB, "migrations/"+subdir); err != nil { t.Fatalf("migration up after down: %v", err) @@ -673,6 +676,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { {"default_reply_records", "text_sent"}, {"automation_runs", "action_cursor"}, {"automation_runs", "action_started"}, + {"account_tokens", "cookie_fingerprint"}, } { if !columnExistsForDialect(t, tg.store.DB, tg.dialect, c.table, c.col) { t.Fatalf("column missing after re-up: %s.%s", c.table, c.col) diff --git a/internal/db/store.go b/internal/db/store.go index 0f1588f..8738070 100644 --- a/internal/db/store.go +++ b/internal/db/store.go @@ -1,6 +1,9 @@ package db -import "database/sql" +import ( + "database/sql" + "sync" +) // Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。 type Store struct { @@ -25,32 +28,57 @@ type Store struct { Renewal *RenewalStore LoginLogs *AccountLoginLogs RiskLogs *RiskControlLogs + + credentialMu sync.Mutex + credentialLocks map[string]*sync.Mutex } // NewStore 基于 *sql.DB 构造聚合 store。dialect 用于业务 SQL 方言分支。 func NewStore(db *sql.DB, dialect Dialect) *Store { codec := secretCodecFromEnvironment() return &Store{ - DB: db, - Dialect: dialect, - Users: &Users{DB: db}, - Sessions: &Sessions{DB: db}, - Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec}, - Items: &Items{DB: db, Dialect: dialect}, - Cards: &Cards{DB: db, Dialect: dialect}, - Automation: &AutomationRules{DB: db, Dialect: dialect}, - Orders: &Orders{DB: db, Dialect: dialect}, - Keywords: &Keywords{DB: db, Dialect: dialect}, - DefaultReps: &DefaultReplies{DB: db, Dialect: dialect}, - ItemReps: &ItemReplies{DB: db, Dialect: dialect}, - AIReply: &AIReply{DB: db, codec: codec}, - Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec}, - Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec}, - WSMessages: &WSMessageStore{DB: db}, - PublishBatches: &ItemPublishBatches{DB: db}, - Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec}, - Renewal: &RenewalStore{DB: db, Dialect: dialect}, - LoginLogs: &AccountLoginLogs{DB: db}, - RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect}, + DB: db, + Dialect: dialect, + Users: &Users{DB: db}, + Sessions: &Sessions{DB: db}, + Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec}, + Items: &Items{DB: db, Dialect: dialect}, + Cards: &Cards{DB: db, Dialect: dialect}, + Automation: &AutomationRules{DB: db, Dialect: dialect}, + Orders: &Orders{DB: db, Dialect: dialect}, + Keywords: &Keywords{DB: db, Dialect: dialect}, + DefaultReps: &DefaultReplies{DB: db, Dialect: dialect}, + ItemReps: &ItemReplies{DB: db, Dialect: dialect}, + AIReply: &AIReply{DB: db, codec: codec}, + Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec}, + Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec}, + WSMessages: &WSMessageStore{DB: db}, + PublishBatches: &ItemPublishBatches{DB: db}, + Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec}, + Renewal: &RenewalStore{DB: db, Dialect: dialect}, + LoginLogs: &AccountLoginLogs{DB: db}, + RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect}, + credentialLocks: make(map[string]*sync.Mutex), } } + +// LockAccountCredentials serializes Cookie/token state transitions for one +// account across the IM runtime and renewal scheduler. The returned function +// must be called exactly once. +func (s *Store) LockAccountCredentials(cookieID string) func() { + if s == nil { + return func() {} + } + s.credentialMu.Lock() + if s.credentialLocks == nil { + s.credentialLocks = make(map[string]*sync.Mutex) + } + lock := s.credentialLocks[cookieID] + if lock == nil { + lock = &sync.Mutex{} + s.credentialLocks[cookieID] = lock + } + s.credentialMu.Unlock() + lock.Lock() + return lock.Unlock +} diff --git a/internal/engine/account.go b/internal/engine/account.go index c7029bc..ebe8775 100644 --- a/internal/engine/account.go +++ b/internal/engine/account.go @@ -26,29 +26,19 @@ import ( // 账号运行时参数。 const ( - MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新 - TokenFetchDisableThreshold = 100 // 参考实现:连续真实 token 故障 100 次后禁用 - MessageSemaphoreSize = 100 // 并发消息处理上限 - MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复 - MessageExpireTime = time.Hour // 去重有效期 - ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理 - HeartbeatInterval = 15 * time.Second - // 与参考实现保持一致:token_refresh_loop 默认 20 小时一次;cookieRefreshLoop - // 每 180 秒检查一次登录凭证。Cookie 循环优先复用 5-10 小时的 token 缓存, - // 只有缓存未命中时才请求 mtop,不能把“检查间隔”误做成“接口请求间隔”。 - TokenRefreshInterval = 20 * time.Hour - CookieRefreshInterval = 180 * time.Second - CookieRefreshCheckInterval = 60 * time.Second - MessageCooldown = 5 * time.Minute // 收到消息后 5 分钟内不刷 cookie - PasswordLoginMinGap = 60 * time.Second - MaxNetworkFailures = 20 - FrequentDisconnectLimit = 5 - FrequentDisconnectWindow = 5 * time.Minute + MaxConnectionFailures = 5 // 连续失败上限,触发密码登录刷新 + TokenFetchDisableThreshold = 100 // 参考实现:连续真实 token 故障 100 次后禁用 + MessageSemaphoreSize = 100 // 并发消息处理上限 + MessageDebounceDelay = 1 * time.Second // 防抖延迟:用户停止发送 1s 后回复 + MessageExpireTime = time.Hour // 去重有效期 + ProcessedIDsMaxSize = 10000 // 去重表上限,超限清理 + HeartbeatInterval = 15 * time.Second + PasswordLoginMinGap = 60 * time.Second + MaxNetworkFailures = 20 + FrequentDisconnectLimit = 5 + FrequentDisconnectWindow = 5 * time.Minute + TokenCaptchaFailureCooldown = 5 * time.Minute - // TokenCacheTTLMin/Max 控制缓存 accessToken 的随机有效期。短重启 / 瞬时 - // mtop 失败时回退到此缓存不掉线;在线 Cookie 保活由 cookieRefreshLoop 续期。 - TokenCacheTTLMin = 5 * time.Hour - TokenCacheTTLMax = 10 * time.Hour // ShortConnectionThreshold 仅用于统计频繁短连接;已经建立后的网络断线 // 不会清 Token 缓存。 ShortConnectionThreshold = 30 * time.Second @@ -107,6 +97,8 @@ const ( tokenRefreshSkippedCooldown = "skipped_cooldown" ) +var errTokenCaptchaCooldown = errors.New("token 风控验证冷却中") + // ChatMessage 防抖后投递给业务层的一条聊天消息。 type ChatMessage struct { AccountID string // cookie_id @@ -163,8 +155,8 @@ type Account struct { shortDisconnects []time.Time lastMsgReceived time.Time lastTokenRefresh time.Time + lastCaptchaFailure time.Time lastTokenStatus string - lastCookieRefresh time.Time runtimeState string runtimeMessage string runtimeUpdatedAt time.Time @@ -211,7 +203,6 @@ type WSConn interface { HeartbeatLoop(ctx context.Context, interval time.Duration) error ReceiveLoop(ctx context.Context, onMessage func(map[string]any)) error Close() error - SetAccessToken(token string) SendText(ctx context.Context, myID, cid, toID, text string) error SendImage(ctx context.Context, myID, cid, toID, imageURL string, width, height int) error } @@ -308,12 +299,8 @@ func New(cfg Config) *Account { // 调用方应在独立 goroutine 中运行;Stop 可优雅停止。 func (a *Account) Run(parent context.Context) error { ctx, cancel := context.WithCancel(parent) - var backgroundWG sync.WaitGroup - backgroundStarted := false - defer func() { - cancel() - backgroundWG.Wait() - }() + defer cancel() + invalidTokenRetried := false a.mu.Lock() a.stopFn = cancel a.mu.Unlock() @@ -332,11 +319,9 @@ func (a *Account) Run(parent context.Context) error { return nil } - // 1) 必须先检查 token 缓存。只有缓存未命中时,refreshToken 才读取 DB cookie; - // 定时续期写入 DB 不得让一个仍有效的 IM token 失效。 - // 参考实现先构造 WS Cookie 头,再获取/刷新 Token。Token API 返回的 - // Set-Cookie 会更新后续轮次,但不回写本轮已经构造好的握手头。 - wsCookieStr := a.currentCookieStr() + // 每次新建 IM 连接前吸收数据库中的最新 Cookie。健康连接不会被续期任务 + // 主动打断;Cookie 变化只会使本次重连放弃旧 token 并重新派生。 + a.reloadCookieFromDB(ctx) token, cookieStr, err := a.acquireRuntimeToken(ctx) if err != nil { a.logger.Error("获取 token 失败", "err", err) @@ -409,22 +394,45 @@ func (a *Account) Run(parent context.Context) error { a.mu.Lock() deviceID := a.deviceID a.mu.Unlock() + credentialUnlock := func() {} + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + } + if !a.cookieSnapshotMatchesDB(ctx, cookieStr) { + credentialUnlock() + a.reloadCookieFromDB(ctx) + continue + } attemptStartedAt := time.Now() conn, err := a.wsDialer.Dial(ctx, ws.Config{ - CookieStr: wsCookieStr, + CookieStr: cookieStr, DeviceID: deviceID, AccessToken: token, Recorder: recorder, }, a.logger) + credentialUnlock() if err != nil { a.logger.Error("WS 连接失败", "err", err) + if ws.IsInvalidTokenError(err) && !invalidTokenRetried { + invalidTokenRetried = true + a.clearCurrentToken() + a.clearTokenCache(ctx) + a.setRuntimeState(RuntimeConnecting, "消息凭证被拒绝,正在重新获取一次新凭证") + continue + } + if ws.IsConnectLimitError(err) { + a.setRuntimeState(RuntimeReconnecting, "消息服务连接数受限,正在限速重试") + if sleepCtx(ctx, withRetryJitter(30*time.Second)) != nil { + return ctx.Err() + } + continue + } a.mu.Lock() a.connFailures++ - a.currentToken = "" failures := a.connFailures a.mu.Unlock() - if time.Since(attemptStartedAt) < 15*time.Second { - a.logger.Warn("连接建立阶段快速失败,清除 token 缓存", "duration", time.Since(attemptStartedAt).Round(time.Millisecond)) + if ws.IsInvalidTokenError(err) || ws.IsAuthenticationError(err) { + a.clearCurrentToken() a.clearTokenCache(ctx) } a.setRuntimeState(RuntimeReconnecting, "消息服务连接失败,稍后自动重试") @@ -451,25 +459,14 @@ func (a *Account) Run(parent context.Context) error { a.offlineSince = time.Time{} a.lastOfflineReason = "" a.mu.Unlock() - if !backgroundStarted { - backgroundStarted = true - backgroundWG.Add(2) - go func() { - defer backgroundWG.Done() - a.tokenRefreshLoop(ctx, nil) - }() - go func() { - defer backgroundWG.Done() - a.cookieRefreshLoop(ctx, nil) - }() - } + invalidTokenRetried = false a.setRuntimeState(RuntimeOnline, "消息服务连接正常") if shouldRecovered { a.alertEvent(ctx, EventAccountRecovered, AlertLevelInfo, "账号已恢复在线", fmt.Sprintf("账号 %s 已重新连接闲鱼消息服务。掉线开始时间:%s。", a.CookieID, formatTimeOrUnknown(offlineSince))) } - // 3) 心跳随连接重建;token/cookie 任务属于账号生命周期,网络重连时不取消。 + // 3) 健康连接只维持心跳和收包;token 只在下一次注册前更新。 hbCtx, hbCancel := context.WithCancel(ctx) var hbErr error hbDone := make(chan struct{}) @@ -612,11 +609,18 @@ func (a *Account) beginTask() (context.Context, bool) { // handleMaxFailures 连续失败达上限:尝试密码登录刷新;失败则返回 err 触发上层重启实例。 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.notifyOffline(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 != "" { a.replaceCookieStr(d.Value) + a.clearCurrentToken() + a.clearTokenCache(ctx) } a.logger.Info("密码登录刷新成功,重置失败计数") a.setRuntimeState(RuntimeConnecting, "登录凭证已刷新,正在重新连接") @@ -795,6 +799,7 @@ func (a *Account) adoptRecoveredCookie(ctx context.Context, newCookies, source s return false } a.replaceCookieStr(newCookies) + a.clearCurrentToken() if a.store != nil && a.store.Cookies != nil { if err := a.store.Cookies.UpdateValueExisting(ctx, a.CookieID, newCookies); err != nil { a.logger.Error(source+"后保存 cookie 失败", "cookie_id", a.CookieID, "err", err) @@ -912,21 +917,26 @@ func (a *Account) refreshToken(ctx context.Context) (string, string, error) { func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, string, error) { a.refreshMu.Lock() defer a.refreshMu.Unlock() + credentialUnlock := func() {} + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + } + defer credentialUnlock() + + // refreshMu serializes the complete token/Cookie update transaction for an + // account. A failed automatic verification also suppresses repeated token API + // calls until the caller-side cooldown expires. + if remaining := a.tokenCaptchaCooldownRemaining(); remaining > 0 { + a.setLastTokenStatus(tokenRefreshSkippedCooldown) + return "", "", fmt.Errorf("%w,剩余 %s", errTokenCaptchaCooldown, remaining.Round(time.Second)) + } - // 只有 acquireToken 已确认缓存未命中后,才读取数据库里的最新 Cookie。 a.reloadCookieFromDB(ctx) a.mu.Lock() cookieStr := a.CookieStr - lastMsg := a.lastMsgReceived a.lastTokenRefresh = time.Now() a.lastTokenStatus = tokenRefreshStarted - if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown { - a.lastTokenStatus = tokenRefreshSkippedCooldown - a.mu.Unlock() - a.logger.Info("收到消息冷却中,跳过 token/cookie 刷新", "cooldown", MessageCooldown) - return "", "", fmt.Errorf("收到消息冷却中,跳过 token/cookie 刷新") - } a.mu.Unlock() deviceID := strings.TrimSpace(a.deviceID) @@ -949,6 +959,7 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s // 它会清缓存后重新走一次标准 token 请求。 continue } + a.markTokenCaptchaFailure() a.setLastTokenStatus(tokenRefreshFailedCaptcha) a.clearCurrentToken() a.clearTokenCache(ctx) @@ -969,9 +980,10 @@ func (a *Account) refreshTokenWithMinGap(ctx context.Context, _ bool) (string, s a.clearTokenCache(ctx) return "", "", fmt.Errorf("token API 未返回结果") } - a.saveTokenCache(ctx, deviceID, res.AccessToken) + a.saveTokenCache(ctx, deviceID, res.AccessToken, res.AccessTokenExpireAt, cookieStr) a.mu.Lock() a.lastMsgReceived = time.Time{} + a.lastCaptchaFailure = time.Time{} a.tokenFetchFailures = 0 a.lastTokenStatus = tokenRefreshSuccess a.mu.Unlock() @@ -1030,6 +1042,26 @@ func (a *Account) tryTokenCaptchaRecovery(ctx context.Context, cookieStr, device return result, true } +func (a *Account) markTokenCaptchaFailure() { + a.mu.Lock() + a.lastCaptchaFailure = time.Now() + a.mu.Unlock() +} + +func (a *Account) tokenCaptchaCooldownRemaining() time.Duration { + a.mu.Lock() + lastFailure := a.lastCaptchaFailure + a.mu.Unlock() + if lastFailure.IsZero() { + return 0 + } + remaining := TokenCaptchaFailureCooldown - time.Since(lastFailure) + if remaining < 0 { + return 0 + } + return remaining +} + // acquireToken 取用于 WS /reg 的 accessToken:缓存命中且未过期则跳过 mtop(降低风控 // 与瞬时失败影响),否则调 refreshToken 重新派生并落库缓存。 // @@ -1107,9 +1139,14 @@ func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) { if err != nil { return "", false } - if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() { + a.mu.Lock() + cookieStr := a.CookieStr + a.mu.Unlock() + expectedFingerprint := credentialCookieFingerprint(cookieStr) + if tk.AccessToken == "" || tk.ExpireAt <= time.Now().Unix() || + tk.CookieFingerprint == "" || tk.CookieFingerprint != expectedFingerprint { // 参考实现发现过期缓存后立即删除整行,再进入标准 token 请求。 - if tk.ExpireAt <= time.Now().Unix() { + if tk.AccessToken != "" { a.clearTokenCache(ctx) } return "", false @@ -1123,12 +1160,20 @@ func (a *Account) cachedTokenIfFresh(ctx context.Context) (string, bool) { return tk.AccessToken, true } -// saveTokenCache 把 accessToken + device_id 缓存到 DB(expire_at = now + tokenCacheTTL)。 -func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string) { +// saveTokenCache uses the expiry returned by the token API. A response without +// a usable accessTokenExpiredTime remains valid for the current process only; +// it is deliberately not assigned a guessed multi-hour lifetime. +func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken string, serverExpireAt int64, cookieStr string) { if a.store == nil || a.store.Tokens == nil || accessToken == "" { return } - if err := a.store.Tokens.Save(ctx, a.CookieID, deviceID, accessToken, time.Now().Add(tokenCacheTTL()).Unix()); err != nil { + expireAt := effectiveTokenExpireAt(serverExpireAt, time.Now()) + if expireAt == 0 { + a.logger.Warn("token API 未返回可用过期时间,本次 token 不持久化") + a.clearTokenCache(ctx) + return + } + if err := a.store.Tokens.SaveBound(ctx, a.CookieID, deviceID, accessToken, expireAt, credentialCookieFingerprint(cookieStr)); err != nil { a.logger.Warn("缓存 accessToken 失败", "err", err) } } @@ -1145,162 +1190,39 @@ func (a *Account) clearTokenCache(ctx context.Context) { // reloadCookieFromDB 复读 DB cookie:与内存不同则采纳,并清 token 缓存(新 cookie 对应 // 新 session,旧 token 作废)。让运行中账号吸收外部更新(人工重新扫码 / refreshAccountProfile)。 -func (a *Account) reloadCookieFromDB(ctx context.Context) { +func (a *Account) reloadCookieFromDB(ctx context.Context) bool { if a.store == nil || a.store.Cookies == nil { - return + return false } d, err := a.store.Cookies.GetDetails(ctx, a.CookieID) if err != nil || d == nil || d.Value == "" { - return + return false } a.mu.Lock() cur := a.CookieStr a.mu.Unlock() - if d.Value == cur { - return + if credentialCookieFingerprint(d.Value) == credentialCookieFingerprint(cur) { + return false } a.logger.Info("检测到 DB cookie 已更新,重新加载", "account", a.CookieID) a.replaceCookieStr(d.Value) + a.clearCurrentToken() a.clearTokenCache(ctx) -} - -func (a *Account) activeConnection(fallback WSConn) WSConn { - if fallback != nil { - return fallback - } a.mu.Lock() - defer a.mu.Unlock() - return a.conn + a.lastCaptchaFailure = time.Time{} + a.mu.Unlock() + return true } -// tokenRefreshLoop 在 WS 在线期间按 TokenRefreshInterval 定时刷新 token。 -// 刷新失败不重连(让心跳/接收循环去判定),仅记录日志;session 过期会触发 -// 接收循环断开,主循环再走 handleMaxFailures 兜底。 -func (a *Account) tokenRefreshLoop(ctx context.Context, conn WSConn) { - ticker := time.NewTicker(TokenRefreshInterval) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - return - case <-ticker.C: - } - if ctx.Err() != nil { - return - } - token, _, err := a.refreshToken(ctx) - if err != nil { - a.logger.Warn("定时刷新 token 失败", "err", err) - if mtop.IsSessionExpiredErr(err) { - // session 失效:清缓存,让接收循环尽快断开走兜底,主动关闭连接。 - a.mu.Lock() - a.currentToken = "" - a.mu.Unlock() - a.clearTokenCache(ctx) - if currentConn := a.activeConnection(conn); currentConn != nil { - _ = currentConn.Close() - } - } - continue - } - a.applyOnlineToken(a.activeConnection(conn), token, false) - a.logger.Info("定时刷新 token 成功") - } -} - -// cookieRefreshLoop 与参考实现保持一致:每 60 秒检查一次,满 180 秒检查登录 -// 凭证;收到消息后 5 分钟内跳过;失败 5 秒后只重试一次。检查优先命中 -// 5-10 小时 token 缓存,不会每 180 秒请求 mtop。 -func (a *Account) cookieRefreshLoop(ctx context.Context, conn WSConn) { - for { - if ctx.Err() != nil { - return - } - a.mu.Lock() - lastRefresh := a.lastCookieRefresh - lastMsg := a.lastMsgReceived - a.mu.Unlock() - if time.Since(lastRefresh) >= CookieRefreshInterval { - if !lastMsg.IsZero() && time.Since(lastMsg) < MessageCooldown { - a.logger.Info("收到消息冷却中,跳过在线 cookie 刷新", "cooldown", MessageCooldown) - } else if !a.runOnlineCookieRefresh(ctx, conn, 5*time.Second) { - return - } - } - // 参考实现每轮处理完成后再等待 60 秒,而不是启动后先等待。 - if sleepCtx(ctx, CookieRefreshCheckInterval) != nil { - return - } - } -} - -// runOnlineCookieRefresh 完成参考实现的一轮在线检查。第一次失败后只在 5 秒后 -// 重试一次;第二次仍失败也推进 lastCookieRefresh,防止之后每 60 秒重复触发。 -// 返回 false 仅表示 context 已取消,调用方应退出循环。 -func (a *Account) runOnlineCookieRefresh(ctx context.Context, conn WSConn, retryDelay time.Duration) bool { - defer func() { - a.mu.Lock() - a.lastMsgReceived = time.Time{} - a.mu.Unlock() - }() - if a.refreshOnlineCookie(ctx, conn, true) { +func (a *Account) cookieSnapshotMatchesDB(ctx context.Context, cookieStr string) bool { + if a.store == nil || a.store.Cookies == nil { return true } - if sleepCtx(ctx, retryDelay) != nil { - return false - } - if !a.refreshOnlineCookie(ctx, conn, false) { - a.mu.Lock() - a.lastCookieRefresh = time.Now() - a.mu.Unlock() - } - return true -} - -func (a *Account) refreshOnlineCookie(ctx context.Context, conn WSConn, enforceMinGap bool) bool { - // 参考实现的 refresh_token 会先查 5-10 小时缓存;这里必须走 acquireToken, - // 不能直接 refreshToken,否则 180 秒检查会退化为 180 秒一次 mtop 请求。 - token, _, err := a.acquireTokenWithMinGap(ctx, enforceMinGap) - if err != nil { - a.logger.Warn("在线 cookie 刷新失败", "err", err) - if mtop.IsSessionExpiredErr(err) { - a.mu.Lock() - a.currentToken = "" - a.mu.Unlock() - a.clearTokenCache(ctx) - if currentConn := a.activeConnection(conn); currentConn != nil { - _ = currentConn.Close() - } - } - return false - } - a.applyOnlineToken(a.activeConnection(conn), token, true) - a.logger.Info("在线 cookie 刷新成功") - return true -} - -// applyOnlineToken 把刷新后的 token 应用到当前 WS。在线刷新 goroutine 会在 -// Run 清理 a.conn 之前退出,因此连接仍存在且状态仍是本轮风控恢复提示时,可以 -// 安全恢复为 online;这不改变 token 获取、续期或重试时序。 -func (a *Account) applyOnlineToken(conn WSConn, token string, markCookieRefresh bool) { - a.mu.Lock() - a.currentToken = token - if markCookieRefresh { - a.lastCookieRefresh = time.Now() - } - a.mu.Unlock() - - if conn != nil { - conn.SetAccessToken(token) - } - - a.mu.Lock() - defer a.mu.Unlock() - if a.conn != nil && a.runtimeState == RuntimeConnecting && a.runtimeMessage == tokenRiskRecoveryMessage { - a.runtimeState = RuntimeOnline - a.runtimeMessage = "消息服务连接正常" - a.runtimeUpdatedAt = time.Now() + current, err := a.store.Cookies.GetValue(ctx, a.CookieID) + if err != nil || strings.TrimSpace(current) == "" { + return true } + return credentialCookieFingerprint(current) == credentialCookieFingerprint(cookieStr) } // RuntimeStatus 返回账号当前连接状态的线程安全快照。 @@ -1405,5 +1327,28 @@ func (a *Account) UpdateCookie(cookieStr string) { if strings.TrimSpace(cookieStr) == "" { return } + a.refreshMu.Lock() + defer a.refreshMu.Unlock() + credentialUnlock := func() {} + if a.store != nil { + credentialUnlock = a.store.LockAccountCredentials(a.CookieID) + } + defer credentialUnlock() + a.mu.Lock() + changed := cookieStr != a.CookieStr + a.mu.Unlock() + if !changed { + return + } + if a.store != nil && a.store.Cookies != nil { + if err := a.store.Cookies.UpdateValueExisting(context.Background(), a.CookieID, cookieStr); err != nil { + a.logger.Warn("同步外部 Cookie 到数据库失败", "err", err) + } + } a.replaceCookieStr(cookieStr) + // Updating credentials does not close a healthy connection. Clearing the + // in-memory and persisted token makes the next reconnect authenticate from + // this Cookie snapshot instead of reusing a token issued for the old one. + a.clearCurrentToken() + a.clearTokenCache(context.Background()) } diff --git a/internal/engine/account_extra_test.go b/internal/engine/account_extra_test.go index a481446..f07a485 100644 --- a/internal/engine/account_extra_test.go +++ b/internal/engine/account_extra_test.go @@ -22,7 +22,7 @@ type riskCountingMTop struct { func (m *riskCountingMTop) RefreshTokenWithDeviceIDContext(context.Context, string, string) (*mtop.RefreshResult, error) { m.calls++ if m.calls > 1 { - return &mtop.RefreshResult{AccessToken: "standard-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, nil + return &mtop.RefreshResult{AccessToken: "standard-token", AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(), UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, nil } return nil, &mtop.RiskVerificationError{Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example"} } @@ -33,6 +33,16 @@ func (h *tokenRecoveredHandler) OnTokenCaptchaVerification(context.Context, stri return &mtop.RefreshResult{AccessToken: "recovered-token", UpdatedCookies: "unb=123; _m_h5_tk=recovered;"}, true } +type rejectingTokenCaptchaHandler struct { + recordingHandler + calls int +} + +func (h *rejectingTokenCaptchaHandler) OnTokenCaptchaVerification(context.Context, string, string, string, string) (*mtop.RefreshResult, bool) { + h.calls++ + return nil, false +} + type capturingCaptchaHandler struct { recordingHandler cookieStr string @@ -70,7 +80,7 @@ func (m *responseCookieRiskMTop) RefreshTokenWithDeviceIDContext(_ context.Conte Ret: []string{"FAIL_SYS_USER_VALIDATE"}, VerificationURL: "https://verify.example/punish", } } - return &mtop.RefreshResult{AccessToken: "standard-after-captcha", UpdatedCookies: cookieStr}, nil + return &mtop.RefreshResult{AccessToken: "standard-after-captcha", AccessTokenExpireAt: time.Now().Add(time.Hour).Unix(), UpdatedCookies: cookieStr}, nil } func TestRefreshTokenRetriesStandardRequestAfterCaptchaRecovery(t *testing.T) { @@ -93,6 +103,25 @@ func TestRefreshTokenRetriesStandardRequestAfterCaptchaRecovery(t *testing.T) { } } +func TestRefreshTokenCaptchaFailureEntersCallerCooldown(t *testing.T) { + acc, _, _, cleanup := newAccountForTest(t) + defer cleanup() + client := &riskCountingMTop{} + handler := &rejectingTokenCaptchaHandler{} + acc.mtop = client + acc.handler = handler + + if _, _, err := acc.refreshToken(context.Background()); !mtop.IsRiskVerificationErr(err) { + t.Fatalf("first refresh error=%v want risk verification", err) + } + if _, _, err := acc.refreshToken(context.Background()); !errors.Is(err, errTokenCaptchaCooldown) { + t.Fatalf("second refresh error=%v want cooldown", err) + } + if client.calls != 1 || handler.calls != 1 { + t.Fatalf("cooldown must suppress repeated API/solver calls: api=%d solver=%d", client.calls, handler.calls) + } +} + func TestRefreshTokenPersistsResponseCookiesBeforeCaptchaRecovery(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, &responseCookieRiskMTop{}) defer cleanup() diff --git a/internal/engine/keepalive_test.go b/internal/engine/keepalive_test.go index 8fcc8e0..f508cd7 100644 --- a/internal/engine/keepalive_test.go +++ b/internal/engine/keepalive_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" ) @@ -19,7 +20,7 @@ type countingMtop struct { func (c *countingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) { atomic.AddInt32(&c.calls, 1) - return &mtop.RefreshResult{AccessToken: c.token}, nil + return &mtop.RefreshResult{AccessToken: c.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil } type statusMtop struct { @@ -39,170 +40,12 @@ func (c *failingCountingMtop) RefreshTokenWithDeviceIDContext(_ context.Context, return nil, c.err } -func TestRiskSensitiveRefreshIntervals(t *testing.T) { - if CookieRefreshInterval != 180*time.Second { - t.Fatalf("在线 Cookie 检查间隔应与参考实现保持 180 秒,got %s", CookieRefreshInterval) - } - if CookieRefreshCheckInterval != time.Minute { - t.Fatalf("在线 Cookie 循环检查频率应与参考实现保持 60 秒,got %s", CookieRefreshCheckInterval) - } - if PasswordLoginMinGap != 60*time.Second { - t.Fatalf("自动密码登录冷却应与参考运行时保持 60 秒,got %s", PasswordLoginMinGap) - } -} - -func TestRefreshOnlineCookie_CacheHitSkipsMtop(t *testing.T) { - mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}} - acc, _, store, cleanup := newRunAccount(t, mtopClient) - defer cleanup() - - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok", - time.Now().Add(time.Hour).Unix()); err != nil { +func saveBoundToken(t *testing.T, store *db.Store, acc *Account, token string, expireAt int64) { + t.Helper() + if err := store.Tokens.SaveBound(context.Background(), acc.CookieID, acc.deviceID, token, expireAt, + credentialCookieFingerprint(acc.currentCookieStr())); err != nil { t.Fatal(err) } - conn := &fakeWSConn{} - if !acc.refreshOnlineCookie(context.Background(), conn, true) { - t.Fatal("缓存命中时在线 Cookie 检查应成功") - } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 { - t.Fatalf("180 秒检查命中缓存时不应请求 mtop,got %d", calls) - } - acc.mu.Lock() - currentToken := acc.currentToken - lastRefresh := acc.lastCookieRefresh - acc.mu.Unlock() - if currentToken != "cached-tok" || lastRefresh.IsZero() { - t.Fatalf("应采用缓存 token 并更新时间,token=%q last_refresh=%s", currentToken, lastRefresh) - } -} - -func TestCookieRefreshLoopRunsInitialCacheCheckImmediately(t *testing.T) { - mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-mtop"}} - acc, _, store, cleanup := newRunAccount(t, mtopClient) - defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } - acc.mu.Lock() - acc.lastCookieRefresh = time.Time{} - acc.lastMsgReceived = time.Now().Add(-MessageCooldown - time.Second) - acc.mu.Unlock() - - ctx, cancel := context.WithCancel(context.Background()) - done := make(chan struct{}) - go func() { - defer close(done) - acc.cookieRefreshLoop(ctx, nil) - }() - deadline := time.Now().Add(time.Second) - for time.Now().Before(deadline) { - acc.mu.Lock() - lastRefresh := acc.lastCookieRefresh - lastMessage := acc.lastMsgReceived - acc.mu.Unlock() - if !lastRefresh.IsZero() { - if !lastMessage.IsZero() { - t.Fatalf("刷新轮次结束后应清空消息冷却标识: %s", lastMessage) - } - break - } - time.Sleep(5 * time.Millisecond) - } - cancel() - <-done - acc.mu.Lock() - lastRefresh := acc.lastCookieRefresh - acc.mu.Unlock() - if lastRefresh.IsZero() { - t.Fatal("Cookie 刷新循环启动后应立即完成首次缓存检查") - } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 { - t.Fatalf("首次检查命中缓存时不应请求 mtop, got %d", calls) - } -} - -func TestRefreshOnlineCookie_RiskRecoveryRestoresOnlineRuntimeState(t *testing.T) { - mtopClient := &riskCountingMTop{} - acc, _, _, cleanup := newRunAccount(t, mtopClient) - defer cleanup() - acc.handler = &tokenRecoveredHandler{} - conn := &fakeWSConn{} - acc.mu.Lock() - acc.conn = conn - acc.runtimeState = RuntimeOnline - acc.runtimeMessage = "消息服务连接正常" - acc.runtimeUpdatedAt = time.Now() - acc.mu.Unlock() - - if !acc.refreshOnlineCookie(context.Background(), conn, true) { - t.Fatal("风控自动恢复成功后在线 Cookie 刷新应成功") - } - status := acc.RuntimeStatus() - if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" { - t.Fatalf("在线风控恢复后运行态未收敛: %+v", status) - } - conn.mu.Lock() - defer conn.mu.Unlock() - if len(conn.tokens) != 1 || conn.tokens[0] != "standard-token" { - t.Fatalf("恢复 token 未更新到现有连接: %+v", conn.tokens) - } -} - -func TestApplyOnlineToken_PeriodicRefreshRestoresRuntimeWithoutChangingCookieSchedule(t *testing.T) { - acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "unused"}) - defer cleanup() - conn := &fakeWSConn{} - acc.mu.Lock() - acc.conn = conn - acc.runtimeState = RuntimeConnecting - acc.runtimeMessage = tokenRiskRecoveryMessage - acc.lastCookieRefresh = time.Time{} - acc.mu.Unlock() - - acc.applyOnlineToken(conn, "periodic-token", false) - - status := acc.RuntimeStatus() - if status.State != RuntimeOnline || !status.Connected || status.Message != "消息服务连接正常" { - t.Fatalf("定时 token 风控恢复后运行态未收敛: %+v", status) - } - acc.mu.Lock() - lastCookieRefresh := acc.lastCookieRefresh - acc.mu.Unlock() - if !lastCookieRefresh.IsZero() { - t.Fatalf("定时 token 刷新不应改变 180 秒 Cookie 检查时间: %s", lastCookieRefresh) - } - conn.mu.Lock() - defer conn.mu.Unlock() - if len(conn.tokens) != 1 || conn.tokens[0] != "periodic-token" { - t.Fatalf("定时刷新 token 未更新到现有连接: %+v", conn.tokens) - } -} - -func TestRunOnlineCookieRefresh_RetriesOnceAndPacesFailure(t *testing.T) { - mtopClient := &failingCountingMtop{ - fakeRunMtop: fakeRunMtop{token: "unused"}, - err: errors.New("temporary token failure"), - } - acc, _, _, cleanup := newRunAccount(t, mtopClient) - defer cleanup() - - started := time.Now() - if !acc.runOnlineCookieRefresh(context.Background(), &fakeWSConn{}, 0) { - t.Fatal("未取消的刷新轮次不应要求退出") - } - if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 { - t.Fatalf("失败后应且只应重试一次,got %d calls", calls) - } - if elapsed := time.Since(started); elapsed >= time.Second { - t.Fatalf("参考实现没有额外一分钟防抖,零延迟测试不应阻塞,elapsed=%s", elapsed) - } - acc.mu.Lock() - lastRefresh := acc.lastCookieRefresh - acc.mu.Unlock() - if lastRefresh.Before(started) { - t.Fatalf("第二次失败后必须重新开始 180 秒计时,last_refresh=%s started=%s", lastRefresh, started) - } } func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing.T) { @@ -212,10 +55,7 @@ func TestRefreshTokenNetworkFailureClearsMemoryButPreservesFreshCache(t *testing } acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix()) acc.mu.Lock() acc.currentToken = "old-memory-token" acc.mu.Unlock() @@ -240,10 +80,7 @@ func TestRefreshTokenBusinessFailureClearsMemoryAndCache(t *testing.T) { } acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix()) acc.mu.Lock() acc.currentToken = "old-memory-token" acc.mu.Unlock() @@ -268,10 +105,7 @@ func TestAcquireTokenDeletesExpiredCacheBeforeNetworkAttempt(t *testing.T) { } acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "expired-tok", - time.Now().Add(-time.Minute).Unix()); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "expired-tok", time.Now().Add(-time.Minute).Unix()) if _, _, err := acc.acquireToken(context.Background()); err == nil { t.Fatal("后续网络请求失败应返回错误") } @@ -290,13 +124,7 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "cached-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } - if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", "unb=123; _m_h5_tk=db-new;"); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "cached-tok", time.Now().Add(time.Hour).Unix()) token, cookies, err := acc.acquireToken(context.Background()) if err != nil { t.Fatalf("acquireToken: %v", err) @@ -307,8 +135,28 @@ func TestAcquireToken_CacheHitSkipsMtop(t *testing.T) { if calls := atomic.LoadInt32(&mtopClient.calls); calls != 0 { t.Fatalf("缓存命中不应调用 mtop,got %d", calls) } - if strings.Contains(cookies, "db-new") { - t.Fatalf("缓存命中时不应提前重载 DB Cookie: %q", cookies) + if !strings.Contains(cookies, "_m_h5_tk=tk_1") { + t.Fatalf("缓存命中应返回其绑定的 Cookie: %q", cookies) + } +} + +func TestAcquireToken_RejectsCacheBoundToDifferentCookie(t *testing.T) { + mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}} + acc, _, store, cleanup := newRunAccount(t, mtopClient) + defer cleanup() + saveBoundToken(t, store, acc, "stale-token", time.Now().Add(time.Hour).Unix()) + newCookie := "unb=123; _m_h5_tk=renewed_2; cookie2=new" + if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil { + t.Fatal(err) + } + acc.replaceCookieStr(newCookie) + + token, _, err := acc.acquireToken(context.Background()) + if err != nil { + t.Fatal(err) + } + if token != "fresh-token" || atomic.LoadInt32(&mtopClient.calls) != 1 { + t.Fatalf("token=%q calls=%d want fresh token", token, atomic.LoadInt32(&mtopClient.calls)) } } @@ -370,10 +218,7 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, mtopClient) defer cleanup() - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix()) res := acc.tryLoginStatusCheck(context.Background()) if !res.recovered || res.riskRequired { t.Fatalf("登录态检查应恢复 Cookie,got %+v", res) @@ -421,10 +266,7 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"}) defer cleanup() // 预置旧 session 的 token 缓存。 - if err := store.Tokens.Save(context.Background(), "cid", acc.deviceID, "old-tok", - time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatal(err) - } + saveBoundToken(t, store, acc, "old-tok", time.Now().Add(time.Hour).Unix()) // 外部更新 DB cookie(模拟重新扫码),userID=0 复用现有 user_id。 newCookie := "unb=123; _m_h5_tk=newtk_2; sgcookie=abc" if err := store.Cookies.Save(context.Background(), "cid", newCookie, 0); err != nil { diff --git a/internal/engine/run_test.go b/internal/engine/run_test.go index 2ee44d8..18c06bc 100644 --- a/internal/engine/run_test.go +++ b/internal/engine/run_test.go @@ -34,7 +34,7 @@ func (f *fakeRunMtop) PublishItem(context.Context, string, mtop.PublishItemReque return nil, nil } func (f *fakeRunMtop) RefreshTokenWithDeviceIDContext(_ context.Context, _ string, _ string) (*mtop.RefreshResult, error) { - return &mtop.RefreshResult{AccessToken: f.token}, nil + return &mtop.RefreshResult{AccessToken: f.token, AccessTokenExpireAt: time.Now().Add(time.Hour).Unix()}, nil } type fakeFailTokenMtop struct{ err error } @@ -62,7 +62,6 @@ func (f *fakeFailTokenMtop) RefreshTokenWithDeviceIDContext(context.Context, str type fakeWSConn struct { mu sync.Mutex closed bool - tokens []string sentTexts []string sentImages []string heartbeatDone chan struct{} @@ -99,12 +98,6 @@ func (f *fakeWSConn) Close() error { return nil } -func (f *fakeWSConn) SetAccessToken(token string) { - f.mu.Lock() - f.tokens = append(f.tokens, token) - f.mu.Unlock() -} - func (f *fakeWSConn) SendText(_ context.Context, _, _, _, text string) error { f.mu.Lock() f.sentTexts = append(f.sentTexts, text) @@ -125,6 +118,7 @@ type fakeDialer struct { results []dialResult // 每次.Dial 的结果 calls int conns []*fakeWSConn + configs []ws.Config lastCfg ws.Config // 记录最后一次 Dial 的配置(含 AccessToken) } @@ -137,6 +131,7 @@ func (d *fakeDialer) Dial(_ context.Context, cfg ws.Config, _ *slog.Logger) (WSC d.mu.Lock() defer d.mu.Unlock() d.lastCfg = cfg + d.configs = append(d.configs, cfg) idx := d.calls d.calls++ if idx >= len(d.results) { @@ -366,6 +361,83 @@ func TestRun_EstablishedNetworkErrorPreservesTokenAndCache(t *testing.T) { } } +func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) { + mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}} + acc, _, _, cleanup := newRunAccount(t, mtopClient) + defer cleanup() + dialer := &fakeDialer{results: []dialResult{ + {err: &ws.RegError{Kind: ws.RegErrorInvalidToken, Code: 401, Reason: "invalid token"}}, + {conn: &fakeWSConn{recvBlock: true}}, + }} + acc.wsDialer = dialer + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- acc.Run(ctx) }() + waitForDialCalls(t, dialer, 2) + cancel() + <-done + + if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 { + t.Fatalf("invalid /reg should fetch exactly one fresh token immediately, calls=%d", calls) + } +} + +func TestRun_ReloadsDatabaseCookieBeforeNaturalReconnect(t *testing.T) { + mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "token"}} + acc, _, store, cleanup := newRunAccount(t, mtopClient) + defer cleanup() + newCookie := "unb=123; _m_h5_tk=db-renewed_2; cookie2=new" + first := &fakeWSConn{recvBlock: false, onReceive: func(func(map[string]any)) { + if err := store.Cookies.UpdateValueExisting(context.Background(), "cid", newCookie); err != nil { + t.Errorf("update Cookie: %v", err) + } + }} + dialer := &fakeDialer{results: []dialResult{ + {conn: first}, + {conn: &fakeWSConn{recvBlock: true}}, + }} + acc.wsDialer = dialer + + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- acc.Run(ctx) }() + waitForDialCalls(t, dialer, 2) + cancel() + <-done + + dialer.mu.Lock() + configs := append([]ws.Config(nil), dialer.configs...) + dialer.mu.Unlock() + if len(configs) < 2 { + t.Fatalf("dial configs=%d want>=2", len(configs)) + } + if configs[1].CookieStr != newCookie { + t.Fatalf("second dial Cookie=%q want=%q", configs[1].CookieStr, newCookie) + } + if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 { + t.Fatalf("Cookie change should invalidate token for reconnect, calls=%d", calls) + } +} + +func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + dialer.mu.Lock() + calls := dialer.calls + dialer.mu.Unlock() + if calls >= want { + return + } + time.Sleep(10 * time.Millisecond) + } + dialer.mu.Lock() + calls := dialer.calls + dialer.mu.Unlock() + t.Fatalf("dial calls=%d want>=%d", calls, want) +} + // TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。 func TestRun_DisabledAccountExits(t *testing.T) { acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"}) diff --git a/internal/engine/token_cache.go b/internal/engine/token_cache.go index 9fc9cc0..9bf170f 100644 --- a/internal/engine/token_cache.go +++ b/internal/engine/token_cache.go @@ -1,45 +1,43 @@ package engine import ( - "crypto/rand" - "math/big" - "os" - "strconv" + "crypto/sha256" + "encoding/hex" + "sort" "strings" "time" + + "xianyu-go/internal/xianyu/protocol" ) -const tokenCacheTTLGranularity = time.Second +const tokenExpirySafetyMargin = time.Minute -func tokenCacheTTL() time.Duration { - minTTL, minOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MIN_HOURS", TokenCacheTTLMin) - maxTTL, maxOK := tokenCacheTTLEnv("TOKEN_CACHE_TTL_MAX_HOURS", TokenCacheTTLMax) - if !minOK || !maxOK || minTTL > maxTTL { - minTTL = TokenCacheTTLMin - maxTTL = TokenCacheTTLMax +func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 { + ttl := time.Unix(serverExpireAt, 0).Sub(now) + if ttl <= 0 { + return 0 } - if maxTTL == minTTL { - return minTTL + margin := tokenExpirySafetyMargin + if ttl <= 2*margin { + margin = ttl / 10 } - steps := int64((maxTTL - minTTL) / tokenCacheTTLGranularity) - if steps <= 0 { - return minTTL - } - n, err := rand.Int(rand.Reader, big.NewInt(steps+1)) - if err != nil { - return minTTL - } - return minTTL + time.Duration(n.Int64())*tokenCacheTTLGranularity + return now.Add(ttl - margin).Unix() } -func tokenCacheTTLEnv(key string, fallback time.Duration) (time.Duration, bool) { - raw := strings.TrimSpace(os.Getenv(key)) - if raw == "" { - return fallback, true +func credentialCookieFingerprint(cookieStr string) string { + cookies := protocol.TransCookies(cookieStr) + keys := make([]string, 0, len(cookies)) + for key := range cookies { + keys = append(keys, key) } - hours, err := strconv.ParseFloat(raw, 64) - if err != nil || hours <= 0 { - return fallback, false + sort.Strings(keys) + var canonical strings.Builder + for _, key := range keys { + canonical.WriteString(key) + canonical.WriteByte(0) + canonical.WriteString(cookies[key]) + canonical.WriteByte(0) } - return time.Duration(hours * float64(time.Hour)), true + sum := sha256.Sum256([]byte(canonical.String())) + return hex.EncodeToString(sum[:]) } diff --git a/internal/engine/token_cache_test.go b/internal/engine/token_cache_test.go index 25bd568..1a29797 100644 --- a/internal/engine/token_cache_test.go +++ b/internal/engine/token_cache_test.go @@ -5,37 +5,31 @@ import ( "time" ) -func TestTokenCacheTTLFixedEnv(t *testing.T) { - t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2") - t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2") - if got := tokenCacheTTL(); got != 2*time.Hour { - t.Fatalf("tokenCacheTTL=%s want 2h", got) +func TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + got := effectiveTokenExpireAt(now.Add(2*time.Hour).Unix(), now) + want := now.Add(2*time.Hour - tokenExpirySafetyMargin).Unix() + if got != want { + t.Fatalf("effective expiry=%d want=%d", got, want) } } -func TestTokenCacheTTLMaxBelowMinFallsBackToDefaultRange(t *testing.T) { - t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "4") - t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "2") - got := tokenCacheTTL() - if got < TokenCacheTTLMin || got > TokenCacheTTLMax { - t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax) +func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + for _, expireAt := range []int64{0, now.Add(-time.Second).Unix()} { + if got := effectiveTokenExpireAt(expireAt, now); got != 0 { + t.Fatalf("effective expiry=%d want=0 for server expiry %d", got, expireAt) + } } } -func TestTokenCacheTTLInvalidEnvFallsBackToDefaultRange(t *testing.T) { - t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "bad") - t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "also-bad") - got := tokenCacheTTL() - if got < TokenCacheTTLMin || got > TokenCacheTTLMax { - t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax) +func TestCredentialCookieFingerprintIsOrderIndependent(t *testing.T) { + left := credentialCookieFingerprint("unb=1; cookie2=abc; _m_h5_tk=tk_1") + right := credentialCookieFingerprint("_m_h5_tk=tk_1; unb=1; cookie2=abc") + if left == "" || left != right { + t.Fatalf("fingerprints differ: %q != %q", left, right) } -} - -func TestTokenCacheTTLPartiallyInvalidEnvFallsBackToDefaultRange(t *testing.T) { - t.Setenv("TOKEN_CACHE_TTL_MIN_HOURS", "2") - t.Setenv("TOKEN_CACHE_TTL_MAX_HOURS", "bad") - got := tokenCacheTTL() - if got < TokenCacheTTLMin || got > TokenCacheTTLMax { - t.Fatalf("tokenCacheTTL=%s want within [%s,%s]", got, TokenCacheTTLMin, TokenCacheTTLMax) + if left == credentialCookieFingerprint("unb=1; cookie2=changed; _m_h5_tk=tk_1") { + t.Fatal("credential change must alter fingerprint") } } diff --git a/internal/renewal/scheduler.go b/internal/renewal/scheduler.go index e9725be..e2601bb 100644 --- a/internal/renewal/scheduler.go +++ b/internal/renewal/scheduler.go @@ -147,6 +147,9 @@ func (s *Scheduler) executeLoginRenew(ctx context.Context) { } func (s *Scheduler) loginRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) { + credentialUnlock := s.store.LockAccountCredentials(account.ID) + defer credentialUnlock() + account = s.reloadRenewalAccount(ctx, account) started := time.Now() runCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() @@ -191,6 +194,9 @@ func (s *Scheduler) executeAPICookieRenew(ctx context.Context) { } func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, account db.RenewalAccount) { + credentialUnlock := s.store.LockAccountCredentials(account.ID) + defer credentialUnlock() + account = s.reloadRenewalAccount(ctx, account) started := time.Now() res, err := s.renewAPI(ctx, account.Value) if err != nil { @@ -281,6 +287,9 @@ func (s *Scheduler) executeBrowserCookieRefresh(ctx context.Context) { } func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string, account db.RenewalAccount, schedule db.CookieRefreshSchedule) { + credentialUnlock := s.store.LockAccountCredentials(account.ID) + defer credentialUnlock() + account = s.reloadRenewalAccount(ctx, account) started := time.Now() if s.browser == nil { schedule.LastStatus = "failed" @@ -347,6 +356,20 @@ func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.R return s.api.RenewAPIFirst(runCtx, cookieStr) } +func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) db.RenewalAccount { + detail, err := s.store.Cookies.GetDetails(ctx, account.ID) + if err != nil || detail == nil { + return account + } + account.Value = detail.Value + account.Username = detail.Username + account.Password = detail.Password + account.ShowBrowser = detail.ShowBrowser + account.MetadataJSON = detail.MetadataJSON + account.LastRefreshAt = detail.LastRefreshAt + return account +} + func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool { if err := s.store.Cookies.UpdateRenewalCookie(ctx, cookieID, cookieStr, metadata, time.Now().Unix()); err != nil { s.logger.Warn("保存续期 Cookie 失败", "account", cookieID, "err", err) @@ -392,13 +415,6 @@ func (s *Scheduler) isSessionCooled(cookieID string) bool { return ok } -func (s *Scheduler) triggerPasswordLoginAsync(cookieID string) { - if s.refresher == nil { - return - } - go s.refresher.OnPasswordLoginRefresh(context.Background(), cookieID) -} - 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 { @@ -486,15 +502,6 @@ func newBatchID() string { return hex.EncodeToString(b[:]) } -func firstNonEmpty(values ...string) string { - for _, value := range values { - if strings.TrimSpace(value) != "" { - return value - } - } - return "" -} - func sleepCtx(ctx context.Context, d time.Duration) error { if d <= 0 { return nil diff --git a/internal/renewal/scheduler_test.go b/internal/renewal/scheduler_test.go index 86d6f83..0b73781 100644 --- a/internal/renewal/scheduler_test.go +++ b/internal/renewal/scheduler_test.go @@ -6,6 +6,7 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "strconv" "strings" "sync/atomic" "testing" @@ -58,32 +59,13 @@ func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ st type schedulerFakePasswordRefresher struct { calls atomic.Int32 - ch chan string } -func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, cookieID string) bool { +func (f *schedulerFakePasswordRefresher) OnPasswordLoginRefresh(_ context.Context, _ string) bool { f.calls.Add(1) - if f.ch != nil { - select { - case f.ch <- cookieID: - default: - } - } return true } -func (f *schedulerFakePasswordRefresher) waitCookie(t *testing.T, want string) { - t.Helper() - select { - case got := <-f.ch: - if got != want { - t.Fatalf("password refresher cookieID=%q want %q", got, want) - } - case <-time.After(time.Second): - t.Fatalf("password refresher 未触发") - } -} - type apiRenewLogSnapshot struct { status string message string @@ -225,35 +207,10 @@ func TestBrowserCookieRefreshSkipsManuallyDisabledAccount(t *testing.T) { } func TestNewSchedulerTreatsTypedNilBrowserAsDisabled(t *testing.T) { - store, cleanup := newSchedulerTestStore(t) - defer cleanup() - ctx := context.Background() - account := createSchedulerAccount(t, store, "cid-typed-nil-browser", "unb=1; cookie2=c2") - refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)} - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/hasLogin.do", "/silentHasLogin.do", "/setLoginSettings.do": - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - var typedNilBrowser *schedulerFakeBrowser - s := NewScheduler(store, nil, typedNilBrowser, refresher, nil) - if s.browser != nil { + if got := browserRenewerOrNil(typedNilBrowser); got != nil { t.Fatal("typed nil BrowserRenewer 应被规范化为 nil") } - s.api = schedulerRenewServiceFromServer(srv) - s.cooldown = NewCooldownManager() - - s.apiCookieRenewOne(ctx, "batch-typed-nil-browser", account) - refresher.waitCookie(t, "cid-typed-nil-browser") - log := lastAPIRenewLog(t, store, "cid-typed-nil-browser") - if log.status != "need_password_login" || !strings.Contains(log.errorMessage, "浏览器自动化未启用") { - t.Fatalf("typed nil browser 应按浏览器禁用处理: %+v", log) - } } func TestSchedulerSettingEnabledOverrides(t *testing.T) { @@ -372,169 +329,54 @@ func TestRenewalCleanupLogsUsesRetentionDays(t *testing.T) { } } -func TestAPICookieRenewOneSavesPartialCookiesBeforePasswordLogin(t *testing.T) { +func TestAPICookieRenewOneSkipsExpiredLongLoginWithoutEscalation(t *testing.T) { store, cleanup := newSchedulerTestStore(t) defer cleanup() ctx := context.Background() - account := createSchedulerAccount(t, store, "cid-partial", "unb=1; cookie2=c2") - refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)} - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/hasLogin.do": - http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"}) - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - case "/silentHasLogin.do": - http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"}) - _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-partial"}`)) - case "/setLoginSettings.do": - _, _ = w.Write([]byte(`{"content":{"success":false}}`)) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() + account := createSchedulerAccount(t, store, "cid-expired", "unb=1; cookie2=c2") + browser := &schedulerFakeBrowser{} + refresher := &schedulerFakePasswordRefresher{} + s := NewScheduler(store, nil, browser, refresher, nil) + s.apiCookieRenewOne(ctx, "batch-expired", account) - s := NewScheduler(store, nil, nil, refresher, nil) - s.api = schedulerRenewServiceFromServer(srv) - s.cooldown = NewCooldownManager() - s.apiCookieRenewOne(ctx, "batch-partial", account) - refresher.waitCookie(t, "cid-partial") - - got, err := store.Cookies.GetValue(ctx, "cid-partial") - if err != nil { - t.Fatalf("GetValue: %v", err) + if browser.quickCalls != 0 || refresher.calls.Load() != 0 { + t.Fatalf("proactive renewal escalated: browser=%d password=%d", browser.quickCalls, refresher.calls.Load()) } - for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1"} { - if !strings.Contains(got, want) { - t.Fatalf("部分 Cookie 未保存,缺少 %s: %q", want, got) - } - } - log := lastAPIRenewLog(t, store, "cid-partial") - if log.status != "need_password_login" { - t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log) - } - if !strings.Contains(log.updatedCookieNames, "sgcookie") || !strings.Contains(log.updatedCookieNames, "_m_h5_tk") { - t.Fatalf("updated_cookie_names 未记录部分更新: %+v", log) - } - if !strings.Contains(log.responseContent, "silent-partial") { - t.Fatalf("response_content 应记录 silentHasLogin 响应: %+v", log) + log := lastAPIRenewLog(t, store, account.ID) + if log.status != "skipped" || !strings.Contains(log.stepDetails, "long_login_expired") { + t.Fatalf("expired long login log=%+v", log) } } -func TestAPICookieRenewOneSavesBrowserCookiesWhenVerifyFails(t *testing.T) { +func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) { store, cleanup := newSchedulerTestStore(t) defer cleanup() ctx := context.Background() - account := createSchedulerAccount(t, store, "cid-browser-fail", "unb=1; cookie2=c2") - browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; sgcookie=s1; _m_h5_tk=tk_1; browser=b1"} - refresher := &schedulerFakePasswordRefresher{ch: make(chan string, 1)} - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/hasLogin.do": - http.SetCookie(w, &http.Cookie{Name: "sgcookie", Value: "s1"}) - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - case "/silentHasLogin.do": - http.SetCookie(w, &http.Cookie{Name: "_m_h5_tk", Value: "tk_1"}) - _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-fail"}`)) - case "/setLoginSettings.do": - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - default: - http.NotFound(w, r) - } + 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{} + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + http.SetCookie(w, &http.Cookie{Name: "sdkSilent", Value: strconv.FormatInt(time.Now().Add(time.Hour).UnixMilli(), 10)}) + _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"single-silent"}`)) })) defer srv.Close() s := NewScheduler(store, nil, browser, refresher, nil) s.api = schedulerRenewServiceFromServer(srv) - s.cooldown = NewCooldownManager() - s.apiCookieRenewOne(ctx, "batch-browser-fail", account) - refresher.waitCookie(t, "cid-browser-fail") + s.apiCookieRenewOne(ctx, "batch-silent", account) - if browser.quickCalls != 1 { - t.Fatalf("BrowserQuickRenew calls=%d want 1", browser.quickCalls) + 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 len(browser.quickInputs) != 1 || !strings.Contains(browser.quickInputs[0], "sgcookie=s1") || !strings.Contains(browser.quickInputs[0], "_m_h5_tk=tk_1") { - t.Fatalf("浏览器续期输入未使用接口部分更新: %#v", browser.quickInputs) + got, err := store.Cookies.GetValue(ctx, account.ID) + if err != nil || !strings.Contains(got, "sdkSilent=") { + t.Fatalf("silent Cookie not saved: value=%q err=%v", got, err) } - got, err := store.Cookies.GetValue(ctx, "cid-browser-fail") - if err != nil { - t.Fatalf("GetValue: %v", err) - } - for _, want := range []string{"sgcookie=s1", "_m_h5_tk=tk_1", "browser=b1"} { - if !strings.Contains(got, want) { - t.Fatalf("浏览器 Cookie 未保存,缺少 %s: %q", want, got) - } - } - log := lastAPIRenewLog(t, store, "cid-browser-fail") - if log.status != "need_password_login" { - t.Fatalf("status=%q want need_password_login, log=%+v", log.status, log) - } - if !strings.Contains(log.updatedCookieNames, "browser") { - t.Fatalf("updated_cookie_names 未记录浏览器更新: %+v", log) - } -} - -func TestAPICookieRenewOneBrowserRenewedAfterVerifySuccess(t *testing.T) { - store, cleanup := newSchedulerTestStore(t) - defer cleanup() - ctx := context.Background() - account := createSchedulerAccount(t, store, "cid-browser-ok", "unb=1; cookie2=c2") - if err := store.Tokens.Save(ctx, account.ID, "did-stable", "cached-token", time.Now().Add(time.Hour).Unix()); err != nil { - t.Fatalf("Save token: %v", err) - } - browser := &schedulerFakeBrowser{quickCookies: "unb=1; cookie2=c2; browser=b1"} - var setLoginCalls atomic.Int32 - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - switch r.URL.Path { - case "/hasLogin.do": - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - case "/silentHasLogin.do": - _, _ = w.Write([]byte(`{"content":{"success":true},"marker":"silent-browser-ok"}`)) - case "/setLoginSettings.do": - if setLoginCalls.Add(1) == 2 { - http.SetCookie(w, &http.Cookie{Name: "havana_lgc2_77", Value: "lgc"}) - } - _, _ = w.Write([]byte(`{"content":{"success":true}}`)) - default: - http.NotFound(w, r) - } - })) - defer srv.Close() - - s := NewScheduler(store, nil, browser, nil, nil) - s.api = schedulerRenewServiceFromServer(srv) - s.cooldown = NewCooldownManager() - s.apiCookieRenewOne(ctx, "batch-browser-ok", account) - if token, err := store.Tokens.Get(ctx, account.ID); err != nil || token.AccessToken != "cached-token" { - t.Fatalf("定时续期不得删除有效 token 缓存: token=%+v err=%v", token, err) - } - - if browser.quickCalls != 1 || setLoginCalls.Load() != 2 { - t.Fatalf("browser calls=%d setLoginCalls=%d", browser.quickCalls, setLoginCalls.Load()) - } - got, err := store.Cookies.GetValue(ctx, "cid-browser-ok") - if err != nil { - t.Fatalf("GetValue: %v", err) - } - for _, want := range []string{"browser=b1", "havana_lgc2_77=lgc"} { - if !strings.Contains(got, want) { - t.Fatalf("最终 Cookie 缺少 %s: %q", want, got) - } - } - log := lastAPIRenewLog(t, store, "cid-browser-ok") - if log.status != "browser_renewed" { - t.Fatalf("status=%q want browser_renewed, log=%+v", log.status, log) - } - if !strings.Contains(log.responseContent, "silent-browser-ok") { - t.Fatalf("response_content 应记录验证阶段 silentHasLogin 响应: %+v", log) - } - if log.renewMethod != "browser+api" || log.requestCount != 6 { - t.Fatalf("浏览器兜底日志应记录方法和请求数: %+v", log) - } - if !strings.Contains(log.stepDetails, "browser: quick_enter") || !strings.Contains(log.stepDetails, "api_verify") { - t.Fatalf("step_details 未记录浏览器兜底步骤: %+v", log) - } - if log.durationMS < 0 { - t.Fatalf("duration_ms 不应为负数: %+v", log) + log := lastAPIRenewLog(t, store, account.ID) + if log.status != "cookie_updated" || log.requestCount != 1 || !strings.Contains(log.responseContent, "single-silent") { + t.Fatalf("silent renewal log=%+v", log) } } diff --git a/internal/xianyu/mtop/client.go b/internal/xianyu/mtop/client.go index 8e04e68..fc0a208 100644 --- a/internal/xianyu/mtop/client.go +++ b/internal/xianyu/mtop/client.go @@ -103,17 +103,19 @@ var _ Client = (*ClientImpl)(nil) // RefreshResult 是刷新 token 的结果。 type RefreshResult struct { - AccessToken string // 用于 WS /reg 注册 - UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同) + AccessToken string // 用于 WS /reg 注册 + AccessTokenExpireAt int64 // 服务端 accessTokenExpiredTime 归一化后的 Unix 秒 + UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同) } // FreshCaptchaResult 是重取 token 风控验证链接的结果。 type FreshCaptchaResult struct { - TokenOK bool - AccessToken string - UpdatedCookies string - VerificationURL string - Ret []string + TokenOK bool + AccessToken string + AccessTokenExpireAt int64 + UpdatedCookies string + VerificationURL string + Ret []string } // UserProfileResult 是 mtop.idle.web.user.page.nav 返回的当前账号资料。 diff --git a/internal/xianyu/mtop/token.go b/internal/xianyu/mtop/token.go index a68baa0..422c9a9 100644 --- a/internal/xianyu/mtop/token.go +++ b/internal/xianyu/mtop/token.go @@ -34,12 +34,12 @@ func (c *ClientImpl) RefreshTokenContext(ctx context.Context, cookiesStr string) func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookiesStr, deviceID string) (*RefreshResult, error) { currentCookies := cookiesStr for attempt := 0; attempt < 2; attempt++ { - accessToken, ret, updatedCookies, verificationURL, status, err := c.refreshTokenOnce(ctx, currentCookies, deviceID) + accessToken, expireAt, ret, updatedCookies, verificationURL, status, err := c.refreshTokenOnce(ctx, currentCookies, deviceID) if err != nil { return &RefreshResult{UpdatedCookies: currentCookies}, err } if accessToken != "" { - return &RefreshResult{AccessToken: accessToken, UpdatedCookies: updatedCookies}, nil + return &RefreshResult{AccessToken: accessToken, AccessTokenExpireAt: expireAt, UpdatedCookies: updatedCookies}, nil } if isRiskVerificationRet(ret) { return &RefreshResult{UpdatedCookies: updatedCookies}, &RiskVerificationError{Ret: ret, VerificationURL: verificationURL} @@ -65,16 +65,17 @@ func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookie // RequestFreshCaptchaURLContext 重新请求 token API,用于浏览器风控验证前获取新鲜验证链接。 // 如果风控已解除并直接返回 accessToken,则 TokenOK=true。 func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*FreshCaptchaResult, error) { - accessToken, ret, updatedCookies, verificationURL, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID) + accessToken, expireAt, ret, updatedCookies, verificationURL, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID) if err != nil { return &FreshCaptchaResult{UpdatedCookies: updatedCookies}, err } if accessToken != "" { return &FreshCaptchaResult{ - TokenOK: true, - AccessToken: accessToken, - UpdatedCookies: updatedCookies, - Ret: ret, + TokenOK: true, + AccessToken: accessToken, + AccessTokenExpireAt: expireAt, + UpdatedCookies: updatedCookies, + Ret: ret, }, nil } return &FreshCaptchaResult{ @@ -84,7 +85,7 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS }, nil } -func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, []string, string, string, int, error) { +func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, int64, []string, string, string, int, error) { hc := c.HTTPClient if hc == nil { hc = &http.Client{Timeout: 30 * time.Second} @@ -93,7 +94,7 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID cookies := protocol.TransCookies(cookiesStr) myid := cookies["unb"] if myid == "" { - return "", nil, cookiesStr, "", 0, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId") + return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId") } if strings.TrimSpace(deviceID) == "" { deviceID = protocol.GenerateDeviceID(myid) @@ -121,10 +122,10 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID URL: requestURL, Body: body, Cookies: cookiesStr, }) if execErr != nil { - return "", nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 请求失败: %w", execErr) + return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 请求失败: %w", execErr) } if browserResp == nil { - return "", nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 返回空响应") + return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 返回空响应") } raw, status = browserResp.Body, browserResp.Status if strings.TrimSpace(browserResp.UpdatedCookies) != "" { @@ -133,17 +134,17 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID } else { req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body)) if reqErr != nil { - return "", nil, cookiesStr, "", 0, reqErr + return "", 0, nil, cookiesStr, "", 0, reqErr } setCommonHeaders(req, cookiesStr) resp, reqErr := hc.Do(req) if reqErr != nil { - return "", nil, cookiesStr, "", 0, fmt.Errorf("token API 请求失败: %w", reqErr) + return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("token API 请求失败: %w", reqErr) } defer resp.Body.Close() raw, reqErr = readMTopBody(resp) if reqErr != nil { - return "", nil, cookiesStr, "", resp.StatusCode, reqErr + return "", 0, nil, cookiesStr, "", resp.StatusCode, reqErr } status = resp.StatusCode // 即使业务返回 token 过期,也要保留响应下发的新签名 Cookie。 @@ -153,12 +154,13 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID var res struct { Ret []string `json:"ret"` Data struct { - AccessToken string `json:"accessToken"` - URL string `json:"url"` + AccessToken string `json:"accessToken"` + AccessTokenExpiredTime json.RawMessage `json:"accessTokenExpiredTime"` + URL string `json:"url"` } `json:"data"` } if err := json.Unmarshal(raw, &res); err != nil { - return "", nil, updated, "", status, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300)) + return "", 0, nil, updated, "", status, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300)) } ok := false @@ -169,12 +171,36 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID } } if !ok { - return "", res.Ret, updated, res.Data.URL, status, nil + return "", 0, res.Ret, updated, res.Data.URL, status, nil } if res.Data.AccessToken == "" { - return "", res.Ret, updated, "", status, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300)) + return "", 0, res.Ret, updated, "", status, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300)) + } + return res.Data.AccessToken, parseAccessTokenExpireAt(res.Data.AccessTokenExpiredTime, time.Now()), res.Ret, updated, "", status, nil +} + +func parseAccessTokenExpireAt(raw json.RawMessage, now time.Time) int64 { + value := strings.Trim(strings.TrimSpace(string(raw)), `"`) + if value == "" || value == "null" { + return 0 + } + if parsed, err := time.Parse(time.RFC3339, value); err == nil { + return parsed.Unix() + } + n, err := strconv.ParseFloat(value, 64) + if err != nil || n <= 0 { + return 0 + } + switch { + case n >= float64(now.UnixMilli()/2): + return int64(n / 1000) + case n >= float64(now.Unix()/2): + return int64(n) + case n >= 1_000_000: + return now.Add(time.Duration(n) * time.Millisecond).Unix() + default: + return now.Add(time.Duration(n) * time.Second).Unix() } - return res.Data.AccessToken, res.Ret, updated, "", status, nil } // buildTokenQuery 构造 token API 的 query string。 diff --git a/internal/xianyu/mtop/token_test.go b/internal/xianyu/mtop/token_test.go index 0d20ef5..12583b7 100644 --- a/internal/xianyu/mtop/token_test.go +++ b/internal/xianyu/mtop/token_test.go @@ -2,6 +2,7 @@ package mtop import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -267,3 +268,30 @@ func TestRefreshTokenRefreshWrapper(t *testing.T) { t.Fatalf("AccessToken=%q", result.AccessToken) } } + +func TestParseAccessTokenExpireAtSupportsOfficialTimestampForms(t *testing.T) { + now := time.Unix(1_700_000_000, 0) + tests := []struct { + name string + raw string + want int64 + }{ + {name: "unix milliseconds", raw: `1700007200000`, want: now.Add(2 * time.Hour).Unix()}, + {name: "unix seconds string", raw: `"1700007200"`, want: now.Add(2 * time.Hour).Unix()}, + {name: "relative seconds", raw: `7200`, want: now.Add(2 * time.Hour).Unix()}, + {name: "relative milliseconds", raw: `7200000`, want: now.Add(2 * time.Hour).Unix()}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := parseAccessTokenExpireAt(json.RawMessage(tt.raw), now); got != tt.want { + t.Fatalf("expireAt=%d want=%d", got, tt.want) + } + }) + } +} + +func TestParseAccessTokenExpireAtRejectsMissingValue(t *testing.T) { + if got := parseAccessTokenExpireAt(nil, time.Now()); got != 0 { + t.Fatalf("expireAt=%d want=0", got) + } +} diff --git a/internal/xianyu/protocol/cookies.go b/internal/xianyu/protocol/cookies.go index 4cebed4..faf461e 100644 --- a/internal/xianyu/protocol/cookies.go +++ b/internal/xianyu/protocol/cookies.go @@ -9,12 +9,14 @@ func TransCookies(cookiesStr string) map[string]string { if cookiesStr == "" { return cookies } - for _, part := range strings.Split(cookiesStr, "; ") { - if eq := strings.Index(part, "="); eq >= 0 { - k := part[:eq] - v := part[eq+1:] - cookies[k] = v + for _, part := range strings.Split(cookiesStr, ";") { + part = strings.TrimSpace(part) + key, value, ok := strings.Cut(part, "=") + key = strings.TrimSpace(key) + if !ok || key == "" { + continue } + cookies[key] = strings.TrimSpace(value) } return cookies } diff --git a/internal/xianyu/protocol/cookies_test.go b/internal/xianyu/protocol/cookies_test.go index e904f79..73ee446 100644 --- a/internal/xianyu/protocol/cookies_test.go +++ b/internal/xianyu/protocol/cookies_test.go @@ -22,9 +22,10 @@ func TestTransCookies_Table(t *testing.T) { {"empty value", "k=", map[string]string{"k": ""}}, {"value with equals sign", "k=a=b=c", map[string]string{"k": "a=b=c"}}, {"url encoded value", "k=" + url.QueryEscape("a b&c=d"), map[string]string{"k": "a+b%26c%3Dd"}}, - {"leading/trailing spaces in value", "k= v ", map[string]string{"k": " v "}}, - {"only separator", "=", map[string]string{"": ""}}, - {"single fragment no space separator", "a=1;b=2", map[string]string{"a": "1;b=2"}}, + {"leading/trailing spaces in value", "k= v ", map[string]string{"k": "v"}}, + {"only separator", "=", map[string]string{}}, + {"single fragment no space separator", "a=1;b=2", map[string]string{"a": "1", "b": "2"}}, + {"trailing separator", "a=1; b=2;", map[string]string{"a": "1", "b": "2"}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/xianyu/qrlogin/client.go b/internal/xianyu/qrlogin/client.go index 70ae040..5196337 100644 --- a/internal/xianyu/qrlogin/client.go +++ b/internal/xianyu/qrlogin/client.go @@ -434,18 +434,6 @@ func (m *Manager) monitorQRStatus(ctx context.Context, sessionID string) { sess.mu.Unlock() } -func (m *Manager) markSessionExpired(sessionID string) { - m.mu.Lock() - sess := m.sessions[sessionID] - m.mu.Unlock() - if sess == nil { - return - } - sess.mu.Lock() - sess.Status = "expired" - 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 { diff --git a/internal/xianyu/renew/service.go b/internal/xianyu/renew/service.go index 926f015..733a975 100644 --- a/internal/xianyu/renew/service.go +++ b/internal/xianyu/renew/service.go @@ -7,13 +7,10 @@ package renew import ( "context" - cryptorand "crypto/rand" "encoding/json" "fmt" "io" - "math/big" "net/http" - "net/url" "sort" "strconv" "strings" @@ -158,128 +155,12 @@ func autoLoginSkipMessage(reason string) string { } } -func (s Service) renewOnce(ctx context.Context, original string) (*Result, error) { - current := original - steps := make([]StepResult, 0, 3) - allSetCookies := make([]string, 0, 8) - - hasLogin, err := s.callHasLogin(ctx, current) - if err != nil { - return nil, err - } - steps = append(steps, hasLogin.Step) - if len(hasLogin.SetCookies) > 0 { - allSetCookies = append(allSetCookies, hasLogin.SetCookies...) - current = MergeSetCookies(current, hasLogin.SetCookies) - } - - silent, err := s.callSilentHasLogin(ctx, current) - if err != nil { - return nil, err - } - steps = append(steps, silent.Step) - if len(silent.SetCookies) > 0 { - allSetCookies = append(allSetCookies, silent.SetCookies...) - current = MergeSetCookies(current, silent.SetCookies) - } - - settings, err := s.callSetLoginSettings(ctx, current) - if err != nil { - return nil, err - } - steps = append(steps, settings.Step) - if len(settings.SetCookies) > 0 { - allSetCookies = append(allSetCookies, settings.SetCookies...) - } - - newCookies := original - if len(allSetCookies) > 0 { - newCookies = MergeSetCookies(original, allSetCookies) - } - updated := ChangedCookieNames(original, newCookies) - success := len(settings.SetCookies) > 0 - method := "none" - msg := "setLoginSettings 未返回 Set-Cookie,需要浏览器续期或密码登录" - if success { - method = "api" - msg = "接口续期成功" - } - return &Result{ - Success: success, - RenewMethod: method, - NewCookies: newCookies, - UpdatedCookieNames: updated, - StepDetails: steps, - Message: msg, - ResponseText: string(silent.Body), - NeedPasswordLogin: !success, - }, nil -} - type callResult struct { Step StepResult SetCookies []string Body []byte } -func (s Service) callHasLogin(ctx context.Context, cookiesStr string) (callResult, error) { - cookies := protocol.TransCookies(cookiesStr) - unb := cookies["unb"] - if unb == "" { - return callResult{Step: StepResult{Name: "hasLogin", Message: "Cookie缺少unb,跳过"}}, nil - } - form := url.Values{} - form.Set("hid", unb) - form.Set("ltl", "true") - form.Set("appName", "xianyu") - form.Set("appEntrance", "web") - form.Set("_csrf_token", cookies["_tb_token_"]) - form.Set("umidToken", firstNonEmpty(cookies["_uab_collina"], cookies["cna"])) - form.Set("hsiz", cookies["cookie2"]) - form.Set("bizParams", "taobaoBizLoginFrom=web&renderRefer=https%3A%2F%2Fwww.goofish.com%2F") - form.Set("mainPage", "false") - form.Set("isMobile", "false") - form.Set("lang", "zh_CN") - form.Set("fromSite", "77") - form.Set("isIframe", "true") - form.Set("documentReferer", "https://www.goofish.com/") - form.Set("defaultView", "hasLogin") - form.Set("umidTag", "SERVER") - form.Set("returnUrl", "") - form.Set("deviceId", "") - form.Set("pageTraceId", "21504"+strconv.FormatInt(time.Now().UnixMilli(), 10)+randomDigits(6)) - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.HasLoginURL, HasLoginURL), strings.NewReader(form.Encode())) - if err != nil { - return callResult{}, err - } - setHasLoginHeaders(req, cookiesStr, miniLoginReferer()) - if xsrf := cookies["XSRF-TOKEN"]; xsrf != "" { - req.Header.Set("x-xsrf-token", xsrf) - } - q := req.URL.Query() - q.Set("appName", "xianyu") - q.Set("fromSite", "77") - req.URL.RawQuery = q.Encode() - return s.doRenewRequest(req, "hasLogin") -} - -func (s Service) callSilentHasLogin(ctx context.Context, cookiesStr string) (callResult, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil) - if err != nil { - return callResult{}, err - } - q := req.URL.Query() - q.Set("documentReferer", "https://www.goofish.com/") - q.Set("appName", "xianyu") - q.Set("appEntrance", "xianyu_sdkSilent") - q.Set("fromSite", "0") - q.Set("ltl", "true") - req.URL.RawQuery = q.Encode() - setSilentHasLoginHeaders(req, cookiesStr) - return s.doRenewRequest(req, "silentHasLogin") -} - func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (callResult, error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil) if err != nil { @@ -304,20 +185,6 @@ func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (ca return s.doRenewRequest(req, "silentHasLogin") } -func (s Service) callSetLoginSettings(ctx context.Context, cookiesStr string) (callResult, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL), strings.NewReader("status=0")) - if err != nil { - return callResult{}, err - } - q := req.URL.Query() - q.Set("fromSite", "77") - q.Set("appName", "xianyu") - q.Set("bizEntrance", "web") - req.URL.RawQuery = q.Encode() - setLoginSettingsHeaders(req, cookiesStr) - return s.doRenewRequest(req, "setLoginSettings") -} - func (s Service) doRenewRequest(req *http.Request, name string) (callResult, error) { hc := s.HTTPClient if hc == nil { @@ -398,16 +265,6 @@ func mtopInt(v any) int { } } -func setHasLoginHeaders(req *http.Request, cookiesStr, referer string) { - xianyu.ApplyBrowserFingerprint(req.Header) - req.Header.Set("Accept", "application/json, text/plain, */*") - req.Header.Set("Accept-Language", "zh-CN") - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.Header.Set("Referer", referer) - req.Header.Set("bx-v", "2.5.31") - req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", "")) -} - func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) { xianyu.ApplyBrowserFingerprint(req.Header) req.Header.Set("Accept", "*/*") @@ -422,18 +279,6 @@ func setSilentHasLoginHeaders(req *http.Request, cookiesStr string) { req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", "")) } -func setLoginSettingsHeaders(req *http.Request, cookiesStr string) { - xianyu.ApplyBrowserFingerprint(req.Header) - req.Header.Set("Accept", "application/json, text/plain, */*") - req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.Header.Set("Referer", "https://www.goofish.com/") - req.Header.Set("sec-fetch-dest", "empty") - req.Header.Set("sec-fetch-mode", "cors") - req.Header.Set("sec-fetch-site", "same-site") - req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", "")) -} - func (s Service) urlOrDefault(v, fallback string) string { if strings.TrimSpace(v) != "" { return v @@ -461,34 +306,6 @@ func firstNonEmpty(values ...string) string { return "" } -func miniLoginReferer() string { - return "https://passport.goofish.com/mini_login.htm?lang=zh_cn&appName=xianyu&appEntrance=web&styleType=vertical&bizParams=¬LoadSsoView=false¬KeepLogin=false&isMobile=false&qrCodeFirst=false&stie=77&rnd=" + randomFraction() -} - -func randomDigits(n int) string { - if n <= 0 { - return "" - } - min := 1 - for i := 1; i < n; i++ { - min *= 10 - } - max := min * 9 - v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(int64(max))) - if err != nil { - return strings.Repeat("0", n) - } - return strconv.Itoa(min + int(v.Int64())) -} - -func randomFraction() string { - v, err := cryptorand.Int(cryptorand.Reader, big.NewInt(1_000_000_000)) - if err != nil { - return "0.0" - } - return "0." + fmt.Sprintf("%09d", v.Int64()) -} - func filterValidSetCookies(setCookies []string) []string { if len(setCookies) == 0 { return nil diff --git a/internal/xianyu/ws/auth_error.go b/internal/xianyu/ws/auth_error.go new file mode 100644 index 0000000..d674269 --- /dev/null +++ b/internal/xianyu/ws/auth_error.go @@ -0,0 +1,94 @@ +package ws + +import ( + "errors" + "fmt" + "strings" +) + +type RegErrorKind string + +const ( + RegErrorInvalidToken RegErrorKind = "invalid_token" + RegErrorConnectLimit RegErrorKind = "connect_limit" + RegErrorAuthentication RegErrorKind = "authentication" +) + +// RegError describes a server-side /reg rejection after the WebSocket itself +// has opened successfully. +type RegError struct { + Kind RegErrorKind + Code int + Reason string +} + +func (e *RegError) Error() string { + if e == nil { + return "" + } + return fmt.Sprintf("WS /reg 被拒绝: kind=%s code=%d reason=%s", e.Kind, e.Code, e.Reason) +} + +func IsInvalidTokenError(err error) bool { + var regErr *RegError + return errors.As(err, ®Err) && regErr.Kind == RegErrorInvalidToken +} + +func IsConnectLimitError(err error) bool { + var regErr *RegError + return errors.As(err, ®Err) && regErr.Kind == RegErrorConnectLimit +} + +func IsAuthenticationError(err error) bool { + var regErr *RegError + return errors.As(err, ®Err) && regErr.Kind == RegErrorAuthentication +} + +func newRegError(code int, frame map[string]any) error { + reason := regErrorReason(frame) + lower := strings.ToLower(reason) + kind := RegErrorAuthentication + switch { + case code == 401, + strings.Contains(lower, "invalid token"), + strings.Contains(lower, "not auth"), + strings.Contains(lower, "token invalid"), + strings.Contains(lower, "device id or appkey is not equal"): + kind = RegErrorInvalidToken + case strings.Contains(lower, "connect limit"), + strings.Contains(lower, "session remove"), + strings.Contains(lower, "too many"): + kind = RegErrorConnectLimit + } + return &RegError{Kind: kind, Code: code, Reason: reason} +} + +func regErrorReason(frame map[string]any) string { + values := make([]string, 0, 8) + appendValue := func(value any) { + if value == nil { + return + } + text := strings.TrimSpace(fmt.Sprint(value)) + if text != "" && text != "" { + values = append(values, text) + } + } + for _, key := range []string{"message", "msg", "reason", "ret"} { + appendValue(frame[key]) + } + if body, ok := frame["body"].(map[string]any); ok { + for _, key := range []string{"message", "msg", "reason", "moreInfo"} { + appendValue(body[key]) + } + } + if headers, ok := frame["headers"].(map[string]any); ok { + for _, key := range []string{"message", "msg", "reason", "error", "error-message"} { + appendValue(headers[key]) + } + } + if len(values) == 0 { + return "unknown authentication error" + } + return strings.Join(values, " | ") +} diff --git a/internal/xianyu/ws/client.go b/internal/xianyu/ws/client.go index d586edf..2cc879d 100644 --- a/internal/xianyu/ws/client.go +++ b/internal/xianyu/ws/client.go @@ -23,6 +23,7 @@ const WSURL = "wss://wss-goofish.dingtalk.com/" const ( wsOpenTimeout = 30 * time.Second + regResponseTimeout = 30 * time.Second protocolPingInterval = 20 * time.Second protocolPingTimeout = 15 * time.Second ) @@ -43,11 +44,18 @@ type Config struct { // Conn 包装一条已注册的 WebSocket 连接。 type Conn struct { - ws *websocket.Conn - cfg Config - logger *slog.Logger - sendMu sync.Mutex - recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) + ws *websocket.Conn + cfg Config + logger *slog.Logger + sendMu sync.Mutex + preReadMu sync.Mutex + preRead []bufferedFrame + recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string) +} + +type bufferedFrame struct { + messageType websocket.MessageType + data []byte } // SetRecorder 设置帧记录器。 @@ -90,6 +98,7 @@ func websocketHeaders(cookieStr string) http.Header { // register 发送 /reg 与 ackDiff。 func (c *Conn) register(ctx context.Context) error { + regMID := protocol.GenerateMid() reg := map[string]any{ "lwp": "/reg", "headers": map[string]any{ @@ -101,14 +110,18 @@ func (c *Conn) register(ctx context.Context) error { "wv": "im:3,au:3,sy:6", "sync": "0,0;0;0;", "did": c.cfg.DeviceID, - "mid": protocol.GenerateMid(), + "mid": regMID, }, } if err := c.sendJSON(ctx, reg); err != nil { return fmt.Errorf("发送 /reg 失败: %w", err) } + if err := c.waitForRegResponse(ctx, regMID); err != nil { + return err + } - // /reg 后等待 1 秒再发送 ackDiff。 + // 官方只在 /reg 认证成功后启动后续同步。保留原有短等待,避免紧贴注册 + // 响应发送同步请求。 select { case <-time.After(time.Second): case <-ctx.Done(): @@ -139,6 +152,104 @@ func (c *Conn) register(ctx context.Context) error { return nil } +func (c *Conn) waitForRegResponse(ctx context.Context, requestMID string) error { + regCtx, cancel := context.WithTimeout(ctx, regResponseTimeout) + defer cancel() + + for { + messageType, data, err := c.ws.Read(regCtx) + if err != nil { + return fmt.Errorf("等待 /reg 响应失败: %w", err) + } + var frame map[string]any + if err := json.Unmarshal(data, &frame); err != nil { + c.bufferFrame(messageType, data) + continue + } + if !isRegResponse(frame, requestMID) { + c.bufferFrame(messageType, data) + continue + } + c.recordParsedIncoming(data, frame) + code, ok := responseCode(frame["code"]) + if ok && code == 200 { + return nil + } + return newRegError(code, frame) + } +} + +func isRegResponse(frame map[string]any, requestMID string) bool { + if _, ok := frame["code"]; !ok { + return false + } + headers, _ := frame["headers"].(map[string]any) + responseMIDValue, hasMID := headers["mid"] + responseMID := strings.TrimSpace(fmt.Sprint(responseMIDValue)) + if !hasMID || responseMID == "" || responseMID == "" { + // /reg is the only outstanding request during registration. Some gateway + // versions omit mid on an immediate authentication failure. + return true + } + return midKey(responseMID) == midKey(requestMID) +} + +func midKey(mid string) string { + fields := strings.Fields(mid) + if len(fields) == 0 { + return "" + } + return fields[0] +} + +func responseCode(value any) (int, bool) { + switch code := value.(type) { + case float64: + return int(code), true + case int: + return code, true + case json.Number: + parsed, err := code.Int64() + return int(parsed), err == nil + case string: + var parsed int + if _, err := fmt.Sscanf(strings.TrimSpace(code), "%d", &parsed); err == nil { + return parsed, true + } + } + return 0, false +} + +func (c *Conn) bufferFrame(messageType websocket.MessageType, data []byte) { + copyOfData := append([]byte(nil), data...) + c.preReadMu.Lock() + c.preRead = append(c.preRead, bufferedFrame{messageType: messageType, data: copyOfData}) + c.preReadMu.Unlock() +} + +func (c *Conn) readNext(ctx context.Context) (websocket.MessageType, []byte, error) { + c.preReadMu.Lock() + if len(c.preRead) > 0 { + frame := c.preRead[0] + c.preRead = c.preRead[1:] + c.preReadMu.Unlock() + return frame.messageType, frame.data, nil + } + c.preReadMu.Unlock() + return c.ws.Read(ctx) +} + +func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) { + if c.recorder == nil { + return + } + parsedJSON := string(data) + if normalized, err := json.Marshal(parsed); err == nil { + parsedJSON = string(normalized) + } + c.recorder("in", string(data), parsedJSON, "json", "") +} + // HeartbeatLoop 周期性发送应用层心跳 {"lwp":"/!"},直到 ctx 取消或连续失败 maxFailures 次。 func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error { const maxFailures = 3 @@ -215,7 +326,7 @@ func (c *Conn) protocolPingLoop(ctx context.Context) error { // 非 JSON / 非同步包消息仅记录后跳过。返回 ctx 错误或致命读取错误。 func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[string]any)) error { for { - msgType, data, err := c.ws.Read(ctx) + msgType, data, err := c.readNext(ctx) if err != nil { return fmt.Errorf("WS read: %w", err) } @@ -359,13 +470,6 @@ func (c *Conn) sendJSON(ctx context.Context, v any) error { return c.ws.Write(ctx, websocket.MessageText, b) } -// SetAccessToken 在线更新 token(仅在连接保持期间用于定时刷新)。 -func (c *Conn) SetAccessToken(token string) { - c.sendMu.Lock() - defer c.sendMu.Unlock() - c.cfg.AccessToken = token -} - // SendText 发送一条闲鱼聊天文本消息。 func (c *Conn) SendText(ctx context.Context, myID, cid, toID, text string) error { content := map[string]any{ diff --git a/internal/xianyu/ws/dial_test.go b/internal/xianyu/ws/dial_test.go index 2a17fb4..9515bc2 100644 --- a/internal/xianyu/ws/dial_test.go +++ b/internal/xianyu/ws/dial_test.go @@ -42,6 +42,20 @@ func startRegServer(t *testing.T) (*httptest.Server, chan map[string]any) { case got <- m: default: } + if m["lwp"] == "/reg" { + headers, _ := m["headers"].(map[string]any) + response := map[string]any{ + "code": 200, + "headers": map[string]any{ + "mid": headers["mid"], + "reg-uid": "123@goofish", + }, + } + raw, _ := json.Marshal(response) + if err := c.Write(ctx, websocket.MessageText, raw); err != nil { + return + } + } } } })) @@ -152,6 +166,80 @@ func TestRegister_ContextCancelledDuringWait(t *testing.T) { } } +func TestRegisterRejectsInvalidToken(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, nil) + if err != nil { + return + } + defer c.CloseNow() + _, data, err := c.Read(r.Context()) + if err != nil { + return + } + var reg map[string]any + _ = json.Unmarshal(data, ®) + headers, _ := reg["headers"].(map[string]any) + response, _ := json.Marshal(map[string]any{ + "code": 401, + "headers": map[string]any{"mid": headers["mid"]}, + "body": map[string]any{"reason": "invalid token"}, + }) + _ = c.Write(r.Context(), websocket.MessageText, response) + })) + t.Cleanup(srv.Close) + + conn := dialLocal(t, srv, Config{AccessToken: "rejected"}) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + err := conn.register(ctx) + if !IsInvalidTokenError(err) { + t.Fatalf("register error=%v, want invalid token", err) + } +} + +func TestRegisterBuffersFrameBeforeResponse(t *testing.T) { + push := map[string]any{"lwp": "/push/test", "headers": map[string]any{"mid": "push-1"}} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := websocket.Accept(w, r, nil) + if err != nil { + return + } + defer c.CloseNow() + ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + defer cancel() + _, data, err := c.Read(ctx) + if err != nil { + return + } + var reg map[string]any + _ = json.Unmarshal(data, ®) + headers, _ := reg["headers"].(map[string]any) + pushRaw, _ := json.Marshal(push) + _ = c.Write(ctx, websocket.MessageText, pushRaw) + response, _ := json.Marshal(map[string]any{"code": 200, "headers": map[string]any{"mid": headers["mid"]}}) + _ = c.Write(ctx, websocket.MessageText, response) + _, _, _ = c.Read(ctx) // ackDiff + })) + t.Cleanup(srv.Close) + + conn := dialLocal(t, srv, Config{}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if err := conn.register(ctx); err != nil { + t.Fatalf("register: %v", err) + } + _, data, err := conn.readNext(ctx) + if err != nil { + t.Fatalf("read buffered frame: %v", err) + } + var got map[string]any + _ = json.Unmarshal(data, &got) + if got["lwp"] != push["lwp"] { + t.Fatalf("buffered frame=%v want=%v", got, push) + } +} + // TestDial_RegisterFailure register 的 ackDiff 发送失败时应返回错误。 // 服务端 accept 后等待 1.5s(超过 register 内 1s 等待)再 CloseNow, // 使 ackDiff 的 sendJSON 写入已关闭连接而失败。 @@ -646,35 +734,6 @@ func TestSendChatContent_MissingParams(t *testing.T) { } } -// TestSetAccessToken_AppliedToSubsequentSend SetAccessToken 后 register/SendText 发送的消息 -// 应携带新 token(通过 register 验证,因为 SendText 不直接带 token;这里用 register 覆盖)。 -func TestSetAccessToken_AppliedToSubsequentSend(t *testing.T) { - srv, got := startRegServer(t) - conn := dialLocal(t, srv, Config{AccessToken: "old-token"}) - - // 在线更新 token。 - conn.SetAccessToken("new-token-999") - - ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) - defer cancel() - if err := conn.register(ctx); err != nil { - t.Fatalf("register: %v", err) - } - - select { - case m := <-got: - if m["lwp"] != "/reg" { - t.Fatalf("期望首条为 /reg, 实际 %v", m["lwp"]) - } - headers, _ := m["headers"].(map[string]any) - if headers["token"] != "new-token-999" { - t.Errorf("/reg token = %v, 期望 new-token-999 (在线更新后)", headers["token"]) - } - case <-time.After(2 * time.Second): - t.Fatal("服务端未收到 /reg") - } -} - // TestSetRecorder_RecordsOutgoingAndIncoming SetRecorder 后 outgoing/incoming 都应触发回调。 func TestSetRecorder_RecordsOutgoingAndIncoming(t *testing.T) { payload := `{"event":"paid"}`