fix: 对齐闲鱼消息连接与登录续期流程

对齐官方 WebSocket 竞速、连接级凭证、注册解码、控制状态与心跳时序。

持久化完整 Cookie Jar,修正请求作用域、删除、分区、加密、并发写回与错误路径。

统一启动续期、长登录开关和业务 MTOP 的原子更新,并补充回归与竞态测试。
This commit is contained in:
Christ committed 2026-07-22 19:33:33 +08:00
1 parent d77c317452
commit de9c12196f
59 files changed
+6170 -1247

No files matched your search

+167 -47
View File
@@ -21,7 +21,6 @@ import (
"xianyu-go/internal/renewal"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
"xianyu-go/internal/xianyu/protocol"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -37,6 +36,14 @@ type browserQuickRenewer interface {
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
}
type browserQuickSnapshotRenewer interface {
BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
}
type browserCookieSnapshotRenewer interface {
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error)
}
type browserTokenCaptchaRecoverer interface {
TokenCaptchaRecover(ctx context.Context, cookieID, cookieStr, verificationURL string, headless bool, provider browser.TokenCaptchaURLProvider) (string, error)
}
@@ -120,6 +127,51 @@ func (a *Adapter) SetRenewService(s xrenew.Service) { a.renewSvc = s }
// SetTokenCaptchaRequester 覆盖 token 风控验证链接刷新器,便于测试隔离网络。
func (a *Adapter) SetTokenCaptchaRequester(r tokenCaptchaRequester) { a.captchaReq = r }
// RenewAccountStartup 复用真实 Chromium /im 页面执行官网 auto-login plugin。
// engine 在账号首条 WebSocket 建立前调用一次;普通 reconnect 不会重复导航页面。
func (a *Adapter) RenewAccountStartup(ctx context.Context, cookieID, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) (*xrenew.Result, error) {
var snapshot []cookierefresh.BrowserCookie
if len(snapshots) > 0 {
snapshot = snapshots[0]
}
if br, ok := a.browser.(browserCookieSnapshotRenewer); ok {
showBrowser := false
if a.store != nil && a.store.Cookies != nil {
if detail, err := a.store.Cookies.GetDetails(ctx, cookieID); err == nil && detail != nil {
showBrowser = detail.ShowBrowser
}
}
newCookies, newSnapshot, reloaded, err := br.CookiesRefreshSnapshot(
ctx, cookieID, cookieStr, snapshot, browser.ResolveHeadless(showBrowser),
)
message := "官网消息页未触发静默续期 reload"
skipReason := "official_no_reload"
if reloaded {
message = "官网消息页静默续期成功并完成 reload"
skipReason = ""
}
if err != nil {
message = "官网消息页续期执行失败: " + err.Error()
skipReason = ""
}
result := &xrenew.Result{
Success: err == nil && reloaded,
Skipped: err == nil && !reloaded,
SkipReason: skipReason,
RenewMethod: "browser_auto_login_plugin",
NewCookies: newCookies,
UpdatedCookieNames: cookierefresh.ChangedSnapshotLabels(snapshot, newSnapshot),
CookieSnapshot: newSnapshot,
CookieSnapshotComplete: newSnapshot != nil,
Message: message,
RequestCount: 1,
}
return result, err
}
// -no-browser 模式只能使用 HTTP 兼容实现;UA 仍由本地指纹统一生成。
return a.renewSvc.RenewAPIFirst(ctx, cookieStr, snapshot)
}
// HandleChatMessage 用户聊天消息由 Account 内部 ReplyService 处理,此处空实现满足接口。
func (a *Adapter) HandleChatMessage(_ context.Context, _ engine.ChatMessage) error {
return nil
@@ -296,7 +348,7 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
// FetchOrderDetail 实现 automation.OrderDetailFetcher。只在本地订单缺少关键字段时启动浏览器,
// 并将所有账号的详情请求串行化、至少间隔 3 秒,避免短时间高频访问闲鱼。
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, cookieStr string) (*automation.OrderDetail, error) {
func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemID, buyerID, _ string) (*automation.OrderDetail, error) {
if detail, ok := a.localOrderDetail(ctx, orderID); ok {
return detail, nil
}
@@ -320,12 +372,55 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
}
}
a.lastOrderFetch = time.Now()
detail, err := a.browser.FetchOrderDetail(ctx, orderID, cookieID, cookieStr, true)
credentialUnlock := a.store.LockAccountCredentials(cookieID)
defer credentialUnlock()
account, err := a.store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
return nil, err
return nil, fmt.Errorf("读取订单账号最新 Cookie: %w", err)
}
if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
_ = a.store.Cookies.UpdateValueExisting(ctx, cookieID, detail.UpdatedCookies)
if account == nil || (strings.TrimSpace(account.Value) == "" && !hasCompleteCookieSnapshot(account.MetadataJSON)) {
return nil, fmt.Errorf("订单账号 %s Cookie 为空", cookieID)
}
cookieStr := account.Value
var requestCtx context.Context
var cookieSession *mtop.CookieSession
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(account.MetadataJSON); complete {
requestCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
} else {
requestCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
}
detail, fetchErr := a.browser.FetchOrderDetail(requestCtx, orderID, cookieID, cookieStr, true)
authoritativeCookies, authoritativeSnapshot, sessionChanged := cookieSession.State()
authoritativeHandled := sessionChanged
if detail != nil && detail.CookieSnapshotComplete {
authoritativeCookies = detail.UpdatedCookies
authoritativeSnapshot = detail.CookieSnapshot
if authoritativeSnapshot == nil {
authoritativeSnapshot = []cookierefresh.BrowserCookie{}
}
authoritativeHandled = true
}
if authoritativeHandled {
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
if authoritativeSnapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, authoritativeSnapshot)
}
if persistErr := a.store.Cookies.UpdateRenewalCookie(ctx, cookieID, authoritativeCookies, metadata, time.Now().Unix()); persistErr != nil {
fetchErr = errors.Join(fetchErr, fmt.Errorf("保存订单详情响应 Cookie: %w", persistErr))
} else {
cookieStr = authoritativeCookies
}
}
if fetchErr != nil {
return nil, fetchErr
}
if detail == nil {
return nil, errors.New("订单详情浏览器返回空结果")
}
if !authoritativeHandled && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieStr {
if err := a.store.Cookies.UpdateValueExisting(ctx, cookieID, detail.UpdatedCookies); err != nil {
return nil, fmt.Errorf("保存订单详情响应 Cookie: %w", err)
}
}
return &automation.OrderDetail{
Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue,
@@ -333,6 +428,11 @@ func (a *Adapter) FetchOrderDetail(ctx context.Context, cookieID, orderID, itemI
}, nil
}
func hasCompleteCookieSnapshot(metadata string) bool {
_, ok := cookierefresh.SnapshotFromMetadataOK(metadata)
return ok
}
// localOrderDetail 命中本地完整订单时直接返回,避免不必要的浏览器抓取。
func (a *Adapter) localOrderDetail(ctx context.Context, orderID string) (*automation.OrderDetail, bool) {
order, err := a.store.Orders.Get(ctx, orderID)
@@ -513,67 +613,76 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
}
current := d.Value
api := a.renewSvc
save := func(cookieStr string) {
if strings.TrimSpace(cookieStr) == "" || cookieStr == current {
return
save := func(cookieStr string, setCookies []string, completeSnapshot []cookierefresh.BrowserCookie) error {
if cookieStr == current && len(setCookies) == 0 && completeSnapshot == nil {
return nil
}
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON), time.Now().Unix()); err != nil {
metadata := cookierefresh.MetadataWithoutSnapshot(d.MetadataJSON)
if completeSnapshot != nil {
// Chromium/API 在完整 Jar 基础上得到的快照是权威结果,包含
// 服务端删除和新的 Domain/Path/expiry 属性。
metadata = cookierefresh.MetadataWithSnapshot(d.MetadataJSON, completeSnapshot)
}
if err := a.store.Cookies.UpdateRenewalCookie(ctx, d.ID, cookieStr, metadata, time.Now().Unix()); err != nil {
a.logger.Warn("轻量续期保存 Cookie 失败", "account", d.ID, "err", err)
return
return err
}
valueChanged := cookieStr != current
current = cookieStr
d.Value = cookieStr
if a.store.Tokens != nil {
_ = a.store.Tokens.Clear(ctx, d.ID)
d.MetadataJSON = metadata
if valueChanged && a.store.Tokens != nil {
if err := a.store.Tokens.Clear(ctx, d.ID); err != nil {
// Token 仅是运行期缓存;Cookie 已原子提交后不能再把整次
// 续期报告成失败,否则调用方可能用旧凭证重试并覆盖新 Jar。
a.logger.Warn("轻量续期清理旧 Token 缓存失败", "account", d.ID, "err", err)
}
}
return nil
}
apiRenew := func(cookieStr string) (*xrenew.Result, error) {
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
return api.RenewAPIFirst(runCtx, cookieStr)
return api.RenewAPIFirst(runCtx, cookieStr, cookierefresh.SnapshotFromMetadata(d.MetadataJSON))
}
browserRenew := func(cookieStr string) (string, error) {
browserRenew := func(cookieStr string) (string, []cookierefresh.BrowserCookie, error) {
if a.browser == nil {
return "", fmt.Errorf("浏览器自动化未启用")
return "", nil, fmt.Errorf("浏览器自动化未启用")
}
if br, ok := a.browser.(browserQuickSnapshotRenewer); ok {
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
snapshot := cookierefresh.SnapshotFromMetadata(d.MetadataJSON)
return br.BrowserQuickRenewSnapshot(runCtx, d.ID, cookieStr, snapshot, browser.ResolveHeadless(d.ShowBrowser))
}
if br, ok := a.browser.(browserQuickRenewer); ok {
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
return br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
renewed, err := br.BrowserQuickRenew(runCtx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
return renewed, nil, err
}
m, err := a.browser.CookieRenew(ctx, d.ID, cookieStr, browser.ResolveHeadless(d.ShowBrowser))
if err != nil {
return "", err
return "", nil, err
}
return browser.MarshalCookies(m), nil
}
hasLongLogin := strings.TrimSpace(protocol.TransCookies(current)["havana_lgc2_77"]) != ""
if hasLongLogin {
if renewed, err := browserRenew(current); err == nil && renewed != "" {
save(renewed)
a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
return true, nil
} else if err != nil {
if errors.Is(err, browser.ErrSecurityVerification) {
return false, err
}
a.logger.Warn("密码登录前浏览器续期失败,继续尝试接口续期", "account", d.ID, "err", err)
}
if res, err := apiRenew(current); err == nil && res != nil {
save(res.NewCookies)
if res.Success {
a.logger.Info("密码登录前静默续期成功,跳过密码登录", "account", d.ID)
return true, nil
}
}
return false, nil
return browser.MarshalCookies(m), nil, nil
}
// 官网始终先由 auto-login plugin 按 havana_lgc_exp/cookie3_bak_exp
// 决定是否调用 silentHasLogin;不存在 havana_lgc2_77 浏览器优先分支。
res, err := apiRenew(current)
if err == nil && res != nil {
save(res.NewCookies)
if res.Success {
if res != nil {
var completeSnapshot []cookierefresh.BrowserCookie
if res.CookieSnapshotComplete {
completeSnapshot = res.CookieSnapshot
if completeSnapshot == nil {
completeSnapshot = []cookierefresh.BrowserCookie{}
}
}
if saveErr := save(res.NewCookies, res.SetCookies, completeSnapshot); saveErr != nil {
return false, saveErr
}
if err == nil && res.Success {
a.logger.Info("密码登录前接口续期成功,跳过密码登录", "account", d.ID)
return true, nil
}
@@ -582,14 +691,25 @@ func (a *Adapter) tryLightRenewBeforePassword(ctx context.Context, d *db.CookieD
if res != nil && strings.TrimSpace(res.NewCookies) != "" {
browserInput = res.NewCookies
}
browserCookies, err := browserRenew(browserInput)
if err != nil || browserCookies == "" {
browserCookies, browserSnapshot, err := browserRenew(browserInput)
browserSaved := false
if browserSnapshot != nil {
if saveErr := save(browserCookies, nil, browserSnapshot); saveErr != nil {
return false, saveErr
}
browserSaved = true
}
if err != nil || (browserCookies == "" && browserSnapshot == nil) {
if errors.Is(err, browser.ErrSecurityVerification) {
return false, err
}
return false, nil
}
save(browserCookies)
if !browserSaved {
if err := save(browserCookies, nil, browserSnapshot); err != nil {
return false, err
}
}
a.logger.Info("密码登录前浏览器续期成功,跳过密码登录", "account", d.ID)
return true, nil
}
+27
View File
@@ -14,6 +14,7 @@ import (
"xianyu-go/internal/db"
"xianyu-go/internal/engine"
"xianyu-go/internal/renewal"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -293,6 +294,32 @@ func TestFetchOrderDetail_BrowserFallback(t *testing.T) {
}
}
func TestFetchOrderDetail_PersistsAuthoritativeBrowserJar(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
defer cleanup()
ctx := context.Background()
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/"},
{Name: "api_only", Value: "scoped", Domain: "h5api.m.goofish.com", Path: "/h5", HTTPOnly: true, Secure: true},
}
a := New(store, nil, nil)
a.SetBrowser(&fakeBrowser{fetchDetail: &browser.OrderDetail{
Quantity: "1", Amount: "9.9", UpdatedCookies: "unb=1",
CookieSnapshot: snapshot, CookieSnapshotComplete: true,
}})
if _, err := a.FetchOrderDetail(ctx, "cid", "o-jar", "item-1", "buyer-1", "old-cookie"); err != nil {
t.Fatal(err)
}
detail, err := store.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatal(err)
}
got, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !complete || len(got) != 2 || detail.Value != "unb=1" {
t.Fatalf("authoritative jar not persisted: value=%q complete=%v snapshot=%+v", detail.Value, complete, got)
}
}
// TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew 浏览器未启用时仍先尝试接口轻量续期。
func TestOnPasswordLoginRefresh_BrowserNilStillUsesAPIRenew(t *testing.T) {
store, cleanup := newAdapterTestStore(t)
+63 -14
View File
@@ -12,6 +12,7 @@ import (
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -732,28 +733,76 @@ func (c *Center) confirmShipment(ctx context.Context, task Task) error {
if !enabled && !task.ForceConfirmShipment {
return nil
}
cookieStr := task.CookieStr
if strings.TrimSpace(cookieStr) == "" {
cookieStr, err = c.cookieValue(ctx, task.AccountID)
if err != nil {
return err
credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
credentialLocked := true
defer func() {
if credentialLocked {
credentialUnlock()
}
}
ok, ret, updated, err := c.mtop.ConsignContext(ctx, cookieStr, task.OrderID)
}()
detail, err := c.store.Cookies.GetDetails(ctx, task.AccountID)
if err != nil {
return uncertainAction(err)
return err
}
if detail == nil {
return db.ErrNotFound
}
_, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if strings.TrimSpace(detail.Value) == "" && !completeSnapshot {
return fmt.Errorf("账号 %s Cookie 为空", task.AccountID)
}
cookieStr := detail.Value
var mtopCtx context.Context
var cookieSession *mtop.CookieSession
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
} else {
mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
}
ok, ret, updated, callErr := c.mtop.ConsignContext(mtopCtx, cookieStr, task.OrderID)
var persistenceErrs []error
if updated != "" && updated != cookieStr {
if saveErr := c.store.Cookies.UpdateValueExisting(ctx, task.AccountID, updated); saveErr != nil {
runtimeCookie := ""
runtimeCookieChanged := false
sessionHandled := false
value, snapshot, changed := cookieSession.State()
if changed {
sessionHandled = true
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil {
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr))
} else if value != cookieStr {
runtimeCookie = value
runtimeCookieChanged = true
}
}
if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr {
// 注入 mock 或没有权威快照的历史账号保留扁平
// Cookie 兼容路径;扁平结果无法维护旧 Jar 的作用域,
// 因此不得继续保留可能已过期的 snapshot。
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil {
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
} else {
runtimeCookie = updated
runtimeCookieChanged = true
}
if c.senders != nil {
if sender, running := c.senders.Sender(task.AccountID); running {
sender.UpdateCookie(updated)
}
}
credentialUnlock()
credentialLocked = false
if runtimeCookieChanged && c.senders != nil {
if sender, running := c.senders.Sender(task.AccountID); running {
sender.UpdateCookie(runtimeCookie)
}
}
if callErr != nil {
if len(persistenceErrs) > 0 {
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
}
return uncertainAction(callErr)
}
if !ok {
failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
if len(persistenceErrs) > 0 {
@@ -7,6 +7,7 @@ import (
"testing"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -145,3 +146,43 @@ func TestConfirmShipmentQuarantinesKnownRemoteSuccessWhenLocalPersistenceFails(t
t.Fatal("failed local write must not be reported as persisted")
}
}
func TestConfirmShipmentKeepsFlatMockFallbackWhenSessionUnchanged(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
initial := "unb=123; _m_h5_tk=old_1;"
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initial, metadata, 1); err != nil {
t.Fatal(err)
}
updated := "unb=123; _m_h5_tk=mock_new_2;"
sender := &testSender{}
center := New(store, testSenderProvider{sender: sender}, nil)
center.SetMTop(&fakeMTop{consignOk: false, consignRet: []string{"FAIL_SHIP"}, consignUpdated: updated})
err := center.confirmShipment(ctx, Task{
AccountID: "cid", OrderID: "flat-mock-fallback", ForceConfirmShipment: true,
})
if err == nil || !strings.Contains(err.Error(), "FAIL_SHIP") {
t.Fatalf("mock 业务失败应保留原返回语义: %v", err)
}
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
if getErr != nil {
t.Fatal(getErr)
}
if detail.Value != updated {
t.Fatalf("session 未 changed 时未保留扁平/mock 写回路径: %q", detail.Value)
}
if _, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
t.Fatalf("扁平 mock 结果不得伪装成权威 Jar: %s", detail.MetadataJSON)
}
if !strings.Contains(detail.MetadataJSON, `"preserved":true`) {
t.Fatalf("清理旧 snapshot 时丢失其他 metadata: %s", detail.MetadataJSON)
}
if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != updated {
t.Fatalf("扁平/mock 更新未同步运行实例: %+v", sender.cookieUpdates)
}
}
+163 -5
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -14,18 +15,27 @@ import (
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
type automationRoundTripperFunc func(*http.Request) (*http.Response, error)
func (f automationRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
type testSenderProvider struct{ sender *testSender }
func (p testSenderProvider) Sender(string) (MessageSender, bool) { return p.sender, true }
type testSender struct {
texts []string
events *[]string
err error
failAfter int
texts []string
cookieUpdates []string
onCookieUpdate func(string)
events *[]string
err error
failAfter int
}
func (s *testSender) SendText(_ context.Context, _, _, text string) error {
@@ -68,7 +78,12 @@ func TestPartialAutomationRunIsQuarantined(t *testing.T) {
}
}
func (s *testSender) SendImage(context.Context, string, string, string, int64) error { return nil }
func (s *testSender) UpdateCookie(string) {}
func (s *testSender) UpdateCookie(cookieStr string) {
s.cookieUpdates = append(s.cookieUpdates, cookieStr)
if s.onCookieUpdate != nil {
s.onCookieUpdate(cookieStr)
}
}
type testFetcher struct{ detail *OrderDetail }
@@ -654,6 +669,149 @@ func TestCenterOrderPaidSendsCardBeforeConfirmShipment(t *testing.T) {
}
}
func TestConfirmShipmentPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
initialValue := "flat_leak=must-not-send; unb=123; _m_h5_tk=flat_old_1"
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "snapshot_old_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":"yes"}`, snapshot)
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
t.Fatal(err)
}
var requestCookie string
client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
requestCookie = req.Header.Get("Cookie")
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": []string{
"_m_h5_tk=snapshot_new_2; Domain=.goofish.com; Path=/; Secure",
"consign_scope=new; Path=/h5; Secure; HttpOnly",
}},
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
Request: req,
}, nil
})}
lockReleasedBeforeRuntimeUpdate := false
sender := &testSender{onCookieUpdate: func(string) {
acquired := make(chan struct{})
go func() {
unlock := store.LockAccountCredentials("cid")
unlock()
close(acquired)
}()
select {
case <-acquired:
lockReleasedBeforeRuntimeUpdate = true
case <-time.After(500 * time.Millisecond):
}
}}
center := New(store, testSenderProvider{sender: sender}, nil)
center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
err := center.confirmShipment(ctx, Task{
AccountID: "cid", OrderID: "session-parse-error", ForceConfirmShipment: true,
})
var uncertain *uncertainActionError
if !errors.As(err, &uncertain) {
t.Fatalf("远程响应解析失败应进入人工核对: %v", err)
}
for _, want := range []string{"unb=123", "_m_h5_tk=snapshot_old_1", "api_only=api"} {
if !strings.Contains(requestCookie, want) {
t.Fatalf("发货请求 Cookie %q 未使用加锁后重读的权威 Jar,缺少 %q", requestCookie, want)
}
}
for _, unwanted := range []string{"flat_leak=", "document_only="} {
if strings.Contains(requestCookie, unwanted) {
t.Fatalf("发货请求 Cookie %q 泄漏了错误作用域 %q", requestCookie, unwanted)
}
}
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
if getErr != nil {
t.Fatal(getErr)
}
if !strings.Contains(detail.Value, "_m_h5_tk=snapshot_new_2") || strings.Contains(detail.Value, "flat_leak=") {
t.Fatalf("正文解析失败后未优先持久化响应 Cookie Jar: %q", detail.Value)
}
if !strings.Contains(detail.MetadataJSON, `"preserved":"yes"`) {
t.Fatalf("持久化 Jar 时丢失原 metadata: %s", detail.MetadataJSON)
}
gotSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
t.Fatalf("响应后权威 snapshot 丢失: %s", detail.MetadataJSON)
}
values := make(map[string]string, len(gotSnapshot))
for _, cookie := range gotSnapshot {
values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path] = cookie.Value
}
if values["_m_h5_tk|.goofish.com|/"] != "snapshot_new_2" ||
values["consign_scope|h5api.m.goofish.com|/h5"] != "new" ||
values["document_only|www.goofish.com|/im"] != "doc" {
t.Fatalf("响应后 snapshot 作用域不完整: %+v", gotSnapshot)
}
if len(sender.cookieUpdates) != 1 || !strings.Contains(sender.cookieUpdates[0], "_m_h5_tk=snapshot_new_2") {
t.Fatalf("运行实例未同步已持久化的 Cookie: %+v", sender.cookieUpdates)
}
if !lockReleasedBeforeRuntimeUpdate {
t.Fatal("运行实例 Cookie 必须在账号凭证锁外更新")
}
}
func TestConfirmShipmentPropagatesAuthoritativeEmptySession(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
ctx := context.Background()
initialValue := "unb=123; _m_h5_tk=old_1"
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":true}`, []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "old_1", Domain: ".goofish.com", Path: "/", Secure: true},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, "cid", initialValue, metadata, 1); err != nil {
t.Fatal(err)
}
client := &http.Client{Transport: automationRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": []string{
"unb=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
"_m_h5_tk=; Max-Age=-1; Domain=.goofish.com; Path=/; Secure",
}},
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
Request: req,
}, nil
})}
sender := &testSender{}
center := New(store, testSenderProvider{sender: sender}, nil)
center.SetMTop(&mtop.ClientImpl{HTTPClient: client, ConsignURL: mtop.ConsignAPI})
err := center.confirmShipment(ctx, Task{
AccountID: "cid", OrderID: "authoritative-empty-session", ForceConfirmShipment: true,
})
var uncertain *uncertainActionError
if !errors.As(err, &uncertain) {
t.Fatalf("删除凭证后的解析失败应进入人工核对: %v", err)
}
detail, getErr := store.Cookies.GetDetails(ctx, "cid")
if getErr != nil {
t.Fatal(getErr)
}
if detail.Value != "" {
t.Fatalf("权威空 Jar 未持久化: %q", detail.Value)
}
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok || snapshot == nil || len(snapshot) != 0 {
t.Fatalf("权威空 snapshot 语义丢失: ok=%v snapshot=%#v metadata=%s", ok, snapshot, detail.MetadataJSON)
}
if len(sender.cookieUpdates) != 1 || sender.cookieUpdates[0] != "" {
t.Fatalf("权威空 Jar 未在锁外通知运行实例: %#v", sender.cookieUpdates)
}
}
func TestManualFullDeliveryIsImmediateIdempotentAndForcesConfirmation(t *testing.T) {
store, cleanup := newAutomationTestStore(t)
defer cleanup()
+179 -80
View File
@@ -6,8 +6,8 @@ import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/playwright-community/playwright-go"
@@ -19,6 +19,9 @@ const (
quickRenewPageLoadWait = 3 * time.Second
quickRenewAfterClick = 5 * time.Second
quickRenewTimeoutMS = 30000
officialAutoLoginWait = 10 * time.Second
officialFetchDrainWait = 30 * time.Second
officialReloadWait = 5 * time.Second
)
var (
@@ -103,19 +106,30 @@ func passwordPersistentContextOptions(headless bool) playwright.BrowserTypeLaunc
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
if cookieStr == "" {
return "", fmt.Errorf("Cookie为空,无法浏览器续期")
}
newCookies, _, err := m.BrowserQuickRenewSnapshot(ctx, cookieID, cookieStr, nil, headless)
return newCookies, err
}
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, nil, quickRenewHeadless(headless))
// BrowserQuickRenewSnapshot is the full-fidelity variant of BrowserQuickRenew.
// Callers that persist cookie metadata should use it directly: Chromium's final
// jar is authoritative for both deletions and attributes such as expiry/path.
func (m *Manager) BrowserQuickRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
if cookieStr == "" && snapshot == nil {
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法浏览器续期")
}
// 持久化的扁平值始终以消息页为 canonical scope;这里也必须按 /im
// 解释,避免漏掉或错误映射 Path=/im 的连接凭证。
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, quickRenewHeadless(headless))
if err != nil {
return "", err
return "", nil, err
}
defer release()
page, err := bctx.NewPage()
if err != nil {
return "", fmt.Errorf("新建 page 失败: %w", err)
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
@@ -128,120 +142,205 @@ func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr str
time.Sleep(quickRenewPageLoadWait)
hasQuickEnter := false
var renewErr error
if err := verifyHomeLoginState(page); err != nil {
if errors.Is(err, ErrSecurityVerification) {
return "", err
}
hasQuickEnter = clickQuickEnter(page)
if !hasQuickEnter {
return "", err
}
time.Sleep(quickRenewAfterClick)
if err := verifyHomeLoginState(page); err != nil {
return "", err
renewErr = err
} else {
hasQuickEnter = clickQuickEnter(page)
if !hasQuickEnter {
renewErr = err
} else {
time.Sleep(quickRenewAfterClick)
renewErr = verifyHomeLoginState(page)
}
}
}
all, err := bctx.Cookies()
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
if err != nil {
return "", fmt.Errorf("提取 cookie 失败: %w", err)
return "", nil, errors.Join(renewErr, err)
}
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", fmt.Errorf("点击[快速进入]后未获取到浏览器Cookie")
renewErr = errors.Join(renewErr, fmt.Errorf("点击[快速进入]后浏览器 Cookie Jar 为空"))
}
if renewErr != nil {
return newCookies, newSnapshot, renewErr
}
cookieFromBrowser := cookierefresh.CookieStringFromSnapshot(newSnapshot)
merged := cookierefresh.MergeOriginalFields(cookieStr, cookieFromBrowser)
m.logger.Info("浏览器续期成功", "cookieID", cookieID, "has_quick_enter", hasQuickEnter, "cookie_count", len(newSnapshot))
return merged, nil
return newCookies, newSnapshot, nil
}
// CookiesRefreshSnapshot executes the optional browser-backed renewal in the
// account's persistent profile. One ordinary page load is enough to run the
// site's own auto-login plugin; repeated reloads create an avoidable risk
// signal and are deliberately not used.
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
if cookieStr == "" && len(snapshot) == 0 {
return "", nil, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
func (m *Manager) CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error) {
if cookieStr == "" && snapshot == nil {
return "", nil, false, fmt.Errorf("Cookie为空,且无完整Cookie快照,无法执行续期")
}
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
effectiveSnapshot := reconcileSnapshotWithCurrentCookie(snapshot, cookieStr, goofishIMURL)
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, effectiveSnapshot, cookiesRefreshHeadless(headless))
if err != nil {
return "", nil, err
return "", nil, false, err
}
defer release()
page, err := bctx.NewPage()
if err != nil {
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
return "", nil, false, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
navigate := func() error {
_, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
})
return err
}
if expectsOfficialSilentLogin(cookieStr) {
response, err := page.ExpectResponse("**/newlogin/silentHasLogin.do**", navigate, playwright.PageExpectResponseOptions{Timeout: playwright.Float(7000)})
if err != nil {
return "", nil, fmt.Errorf("等待官网静默续期请求完成: %w", err)
}
if response == nil || response.Status() < 200 || response.Status() >= 300 {
return "", nil, fmt.Errorf("官网静默续期 HTTP 状态异常")
}
// 插件在业务成功后立即 location.reload;等待短暂调度窗口,再等待
// 新文档进入 DOMContentLoaded,避免提取续期前 Cookie。
page.WaitForTimeout(500)
_ = page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
State: playwright.LoadStateDomcontentloaded,
Timeout: playwright.Float(5000),
})
} else if err := navigate(); err != nil {
m.logger.Warn("COOKIES续期访问消息页异常", "cookieID", cookieID, "err", err)
}
if err := verifyHomeLoginState(page); err != nil {
return "", nil, err
reloaded, renewErr := navigateOfficialRenewPage(ctx, page)
if renewErr == nil {
renewErr = verifyHomeLoginState(page)
}
newCookies, newSnapshot, err := readAuthoritativeCookieJar(bctx, goofishIMURL)
if err != nil {
return "", nil, reloaded, errors.Join(renewErr, err)
}
if len(newSnapshot) == 0 {
renewErr = errors.Join(renewErr, fmt.Errorf("消息页执行后浏览器 Cookie Jar 为空"))
}
if renewErr != nil {
return newCookies, newSnapshot, reloaded, renewErr
}
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot), "official_reload", reloaded)
return newCookies, newSnapshot, reloaded, nil
}
func navigateOfficialRenewPage(ctx context.Context, page playwright.Page) (bool, error) {
silentStarted := make(chan struct{}, 1)
silentSettled := make(chan bool, 1)
reloadCommitted := make(chan struct{}, 1)
var navigationArmed atomic.Bool
page.OnRequest(func(request playwright.Request) {
if isSilentHasLoginURL(request.URL()) {
select {
case silentStarted <- struct{}{}:
default:
}
}
})
page.OnFrameNavigated(func(frame playwright.Frame) {
if navigationArmed.Load() && frame.ParentFrame() == nil && strings.HasPrefix(frame.URL(), goofishIMURL) {
select {
case reloadCommitted <- struct{}{}:
default:
}
}
})
page.OnRequestFinished(func(request playwright.Request) {
if isSilentHasLoginURL(request.URL()) {
select {
case silentSettled <- true:
default:
}
}
})
page.OnRequestFailed(func(request playwright.Request) {
if isSilentHasLoginURL(request.URL()) {
select {
case silentSettled <- false:
default:
}
}
})
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
return false, fmt.Errorf("COOKIES续期访问消息页: %w", err)
}
navigationArmed.Store(true)
// The plugin starts after the SPA hydrates, then waits 2s before issuing
// silentHasLogin. Observe the actual request instead of assuming hydration
// completed at DOMContentLoaded; navigation Set-Cookie may also change the
// sdkSilent/long-login branch.
observeTimer := time.NewTimer(officialAutoLoginWait)
requestStarted := false
select {
case <-ctx.Done():
observeTimer.Stop()
return false, ctx.Err()
case <-silentStarted:
requestStarted = true
observeTimer.Stop()
case <-observeTimer.C:
}
if requestStarted {
// The plugin's 2s Promise timeout does not abort fetch. Keep the page
// alive until Chromium finishes the response body (and applies Set-Cookie), while
// leaving reload/no-reload entirely to the official JavaScript.
drainTimer := time.NewTimer(officialFetchDrainWait)
requestFinished := false
select {
case requestFinished = <-silentSettled:
drainTimer.Stop()
case <-ctx.Done():
drainTimer.Stop()
return false, ctx.Err()
case <-drainTimer.C:
}
if requestFinished {
reloadTimer := time.NewTimer(officialReloadWait)
select {
case <-reloadCommitted:
reloadTimer.Stop()
if err := page.WaitForLoadState(playwright.PageWaitForLoadStateOptions{
State: playwright.LoadStateDomcontentloaded, Timeout: playwright.Float(10000),
}); err != nil {
return true, fmt.Errorf("等待官网续期 reload 完成: %w", err)
}
return true, nil
case <-ctx.Done():
reloadTimer.Stop()
return false, ctx.Err()
case <-reloadTimer.C:
}
}
}
// Absence of a reload is the official outcome for fatigue, timeout or a
// non-100 business result.
return false, nil
}
func readAuthoritativeCookieJar(bctx playwright.BrowserContext, rawURL string) (string, []cookierefresh.BrowserCookie, error) {
all, err := bctx.Cookies()
if err != nil {
return "", nil, fmt.Errorf("提取 cookie 失败: %w", err)
return "", nil, fmt.Errorf("提取浏览器 Cookie Jar: %w", err)
}
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", nil, fmt.Errorf("页面刷新完成,但未获取到浏览器Cookie")
snapshot := cookieSnapshotFromPlaywright(all)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
newCookies := cookierefresh.CookieStringFromSnapshot(newSnapshot)
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot))
return newCookies, newSnapshot, nil
return currentCookieHeader(snapshot, rawURL), snapshot, nil
}
func expectsOfficialSilentLogin(cookieStr string) bool {
cookies := cookierefresh.ParseCookieString(cookieStr)
now := time.Now().UnixMilli()
if futureCookieMillis(cookies["sdkSilent"], now) {
return false
}
return futureCookieMillis(cookies["havana_lgc_exp"], now) || futureCookieMillis(cookies["cookie3_bak_exp"], now)
func isSilentHasLoginURL(rawURL string) bool {
return strings.Contains(rawURL, "/newlogin/silentHasLogin.do")
}
func futureCookieMillis(raw string, now int64) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
func reconcileSnapshotWithCurrentCookie(snapshot []cookierefresh.BrowserCookie, cookieStr, rawURL string) []cookierefresh.BrowserCookie {
if snapshot == nil {
return nil
}
value, err := strconv.ParseInt(raw, 10, 64)
if err != nil {
return true
if len(snapshot) == 0 {
return []cookierefresh.BrowserCookie{}
}
return value > now
if strings.TrimSpace(cookieStr) == "" {
return cookierefresh.NormalizeSnapshot(snapshot)
}
return credentialCookieSnapshotForURL(snapshot, parseCookieStr(cookieStr), rawURL)
}
// CookieRenewSnapshot 兼容旧调用,等价于定时 COOKIES 快照续期。
func (m *Manager) CookieRenewSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error) {
return m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
cookies, refreshed, _, err := m.CookiesRefreshSnapshot(ctx, cookieID, cookieStr, snapshot, headless)
return cookies, refreshed, err
}
func clickQuickEnter(page playwright.Page) bool {
@@ -404,7 +503,7 @@ func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cooki
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if len(snapshot) > 0 {
if snapshot != nil {
if err := bctx.ClearCookies(); err != nil {
_ = bctx.Close()
releaseSlot()
+102
View File
@@ -0,0 +1,102 @@
package browser
import (
"testing"
"xianyu-go/internal/xianyu/cookierefresh"
)
func TestCredentialCookieSnapshotUsesCurrentFlatCookieAsAuthority(t *testing.T) {
existing := []cookierefresh.BrowserCookie{
{Name: "session", Value: "stale", Domain: ".goofish.com", Path: "/", Expires: 123, HTTPOnly: true, Secure: true, SameSite: "Lax"},
{Name: "removed", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "passport", Value: "keep", Domain: ".taobao.com", Path: "/", Secure: true},
}
got := credentialCookieSnapshot(existing, map[string]string{
"session": "fresh",
"new": "value",
})
if len(got) != 3 {
t.Fatalf("snapshot len=%d, want 3: %+v", len(got), got)
}
byName := make(map[string]cookierefresh.BrowserCookie, len(got))
for _, cookie := range got {
byName[cookie.Name] = cookie
}
session := byName["session"]
if session.Value != "fresh" || session.Expires != 123 || !session.HTTPOnly || session.SameSite != "Lax" {
t.Fatalf("existing attributes or fresh value were lost: %+v", session)
}
if _, exists := byName["removed"]; exists {
t.Fatalf("cookie absent from current flat value was resurrected: %+v", got)
}
if passport := byName["passport"]; passport.Value != "keep" || passport.Domain != ".taobao.com" {
t.Fatalf("out-of-scope cookie was lost: %+v", passport)
}
added := byName["new"]
if added.Value != "value" || added.Domain != goofishDot || added.Path != "/" || !added.Secure {
t.Fatalf("new cookie defaults mismatch: %+v", added)
}
}
func TestCredentialCookieSnapshotPreservesAmbiguousSameNameScopes(t *testing.T) {
existing := []cookierefresh.BrowserCookie{
{Name: "token", Value: "old-root", Domain: ".goofish.com", Path: "/"},
{Name: "token", Value: "old-im", Domain: "www.goofish.com", Path: "/im", HTTPOnly: true},
}
got := credentialCookieSnapshot(existing, map[string]string{"token": "fresh"})
if len(got) != 2 {
t.Fatalf("same-name scoped cookies collapsed: %+v", got)
}
values := map[string]string{}
for _, cookie := range got {
values[cookie.Path] = cookie.Value
}
if values["/"] != "old-root" || values["/im"] != "old-im" {
t.Fatalf("ambiguous flat value corrupted scoped cookies: %+v", got)
}
}
func TestReconcileSnapshotWithCurrentCookie(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{{Name: "session", Value: "old", Domain: ".goofish.com", Path: "/", Expires: 456}}
got := reconcileSnapshotWithCurrentCookie(snapshot, "session=new", goofishIMURL)
if len(got) != 1 || got[0].Value != "new" || got[0].Expires != 456 {
t.Fatalf("flat cookie did not update snapshot without losing attributes: %+v", got)
}
got = reconcileSnapshotWithCurrentCookie(snapshot, "", goofishIMURL)
if len(got) != 1 || got[0].Value != "old" {
t.Fatalf("snapshot-only renewal input was discarded: %+v", got)
}
got = reconcileSnapshotWithCurrentCookie([]cookierefresh.BrowserCookie{}, "session=stale", goofishIMURL)
if got == nil || len(got) != 0 {
t.Fatalf("authoritative empty snapshot must not fall back to flat cookies: %#v", got)
}
if got := reconcileSnapshotWithCurrentCookie(nil, "session=legacy", goofishIMURL); got != nil {
t.Fatalf("missing snapshot should preserve the legacy flat-cookie fallback: %#v", got)
}
}
func TestSilentHasLoginURLMatcher(t *testing.T) {
if !isSilentHasLoginURL("https://passport.goofish.com/newlogin/silentHasLogin.do?appName=xianyu") {
t.Fatal("official silentHasLogin request was not recognized")
}
if isSilentHasLoginURL("https://passport.goofish.com/newlogin/hasLogin.do") {
t.Fatal("ordinary hasLogin request must not be treated as silentHasLogin")
}
}
func TestTokenPageURLPatternIsLimitedToIMDocument(t *testing.T) {
for _, rawURL := range []string{goofishIMURL, goofishIMURL + "?spm=test", goofishIMURL + "#messages"} {
if !tokenPageURLPattern.MatchString(rawURL) {
t.Fatalf("expected token page URL match: %s", rawURL)
}
}
for _, rawURL := range []string{goofishHomeURL, goofishIMURL + "/other", "https://h5api.m.goofish.com/im"} {
if tokenPageURLPattern.MatchString(rawURL) {
t.Fatalf("unexpected token page URL match: %s", rawURL)
}
}
}
+6
View File
@@ -81,6 +81,9 @@ func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwri
if c.Expires > 0 {
oc.Expires = playwright.Float(c.Expires)
}
if c.PartitionKey != "" {
oc.PartitionKey = playwright.String(c.PartitionKey)
}
switch c.SameSite {
case "Strict":
oc.SameSite = playwright.SameSiteAttributeStrict
@@ -109,6 +112,9 @@ func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.Browse
if c.SameSite != nil {
bc.SameSite = string(*c.SameSite)
}
if c.PartitionKey != nil {
bc.PartitionKey = *c.PartitionKey
}
out = append(out, bc)
}
return cookierefresh.NormalizeSnapshot(out)
+57 -13
View File
@@ -87,10 +87,12 @@ type Manager struct {
}
type poolEntry struct {
cookieID string
browser playwright.Browser
context playwright.BrowserContext
lastUsed time.Time
cookieID string
browser playwright.Browser
context playwright.BrowserContext
lastUsed time.Time
active int
initialLeaseAvailable bool
}
// NewManager 构造。logger 为 nil 用默认。
@@ -257,6 +259,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
page, err := entry.context.NewPage()
if err != nil {
// context 损坏,丢弃重建一次。
m.releaseEntry(cookieID, entry)
m.evict(cookieID)
entry, err = m.acquireEntry(cookieID, cookieStr, headless)
if err != nil {
@@ -264,12 +267,14 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
}
page, err = entry.context.NewPage()
if err != nil {
m.releaseEntry(cookieID, entry)
m.evict(cookieID)
return nil, nil, fmt.Errorf("新建 page 失败: %w", err)
}
}
release := func() {
_ = page.Close()
m.touch(cookieID)
m.releaseEntry(cookieID, entry)
}
return page, release, nil
}
@@ -277,7 +282,7 @@ func (m *Manager) newPage(ctx context.Context, cookieID, cookieStr string, headl
func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
e.lastUsed = time.Now()
m.claimEntryLocked(e)
m.mu.Unlock()
return e, nil
}
@@ -286,7 +291,6 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
created, err, _ := m.creates.Do(cookieID, func() (any, error) {
m.mu.Lock()
if e, ok := m.pool[cookieID]; ok && e.browser != nil && e.browser.IsConnected() {
e.lastUsed = time.Now()
m.mu.Unlock()
return e, nil
}
@@ -302,9 +306,38 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
if !ok || entry == nil {
return nil, fmt.Errorf("浏览器池创建返回异常")
}
m.mu.Lock()
if current := m.pool[cookieID]; current == entry {
m.claimEntryLocked(entry)
m.mu.Unlock()
} else {
m.mu.Unlock()
return nil, fmt.Errorf("浏览器池条目在获取期间已失效")
}
return entry, nil
}
func (m *Manager) claimEntryLocked(entry *poolEntry) {
entry.lastUsed = time.Now()
if entry.initialLeaseAvailable {
entry.initialLeaseAvailable = false
return
}
entry.active++
}
func (m *Manager) releaseEntry(cookieID string, entry *poolEntry) {
m.mu.Lock()
defer m.mu.Unlock()
if current := m.pool[cookieID]; current != entry {
return
}
if entry.active > 0 {
entry.active--
}
entry.lastUsed = time.Now()
}
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
@@ -334,10 +367,12 @@ func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolE
}
}
entry := &poolEntry{
cookieID: cookieID,
browser: browser,
context: context,
lastUsed: time.Now(),
cookieID: cookieID,
browser: browser,
context: context,
lastUsed: time.Now(),
active: 1,
initialLeaseAvailable: true,
}
m.mu.Lock()
m.pool[cookieID] = entry
@@ -356,6 +391,10 @@ func (m *Manager) touch(cookieID string) {
func (m *Manager) evict(cookieID string) {
m.mu.Lock()
e, ok := m.pool[cookieID]
if ok && e.active > 0 {
m.mu.Unlock()
return
}
delete(m.pool, cookieID)
m.mu.Unlock()
if ok {
@@ -372,12 +411,17 @@ func (m *Manager) evictIfNeeded() {
var oldest *poolEntry
var oldestID string
for id, e := range m.pool {
if e.active > 0 {
continue
}
if oldest == nil || e.lastUsed.Before(oldest.lastUsed) {
oldest = e
oldestID = id
}
}
delete(m.pool, oldestID)
if oldest != nil {
delete(m.pool, oldestID)
}
m.mu.Unlock()
if oldest != nil {
closeEntry(oldest, m.logger)
@@ -390,7 +434,7 @@ func (m *Manager) CleanupIdle() {
m.mu.Lock()
var toClose []*poolEntry
for id, e := range m.pool {
if now.Sub(e.lastUsed) > m.idleTTL {
if e.active == 0 && now.Sub(e.lastUsed) > m.idleTTL {
toClose = append(toClose, e)
delete(m.pool, id)
}
+38
View File
@@ -91,6 +91,44 @@ func TestEvictIfNeededNoopWhenUnderLimit(t *testing.T) {
}
}
func TestEvictIfNeededSkipsActiveEntries(t *testing.T) {
m := newTestManager(2)
m.pool["active-old"] = &poolEntry{cookieID: "active-old", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
m.pool["idle-new"] = &poolEntry{cookieID: "idle-new", lastUsed: time.Now()}
m.evictIfNeeded()
if _, ok := m.pool["active-old"]; !ok {
t.Fatal("正在执行 token 请求的条目不得被淘汰")
}
if _, ok := m.pool["idle-new"]; ok {
t.Fatal("池满时应优先淘汰空闲条目")
}
}
func TestEvictIfNeededAllowsTemporaryOverflowWhenAllActive(t *testing.T) {
m := newTestManager(2)
m.pool["active-1"] = &poolEntry{cookieID: "active-1", lastUsed: time.Now().Add(-2 * time.Hour), active: 1}
m.pool["active-2"] = &poolEntry{cookieID: "active-2", lastUsed: time.Now().Add(-time.Hour), active: 1}
m.evictIfNeeded()
if len(m.pool) != 2 {
t.Fatalf("所有条目活跃时不得强制淘汰,pool=%d", len(m.pool))
}
}
func TestCleanupIdleSkipsActiveEntries(t *testing.T) {
m := newTestManager(3)
m.idleTTL = time.Minute
old := time.Now().Add(-time.Hour)
m.pool["active"] = &poolEntry{cookieID: "active", lastUsed: old, active: 1}
m.pool["idle"] = &poolEntry{cookieID: "idle", lastUsed: old}
m.CleanupIdle()
if _, ok := m.pool["active"]; !ok {
t.Fatal("CleanupIdle 不得关闭仍有租约的条目")
}
if _, ok := m.pool["idle"]; ok {
t.Fatal("CleanupIdle 应清理过期空闲条目")
}
}
// TestMarshalCookies 导出包装器等价 cookieMarshal。
func TestMarshalCookies(t *testing.T) {
got := MarshalCookies(map[string]string{"unb": "1", "cna": "xx"})
+34 -7
View File
@@ -11,6 +11,7 @@ import (
"github.com/playwright-community/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -18,13 +19,15 @@ const mtopOrderDetailURL = "mtop.idle.web.trade.order.detail"
// OrderDetail 订单详情(对齐 engine.OrderDetail)。
type OrderDetail struct {
OrderID string `json:"order_id"`
Quantity string `json:"quantity"`
SpecName string `json:"spec_name"`
SpecValue string `json:"spec_value"`
OrderStatus string `json:"order_status"`
Amount string `json:"amount"`
UpdatedCookies string `json:"-"`
OrderID string `json:"order_id"`
Quantity string `json:"quantity"`
SpecName string `json:"spec_name"`
SpecValue string `json:"spec_value"`
OrderStatus string `json:"order_status"`
Amount string `json:"amount"`
UpdatedCookies string `json:"-"`
CookieSnapshot []cookierefresh.BrowserCookie `json:"-"`
CookieSnapshotComplete bool `json:"-"`
}
// orderStatusMap 移植自 order_fetcher_optimized._parse_api_response。纯映射,可单测。
@@ -48,6 +51,12 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
} else if directErr != nil {
m.logger.Warn("MTop 订单详情获取失败,回退浏览器", "order_id", orderID, "err", directErr)
}
// A shared Chromium context owns one mutable Cookie Jar. Serialize browser
// fallback refreshes for the account so concurrent batch rows cannot clear
// and re-inject different snapshots underneath each other.
browserCredentialLock := m.accountRenewLock("order_credential_" + cookieID)
browserCredentialLock.Lock()
defer browserCredentialLock.Unlock()
if err := m.init(); err != nil {
return nil, err
}
@@ -56,6 +65,11 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
return nil, err
}
defer release()
if session := mtop.CookieSessionFromContext(ctx); session != nil {
if err := syncCredentialCookies(page.Context(), cookieValue, session.Snapshot()); err != nil {
return nil, fmt.Errorf("订单详情同步完整 Cookie Jar: %w", err)
}
}
var mu sync.Mutex
var apiBody map[string]any
@@ -121,6 +135,19 @@ func (m *Manager) FetchOrderDetail(ctx context.Context, orderID, cookieID, cooki
// DOM 补充(金额 / SKU)。
parseDOMContent(page, od)
allCookies, cookieErr := page.Context().Cookies()
if cookieErr != nil {
return nil, fmt.Errorf("读取订单详情浏览器 Cookie Jar: %w", cookieErr)
}
od.CookieSnapshot = cookieSnapshotFromPlaywright(allCookies)
if od.CookieSnapshot == nil {
od.CookieSnapshot = []cookierefresh.BrowserCookie{}
}
od.CookieSnapshotComplete = true
od.UpdatedCookies = currentCookieHeader(od.CookieSnapshot, goofishIMURL)
if session := mtop.CookieSessionFromContext(ctx); session != nil {
session.ReplaceSnapshot(od.CookieSnapshot)
}
if od.Amount == "" {
title, _ := page.Title()
m.logger.Warn("订单详情未解析到实付金额", "order_id", orderID, "page_title", title, "page_url", page.URL(), "api_captured", body != nil, "observed_apis", observedAPIs)
+182 -42
View File
@@ -3,8 +3,11 @@ package browser
import (
"context"
"encoding/json"
"errors"
"fmt"
"regexp"
"strings"
"time"
"github.com/playwright-community/playwright-go"
@@ -13,13 +16,21 @@ import (
"xianyu-go/internal/xianyu/protocol"
)
const tokenRequestTimeoutMS = 20000
var tokenPageURLPattern = regexp.MustCompile(`^https://www\.goofish\.com/im(?:[?#].*)?$`)
// ExecuteTokenRequest sends the signed token request from a real Chromium page
// so TLS, UA, Client Hints, Origin, Referer and the browser cookie jar all agree.
func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowserRequest) (*mtop.TokenBrowserResponse, error) {
if strings.TrimSpace(req.URL) == "" || strings.TrimSpace(req.Cookies) == "" {
if strings.TrimSpace(req.URL) == "" || (strings.TrimSpace(req.Cookies) == "" && req.CookieSnapshot == nil) {
return nil, fmt.Errorf("浏览器 token 请求参数不完整")
}
unb := protocol.TransCookies(req.Cookies)["unb"]
credentialCookies := req.Cookies
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(req.CookieSnapshot, goofishIMURL, "https://goofish.com", time.Now()); authoritative {
credentialCookies = scoped
}
unb := protocol.TransCookies(credentialCookies)["unb"]
if unb == "" {
return nil, fmt.Errorf("浏览器 token 请求缺少 unb")
}
@@ -28,65 +39,155 @@ func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowser
lock.Lock()
defer lock.Unlock()
page, release, err := m.newPage(ctx, credentialID, req.Cookies, true)
page, bctx, releaseEntry, err := m.tokenRequestPage(ctx, credentialID, req.Cookies, req.CookieSnapshot)
if err != nil {
return nil, err
}
defer release()
bctx := page.Context()
if err := syncCredentialCookies(bctx, req.Cookies); err != nil {
m.evict(credentialID)
return nil, fmt.Errorf("浏览器 token 请求同步 Cookie: %w", err)
defer releaseEntry()
m.touch(credentialID)
value, err := page.Evaluate(`async ({url, body, timeout}) => {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
const response = await fetch(url, {
method: 'POST',
credentials: 'include',
signal: controller.signal,
headers: {
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
body
});
return {status: response.status, body: await response.text()};
} finally {
clearTimeout(timer);
}
}`, map[string]any{"url": req.URL, "body": req.Body, "timeout": tokenRequestTimeoutMS})
evalErr := err
all, cookieErr := bctx.Cookies()
if cookieErr != nil {
return nil, errors.Join(wrapTokenBrowserEvalError(evalErr), fmt.Errorf("读取浏览器 token Cookie: %w", cookieErr))
}
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(15000),
}); err != nil {
return nil, fmt.Errorf("浏览器 token 请求初始化站点: %w", err)
snapshot := cookieSnapshotFromPlaywright(all)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
value, err := page.Evaluate(`async ({url, body}) => {
const response = await fetch(url, {
method: 'POST',
credentials: 'include',
headers: {
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded'
},
body
});
return {status: response.status, body: await response.text()};
}`, map[string]any{"url": req.URL, "body": req.Body})
if err != nil {
return nil, fmt.Errorf("浏览器执行 token fetch: %w", err)
browserCookies := currentCookieHeader(snapshot, goofishIMURL)
response := &mtop.TokenBrowserResponse{
UpdatedCookies: browserCookies,
CookieSnapshot: snapshot,
CookieSnapshotComplete: true,
}
if evalErr != nil {
return response, fmt.Errorf("浏览器执行 token fetch: %w", evalErr)
}
raw, err := json.Marshal(value)
if err != nil {
return nil, err
return response, err
}
var result struct {
Status int `json:"status"`
Body string `json:"body"`
}
if err := json.Unmarshal(raw, &result); err != nil {
return nil, fmt.Errorf("解析浏览器 token 响应: %w", err)
return response, fmt.Errorf("解析浏览器 token 响应: %w", err)
}
all, err := bctx.Cookies()
response.Status = result.Status
response.Body = []byte(result.Body)
return response, nil
}
func wrapTokenBrowserEvalError(err error) error {
if err == nil {
return nil
}
return fmt.Errorf("浏览器执行 token fetch: %w", err)
}
// tokenRequestPage keeps one inert /im document for each account credential.
// Its URL and origin are identical to the official message page, so Chromium
// supplies the same Referer/Origin/Cookie/Client-Hints context for token fetches.
// The main document is fulfilled locally on first use: loading the full SPA on
// every reconnect would start another official WebSocket and rerun auto-login,
// neither of which happens for a normal reconnect in an already-open /im tab.
func (m *Manager) tokenRequestPage(ctx context.Context, credentialID, cookieStr string, snapshot []cookierefresh.BrowserCookie) (playwright.Page, playwright.BrowserContext, func(), error) {
if err := ctx.Err(); err != nil {
return nil, nil, nil, err
}
if err := m.init(); err != nil {
return nil, nil, nil, err
}
entry, err := m.acquireEntry(credentialID, cookieStr, true)
if err != nil {
return nil, fmt.Errorf("读取浏览器 token Cookie: %w", err)
return nil, nil, nil, err
}
browserCookies := cookierefresh.CookieStringFromSnapshot(cookieSnapshotFromPlaywright(all))
return &mtop.TokenBrowserResponse{
Status: result.Status,
Body: []byte(result.Body),
UpdatedCookies: cookierefresh.MergeOriginalFields(req.Cookies, browserCookies),
}, nil
release := func() { m.releaseEntry(credentialID, entry) }
if err := syncCredentialCookies(entry.context, cookieStr, snapshot); err != nil {
release()
m.evict(credentialID)
return nil, nil, nil, fmt.Errorf("浏览器 token 请求同步 Cookie: %w", err)
}
for _, candidate := range entry.context.Pages() {
if !candidate.IsClosed() && tokenPageURLPattern.MatchString(candidate.URL()) {
return candidate, entry.context, release, nil
}
}
page, err := entry.context.NewPage()
if err != nil {
release()
m.evict(credentialID)
return nil, nil, nil, fmt.Errorf("浏览器 token 请求新建消息页: %w", err)
}
route := func(route playwright.Route) {
request := route.Request()
if request.IsNavigationRequest() && request.ResourceType() == "document" {
_ = route.Fulfill(playwright.RouteFulfillOptions{
Status: playwright.Int(200),
ContentType: playwright.String("text/html; charset=utf-8"),
Body: playwright.String("<!doctype html><html><head><meta charset=\"utf-8\"><title>Goofish IM</title></head><body></body></html>"),
})
return
}
_ = route.Continue()
}
if err := page.Route(tokenPageURLPattern, route, 1); err != nil {
_ = page.Close()
release()
m.evict(credentialID)
return nil, nil, nil, fmt.Errorf("浏览器 token 请求初始化消息页路由: %w", err)
}
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(15000),
}); err != nil {
_ = page.Close()
release()
m.evict(credentialID)
return nil, nil, nil, fmt.Errorf("浏览器 token 请求初始化消息页: %w", err)
}
return page, entry.context, release, nil
}
// syncCredentialCookies updates a reused credential context without flattening
// attributes already observed from Chromium. Unknown cookies use the narrow
// goofish default only on their first import; later server updates retain their
// real domain, path, expiry, SameSite, Secure and HttpOnly fields.
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string) error {
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string, snapshots ...[]cookierefresh.BrowserCookie) error {
if len(snapshots) > 0 && snapshots[0] != nil {
// A Chromium snapshot is the complete authoritative jar, including an
// explicitly empty jar. Do not flatten it through cookieStr: doing so
// loses scopes and can resurrect cookies Chromium already deleted.
preserved := cookierefresh.NormalizeSnapshot(snapshots[0])
if err := bctx.ClearCookies(); err != nil {
return err
}
if len(preserved) == 0 {
return nil
}
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
}
incoming := parseCookieStr(cookieStr)
if len(incoming) == 0 {
return fmt.Errorf("Cookie为空或格式错误")
@@ -95,7 +196,8 @@ func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string) err
if err != nil {
return err
}
preserved := credentialCookieSnapshot(cookieSnapshotFromPlaywright(existing), incoming)
basis := cookieSnapshotFromPlaywright(existing)
preserved := credentialCookieSnapshotForURL(basis, incoming, goofishIMURL)
if err := bctx.ClearCookies(); err != nil {
return err
}
@@ -103,14 +205,42 @@ func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string) err
}
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
preserved := make([]cookierefresh.BrowserCookie, 0, len(incoming))
return credentialCookieSnapshotForURL(existing, incoming, goofishIMURL)
}
func credentialCookieSnapshotForURL(existing []cookierefresh.BrowserCookie, incoming map[string]string, rawURL string) []cookierefresh.BrowserCookie {
preserved := make([]cookierefresh.BrowserCookie, 0, len(existing)+len(incoming))
matched := make(map[string]bool, len(incoming))
counts := make(map[string]int, len(existing))
for _, cookie := range cookierefresh.NormalizeSnapshot(existing) {
counts[cookie.Name]++
}
for _, cookie := range existing {
// A flat Cookie header only describes cookies applicable to its source
// URL. Keep absent cookies for passport/other paths untouched; otherwise
// a goofish header would silently erase the rest of Chromium's jar. When
// the flat representation does carry the same name, update its value for
// backward compatibility with historical all-domain flattened snapshots.
if !cookieScopeMatches(cookie, rawURL) {
if value, ok := incoming[cookie.Name]; ok {
if counts[cookie.Name] == 1 && cookie.PartitionKey == "" {
cookie.Value = value
}
matched[cookie.Name] = true
}
preserved = append(preserved, cookie)
continue
}
value, ok := incoming[cookie.Name]
if !ok {
continue
}
cookie.Value = value
// A flat string cannot identify which Domain/Path/PartitionKey owns a
// value when the same name occurs more than once. Preserve those scoped
// values instead of corrupting every variant with one ambiguous value.
if counts[cookie.Name] == 1 {
cookie.Value = value
}
preserved = append(preserved, cookie)
matched[cookie.Name] = true
}
@@ -119,8 +249,18 @@ func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming m
continue
}
preserved = append(preserved, cookierefresh.BrowserCookie{
Name: name, Value: value, Domain: goofishDot, Path: "/",
Name: name, Value: value, Domain: goofishDot, Path: "/", Secure: true,
})
}
return cookierefresh.NormalizeSnapshot(preserved)
}
func cookieScopeMatches(cookie cookierefresh.BrowserCookie, rawURL string) bool {
header, _ := cookierefresh.ScopedCookieHeaderForRequest([]cookierefresh.BrowserCookie{cookie}, rawURL, "https://goofish.com", time.Unix(0, 0))
return header != ""
}
func currentCookieHeader(snapshot []cookierefresh.BrowserCookie, rawURL string) string {
header, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, rawURL, "https://goofish.com", time.Now())
return header
}
+106 -23
View File
@@ -3,6 +3,7 @@ package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
@@ -43,7 +44,8 @@ func (c *Cookies) UpdateSettings(ctx context.Context, cookieID string, input Acc
}
defer tx.Rollback()
var ownerID int64
if err := tx.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&ownerID); err != nil {
var metadataJSON string
if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`user_id,COALESCE(metadata_json,'')`), cookieID).Scan(&ownerID, &metadataJSON); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return 0, ErrNotFound
}
@@ -62,6 +64,16 @@ func (c *Cookies) UpdateSettings(ctx context.Context, cookieID string, input Acc
}
assignments = append(assignments, "value=?")
args = append(args, encrypted)
plainMetadata, err := c.codec.decrypt(cookieMetadataScope, cookieID, metadataJSON)
if err != nil {
return 0, err
}
cleanMetadata, err := c.codec.encrypt(cookieMetadataScope, cookieID, stripCookieSnapshotMetadata(plainMetadata))
if err != nil {
return 0, err
}
assignments = append(assignments, "metadata_json=?")
args = append(args, cleanMetadata)
}
if input.Remark != nil {
assignments = append(assignments, "remark=?")
@@ -186,20 +198,14 @@ func (c *Cookies) UpdateValueOwned(ctx context.Context, cookieID, cookieValue st
if err != nil {
return err
}
res, err := c.DB.ExecContext(ctx,
`UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
encrypted, cookieID, userID)
tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
return rowsErr
} else if n == 1 {
return nil
}
defer tx.Rollback()
var existingOwner int64
if err := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&existingOwner); err != nil {
var rawMetadata string
if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`user_id,COALESCE(metadata_json,'')`), cookieID).Scan(&existingOwner, &rawMetadata); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
@@ -208,7 +214,22 @@ func (c *Cookies) UpdateValueOwned(ctx context.Context, cookieID, cookieValue st
if existingOwner != userID {
return ErrForbidden
}
return ErrNotFound
metadata, err := c.metadataWithoutCookieSnapshotValue(cookieID, rawMetadata)
if err != nil {
return err
}
res, err := tx.ExecContext(ctx,
`UPDATE cookies SET value=?,metadata_json=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
encrypted, metadata, cookieID, userID)
if err != nil {
return err
}
if n, rowsErr := res.RowsAffected(); rowsErr != nil {
return rowsErr
} else if n > 1 {
return fmt.Errorf("更新 cookie 影响了 %d 行", n)
}
return tx.Commit()
}
// UpdateValueExisting 供续期和运行时写回使用,只能更新现存账号。
@@ -221,8 +242,24 @@ func (c *Cookies) UpdateValueExisting(ctx context.Context, cookieID, cookieValue
if err != nil {
return err
}
res, err := c.DB.ExecContext(ctx,
`UPDATE cookies SET value=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, encrypted, cookieID)
tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var rawMetadata string
if err := tx.QueryRowContext(ctx, c.cookieSelectForUpdate(`COALESCE(metadata_json,'')`), cookieID).Scan(&rawMetadata); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return ErrNotFound
}
return err
}
metadata, err := c.metadataWithoutCookieSnapshotValue(cookieID, rawMetadata)
if err != nil {
return err
}
res, err := tx.ExecContext(ctx,
`UPDATE cookies SET value=?,metadata_json=?,updated_at=CURRENT_TIMESTAMP WHERE id=?`, encrypted, metadata, cookieID)
if err != nil {
return err
}
@@ -230,10 +267,44 @@ func (c *Cookies) UpdateValueExisting(ctx context.Context, cookieID, cookieValue
if err != nil {
return err
}
if n != 1 {
return ErrNotFound
if n > 1 {
return fmt.Errorf("更新 cookie 影响了 %d 行", n)
}
return nil
return tx.Commit()
}
func (c *Cookies) cookieSelectForUpdate(columns string) string {
query := `SELECT ` + columns + ` FROM cookies WHERE id=?`
if c.Dialect == DialectMySQL || c.Dialect == DialectPostgres {
query += ` FOR UPDATE`
}
return query
}
func (c *Cookies) metadataWithoutCookieSnapshotValue(cookieID, raw string) (string, error) {
plain, err := c.codec.decrypt(cookieMetadataScope, cookieID, raw)
if err != nil {
return "", err
}
return c.codec.encrypt(cookieMetadataScope, cookieID, stripCookieSnapshotMetadata(plain))
}
func stripCookieSnapshotMetadata(metadata string) string {
if strings.TrimSpace(metadata) == "" {
return ""
}
var values map[string]any
if err := json.Unmarshal([]byte(metadata), &values); err != nil {
// 无法解析的历史 metadata 本来也不能被当作快照使用,原样保留。
return metadata
}
delete(values, "cookies_refresh_snapshot")
delete(values, "cookie_refresh_snapshot")
raw, err := json.Marshal(values)
if err != nil {
return metadata
}
return string(raw)
}
// Save 保留给历史调用和测试夹具使用。新业务代码应选择 CreateOwned、
@@ -364,6 +435,10 @@ func (c *Cookies) GetDetails(ctx context.Context, cookieID string) (*CookieDetai
if err != nil {
return nil, err
}
d.MetadataJSON, err = c.codec.decrypt(cookieMetadataScope, d.ID, d.MetadataJSON)
if err != nil {
return nil, err
}
d.Password, err = c.codec.decrypt("login-password", d.ID, d.Password)
if err != nil {
return nil, err
@@ -497,20 +572,28 @@ func (c *Cookies) GetStatus(ctx context.Context, cookieID string) bool {
// Status 返回账号启用状态;没有 cookie_status 记录时按启用处理,数据库错误不再静默放行。
func (c *Cookies) Status(ctx context.Context, cookieID string) (bool, error) {
enabled, _, err := c.StatusWithReason(ctx, cookieID)
return enabled, err
}
// StatusWithReason 原子语义地读取账号当前启用状态和禁用原因;调用方应在
// Store.LockAccountCredentials 保护下使用,以复核列表查询后的最新状态。
func (c *Cookies) StatusWithReason(ctx context.Context, cookieID string) (bool, string, error) {
var exists bool
if err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cookies WHERE id=?)`, cookieID).Scan(&exists); err != nil {
return false, err
return false, "", err
}
if !exists {
return false, ErrNotFound
return false, "", ErrNotFound
}
var enabled int
err := c.DB.QueryRowContext(ctx, `SELECT enabled FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled)
var reason string
err := c.DB.QueryRowContext(ctx, `SELECT enabled,COALESCE(disable_reason,'') FROM cookie_status WHERE cookie_id=?`, cookieID).Scan(&enabled, &reason)
if errors.Is(err, sql.ErrNoRows) {
return true, nil
return true, "", nil
}
if err != nil {
return false, err
return false, "", err
}
return enabled != 0, nil
return enabled != 0, reason, nil
}
+48 -5
View File
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
)
@@ -70,7 +71,7 @@ func (c *Cookies) AllRenewalAccounts(ctx context.Context) ([]RenewalAccount, err
return nil, err
}
defer rows.Close()
return scanRenewalAccounts(rows)
return c.scanRenewalAccounts(rows)
}
// ActiveRenewalAccounts 返回启用账号,用于 WS/API 续期类任务。
@@ -87,10 +88,10 @@ func (c *Cookies) ActiveRenewalAccounts(ctx context.Context) ([]RenewalAccount,
return nil, err
}
defer rows.Close()
return scanRenewalAccounts(rows)
return c.scanRenewalAccounts(rows)
}
func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
func (c *Cookies) scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
var out []RenewalAccount
for rows.Next() {
var a RenewalAccount
@@ -100,6 +101,19 @@ func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
}
a.Enabled = enabled != 0
a.ShowBrowser = showBrowser != 0
var err error
a.Value, err = c.codec.decrypt("cookie", a.ID, a.Value)
if err != nil {
return nil, fmt.Errorf("解密账号 %s Cookie: %w", a.ID, err)
}
a.Password, err = c.codec.decrypt("login-password", a.ID, a.Password)
if err != nil {
return nil, fmt.Errorf("解密账号 %s 登录密码: %w", a.ID, err)
}
a.MetadataJSON, err = c.codec.decrypt(cookieMetadataScope, a.ID, a.MetadataJSON)
if err != nil {
return nil, fmt.Errorf("解密账号 %s Cookie metadata: %w", a.ID, err)
}
out = append(out, a)
}
return out, rows.Err()
@@ -107,17 +121,46 @@ func scanRenewalAccounts(rows *sql.Rows) ([]RenewalAccount, error) {
// UpdateRenewalCookie 保存续期后的 Cookie,同时写入浏览器快照和最后续期时间。
func (c *Cookies) UpdateRenewalCookie(ctx context.Context, cookieID, cookieValue, metadataJSON string, lastRefreshAt int64) error {
if strings.TrimSpace(cookieID) == "" {
return errors.New("账号 ID 不能为空")
}
if lastRefreshAt <= 0 {
lastRefreshAt = time.Now().Unix()
}
_, err := c.DB.ExecContext(ctx,
encryptedCookie, err := c.codec.encrypt("cookie", cookieID, cookieValue)
if err != nil {
return fmt.Errorf("加密 Cookie: %w", err)
}
encryptedMetadata, err := c.codec.encrypt(cookieMetadataScope, cookieID, metadataJSON)
if err != nil {
return fmt.Errorf("加密 Cookie metadata: %w", err)
}
res, err := c.DB.ExecContext(ctx,
`UPDATE cookies
SET value=?, metadata_json=?, last_refresh_at=?, updated_at=CURRENT_TIMESTAMP
WHERE id=?`,
cookieValue, metadataJSON, lastRefreshAt, cookieID)
encryptedCookie, encryptedMetadata, lastRefreshAt, cookieID)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows > 1 {
return fmt.Errorf("更新续期 Cookie 影响了 %d 行", rows)
}
if rows == 0 {
// MySQL 默认报告“实际变更行数”,同值且同秒更新可能返回 0;
// 只有记录确实不存在时才应映射为 ErrNotFound。
var exists bool
if err := c.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cookies WHERE id=?)`, cookieID).Scan(&exists); err != nil {
return err
}
if !exists {
return ErrNotFound
}
}
return nil
}
+125
View File
@@ -0,0 +1,125 @@
package db
import (
"context"
"errors"
"strings"
"testing"
)
func TestUpdateRenewalCookieEncryptsCookieAndMetadataAtRest(t *testing.T) {
t.Setenv("XIANYU_DATA_KEY", "renewal-encryption-key")
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "renewal-owner", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create owner: ok=%v err=%v", ok, err)
}
owner, _ := store.Users.GetByUsername(ctx, "renewal-owner")
if err := store.Cookies.CreateOwned(ctx, "renewal-cookie", "old=1", owner.ID); err != nil {
t.Fatal(err)
}
metadata := `{"cookies_refresh_snapshot":[{"name":"token","value":"metadata-secret","domain":".goofish.com","path":"/"}],"other":true}`
if err := store.Cookies.UpdateRenewalCookie(ctx, "renewal-cookie", "token=cookie-secret", metadata, 12345); err != nil {
t.Fatal(err)
}
var rawCookie, rawMetadata string
if err := store.DB.QueryRowContext(ctx, `SELECT value,metadata_json FROM cookies WHERE id=?`, "renewal-cookie").Scan(&rawCookie, &rawMetadata); err != nil {
t.Fatal(err)
}
for name, raw := range map[string]string{"cookie": rawCookie, "metadata": rawMetadata} {
if !strings.HasPrefix(raw, encryptedValuePrefix) || strings.Contains(raw, "secret") {
t.Fatalf("%s was not encrypted at rest: %q", name, raw)
}
}
detail, err := store.Cookies.GetDetails(ctx, "renewal-cookie")
if err != nil {
t.Fatal(err)
}
if detail.Value != "token=cookie-secret" || detail.MetadataJSON != metadata || detail.LastRefreshAt != 12345 {
t.Fatalf("detail=%+v", detail)
}
accounts, err := store.Cookies.ActiveRenewalAccounts(ctx)
if err != nil || len(accounts) != 1 {
t.Fatalf("accounts=%+v err=%v", accounts, err)
}
if accounts[0].Value != detail.Value || accounts[0].MetadataJSON != metadata {
t.Fatalf("renewal account not decrypted: %+v", accounts[0])
}
}
func TestUpdateRenewalCookieRejectsMissingAccount(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
err := store.Cookies.UpdateRenewalCookie(context.Background(), "missing", "a=1", `{}`, 1)
if !errors.Is(err, ErrNotFound) {
t.Fatalf("err=%v want ErrNotFound", err)
}
}
func TestFlatCookieUpdateClearsSnapshotAndPreservesOtherMetadata(t *testing.T) {
t.Setenv("XIANYU_DATA_KEY", "flat-update-metadata-key")
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "flat-owner", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create owner: ok=%v err=%v", ok, err)
}
owner, _ := store.Users.GetByUsername(ctx, "flat-owner")
if err := store.Cookies.CreateOwned(ctx, "flat-cookie", "sid=old", owner.ID); err != nil {
t.Fatal(err)
}
metadata := `{"cookies_refresh_snapshot":[{"name":"sid","value":"old","domain":".goofish.com","path":"/"}],"other":true}`
if err := store.Cookies.UpdateRenewalCookie(ctx, "flat-cookie", "sid=old", metadata, 1); err != nil {
t.Fatal(err)
}
if err := store.Cookies.UpdateValueExisting(ctx, "flat-cookie", "sid=fresh"); err != nil {
t.Fatal(err)
}
detail, err := store.Cookies.GetDetails(ctx, "flat-cookie")
if err != nil {
t.Fatal(err)
}
if detail.Value != "sid=fresh" || strings.Contains(detail.MetadataJSON, "cookies_refresh_snapshot") || !strings.Contains(detail.MetadataJSON, `"other":true`) {
t.Fatalf("detail=%+v", detail)
}
var rawMetadata string
if err := store.DB.QueryRowContext(ctx, `SELECT metadata_json FROM cookies WHERE id=?`, "flat-cookie").Scan(&rawMetadata); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(rawMetadata, encryptedValuePrefix) || strings.Contains(rawMetadata, "other") {
t.Fatalf("metadata not encrypted at rest: %q", rawMetadata)
}
}
func TestEncryptLegacySecretsMigratesCookieMetadata(t *testing.T) {
t.Setenv("XIANYU_DATA_KEY", "metadata-migration-key")
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "metadata-owner", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create owner: ok=%v err=%v", ok, err)
}
owner, _ := store.Users.GetByUsername(ctx, "metadata-owner")
metadata := `{"cookies_refresh_snapshot":[{"name":"sid","value":"legacy-secret"}]}`
if _, err := store.DB.ExecContext(ctx,
`INSERT INTO cookies (id,value,user_id,metadata_json) VALUES (?,?,?,?)`,
"legacy-metadata", "legacy-cookie", owner.ID, metadata); err != nil {
t.Fatal(err)
}
if err := store.EncryptLegacySecrets(ctx); err != nil {
t.Fatal(err)
}
var raw string
if err := store.DB.QueryRowContext(ctx, `SELECT metadata_json FROM cookies WHERE id=?`, "legacy-metadata").Scan(&raw); err != nil {
t.Fatal(err)
}
if !strings.HasPrefix(raw, encryptedValuePrefix) || strings.Contains(raw, "legacy-secret") {
t.Fatalf("legacy metadata was not encrypted: %q", raw)
}
detail, err := store.Cookies.GetDetails(ctx, "legacy-metadata")
if err != nil || detail.MetadataJSON != metadata {
t.Fatalf("detail=%+v err=%v", detail, err)
}
}
+13 -6
View File
@@ -14,7 +14,10 @@ import (
"strings"
)
const encryptedValuePrefix = "enc:v1:"
const (
encryptedValuePrefix = "enc:v1:"
cookieMetadataScope = "cookie-metadata"
)
// secretCodec 对数据库敏感字段做 AES-256-GCM 信封加密。未配置密钥时保持
// 明文兼容;已加密数据若缺少/使用错误密钥会明确报错,绝不把密文当凭证使用。
@@ -77,15 +80,15 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
}
defer tx.Rollback()
type cookieSecret struct{ id, value, password string }
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,'') FROM cookies`)
type cookieSecret struct{ id, value, password, metadata string }
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
if err != nil {
return err
}
var cookies []cookieSecret
for rows.Next() {
var row cookieSecret
if err := rows.Scan(&row.id, &row.value, &row.password); err != nil {
if err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
rows.Close()
return err
}
@@ -103,8 +106,12 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
if err != nil {
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
}
if value != row.value || password != row.password {
if _, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=? WHERE id=?`, value, password, row.id); err != nil {
metadata, err := codec.encrypt(cookieMetadataScope, row.id, row.metadata)
if err != nil {
return fmt.Errorf("校验账号 %s Cookie metadata: %w", row.id, err)
}
if value != row.value || password != row.password || metadata != row.metadata {
if _, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
return err
}
}
+447 -229
View File
File diff suppressed because it is too large. Load diff
+221 -8
View File
@@ -10,6 +10,7 @@ import (
"time"
"xianyu-go/internal/automation"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
@@ -241,7 +242,7 @@ type stubCookieRenewer struct {
got string
}
func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string) (*xrenew.Result, error) {
func (s *stubCookieRenewer) RenewAPIFirst(_ context.Context, cookiesStr string, _ ...[]cookierefresh.BrowserCookie) (*xrenew.Result, error) {
s.calls++
s.got = cookiesStr
return s.result, s.err
@@ -292,6 +293,7 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
RenewMethod: "none",
NewCookies: "unb=123; _m_h5_tk=partial;",
UpdatedCookieNames: []string{"_m_h5_tk"},
SetCookies: []string{"_m_h5_tk=partial; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
Message: "setLoginSettings 未返回 Set-Cookie",
}}
acc.renewer = renewer
@@ -309,6 +311,52 @@ func TestTryAPIRenewPartialCookiesContinueRecovery(t *testing.T) {
if tk, err := store.Tokens.Get(ctx, "cid"); err != nil || tk.AccessToken != "" {
t.Fatalf("部分 cookie 更新后应清 token: tk=%+v err=%v", tk, err)
}
detail, err := store.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatal(err)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
t.Fatal("接口扁平 Cookie 更新不得伪造成完整浏览器 Jar")
}
}
func TestTryAPIRenewPersistsExplicitFlatCookieDeletionOnError(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
if err := store.Tokens.Save(ctx, "cid", "did-old", "tok-old", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
acc.renewer = &stubCookieRenewer{
result: &xrenew.Result{
NewCookies: "",
SetCookies: []string{
"unb=; Domain=.goofish.com; Path=/; Max-Age=0",
"_m_h5_tk=; Domain=.goofish.com; Path=/; Max-Age=0",
},
},
err: errors.New("续期响应正文损坏"),
}
if acc.tryAPIRenew(ctx) {
t.Fatal("失败响应即使带 Cookie 删除也不应视为续期成功")
}
if got := acc.currentCookieStr(); got != "" {
t.Fatalf("运行时应采用服务端明确删除后的空 Cookie,got %q", got)
}
detail, err := store.Cookies.GetDetails(ctx, "cid")
if err != nil {
t.Fatal(err)
}
if detail.Value != "" {
t.Fatalf("数据库应保存明确删除后的空 Cookie,got %q", detail.Value)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
t.Fatal("扁平删除结果不得伪造成完整浏览器 Jar")
}
if token, err := store.Tokens.Get(ctx, "cid"); err != nil || token.AccessToken != "" {
t.Fatalf("Cookie 删除后应清理旧 token: token=%+v err=%v", token, err)
}
}
// TestSetRuntimeError_AllBranches 覆盖验证/captcha、token 失效、默认重连三分支
@@ -694,7 +742,7 @@ func TestReplaceCookieStr_NoUnbNoChange(t *testing.T) {
// TestUpdateCookie_IgnoresEmpty 纯空白/空字符串被忽略,不覆盖现有 cookie。
func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
orig := acc.currentCookieStr()
@@ -706,22 +754,187 @@ func TestUpdateCookie_IgnoresEmpty(t *testing.T) {
t.Errorf("空白 cookie 不应更新: got %q want %q", got, orig)
}
// 非空(即使含首尾空白)应原样存储——UpdateCookie 只做空值检查,不做 trim。
acc.UpdateCookie("unb=123; _m_h5_tk=tk_new;")
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_new;" {
acc.mu.Lock()
originalDevice := acc.deviceID
healthyConn := &fakeWSConn{}
acc.conn = healthyConn
acc.mu.Unlock()
// 非空(即使含首尾空白)应原样存储,但不能模拟页面 reload 去打断健康 WS。
updated := "unb=123; _m_h5_tk=tk_new;"
if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
t.Fatal(err)
}
acc.UpdateCookie(updated)
if got := acc.currentCookieStr(); got != updated {
t.Errorf("非空 cookie 应更新: got %q", got)
}
acc.mu.Lock()
currentDevice := acc.deviceID
acc.mu.Unlock()
healthyConn.mu.Lock()
closed := healthyConn.closed
healthyConn.mu.Unlock()
if currentDevice != originalDevice || closed {
t.Fatalf("普通 Cookie 更新不应轮换 device ID 或关闭健康连接: device=%q/%q closed=%v", currentDevice, originalDevice, closed)
}
}
func TestUpdateCookie_AcceptsAuthoritativeEmptySnapshot(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
metadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
if err := store.Cookies.UpdateRenewalCookie(context.Background(), acc.CookieID, "", metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
acc.UpdateCookie("")
if got := acc.currentCookieStr(); got != "" {
t.Fatalf("权威空 Jar 应清空运行时 Cookie,got %q", got)
}
}
func TestReloadCookieFromDBDetectsMetadataOnlyCredentialRotation(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
flat := acc.currentCookieStr()
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/im"},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
t.Fatal(err)
}
if !acc.reloadCookieFromDB(ctx) {
t.Fatal("首次权威 Jar 应同步到运行时")
}
acc.mu.Lock()
boundFP := acc.credentialFP
acc.currentToken = "old-token"
acc.tokenCredentialFP = boundFP
acc.mu.Unlock()
if err := store.Tokens.SaveBound(ctx, acc.CookieID, acc.deviceID, "old-token", time.Now().Add(time.Hour).Unix(), boundFP); err != nil {
t.Fatal(err)
}
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/im"},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
t.Fatal(err)
}
if !acc.reloadCookieFromDB(ctx) {
t.Fatal("扁平 Cookie 未变但权威 Jar 已变化时必须重新加载")
}
acc.mu.Lock()
currentToken := acc.currentToken
currentFP := acc.credentialFP
acc.mu.Unlock()
if currentToken != "" {
t.Fatalf("Jar 变化后应清内存 token,got %q", currentToken)
}
if currentFP != credentialStateFingerprint(flat, metadataB) {
t.Fatal("运行时未绑定到最新完整凭证状态")
}
if cached, err := store.Tokens.Get(ctx, acc.CookieID); err != nil || cached.AccessToken != "" {
t.Fatalf("Jar 变化后应清数据库 token: cached=%+v err=%v", cached, err)
}
}
func TestCookieSnapshotMatchesDBUsesCompleteCredentialState(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
flat := acc.currentCookieStr()
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "sgcookie", Value: "a", Domain: ".goofish.com", Path: "/"},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataA, time.Now().Unix()); err != nil {
t.Fatal(err)
}
expected := credentialStateFingerprint(flat, metadataA)
if !acc.cookieSnapshotMatchesDB(ctx, expected) {
t.Fatal("相同扁平 Cookie 与权威 Jar 应允许 /reg")
}
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "sgcookie", Value: "b", Domain: ".goofish.com", Path: "/"},
})
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, flat, metadataB, time.Now().Unix()); err != nil {
t.Fatal(err)
}
if acc.cookieSnapshotMatchesDB(ctx, expected) {
t.Fatal("token 获取后 Jar 变化时必须拒绝 /reg")
}
emptyMetadata := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
if err := store.Cookies.UpdateRenewalCookie(ctx, acc.CookieID, "", emptyMetadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
if !acc.cookieSnapshotMatchesDB(ctx, credentialStateFingerprint("", emptyMetadata)) {
t.Fatal("完整空 Jar 是权威状态,不应因扁平值为空而被拒绝")
}
}
func TestAdoptIncompleteTokenCookiesDoesNotInventCompleteSnapshot(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
updated := "unb=123; _m_h5_tk=flat-only; cookie2=next"
got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
UpdatedCookies: updated,
})
if err != nil {
t.Fatal(err)
}
if got != updated {
t.Fatalf("adopted Cookie=%q want %q", got, updated)
}
detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
if err != nil {
t.Fatal(err)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
t.Fatal("仅有扁平 token 响应时不得伪造成完整浏览器 Jar")
}
}
func TestAdoptTokenResponseCookiesPersistsExplicitDeletionToEmpty(t *testing.T) {
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
ctx := context.Background()
got, err := acc.adoptTokenResponseCookies(ctx, acc.currentCookieStr(), &mtop.RefreshResult{
UpdatedCookies: "",
CookieStateChanged: true,
})
if err != nil {
t.Fatal(err)
}
if got != "" || acc.currentCookieStr() != "" {
t.Fatalf("明确删除后的 Cookie 未同步: got=%q runtime=%q", got, acc.currentCookieStr())
}
detail, err := store.Cookies.GetDetails(ctx, acc.CookieID)
if err != nil {
t.Fatal(err)
}
if detail.Value != "" {
t.Fatalf("数据库 Cookie=%q want empty", detail.Value)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
t.Fatal("扁平 token 删除不得伪造成完整浏览器 Jar")
}
}
// TestCurrentCookieStr 线程安全返回当前 CookieStr。
func TestCurrentCookieStr(t *testing.T) {
acc, _, _, cleanup := newAccountForTest(t)
acc, _, store, cleanup := newAccountForTest(t)
defer cleanup()
if got := acc.currentCookieStr(); got != "unb=123; _m_h5_tk=tk_1;" {
t.Errorf("currentCookieStr=%q", got)
}
acc.UpdateCookie("unb=1; x=2;")
if got := acc.currentCookieStr(); got != "unb=1; x=2;" {
updated := "unb=1; x=2;"
if err := store.Cookies.UpdateValueExisting(context.Background(), acc.CookieID, updated); err != nil {
t.Fatal(err)
}
acc.UpdateCookie(updated)
if got := acc.currentCookieStr(); got != updated {
t.Errorf("更新后 currentCookieStr=%q", got)
}
}
+5 -5
View File
@@ -233,8 +233,8 @@ func TestTryLoginStatusCheck_AdoptsUpdatedCookie(t *testing.T) {
if err != nil || saved != newCookie {
t.Fatalf("DB Cookie 未更新: got %q err=%v", saved, err)
}
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
t.Fatalf("Cookie 更新后应清 token 并为页面重载轮换 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
t.Fatalf("Cookie 更新后应清 token 并保持页面 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
@@ -280,9 +280,9 @@ func TestReloadCookieFromDB_AdoptsNewCookieAndClearsCache(t *testing.T) {
if got := acc.CurrentCookieStr(); got != newCookie {
t.Fatalf("应采纳 DB 新 cookie,got %s", got)
}
// 新 cookie 对应官网页面重载:旧 token 清除,运行时 device ID 轮换。
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID == oldDeviceID {
t.Fatalf("cookie 变更后应清 token 并轮换运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
// 普通 Cookie Jar 更新不等于页面 reload:旧 token 清除,device ID 保持。
if tk, err := store.Tokens.Get(context.Background(), "cid"); err != nil || tk.AccessToken != "" || tk.DeviceID != oldDeviceID || acc.deviceID != oldDeviceID {
t.Fatalf("cookie 变更后应清 token 并保持运行时 device ID: runtime=%q tk=%+v err=%v", acc.deviceID, tk, err)
}
}
+79 -56
View File
@@ -274,33 +274,27 @@ func TestRun_ConnectsAndDispatchesMessage(t *testing.T) {
}
}
// TestRun_DialFailureIncrementsFailures 拨号失败时 connFailures 递增,
// ctx 在重试 sleep 期间取消 → Run 返回 ctx.Err。
func TestRun_DialFailureIncrementsFailures(t *testing.T) {
// TestRun_DialFailureRequiresRelogin mirrors the web page: native
// CONNECT_FAILED enters CONN_ERROR and does not auto-reconnect.
func TestRun_DialFailureRequiresRelogin(t *testing.T) {
acc, _, _, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
defer cleanup()
// 拨号始终失败。
acc.wsDialer = &fakeDialer{results: []dialResult{{err: errFakeDial}}}
ctx, cancel := context.WithCancel(context.Background())
runDone := make(chan error, 1)
go func() { runDone <- acc.Run(ctx) }()
// 等待首次拨号失败 + 进入重试 sleep。
time.Sleep(300 * time.Millisecond)
cancel()
go func() { runDone <- acc.Run(context.Background()) }()
select {
case <-runDone:
// Run 应已退出。
case <-time.After(3 * time.Second):
t.Fatal("拨号失败 + ctx 取消后 Run 未退出")
case err := <-runDone:
if !errors.Is(err, errFakeDial) {
t.Fatalf("Run error=%v,期望拨号错误", err)
}
case <-time.After(2 * time.Second):
t.Fatal("拨号失败后 Run 未退出")
}
acc.mu.Lock()
failures := acc.connFailures
acc.mu.Unlock()
if failures < 1 {
t.Fatalf("拨号失败应使 connFailures>=1,got %d", failures)
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
t.Fatalf("runtime state=%q,期望 %q", status.State, RuntimeAuthExpired)
}
}
@@ -352,9 +346,11 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
mtopClient := &sequencedTokenMtop{fakeRunMtop: fakeRunMtop{token: "unused"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
first := &fakeWSConn{recvBlock: false}
second := &fakeWSConn{recvBlock: true}
dialer := &fakeDialer{results: []dialResult{
{conn: &fakeWSConn{recvBlock: false}},
{conn: &fakeWSConn{recvBlock: true}},
{conn: first},
{conn: second},
}}
acc.wsDialer = dialer
@@ -362,6 +358,7 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
waitForDialCalls(t, dialer, 2)
waitForRegisteredToken(t, second, "fresh-2")
cancel()
<-done
@@ -388,39 +385,33 @@ func TestRun_ReconnectUsesFreshTokenAndStableDeviceID(t *testing.T) {
}
}
func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
func TestRun_EstablishedNetworkErrorReconnectsWithFreshToken(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "tok-1"}}
acc, _, store, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
conn := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: conn}}}
first := &fakeWSConn{recvErr: errors.New("connection reset by peer")}
second := &fakeWSConn{recvBlock: true}
dialer := &fakeDialer{results: []dialResult{{conn: first}, {conn: second}}}
acc.wsDialer = dialer
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- acc.Run(ctx) }()
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
acc.mu.Lock()
failures := acc.networkFailures
acc.mu.Unlock()
if failures == 1 {
break
}
time.Sleep(10 * time.Millisecond)
}
waitForDialCalls(t, dialer, 2)
waitForRegisteredToken(t, second, "tok-1")
acc.mu.Lock()
currentToken := acc.currentToken
networkFailures := acc.networkFailures
acc.mu.Unlock()
if networkFailures != 1 || currentToken != "" {
if networkFailures != 0 || currentToken != "tok-1" {
cancel()
<-done
t.Fatalf("网络断线应结束当前 token 生命周期: failures=%d token=%q", networkFailures, currentToken)
t.Fatalf("网络断线后应立即用新凭证恢复连接: failures=%d token=%q", networkFailures, currentToken)
}
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "" {
if cached, err := store.Tokens.Get(context.Background(), "cid"); err != nil || cached.AccessToken != "tok-1" {
cancel()
<-done
t.Fatalf("网络断线应清除 token 缓存: cached=%+v err=%v", cached, err)
t.Fatalf("重连成功后应缓存新连接凭证: cached=%+v err=%v", cached, err)
}
cancel()
select {
@@ -428,30 +419,39 @@ func TestRun_EstablishedNetworkErrorClearsConnectionToken(t *testing.T) {
case <-time.After(2 * time.Second):
t.Fatal("取消后 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("网络断线前只应获取一次 token: calls=%d", calls)
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("官网重连会重新获取连接凭证: calls=%d", calls)
}
}
func TestRun_InvalidRegTokenFetchesOneFreshTokenImmediately(t *testing.T) {
func TestRun_InvalidRegTokenRequiresRelogin(t *testing.T) {
mtopClient := &countingMtop{fakeRunMtop: fakeRunMtop{token: "fresh-token"}}
acc, _, _, cleanup := newRunAccount(t, mtopClient)
defer cleanup()
dialer := &fakeDialer{results: []dialResult{
{conn: &fakeWSConn{registerErr: &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
go func() { done <- acc.Run(context.Background()) }()
select {
case err := <-done:
if !ws.IsInvalidTokenError(err) {
t.Fatalf("Run error=%v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("invalid /reg 后 Run 未退出")
}
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 2 {
t.Fatalf("invalid /reg should fetch exactly one fresh token immediately, calls=%d", calls)
if calls := atomic.LoadInt32(&mtopClient.calls); calls != 1 {
t.Fatalf("invalid /reg 不应在页面要求重新登录时静默重试: calls=%d", calls)
}
if dialer.calls != 1 {
t.Fatalf("invalid /reg dial calls=%d want 1", dialer.calls)
}
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
}
}
@@ -507,6 +507,24 @@ func waitForDialCalls(t *testing.T, dialer *fakeDialer, want int) {
t.Fatalf("dial calls=%d want>=%d", calls, want)
}
func waitForRegisteredToken(t *testing.T, conn *fakeWSConn, want string) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for time.Now().Before(deadline) {
conn.mu.Lock()
token := conn.registeredTok
conn.mu.Unlock()
if token == want {
return
}
time.Sleep(10 * time.Millisecond)
}
conn.mu.Lock()
token := conn.registeredTok
conn.mu.Unlock()
t.Fatalf("registered token=%q want=%q", token, want)
}
// TestRun_DisabledAccountExits 账号被禁用时 Run 立即退出。
func TestRun_DisabledAccountExits(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeRunMtop{token: "tok-1"})
@@ -528,7 +546,7 @@ func TestRun_DisabledAccountExits(t *testing.T) {
}
}
func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
func TestRun_TokenFetchThresholdDoesNotDisableAccount(t *testing.T) {
acc, _, store, cleanup := newRunAccount(t, &fakeFailTokenMtop{err: errFakeDial})
defer cleanup()
acc.wsDialer = &fakeDialer{results: []dialResult{{conn: &fakeWSConn{recvBlock: true}}}}
@@ -542,17 +560,22 @@ func TestRun_TokenFetchThresholdDisablesAccount(t *testing.T) {
go func() { done <- acc.Run(context.Background()) }()
select {
case err := <-done:
if err != nil {
t.Fatalf("threshold disable should exit nil, got %v", err)
if !errors.Is(err, errFakeDial) {
t.Fatalf("token callback reject should enter CONN_ERROR, got %v", err)
}
case <-time.After(2 * time.Second):
t.Fatal("token failure threshold should disable without retry sleep")
t.Fatal("Run did not stop after token callback reject")
}
if store.Cookies.GetStatus(context.Background(), "cid") {
t.Fatal("token failure threshold should disable account")
if !store.Cookies.GetStatus(context.Background(), "cid") {
t.Fatal("token failure threshold must not disable account")
}
if len(h.events) == 0 || h.events[len(h.events)-1] != EventAccountDisabled {
t.Fatalf("disable event not emitted: events=%+v alerts=%+v", h.events, h.alerts)
for _, event := range h.events {
if event == EventAccountDisabled {
t.Fatalf("unexpected disable event: events=%+v alerts=%+v", h.events, h.alerts)
}
}
if status := acc.RuntimeStatus(); status.State != RuntimeAuthExpired {
t.Fatalf("runtime state=%q want %q", status.State, RuntimeAuthExpired)
}
}
+30 -10
View File
@@ -3,11 +3,11 @@ package engine
import (
"crypto/sha256"
"encoding/hex"
"sort"
"encoding/json"
"strings"
"time"
"xianyu-go/internal/xianyu/protocol"
"xianyu-go/internal/xianyu/cookierefresh"
)
const tokenExpirySafetyMargin = time.Minute
@@ -25,19 +25,39 @@ func effectiveTokenExpireAt(serverExpireAt int64, now time.Time) int64 {
}
func credentialCookieFingerprint(cookieStr string) string {
cookies := protocol.TransCookies(cookieStr)
keys := make([]string, 0, len(cookies))
for key := range cookies {
keys = append(keys, key)
}
sort.Strings(keys)
var canonical strings.Builder
for _, key := range keys {
for _, part := range strings.Split(cookieStr, ";") {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
key = strings.TrimSpace(key)
if !ok || key == "" {
continue
}
canonical.WriteString(key)
canonical.WriteByte(0)
canonical.WriteString(cookies[key])
canonical.WriteString(strings.TrimSpace(value))
canonical.WriteByte(0)
}
sum := sha256.Sum256([]byte(canonical.String()))
return hex.EncodeToString(sum[:])
}
// credentialStateFingerprint binds a connection token to both the exact flat
// Cookie header and the authoritative browser Jar that produced it. The flat
// fingerprint deliberately retains duplicate names and their order because
// lib-mtop reads the first path-ordered _m_h5_tk entry. A present empty Jar is
// distinct from legacy metadata that has no complete snapshot.
func credentialStateFingerprint(cookieStr, metadataJSON string) string {
var canonical strings.Builder
canonical.WriteString("flat\x00")
canonical.WriteString(credentialCookieFingerprint(cookieStr))
canonical.WriteString("\x00snapshot\x00")
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(metadataJSON); complete {
canonical.WriteByte('1')
raw, _ := json.Marshal(cookierefresh.NormalizeSnapshot(snapshot))
canonical.Write(raw)
} else {
canonical.WriteByte('0')
}
sum := sha256.Sum256([]byte(canonical.String()))
return hex.EncodeToString(sum[:])
}
+30 -3
View File
@@ -3,6 +3,8 @@ package engine
import (
"testing"
"time"
"xianyu-go/internal/xianyu/cookierefresh"
)
func TestEffectiveTokenExpireAtUsesServerDeadlineWithSafetyMargin(t *testing.T) {
@@ -23,13 +25,38 @@ func TestEffectiveTokenExpireAtRejectsMissingOrExpiredDeadline(t *testing.T) {
}
}
func TestCredentialCookieFingerprintIsOrderIndependent(t *testing.T) {
func TestCredentialCookieFingerprintPreservesHeaderOrderAndDuplicates(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)
if left == "" || left == right {
t.Fatalf("Cookie Header 顺序变化必须改变指纹: %q == %q", left, right)
}
if left == credentialCookieFingerprint("unb=1; cookie2=changed; _m_h5_tk=tk_1") {
t.Fatal("credential change must alter fingerprint")
}
if left != credentialCookieFingerprint(" unb = 1 ; cookie2=abc;_m_h5_tk = tk_1 ;") {
t.Fatal("无语义空白不应改变指纹")
}
firstPathToken := credentialCookieFingerprint("_m_h5_tk=first; _m_h5_tk=second; unb=1")
secondPathToken := credentialCookieFingerprint("_m_h5_tk=second; _m_h5_tk=first; unb=1")
if firstPathToken == secondPathToken {
t.Fatal("同名 Cookie 的路径顺序会影响首值签名,不能折叠")
}
}
func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
flat := "unb=1; _m_h5_tk=tk_1"
metadataA := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-a", Domain: ".goofish.com", Path: "/"},
})
metadataB := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "path-b", Domain: ".goofish.com", Path: "/"},
})
if credentialStateFingerprint(flat, metadataA) == credentialStateFingerprint(flat, metadataB) {
t.Fatal("权威 Jar 变化必须改变完整凭证指纹")
}
emptyJar := cookierefresh.MetadataWithSnapshot("", []cookierefresh.BrowserCookie{})
if credentialStateFingerprint("", emptyJar) == credentialStateFingerprint("", "") {
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
}
}
+155 -61
View File
@@ -4,6 +4,7 @@ import (
"context"
crand "crypto/rand"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"math/big"
@@ -52,7 +53,7 @@ type accountRestarter interface {
type BrowserRenewer interface {
BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error)
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, error)
CookiesRefreshSnapshot(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (string, []cookierefresh.BrowserCookie, bool, error)
}
type PasswordRefresher interface {
@@ -155,25 +156,69 @@ 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()
latest, err := s.reloadRenewalAccount(ctx, account)
if err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "重读账号凭证失败: "+err.Error(), nil, time.Since(started))
return
}
account = latest
if !account.Enabled {
return
}
runCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
res, err := s.mtop.CheckLoginStatusContext(runCtx, account.Value)
if err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", err.Error(), nil, time.Since(started))
s.logger.Warn("login_renew 失败", "account", account.ID, "err", err)
var mtopCtx context.Context
var cookieSession *mtop.CookieSession
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(account.MetadataJSON); ok {
mtopCtx, cookieSession = mtop.WithCookieSnapshot(runCtx, snapshot)
} else {
mtopCtx, cookieSession = mtop.WithFlatCookieSession(runCtx, account.Value)
}
res, callErr := s.mtop.CheckLoginStatusContext(mtopCtx, account.Value)
// Chromium 在收到响应头时就会应用 Set-Cookie。权威 session
// 因此必须在处理请求或解析错误之前持久化,否则下次请求会
// 从数据库回滚到旧 Jar。
updated := []string(nil)
sessionHandled := false
value, snapshot, changed := cookieSession.State()
if changed {
sessionHandled = true
updated = cookierefresh.ChangedCookieNames(account.Value, value)
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, snapshot)
}
if persistErr := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, value, metadata, time.Now().Unix()); persistErr != nil {
if callErr != nil {
persistErr = errors.Join(callErr, fmt.Errorf("保存 loginuser.get 响应 Cookie Jar: %w", persistErr))
}
s.addLoginLog(ctx, batchID, account.ID, "failed", persistErr.Error(), updated, time.Since(started))
s.logger.Warn("login_renew 保存响应 Cookie Jar 失败", "account", account.ID, "err", persistErr)
return
}
}
if callErr != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", callErr.Error(), updated, time.Since(started))
s.logger.Warn("login_renew 失败", "account", account.ID, "err", callErr)
return
}
if res == nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "loginuser.get 未返回结果", nil, time.Since(started))
return
}
updated := cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, account.MetadataJSON, time.Now().Unix()); err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
return
if !sessionHandled {
updated = cookierefresh.ChangedCookieNames(account.Value, res.UpdatedCookies)
if res.UpdatedCookies != "" && res.UpdatedCookies != account.Value {
// 注入 mock 或没有权威快照的历史账号仍走扁平
// Cookie 兼容路径。扁平值无法证明旧 snapshot 的
// Domain/Path/expiry 仍有效,因此必须清除旧快照。
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, res.UpdatedCookies, metadata, time.Now().Unix()); err != nil {
s.addLoginLog(ctx, batchID, account.ID, "failed", "保存 Cookie 失败: "+err.Error(), updated, time.Since(started))
return
}
}
}
s.addLoginLog(ctx, batchID, account.ID, res.Status, res.Message, updated, time.Since(started))
@@ -200,23 +245,29 @@ 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)
shouldRestart := false
credentialLocked := true
defer func() {
credentialUnlock()
if shouldRestart {
s.restartAccount(ctx, account.ID)
if credentialLocked {
credentialUnlock()
}
}()
account = s.reloadRenewalAccount(ctx, account)
started := time.Now()
res, err := s.renewAPI(ctx, account.Value)
latest, err := s.reloadRenewalAccount(ctx, account)
if err != nil {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
s.logger.Warn("api_cookie_renew 失败", "account", account.ID, "err", err)
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重读账号凭证失败: " + err.Error(), RenewMethod: "auto_login_plugin"})
return
}
account = latest
if !account.Enabled {
return
}
res, callErr := s.renewAPI(ctx, account.Value, cookierefresh.SnapshotFromMetadata(account.MetadataJSON))
if res == nil {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "接口续期未返回结果", RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
message := "接口续期未返回结果"
if callErr != nil {
message = callErr.Error()
}
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: message, RenewMethod: "auto_login_plugin", DurationMS: time.Since(started).Milliseconds()})
return
}
stepDetails := make([]string, 0, len(res.StepDetails)+1)
@@ -225,18 +276,34 @@ func (s *Scheduler) apiCookieRenewOne(ctx context.Context, batchID string, accou
}
stepDetails = append(stepDetails, fmt.Sprintf("result: success=%v skipped=%v reason=%s", res.Success, res.Skipped, res.SkipReason))
updated := cookierefresh.ChangedCookieNames(account.Value, res.NewCookies)
if res.NewCookies != "" && res.NewCookies != account.Value {
snapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
if len(snapshot) == 0 {
snapshot = cookierefresh.SnapshotFromCookieString(account.Value, ".goofish.com")
if res.CookieSnapshotComplete || len(res.SetCookies) > 0 || res.NewCookies != account.Value {
metadata := cookierefresh.MetadataWithoutSnapshot(account.MetadataJSON)
if res.CookieSnapshotComplete {
metadata = cookierefresh.MetadataWithSnapshot(account.MetadataJSON, res.CookieSnapshot)
}
snapshot = cookierefresh.ApplySetCookies(snapshot, apirenew.SilentHasLoginURL, res.SetCookies, time.Now())
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, snapshot)
if !s.saveRenewedCookies(ctx, account.ID, res.NewCookies, metadata) {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败", UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
return
}
shouldRestart = account.Enabled && res.Success
}
if callErr != nil {
s.addAPILog(ctx, db.RenewalLog{
BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: callErr.Error(),
UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod,
DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount,
})
s.logger.Warn("api_cookie_renew 失败,已保存响应头 Cookie", "account", account.ID, "err", callErr)
return
}
if res.Success && account.Enabled {
credentialUnlock()
credentialLocked = false
if restarter, ok := s.starter.(accountRestarter); ok {
if err := restarter.Restart(ctx, account.ID); err != nil {
s.addAPILog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, StepDetails: strings.Join(stepDetails, " | "), RenewMethod: res.RenewMethod, DurationMS: time.Since(started).Milliseconds(), RequestCount: res.RequestCount})
return
}
}
}
status := "failed"
if res.Skipped {
@@ -306,15 +373,22 @@ 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)
shouldRestart := false
credentialLocked := true
defer func() {
credentialUnlock()
if shouldRestart {
s.restartAccount(ctx, account.ID)
if credentialLocked {
credentialUnlock()
}
}()
account = s.reloadRenewalAccount(ctx, account)
started := time.Now()
latest, err := s.reloadRenewalAccount(ctx, account)
if err != nil {
s.logger.Warn("cookies_refresh 重读账号凭证失败", "account", account.ID, "err", err)
return
}
account = latest
if !account.Enabled && account.DisableReason == db.DisableReasonManual {
return
}
if s.browser == nil {
schedule.LastStatus = "failed"
schedule.LastErrorMessage = "浏览器自动化未启用"
@@ -325,33 +399,53 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string,
runCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
oldSnapshot := cookierefresh.SnapshotFromMetadata(account.MetadataJSON)
newCookies, newSnapshot, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, browser.ResolveHeadless(account.ShowBrowser))
newCookies, newSnapshot, officialReload, err := s.browser.CookiesRefreshSnapshot(runCtx, account.ID, account.Value, oldSnapshot, browser.ResolveHeadless(account.ShowBrowser))
if newSnapshot == nil && err == nil {
err = errors.New("浏览器未返回权威 Cookie Jar")
}
if newSnapshot != nil {
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
if saveErr := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); saveErr != nil {
if err == nil {
err = fmt.Errorf("保存浏览器最终 Cookie Jar: %w", saveErr)
} else {
err = errors.Join(err, fmt.Errorf("保存浏览器最终 Cookie Jar: %w", saveErr))
}
}
}
if err != nil {
schedule.ConsecutiveFailures++
schedule.LastStatus = "failed"
schedule.LastError = err.Error()
schedule.LastErrorMessage = err.Error()
_ = s.store.Renewal.UpsertCookieRefreshSchedule(ctx, schedule)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: err.Error(), NextExpireAt: schedule.ExpireAt, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v page_load=1 plugin_call=true", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 1})
s.logger.Warn("cookies_refresh 失败", "account", account.ID, "err", err)
return
}
metadata := cookierefresh.MetadataWithSnapshot(account.MetadataJSON, newSnapshot)
updated := cookierefresh.ChangedSnapshotLabels(oldSnapshot, newSnapshot)
if err := s.store.Cookies.UpdateRenewalCookie(ctx, account.ID, newCookies, metadata, time.Now().Unix()); err != nil {
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "保存 Cookie 失败: " + err.Error(), UpdatedCookieNames: updated, RenewMethod: "browser", StepDetails: fmt.Sprintf("snapshot=%v reload=3", len(oldSnapshot) > 0), DurationMS: time.Since(started).Milliseconds(), RequestCount: 4})
return
}
if !account.Enabled {
if err := s.store.Cookies.SetStatusWithReason(ctx, account.ID, true, ""); err != nil {
s.logger.Warn("cookies_refresh 自动启用账号失败", "account", account.ID, "err", err)
} else if s.starter != nil {
if err := s.starter.Start(ctx, account.ID, newCookies); err != nil {
s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
} else {
credentialUnlock()
credentialLocked = false
if s.starter != nil {
if err := s.starter.Start(ctx, account.ID, newCookies); err != nil {
s.logger.Warn("cookies_refresh 启动账号失败", "account", account.ID, "err", err)
}
}
}
} else if officialReload {
credentialUnlock()
credentialLocked = false
if restarter, ok := s.starter.(accountRestarter); ok {
if err := restarter.Restart(ctx, account.ID); err != nil {
s.logger.Warn("cookies_refresh 重建消息连接失败", "account", account.ID, "err", err)
_ = s.store.Renewal.AddBrowserCookieRenewLog(ctx, db.RenewalLog{BatchID: batchID, CookieID: account.ID, Status: "failed", ErrorMessage: "重建消息连接失败: " + err.Error(), UpdatedCookieNames: updated, RenewMethod: "browser", DurationMS: time.Since(started).Milliseconds(), RequestCount: 1})
return
}
}
} else if len(updated) > 0 {
shouldRestart = true
}
nextExpire := time.Now().Add(browserSuccessDelay()).Unix()
schedule.Disabled = false
@@ -370,40 +464,40 @@ func (s *Scheduler) browserCookieRefreshOne(ctx context.Context, batchID string,
UpdatedCookieNames: updated,
NextExpireAt: nextExpire,
RenewMethod: "browser",
StepDetails: fmt.Sprintf("snapshot=%v reload=3 modal_check=true", len(oldSnapshot) > 0),
StepDetails: fmt.Sprintf("snapshot=%v page_load=1 plugin_call=true", len(oldSnapshot) > 0),
DurationMS: time.Since(started).Milliseconds(),
RequestCount: 4,
RequestCount: 1,
})
}
func (s *Scheduler) restartAccount(ctx context.Context, cookieID string) {
restarter, ok := s.starter.(accountRestarter)
if !ok {
return
}
if err := restarter.Restart(ctx, cookieID); err != nil {
s.logger.Warn("Cookie 更新后重启账号失败", "account", cookieID, "err", err)
}
}
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string) (*apirenew.Result, error) {
func (s *Scheduler) renewAPI(ctx context.Context, cookieStr string, snapshot []cookierefresh.BrowserCookie) (*apirenew.Result, error) {
runCtx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
return s.api.RenewAPIFirst(runCtx, cookieStr)
return s.api.RenewAPIFirst(runCtx, cookieStr, snapshot)
}
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) db.RenewalAccount {
func (s *Scheduler) reloadRenewalAccount(ctx context.Context, account db.RenewalAccount) (db.RenewalAccount, error) {
detail, err := s.store.Cookies.GetDetails(ctx, account.ID)
if err != nil || detail == nil {
return account
if err == nil {
err = db.ErrNotFound
}
return db.RenewalAccount{}, err
}
enabled, reason, err := s.store.Cookies.StatusWithReason(ctx, account.ID)
if err != nil {
return db.RenewalAccount{}, err
}
account.Value = detail.Value
account.UserID = detail.UserID
account.Enabled = enabled
account.DisableReason = reason
account.Username = detail.Username
account.Password = detail.Password
account.ShowBrowser = detail.ShowBrowser
account.MetadataJSON = detail.MetadataJSON
account.LastRefreshAt = detail.LastRefreshAt
return account
return account, nil
}
func (s *Scheduler) saveRenewedCookies(ctx context.Context, cookieID, cookieStr, metadata string) bool {
+121 -6
View File
@@ -3,6 +3,7 @@ package renewal
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
@@ -18,6 +19,12 @@ import (
apirenew "xianyu-go/internal/xianyu/renew"
)
type schedulerRoundTripperFunc func(*http.Request) (*http.Response, error)
func (f schedulerRoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func newSchedulerTestStore(t *testing.T) (*db.Store, func()) {
t.Helper()
d, _, err := db.Open(context.Background(), filepath.Join(t.TempDir(), "renewal.db"))
@@ -35,16 +42,35 @@ type schedulerFakeBrowser struct {
}
type schedulerRefreshBrowser struct {
refreshCalls int
refreshCalls int
officialReload bool
}
func (f *schedulerRefreshBrowser) BrowserQuickRenew(context.Context, string, string, bool) (string, error) {
return "", errors.New("not implemented")
}
func (f *schedulerRefreshBrowser) CookiesRefreshSnapshot(_ context.Context, _ string, cookieStr string, snapshot []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, error) {
func (f *schedulerRefreshBrowser) CookiesRefreshSnapshot(_ context.Context, _ string, cookieStr string, snapshot []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, bool, error) {
f.refreshCalls++
return cookieStr, snapshot, nil
if snapshot == nil {
snapshot = cookierefresh.SnapshotFromCookieString(cookieStr, ".goofish.com")
}
return cookieStr, snapshot, f.officialReload, nil
}
type schedulerFakeStarter struct {
starts atomic.Int32
restarts atomic.Int32
}
func (f *schedulerFakeStarter) Start(context.Context, string, string) error {
f.starts.Add(1)
return nil
}
func (f *schedulerFakeStarter) Restart(context.Context, string) error {
f.restarts.Add(1)
return nil
}
func (f *schedulerFakeBrowser) BrowserQuickRenew(_ context.Context, _ string, cookieStr string, _ bool) (string, error) {
@@ -53,8 +79,8 @@ func (f *schedulerFakeBrowser) BrowserQuickRenew(_ context.Context, _ string, co
return f.quickCookies, f.quickErr
}
func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ string, _ []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, error) {
return "", nil, errors.New("not implemented")
func (f *schedulerFakeBrowser) CookiesRefreshSnapshot(_ context.Context, _, _ string, _ []cookierefresh.BrowserCookie, _ bool) (string, []cookierefresh.BrowserCookie, bool, error) {
return "", nil, false, errors.New("not implemented")
}
type schedulerFakePasswordRefresher struct {
@@ -180,6 +206,76 @@ func TestLoginRenewPreservesValidTokenCache(t *testing.T) {
}
}
func TestLoginRenewPersistsAuthoritativeSessionBeforeParseError(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-login-session-error",
"flat_leak=must-not-send; unb=1; _m_h5_tk=flat_old_1")
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "snapshot_old_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
metadata := cookierefresh.MetadataWithSnapshot(`{"preserved":"yes"}`, snapshot)
if err := store.Cookies.UpdateRenewalCookie(ctx, account.ID, account.Value, metadata, 1); err != nil {
t.Fatal(err)
}
var requestCookie string
client := &http.Client{Transport: schedulerRoundTripperFunc(func(req *http.Request) (*http.Response, error) {
requestCookie = req.Header.Get("Cookie")
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": []string{
"_m_h5_tk=snapshot_new_2; Domain=.goofish.com; Path=/; Secure",
"api_rotated=new; Path=/h5; Secure; HttpOnly",
}},
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
Request: req,
}, nil
})}
s := NewScheduler(store, nil, nil, nil, nil)
s.mtop = &mtop.ClientImpl{HTTPClient: client, LoginUserURL: mtop.LoginUserAPI}
s.loginRenewOne(ctx, "batch-login-session-error", account)
for _, want := range []string{"unb=1", "_m_h5_tk=snapshot_old_1", "api_only=api"} {
if !strings.Contains(requestCookie, want) {
t.Fatalf("请求 Cookie %q 未使用加锁后重读的权威 Jar,缺少 %q", requestCookie, want)
}
}
for _, unwanted := range []string{"flat_leak=", "document_only="} {
if strings.Contains(requestCookie, unwanted) {
t.Fatalf("请求 Cookie %q 泄漏了错误作用域 %q", requestCookie, unwanted)
}
}
detail, err := store.Cookies.GetDetails(ctx, account.ID)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(detail.Value, "_m_h5_tk=snapshot_new_2") || strings.Contains(detail.Value, "flat_leak=") {
t.Fatalf("正文解析失败后未优先持久化响应 Cookie Jar: %q", detail.Value)
}
if !strings.Contains(detail.MetadataJSON, `"preserved":"yes"`) {
t.Fatalf("持久化 Jar 时丢失原 metadata: %s", detail.MetadataJSON)
}
gotSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
t.Fatalf("响应后权威 snapshot 丢失: %s", detail.MetadataJSON)
}
values := make(map[string]string, len(gotSnapshot))
for _, cookie := range gotSnapshot {
values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path] = cookie.Value
}
if values["_m_h5_tk|.goofish.com|/"] != "snapshot_new_2" ||
values["api_rotated|h5api.m.goofish.com|/h5"] != "new" ||
values["document_only|www.goofish.com|/im"] != "doc" {
t.Fatalf("响应后 snapshot 作用域不完整: %+v", gotSnapshot)
}
}
func TestBrowserCookieRefreshSkipsManuallyDisabledAccount(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
@@ -356,6 +452,7 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
account := createSchedulerAccount(t, store, "cid-silent", "unb=1; cookie2=c2; havana_lgc_exp="+expire)
browser := &schedulerFakeBrowser{}
refresher := &schedulerFakePasswordRefresher{}
starter := &schedulerFakeStarter{}
var requests atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
@@ -364,13 +461,16 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
}))
defer srv.Close()
s := NewScheduler(store, nil, browser, refresher, nil)
s := NewScheduler(store, starter, browser, refresher, nil)
s.api = schedulerRenewServiceFromServer(srv)
s.apiCookieRenewOne(ctx, "batch-silent", account)
if requests.Load() != 1 || browser.quickCalls != 0 || refresher.calls.Load() != 0 {
t.Fatalf("requests=%d browser=%d password=%d", requests.Load(), browser.quickCalls, refresher.calls.Load())
}
if starter.restarts.Load() != 1 || starter.starts.Load() != 0 {
t.Fatalf("官网静默续期成功应模拟 reload 重建运行时: starts=%d restarts=%d", starter.starts.Load(), starter.restarts.Load())
}
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)
@@ -380,3 +480,18 @@ func TestAPICookieRenewOneUsesSingleSilentRequestAndSavesCookies(t *testing.T) {
t.Fatalf("silent renewal log=%+v", log)
}
}
func TestBrowserCookieRefreshRestartsOnlyAfterOfficialReload(t *testing.T) {
store, cleanup := newSchedulerTestStore(t)
defer cleanup()
ctx := context.Background()
account := createSchedulerAccount(t, store, "cid-browser-reload", "unb=1; havana_lgc_exp=1")
starter := &schedulerFakeStarter{}
browser := &schedulerRefreshBrowser{officialReload: true}
s := NewScheduler(store, starter, browser, nil, nil)
s.browserCookieRefreshOne(ctx, "batch-browser-reload", account, db.CookieRefreshSchedule{CookieID: account.ID})
if browser.refreshCalls != 1 || starter.restarts.Load() != 1 || starter.starts.Load() != 0 {
t.Fatalf("refresh=%d starts=%d restarts=%d", browser.refreshCalls, starter.starts.Load(), starter.restarts.Load())
}
}
+242 -52
View File
@@ -3,6 +3,7 @@ package server
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
@@ -41,25 +42,44 @@ func (s *Server) mountCookies(r chi.Router) {
func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
detail, ok := s.requireCookieOwner(w, r, cid)
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
result, err := s.CookieRenew.QueryLongLoginSettings(r.Context(), detail.Value)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
credentialUnlock := s.Store.LockAccountCredentials(cid)
detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL); err != nil {
requestCookies := scopedCookieHeader(detail, xrenew.QueryLoginSettingsURL)
var result *xrenew.LongLoginSettings
var requestErr error
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies, snapshot)
} else {
result, requestErr = s.CookieRenew.QueryLongLoginSettings(r.Context(), requestCookies)
}
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.QueryLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
return
}
if credentialChanged {
s.updateRunningCookie(r.Context(), cid, result.NewCookies)
}
if requestErr != nil {
writeErr(w, http.StatusBadGateway, requestErr.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
detail, ok := s.requireCookieOwner(w, r, cid)
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
@@ -70,41 +90,117 @@ func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
result, err := s.CookieRenew.SetLongLoginSettings(r.Context(), detail.Value, *req.Enabled)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
credentialUnlock := s.Store.LockAccountCredentials(cid)
detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL); err != nil {
requestCookies := scopedCookieHeader(detail, xrenew.SetLoginSettingsURL)
var result *xrenew.LongLoginSettings
var requestErr error
if snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled, snapshot)
} else {
result, requestErr = s.CookieRenew.SetLongLoginSettings(r.Context(), requestCookies, *req.Enabled)
}
credentialChanged, persistErr := s.persistLongLoginCookies(r.Context(), detail, result, xrenew.SetLoginSettingsURL)
credentialUnlock()
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存续期 Cookie 失败")
return
}
if credentialChanged {
s.updateRunningCookie(r.Context(), cid, result.NewCookies)
}
if requestErr != nil {
writeErr(w, http.StatusBadGateway, requestErr.Error())
return
}
writeJSON(w, http.StatusOK, result)
}
func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) error {
if result == nil || result.NewCookies == "" || result.NewCookies == detail.Value {
return nil
// persistLongLoginCookies 必须在账号凭证锁内调用。它只更新持久化状态;
// 运行中实例的 Cookie 更新必须等调用方释放凭证锁后再执行。
func (s *Server) persistLongLoginCookies(ctx context.Context, detail *db.CookieDetail, result *xrenew.LongLoginSettings, requestURL string) (bool, error) {
if result == nil || detail == nil {
return false, nil
}
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
if len(snapshot) == 0 {
snapshot = cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com")
metadata := detail.MetadataJSON
snapshot, hasSnapshot := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if result.CookieSnapshotComplete {
snapshot = cookierefresh.NormalizeSnapshot(result.CookieSnapshot)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
)
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
} else if hasSnapshot {
// 兼容非标准 Service 实现:只有未返回最终 Jar 时才按当前请求 URL
// 应用响应头;官方 Service 会在 SET→QUERY 间逐请求维护完整 Jar。
snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now(), "https://goofish.com")
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
result.NewCookies, _ = cookierefresh.ScopedCookieHeaderForRequest(
snapshot, "https://www.goofish.com/im", "https://goofish.com", time.Now(),
)
metadata = cookierefresh.MetadataWithSnapshot(metadata, snapshot)
} else {
// 历史账号只有扁平 Cookie 时只能合并兼容值,不能凭空推断完整
// Domain/Path/HttpOnly/PartitionKey 属性。
result.NewCookies = xrenew.MergeSetCookies(detail.Value, result.SetCookies)
metadata = cookierefresh.MetadataWithoutSnapshot(metadata)
}
credentialChanged := result.NewCookies != detail.Value || metadata != detail.MetadataJSON
if !credentialChanged && len(result.SetCookies) == 0 {
return false, nil
}
snapshot = cookierefresh.ApplySetCookies(snapshot, requestURL, result.SetCookies, time.Now())
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, result.NewCookies, metadata, time.Now().Unix()); err != nil {
s.Logger.Warn("保存长登录 Cookie 失败", "cookie_id", detail.ID, "err", err)
return err
return false, err
}
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, detail.ID)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, detail.ID) {
if err := s.Manager.Restart(ctx, detail.ID); err != nil {
s.Logger.Warn("保存登录信息更新后重启账号失败", "cookie_id", detail.ID, "err", err)
if credentialChanged && s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(ctx, detail.ID); err != nil {
s.Logger.Warn("长登录 Cookie 保存后清理旧连接凭证失败", "cookie_id", detail.ID, "err", err)
}
}
return nil
return credentialChanged, nil
}
// updateFlatCookieOwnedLocked 用新的扁平 Cookie 覆盖账号时同步移除旧浏览器
// 快照,避免下一次浏览器取 token 又把旧 Cookie 注入回来。调用方必须持有
// 对应账号的凭证锁,并已验证 detail 的归属。
func (s *Server) updateFlatCookieOwnedLocked(ctx context.Context, detail *db.CookieDetail, value string) error {
if detail == nil {
return db.ErrNotFound
}
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
return s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix())
}
func (s *Server) updateRunningCookie(ctx context.Context, cookieID, value string) {
if s.Manager == nil || !s.Store.Cookies.GetStatus(ctx, cookieID) {
return
}
if sender, ok := s.Manager.GetInstance(cookieID); ok {
sender.UpdateCookie(value)
}
}
func scopedCookieHeader(detail *db.CookieDetail, requestURL string) string {
if detail == nil {
return ""
}
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
if header, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, "https://goofish.com", time.Now()); authoritative {
return header
}
}
return detail.Value
}
type updateCookieSettingsRequest struct {
@@ -148,6 +244,15 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
return
}
credentialUnlock := s.Store.LockAccountCredentials(cid)
latestDetail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || latestDetail == nil || latestDetail.UserID != detail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
detail = latestDetail
input := db.AccountSettingsUpdate{
UserID: detail.UserID,
Value: req.Cookie,
@@ -179,6 +284,7 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
}
pausedUntil, err := s.Store.Cookies.UpdateSettings(r.Context(), cid, input)
if err != nil {
credentialUnlock()
switch {
case errors.Is(err, db.ErrForbidden):
writeErr(w, http.StatusForbidden, "账号设置包含无权限使用的资源")
@@ -189,9 +295,16 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
}
return
}
if req.Cookie != nil && s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(r.Context(), cid)
if req.Cookie != nil {
// UpdateSettings 已在同一事务中写入 Cookie 并清除旧快照,不能再做
// 第二次非原子覆盖。
if s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
s.Logger.Warn("账号设置保存后清理旧连接凭证失败", "cookie_id", cid, "err", err)
}
}
}
credentialUnlock()
if req.Cookie != nil && s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
@@ -349,7 +462,9 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
return
}
sess := auth.SessionFromContext(r.Context())
credentialUnlock := s.Store.LockAccountCredentials(req.ID)
if err := s.Store.Cookies.CreateOwned(r.Context(), req.ID, req.Value, sess.UserID); err != nil {
credentialUnlock()
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
return
@@ -362,16 +477,19 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
return
}
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(r.Context(), req.ID)
}
if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
s.refreshAccountProfile(r.Context(), d)
if err := s.Store.Tokens.Clear(r.Context(), req.ID); err != nil {
s.Logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", req.ID, "err", err)
}
}
loginMethod := normalizeLoginMethod(req.LoginMethod)
if loginMethod == "" {
loginMethod = loginMethodManual
}
s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功")
credentialUnlock()
if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
@@ -383,7 +501,8 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
// updateCookie 更新 cookie 值。
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
var req struct {
@@ -395,7 +514,15 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), cid, req.Value, sess.UserID); err != nil {
credentialUnlock := s.Store.LockAccountCredentials(cid)
detail, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID || detail.UserID != sess.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.updateFlatCookieOwnedLocked(r.Context(), detail, req.Value); err != nil {
credentialUnlock()
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
@@ -404,14 +531,17 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
return
}
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(r.Context(), cid)
}
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
s.refreshAccountProfile(r.Context(), d)
if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", cid, "err", err)
}
}
if loginMethod := normalizeLoginMethod(req.LoginMethod); loginMethod != "" {
s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功")
}
credentialUnlock()
if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil {
s.refreshAccountProfile(r.Context(), d)
}
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
if err := s.Manager.Restart(r.Context(), cid); err != nil {
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
@@ -457,7 +587,8 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
// setCookieStatus 启用/禁用账号。
func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
var req struct {
@@ -471,10 +602,19 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
if !req.Enabled {
reason = db.DisableReasonManual
}
credentialUnlock := s.Store.LockAccountCredentials(cid)
latest, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.Store.Cookies.SetStatusWithReason(r.Context(), cid, req.Enabled, reason); err != nil {
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
credentialUnlock()
// 启停引擎实例。
if s.Manager != nil {
if req.Enabled {
@@ -494,16 +634,28 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
// deleteCookie 删除账号。
func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
if !ok {
return
}
if s.Manager != nil {
s.Manager.Stop(cid)
credentialUnlock := s.Store.LockAccountCredentials(cid)
latest, err := s.Store.Cookies.GetDetails(r.Context(), cid)
if err != nil || latest == nil || latest.UserID != ownedDetail.UserID {
credentialUnlock()
writeErr(w, http.StatusNotFound, "账号不存在")
return
}
if err := s.Store.Cookies.Delete(r.Context(), cid); err != nil {
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
credentialUnlock()
// Stop 会等待 Account.Run 退出,而 Run 可能正在等待同一凭证锁,因此必须
// 在删除事务完成并释放锁后调用。
if s.Manager != nil {
s.Manager.Stop(cid)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
@@ -612,19 +764,57 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail)
return cachedAccountNickname(d), d.AvatarURL, "账号资料客户端未初始化"
}
profile, err := s.MTop.FetchUserProfile(ctx, d.Value)
if err != nil {
if s.Logger != nil {
s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", err)
credentialUnlock := s.Store.LockAccountCredentials(d.ID)
latest, latestErr := s.Store.Cookies.GetDetails(ctx, d.ID)
if latestErr != nil || latest == nil || latest.UserID != d.UserID {
credentialUnlock()
if latestErr == nil {
latestErr = db.ErrNotFound
}
return cachedAccountNickname(d), d.AvatarURL, truncate(err.Error(), 180)
return cachedAccountNickname(d), d.AvatarURL, truncate(latestErr.Error(), 180)
}
if profile.UpdatedCookies != "" && profile.UpdatedCookies != d.Value {
if err := s.Store.Cookies.UpdateValueOwned(ctx, d.ID, profile.UpdatedCookies, d.UserID); err != nil && s.Logger != nil {
s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
profile, callErr := s.MTop.FetchUserProfile(mtopCtx, latest.Value)
runtimeCookie := ""
runtimeCookieChanged := false
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Warn("保存账号资料响应 Cookie Jar 失败", "account", d.ID, "err", persistErr)
}
d.Value = profile.UpdatedCookies
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", persistErr))
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
d.Value = value
} else if callErr == nil && profile != nil && profile.UpdatedCookies != "" && profile.UpdatedCookies != latest.Value {
// 注入 mock 或没有权威快照的历史账号继续沿用扁平 Cookie 路径;
// 该路径必须清除旧 snapshot,不能伪造完整 Jar。
if err := s.updateFlatCookieOwnedLocked(ctx, latest, profile.UpdatedCookies); err != nil {
if s.Logger != nil {
s.Logger.Warn("保存账号刷新 cookie 失败", "account", d.ID, "err", err)
}
callErr = errors.Join(callErr, fmt.Errorf("保存账号资料响应凭证: %w", err))
} else {
runtimeCookie = profile.UpdatedCookies
runtimeCookieChanged = true
d.Value = profile.UpdatedCookies
}
}
credentialUnlock()
if runtimeCookieChanged {
s.updateRunningCookie(ctx, d.ID, runtimeCookie)
}
if callErr != nil {
if s.Logger != nil {
s.Logger.Warn("刷新账号资料失败", "account", d.ID, "err", callErr)
}
return cachedAccountNickname(d), d.AvatarURL, truncate(callErr.Error(), 180)
}
if profile == nil {
return cachedAccountNickname(d), d.AvatarURL, "账号资料接口未返回结果"
}
apiNickname := strings.TrimSpace(profile.Nickname)
+215 -2
View File
@@ -15,17 +15,52 @@ import (
xrenew "xianyu-go/internal/xianyu/renew"
)
func seedStaleCookieSnapshot(t *testing.T, store *db.Store, cookieID string) {
t.Helper()
ctx := context.Background()
detail, err := store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
t.Fatalf("GetDetails before seeding snapshot: %v", err)
}
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, []cookierefresh.BrowserCookie{{
Name: "stale_snapshot", Value: "old", Domain: ".goofish.com", Path: "/",
}})
if err := store.Cookies.UpdateRenewalCookie(ctx, cookieID, detail.Value, metadata, time.Now().Unix()); err != nil {
t.Fatalf("seed stale snapshot: %v", err)
}
}
func requireCookieSnapshotCleared(t *testing.T, store *db.Store, cookieID string) {
t.Helper()
detail, err := store.Cookies.GetDetails(context.Background(), cookieID)
if err != nil {
t.Fatalf("GetDetails after cookie overwrite: %v", err)
}
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); ok {
t.Fatalf("扁平 Cookie 覆盖后必须清除旧快照: %+v", snapshot)
}
}
func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("fromSite") != "77" || r.URL.Query().Get("appName") != "xianyu" || r.URL.Query().Get("bizEntrance") != "web" {
t.Fatalf("query=%s", r.URL.RawQuery)
}
requestCookies := r.Header.Get("Cookie")
if !strings.Contains(requestCookies, "passport_only=allowed") || strings.Contains(requestCookies, "www_only=blocked") {
http.Error(w, "Cookie 未按 passport 域作用域发送: "+requestCookies, http.StatusBadRequest)
return
}
if strings.Contains(r.URL.Path, "set") {
if err := r.ParseForm(); err != nil || r.Form.Get("status") != "0" {
t.Fatalf("form=%v err=%v", r.Form, err)
}
}
w.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure; HttpOnly; SameSite=None")
if strings.Contains(r.URL.Path, "set") {
_, _ = w.Write([]byte(`{"data":{"success":true}}`))
return
}
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer passport.Close()
@@ -37,6 +72,19 @@ func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
SetLoginSettingsURL: passport.URL + "/setLoginSettings.do",
}
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
snapshot := cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com")
snapshot = append(snapshot,
cookierefresh.BrowserCookie{Name: "passport_only", Value: "allowed", Domain: ".goofish.com", Path: "/", Secure: true},
cookierefresh.BrowserCookie{Name: "www_only", Value: "blocked", Domain: "www.goofish.com", Path: "/", Secure: true},
)
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if err := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", detail.Value, metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
h := srv.Router()
session := loginHelper(t, h)
@@ -56,11 +104,11 @@ func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
}
}
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
detail, err = store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil || !strings.Contains(detail.Value, "havana_lgc_exp=4102444800000") {
t.Fatalf("cookie detail=%+v err=%v", detail, err)
}
snapshot := cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
snapshot = cookierefresh.SnapshotFromMetadata(detail.MetadataJSON)
var longLoginCookie *cookierefresh.BrowserCookie
for i := range snapshot {
if snapshot[i].Name == "havana_lgc_exp" {
@@ -73,6 +121,85 @@ func TestLongLoginSettingsProxyAndPersistCookieSnapshot(t *testing.T) {
}
}
func TestLongLoginFailureStillPersistsResponseCookiesWithoutInventingSnapshot(t *testing.T) {
passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
_, _ = w.Write([]byte(`not-json`))
}))
defer passport.Close()
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.CookieRenew = xrenew.Service{
HTTPClient: passport.Client(),
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
}
h := srv.Router()
session := loginHelper(t, h)
req := httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil)
req.AddCookie(session)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusBadGateway {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(detail.Value, "rotated=fresh") {
t.Fatalf("失败响应头的 Cookie 未持久化: %q", detail.Value)
}
if _, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON); complete {
t.Fatal("历史扁平 Cookie 不得因长登录响应伪造成完整浏览器 Jar")
}
}
func TestLongLoginAuthoritativeSnapshotCanBeDeletedToEmpty(t *testing.T) {
passport := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Set-Cookie", "only_cookie=; Domain=.goofish.com; Path=/; Max-Age=0; Secure")
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer passport.Close()
srv, store, cleanup := newTestServer(t)
defer cleanup()
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, []cookierefresh.BrowserCookie{{
Name: "only_cookie", Value: "old", Domain: ".goofish.com", Path: "/", Secure: true,
}})
if err := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", "only_cookie=old", metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
srv.CookieRenew = xrenew.Service{
HTTPClient: passport.Client(),
QueryLoginSettingsURL: passport.URL + "/queryLoginSettings.do",
}
h := srv.Router()
session := loginHelper(t, h)
req := httptest.NewRequest(http.MethodGet, "/cookies/acc1/long-login", nil)
req.AddCookie(session)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
detail, err = store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
if detail.Value != "" {
t.Fatalf("权威 Jar 删除后扁平值=%q want empty", detail.Value)
}
snapshot, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !complete || len(snapshot) != 0 {
t.Fatalf("应保留权威空 Jar,complete=%v snapshot=%+v", complete, snapshot)
}
}
// TestListCookies 列表 cookie_id。
func TestListCookies(t *testing.T) {
srv, _, cleanup := newTestServer(t)
@@ -221,6 +348,7 @@ func TestUpdateCookieSettingsClearsTokenButKeepsDeviceID(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "permanent-device", "old-token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
seedStaleCookieSnapshot(t, store, "acc1")
h := srv.Router()
cookie := loginHelper(t, h)
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/settings", strings.NewReader(`{"cookie":"unb=123; _m_h5_tk=new_1;"}`))
@@ -234,6 +362,7 @@ func TestUpdateCookieSettingsClearsTokenButKeepsDeviceID(t *testing.T) {
if err != nil || token.DeviceID != "permanent-device" || token.AccessToken != "" || token.ExpireAt != 0 {
t.Fatalf("token=%+v err=%v", token, err)
}
requireCookieSnapshotCleared(t, store, "acc1")
}
func jsonInt(value int64) string { return strconv.FormatInt(value, 10) }
@@ -264,6 +393,7 @@ func TestUpdateCookie(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "permanent-device", "old-token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatal(err)
}
seedStaleCookieSnapshot(t, store, "acc1")
body := `{"value":"unb=123; _m_h5_tk=newtoken_2;"}`
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1", strings.NewReader(body))
@@ -284,6 +414,7 @@ func TestUpdateCookie(t *testing.T) {
if err != nil || token.DeviceID != "permanent-device" || token.AccessToken != "" || token.ExpireAt != 0 {
t.Fatalf("token=%+v err=%v", token, err)
}
requireCookieSnapshotCleared(t, store, "acc1")
}
func TestUpdateCookieQRLoginEnablesAccount(t *testing.T) {
@@ -345,6 +476,88 @@ func TestSetCookieStatusRecordsManualDisableReason(t *testing.T) {
}
}
func TestSetCookieStatusWaitsForCredentialTransition(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
h := srv.Router()
cookie := loginHelper(t, h)
credentialUnlock := store.LockAccountCredentials("acc1")
done := make(chan *httptest.ResponseRecorder, 1)
go func() {
req := httptest.NewRequest(http.MethodPut, "/cookies/acc1/status", strings.NewReader(`{"enabled":false}`))
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
done <- rec
}()
select {
case rec := <-done:
credentialUnlock()
t.Fatalf("状态更新绕过了账号凭证锁: status=%d body=%s", rec.Code, rec.Body.String())
case <-time.After(50 * time.Millisecond):
}
credentialUnlock()
select {
case rec := <-done:
if rec.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
case <-time.After(2 * time.Second):
t.Fatal("释放凭证锁后状态更新未完成")
}
}
func TestDeleteCookieRechecksOwnershipInsideCredentialLock(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
ctx := context.Background()
if ok, err := store.Users.Create(ctx, "member-delete", "[email protected]", "pw"); err != nil || !ok {
t.Fatalf("create replacement owner: ok=%v err=%v", ok, err)
}
replacementOwner, err := store.Users.GetByUsername(ctx, "member-delete")
if err != nil {
t.Fatal(err)
}
h := srv.Router()
cookie := loginHelper(t, h)
credentialUnlock := store.LockAccountCredentials("acc1")
done := make(chan *httptest.ResponseRecorder, 1)
go func() {
req := httptest.NewRequest(http.MethodDelete, "/cookies/acc1", nil)
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
done <- rec
}()
select {
case rec := <-done:
credentialUnlock()
t.Fatalf("删除绕过了账号凭证锁: status=%d body=%s", rec.Code, rec.Body.String())
case <-time.After(50 * time.Millisecond):
}
if err := store.Cookies.Delete(ctx, "acc1"); err != nil {
credentialUnlock()
t.Fatal(err)
}
if err := store.Cookies.CreateOwned(ctx, "acc1", "unb=replacement; _m_h5_tk=fresh", replacementOwner.ID); err != nil {
credentialUnlock()
t.Fatal(err)
}
credentialUnlock()
rec := <-done
if rec.Code == http.StatusOK {
t.Fatalf("旧 owner 的并发请求不得删除新 owner 账号: body=%s", rec.Body.String())
}
detail, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil || detail.UserID != replacementOwner.ID {
t.Fatalf("替换后的账号被误删: detail=%+v err=%v", detail, err)
}
}
// TestUpdateCookieBadJSON 非法 JSON 400。
func TestUpdateCookieBadJSON(t *testing.T) {
srv, _, cleanup := newTestServer(t)
+158 -28
View File
@@ -53,7 +53,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请选择发布账号")
return
}
cookieValue, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
_, userID, ok := s.cookieForCurrentUser(w, r, cookieID)
if !ok {
return
}
@@ -88,10 +88,19 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
client := s.mtopClient()
res, err := client.PublishItem(ctx, cookieValue, mtop.PublishItemRequest{
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
Title: title,
Description: description,
PriceCents: priceCents,
@@ -101,9 +110,37 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
PostageCents: postageCents,
Images: images,
})
if err != nil {
runtimeCookie := ""
runtimeCookieChanged := false
var responseCookieErr error
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
s.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
responseCookieErr = persistErr
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
} else if callErr == nil && res != nil && res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), cookieID, res.UpdatedCookies, userID); saveErr != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr)
responseCookieErr = saveErr
} else {
runtimeCookie = res.UpdatedCookies
runtimeCookieChanged = true
}
}
credentialUnlock()
if runtimeCookieChanged {
s.updateRunningCookie(r.Context(), cookieID, runtimeCookie)
}
if callErr != nil {
if responseCookieErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr))
}
var perr *mtop.PublishError
if errors.As(err, &perr) {
if errors.As(callErr, &perr) {
status := http.StatusBadGateway
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
@@ -118,7 +155,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
writeErr(w, http.StatusBadGateway, err.Error())
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
if res == nil || strings.TrimSpace(res.ItemID) == "" {
@@ -129,11 +166,6 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), cookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
}
}
detail := map[string]any{
"item_image": res.ImageURL,
"web_url": res.ItemURL,
@@ -164,6 +196,16 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
return
}
if responseCookieErr != nil {
writeJSON(w, http.StatusInternalServerError, map[string]any{
"success": false,
"code": "remote_published_cookie_save_failed",
"message": "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录",
"item_id": res.ItemID,
"item_url": res.ItemURL,
})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "商品发布成功",
@@ -295,31 +337,75 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
cookieValue := latest.Value
if req.PageSize <= 0 {
req.PageSize = 20
}
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
client := s.mtopClient()
res, err := client.FetchAllItems(ctx, cookieValue, req.PageSize, req.MaxPages)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
return
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
res, callErr := client.FetchAllItems(mtopCtx, cookieValue, req.PageSize, req.MaxPages)
if callErr == nil && res == nil {
callErr = errors.New("商品列表接口未返回结果")
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
if callErr != nil {
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
credentialUnlock()
if persistErr != nil {
s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
return
} else if valueChanged {
s.updateRunningCookie(r.Context(), req.CookieID, value)
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
detailCookies := cookieValue
if res.UpdatedCookies != "" {
detailCookies = res.UpdatedCookies
}
s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items)
s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
runtimeCookie := ""
runtimeCookieChanged := false
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
s.Logger.Error("保存商品同步响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
return
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
} else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品同步响应凭证保存失败")
return
} else {
runtimeCookie = res.UpdatedCookies
runtimeCookieChanged = true
}
}
credentialUnlock()
if runtimeCookieChanged {
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
@@ -340,28 +426,72 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusBadRequest, "缺少 cookie_id 参数")
return
}
cookieValue, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
if !ok {
return
}
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
client := s.mtopClient()
res, err := client.FetchItemsPage(ctx, cookieValue, req.PageNumber, req.PageSize)
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
return
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
res, callErr := client.FetchItemsPage(mtopCtx, cookieValue, req.PageNumber, req.PageSize)
if callErr == nil && res == nil {
callErr = errors.New("商品列表接口未返回结果")
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", err)
if callErr != nil {
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
credentialUnlock()
if persistErr != nil {
s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
return
} else if valueChanged {
s.updateRunningCookie(r.Context(), req.CookieID, value)
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
detailCookies := cookieValue
if res.UpdatedCookies != "" {
detailCookies = res.UpdatedCookies
}
s.enrichSyncedItemMultiSpec(ctx, client, detailCookies, req.CookieID, res.Items)
s.enrichSyncedItemMultiSpec(mtopCtx, client, detailCookies, req.CookieID, res.Items)
runtimeCookie := ""
runtimeCookieChanged := false
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
s.Logger.Error("保存商品分页响应 Cookie Jar 失败", "cookie_id", req.CookieID, "err", persistErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
return
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
} else if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, res.UpdatedCookies, userID); saveErr != nil {
s.Logger.Error("保存刷新后的 cookie 失败", "cookie_id", req.CookieID, "err", saveErr)
credentialUnlock()
writeErr(w, http.StatusInternalServerError, "商品分页响应凭证保存失败")
return
} else {
runtimeCookie = res.UpdatedCookies
runtimeCookieChanged = true
}
}
credentialUnlock()
if runtimeCookieChanged {
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
+66 -17
View File
@@ -775,6 +775,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
origCents, _ := parseMoneyCents(row.OriginalPrice)
postageCents, _ := parseMoneyCents(row.Postage)
res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity}
var responseCookieErr error
if row.ItemID == "" {
images, err := loadBatchPublishImages(ctx, batch.UploadDir, row)
if err != nil {
@@ -786,18 +787,68 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if markErr != nil || !remoteStarted {
return fmt.Errorf("保存远端发布前检查点失败: %w", firstError(markErr, errors.New("批次租约已失效")))
}
pctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
res, err = client.PublishItem(pctx, cookieValue, mtop.PublishItemRequest{
Title: row.Title,
Description: firstNonEmpty(row.Description, row.Title),
PriceCents: priceCents,
OriginalPriceCents: origCents,
Quantity: row.Quantity,
PostageMode: row.PostageMode,
PostageCents: postageCents,
Images: images,
})
cancel()
runtimeCookie := ""
runtimeCookieChanged := false
res, err = func() (*mtop.PublishItemResult, error) {
credentialUnlock := s.Store.LockAccountCredentials(row.CookieID)
defer credentialUnlock()
latest, latestErr := s.Store.Cookies.GetDetails(ctx, row.CookieID)
if latestErr != nil {
return nil, latestErr
}
if latest == nil || latest.UserID != userID {
return nil, db.ErrForbidden
}
if !hasStoredCookieCredential(latest) {
return nil, errors.New("账号 Cookie 为空")
}
cookieValue = latest.Value
pctx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
mtopCtx, cookieSession := withMTopCookieSnapshot(pctx, latest)
published, publishErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
Title: row.Title,
Description: firstNonEmpty(row.Description, row.Title),
PriceCents: priceCents,
OriginalPriceCents: origCents,
Quantity: row.Quantity,
PostageMode: row.PostageMode,
PostageCents: postageCents,
Images: images,
})
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
cookieErr := fmt.Errorf("发布商品后保存响应 Cookie Jar: %w", persistErr)
if publishErr != nil {
return published, errors.Join(publishErr, cookieErr)
}
responseCookieErr = cookieErr
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
} else if publishErr == nil && published != nil && published.UpdatedCookies != "" && published.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueOwned(ctx, row.CookieID, published.UpdatedCookies, userID); saveErr != nil {
responseCookieErr = fmt.Errorf("发布商品后保存响应 Cookie: %w", saveErr)
} else {
runtimeCookie = published.UpdatedCookies
runtimeCookieChanged = true
}
}
if publishErr != nil {
return published, publishErr
}
if published == nil {
return nil, errors.New("发布商品接口未返回结果")
}
return published, nil
}()
if runtimeCookieChanged && s.Manager != nil {
if account, running := s.Manager.GetInstance(row.CookieID); running {
account.UpdateCookie(runtimeCookie)
}
}
if err != nil {
if ctx.Err() != nil {
return &uncertainRemotePublishError{err: fmt.Errorf("取消时远端发布结果未知: %w", err)}
@@ -818,6 +869,9 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if saveErr != nil || !saved {
return &uncertainRemotePublishError{err: fmt.Errorf("保存远端发布结果失败: %w", firstError(saveErr, errors.New("批次租约已失效")))}
}
if responseCookieErr != nil {
return &postPublishError{err: responseCookieErr}
}
} else if strings.TrimSpace(row.RawJSON) != "" {
_ = json.Unmarshal([]byte(row.RawJSON), &res.RawData)
}
@@ -828,11 +882,6 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
if err != nil || currentBatch.Status == "canceled" || currentBatch.WorkerToken != workerToken {
return &postPublishError{err: context.Canceled}
}
if res.UpdatedCookies != "" && res.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(ctx, row.CookieID, res.UpdatedCookies, userID); err != nil {
s.Logger.Error("发布商品后保存刷新 cookie 失败", "cookie_id", row.CookieID, "err", err)
}
}
if res.ItemID != "" {
detail := map[string]any{
"item_image": res.ImageURL,
+61
View File
@@ -0,0 +1,61 @@
package server
import (
"context"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
// withMTopCookieSnapshot 为一次业务 MTOP 流程挂载账号 Cookie 会话。有完整
// Jar 时保持所有作用域;历史账号则使用不冒充完整 Jar 的 flat session,仍能
// 在成功或失败路径观察并持久化 Set-Cookie。
func withMTopCookieSnapshot(ctx context.Context, detail *db.CookieDetail) (context.Context, *mtop.CookieSession) {
if detail == nil {
return ctx, nil
}
snapshot, ok := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
if !ok {
return mtop.WithFlatCookieSession(ctx, detail.Value)
}
return mtop.WithCookieSnapshot(ctx, snapshot)
}
func hasStoredCookieCredential(detail *db.CookieDetail) bool {
if detail == nil {
return false
}
if detail.Value != "" {
return true
}
_, complete := cookierefresh.SnapshotFromMetadataOK(detail.MetadataJSON)
return complete
}
// persistMTopCookieSessionLocked 原子保存业务 MTOP 响应后的完整 Cookie Jar。
// 调用方必须持有账号凭证锁,并且 detail 必须是加锁后重读的最新记录。
// handled 表示 session 已产生权威更新;此时即使保存失败,也不得再退回扁平
// UpdatedCookies 写回,否则会清除或覆盖完整 Jar。
func (s *Server) persistMTopCookieSessionLocked(
ctx context.Context,
detail *db.CookieDetail,
session *mtop.CookieSession,
) (value string, valueChanged, handled bool, err error) {
if detail == nil || session == nil {
return "", false, false, nil
}
value, snapshot, changed := session.State()
if !changed {
return "", false, false, nil
}
metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON)
if snapshot != nil {
metadata = cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
}
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, value, metadata, time.Now().Unix()); err != nil {
return value, value != detail.Value, true, err
}
return value, value != detail.Value, true, nil
}
+110
View File
@@ -0,0 +1,110 @@
package server
import (
"context"
"io"
"net/http"
"strings"
"testing"
"time"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
type stubProfileMTop struct {
mtop.Client
profile func(context.Context, string) (*mtop.UserProfileResult, error)
}
func (s *stubProfileMTop) FetchUserProfile(ctx context.Context, cookies string) (*mtop.UserProfileResult, error) {
return s.profile(ctx, cookies)
}
func TestRefreshAccountProfilePersistsCookieSessionOnResponseError(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
detail, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "tk1_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "keep", Value: "yes", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, snapshot)
if err := store.Cookies.UpdateRenewalCookie(ctx, detail.ID, detail.Value, metadata, time.Now().Unix()); err != nil {
t.Fatal(err)
}
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
header := make(http.Header)
header.Add("Set-Cookie", "rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly")
return &http.Response{
StatusCode: http.StatusOK,
Header: header,
Body: io.NopCloser(strings.NewReader(`{"ret":`)),
Request: req,
}, nil
})}
srv.MTop = client
detail, err = store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
_, _, message := srv.refreshAccountProfile(ctx, detail)
if message == "" {
t.Fatal("无效响应应返回解析错误")
}
updated, err := store.Cookies.GetDetails(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(updated.Value, "rotated=fresh") {
t.Fatalf("响应错误时仍应保存 canonical Cookie: %q", updated.Value)
}
updatedSnapshot, ok := cookierefresh.SnapshotFromMetadataOK(updated.MetadataJSON)
if !ok {
t.Fatal("响应错误时不应清除权威 Cookie Jar")
}
values := make(map[string]string, len(updatedSnapshot))
for _, cookie := range updatedSnapshot {
values[cookie.Name+"@"+cookie.Domain+cookie.Path] = cookie.Value
}
if values["[email protected]/"] != "fresh" || values["[email protected]/im"] != "yes" {
t.Fatalf("Cookie Jar 写回不完整: %+v", updatedSnapshot)
}
}
func TestRefreshAccountProfileKeepsFlatMockFallback(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
seedStaleCookieSnapshot(t, store, "acc1")
srv.MTop = &stubProfileMTop{profile: func(context.Context, string) (*mtop.UserProfileResult, error) {
return &mtop.UserProfileResult{
Nickname: "mock-profile",
UpdatedCookies: "unb=123; _m_h5_tk=mockfresh_2",
}, nil
}}
detail, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
srv.refreshAccountProfile(context.Background(), detail)
requireCookieSnapshotCleared(t, store, "acc1")
updated, err := store.Cookies.GetDetails(context.Background(), "acc1")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(updated.Value, "_m_h5_tk=mockfresh_2") {
t.Fatalf("mock 扁平 Cookie 未沿用兼容写回: %q", updated.Value)
}
}
+155 -35
View File
@@ -13,6 +13,7 @@ import (
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
)
@@ -186,8 +187,33 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
results := []map[string]any{}
newOrderIDs := make(map[string]struct{})
if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok {
for cid, cookieValue := range all {
accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(r.Context(), fetcher, cid, cookieValue)
for cid := range all {
credentialUnlock := s.Store.LockAccountCredentials(cid)
latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
credentialUnlock()
if latestErr == nil {
latestErr = errors.New("账号凭证已变化")
}
failed++
results = append(results, map[string]any{
"cookie_id": cid, "stage": "discover", "success": false, "error": latestErr.Error(),
})
continue
}
all[cid] = latest.Value
mtopCtx, cookieSession := withMTopCookieSnapshot(r.Context(), latest)
accountDiscovered, accountUpdated, accountNewIDs, discoveryErr := s.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
} else if valueChanged {
all[cid] = value
}
credentialUnlock()
if persistErr == nil && valueChanged {
s.updateRunningCookie(r.Context(), cid, value)
}
discovered += accountDiscovered
listUpdated += accountUpdated
for orderID := range accountNewIDs {
@@ -271,11 +297,6 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
updated, noChange := 0, 0
for cid, targets := range ordersByCookie {
cookieValue := all[cid]
if cookieValue == "" {
failed += len(targets)
continue
}
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
orderIDs := make([]string, 0, len(chunk))
currentStatus := make(map[string]string, len(chunk))
@@ -283,9 +304,26 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
orderIDs = append(orderIDs, target.OrderID)
currentStatus[target.OrderID] = target.CurrentStatus
}
credentialUnlock := s.Store.LockAccountCredentials(cid)
latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid)
if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
credentialUnlock()
failed += len(chunk)
results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": "账号凭证已变化"})
continue
}
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
batch, err := s.Browser.BatchRefreshOrders(ctx, orderIDs, cid, cookieValue)
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
batch, err := s.Browser.BatchRefreshOrders(mtopCtx, orderIDs, cid, latest.Value)
cancel()
value, valueChanged, _, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
err = errors.Join(err, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
}
credentialUnlock()
if persistErr == nil && valueChanged {
s.updateRunningCookie(r.Context(), cid, value)
}
if err != nil {
failed += len(chunk)
results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": err.Error()})
@@ -465,27 +503,66 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
return
}
cookieID := order.CookieID
cookieValue, _, ok := s.cookieForCurrentUser(w, r, cookieID)
if !ok {
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
credentialLocked := true
defer func() {
if credentialLocked {
credentialUnlock()
}
}()
sess := auth.SessionFromContext(r.Context())
latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID)
if err != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
defer cancel()
detail, err := s.Browser.FetchOrderDetail(ctx, orderID, cookieID, cookieValue, s.Store.Items.IsMultiSpec(ctx, cookieID, order.ItemID))
if err != nil {
writeErr(w, http.StatusBadGateway, err.Error())
return
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
detail, callErr := s.Browser.FetchOrderDetail(mtopCtx, orderID, cookieID, cookieValue, s.Store.Items.IsMultiSpec(mtopCtx, cookieID, order.ItemID))
if callErr == nil && detail == nil {
callErr = errors.New("订单详情接口未返回结果")
}
if detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueExisting(r.Context(), cookieID, detail.UpdatedCookies); err != nil {
s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", err)
runtimeCookie := ""
runtimeCookieChanged := false
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if !handled && detail != nil && detail.CookieSnapshotComplete {
// 没有历史 snapshot 时不会创建 CookieSession;浏览器 fallback 返回的
// 完整 Jar 仍是权威结果,必须原子落库(包括空 Jar/空 flat)。
value = detail.UpdatedCookies
valueChanged = value != latest.Value
handled = true
metadata := cookierefresh.MetadataWithSnapshot(latest.MetadataJSON, detail.CookieSnapshot)
persistErr = s.Store.Cookies.UpdateRenewalCookie(r.Context(), cookieID, value, metadata, time.Now().Unix())
}
if persistErr != nil {
s.Logger.Error("保存订单详情响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
callErr = errors.Join(callErr, fmt.Errorf("保存订单详情响应 Cookie Jar: %w", persistErr))
} else if handled {
if valueChanged {
runtimeCookie = value
runtimeCookieChanged = true
}
if s.Manager != nil {
if account, running := s.Manager.GetInstance(cookieID); running {
account.UpdateCookie(detail.UpdatedCookies)
}
} else if callErr == nil && detail.UpdatedCookies != "" && detail.UpdatedCookies != cookieValue {
if saveErr := s.Store.Cookies.UpdateValueExisting(r.Context(), cookieID, detail.UpdatedCookies); saveErr != nil {
s.Logger.Error("保存订单详情刷新后的 cookie 失败", "cookie_id", cookieID, "err", saveErr)
} else {
runtimeCookie = detail.UpdatedCookies
runtimeCookieChanged = true
}
}
credentialUnlock()
credentialLocked = false
if runtimeCookieChanged && s.Manager != nil {
if account, running := s.Manager.GetInstance(cookieID); running {
account.UpdateCookie(runtimeCookie)
}
}
if callErr != nil {
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
status := db.NormalizeOrderStatus(detail.OrderStatus)
if !validEditableOrderStatus(status) {
status = db.NormalizeOrderStatus(order.OrderStatus)
@@ -677,7 +754,7 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "订单不存在"})
continue
}
cookieValue, ok := userCookies[order.CookieID]
_, ok := userCookies[order.CookieID]
if !ok {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "无权操作此订单"})
@@ -721,23 +798,18 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "mtop 客户端未初始化"})
continue
}
ok, ret, updatedCookies, err := s.MTop.ConsignContext(r.Context(), cookieValue, orderID)
if err != nil {
ok, ret, runtimeCookie, runtimeCookieChanged, err := s.consignWithCurrentCookie(r.Context(), order.CookieID, orderID, sess.UserID)
if runtimeCookieChanged && s.Manager != nil {
if acc, running := s.Manager.GetInstance(order.CookieID); running {
acc.UpdateCookie(runtimeCookie)
}
}
if err != nil && !ok {
failedCount++
results = append(results, map[string]any{"order_id": orderID, "success": false, "message": "确认发货异常: " + err.Error()})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID, "手动确认发货异常: "+err.Error())
continue
}
if updatedCookies != "" && updatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), order.CookieID, updatedCookies, sess.UserID); err != nil {
s.Logger.Error("保存发货刷新后的 cookie 失败", "cookie_id", order.CookieID, "err", err)
}
if s.Manager != nil {
if acc, running := s.Manager.GetInstance(order.CookieID); running {
acc.UpdateCookie(updatedCookies)
}
}
}
if !ok {
failedCount++
msg := "确认发货失败"
@@ -768,7 +840,13 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
s.Logger.Error("更新订单为系统已发货失败", "order_id", orderID, "err", err)
}
successCount++
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "已成功修改闲鱼发货状态"})
message := "已成功修改闲鱼发货状态"
credentialWarning := ""
if err != nil {
message += ";但登录凭证更新保存失败,请尽快重新登录(请勿重复确认发货)"
credentialWarning = err.Error()
}
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": message, "credential_warning": credentialWarning})
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
}
@@ -781,6 +859,48 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
})
}
func (s *Server) consignWithCurrentCookie(ctx context.Context, cookieID, orderID string, userID int64) (bool, []string, string, bool, error) {
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
defer credentialUnlock()
detail, err := s.Store.Cookies.GetDetails(ctx, cookieID)
if err != nil {
return false, nil, "", false, err
}
if detail == nil || detail.UserID != userID {
return false, nil, "", false, db.ErrForbidden
}
if !hasStoredCookieCredential(detail) {
return false, nil, "", false, errors.New("账号 Cookie 为空")
}
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, detail)
ok, ret, updatedCookies, callErr := s.MTop.ConsignContext(mtopCtx, detail.Value, orderID)
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, detail, cookieSession)
if persistErr != nil {
persistErr = fmt.Errorf("保存发货响应 Cookie Jar: %w", persistErr)
if callErr != nil {
return ok, ret, "", false, errors.Join(callErr, persistErr)
}
return ok, ret, "", false, persistErr
}
if handled {
runtimeCookie := ""
if valueChanged {
runtimeCookie = value
}
return ok, ret, runtimeCookie, valueChanged, callErr
}
if callErr != nil {
return false, ret, "", false, callErr
}
if updatedCookies == "" || updatedCookies == detail.Value {
return ok, ret, "", false, nil
}
if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return ok, ret, "", false, fmt.Errorf("保存发货响应 Cookie: %w", err)
}
return ok, ret, updatedCookies, true, nil
}
func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
orders, err := parseImportedOrders(w, r)
if err != nil {
+57 -30
View File
@@ -47,6 +47,7 @@ type passwordLoginSession struct {
QRCodeURL string
CooldownHours int
IsNewAccount bool
AccountExisted bool
CookieCount int
ShowBrowser bool
CreatedAt time.Time
@@ -89,7 +90,8 @@ func (s *Server) startPasswordLogin(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return
}
if ok, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID); !ok {
allowed, accountExisted, message := s.canStartPasswordLogin(r.Context(), sess.UserID, accountID)
if !allowed {
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": message})
return
}
@@ -111,15 +113,16 @@ func (s *Server) startPasswordLogin(w http.ResponseWriter, r *http.Request) {
}
ctx, cancel := context.WithTimeout(s.lifecycleContext(), passwordLoginProcessingTimeout)
loginSession := &passwordLoginSession{
ID: sessionID,
AccountID: accountID,
Account: account,
UserID: sess.UserID,
Status: "processing",
Message: "登录处理中,请稍候...",
ShowBrowser: req.ShowBrowser,
CreatedAt: time.Now(),
cancel: cancel,
ID: sessionID,
AccountID: accountID,
Account: account,
UserID: sess.UserID,
Status: "processing",
Message: "登录处理中,请稍候...",
ShowBrowser: req.ShowBrowser,
AccountExisted: accountExisted,
CreatedAt: time.Now(),
cancel: cancel,
}
s.passwordMu.Lock()
s.passwordSessions[sessionID] = loginSession
@@ -234,20 +237,44 @@ func (s *Server) savePasswordLoginCookies(ctx context.Context, session *password
return "", false, fmt.Errorf("登录结果账号 %s 与正在编辑的账号 %s 不一致,已拒绝覆盖", accountID, session.AccountID)
}
cookieValue := browser.MarshalCookies(cookies)
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return "", false, err
}
if err := s.Store.Cookies.UpdateValueOwned(ctx, accountID, cookieValue, session.UserID); err != nil {
return "", false, err
}
if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
return "", false, err
}
s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
isNew := false
credentialUnlock := s.Store.LockAccountCredentials(accountID)
saveErr := func() error {
defer credentialUnlock()
detail, err := s.Store.Cookies.GetDetails(ctx, accountID)
switch {
case errors.Is(err, db.ErrNotFound):
if session.AccountExisted {
return errors.New("账号已在登录期间删除,拒绝重新创建")
}
isNew = true
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookieValue, session.UserID); err != nil {
return err
}
case err != nil:
return err
case detail == nil:
return db.ErrNotFound
case detail.UserID != session.UserID:
return db.ErrForbidden
default:
if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookieValue); err != nil {
return err
}
}
if err := s.Store.Cookies.UpdateLoginInfo(ctx, accountID, session.Account, password, session.ShowBrowser); err != nil {
return err
}
s.markSuccessfulLogin(ctx, accountID, session.UserID, loginMethodPassword, "账号密码登录成功")
if s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(ctx, accountID); err != nil {
s.Logger.Warn("密码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
}
}
return nil
}()
if saveErr != nil {
return "", false, saveErr
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
@@ -260,21 +287,21 @@ func (s *Server) savePasswordLoginCookies(ctx context.Context, session *password
return accountID, isNew, nil
}
func (s *Server) canStartPasswordLogin(ctx context.Context, userID int64, accountID string) (bool, string) {
func (s *Server) canStartPasswordLogin(ctx context.Context, userID int64, accountID string) (bool, bool, string) {
d, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err == nil {
if d.UserID != userID {
return false, "无权限操作该账号"
return false, true, "无权限操作该账号"
}
if !s.Store.Cookies.GetStatus(ctx, accountID) {
return false, "账号已禁用,请先在账号管理中启用"
return false, true, "账号已禁用,请先在账号管理中启用"
}
return true, ""
return true, true, ""
}
if errors.Is(err, db.ErrNotFound) {
return true, ""
return true, false, ""
}
return false, "查询账号失败"
return false, false, "查询账号失败"
}
func passwordProcessingKey(userID int64, accountID string) string {
@@ -149,6 +149,7 @@ func TestPasswordLoginSessionSuccessSavesCookiesAndAudit(t *testing.T) {
if err := store.Tokens.Save(context.Background(), "acc1", "did", "token", time.Now().Add(time.Hour).Unix()); err != nil {
t.Fatalf("save token: %v", err)
}
seedStaleCookieSnapshot(t, store, "acc1")
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret","show_browser":false}`)
if start["success"] != true || start["status"] != "processing" {
@@ -180,12 +181,53 @@ func TestPasswordLoginSessionSuccessSavesCookiesAndAudit(t *testing.T) {
if tk, err := store.Tokens.Get(context.Background(), "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("密码登录成功应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
requireCookieSnapshotCleared(t, store, "acc1")
logs, err := store.LoginLogs.ListByCookie(context.Background(), "acc1", 10)
if err != nil || len(logs) != 1 || logs[0].Status != "success" {
t.Fatalf("登录日志异常: logs=%#v err=%v", logs, err)
}
}
func TestPasswordLoginDoesNotRecreateAccountDeletedWhileBrowserRuns(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
fake := &fakePasswordLoginRunner{
block: make(chan struct{}),
cookies: map[string]string{"unb": "acc1", "_m_h5_tk": "fresh"},
}
srv.PasswordLogin = fake
h := srv.Router()
cookie := loginForPasswordTest(t, h)
start := startPasswordLoginForTest(t, h, cookie, `{"account_id":"acc1","account":"login-user","password":"secret"}`)
sessionID := start["session_id"].(string)
for i := 0; i < 100; i++ {
if calls, _, _ := fake.snapshot(); calls == 1 {
break
}
if i == 99 {
t.Fatal("浏览器登录任务未启动")
}
time.Sleep(5 * time.Millisecond)
}
deleteReq := httptest.NewRequest(http.MethodDelete, "/cookies/acc1", nil)
deleteReq.AddCookie(cookie)
deleteRec := httptest.NewRecorder()
h.ServeHTTP(deleteRec, deleteReq)
if deleteRec.Code != http.StatusOK {
t.Fatalf("delete status=%d body=%s", deleteRec.Code, deleteRec.Body.String())
}
close(fake.block)
done := waitPasswordLoginStatus(t, h, cookie, sessionID, "failed")
if !strings.Contains(done["error"].(string), "登录期间删除") {
t.Fatalf("删除中的账号应明确拒绝复活: %+v", done)
}
if _, err := store.Cookies.GetDetails(context.Background(), "acc1"); !errors.Is(err, db.ErrNotFound) {
t.Fatalf("异步登录不得重建已删除账号: %v", err)
}
}
func TestPasswordLoginRejectsMismatchedReturnedAccount(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
+38 -26
View File
@@ -194,30 +194,46 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
accountID := strings.TrimSpace(targetAccountID)
if accountID == "" {
accountID = scannedAccountID
} else {
if accountID != scannedAccountID {
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
}
target, err := s.Store.Cookies.GetDetails(ctx, accountID)
if err != nil {
return qrLoginPersistence{}, errors.New("待重新授权账号不存在")
}
if target.UserID != userID {
return qrLoginPersistence{}, errors.New("待重新授权账号不属于当前用户")
}
} else if accountID != scannedAccountID {
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
}
_, err := s.Store.Cookies.GetDetails(ctx, accountID)
isNew := errors.Is(err, db.ErrNotFound)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return qrLoginPersistence{}, err
}
var saveErr error
if isNew {
saveErr = s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID)
} else {
saveErr = s.Store.Cookies.UpdateValueOwned(ctx, accountID, cookies, userID)
}
isNew := false
credentialUnlock := s.Store.LockAccountCredentials(accountID)
saveErr := func() error {
defer credentialUnlock()
detail, err := s.Store.Cookies.GetDetails(ctx, accountID)
switch {
case errors.Is(err, db.ErrNotFound):
if targetAccountID != "" {
return errors.New("待重新授权账号不存在")
}
isNew = true
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID); err != nil {
return err
}
case err != nil:
return err
case detail == nil:
return db.ErrNotFound
case detail.UserID != userID:
if targetAccountID != "" {
return errors.New("待重新授权账号不属于当前用户")
}
return db.ErrForbidden
default:
if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
return err
}
}
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
if s.Store.Tokens != nil {
if err := s.Store.Tokens.Clear(ctx, accountID); err != nil {
s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
}
}
return nil
}()
if saveErr != nil {
if errors.Is(saveErr, db.ErrForbidden) {
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
@@ -227,10 +243,6 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses
}
return qrLoginPersistence{}, saveErr
}
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
if s.Store.Tokens != nil {
_ = s.Store.Tokens.Clear(ctx, accountID)
}
if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil {
s.refreshAccountProfile(ctx, d)
}
+2
View File
@@ -259,6 +259,7 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
if err := store.Tokens.Save(ctx, "acc1", "did", "token", 9999999999); err != nil {
t.Fatalf("Save token: %v", err)
}
seedStaleCookieSnapshot(t, store, "acc1")
h := srv.Router()
cookie := loginHelper(t, h)
@@ -282,6 +283,7 @@ func TestCompleteQRVerificationPersistsAndReenablesAccount(t *testing.T) {
if !store.Cookies.GetStatus(ctx, "acc1") {
t.Fatal("扫码验证成功后应重新启用账号")
}
requireCookieSnapshotCleared(t, store, "acc1")
if tk, err := store.Tokens.Get(ctx, "acc1"); err != nil || tk.AccessToken != "" || tk.DeviceID != "did" {
t.Fatalf("扫码验证成功后应清 token 并保留 device ID: tk=%+v err=%v", tk, err)
}
+162 -51
View File
@@ -17,14 +17,15 @@ const (
// BrowserCookie 保存浏览器返回的完整 Cookie 属性。
type BrowserCookie struct {
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Expires float64 `json:"expires,omitempty"`
HTTPOnly bool `json:"httpOnly,omitempty"`
Secure bool `json:"secure,omitempty"`
SameSite string `json:"sameSite,omitempty"`
Name string `json:"name"`
Value string `json:"value"`
Domain string `json:"domain,omitempty"`
Path string `json:"path,omitempty"`
Expires float64 `json:"expires,omitempty"`
HTTPOnly bool `json:"httpOnly,omitempty"`
Secure bool `json:"secure,omitempty"`
SameSite string `json:"sameSite,omitempty"`
PartitionKey string `json:"partitionKey,omitempty"`
}
// ParseCookieString 把 Cookie 头解析为 name -> value。
@@ -88,8 +89,15 @@ func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
if domain == "" {
domain = ".goofish.com"
}
out := make([]BrowserCookie, 0)
for name, value := range ParseCookieString(cookieString) {
values := ParseCookieString(cookieString)
names := make([]string, 0, len(values))
for name := range values {
names = append(names, name)
}
sort.Strings(names)
out := make([]BrowserCookie, 0, len(names))
for _, name := range names {
value := values[name]
out = append(out, BrowserCookie{Name: name, Value: value, Domain: domain, Path: "/", Secure: true})
}
return NormalizeSnapshot(out)
@@ -99,6 +107,10 @@ func SnapshotFromCookieString(cookieString, domain string) []BrowserCookie {
// 已知属性,并同步值与删除项。新增字段使用 .goofish.com 根路径作为兼容作用域。
func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString string) []BrowserCookie {
values := ParseCookieString(cookieString)
counts := make(map[string]int, len(snapshot))
for _, cookie := range NormalizeSnapshot(snapshot) {
counts[cookie.Name]++
}
seen := make(map[string]struct{})
out := make([]BrowserCookie, 0, len(snapshot)+len(values))
for _, cookie := range NormalizeSnapshot(snapshot) {
@@ -106,14 +118,25 @@ func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString st
if !exists {
continue
}
cookie.Value = value
// 扁平 Cookie 字符串无法表达同名 Cookie 的 Domain/Path/PartitionKey。
// 只有名称唯一时才可确定其新值;否则保留各作用域原值,避免把一个值
// 错误覆盖到完整 Jar 的所有同名项。
if counts[cookie.Name] == 1 {
cookie.Value = value
}
out = append(out, cookie)
seen[cookie.Name] = struct{}{}
}
for name, value := range values {
names := make([]string, 0, len(values))
for name := range values {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
if _, exists := seen[name]; exists {
continue
}
value := values[name]
out = append(out, BrowserCookie{Name: name, Value: value, Domain: ".goofish.com", Path: "/", Secure: true})
}
return NormalizeSnapshot(out)
@@ -122,9 +145,28 @@ func ReconcileSnapshotWithCookieString(snapshot []BrowserCookie, cookieString st
// CookieHeaderForURL 按浏览器 Domain/Path/Secure/Expires 规则生成指定 URL 的
// Cookie header,并保留不同路径下的同名 Cookie。
func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) string {
header, _ := ScopedCookieHeaderForURL(snapshot, rawURL, now)
return header
}
// ScopedCookieHeaderForURL 按浏览器匹配规则生成 Cookie header。第二个返回值
// 表示调用方提供了权威快照且 URL 有效;即使没有任何 Cookie 匹配,也会返回
// ("", true),让调用方能区分“明确为空”和“没有快照,需要兼容回退”。
//
// 此简化入口不具备顶级站点上下文,因此不会发送分区 Cookie。需要处理 CHIPS
// 时应使用 ScopedCookieHeaderForRequest 并传入浏览器提供的 PartitionKey。
func ScopedCookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time) (string, bool) {
return ScopedCookieHeaderForRequest(snapshot, rawURL, "", now)
}
// ScopedCookieHeaderForRequest 为带顶级站点 PartitionKey 的请求生成 Cookie header。
func ScopedCookieHeaderForRequest(snapshot []BrowserCookie, rawURL, partitionKey string, now time.Time) (string, bool) {
if snapshot == nil {
return "", false
}
target, err := url.Parse(rawURL)
if err != nil || target.Hostname() == "" {
return ""
return "", false
}
type matchedCookie struct {
cookie BrowserCookie
@@ -132,6 +174,11 @@ func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time)
}
matched := make([]matchedCookie, 0, len(snapshot))
for index, cookie := range NormalizeSnapshot(snapshot) {
// Unpartitioned cookies are always eligible. Partitioned cookies are
// additionally sent when their key matches the current top-level site.
if cookie.PartitionKey != "" && cookie.PartitionKey != partitionKey {
continue
}
if cookie.Expires > 0 && cookie.Expires <= float64(now.Unix()) {
continue
}
@@ -153,58 +200,106 @@ func CookieHeaderForURL(snapshot []BrowserCookie, rawURL string, now time.Time)
for _, item := range matched {
parts = append(parts, item.cookie.Name+"="+item.cookie.Value)
}
return strings.Join(parts, "; ")
return strings.Join(parts, "; "), true
}
// ApplySetCookies 把某次请求响应的 Set-Cookie 应用到完整快照。删除操作只删除
// 相同 name/domain/path 的 Cookie,不会误删其他作用域下的同名项。
func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time) []BrowserCookie {
func ApplySetCookies(snapshot []BrowserCookie, requestURL string, setCookies []string, now time.Time, partitionKeys ...string) []BrowserCookie {
target, err := url.Parse(requestURL)
if err != nil || target.Hostname() == "" {
return NormalizeSnapshot(snapshot)
}
state := make(map[string]BrowserCookie)
// Cookie identity is name/domain/path/partition key, while header ordering for
// equal paths follows creation time. Keep the input position when replacing an
// existing cookie; if it is deleted and later recreated, append it as a new
// creation, just like Chromium's cookie store.
state := make([]BrowserCookie, 0, len(snapshot)+len(setCookies))
positions := make(map[string]int, len(snapshot)+len(setCookies))
for _, cookie := range NormalizeSnapshot(snapshot) {
state[snapshotKey(cookie)] = cookie
key := snapshotKey(cookie)
if index, exists := positions[key]; exists {
state[index] = cookie
continue
}
positions[key] = len(state)
state = append(state, cookie)
}
for _, raw := range setCookies {
parsed, err := http.ParseSetCookie(raw)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
domain := strings.ToLower(strings.TrimSpace(parsed.Domain))
rawDomain := strings.TrimSpace(parsed.Domain)
domain := strings.ToLower(rawDomain)
if domain == "" {
domain = strings.ToLower(target.Hostname())
} else if !strings.HasPrefix(domain, ".") {
domain = "." + domain
} else {
if !cookieDomainMatches(strings.ToLower(target.Hostname()), domain) {
// Chromium rejects a Domain attribute unrelated to the response host.
continue
}
if !strings.HasPrefix(domain, ".") {
domain = "." + domain
}
}
cookiePath := parsed.Path
if cookiePath == "" {
cookiePath = defaultCookiePath(target.Path)
}
if parsed.SameSite == http.SameSiteNoneMode && !parsed.Secure {
// Chromium rejects SameSite=None cookies unless they are also Secure.
continue
}
if strings.HasPrefix(parsed.Name, "__Secure-") && !parsed.Secure {
continue
}
if strings.HasPrefix(parsed.Name, "__Host-") && (!parsed.Secure || rawDomain != "" || parsed.Path != "/") {
// __Host- requires Secure, an explicit Path=/, and no Domain attribute.
continue
}
partitionKey := ""
if parsed.Partitioned {
if !parsed.Secure || len(partitionKeys) == 0 || strings.TrimSpace(partitionKeys[0]) == "" {
// Without the top-level site key this cookie cannot be represented
// faithfully; never turn it into an unpartitioned cookie.
continue
}
partitionKey = strings.TrimSpace(partitionKeys[0])
}
cookie := BrowserCookie{
Name: parsed.Name, Value: parsed.Value, Domain: domain, Path: cookiePath,
HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite),
HTTPOnly: parsed.HttpOnly, Secure: parsed.Secure, SameSite: sameSiteLabel(parsed.SameSite), PartitionKey: partitionKey,
}
if !parsed.Expires.IsZero() {
if parsed.MaxAge > 0 {
// RFC 6265: Max-Age 优先于 Expires,并从收到响应的时刻计算。
cookie.Expires = float64(now.Add(time.Duration(parsed.MaxAge) * time.Second).Unix())
} else if !parsed.Expires.IsZero() {
cookie.Expires = float64(parsed.Expires.Unix())
}
key := snapshotKey(cookie)
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
delete(state, key)
if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
if index, exists := positions[key]; exists {
state = append(state[:index], state[index+1:]...)
delete(positions, key)
for i := index; i < len(state); i++ {
positions[snapshotKey(state[i])] = i
}
}
continue
}
state[key] = cookie
if index, exists := positions[key]; exists {
state[index] = cookie
continue
}
positions[key] = len(state)
state = append(state, cookie)
}
out := make([]BrowserCookie, 0, len(state))
for _, cookie := range state {
out = append(out, cookie)
}
return NormalizeSnapshot(out)
return NormalizeSnapshot(state)
}
func snapshotKey(cookie BrowserCookie) string {
return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path
return cookie.Name + "\x00" + strings.ToLower(cookie.Domain) + "\x00" + cookie.Path + "\x00" + cookie.PartitionKey
}
func cookieDomainMatches(host, domain string) bool {
@@ -288,7 +383,7 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
if path == "" {
path = "/"
}
return c.Name + "|" + c.Domain + "|" + path
return c.Name + "|" + c.Domain + "|" + path + "|" + c.PartitionKey
}
label := func(c BrowserCookie) string {
path := c.Path
@@ -296,7 +391,11 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
path = "/"
}
if c.Domain != "" {
return c.Name + "@" + c.Domain + path
out := c.Name + "@" + c.Domain + path
if c.PartitionKey != "" {
out += "#" + c.PartitionKey
}
return out
}
return c.Name
}
@@ -334,14 +433,14 @@ func ChangedSnapshotLabels(before, after []BrowserCookie) []string {
// CookieStringFromSnapshot 将浏览器 Cookie 快照压成请求 Cookie 字符串。
func CookieStringFromSnapshot(cookies []BrowserCookie) string {
m := make(map[string]string, len(cookies))
for _, c := range cookies {
parts := make([]string, 0, len(cookies))
for _, c := range NormalizeSnapshot(cookies) {
if c.Name == "" {
continue
}
m[c.Name] = c.Value
parts = append(parts, c.Name+"="+c.Value)
}
return MarshalCookieString(m)
return strings.Join(parts, "; ")
}
// MergeOriginalFields 补回浏览器未返回但原 Cookie 中存在的字段。
@@ -353,8 +452,12 @@ func MergeOriginalFields(original, browserCookieString string) string {
return MarshalCookieString(m)
}
// NormalizeSnapshot 排序并补齐默认 path,保证 metadata 稳定。
// NormalizeSnapshot 补齐默认 path 并保留浏览器返回的创建顺序。Cookie
// header 在 Path 长度相同时必须沿用该顺序,因此不能在这里按名称重排。
func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
if cookies == nil {
return nil
}
out := make([]BrowserCookie, 0, len(cookies))
for _, c := range cookies {
if c.Name == "" {
@@ -365,31 +468,39 @@ func NormalizeSnapshot(cookies []BrowserCookie) []BrowserCookie {
}
out = append(out, c)
}
sort.Slice(out, func(i, j int) bool {
if out[i].Domain != out[j].Domain {
return out[i].Domain < out[j].Domain
}
if out[i].Path != out[j].Path {
return out[i].Path < out[j].Path
}
return out[i].Name < out[j].Name
})
return out
}
// SnapshotFromMetadata 从 cookies.metadata_json 中读取浏览器 Cookie 快照。
func SnapshotFromMetadata(metadata string) []BrowserCookie {
out, _ := SnapshotFromMetadataOK(metadata)
return out
}
// SnapshotFromMetadataOK 读取完整 Cookie 快照,并报告 metadata 中是否真的
// 存在快照键。存在空数组时返回非 nil 空切片和 true,避免被误当成历史账号
// 而回退到扁平 Cookie。
func SnapshotFromMetadataOK(metadata string) ([]BrowserCookie, bool) {
var m map[string]json.RawMessage
if err := json.Unmarshal([]byte(strings.TrimSpace(metadata)), &m); err != nil {
return nil
return nil, false
}
var out []BrowserCookie
if raw := m[metadataSnapshotKey]; len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
if err := json.Unmarshal(raw, &out); err != nil {
return nil, false
}
} else if raw := m[legacyMetadataSnapshot]; len(raw) > 0 {
_ = json.Unmarshal(raw, &out)
if err := json.Unmarshal(raw, &out); err != nil {
return nil, false
}
} else {
return nil, false
}
return NormalizeSnapshot(out)
if out == nil {
out = []BrowserCookie{}
}
return NormalizeSnapshot(out), true
}
// MetadataWithSnapshot 写入浏览器 Cookie 快照,保留 metadata 中的其他键。
@@ -35,6 +35,50 @@ func TestCookieHeaderForURLScopesDomainPathAndSecure(t *testing.T) {
}
}
func TestCookieHeaderForURLOrdersLongerPathFirst(t *testing.T) {
now := time.Now()
snapshot := []BrowserCookie{
{Name: "_m_h5_tk", Value: "root_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "im_2", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now)
if !strings.HasPrefix(got, "_m_h5_tk=im_2; _m_h5_tk=root_1") {
t.Fatalf("longer-path cookie must be first, got %q", got)
}
}
func TestCookieHeaderForURLKeepsCreationOrderForEqualPaths(t *testing.T) {
now := time.Now()
snapshot := []BrowserCookie{
{Name: "third", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "first", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "second", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true},
}
if got := CookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); got != "third=3; first=1; second=2" {
t.Fatalf("equal-path creation order lost: %q", got)
}
}
func TestScopedCookieHeaderDistinguishesEmptySnapshotFromUnavailable(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
if got, ok := ScopedCookieHeaderForURL(nil, "https://www.goofish.com/im", now); ok || got != "" {
t.Fatalf("nil snapshot=(%q,%v), want unavailable", got, ok)
}
if got, ok := ScopedCookieHeaderForURL([]BrowserCookie{}, "https://www.goofish.com/im", now); !ok || got != "" {
t.Fatalf("empty snapshot=(%q,%v), want authoritative empty", got, ok)
}
snapshot := []BrowserCookie{{
Name: "partitioned", Value: "1", Domain: ".goofish.com", Path: "/",
Secure: true, PartitionKey: "https://example.com",
}}
if got, ok := ScopedCookieHeaderForURL(snapshot, "https://www.goofish.com/im", now); !ok || got != "" {
t.Fatalf("partitionless request=(%q,%v)", got, ok)
}
if got, ok := ScopedCookieHeaderForRequest(snapshot, "https://www.goofish.com/im", "https://example.com", now); !ok || got != "partitioned=1" {
t.Fatalf("partitioned request=(%q,%v)", got, ok)
}
}
func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
snapshot := []BrowserCookie{
@@ -58,6 +102,149 @@ func TestApplySetCookiesPreservesAttributesAndDeletesExactScope(t *testing.T) {
}
}
func TestApplySetCookiesMaxAgeOverridesExpires(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
"sid=fresh; Domain=.goofish.com; Path=/; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT",
}, now)
if len(updated) != 1 {
t.Fatalf("snapshot=%+v", updated)
}
if got, want := int64(updated[0].Expires), now.Add(time.Hour).Unix(); got != want {
t.Fatalf("expires=%d want %d", got, want)
}
deleted := ApplySetCookies(updated, "https://www.goofish.com/im", []string{
"sid=stale; Domain=.goofish.com; Path=/; Max-Age=0; Expires=Thu, 01 Jan 2099 00:00:00 GMT",
}, now)
if len(deleted) != 0 {
t.Fatalf("Max-Age=0 must delete cookie: %+v", deleted)
}
}
func TestApplySetCookiesReplacementAndRecreationOrder(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
initial := []BrowserCookie{
{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"},
{Name: "b", Value: "2", Domain: ".goofish.com", Path: "/"},
{Name: "c", Value: "3", Domain: ".goofish.com", Path: "/"},
}
replaced := ApplySetCookies(initial, "https://www.goofish.com/im", []string{
"b=fresh; Domain=.goofish.com; Path=/",
}, now)
if got := CookieHeaderForURL(replaced, "https://www.goofish.com/im", now); got != "a=1; b=fresh; c=3" {
t.Fatalf("replacement moved cookie: %q", got)
}
recreated := ApplySetCookies(replaced, "https://www.goofish.com/im", []string{
"b=; Domain=.goofish.com; Path=/; Max-Age=0",
"b=recreated; Domain=.goofish.com; Path=/",
}, now)
if got := CookieHeaderForURL(recreated, "https://www.goofish.com/im", now); got != "a=1; c=3; b=recreated" {
t.Fatalf("recreated cookie was not appended: %q", got)
}
}
func TestApplySetCookiesRejectsUnrepresentablePartitionedCookie(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
raw := []string{"chip=value; Domain=.goofish.com; Path=/; Secure; SameSite=None; Partitioned"}
if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now); len(got) != 0 {
t.Fatalf("partitioned cookie without key must be rejected: %+v", got)
}
if got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, " "); len(got) != 0 {
t.Fatalf("partitioned cookie with empty key must be rejected: %+v", got)
}
got := ApplySetCookies(nil, "https://www.goofish.com/im", raw, now, "https://goofish.com")
if len(got) != 1 || got[0].PartitionKey != "https://goofish.com" {
t.Fatalf("valid partitioned cookie missing: %+v", got)
}
}
func TestApplySetCookiesEnforcesSameSiteAndCookiePrefixes(t *testing.T) {
now := time.Unix(1_800_000_000, 0)
updated := ApplySetCookies(nil, "https://www.goofish.com/im", []string{
"none_insecure=1; Domain=.goofish.com; Path=/; SameSite=None",
"none_secure=1; Domain=.goofish.com; Path=/; SameSite=None; Secure",
"__Secure-bad=1; Domain=.goofish.com; Path=/",
"__Secure-good=1; Domain=.goofish.com; Path=/; Secure",
"__Host-domain=1; Domain=www.goofish.com; Path=/; Secure",
"__Host-default-path=1; Secure",
"__Host-good=1; Path=/; Secure",
}, now)
values := make(map[string]BrowserCookie, len(updated))
for _, cookie := range updated {
values[cookie.Name] = cookie
}
for _, rejected := range []string{"none_insecure", "__Secure-bad", "__Host-domain", "__Host-default-path"} {
if _, exists := values[rejected]; exists {
t.Fatalf("invalid cookie %s was accepted: %+v", rejected, updated)
}
}
for _, accepted := range []string{"none_secure", "__Secure-good", "__Host-good"} {
if _, exists := values[accepted]; !exists {
t.Fatalf("valid cookie %s was rejected: %+v", accepted, updated)
}
}
}
func TestSameNameCookiesKeepScopeAndPartitionIdentity(t *testing.T) {
snapshot := []BrowserCookie{
{Name: "sid", Value: "root", Domain: ".goofish.com", Path: "/"},
{Name: "sid", Value: "im", Domain: ".goofish.com", Path: "/im"},
{Name: "sid", Value: "partitioned", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com"},
}
if got := CookieStringFromSnapshot(snapshot); got != "sid=root; sid=im; sid=partitioned" {
t.Fatalf("flat snapshot lost scoped duplicate: %q", got)
}
reconciled := ReconcileSnapshotWithCookieString(snapshot, "sid=new-flat")
if len(reconciled) != 3 {
t.Fatalf("reconciled=%+v", reconciled)
}
for _, cookie := range reconciled {
if cookie.Value == "new-flat" {
t.Fatalf("ambiguous flat value overwrote scoped cookie: %+v", reconciled)
}
}
updated := ApplySetCookies(snapshot, "https://www.goofish.com/", []string{
"sid=new-root; Domain=.goofish.com; Path=/",
}, time.Unix(1_800_000_000, 0))
if len(updated) != 3 {
t.Fatalf("partition identity collapsed: %+v", updated)
}
}
func TestSynthesizedSnapshotsRemainDeterministic(t *testing.T) {
fromFlat := SnapshotFromCookieString("z=3; a=1; m=2", ".goofish.com")
if got := CookieStringFromSnapshot(fromFlat); got != "a=1; m=2; z=3" {
t.Fatalf("flat snapshot order=%q", got)
}
reconciled := ReconcileSnapshotWithCookieString(
[]BrowserCookie{{Name: "keep", Value: "old", Domain: ".goofish.com", Path: "/"}},
"z=3; keep=new; a=1",
)
if got := CookieStringFromSnapshot(reconciled); got != "keep=new; a=1; z=3" {
t.Fatalf("reconciled snapshot order=%q", got)
}
}
func TestSnapshotMetadataReportsAuthoritativeEmptyAndPreservesPartitionKey(t *testing.T) {
if got, ok := SnapshotFromMetadataOK(`{"other":true}`); ok || got != nil {
t.Fatalf("missing snapshot=(%+v,%v)", got, ok)
}
metadata := MetadataWithSnapshot(`{"other":true}`, []BrowserCookie{})
if got, ok := SnapshotFromMetadataOK(metadata); !ok || got == nil || len(got) != 0 {
t.Fatalf("empty snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
}
metadata = MetadataWithSnapshot("", []BrowserCookie{{
Name: "chip", Value: "secret", Domain: ".goofish.com", Path: "/", PartitionKey: "https://example.com",
}})
got, ok := SnapshotFromMetadataOK(metadata)
if !ok || len(got) != 1 || got[0].PartitionKey != "https://example.com" {
t.Fatalf("partition snapshot=(%+v,%v) metadata=%s", got, ok, metadata)
}
}
func TestChangedSnapshotLabels(t *testing.T) {
before := []BrowserCookie{{Name: "a", Value: "1", Domain: ".goofish.com", Path: "/"}}
after := []BrowserCookie{{Name: "a", Value: "2", Domain: ".goofish.com", Path: "/"}}
+18 -10
View File
@@ -15,6 +15,7 @@ import (
"time"
"xianyu-go/internal/xianyu"
"xianyu-go/internal/xianyu/cookierefresh"
)
// RegAppKey 是 WS 注册用的 appKey(与签名用的 protocol.SignAppKey 不同)。
@@ -72,15 +73,19 @@ type ClientImpl struct {
}
type TokenBrowserRequest struct {
URL string
Body string
Cookies string
URL string
Body string
Cookies string
CookieSnapshot []cookierefresh.BrowserCookie
}
type TokenBrowserResponse struct {
Status int
Body []byte
UpdatedCookies string
Status int
Body []byte
UpdatedCookies string
CookieSnapshot []cookierefresh.BrowserCookie
CookieSnapshotComplete bool // true 表示 CookieSnapshot 是响应后的权威完整 Jar,空切片也代表全部删除
CookieStateChanged bool // true 表示响应明确把不完整扁平 Cookie 更新或删除到了空值
}
type TokenRequestExecutor interface {
@@ -111,9 +116,12 @@ var _ Client = (*ClientImpl)(nil)
// RefreshResult 是刷新 token 的结果。
type RefreshResult struct {
AccessToken string // 用于 WS /reg 注册
AccessTokenExpireAt int64 // 服务端 accessTokenExpiredTime 归一化后的 Unix 秒
UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
AccessToken string // 用于 WS /reg 注册
AccessTokenExpireAt int64 // 服务端 accessTokenExpiredTime 归一化后的 Unix 秒
UpdatedCookies string // 合并 Set-Cookie 后的新 cookie 字符串(无变化则与入参相同)
CookieSnapshot []cookierefresh.BrowserCookie // 浏览器执行 token 请求后得到的完整 Cookie Jar
CookieSnapshotComplete bool // true 表示快照权威完整;空切片代表 Cookie Jar 已被清空
CookieStateChanged bool // true 表示本次响应明确更新或删除了 Cookie(包括更新后为空)
}
// FreshCaptchaResult 是重取 token 风控验证链接的结果。
@@ -314,7 +322,7 @@ func mergeSetCookie(orig string, current map[string]string, resp *http.Response)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
delete(current, parsed.Name)
} else {
current[parsed.Name] = parsed.Value
+14 -3
View File
@@ -52,7 +52,7 @@ func TestReadMTopBodyRejectsOversizedResponse(t *testing.T) {
}
}
func TestRefreshTokenRetriesOnceWithoutUpdatedCookie(t *testing.T) {
func TestRefreshTokenUsesOfficialAttemptLimitWithoutUpdatedCookie(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
@@ -65,8 +65,8 @@ func TestRefreshTokenRetriesOnceWithoutUpdatedCookie(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
}
if requests.Load() != 2 {
t.Fatalf("请求次数=%d want 2", requests.Load())
if requests.Load() != officialMTopMaxAttempts {
t.Fatalf("请求次数=%d want %d", requests.Load(), officialMTopMaxAttempts)
}
}
@@ -310,6 +310,17 @@ func TestMergeSetCookieMalformedIgnored(t *testing.T) {
}
}
func TestMergeSetCookieMaxAgeOverridesPastExpires(t *testing.T) {
orig := "session=old"
current := map[string]string{"session": "old"}
resp := &http.Response{Header: http.Header{
"Set-Cookie": {"session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/"},
}}
if got := mergeSetCookie(orig, current, resp); !strings.Contains(got, "session=fresh") {
t.Fatalf("positive Max-Age must override past Expires: %q", got)
}
}
func TestSleepCtx(t *testing.T) {
// d <= 0 直接返回
if err := sleepCtx(context.Background(), 0); err != nil {
+12 -9
View File
@@ -25,6 +25,9 @@ func (c *ClientImpl) Consign(cookiesStr, orderID string) (ok bool, ret []string,
// ConsignContext 确认发货;签名 token 过期时使用响应下发的新 Cookie 重签并重试。
func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
previousCookies := currentCookies
@@ -69,35 +72,35 @@ func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
token := protocol.SignToken(cookiesStr)
consignURL := c.ConsignURL
if consignURL == "" {
consignURL = ConsignAPI
}
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", consignURL)
token := protocol.SignToken(signingCookies)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"orderId":"` + orderID + `", "tradeText":"","picList":[],"newUnconsign":true}`
sign := protocol.GenerateSign(t, token, dataVal)
query := buildConsignQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
consignURL := c.ConsignURL
if consignURL == "" {
consignURL = ConsignAPI
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
consignURL+"?"+query,
strings.NewReader(body))
if err != nil {
return false, nil, cookiesStr, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return false, nil, cookiesStr, fmt.Errorf("consign 请求失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return false, nil, cookiesStr, err
return false, nil, updated, err
}
updated := mergeSetCookie(cookiesStr, cookies, resp)
var res struct {
Ret []string `json:"ret"`
}
+241
View File
@@ -0,0 +1,241 @@
package mtop
import (
"context"
"net/http"
"slices"
"strings"
"sync"
"time"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
const (
mtopDocumentURL = "https://www.goofish.com/im"
goofishTopSite = "https://goofish.com"
)
type cookieSessionContextKey struct{}
// CookieSession carries an authoritative browser Cookie Jar through one MTOP
// workflow. It lets direct Go HTTP calls reproduce the browser split between
// document cookies used for signing and cookies scoped to the request URL.
// The same session absorbs every Set-Cookie before response-body processing,
// so callers can persist rotations and deletions even when parsing later fails.
type CookieSession struct {
mu sync.Mutex
snapshot []cookierefresh.BrowserCookie
flat string
authoritative bool
changed bool
}
// WithCookieSnapshot installs an authoritative Cookie Jar on ctx. A nil input
// is normalized to an explicitly empty Jar; callers should invoke this only
// when metadata confirms that a complete snapshot exists.
func WithCookieSnapshot(ctx context.Context, snapshot []cookierefresh.BrowserCookie) (context.Context, *CookieSession) {
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
session := &CookieSession{snapshot: normalized, authoritative: true}
return context.WithValue(ctx, cookieSessionContextKey{}, session), session
}
// WithFlatCookieSession carries a legacy flat Cookie header without claiming
// that it is a complete browser Jar. Response Set-Cookie values are still
// observable and persistable, but callers must keep metadata snapshot-free
// until Chromium supplies an authoritative Jar.
func WithFlatCookieSession(ctx context.Context, cookies string) (context.Context, *CookieSession) {
session := &CookieSession{flat: cookies}
return context.WithValue(ctx, cookieSessionContextKey{}, session), session
}
// State returns the /im canonical Cookie header, a copy of the complete Jar,
// and whether the workflow observed an authoritative update.
func (s *CookieSession) State() (string, []cookierefresh.BrowserCookie, bool) {
if s == nil {
return "", nil, false
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.authoritative {
return s.flat, nil, s.changed
}
snapshot := normalizedCompleteSnapshot(s.snapshot)
value, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
return value, snapshot, s.changed
}
func cookieSessionFromContext(ctx context.Context) *CookieSession {
if ctx == nil {
return nil
}
session, _ := ctx.Value(cookieSessionContextKey{}).(*CookieSession)
return session
}
// CookieSessionFromContext exposes the operation-scoped session to browser
// fallbacks that can replace it with Chromium's final authoritative Jar.
func CookieSessionFromContext(ctx context.Context) *CookieSession {
return cookieSessionFromContext(ctx)
}
// Snapshot returns a copy of the current complete Jar.
func (s *CookieSession) Snapshot() []cookierefresh.BrowserCookie {
snapshot, authoritative, _ := s.requestState()
if !authoritative {
return nil
}
return snapshot
}
// ReplaceSnapshot records Chromium's final complete Jar, including an
// explicitly empty one.
func (s *CookieSession) ReplaceSnapshot(snapshot []cookierefresh.BrowserCookie) {
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
s.replace(snapshot)
}
func (s *CookieSession) requestState() ([]cookierefresh.BrowserCookie, bool, string) {
if s == nil {
return nil, false, ""
}
s.mu.Lock()
defer s.mu.Unlock()
if !s.authoritative {
return nil, false, s.flat
}
return normalizedCompleteSnapshot(s.snapshot), true, ""
}
func (s *CookieSession) replace(snapshot []cookierefresh.BrowserCookie) {
if s == nil || snapshot == nil {
return
}
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
normalized = []cookierefresh.BrowserCookie{}
}
s.mu.Lock()
s.snapshot = normalized
s.flat = ""
s.authoritative = true
s.changed = true
s.mu.Unlock()
}
func (s *CookieSession) replaceFlat(flat string) {
if s == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.authoritative {
return
}
if s.flat != flat {
s.flat = flat
s.changed = true
}
}
func (s *CookieSession) absorb(requestURL string, setCookies []string) string {
if s == nil {
return ""
}
s.mu.Lock()
defer s.mu.Unlock()
if len(setCookies) > 0 && s.authoritative {
updated := normalizedCompleteSnapshot(cookierefresh.ApplySetCookies(s.snapshot, requestURL, setCookies, time.Now(), goofishTopSite))
if !slices.Equal(s.snapshot, updated) {
s.snapshot = updated
s.changed = true
}
value, _ := cookierefresh.ScopedCookieHeaderForRequest(s.snapshot, mtopDocumentURL, goofishTopSite, time.Now())
return value
}
if len(setCookies) > 0 {
updated, changed := applyFlatSetCookies(s.flat, setCookies, time.Now())
if changed {
s.flat = updated
s.changed = true
}
}
return s.flat
}
// mtopRequestCookies returns the document-visible cookies used by lib-mtop for
// token/sign generation and the URL-scoped Cookie header sent on the request.
func mtopRequestCookies(ctx context.Context, fallback, documentURL, requestURL string) (string, string) {
session := cookieSessionFromContext(ctx)
if session == nil {
return fallback, fallback
}
snapshot, authoritative, flat := session.requestState()
if !authoritative {
return flat, flat
}
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
for _, cookie := range snapshot {
if !cookie.HTTPOnly {
documentCookies = append(documentCookies, cookie)
}
}
signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, time.Now())
requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
return signing, requestCookies
}
func normalizedCompleteSnapshot(snapshot []cookierefresh.BrowserCookie) []cookierefresh.BrowserCookie {
normalized := cookierefresh.NormalizeSnapshot(snapshot)
if normalized == nil {
return []cookierefresh.BrowserCookie{}
}
return normalized
}
func applyFlatSetCookies(original string, setCookies []string, now time.Time) (string, bool) {
values := protocol.TransCookies(original)
changed := false
for _, raw := range setCookies {
parsed, err := http.ParseSetCookie(raw)
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
changed = true
if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(now)) {
delete(values, parsed.Name)
continue
}
values[parsed.Name] = parsed.Value
}
if !changed {
return original, false
}
return cookierefresh.MarshalCookieString(values), true
}
// absorbMTopResponseCookies applies response cookies before body reads. Without
// an authoritative session it preserves the historical flat-cookie fallback.
func absorbMTopResponseCookies(ctx context.Context, fallback string, resp *http.Response) string {
if resp == nil {
return fallback
}
if session := cookieSessionFromContext(ctx); session != nil {
setCookies := resp.Header.Values("Set-Cookie")
if len(setCookies) == 0 {
return fallback
}
requestURL := ""
if resp.Request != nil && resp.Request.URL != nil {
requestURL = resp.Request.URL.String()
}
return session.absorb(requestURL, setCookies)
}
return mergeSetCookie(fallback, protocol.TransCookies(fallback), resp)
}
+312
View File
@@ -0,0 +1,312 @@
package mtop
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"testing"
"time"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
type cookieSessionRoundTripFunc func(*http.Request) (*http.Response, error)
func (fn cookieSessionRoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return fn(req)
}
func TestMTopRequestCookiesSeparatesDocumentAndRequestScopes(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "token_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "doc_only", Value: "doc", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
{Name: "partitioned", Value: "part", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "foreign_partition", Value: "no", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
signing, request := mtopRequestCookies(ctx, "fallback=1", mtopDocumentURL, TokenAPI)
for _, want := range []string{"_m_h5_tk=token_1", "doc_only=doc", "partitioned=part"} {
if !strings.Contains(signing, want) {
t.Fatalf("document cookies %q missing %q", signing, want)
}
}
for _, unwanted := range []string{"api_only=", "foreign_partition="} {
if strings.Contains(signing, unwanted) {
t.Fatalf("document cookies %q unexpectedly contain %q", signing, unwanted)
}
}
for _, want := range []string{"_m_h5_tk=token_1", "api_only=api", "partitioned=part"} {
if !strings.Contains(request, want) {
t.Fatalf("request cookies %q missing %q", request, want)
}
}
for _, unwanted := range []string{"doc_only=", "foreign_partition="} {
if strings.Contains(request, unwanted) {
t.Fatalf("request cookies %q unexpectedly contain %q", request, unwanted)
}
}
}
func TestCookieSessionAbsorbsScopedSetCookieAndDeletion(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "same", Value: "root", Domain: ".goofish.com", Path: "/"},
{Name: "same", Value: "api-old", Domain: "h5api.m.goofish.com", Path: "/h5"},
}
_, session := WithCookieSnapshot(context.Background(), snapshot)
requestURL, err := url.Parse(TokenAPI)
if err != nil {
t.Fatal(err)
}
resp := &http.Response{
Request: &http.Request{URL: requestURL},
Header: http.Header{"Set-Cookie": {
"same=api-new; Path=/h5; Secure",
"partitioned=value; Path=/; Secure; SameSite=None; Partitioned",
}},
}
session.absorb(requestURL.String(), resp.Header.Values("Set-Cookie"))
_, got, changed := session.State()
if !changed {
t.Fatal("Set-Cookie must mark session changed")
}
values := make(map[string]string)
for _, cookie := range got {
values[cookie.Name+"|"+cookie.Domain+"|"+cookie.Path+"|"+cookie.PartitionKey] = cookie.Value
}
if values["same|.goofish.com|/|"] != "root" {
t.Fatalf("root same-name cookie changed: %+v", got)
}
if values["same|h5api.m.goofish.com|/h5|"] != "api-new" {
t.Fatalf("host/path cookie not updated precisely: %+v", got)
}
if values["partitioned|h5api.m.goofish.com|/|"+goofishTopSite] != "value" {
t.Fatalf("partitioned cookie missing top-level key: %+v", got)
}
session.absorb(requestURL.String(), []string{"same=; Max-Age=-1; Path=/h5"})
_, got, _ = session.State()
for _, cookie := range got {
if cookie.Name == "same" && cookie.Domain == "h5api.m.goofish.com" && cookie.Path == "/h5" {
t.Fatalf("scoped deletion was not applied: %+v", got)
}
}
}
func TestCookieSessionAuthoritativeEmptyJar(t *testing.T) {
ctx, session := WithCookieSnapshot(context.Background(), nil)
signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
if signing != "" || request != "" {
t.Fatalf("authoritative empty jar leaked fallback: signing=%q request=%q", signing, request)
}
canonical, snapshot, changed := session.State()
if canonical != "" || snapshot == nil || len(snapshot) != 0 || changed {
t.Fatalf("empty state canonical=%q snapshot=%#v changed=%v", canonical, snapshot, changed)
}
}
func TestFlatCookieSessionCapturesUpdatesWithoutInventingSnapshot(t *testing.T) {
ctx, session := WithFlatCookieSession(context.Background(), "sid=old; keep=1")
signing, request := mtopRequestCookies(ctx, "fallback=must-not-leak", mtopDocumentURL, TokenAPI)
if signing != "sid=old; keep=1" || request != signing {
t.Fatalf("legacy flat session signing=%q request=%q", signing, request)
}
session.absorb(TokenAPI, []string{
"sid=new; Domain=.goofish.com; Path=/; Secure",
"keep=; Max-Age=0; Domain=.goofish.com; Path=/; Secure",
})
value, snapshot, changed := session.State()
if !changed || snapshot != nil || value != "sid=new" {
t.Fatalf("flat update value=%q snapshot=%#v changed=%v", value, snapshot, changed)
}
}
func TestScopedCookieHeaderForRequestIncludesMatchingPartitionAndUnpartitioned(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "plain", Value: "1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "part", Value: "2", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "other", Value: "3", Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
header, ok := cookierefresh.ScopedCookieHeaderForRequest(snapshot, TokenAPI, goofishTopSite, time.Now())
if !ok || !strings.Contains(header, "plain=1") || !strings.Contains(header, "part=2") || strings.Contains(header, "other=3") {
t.Fatalf("partition-scoped header=%q ok=%v", header, ok)
}
}
func TestLoginStatusUsesDocumentSigningAndURLScopedRequestCookies(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "im-token_1", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
ctx, session := WithCookieSnapshot(context.Background(), snapshot)
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
requestCookies := req.Header.Get("Cookie")
for _, want := range []string{"_m_h5_tk=root-token_1", "unb=123", "api_http_only=secret"} {
if !strings.Contains(requestCookies, want) {
t.Errorf("URL scoped Cookie %q missing %q", requestCookies, want)
}
}
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(requestCookies, unwanted) {
t.Errorf("URL scoped Cookie %q unexpectedly contains %q", requestCookies, unwanted)
}
}
if got := req.Header.Get("Referer"); got != mtopDocumentURL {
t.Errorf("Referer=%q want %q", got, mtopDocumentURL)
}
timestamp := req.URL.Query().Get("t")
wantSign := protocol.GenerateSign(timestamp, "im-token", `{}`)
if got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": {
"_m_h5_tk=rotated-token_9; Domain=.goofish.com; Path=/; Secure",
}},
Body: io.NopCloser(strings.NewReader("not-json")),
Request: req,
}, nil
})}}
_, err := client.CheckLoginStatusContext(ctx, "_m_h5_tk=fallback_1; fallback_only=leak")
if err == nil || !strings.Contains(err.Error(), "解析 loginuser.get 响应失败") {
t.Fatalf("err=%v", err)
}
canonical, gotSnapshot, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=rotated-token_9") {
t.Fatalf("response Cookie was not absorbed before body parse: canonical=%q changed=%v snapshot=%+v", canonical, changed, gotSnapshot)
}
}
func TestOrderDetailUsesOrderDocumentForSigningAndReferer(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "_m_h5_tk", Value: "order-token_1", Domain: "www.goofish.com", Path: "/order-detail", Secure: true},
{Name: "_m_h5_tk", Value: "root-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
}
ctx, _ := WithCookieSnapshot(context.Background(), snapshot)
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
if got := req.Header.Get("Referer"); got != "https://www.goofish.com/order-detail?orderId=order-1&role=seller" {
t.Errorf("Referer=%q", got)
}
if got := req.Header.Get("Cookie"); !strings.Contains(got, "_m_h5_tk=root-token_1") || strings.Contains(got, "order-token_1") {
t.Errorf("request Cookie=%q", got)
}
timestamp := req.URL.Query().Get("t")
wantSign := protocol.GenerateSign(timestamp, "order-token", `{"tid":"order-1"}`)
if got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"components":[]}}`)),
Request: req,
}, nil
})}}
if _, err := client.FetchOrderDetail(ctx, "fallback=must-not-leak", "order-1"); err != nil {
t.Fatal(err)
}
}
func TestPublishWorkflowUsesCookieSessionForEveryRequest(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "token0_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_http_only", Value: "api", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
{Name: "upload_http_only", Value: "upload", Domain: "stream-upload.goofish.com", Path: "/api", Secure: true, HTTPOnly: true},
}
ctx, session := WithCookieSnapshot(context.Background(), snapshot)
requestCount := 0
assertCookies := func(req *http.Request, token, scoped string) {
t.Helper()
requestCount++
cookieHeader := req.Header.Get("Cookie")
for _, want := range []string{"unb=123", "_m_h5_tk=" + token + "_1", scoped} {
if !strings.Contains(cookieHeader, want) {
t.Errorf("%s Cookie %q missing %q", req.URL.Host, cookieHeader, want)
}
}
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(cookieHeader, unwanted) {
t.Errorf("%s Cookie %q unexpectedly contains %q", req.URL.Host, cookieHeader, unwanted)
}
}
}
assertSign := func(req *http.Request, token string) {
t.Helper()
body, err := io.ReadAll(req.Body)
if err != nil {
t.Errorf("read request body: %v", err)
return
}
form, err := url.ParseQuery(string(body))
if err != nil {
t.Errorf("parse request body: %v", err)
return
}
timestamp := req.URL.Query().Get("t")
want := protocol.GenerateSign(timestamp, token, form.Get("data"))
if got := req.URL.Query().Get("sign"); got != want {
t.Errorf("%s sign=%q want %q", req.URL.Query().Get("api"), got, want)
}
}
rotate := func(w http.ResponseWriter, value string) {
w.Header().Add("Set-Cookie", "_m_h5_tk="+value+"_1; Domain=.goofish.com; Path=/; Secure")
}
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
"_upload": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token0", "upload_http_only=upload")
if strings.Contains(req.Header.Get("Cookie"), "api_http_only=") {
t.Errorf("upload request leaked h5api cookie: %q", req.Header.Get("Cookie"))
}
rotate(w, "token1")
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"1x1"}}`)
},
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token1", "api_http_only=api")
assertSign(req, "token1")
rotate(w, "token2")
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"categoryPredictResult":{"catId":"c1","catName":"类目"}}}`)
},
"mtop.taobao.idle.local.poi.get": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token2", "api_http_only=api")
assertSign(req, "token2")
rotate(w, "token3")
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"commonAddresses":[{"area":"X","city":"Y","divisionId":"1","longitude":118.7,"latitude":31.9,"poiId":"p1","poi":"P","prov":"Z"}]}}`)
},
"mtop.idle.pc.idleitem.publish": func(w http.ResponseWriter, req *http.Request) {
assertCookies(req, "token3", "api_http_only=api")
assertSign(req, "token3")
rotate(w, "token4")
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"itemId":"new-item"}}`)
},
}}
client := &ClientImpl{HTTPClient: &http.Client{Transport: dt}}
result, err := client.PublishItem(ctx, "_m_h5_tk=fallback_1; fallback_only=leak", PublishItemRequest{
Title: "T",
PriceCents: 100,
Quantity: 1,
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: tinyPNG(t)}},
})
if err != nil {
t.Fatalf("PublishItem: %v", err)
}
if requestCount != 4 || result.ItemID != "new-item" || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=token4_1") {
t.Fatalf("requests=%d result=%+v", requestCount, result)
}
canonical, _, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=token4_1") {
t.Fatalf("final session canonical=%q changed=%v", canonical, changed)
}
}
+12 -9
View File
@@ -21,31 +21,33 @@ type ItemDetailFetcher interface {
var _ ItemDetailFetcher = (*ClientImpl)(nil)
// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不刷新 token,
// 也不合并或持久化响应 Cookie。
// DetectItemMultiSpec 查询商品详情并识别多规格结构。该调用不主动刷新 token;
// 当 ctx 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID string) (bool, error) {
itemID = strings.TrimSpace(itemID)
if itemID == "" {
return false, fmt.Errorf("item_id 不能为空")
}
token := protocol.SignToken(cookies)
endpoint := c.ItemDetailURL
if endpoint == "" {
endpoint = ItemDetailAPI
}
documentURL := "https://www.goofish.com/item?id=" + url.QueryEscape(itemID)
signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, documentURL, endpoint)
token := protocol.SignToken(signingCookies)
if token == "" {
return false, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取商品详情")
}
dataVal := `{"itemId":` + strconv.Quote(itemID) + `}`
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
sign := protocol.GenerateSign(timestamp, token, dataVal)
endpoint := c.ItemDetailURL
if endpoint == "" {
endpoint = ItemDetailAPI
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildItemDetailQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return false, err
}
setCommonHeaders(req, cookies)
setCommonHeaders(req, requestCookies)
req.Header.Set("Origin", "https://www.goofish.com")
req.Header.Set("Referer", "https://www.goofish.com/item?id="+url.QueryEscape(itemID))
req.Header.Set("Referer", documentURL)
hc := c.HTTPClient
if hc == nil {
@@ -56,6 +58,7 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
return false, fmt.Errorf("商品详情请求失败: %w", err)
}
defer resp.Body.Close()
absorbMTopResponseCookies(ctx, cookies, resp)
raw, err := readMTopBody(resp)
if err != nil {
return false, err
+13 -6
View File
@@ -23,6 +23,9 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
pageSize = 20
}
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
res, ret, updatedCookies, err := c.fetchItemsPageOnce(ctx, currentCookies, pageNumber, pageSize)
@@ -46,7 +49,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
refreshed, err := c.RefreshToken(currentCookies)
refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
}
@@ -60,7 +63,8 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
cookies := protocol.TransCookies(signingCookies)
userID := cookies["unb"]
if userID == "" {
return nil, nil, cookiesStr, fmt.Errorf("cookie 缺少 unb 字段,无法获取商品列表")
@@ -78,7 +82,7 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildItemListQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
@@ -86,17 +90,17 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string,
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("商品列表请求失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, cookiesStr, err
return nil, nil, updated, err
}
updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
@@ -126,6 +130,9 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS
pageSize = 20
}
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
page := 1
var all []ItemListItem
for maxPages <= 0 || page <= maxPages {
+11 -6
View File
@@ -35,34 +35,39 @@ type LoginStatusResult struct {
// CheckLoginStatusContext 调用 loginuser.get 做低成本登录态检查。
// 它不会做浏览器动作;只负责分类响应和合并 Set-Cookie。
func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr string) (*LoginStatusResult, error) {
if session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, _, _ = session.State()
}
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{}`
query := buildLoginStatusQuery(t, protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal))
loginURL := c.LoginUserURL
if loginURL == "" {
loginURL = LoginUserAPI
}
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, loginURL)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{}`
query := buildLoginStatusQuery(t, protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal))
req, err := http.NewRequestWithContext(ctx, http.MethodPost, loginURL+"?"+query, strings.NewReader("data=%7B%7D"))
if err != nil {
return nil, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", mtopDocumentURL)
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("loginuser.get 请求失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, err
}
updated := mergeSetCookie(cookiesStr, protocol.TransCookies(cookiesStr), resp)
var payload struct {
Ret []string `json:"ret"`
+12 -7
View File
@@ -27,6 +27,9 @@ type OrderDetailResult struct {
// FetchOrderDetail 获取订单真实成交价、数量、状态和规格;token 过期时自动重签重试。
func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, error) {
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
previousCookies := currentCookies
@@ -67,29 +70,31 @@ func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, order
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"tid":"` + orderID + `"}`
sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
endpoint := c.OrderDetailURL
if endpoint == "" {
endpoint = OrderDetailAPI
}
documentURL := "https://www.goofish.com/order-detail?orderId=" + url.QueryEscape(orderID) + "&role=seller"
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, documentURL, endpoint)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"tid":"` + orderID + `"}`
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildOrderDetailQuery(t, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", documentURL)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("订单详情请求失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, cookiesStr, err
return nil, nil, updated, err
}
updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
Data map[string]any `json:"data"`
+12 -8
View File
@@ -110,6 +110,9 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
return nil, errors.New("商品图片最多 9 张")
}
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
uploaded := make([]uploadedImage, 0, len(req.Images))
for _, img := range req.Images {
res, updated, err := c.uploadPublishImage(ctx, currentCookies, img)
@@ -174,19 +177,20 @@ func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string,
if err != nil {
return uploadedImage{}, cookiesStr, err
}
_, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", u.String())
req.Header.Set("content-type", mw.FormDataContentType())
setBrowserHeaders(req, cookiesStr)
setBrowserHeaders(req, requestCookies)
req.Header.Set("accept", "*/*")
resp, err := hc.Do(req)
if err != nil {
return uploadedImage{}, cookiesStr, fmt.Errorf("上传商品图片失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return uploadedImage{}, cookiesStr, err
return uploadedImage{}, updated, err
}
updated := mergeSetCookie(cookiesStr, protocol.TransCookies(cookiesStr), resp)
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return uploadedImage{}, updated, fmt.Errorf("上传商品图片失败: http=%d body=%s", resp.StatusCode, truncate(string(raw), 240))
}
@@ -349,28 +353,28 @@ func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, ve
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildMTopQuery(api, version, t, sign, spmCnt, spmPre, logID)
body := "data=" + url.QueryEscape(dataVal)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+query, strings.NewReader(body))
if err != nil {
return nil, cookiesStr, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, cookiesStr, fmt.Errorf("%s 请求失败: %w", api, err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, cookiesStr, err
return nil, updated, err
}
updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded map[string]any
if err := json.Unmarshal(raw, &decoded); err != nil {
return nil, updated, fmt.Errorf("解析 %s 响应失败: %w (body=%s)", api, err, truncate(string(raw), 300))
+10 -8
View File
@@ -46,8 +46,8 @@ type SoldOrder struct {
var _ SoldOrderFetcher = (*ClientImpl)(nil)
// FetchSoldOrdersPage 获取卖家已售订单。该能力只使用调用方传入的 Cookie 签名,
// 不刷新 token、不合并 Set-Cookie,也不持久化 Cookie。
// FetchSoldOrdersPage 获取卖家已售订单。该调用不主动刷新 token;当 ctx
// 携带 CookieSession 时会像浏览器一样吸收响应 Cookie。
func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pageNumber, pageSize int) (*SoldOrdersPage, error) {
if pageNumber < 1 {
pageNumber = 1
@@ -55,7 +55,12 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
if pageSize < 1 || pageSize > 100 {
pageSize = 30
}
token := protocol.SignToken(cookies)
endpoint := c.SoldOrdersURL
if endpoint == "" {
endpoint = SoldOrdersAPI
}
signingCookies, requestCookies := mtopRequestCookies(ctx, cookies, soldOrdersReferer, endpoint)
token := protocol.SignToken(signingCookies)
if token == "" {
return nil, fmt.Errorf("cookie 缺少 _m_h5_tk,无法获取订单列表")
}
@@ -73,15 +78,11 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
dataVal := string(rawPayload)
timestamp := strconv.FormatInt(time.Now().UnixMilli(), 10)
sign := protocol.GenerateSign(timestamp, token, dataVal)
endpoint := c.SoldOrdersURL
if endpoint == "" {
endpoint = SoldOrdersAPI
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint+"?"+buildSoldOrdersQuery(timestamp, sign), strings.NewReader("data="+url.QueryEscape(dataVal)))
if err != nil {
return nil, err
}
setCommonHeaders(req, cookies)
setCommonHeaders(req, requestCookies)
req.Header.Set("Accept", "application/json")
req.Header.Set("Origin", "https://seller.goofish.com")
req.Header.Set("Referer", soldOrdersReferer)
@@ -96,6 +97,7 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
return nil, fmt.Errorf("订单列表请求失败: %w", err)
}
defer resp.Body.Close()
absorbMTopResponseCookies(ctx, cookies, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, err
+240 -59
View File
@@ -7,17 +7,21 @@ import (
"fmt"
"net/http"
"net/url"
"slices"
"sort"
"strconv"
"strings"
"time"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
const tokenRetryGap = 500 * time.Millisecond
const officialMTopMaxAttempts = 5
// RefreshToken 调用 mtop.taobao.idlemessage.pc.login.token 获取 accessToken。
// 遇到 mtop 签名 token 过期时,仅在响应下发了新 Cookie 后低频重试一次。
// 遇到 mtop 签名 token 过期时,按官网 lib-mtop 2.7.3 的 H5 流程最多执行
// 5 次请求(含首次),每次先吸收浏览器 Cookie Jar 再重新签名。
func (c *ClientImpl) RefreshToken(cookiesStr string) (*RefreshResult, error) {
return c.RefreshTokenContext(context.Background(), cookiesStr)
}
@@ -32,40 +36,104 @@ func (c *ClientImpl) RefreshTokenContext(ctx context.Context, cookiesStr string)
// 必须与 /reg.headers.did 完全一致,否则 /reg 会返回
// "device id or appkey is not equal"。
func (c *ClientImpl) RefreshTokenWithDeviceIDContext(ctx context.Context, cookiesStr, deviceID string) (*RefreshResult, error) {
return c.RefreshTokenWithCredentialContext(ctx, cookiesStr, deviceID, nil)
}
// RefreshTokenWithCredentialContext 在浏览器执行器可用时同时传入完整 Cookie
// 快照,避免把不同 Domain/Path 的同名 Cookie 压成一个值后再注入 Chromium。
func (c *ClientImpl) RefreshTokenWithCredentialContext(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (*RefreshResult, error) {
currentCookies := cookiesStr
for attempt := 0; attempt < 2; attempt++ {
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, AccessTokenExpireAt: expireAt, UpdatedCookies: updatedCookies}, nil
}
if isRiskVerificationRet(ret) {
return &RefreshResult{UpdatedCookies: updatedCookies}, &RiskVerificationError{Ret: ret, VerificationURL: verificationURL}
}
if !isTokenExpiredRet(ret) {
return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status)
}
// 参考实现对 FAIL_SYS_TOKEN_EXOIRED/EXPIRED 固定等待 0.5 秒重试
// 一次;是否收到 Set-Cookie 不改变重试次数。
if attempt == 1 {
return &RefreshResult{UpdatedCookies: updatedCookies}, fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status)
}
if updatedCookies != "" {
currentSnapshot := cookierefresh.NormalizeSnapshot(cookieSnapshot)
currentSnapshotComplete := cookieSnapshot != nil
cookieStateChanged := false
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, currentSnapshot, cookieStateChanged = session.State()
currentSnapshotComplete = currentSnapshot != nil
}
for attempt := 0; attempt < officialMTopMaxAttempts; attempt++ {
accessToken, expireAt, ret, updatedCookies, snapshot, verificationURL, status, snapshotComplete, attemptChanged, err := c.refreshTokenOnce(ctx, currentCookies, deviceID, currentSnapshot)
if updatedCookies != "" || snapshot != nil || attemptChanged {
currentCookies = updatedCookies
}
if err := sleepCtx(ctx, tokenRetryGap); err != nil {
return &RefreshResult{UpdatedCookies: currentCookies}, err
if snapshotComplete {
currentSnapshot = snapshot
currentSnapshotComplete = true
} else if attemptChanged {
// 只有扁平更新时无法把变化安全映射回既有 Domain/Path Jar;
// 必须降级为非权威状态,等待 Chromium 下次提供完整快照。
currentSnapshot = nil
currentSnapshotComplete = false
}
cookieStateChanged = cookieStateChanged || attemptChanged
if err != nil {
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), err
}
if accessToken != "" {
result := refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged)
result.AccessToken = accessToken
result.AccessTokenExpireAt = expireAt
return result, nil
}
if isRiskVerificationRet(ret) {
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), &RiskVerificationError{Ret: ret, VerificationURL: verificationURL}
}
if !isOfficialTokenRetryRet(ret) {
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 返回非成功: ret=%v (status=%d)", ret, status)
}
if attempt == officialMTopMaxAttempts-1 {
var snapshotForClear []cookierefresh.BrowserCookie
if currentSnapshotComplete {
snapshotForClear = currentSnapshot
}
cleanedCookies, cleanedSnapshot := clearOfficialMTopTokenCookies(currentCookies, snapshotForClear)
cookieStateChanged = cookieStateChanged || cleanedCookies != currentCookies || !slices.Equal(cleanedSnapshot, currentSnapshot)
currentCookies, currentSnapshot = cleanedCookies, cleanedSnapshot
if session := cookieSessionFromContext(ctx); session != nil {
if currentSnapshot != nil {
session.replace(currentSnapshot)
} else {
session.replaceFlat(currentCookies)
}
}
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 登录凭证已失效: ret=%v (status=%d)", ret, status)
}
}
return &RefreshResult{UpdatedCookies: currentCookies}, fmt.Errorf("token API 登录凭证已失效")
return refreshResultFromContext(ctx, currentCookies, currentSnapshot, currentSnapshotComplete, cookieStateChanged), fmt.Errorf("token API 登录凭证已失效")
}
func refreshResult(updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
if !complete {
snapshot = nil
}
return &RefreshResult{
UpdatedCookies: updatedCookies,
CookieSnapshot: snapshot,
CookieSnapshotComplete: complete,
CookieStateChanged: changed,
}
}
func refreshResultFromContext(ctx context.Context, updatedCookies string, snapshot []cookierefresh.BrowserCookie, complete, changed bool) *RefreshResult {
if session := cookieSessionFromContext(ctx); session != nil {
var sessionChanged bool
updatedCookies, snapshot, sessionChanged = session.State()
complete = snapshot != nil
changed = changed || sessionChanged
}
return refreshResult(updatedCookies, snapshot, complete, changed)
}
// RequestFreshCaptchaURLContext 重新请求 token API,用于浏览器风控验证前获取新鲜验证链接。
// 如果风控已解除并直接返回 accessToken,则 TokenOK=true。
func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesStr, deviceID string) (*FreshCaptchaResult, error) {
accessToken, expireAt, ret, updatedCookies, verificationURL, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID)
var snapshot []cookierefresh.BrowserCookie
if session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, snapshot, _ = session.State()
}
accessToken, expireAt, ret, updatedCookies, _, verificationURL, _, _, _, err := c.refreshTokenOnce(ctx, cookiesStr, deviceID, snapshot)
if session := cookieSessionFromContext(ctx); session != nil {
updatedCookies, _, _ = session.State()
}
if err != nil {
return &FreshCaptchaResult{UpdatedCookies: updatedCookies}, err
}
@@ -85,21 +153,28 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
}, nil
}
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string) (string, int64, []string, string, string, int, error) {
func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID string, cookieSnapshot []cookierefresh.BrowserCookie) (string, int64, []string, string, []cookierefresh.BrowserCookie, string, int, bool, bool, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
hc = &http.Client{Timeout: 20 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
myid := cookies["unb"]
tokenURL := c.TokenURL
if tokenURL == "" {
tokenURL = TokenAPI
}
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, mtopDocumentURL, tokenURL)
if cookieSessionFromContext(ctx) == nil && cookieSnapshot != nil {
signingCookies, requestCookies = snapshotRequestCookies(cookieSnapshot, cookiesStr, tokenURL)
}
myid := protocol.TransCookies(signingCookies)["unb"]
if myid == "" {
return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId")
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("cookie 缺少 unb 字段,无法生成 deviceId")
}
if strings.TrimSpace(deviceID) == "" {
deviceID = protocol.GenerateDeviceID(myid)
}
token := protocol.SignToken(cookiesStr)
token := protocol.SignToken(signingCookies)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"` + deviceID + `"}`
@@ -109,46 +184,81 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
body := "data=" + url.QueryEscape(dataVal)
tokenURL := c.TokenURL
if tokenURL == "" {
tokenURL = TokenAPI
}
requestURL := tokenURL + "?" + query
var raw []byte
var status int
updated := cookiesStr
var snapshot []cookierefresh.BrowserCookie
snapshotComplete := false
stateChanged := false
if c.TokenExecutor != nil {
browserResp, execErr := c.TokenExecutor.ExecuteTokenRequest(ctx, TokenBrowserRequest{
URL: requestURL, Body: body, Cookies: cookiesStr,
URL: requestURL, Body: body, Cookies: cookiesStr, CookieSnapshot: cookieSnapshot,
})
if browserResp != nil {
raw, status = browserResp.Body, browserResp.Status
stateChanged = browserResp.CookieStateChanged
if browserResp.CookieStateChanged || browserResp.CookieSnapshotComplete || strings.TrimSpace(browserResp.UpdatedCookies) != "" {
updated = browserResp.UpdatedCookies
}
if browserResp.CookieSnapshotComplete {
snapshot = cookierefresh.NormalizeSnapshot(browserResp.CookieSnapshot)
if snapshot == nil {
snapshot = []cookierefresh.BrowserCookie{}
}
snapshotComplete = true
updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
}
stateChanged = stateChanged || updated != cookiesStr || (snapshot != nil && !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot)))
}
if session := cookieSessionFromContext(ctx); session != nil && snapshot != nil {
session.replace(snapshot)
var sessionChanged bool
updated, snapshot, sessionChanged = session.State()
stateChanged = stateChanged || sessionChanged
snapshotComplete = true
}
if execErr != nil {
return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 请求失败: %w", execErr)
return "", 0, nil, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("浏览器 token API 请求失败: %w", execErr)
}
if browserResp == nil {
return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("浏览器 token API 返回空响应")
}
raw, status = browserResp.Body, browserResp.Status
if strings.TrimSpace(browserResp.UpdatedCookies) != "" {
updated = browserResp.UpdatedCookies
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("浏览器 token API 返回空响应")
}
} else {
req, reqErr := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, strings.NewReader(body))
if reqErr != nil {
return "", 0, nil, cookiesStr, "", 0, reqErr
return "", 0, nil, cookiesStr, nil, "", 0, false, false, reqErr
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
req.Header.Set("Referer", "https://www.goofish.com/im")
resp, reqErr := hc.Do(req)
if reqErr != nil {
return "", 0, nil, cookiesStr, "", 0, fmt.Errorf("token API 请求失败: %w", reqErr)
return "", 0, nil, cookiesStr, nil, "", 0, false, false, fmt.Errorf("token API 请求失败: %w", reqErr)
}
defer resp.Body.Close()
// Chromium applies Set-Cookie as soon as response headers arrive. Mirror
// that ordering so a body read/parse failure cannot discard credential
// rotation or deletion already issued by the server.
if session := cookieSessionFromContext(ctx); session != nil {
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
var sessionChanged bool
_, snapshot, sessionChanged = session.State()
stateChanged = sessionChanged
snapshotComplete = snapshot != nil
} else if cookieSnapshot != nil {
snapshot = cookierefresh.ApplySetCookies(cookieSnapshot, requestURL, resp.Header.Values("Set-Cookie"), time.Now(), goofishTopSite)
updated, _ = cookierefresh.ScopedCookieHeaderForRequest(snapshot, mtopDocumentURL, goofishTopSite, time.Now())
stateChanged = !slices.Equal(snapshot, cookierefresh.NormalizeSnapshot(cookieSnapshot))
snapshotComplete = true
} else {
updated = absorbMTopResponseCookies(ctx, cookiesStr, resp)
stateChanged = updated != cookiesStr
}
raw, reqErr = readMTopBody(resp)
if reqErr != nil {
return "", 0, nil, cookiesStr, "", resp.StatusCode, reqErr
return "", 0, nil, updated, snapshot, "", resp.StatusCode, snapshotComplete, stateChanged, reqErr
}
status = resp.StatusCode
// 即使业务返回 token 过期,也要保留响应下发的新签名 Cookie。
updated = mergeSetCookie(cookiesStr, cookies, resp)
}
var res struct {
@@ -160,23 +270,93 @@ func (c *ClientImpl) refreshTokenOnce(ctx context.Context, cookiesStr, deviceID
} `json:"data"`
}
if err := json.Unmarshal(raw, &res); err != nil {
return "", 0, nil, updated, "", status, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
return "", 0, nil, updated, snapshot, "", status, snapshotComplete, stateChanged, fmt.Errorf("解析 token 响应失败: %w (body=%s)", err, truncate(string(raw), 300))
}
ok := false
for _, r := range res.Ret {
if strings.Contains(r, "SUCCESS::调用成功") {
if strings.Contains(r, "SUCCESS") {
ok = true
break
}
}
if !ok {
return "", 0, res.Ret, updated, res.Data.URL, status, nil
return "", 0, res.Ret, updated, snapshot, res.Data.URL, status, snapshotComplete, stateChanged, nil
}
if res.Data.AccessToken == "" {
return "", 0, res.Ret, updated, "", status, fmt.Errorf("token API 成功但 accessToken 为空 (body=%s)", truncate(string(raw), 300))
return "", 0, res.Ret, updated, snapshot, "", status, snapshotComplete, stateChanged, 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
return res.Data.AccessToken, parseAccessTokenExpireAt(res.Data.AccessTokenExpiredTime, time.Now()), res.Ret, updated, snapshot, "", status, snapshotComplete, stateChanged, nil
}
func snapshotRequestCookies(snapshot []cookierefresh.BrowserCookie, fallback, requestURL string) (string, string) {
if snapshot == nil {
return fallback, fallback
}
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
for _, cookie := range snapshot {
if !cookie.HTTPOnly {
documentCookies = append(documentCookies, cookie)
}
}
signing, _ := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, mtopDocumentURL, goofishTopSite, time.Now())
requestCookies, _ := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, time.Now())
return signing, requestCookies
}
func isOfficialTokenRetryRet(ret []string) bool {
for _, value := range ret {
if strings.Contains(value, "TOKEN_EMPTY") || strings.Contains(value, "TOKEN_EXOIRED") {
return true
}
}
return false
}
func clearOfficialMTopTokenCookies(cookieStr string, snapshot []cookierefresh.BrowserCookie) (string, []cookierefresh.BrowserCookie) {
values := protocol.TransCookies(cookieStr)
for _, name := range []string{"_m_h5_c", "_m_h5_tk", "_m_h5_tk_enc"} {
delete(values, name)
}
var cleaned []cookierefresh.BrowserCookie
if snapshot != nil {
cleaned = make([]cookierefresh.BrowserCookie, 0, len(snapshot))
}
for _, cookie := range snapshot {
domain := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(cookie.Domain), "."))
cookiePath := cookie.Path
if cookiePath == "" {
cookiePath = "/"
}
remove := cookiePath == "/" && domain == "goofish.com" &&
(cookie.Name == "_m_h5_c" || cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc")
remove = remove || (cookiePath == "/" && domain == "m.goofish.com" &&
(cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc"))
if !remove {
cleaned = append(cleaned, cookie)
}
}
cleaned = cookierefresh.NormalizeSnapshot(cleaned)
if snapshot != nil {
// 完整 Jar 存在时,扁平兼容值也必须重新按 /im scope 生成;不能用
// name map 把仍有效的 Path=/im 同名凭证一并抹掉。
canonical, _ := cookierefresh.ScopedCookieHeaderForRequest(cleaned, mtopDocumentURL, goofishTopSite, time.Now())
return canonical, cleaned
}
return marshalTokenCookies(values), cleaned
}
func marshalTokenCookies(cookies map[string]string) string {
keys := make([]string, 0, len(cookies))
for key := range cookies {
keys = append(keys, key)
}
sort.Strings(keys)
parts := make([]string, 0, len(keys))
for _, key := range keys {
parts = append(parts, key+"="+cookies[key])
}
return strings.Join(parts, "; ")
}
func parseAccessTokenExpireAt(raw json.RawMessage, now time.Time) int64 {
@@ -216,15 +396,16 @@ func buildTokenQuery(t, sign string) string {
{"accountSite", "xianyu"},
{"dataType", "json"},
{"timeout", "20000"},
{"needLoginPC", "false"},
{"showErrorToast", "false"},
{"api", "mtop.taobao.idlemessage.pc.login.token"},
{"needLogin", "false"},
{"sessionOption", "AutoLoginOnly"},
{"ecode", "0"},
{"dangerouslySetWindvaneParams", "%5Bobject%20Object%5D"},
{"smToken", "token"},
{"queryToken", "sm"},
{"sm", "sm"},
{"spm_cnt", "a21ybx.im.0.0"},
{"spm_pre", "a21ybx.home.sidebar.1.4c053da6vYwnmf"},
{"log_id", "4c053da6vYwnmf"},
{"spm_pre", ""},
{"log_id", ""},
}
var b strings.Builder
for i, p := range parts {
+309 -10
View File
@@ -4,14 +4,18 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"xianyu-go/internal/xianyu"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
const testCookiesWithUnb = "unb=123; _m_h5_tk=oldtoken_1;"
@@ -32,10 +36,12 @@ func (e *recordingTokenExecutor) ExecuteTokenRequest(_ context.Context, req Toke
}
func TestRefreshTokenUsesBrowserExecutor(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true}}
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
Status: http.StatusOK,
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"browser-token"}}`),
UpdatedCookies: testCookiesWithUnb + " x5sec=fresh;",
CookieSnapshot: snapshot,
}}}
client := &ClientImpl{TokenExecutor: executor}
result, err := client.RefreshTokenWithDeviceIDContext(context.Background(), testCookiesWithUnb, "permanent-device")
@@ -45,6 +51,9 @@ func TestRefreshTokenUsesBrowserExecutor(t *testing.T) {
if result.AccessToken != "browser-token" || !strings.Contains(result.UpdatedCookies, "x5sec=fresh") {
t.Fatalf("result=%+v", result)
}
if result.CookieSnapshotComplete || result.CookieSnapshot != nil {
t.Fatalf("未声明完整的浏览器快照不得冒充权威 Jar: %+v", result)
}
if len(executor.requests) != 1 {
t.Fatalf("browser requests=%d", len(executor.requests))
}
@@ -54,6 +63,136 @@ func TestRefreshTokenUsesBrowserExecutor(t *testing.T) {
}
}
func TestRefreshTokenWithCredentialPassesBrowserSnapshot(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "sid", Value: "scoped", Domain: "h5api.m.goofish.com", Path: "/h5", HTTPOnly: true, Secure: true},
}
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
Status: http.StatusOK,
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"scoped-token"}}`),
UpdatedCookies: "unb=123; sid=scoped",
CookieSnapshot: snapshot,
}}}
client := &ClientImpl{TokenExecutor: executor}
result, err := client.RefreshTokenWithCredentialContext(context.Background(), testCookiesWithUnb, "device", snapshot)
if err != nil || result.AccessToken != "scoped-token" {
t.Fatalf("result=%+v err=%v", result, err)
}
if len(executor.requests) != 1 || len(executor.requests[0].CookieSnapshot) != 2 {
t.Fatalf("完整 Cookie 快照未传给浏览器执行器: %+v", executor.requests)
}
}
func TestRefreshTokenContextInheritsAndWritesCookieSession(t *testing.T) {
initial := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "session-old_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "api_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
refreshed := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "session-new_9", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "api_only", Value: "rotated", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
Status: http.StatusOK,
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"context-token"}}`),
UpdatedCookies: "must-not-replace-authoritative-session=1",
CookieSnapshot: refreshed,
CookieSnapshotComplete: true,
}}}
ctx, session := WithCookieSnapshot(context.Background(), initial)
explicitWrong := []cookierefresh.BrowserCookie{{Name: "unb", Value: "999", Domain: ".goofish.com", Path: "/", Secure: true}}
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
ctx, "unb=fallback; _m_h5_tk=fallback_1", "device", explicitWrong,
)
if err != nil || result.AccessToken != "context-token" {
t.Fatalf("result=%+v err=%v", result, err)
}
if len(executor.requests) != 1 || len(executor.requests[0].CookieSnapshot) != len(initial) {
t.Fatalf("executor did not inherit context snapshot: %+v", executor.requests)
}
if got := protocol.TransCookies(executor.requests[0].Cookies)["_m_h5_tk"]; got != "session-old_1" {
t.Fatalf("executor flat cookies did not inherit context: %q", executor.requests[0].Cookies)
}
canonical, gotSnapshot, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=session-new_9") || len(gotSnapshot) != len(refreshed) {
t.Fatalf("session was not written back: canonical=%q snapshot=%+v changed=%v", canonical, gotSnapshot, changed)
}
if !result.CookieSnapshotComplete || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=session-new_9") {
t.Fatalf("result did not reflect authoritative context session: %+v", result)
}
}
func TestRefreshTokenHTTPUsesCookieSessionScopes(t *testing.T) {
initial := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "document-old_1", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "document_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
{Name: "api_http_only", Value: "secret", Domain: "h5api.m.goofish.com", Path: "/h5", Secure: true, HTTPOnly: true},
}
ctx, session := WithCookieSnapshot(context.Background(), initial)
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
cookieHeader := req.Header.Get("Cookie")
for _, want := range []string{"unb=123", "_m_h5_tk=document-old_1", "api_http_only=secret"} {
if !strings.Contains(cookieHeader, want) {
t.Errorf("request Cookie %q missing %q", cookieHeader, want)
}
}
for _, unwanted := range []string{"document_only=", "fallback_only="} {
if strings.Contains(cookieHeader, unwanted) {
t.Errorf("request Cookie %q unexpectedly contains %q", cookieHeader, unwanted)
}
}
timestamp := req.URL.Query().Get("t")
dataVal := `{"appKey":"` + RegAppKey + `","deviceId":"did"}`
wantSign := protocol.GenerateSign(timestamp, "document-old", dataVal)
if got := req.URL.Query().Get("sign"); got != wantSign {
t.Errorf("sign=%q want %q", got, wantSign)
}
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": {
"_m_h5_tk=document-new_9; Domain=.goofish.com; Path=/; Secure",
}},
Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"direct-context"}}`)),
Request: req,
}, nil
})}}
result, err := client.RefreshTokenWithDeviceIDContext(ctx, "unb=fallback; _m_h5_tk=fallback_1; fallback_only=leak", "did")
if err != nil || result.AccessToken != "direct-context" {
t.Fatalf("result=%+v err=%v", result, err)
}
canonical, _, changed := session.State()
if !changed || !strings.Contains(canonical, "_m_h5_tk=document-new_9") || !strings.Contains(result.UpdatedCookies, "_m_h5_tk=document-new_9") {
t.Fatalf("canonical=%q result=%+v changed=%v", canonical, result, changed)
}
}
func TestRefreshTokenAllowsSnapshotOnlyCredential(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "snapshot-token_1", Domain: ".goofish.com", Path: "/", Secure: true},
}
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
Status: http.StatusOK,
Body: []byte(`{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"snapshot-only"}}`),
UpdatedCookies: "unb=123; _m_h5_tk=snapshot-token_1",
CookieSnapshot: snapshot,
CookieSnapshotComplete: true,
}}}
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
context.Background(), "", "device", snapshot,
)
if err != nil || result.AccessToken != "snapshot-only" {
t.Fatalf("result=%+v err=%v", result, err)
}
if len(executor.requests) != 1 || executor.requests[0].Cookies != "" {
t.Fatalf("snapshot-only request=%+v", executor.requests)
}
}
// TestRefreshTokenWithDeviceIDSuccessOnRetry: 首次返回 token 过期 + Set-Cookie,二次成功。
func TestRefreshTokenWithDeviceIDSuccessOnRetry(t *testing.T) {
var requests atomic.Int32
@@ -178,9 +317,9 @@ func TestRefreshTokenRequestError(t *testing.T) {
}
}
// TestRefreshTokenExpiredRetNoCookieRetriesOnce: 参考实现即使响应未下发新 Cookie,
// 也固定等待 0.5 秒重试一次。
func TestRefreshTokenExpiredRetNoCookieRetriesOnce(t *testing.T) {
// TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit: 官网 lib-mtop 即使
// 响应未下发新 Cookie,也会最多执行五次请求(含首次)。
func TestRefreshTokenExpiredRetNoCookieUsesOfficialAttemptLimit(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
@@ -194,8 +333,166 @@ func TestRefreshTokenExpiredRetNoCookieRetriesOnce(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("err=%v", err)
}
if requests.Load() != 2 {
t.Fatalf("requests=%d want 2", requests.Load())
if requests.Load() != officialMTopMaxAttempts {
t.Fatalf("requests=%d want %d", requests.Load(), officialMTopMaxAttempts)
}
}
func TestRefreshTokenExhaustionClearsOfficialMTopCookies(t *testing.T) {
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/"},
{Name: "keep", Value: "yes", Domain: ".goofish.com", Path: "/"},
{Name: "_m_h5_c", Value: "c", Domain: ".goofish.com", Path: "/"},
{Name: "_m_h5_tk", Value: "tk", Domain: ".goofish.com", Path: "/"},
{Name: "_m_h5_tk_enc", Value: "enc", Domain: ".m.goofish.com", Path: "/"},
{Name: "_m_h5_tk", Value: "scoped", Domain: ".goofish.com", Path: "/im"},
}
responses := make([]*TokenBrowserResponse, officialMTopMaxAttempts)
for i := range responses {
responses[i] = &TokenBrowserResponse{
Status: http.StatusOK,
Body: []byte(`{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"]}`),
UpdatedCookies: "unb=123; _m_h5_c=c; _m_h5_tk=tk; _m_h5_tk_enc=enc; keep=yes",
CookieSnapshot: snapshot,
CookieSnapshotComplete: true,
}
}
executor := &recordingTokenExecutor{responses: responses}
result, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenWithCredentialContext(
context.Background(), testCookiesWithUnb, "did", snapshot,
)
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("result=%+v err=%v", result, err)
}
if len(executor.requests) != officialMTopMaxAttempts {
t.Fatalf("requests=%d want %d", len(executor.requests), officialMTopMaxAttempts)
}
for _, name := range []string{"_m_h5_c=", "_m_h5_tk_enc="} {
if strings.Contains(result.UpdatedCookies, name) {
t.Fatalf("官网清理后仍包含 %s: %q", name, result.UpdatedCookies)
}
}
if !strings.Contains(result.UpdatedCookies, "_m_h5_tk=scoped") {
t.Fatalf("Path=/im 的同名 token 不应被根路径清理误删: %q", result.UpdatedCookies)
}
if !strings.Contains(result.UpdatedCookies, "keep=yes") {
t.Fatalf("无关 Cookie 被误删: %q", result.UpdatedCookies)
}
var keptScoped bool
for _, cookie := range result.CookieSnapshot {
if cookie.Name == "_m_h5_tk" && cookie.Path == "/im" {
keptScoped = true
}
if cookie.Path == "/" && (cookie.Name == "_m_h5_c" || cookie.Name == "_m_h5_tk" || cookie.Name == "_m_h5_tk_enc") {
t.Fatalf("官网根路径凭证 Cookie 未清理: %+v", cookie)
}
}
if !keptScoped {
t.Fatal("不属于官网清理目标的同名作用域 Cookie 被误删")
}
}
func TestRefreshTokenFlatSessionExhaustionPersistsOfficialCookieClear(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
}))
defer server.Close()
initial := "unb=123; _m_h5_c=c; _m_h5_tk=oldtoken_1; _m_h5_tk_enc=enc; keep=yes"
ctx, session := WithFlatCookieSession(context.Background(), initial)
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(ctx, initial)
if err == nil || !strings.Contains(err.Error(), "登录凭证已失效") {
t.Fatalf("result=%+v err=%v", result, err)
}
for _, removed := range []string{"_m_h5_c=", "_m_h5_tk=", "_m_h5_tk_enc="} {
if strings.Contains(result.UpdatedCookies, removed) {
t.Fatalf("legacy flat 清理结果仍包含 %s: %q", removed, result.UpdatedCookies)
}
}
if !strings.Contains(result.UpdatedCookies, "unb=123") || !strings.Contains(result.UpdatedCookies, "keep=yes") || !result.CookieStateChanged {
t.Fatalf("result=%+v", result)
}
value, snapshot, changed := session.State()
if !changed || snapshot != nil || value != result.UpdatedCookies {
t.Fatalf("session value=%q snapshot=%+v changed=%v result=%+v", value, snapshot, changed, result)
}
}
func TestRefreshTokenKeepsAccumulatedSnapshotWhenLaterAttemptFails(t *testing.T) {
var calls atomic.Int32
client := &ClientImpl{HTTPClient: &http.Client{Transport: cookieSessionRoundTripFunc(func(req *http.Request) (*http.Response, error) {
if calls.Add(1) == 1 {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Set-Cookie": {
"off_im=rotated; Domain=.goofish.com; Path=/account; Secure; HttpOnly",
}},
Body: io.NopCloser(strings.NewReader(`{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)),
Request: req,
}, nil
}
return nil, fmt.Errorf("second attempt network failure")
})}}
snapshot := []cookierefresh.BrowserCookie{
{Name: "unb", Value: "123", Domain: ".goofish.com", Path: "/", Secure: true},
{Name: "_m_h5_tk", Value: "oldtoken_1", Domain: ".goofish.com", Path: "/", Secure: true},
}
result, err := client.RefreshTokenWithCredentialContext(context.Background(), testCookiesWithUnb, "did", snapshot)
if err == nil || !strings.Contains(err.Error(), "network failure") {
t.Fatalf("result=%+v err=%v", result, err)
}
if !result.CookieSnapshotComplete || !result.CookieStateChanged {
t.Fatalf("累计 Jar 状态丢失: %+v", result)
}
var found bool
for _, cookie := range result.CookieSnapshot {
if cookie.Name == "off_im" && cookie.Value == "rotated" && cookie.Path == "/account" {
found = true
}
}
if !found {
t.Fatalf("首轮 off-/im Set-Cookie 在后续网络失败后丢失: %+v", result.CookieSnapshot)
}
}
func TestRefreshTokenPreservesExplicitFlatDeletionOnParseError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Add("Set-Cookie", "unb=; Path=/; Max-Age=0")
w.Header().Add("Set-Cookie", "_m_h5_tk=; Path=/; Max-Age=0")
_, _ = w.Write([]byte(`not-json`))
}))
defer server.Close()
result, err := (&ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || !strings.Contains(err.Error(), "解析 token 响应失败") {
t.Fatalf("result=%+v err=%v", result, err)
}
if result.UpdatedCookies != "" || !result.CookieStateChanged || result.CookieSnapshotComplete {
t.Fatalf("明确删除到空的 flat Cookie 被恢复: %+v", result)
}
}
func TestRefreshTokenSessionExpiredDoesNotUseTokenRetry(t *testing.T) {
executor := &recordingTokenExecutor{responses: []*TokenBrowserResponse{{
Status: http.StatusOK,
Body: []byte(`{"ret":["FAIL_SYS_SESSION_EXPIRED::会话过期"]}`),
}}}
_, err := (&ClientImpl{TokenExecutor: executor}).RefreshTokenContext(context.Background(), testCookiesWithUnb)
if err == nil || len(executor.requests) != 1 {
t.Fatalf("err=%v requests=%d want 1", err, len(executor.requests))
}
}
func TestBuildTokenQueryMatchesCurrentMessagePageContext(t *testing.T) {
query, err := url.ParseQuery(buildTokenQuery("123", "sig"))
if err != nil {
t.Fatal(err)
}
if query.Get("spm_cnt") != "a21ybx.im.0.0" || query.Get("spm_pre") != "" || query.Get("log_id") != "" {
t.Fatalf("spm query=%v", query)
}
for _, stale := range []string{"smToken", "queryToken", "sm"} {
if _, ok := query[stale]; ok {
t.Fatalf("官网当前 token 请求不应包含 %s: %v", stale, query)
}
}
}
@@ -218,7 +515,7 @@ func TestRefreshTokenUsesReferenceFingerprint(t *testing.T) {
}
}
// TestRefreshTokenContextCanceled: ctx 取消时 sleepCtx 返回 ctx.Err。
// TestRefreshTokenContextCanceled: 连续重试期间仍遵守调用方 ctx。
func TestRefreshTokenContextCanceled(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -228,16 +525,18 @@ func TestRefreshTokenContextCanceled(t *testing.T) {
fmt.Fprint(w, `{"ret":["FAIL_SYS_TOKEN_EXOIRED::令牌过期"],"data":{}}`)
return
}
fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"accessToken":"x"}}`)
select {
case <-r.Context().Done():
case <-time.After(time.Second):
}
}))
defer server.Close()
client := &ClientImpl{HTTPClient: server.Client(), TokenURL: server.URL + "/"}
ctx, cancel := context.WithCancel(context.Background())
// 在第一次请求返回后、sleep 触发前取消
// 在第二次请求开始后取消,避免依赖固定重试延迟。
go func() {
// 等待第一次请求完成
for requests.Load() < 1 {
for requests.Load() < 2 {
time.Sleep(5 * time.Millisecond)
}
cancel()
+9 -6
View File
@@ -17,6 +17,9 @@ import (
// FetchUserProfile 获取当前 cookie 对应账号的实时昵称和头像。
func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*UserProfileResult, error) {
currentCookies := cookiesStr
if session := cookieSessionFromContext(ctx); session != nil {
currentCookies, _, _ = session.State()
}
var lastRet []string
for attempt := 0; attempt < 4; attempt++ {
res, ret, updatedCookies, err := c.fetchUserProfileOnce(ctx, currentCookies)
@@ -40,7 +43,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
if err := sleepCtx(ctx, MTopRetryGap); err != nil {
return nil, err
}
refreshed, err := c.RefreshToken(currentCookies)
refreshed, err := c.RefreshTokenContext(ctx, currentCookies)
if err != nil {
return nil, fmt.Errorf("刷新 mtop token 失败: %w", err)
}
@@ -55,10 +58,10 @@ func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string
hc = &http.Client{Timeout: 30 * time.Second}
}
cookies := protocol.TransCookies(cookiesStr)
dataVal := "{}"
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
t := strconv.FormatInt(time.Now().UnixMilli(), 10)
sign := protocol.GenerateSign(t, protocol.SignToken(cookiesStr), dataVal)
sign := protocol.GenerateSign(t, protocol.SignToken(signingCookies), dataVal)
query := buildUserPageNavQuery(t, sign)
body := "data=" + url.QueryEscape(dataVal)
@@ -66,18 +69,18 @@ func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string
if err != nil {
return nil, nil, cookiesStr, err
}
setCommonHeaders(req, cookiesStr)
setCommonHeaders(req, requestCookies)
resp, err := hc.Do(req)
if err != nil {
return nil, nil, cookiesStr, fmt.Errorf("账号资料请求失败: %w", err)
}
defer resp.Body.Close()
updated := absorbMTopResponseCookies(ctx, cookiesStr, resp)
raw, err := readMTopBody(resp)
if err != nil {
return nil, nil, cookiesStr, err
return nil, nil, updated, err
}
updated := mergeSetCookie(cookiesStr, cookies, resp)
var decoded struct {
Ret []string `json:"ret"`
+11 -1
View File
@@ -24,7 +24,17 @@ func TransCookies(cookiesStr string) map[string]string {
// SignToken 从 cookie 字符串中提取 _m_h5_tk 的前半段,作为 mtop API 签名用的 token。
// _m_h5_tk 形如 "<token>_<timestamp>",取 "_" 前的部分。
func SignToken(cookiesStr string) string {
v := TransCookies(cookiesStr)["_m_h5_tk"]
// 浏览器 Cookie header / document.cookie 会把更长 Path 的同名 Cookie
// 排在前面,官网 cookie getter 读取首个匹配项。不能先压成 map 再取值,
// 否则同名 token 会被最后一个(通常是更宽作用域)错误覆盖。
v := ""
for _, part := range strings.Split(cookiesStr, ";") {
key, value, ok := strings.Cut(strings.TrimSpace(part), "=")
if ok && strings.TrimSpace(key) == "_m_h5_tk" {
v = strings.TrimSpace(value)
break
}
}
if v == "" {
return ""
}
+7
View File
@@ -69,6 +69,13 @@ func TestSignToken(t *testing.T) {
}
}
func TestSignTokenUsesFirstScopedDuplicate(t *testing.T) {
got := SignToken("_m_h5_tk=narrow_1; other=x; _m_h5_tk=wide_2")
if got != "narrow" {
t.Fatalf("SignToken duplicate=%q want narrow", got)
}
}
// TestSignToken_ConsistentWithTransCookies SignToken 必须基于 TransCookies 的解析结果。
func TestSignToken_ConsistentWithTransCookies(t *testing.T) {
cookies := "x=1; _m_h5_tk=mytoken_999; y=2"
+332 -124
View File
@@ -1,8 +1,6 @@
// Package renew 实现闲鱼登录 Cookie 续期链路。
//
// 这层只负责低成本 HTTP 续期:hasLogin.do -> silentHasLogin.do ->
// setLoginSettings.do。浏览器续期和密码登录属于更重的恢复手段,应该由上层在
// 本包返回失败后再决定是否执行。
// Package renew 实现闲鱼登录 Cookie 续期与“保存登录信息”接口。
// 主动续期严格复用 auto-login plugin 的单次 silentHasLogin 流程;长登录开关
// 独立执行 setLoginSettings -> queryLoginSettings,不混入主动续期链。
package renew
import (
@@ -18,16 +16,21 @@ import (
"time"
"xianyu-go/internal/xianyu"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/protocol"
)
const (
HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
QueryLoginSettingsURL = "https://passport.goofish.com/ac/account/queryLoginSettings.do"
defaultRequestTimout = 2 * time.Second
maxRenewBodyBytes = 2 << 20
HasLoginURL = "https://passport.goofish.com/newlogin/hasLogin.do"
SilentHasLoginURL = "https://passport.goofish.com/newlogin/silentHasLogin.do"
SetLoginSettingsURL = "https://passport.goofish.com/ac/account/setLoginSettings.do"
QueryLoginSettingsURL = "https://passport.goofish.com/ac/account/queryLoginSettings.do"
defaultRequestTimout = 2 * time.Second
backgroundFetchTimeout = 30 * time.Second
longLoginRequestTimout = 30 * time.Second
maxRenewBodyBytes = 2 << 20
goofishTopSite = "https://goofish.com"
goofishIMDocumentURL = "https://www.goofish.com/im"
)
// Service 是 Cookie 接口续期服务。零值可用;测试可覆盖 URL 和 HTTPClient。
@@ -42,80 +45,185 @@ type Service struct {
}
type LongLoginSettings struct {
CanOpenLongLogin bool `json:"can_open_long_login"`
Enabled bool `json:"enabled"`
NewCookies string `json:"-"`
SetCookies []string `json:"-"`
CanOpenLongLogin bool `json:"can_open_long_login"`
Enabled bool `json:"enabled"`
NewCookies string `json:"-"`
SetCookies []string `json:"-"`
CookieSnapshot []cookierefresh.BrowserCookie `json:"-"`
CookieSnapshotComplete bool `json:"-"`
}
type longLoginCookieState struct {
flat string
snapshot []cookierefresh.BrowserCookie
authoritative bool
}
func newLongLoginCookieState(cookiesStr string, snapshots [][]cookierefresh.BrowserCookie) *longLoginCookieState {
state := &longLoginCookieState{flat: cookiesStr, authoritative: len(snapshots) > 0}
if state.authoritative {
state.snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
if state.snapshot == nil {
state.snapshot = []cookierefresh.BrowserCookie{}
}
state.refreshCanonical()
}
return state
}
func (state *longLoginCookieState) requestCookies(requestURL string) string {
if state == nil || !state.authoritative {
if state == nil {
return ""
}
return state.flat
}
value, _ := cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, requestURL, goofishTopSite, time.Now())
return value
}
func (state *longLoginCookieState) apply(requestURL string, setCookies []string) {
if state == nil {
return
}
if state.authoritative {
state.snapshot = cookierefresh.ApplySetCookies(state.snapshot, requestURL, setCookies, time.Now(), goofishTopSite)
if state.snapshot == nil {
state.snapshot = []cookierefresh.BrowserCookie{}
}
state.refreshCanonical()
return
}
state.flat = MergeSetCookies(state.flat, setCookies)
}
func (state *longLoginCookieState) refreshCanonical() {
state.flat, _ = cookierefresh.ScopedCookieHeaderForRequest(state.snapshot, goofishIMDocumentURL, goofishTopSite, time.Now())
}
func (state *longLoginCookieState) populate(result *LongLoginSettings) {
if state == nil || result == nil {
return
}
result.NewCookies = state.flat
result.CookieSnapshotComplete = state.authoritative
if state.authoritative {
result.CookieSnapshot = cookierefresh.NormalizeSnapshot(state.snapshot)
if result.CookieSnapshot == nil {
result.CookieSnapshot = []cookierefresh.BrowserCookie{}
}
}
}
// QueryLongLoginSettings 对齐官网个人信息弹窗的“保存登录信息”查询。
func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string) (*LongLoginSettings, error) {
return s.longLoginRequest(ctx, cookiesStr, nil)
func (s Service) QueryLongLoginSettings(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
return s.longLoginRequest(ctx, newLongLoginCookieState(cookiesStr, snapshots), nil)
}
// SetLongLoginSettings 中 status=0 表示开启,status=1 表示关闭。
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool) (*LongLoginSettings, error) {
func (s Service) SetLongLoginSettings(ctx context.Context, cookiesStr string, enabled bool, snapshots ...[]cookierefresh.BrowserCookie) (*LongLoginSettings, error) {
status := "1"
if enabled {
status = "0"
}
return s.longLoginRequest(ctx, cookiesStr, &status)
state := newLongLoginCookieState(cookiesStr, snapshots)
setResult, err := s.longLoginRequest(ctx, state, &status)
if err != nil {
return setResult, err
}
// 官网 SET 成功后触发 LONG_LOGIN_SWITCH,再通过 QUERY 获取最终状态;SET
// 本身只要求 data.success,不要求携带 returnValue。
queried, err := s.longLoginRequest(ctx, state, nil)
if queried == nil {
queried = &LongLoginSettings{
Enabled: enabled,
}
state.populate(queried)
}
queried.SetCookies = append(append([]string(nil), setResult.SetCookies...), queried.SetCookies...)
if err != nil {
// QUERY 失败时仍返回 SET 请求及 QUERY 响应头已经刷新的 Cookie;最终
// 开关状态尚未确认,只能保留调用方本次请求的目标值。
queried.Enabled = enabled
return queried, err
}
return queried, nil
}
func (s Service) longLoginRequest(ctx context.Context, cookiesStr string, status *string) (*LongLoginSettings, error) {
func (s Service) longLoginRequest(ctx context.Context, cookieState *longLoginCookieState, status *string) (*LongLoginSettings, error) {
partial := &LongLoginSettings{}
cookieState.populate(partial)
if status != nil {
partial.Enabled = *status == "0"
}
cookieURL := QueryLoginSettingsURL
target := s.urlOrDefault(s.QueryLoginSettingsURL, QueryLoginSettingsURL)
var body io.Reader
if status != nil {
cookieURL = SetLoginSettingsURL
target = s.urlOrDefault(s.SetLoginSettingsURL, SetLoginSettingsURL)
body = strings.NewReader("status=" + url.QueryEscape(*status))
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, body)
if err != nil {
return nil, err
return partial, err
}
q := req.URL.Query()
q.Set("fromSite", "77")
q.Set("appName", "xianyu")
q.Set("bizEntrance", "web")
req.URL.RawQuery = q.Encode()
setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer())
appendOrderedQuery(req.URL, [][2]string{{"fromSite", "77"}, {"appName", "xianyu"}, {"bizEntrance", "web"}})
setSilentHasLoginHeaders(req, cookieState.requestCookies(cookieURL), s.documentReferer())
if status != nil {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
hc := s.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: defaultRequestTimout}
hc = &http.Client{Timeout: longLoginRequestTimout}
}
requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout)
requestCtx, cancel := context.WithTimeout(req.Context(), longLoginRequestTimout)
defer cancel()
resp, err := hc.Do(req.Clone(requestCtx))
if err != nil {
return nil, fmt.Errorf("保存登录信息请求失败: %w", err)
return partial, fmt.Errorf("保存登录信息请求失败: %w", err)
}
defer resp.Body.Close()
// 浏览器在响应头到达时就会更新 Cookie Jar;因此必须先捕获 Set-Cookie,
// 即使随后读取响应体、校验 HTTP 状态或解析业务 JSON 失败也要返回给调用方。
partial.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
cookieState.apply(cookieURL, partial.SetCookies)
cookieState.populate(partial)
raw, err := readRenewBody(resp.Body)
if err != nil {
return nil, err
return partial, fmt.Errorf("保存登录信息响应读取失败: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
return partial, fmt.Errorf("保存登录信息 HTTP 状态异常: %d", resp.StatusCode)
}
if status != nil {
if !longLoginSetBusinessOK(raw) {
return partial, fmt.Errorf("保存登录信息业务结果未确认成功")
}
return partial, nil
}
value, ok := findReturnValue(raw)
if !ok {
return nil, fmt.Errorf("保存登录信息响应缺少 returnValue")
return partial, fmt.Errorf("保存登录信息响应缺少 returnValue")
}
canOpen, _ := value["canOpenLongLogin"].(bool)
enabledValue, hasEnabled := value["hasLongTokenLogin"].(bool)
if status != nil && !hasEnabled {
enabledValue = *status == "0"
partial.CanOpenLongLogin, _ = value["canOpenLongLogin"].(bool)
partial.Enabled, _ = value["hasLongTokenLogin"].(bool)
return partial, nil
}
func longLoginSetBusinessOK(raw []byte) bool {
var payload map[string]any
if json.Unmarshal(raw, &payload) != nil {
return false
}
setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie"))
return &LongLoginSettings{
CanOpenLongLogin: canOpen,
Enabled: enabledValue,
NewCookies: MergeSetCookies(cookiesStr, setCookies),
SetCookies: setCookies,
}, nil
if success, _ := payload["success"].(bool); success {
return true
}
if data, _ := payload["data"].(map[string]any); data != nil {
success, _ := data["success"].(bool)
return success
}
return false
}
func findReturnValue(raw []byte) (map[string]any, bool) {
@@ -145,18 +253,20 @@ func findMapChild(parent map[string]any, key string, depth int) (map[string]any,
// Result 描述一次接口续期的完整结果。
type Result struct {
Success bool
Skipped bool
SkipReason string
RenewMethod string
NewCookies string
UpdatedCookieNames []string
SetCookies []string
StepDetails []StepResult
Message string
ResponseText string
NeedPasswordLogin bool
RequestCount int
Success bool
Skipped bool
SkipReason string
RenewMethod string
NewCookies string
UpdatedCookieNames []string
SetCookies []string
CookieSnapshot []cookierefresh.BrowserCookie
CookieSnapshotComplete bool
StepDetails []StepResult
Message string
ResponseText string
NeedPasswordLogin bool
RequestCount int
}
// StepResult 是单个续期接口的执行结果,便于上层记录日志和定位失败点。
@@ -178,20 +288,62 @@ const (
// branch, waits briefly, and sends exactly one silentHasLogin request.
// It never chains hasLogin/setLoginSettings or escalates to an interactive
// login from this proactive renewal path.
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result, error) {
func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string, snapshots ...[]cookierefresh.BrowserCookie) (*Result, error) {
cookiesStr = strings.TrimSpace(cookiesStr)
if cookiesStr == "" {
return &Result{RenewMethod: "none", Message: "Cookie为空,无法续期", NeedPasswordLogin: true}, nil
authoritativeSnapshot := len(snapshots) > 0 && snapshots[0] != nil
documentURL := s.documentReferer()
requestURL := s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL)
now := time.Now()
decisionCookies := cookiesStr
requestCookies := cookiesStr
newCookies := cookiesStr
var snapshot []cookierefresh.BrowserCookie
if authoritativeSnapshot {
snapshot = cookierefresh.NormalizeSnapshot(snapshots[0])
documentCookies := make([]cookierefresh.BrowserCookie, 0, len(snapshot))
for _, cookie := range snapshot {
if !cookie.HTTPOnly {
documentCookies = append(documentCookies, cookie)
}
}
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(documentCookies, documentURL, goofishTopSite, now); authoritative {
decisionCookies = scoped
}
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, requestURL, goofishTopSite, now); authoritative {
requestCookies = scoped
}
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(snapshot, goofishIMDocumentURL, goofishTopSite, now); authoritative {
newCookies = scoped
}
}
mode, skipReason := autoLoginMode(protocol.TransCookies(cookiesStr), time.Now())
result := &Result{
RenewMethod: "auto_login_plugin",
NewCookies: newCookies,
}
if authoritativeSnapshot {
result.CookieSnapshot = make([]cookierefresh.BrowserCookie, len(snapshot))
copy(result.CookieSnapshot, snapshot)
result.CookieSnapshotComplete = true
}
if cookiesStr == "" && !authoritativeSnapshot {
result.RenewMethod = "none"
result.Message = "Cookie为空,无法续期"
result.NeedPasswordLogin = true
return result, nil
}
if ua := strings.ToLower(xianyu.CurrentBrowserFingerprint().UserAgent); ua != "" &&
!strings.Contains(ua, "windows") && !strings.Contains(ua, "macintosh") {
result.Skipped = true
result.SkipReason = "unsupported_desktop_ua"
result.Message = autoLoginSkipMessage(result.SkipReason)
return result, nil
}
mode, skipReason := autoLoginMode(firstCookieValues(decisionCookies), now)
if skipReason != "" {
return &Result{
Skipped: true,
SkipReason: skipReason,
RenewMethod: "auto_login_plugin",
NewCookies: cookiesStr,
Message: autoLoginSkipMessage(skipReason),
}, nil
result.Skipped = true
result.SkipReason = skipReason
result.Message = autoLoginSkipMessage(skipReason)
return result, nil
}
delay := 2 * time.Second
if s.RetryDelay < 0 {
@@ -204,38 +356,48 @@ func (s Service) RenewAPIFirst(ctx context.Context, cookiesStr string) (*Result,
select {
case <-ctx.Done():
timer.Stop()
return nil, ctx.Err()
result.Message = ctx.Err().Error()
result.NeedPasswordLogin = true
return result, ctx.Err()
case <-timer.C:
}
}
call, err := s.callAutoLogin(ctx, cookiesStr, mode)
if err != nil {
return nil, err
call, err := s.callAutoLogin(ctx, requestCookies, mode)
result.RequestCount = 1
result.SetCookies = append([]string(nil), call.SetCookies...)
result.ResponseText = string(call.Body)
if strings.TrimSpace(call.Step.Name) != "" {
result.StepDetails = []StepResult{call.Step}
}
newCookies := cookiesStr
if len(call.SetCookies) > 0 {
newCookies = MergeSetCookies(cookiesStr, call.SetCookies)
if authoritativeSnapshot {
updatedSnapshot := cookierefresh.ApplySetCookies(snapshot, requestURL, call.SetCookies, time.Now(), goofishTopSite)
result.CookieSnapshot = updatedSnapshot
result.CookieSnapshotComplete = true
if scoped, authoritative := cookierefresh.ScopedCookieHeaderForRequest(updatedSnapshot, goofishIMDocumentURL, goofishTopSite, time.Now()); authoritative {
result.NewCookies = scoped
}
result.UpdatedCookieNames = cookierefresh.ChangedSnapshotLabels(snapshot, updatedSnapshot)
} else {
result.NewCookies = MergeSetCookies(cookiesStr, call.SetCookies)
result.UpdatedCookieNames = ChangedCookieNames(cookiesStr, result.NewCookies)
}
if err != nil {
result.Message = err.Error()
result.NeedPasswordLogin = true
return result, err
}
message := "静默续期成功"
if !call.Step.BusinessOK {
message = firstNonEmpty(call.Step.Message, "静默续期未通过")
}
return &Result{
Success: call.Step.BusinessOK,
RenewMethod: "auto_login_plugin",
NewCookies: newCookies,
UpdatedCookieNames: ChangedCookieNames(cookiesStr, newCookies),
SetCookies: append([]string(nil), call.SetCookies...),
StepDetails: []StepResult{call.Step},
Message: message,
ResponseText: string(call.Body),
NeedPasswordLogin: !call.Step.BusinessOK,
RequestCount: 1,
}, nil
result.Success = call.Step.BusinessOK
result.Message = message
result.NeedPasswordLogin = !call.Step.BusinessOK
return result, nil
}
func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason string) {
if cookieTimeAfter(cookies["sdkSilent"], now) {
if strictCookieTimeAfter(cookies["sdkSilent"], now) {
return "", "fatigue"
}
if cookieTimeAfter(cookies["havana_lgc_exp"], now) {
@@ -247,6 +409,33 @@ func autoLoginMode(cookies map[string]string, now time.Time) (mode, skipReason s
return "", "long_login_expired"
}
// firstCookieValues 对齐浏览器 document.cookie getter:同名 Cookie 按浏览器
// header 顺序读取首个值。ScopedCookieHeaderForRequest 已把更长 Path 排在前面。
func firstCookieValues(cookieHeader string) map[string]string {
values := make(map[string]string)
for _, part := range strings.Split(cookieHeader, ";") {
name, value, ok := strings.Cut(strings.TrimSpace(part), "=")
name = strings.TrimSpace(name)
if !ok || name == "" {
continue
}
if _, exists := values[name]; exists {
continue
}
values[name] = strings.TrimSpace(value)
}
return values
}
func strictCookieTimeAfter(raw string, now time.Time) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
return false
}
millis, err := strconv.ParseInt(raw, 10, 64)
return err == nil && millis > now.UnixMilli()
}
func cookieTimeAfter(raw string, now time.Time) bool {
raw = strings.TrimSpace(raw)
if raw == "" {
@@ -267,6 +456,8 @@ func autoLoginSkipMessage(reason string) string {
return "sdkSilent 疲劳窗口内,跳过静默续期"
case "long_login_expired":
return "长登录凭证已过期,静默续期不应发起请求"
case "unsupported_desktop_ua":
return "官网静默续期仅支持 Windows 或 macOS 桌面浏览器"
default:
return "无需静默续期"
}
@@ -279,63 +470,73 @@ type callResult struct {
}
func (s Service) callAutoLogin(ctx context.Context, cookiesStr, mode string) (callResult, error) {
partial := callResult{Step: StepResult{Name: "silentHasLogin"}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.urlOrDefault(s.SilentHasLoginURL, SilentHasLoginURL), nil)
if err != nil {
return callResult{}, err
return partial, err
}
query := [][2]string{
{"documentReferer", s.documentReferer()},
{"appName", "xianyu"},
{"appEntrance", "xianyu_sdkSilent"},
{"fromSite", "0"},
}
q := req.URL.Query()
q.Set("documentReferer", s.documentReferer())
q.Set("appName", "xianyu")
q.Set("appEntrance", "xianyu_sdkSilent")
q.Set("fromSite", "0")
switch mode {
case autoLoginModeHavana:
q.Set("ltl", "true")
query = append(query, [2]string{"ltl", "true"})
case autoLoginModeCookie3:
q.Set("skipSessionFilter", "true")
q.Set("c2r", "true")
query = append(query, [2]string{"skipSessionFilter", "true"}, [2]string{"c2r", "true"})
default:
return callResult{}, fmt.Errorf("未知静默续期模式: %s", mode)
return partial, fmt.Errorf("未知静默续期模式: %s", mode)
}
req.URL.RawQuery = q.Encode()
appendOrderedQuery(req.URL, query)
setSilentHasLoginHeaders(req, cookiesStr, s.documentReferer())
return s.doRenewRequest(req, "silentHasLogin")
}
func (s Service) doRenewRequest(req *http.Request, name string) (callResult, error) {
result := callResult{Step: StepResult{Name: name}}
hc := s.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: defaultRequestTimout}
hc = &http.Client{Timeout: backgroundFetchTimeout}
}
requestCtx, cancel := context.WithTimeout(req.Context(), defaultRequestTimout)
// 官网 2 秒超时只 reject 外层 Promise,不会 AbortController 取消 fetch。
// 这里继续等待底层响应以吸收可能迟到的 Set-Cookie,但超过 2 秒后不再把
// 业务成功解释成 location.reload。
requestCtx, cancel := context.WithTimeout(req.Context(), backgroundFetchTimeout)
defer cancel()
req = req.Clone(requestCtx)
startedAt := time.Now()
resp, err := hc.Do(req)
if err != nil {
return callResult{}, fmt.Errorf("%s 请求失败: %w", name, err)
result.Step.Message = fmt.Sprintf("请求失败: %v", err)
return result, fmt.Errorf("%s 请求失败: %w", name, err)
}
defer resp.Body.Close()
// 与浏览器 Cookie Jar 一样,在响应头到达后立即接收 Set-Cookie。后续响应体
// 读取失败也不能丢弃服务端已经完成的凭证轮换。
result.SetCookies = filterValidSetCookies(resp.Header.Values("Set-Cookie"))
result.Step.HTTPStatus = resp.StatusCode
result.Step.SetCookieCount = len(result.SetCookies)
body, err := readRenewBody(resp.Body)
if err != nil {
return callResult{}, fmt.Errorf("%s 响应读取失败: %w", name, err)
}
setCookies := filterValidSetCookies(resp.Header.Values("Set-Cookie"))
step := StepResult{
Name: name,
HTTPStatus: resp.StatusCode,
SetCookieCount: len(setCookies),
result.Step.Message = fmt.Sprintf("响应读取失败: %v", err)
return result, fmt.Errorf("%s 响应读取失败: %w", name, err)
}
result.Body = body
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
return callResult{Step: step, SetCookies: setCookies, Body: body}, nil
result.Step.Message = fmt.Sprintf("HTTP状态异常: %d", resp.StatusCode)
return result, nil
}
step.BusinessOK = renewBusinessOK(body)
if step.BusinessOK {
step.Message = "业务成功"
result.Step.BusinessOK = time.Since(startedAt) <= defaultRequestTimout && renewBusinessOK(body)
if result.Step.BusinessOK {
result.Step.Message = "业务成功"
} else if time.Since(startedAt) > defaultRequestTimout {
result.Step.Message = "官网静默续期 Promise 已超时;已保留底层响应 Cookie"
} else {
step.Message = "业务结果未确认成功"
result.Step.Message = "业务结果未确认成功"
}
return callResult{Step: step, SetCookies: setCookies, Body: body}, nil
return result, nil
}
func renewBusinessOK(body []byte) bool {
@@ -358,23 +559,22 @@ func renewBusinessOK(body []byte) bool {
data, _ := content["data"].(map[string]any)
if data != nil {
finished, _ := data["processFinished"].(bool)
if finished && mtopInt(data["resultCode"]) == 100 {
if finished && numericResultCode(data["resultCode"]) == 100 {
return true
}
}
return false
}
func mtopInt(v any) int {
func numericResultCode(v any) int {
switch value := v.(type) {
case float64:
return int(value)
case json.Number:
n, _ := strconv.Atoi(value.String())
return n
case string:
n, _ := strconv.Atoi(value)
return n
case int:
return value
default:
return 0
}
@@ -384,9 +584,6 @@ func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer str
xianyu.ApplyBrowserFingerprint(req.Header)
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Priority", "u=1, i")
req.Header.Set("Origin", "https://www.goofish.com")
req.Header.Set("Referer", documentReferer)
req.Header.Set("sec-fetch-dest", "empty")
@@ -395,6 +592,17 @@ func setSilentHasLoginHeaders(req *http.Request, cookiesStr, documentReferer str
req.Header.Set("Cookie", strings.ReplaceAll(strings.ReplaceAll(cookiesStr, "\n", ""), "\r", ""))
}
func appendOrderedQuery(target *url.URL, values [][2]string) {
parts := make([]string, 0, len(values)+1)
if strings.TrimSpace(target.RawQuery) != "" {
parts = append(parts, target.RawQuery)
}
for _, item := range values {
parts = append(parts, url.QueryEscape(item[0])+"="+url.QueryEscape(item[1]))
}
target.RawQuery = strings.Join(parts, "&")
}
func (s Service) urlOrDefault(v, fallback string) string {
if strings.TrimSpace(v) != "" {
return v
@@ -452,7 +660,7 @@ func MergeSetCookies(original string, setCookies []string) string {
if err != nil || strings.TrimSpace(parsed.Name) == "" {
continue
}
if parsed.MaxAge < 0 || (!parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
if parsed.MaxAge < 0 || (parsed.MaxAge == 0 && !parsed.Expires.IsZero() && !parsed.Expires.After(time.Now())) {
delete(cookies, parsed.Name)
} else {
cookies[parsed.Name] = parsed.Value
+285 -5
View File
@@ -2,7 +2,9 @@ package renew
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
@@ -12,12 +14,40 @@ import (
"time"
"xianyu-go/internal/xianyu"
"xianyu-go/internal/xianyu/cookierefresh"
)
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
type failingReadCloser struct {
err error
}
func (r failingReadCloser) Read([]byte) (int, error) { return 0, r.err }
func (failingReadCloser) Close() error { return nil }
func futureMillis(d time.Duration) string {
return strconv.FormatInt(time.Now().Add(d).UnixMilli(), 10)
}
func useTestDesktopFingerprint(t *testing.T) xianyu.BrowserFingerprint {
t.Helper()
old := xianyu.CurrentBrowserFingerprint()
fingerprint := xianyu.BrowserFingerprint{
UserAgent: `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/999.0.0.0 Safari/537.36`,
SecChUA: `"Chromium";v="999", "Google Chrome";v="999", "Not_A Brand";v="24"`,
Platform: "macOS",
Mobile: "?0",
}
xianyu.SetBrowserFingerprint(fingerprint)
t.Cleanup(func() { xianyu.SetBrowserFingerprint(old) })
return fingerprint
}
func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
now := time.Now()
tests := []struct {
@@ -27,6 +57,7 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
wantReason string
}{
{name: "fatigue", cookies: map[string]string{"sdkSilent": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10), "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantReason: "fatigue"},
{name: "malformed sdkSilent does not cause fatigue", cookies: map[string]string{"sdkSilent": "invalid", "havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
{name: "havana", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
{name: "cookie3 backup", cookies: map[string]string{"havana_lgc_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10), "cookie3_bak_exp": strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeCookie3},
{name: "malformed long-login expiry follows browser Invalid Date branch", cookies: map[string]string{"havana_lgc_exp": "bad", "cookie3_bak_exp": strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10)}, wantMode: autoLoginModeHavana},
@@ -41,6 +72,20 @@ func TestAutoLoginModeMatchesBrowserPlugin(t *testing.T) {
}
}
func TestAutoLoginDecisionUsesFirstCookieForDuplicatePaths(t *testing.T) {
now := time.Now()
cookies := strings.Join([]string{
"sdkSilent=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
"sdkSilent=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
"havana_lgc_exp=" + strconv.FormatInt(now.Add(time.Hour).UnixMilli(), 10),
"havana_lgc_exp=" + strconv.FormatInt(now.Add(-time.Hour).UnixMilli(), 10),
}, "; ")
mode, reason := autoLoginMode(firstCookieValues(cookies), now)
if mode != autoLoginModeHavana || reason != "" {
t.Fatalf("mode=%q reason=%q;应采用浏览器排序后的首个同名 Cookie", mode, reason)
}
}
func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -63,6 +108,10 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
}
}
http.SetCookie(w, &http.Cookie{Name: "havana_lgc_exp", Value: futureMillis(24 * time.Hour), Path: "/", HttpOnly: true})
if strings.Contains(r.URL.Path, "set") {
_, _ = w.Write([]byte(`{"data":{"success":true}}`))
return
}
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer srv.Close()
@@ -78,16 +127,132 @@ func TestLongLoginSettingsMatchOfficialRequest(t *testing.T) {
t.Fatalf("query result=%+v err=%v", queried, err)
}
set, err := service.SetLongLoginSettings(context.Background(), queried.NewCookies, true)
if err != nil || !set.Enabled || len(set.SetCookies) != 1 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") {
if err != nil || !set.Enabled || len(set.SetCookies) != 2 || !strings.Contains(set.NewCookies, "havana_lgc_exp=") {
t.Fatalf("set result=%+v err=%v", set, err)
}
if calls.Load() != 2 {
if calls.Load() != 3 {
t.Fatalf("calls=%d", calls.Load())
}
}
func TestLongLoginRequestKeepsResponseCookiesOnFailures(t *testing.T) {
tests := []struct {
name string
statusCode int
body io.ReadCloser
}{
{
name: "body read",
statusCode: http.StatusOK,
body: failingReadCloser{err: errors.New("broken body")},
},
{
name: "business parse",
statusCode: http.StatusOK,
body: io.NopCloser(strings.NewReader(`not-json`)),
},
{
name: "http status",
statusCode: http.StatusServiceUnavailable,
body: io.NopCloser(strings.NewReader(`{"error":"busy"}`)),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: tt.statusCode,
Header: http.Header{
"Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
},
Body: tt.body,
}, nil
})}
settings, err := (Service{HTTPClient: client}).QueryLongLoginSettings(context.Background(), "unb=1")
if err == nil || settings == nil {
t.Fatalf("settings=%+v err=%v", settings, err)
}
if len(settings.SetCookies) != 1 || !strings.Contains(settings.NewCookies, "rotated=fresh") {
t.Fatalf("response Cookie was lost: %+v", settings)
}
})
}
}
func TestSetLongLoginSettingsMergesSetAndFailedQueryCookies(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
if strings.Contains(r.URL.Path, "set") {
http.SetCookie(w, &http.Cookie{Name: "set_cookie", Value: "one", Path: "/"})
_, _ = w.Write([]byte(`{"data":{"success":true}}`))
return
}
if !strings.Contains(r.Header.Get("Cookie"), "set_cookie=one") {
t.Fatalf("QUERY did not receive SET Cookie: %q", r.Header.Get("Cookie"))
}
http.SetCookie(w, &http.Cookie{Name: "query_cookie", Value: "two", Path: "/"})
w.WriteHeader(http.StatusBadGateway)
_, _ = w.Write([]byte(`{"error":"upstream"}`))
}))
defer srv.Close()
svc := Service{
HTTPClient: srv.Client(),
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
}
settings, err := svc.SetLongLoginSettings(context.Background(), "unb=1", true)
if err == nil || settings == nil {
t.Fatalf("settings=%+v err=%v", settings, err)
}
if calls.Load() != 2 || len(settings.SetCookies) != 2 || !settings.Enabled {
t.Fatalf("settings=%+v calls=%d", settings, calls.Load())
}
if !strings.Contains(settings.NewCookies, "set_cookie=one") || !strings.Contains(settings.NewCookies, "query_cookie=two") {
t.Fatalf("SET/QUERY Cookie was lost: %q", settings.NewCookies)
}
}
func TestSetLongLoginSettingsScopesCompleteJarBetweenSetAndQuery(t *testing.T) {
var queryCookie string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.URL.Path, "set") {
w.Header().Add("Set-Cookie", "set_only=hidden; Path=/ac/account/setLoginSettings.do; Secure")
w.Header().Add("Set-Cookie", "shared=next; Path=/ac/account; Secure")
_, _ = w.Write([]byte(`{"data":{"success":true}}`))
return
}
queryCookie = r.Header.Get("Cookie")
_, _ = w.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer srv.Close()
snapshot := []cookierefresh.BrowserCookie{
{Name: "shared", Value: "old", Domain: "passport.goofish.com", Path: "/ac/account", Secure: true},
{Name: "im_only", Value: "visible", Domain: "www.goofish.com", Path: "/im", Secure: true},
}
svc := Service{
HTTPClient: srv.Client(),
SetLoginSettingsURL: srv.URL + "/setLoginSettings.do",
QueryLoginSettingsURL: srv.URL + "/queryLoginSettings.do",
}
settings, err := svc.SetLongLoginSettings(context.Background(), "fallback=must-not-leak", true, snapshot)
if err != nil {
t.Fatal(err)
}
if strings.Contains(queryCookie, "set_only=hidden") || !strings.Contains(queryCookie, "shared=next") {
t.Fatalf("QUERY Cookie 未按更新后 Jar 重新做 Path scope: %q", queryCookie)
}
if !settings.CookieSnapshotComplete || len(settings.CookieSnapshot) != 3 {
t.Fatalf("最终完整 Jar 未返回: %+v", settings)
}
if settings.NewCookies != "im_only=visible" {
t.Fatalf("/im canonical Cookie=%q", settings.NewCookies)
}
}
func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
xianyu.SetBrowserFingerprint(xianyu.BrowserFingerprint{UserAgent: "native-browser-ua", SecChUA: `"Chromium";v="999"`, Platform: "macOS", Mobile: "?0"})
fingerprint := useTestDesktopFingerprint(t)
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
@@ -100,7 +265,7 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
if got := r.URL.Query().Get("documentReferer"); got != "https://www.goofish.com/im" {
t.Fatalf("documentReferer=%q", got)
}
if got := r.Header.Get("User-Agent"); got != "native-browser-ua" {
if got := r.Header.Get("User-Agent"); got != fingerprint.UserAgent {
t.Fatalf("User-Agent=%q", got)
}
if got := r.Header.Get("Cookie"); !strings.Contains(got, "unb=1") {
@@ -125,12 +290,117 @@ func TestRenewAPIFirstHavanaSendsOneSilentRequest(t *testing.T) {
}
}
func TestRenewAPIFirstUsesBrowserCookieScopes(t *testing.T) {
useTestDesktopFingerprint(t)
var receivedCookie string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedCookie = r.Header.Get("Cookie")
_, _ = w.Write([]byte(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`))
}))
defer srv.Close()
host := strings.TrimPrefix(srv.URL, "http://")
host = strings.Split(host, ":")[0]
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/"},
{Name: "request_only", Value: "passport", Domain: host, Path: "/"},
{Name: "www_only", Value: "private", Domain: "www.goofish.com", Path: "/im"},
{Name: "http_only_document", Value: "hidden", Domain: ".goofish.com", Path: "/", HTTPOnly: true},
}
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, DocumentReferer: "https://www.goofish.com/im", RetryDelay: -1}
res, err := svc.RenewAPIFirst(context.Background(), "havana_lgc_exp="+futureMillis(time.Hour)+"; request_only=passport; www_only=private", snapshot)
if err != nil || !res.Success {
t.Fatalf("result=%+v err=%v", res, err)
}
if !strings.Contains(receivedCookie, "request_only=passport") || strings.Contains(receivedCookie, "www_only=private") {
t.Fatalf("passport 请求未遵守 Cookie Domain/Path: %q", receivedCookie)
}
if !res.CookieSnapshotComplete || res.CookieSnapshot == nil {
t.Fatalf("authoritative snapshot was not returned: %+v", res)
}
}
func TestRenewAPIFirstUsesTopSiteAndAppliesPartitionedSetCookie(t *testing.T) {
useTestDesktopFingerprint(t)
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "passport_partitioned", Value: "right", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: goofishTopSite},
{Name: "wrong_partition", Value: "hidden", Domain: "passport.goofish.com", Path: "/", Secure: true, PartitionKey: "https://example.com"},
}
client := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
cookies := req.Header.Get("Cookie")
if !strings.Contains(cookies, "passport_partitioned=right") || strings.Contains(cookies, "wrong_partition=hidden") {
t.Fatalf("partitioned request Cookie=%q", cookies)
}
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; Partitioned"},
},
Body: io.NopCloser(strings.NewReader(`{"data":{"content":{"data":{"processFinished":true,"resultCode":100}}}}`)),
}, nil
})}
svc := Service{HTTPClient: client, RetryDelay: -1}
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
if err != nil || !res.Success {
t.Fatalf("result=%+v err=%v", res, err)
}
if !res.CookieSnapshotComplete || !strings.Contains(res.NewCookies, "rotated=fresh") {
t.Fatalf("authoritative renewal result=%+v", res)
}
found := false
for _, cookie := range res.CookieSnapshot {
if cookie.Name == "rotated" && cookie.Value == "fresh" && cookie.PartitionKey == goofishTopSite {
found = true
}
}
if !found || len(res.UpdatedCookieNames) == 0 {
t.Fatalf("partitioned Set-Cookie was not applied exactly: %+v", res)
}
}
func TestRenewAPIFirstKeepsSetCookieWhenBodyReadFails(t *testing.T) {
useTestDesktopFingerprint(t)
snapshot := []cookierefresh.BrowserCookie{
{Name: "havana_lgc_exp", Value: futureMillis(time.Hour), Domain: ".goofish.com", Path: "/", Secure: true},
}
client := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{
"Set-Cookie": {"rotated=fresh; Domain=.goofish.com; Path=/; Secure; HttpOnly"},
},
Body: failingReadCloser{err: errors.New("broken response body")},
}, nil
})}
svc := Service{HTTPClient: client, RetryDelay: -1}
res, err := svc.RenewAPIFirst(context.Background(), "", snapshot)
if err == nil || res == nil {
t.Fatalf("result=%+v err=%v", res, err)
}
if !res.CookieSnapshotComplete || res.RequestCount != 1 || len(res.SetCookies) != 1 || !strings.Contains(res.NewCookies, "rotated=fresh") {
t.Fatalf("response Cookie was lost after body error: %+v", res)
}
}
func TestRenewAPIFirstTreatsNonNilEmptySnapshotAsAuthoritative(t *testing.T) {
useTestDesktopFingerprint(t)
emptySnapshot := make([]cookierefresh.BrowserCookie, 0)
res, err := (Service{RetryDelay: -1}).RenewAPIFirst(context.Background(), "", emptySnapshot)
if err != nil || !res.Skipped || res.SkipReason != "long_login_expired" {
t.Fatalf("result=%+v err=%v", res, err)
}
if !res.CookieSnapshotComplete || res.CookieSnapshot == nil || len(res.CookieSnapshot) != 0 || res.RenewMethod != "auto_login_plugin" {
t.Fatalf("empty authoritative snapshot was downgraded: %+v", res)
}
}
func TestRenewAPIFirstCookie3UsesBackupFlags(t *testing.T) {
useTestDesktopFingerprint(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("skipSessionFilter") != "true" || r.URL.Query().Get("c2r") != "true" || r.URL.Query().Get("ltl") != "" {
t.Fatalf("cookie3 query=%s", r.URL.RawQuery)
}
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":"100"}}}`))
_, _ = w.Write([]byte(`{"content":{"data":{"processFinished":true,"resultCode":100}}}`))
}))
defer srv.Close()
svc := Service{HTTPClient: srv.Client(), SilentHasLoginURL: srv.URL, RetryDelay: -1}
@@ -161,6 +431,7 @@ func TestRenewAPIFirstSkipsFatigueAndExpiredCookies(t *testing.T) {
}
func TestRenewAPIFirstDoesNotRetryOrEscalateFailure(t *testing.T) {
useTestDesktopFingerprint(t)
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls.Add(1)
@@ -201,6 +472,15 @@ func TestMergeSetCookiesAppliesServerDeletion(t *testing.T) {
}
}
func TestMergeSetCookiesMaxAgeOverridesPastExpires(t *testing.T) {
got := MergeSetCookies("session=old", []string{
"session=fresh; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",
})
if !strings.Contains(got, "session=fresh") {
t.Fatalf("positive Max-Age must override past Expires: %q", got)
}
}
func TestRenewBusinessOKMatchesOfficialPlugin(t *testing.T) {
if renewBusinessOK([]byte(`{"content":{"success":true}}`)) {
t.Fatal("official plugin requires processFinished=true and resultCode=100")
+157 -82
View File
@@ -8,10 +8,12 @@ import (
"fmt"
"log/slog"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/coder/websocket"
@@ -45,11 +47,12 @@ 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
sendGate chan struct{}
recorderMu sync.RWMutex
recorder func(direction, rawText, parsedJSON, parseStatus, errMsg string)
readCtx context.Context
readCancel context.CancelFunc
@@ -71,7 +74,16 @@ type incomingFrame struct {
// SetRecorder 设置帧记录器。
func (c *Conn) SetRecorder(rec func(direction, rawText, parsedJSON, parseStatus, errMsg string)) {
c.recorderMu.Lock()
c.recorder = rec
c.recorderMu.Unlock()
}
func (c *Conn) recorderSnapshot() func(direction, rawText, parsedJSON, parseStatus, errMsg string) {
c.recorderMu.RLock()
recorder := c.recorder
c.recorderMu.RUnlock()
return recorder
}
// Dial 保留旧的一步式入口;新账号主循环使用 Open → 获取 token → Register,
@@ -88,8 +100,9 @@ func Dial(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
return conn, nil
}
// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,采用最先
// 成功的连接并关闭冗余连接。此阶段不请求 token,也不发送 /reg。
// Open 按官网 batchConnectWs 策略并行打开最多五条原生 WebSocket,由最先
// settle 的成功或失败决定本轮结果,并关闭迟到连接。此阶段不请求 token,
// 也不发送 /reg。
func Open(ctx context.Context, cfg Config, logger *slog.Logger) (*Conn, error) {
if logger == nil {
logger = slog.Default()
@@ -109,6 +122,7 @@ func websocketHeaders() http.Header {
var (
chromeVersionPattern = regexp.MustCompile(`(?:Chrome|CriOS)/([\d.]+)`)
headlessChromePattern = regexp.MustCompile(`HeadlessChrome/([\d.]+)`)
edgeVersionPattern = regexp.MustCompile(`Edg(?:e|A|iOS)?/([\d.]+)`)
firefoxVersionPattern = regexp.MustCompile(`Firefox/([\d.]+)`)
safariVersionPattern = regexp.MustCompile(`Version/([\d.]+).*Safari`)
@@ -133,6 +147,7 @@ func OfficialRegistrationUA(rawUA string) string {
fmt.Sprintf("OS(%s/%s)", osName, osVersion),
fmt.Sprintf("Browser(%s/%s)", browserName, browserVersion),
"DingWeb/2.2.0",
"IMPaaS",
"DingWeb/2.2.0",
}, " ")
}
@@ -161,7 +176,7 @@ func parseOfficialBrowser(ua string) (string, string) {
for _, candidate := range []struct {
name string
pattern *regexp.Regexp
}{{"Edge", edgeVersionPattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} {
}{{"Edge", edgeVersionPattern}, {"Chrome Headless", headlessChromePattern}, {"Chrome", chromeVersionPattern}, {"Firefox", firefoxVersionPattern}, {"Safari", safariVersionPattern}} {
if match := candidate.pattern.FindStringSubmatch(ua); len(match) == 2 {
return candidate.name, match[1]
}
@@ -175,9 +190,13 @@ type dialResult struct {
}
func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logger) (*Conn, error) {
delays := append([]time.Duration(nil), batchConnectDelays...)
if len(delays) == 0 {
return nil, fmt.Errorf("WS dial: batchConnect 未配置竞速连接")
}
batchCtx, cancel := context.WithCancel(ctx)
results := make(chan dialResult, len(batchConnectDelays))
for _, delay := range batchConnectDelays {
results := make(chan dialResult, len(delays))
for _, delay := range delays {
delay := delay
go func() {
if delay > 0 {
@@ -197,39 +216,39 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
}()
}
var lastErr error
for processed := 1; processed <= len(batchConnectDelays); processed++ {
result := <-results
if result.err != nil {
lastErr = result.err
continue
}
cancel()
// 继续排空结果并关闭稍后成功的冗余连接。
remaining := len(batchConnectDelays) - processed
go func() {
for i := 0; i < remaining; i++ {
result := <-results
if result.conn != nil {
_ = result.conn.CloseNow()
}
// 官网使用 Promise.race:第一条完成的连接无论成功或失败都会决定本轮
// batchConnect 的结果;不会在先收到失败后继续等待其他竞速连接。
result := <-results
go func() {
defer cancel()
for i := 1; i < len(delays); i++ {
late := <-results
if late.conn != nil {
_ = late.conn.CloseNow()
}
}()
result.conn.SetReadLimit(8 << 20)
return newConn(result.conn, cfg, logger), nil
}
}()
if result.err != nil {
if result.conn != nil {
_ = result.conn.CloseNow()
}
return nil, fmt.Errorf("WS dial: %w", result.err)
}
cancel()
if lastErr == nil {
lastErr = context.Canceled
}
return nil, fmt.Errorf("WS dial: %w", lastErr)
result.conn.SetReadLimit(8 << 20)
return newConn(result.conn, cfg, logger), nil
}
func newConn(raw *websocket.Conn, cfg Config, logger *slog.Logger) *Conn {
if logger == nil {
logger = slog.Default()
}
c := &Conn{ws: raw, cfg: cfg, logger: logger, recorder: cfg.Recorder}
c := &Conn{
ws: raw,
cfg: cfg,
logger: logger,
sendGate: make(chan struct{}, 1),
recorder: cfg.Recorder,
}
c.ensureReadPump()
return c
}
@@ -251,11 +270,20 @@ func (c *Conn) ensureReadPump() {
func (c *Conn) Register(ctx context.Context, deviceID, accessToken string) error {
c.ensureReadPump()
c.cfg.DeviceID = deviceID
// 官网 authConnect 在 _auth 前对 MTOP accessToken 执行
// decodeURIComponent。保留原始值供重试,再把解码值写入 /reg。
c.cfg.AccessToken = accessToken
decodedAccessToken, err := url.PathUnescape(accessToken)
if err != nil {
return fmt.Errorf("解码 WebSocket accessToken 失败: %w", err)
}
if !utf8.ValidString(decodedAccessToken) {
return fmt.Errorf("解码 WebSocket accessToken 失败: 非法 UTF-8")
}
response, err := c.request(ctx, "/reg", map[string]any{
"cache-header": "app-key token ua wv",
"app-key": RegAppKey,
"token": accessToken,
"token": decodedAccessToken,
"ua": OfficialRegistrationUA(xianyu.CurrentBrowserFingerprint().UserAgent),
"dt": "j",
"wv": "im:3,au:3,sy:6",
@@ -306,6 +334,13 @@ func responseCode(value any) (int, bool) {
func (c *Conn) request(ctx context.Context, path string, headers map[string]any, body any, timeout time.Duration) (map[string]any, error) {
c.ensureReadPump()
requestCtx := ctx
cancel := func() {}
if timeout > 0 {
requestCtx, cancel = context.WithTimeout(ctx, timeout)
}
defer cancel()
if headers == nil {
headers = make(map[string]any)
}
@@ -329,22 +364,24 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
if body != nil {
frame["body"] = body
}
if err := c.sendJSON(ctx, frame); err != nil {
if err := c.sendJSON(requestCtx, frame); err != nil {
return nil, err
}
waitCtx := ctx
cancel := func() {}
if timeout > 0 {
waitCtx, cancel = context.WithTimeout(ctx, timeout)
}
defer cancel()
select {
case response := <-responseCh:
return response, nil
case <-c.readDone:
// readPump always dispatches a decoded response before it can observe the
// following close. Prefer that already-resolved response over readDone,
// matching browser event ordering (message before close).
select {
case response := <-responseCh:
return response, nil
default:
}
return nil, c.connectionReadError()
case <-waitCtx.Done():
return nil, waitCtx.Err()
case <-requestCtx.Done():
return nil, requestCtx.Err()
}
}
@@ -360,8 +397,8 @@ func (c *Conn) readPump() {
}
var parsed map[string]any
if err := json.Unmarshal(data, &parsed); err != nil {
if c.recorder != nil {
c.recorder("in", string(data), "", "non_json", err.Error())
if recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", string(data), "", "non_json", err.Error())
}
continue
}
@@ -372,6 +409,14 @@ func (c *Conn) readPump() {
continue
}
}
lwp, hasLWP := parsed["lwp"].(string)
_, hasHeaders := parsed["headers"].(map[string]any)
if !hasLWP || strings.TrimSpace(lwp) == "" || !hasHeaders {
if recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", string(data), string(data), "skip_invalid_lwp", "")
}
continue
}
incoming := incomingFrame{messageType: messageType, data: append([]byte(nil), data...), parsed: parsed}
select {
case c.pushes <- incoming:
@@ -386,11 +431,6 @@ func (c *Conn) dispatchResponse(frame map[string]any) bool {
key := midKey(strings.TrimSpace(fmt.Sprint(headers["mid"])))
c.pendingMu.Lock()
ch := c.pending[key]
if ch == nil && key == "" && len(c.pending) == 1 {
for _, only := range c.pending {
ch = only
}
}
c.pendingMu.Unlock()
if ch == nil {
return false
@@ -412,39 +452,47 @@ func (c *Conn) connectionReadError() error {
}
func (c *Conn) recordParsedIncoming(data []byte, parsed map[string]any) {
if c.recorder == nil {
recorder := c.recorderSnapshot()
if recorder == nil {
return
}
parsedJSON := string(data)
if normalized, err := json.Marshal(parsed); err == nil {
parsedJSON = string(normalized)
}
c.recorder("in", string(data), parsedJSON, "json", "")
recorder("in", string(data), parsedJSON, "json", "")
}
// HeartbeatLoop 对齐官网:注册后先等待一个间隔,再发送 /! 并等待同 mid 响应;
// 任一请求失败或 30 秒无响应即结束连接。
// HeartbeatLoop 对齐官网:注册后以固定 15 秒节拍发送 /!,即使上一请求仍在
// 等待也不推迟下一次;任一请求失败或 30 秒无响应即结束连接。官网只以
// Promise 是否 reject 判断心跳,不因已收到的非 200 响应主动断线。
func (c *Conn) HeartbeatLoop(ctx context.Context, interval time.Duration) error {
c.ensureReadPump()
heartbeatCtx, cancel := context.WithCancel(ctx)
defer cancel()
ticker := time.NewTicker(interval)
defer ticker.Stop()
heartbeatErr := make(chan error, 1)
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-heartbeatCtx.Done():
return heartbeatCtx.Err()
case <-c.readDone:
return c.connectionReadError()
case <-ticker.C:
}
response, err := c.request(ctx, "/!", map[string]any{}, nil, heartbeatResponseTimeout)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
case err := <-heartbeatErr:
_ = c.Close()
return fmt.Errorf("心跳响应失败: %w", err)
}
if code, ok := responseCode(response["code"]); ok && code != http.StatusOK {
return fmt.Errorf("心跳响应状态异常: %d", code)
case <-ticker.C:
go func() {
_, err := c.request(heartbeatCtx, "/!", map[string]any{}, nil, heartbeatResponseTimeout)
if err == nil || heartbeatCtx.Err() != nil {
return
}
select {
case heartbeatErr <- err:
default:
}
}()
}
}
}
@@ -459,37 +507,60 @@ func (c *Conn) ReceiveLoop(ctx context.Context, onMessage func(decrypted map[str
case <-ctx.Done():
return ctx.Err()
case <-c.readDone:
return fmt.Errorf("WS read: %w", c.connectionReadError())
// onmessage is delivered before the subsequent onclose in browsers.
// If readPump already queued a final push/control frame, consume it
// before surfacing the close.
select {
case frame = <-c.pushes:
default:
return fmt.Errorf("WS read: %w", c.connectionReadError())
}
case frame = <-c.pushes:
}
raw := frame.parsed
rawText := string(frame.data)
c.sendACK(ctx, raw)
if err := c.handleSyncExtra(ctx, raw); err != nil {
c.logger.Error("同步状态恢复失败", "err", err)
switch strings.TrimSpace(fmt.Sprint(raw["lwp"])) {
case "/push/kickout":
c.readCancel()
_ = c.ws.CloseNow()
return &RegError{Kind: RegErrorAuthentication, Code: http.StatusUnauthorized, Reason: "server kickout"}
case "/s/session/remove":
c.readCancel()
_ = c.ws.CloseNow()
return &RegError{Kind: RegErrorConnectLimit, Code: http.StatusOK, Reason: "session remove"}
}
// 官网异步启动 sync state 恢复,并立即完成当前 Push handler;不能
// 为 getState/ackDiff 最多阻塞 Push ACK 60 秒。
go func(message map[string]any) {
if err := c.handleSyncExtra(c.readCtx, message); err != nil && c.readCtx.Err() == nil {
c.logger.Error("同步状态恢复失败", "err", err)
}
}(raw)
// 仅处理同步包:body.syncPushPackage.data[0].data
syncData, ok := extractSyncPayload(raw)
if !ok {
if c.recorder != nil {
c.recorder("in", rawText, "", "skip_non_sync", "")
c.sendACK(ctx, raw)
if recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", rawText, "", "skip_non_sync", "")
}
continue
}
decoded, err := decodeSyncData(syncData)
if err != nil {
if c.recorder != nil {
c.recorder("in", rawText, "", "decrypt_failed", err.Error())
c.sendACK(ctx, raw)
if recorder := c.recorderSnapshot(); recorder != nil {
recorder("in", rawText, "", "decrypt_failed", err.Error())
}
c.logger.Error("消息解密失败", "err", err)
continue
}
if c.recorder != nil {
if recorder := c.recorderSnapshot(); recorder != nil {
if b, e := json.Marshal(decoded); e == nil {
c.recorder("in", rawText, string(b), "decrypted", "")
recorder("in", rawText, string(b), "decrypted", "")
}
}
c.sendACK(ctx, raw)
if onMessage != nil {
onMessage(decoded)
}
@@ -586,11 +657,15 @@ func (c *Conn) sendJSON(ctx context.Context, v any) error {
if err != nil {
return err
}
if c.recorder != nil {
c.recorder("out", string(b), string(b), "json", "")
if recorder := c.recorderSnapshot(); recorder != nil {
recorder("out", string(b), string(b), "json", "")
}
select {
case c.sendGate <- struct{}{}:
defer func() { <-c.sendGate }()
case <-ctx.Done():
return ctx.Err()
}
c.sendMu.Lock()
defer c.sendMu.Unlock()
return c.ws.Write(ctx, websocket.MessageText, b)
}
+9 -1
View File
@@ -20,7 +20,15 @@ func TestWebsocketHeadersMatchBrowserHandshake(t *testing.T) {
func TestOfficialRegistrationUAUsesRuntimeBrowserVersion(t *testing.T) {
raw := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 Chrome/138.0.7204.92 Safari/537.36"
want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 DingWeb/2.2.0"
want := raw + " DingTalk(2.2.0) OS(Mac OS/10.15.7) Browser(Chrome/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
if got := OfficialRegistrationUA(raw); got != want {
t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
}
}
func TestOfficialRegistrationUARecognizesHeadlessChrome(t *testing.T) {
raw := "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 HeadlessChrome/138.0.7204.92 Safari/537.36"
want := raw + " DingTalk(2.2.0) OS(Linux/other) Browser(Chrome Headless/138.0.7204.92) DingWeb/2.2.0 IMPaaS DingWeb/2.2.0"
if got := OfficialRegistrationUA(raw); got != want {
t.Fatalf("OfficialRegistrationUA() = %q, want %q", got, want)
}
+208 -32
View File
@@ -7,7 +7,9 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
@@ -76,6 +78,88 @@ func dialLocal(t *testing.T, srv *httptest.Server, cfg Config) *Conn {
return newConn(dialed, cfg, nilLogger())
}
// TestOpenBatchRacesDelayedConnections 验证官网 batchConnectWs 会在首条握手
// 迟滞时启动后续连接,并采用最先成功者。
func TestOpenBatchRacesDelayedConnections(t *testing.T) {
originalDelays := batchConnectDelays
batchConnectDelays = []time.Duration{0, 20 * time.Millisecond, 60 * time.Millisecond}
t.Cleanup(func() { batchConnectDelays = originalDelays })
var attempts atomic.Int32
firstAttempt := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempt := attempts.Add(1)
if attempt == 1 {
close(firstAttempt)
<-r.Context().Done()
return
}
c, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true})
if err != nil {
return
}
defer c.CloseNow()
<-r.Context().Done()
}))
t.Cleanup(srv.Close)
type openResult struct {
conn *Conn
err error
}
resultCh := make(chan openResult, 1)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
go func() {
conn, err := openBatch(ctx, wsURL(srv), Config{}, nilLogger())
resultCh <- openResult{conn: conn, err: err}
}()
select {
case <-firstAttempt:
case <-time.After(time.Second):
t.Fatal("WebSocket 首次握手未开始")
}
select {
case result := <-resultCh:
if result.err != nil {
t.Fatalf("openBatch: %v", result.err)
}
t.Cleanup(func() { _ = result.conn.ws.CloseNow() })
case <-time.After(time.Second):
t.Fatal("后续竞速连接未在首条握手阻塞时成功")
}
if got := attempts.Load(); got < 2 {
t.Fatalf("WebSocket 握手次数=%d,期望至少启动 2 条竞速连接", got)
}
}
// TestOpenBatchFirstFailureWins mirrors Promise.race: a fast failed handshake
// rejects the whole batch even when a later candidate could have connected.
func TestOpenBatchFirstFailureWins(t *testing.T) {
originalDelays := batchConnectDelays
batchConnectDelays = []time.Duration{0, 100 * time.Millisecond}
t.Cleanup(func() { batchConnectDelays = originalDelays })
var attempts atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
attempts.Add(1)
http.Error(w, "handshake rejected", http.StatusServiceUnavailable)
}))
t.Cleanup(srv.Close)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
conn, err := openBatch(ctx, wsURL(srv), Config{}, nilLogger())
if err == nil || conn != nil {
t.Fatalf("openBatch conn=%v err=%v,期望首个握手失败直接结束", conn, err)
}
time.Sleep(150 * time.Millisecond)
if got := attempts.Load(); got != 2 {
t.Fatalf("官网延迟任务应继续启动,实际握手 %d 次,期望 2", got)
}
}
// TestRegisterSendsOnlyOfficialReg 验证注册只发送 /reg,不再伪造 ackDiff。
func TestRegisterSendsOnlyOfficialReg(t *testing.T) {
rawUA := "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/138.0.7204.92 Safari/537.36"
@@ -84,7 +168,7 @@ func TestRegisterSendsOnlyOfficialReg(t *testing.T) {
conn := dialLocal(t, srv, Config{
CookieStr: "cookie=1",
DeviceID: "device-xyz",
AccessToken: "token-abc",
AccessToken: "token%2Fabc%2Braw",
})
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
@@ -120,8 +204,8 @@ collect:
if headers["app-key"] != RegAppKey {
t.Errorf("/reg app-key = %v, 期望 %s", headers["app-key"], RegAppKey)
}
if headers["token"] != "token-abc" {
t.Errorf("/reg token = %v, 期望 token-abc", headers["token"])
if headers["token"] != "token/abc+raw" {
t.Errorf("/reg token = %v, 期望 decodeURIComponent 后的 token/abc+raw", headers["token"])
}
if headers["ua"] != OfficialRegistrationUA(rawUA) {
t.Errorf("/reg ua = %v, 期望官方复合 UA", headers["ua"])
@@ -135,6 +219,15 @@ collect:
}
func TestRegisterRejectsDecodeURIComponentInvalidUTF8(t *testing.T) {
srv, _ := startRegServer(t)
conn := dialLocal(t, srv, Config{DeviceID: "did", AccessToken: "%FF"})
err := conn.register(context.Background())
if err == nil || !strings.Contains(err.Error(), "非法 UTF-8") {
t.Fatalf("register error=%v", err)
}
}
// TestRegister_ContextCancelledDuringWait register 等不到响应时应服从 ctx 取消。
func TestRegister_ContextCancelledDuringWait(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -160,6 +253,69 @@ func TestRegister_ContextCancelledDuringWait(t *testing.T) {
}
}
func TestRegisterResponseWinsImmediateClose(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()
_, raw, err := c.Read(r.Context())
if err != nil {
return
}
var request map[string]any
if json.Unmarshal(raw, &request) != nil {
return
}
headers, _ := request["headers"].(map[string]any)
response, _ := json.Marshal(map[string]any{
"code": 200, "headers": map[string]any{"mid": headers["mid"], "reg-uid": "123@goofish"},
})
_ = c.Write(r.Context(), websocket.MessageText, response)
}))
t.Cleanup(srv.Close)
conn := dialLocal(t, srv, Config{DeviceID: "did", AccessToken: "token"})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if err := conn.register(ctx); err != nil {
t.Fatalf("服务端响应后立即断链不应覆盖成功响应: %v", err)
}
}
// TestRequestTimeoutIncludesSendPhase 验证请求超时从等待发送权开始计算,
// 不会因另一条半开连接写入占用发送权而永久阻塞。
func TestRequestTimeoutIncludesSendPhase(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()
<-r.Context().Done()
}))
t.Cleanup(srv.Close)
conn := dialLocal(t, srv, Config{})
conn.sendGate <- struct{}{}
started := time.Now()
_, err := conn.request(context.Background(), "/!", map[string]any{}, nil, 60*time.Millisecond)
elapsed := time.Since(started)
<-conn.sendGate
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("request error=%v,期望 context.DeadlineExceeded", err)
}
if elapsed > 500*time.Millisecond {
t.Fatalf("发送阶段未及时超时,耗时 %v", elapsed)
}
conn.pendingMu.Lock()
pending := len(conn.pending)
conn.pendingMu.Unlock()
if pending != 0 {
t.Fatalf("请求超时后仍残留 %d 个 pending", pending)
}
}
func TestRegisterRejectsInvalidToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
c, err := websocket.Accept(w, r, nil)
@@ -278,6 +434,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
defer c.Close(websocket.StatusNormalClosure, "")
// 发一条带 mid/sid 的非同步消息(无 syncPushPackage),客户端应回 ACK 但不调 onMessage。
frame := map[string]any{
"lwp": "/push/test",
"headers": map[string]any{
"mid": "server-mid-1",
"sid": "server-sid-1",
@@ -305,6 +462,7 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
ackBytes, _ := json.Marshal(map[string]any{"ack": ack})
b64 := base64.StdEncoding.EncodeToString(ackBytes)
echo, _ := json.Marshal(map[string]any{
"lwp": "/s/sync",
"headers": map[string]any{"mid": "echo"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
})
@@ -360,8 +518,8 @@ func TestSendACK_RepliesWithMidSid(t *testing.T) {
}
}
// TestSendACK_NoHeaders 消息无 headers 时 ACK 原样返回空 headers。
func TestSendACK_NoHeaders(t *testing.T) {
// TestReceiveLoop_NoHeadersIsIgnored 官网只把同时包含 lwp/headers 的帧当 Push。
func TestReceiveLoop_NoHeadersIsIgnored(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 {
@@ -373,22 +531,6 @@ func TestSendACK_NoHeaders(t *testing.T) {
_ = c.Write(r.Context(), websocket.MessageText, raw)
ctx, cancel := context.WithTimeout(r.Context(), time.Second)
defer cancel()
_, data, err := c.Read(ctx)
if err != nil {
return
}
var ack map[string]any
if json.Unmarshal(data, &ack) != nil {
return
}
// 回写 echo 带 ack(包成同步推送帧)。
ackBytes, _ := json.Marshal(map[string]any{"ack": ack})
b64 := base64.StdEncoding.EncodeToString(ackBytes)
echo, _ := json.Marshal(map[string]any{
"headers": map[string]any{"mid": "echo"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
})
_ = c.Write(r.Context(), websocket.MessageText, echo)
_, _, _ = c.Read(ctx)
}))
t.Cleanup(srv.Close)
@@ -403,24 +545,58 @@ func TestSendACK_NoHeaders(t *testing.T) {
dialed.SetReadLimit(8 << 20)
conn := newConn(dialed, Config{}, nilLogger())
var ackSeen map[string]any
var called bool
loopDone := make(chan error, 1)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
go func() {
loopDone <- conn.ReceiveLoop(ctx, func(d map[string]any) {
if ack, ok := d["ack"].(map[string]any); ok {
ackSeen = ack
}
})
loopDone <- conn.ReceiveLoop(ctx, func(map[string]any) { called = true })
}()
<-loopDone
if ackSeen == nil {
t.Fatal("未收到 ack")
if called {
t.Fatal("无 headers 的帧不应进入 Push 回调")
}
ackHeaders, _ := ackSeen["headers"].(map[string]any)
if len(ackHeaders) != 0 {
t.Errorf("无 headers 时 ACK 应保持空 headers, 实际 %v", ackHeaders)
}
func TestReceiveLoop_OfficialControlPushesCloseSession(t *testing.T) {
tests := []struct {
name string
lwp string
matchesErr func(error) bool
}{
{name: "kickout", lwp: "/push/kickout", matchesErr: IsAuthenticationError},
{name: "session remove", lwp: "/s/session/remove", matchesErr: IsConnectLimitError},
}
for _, tt := range tests {
t.Run(tt.name, func(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()
frame, _ := json.Marshal(map[string]any{
"lwp": tt.lwp, "headers": map[string]any{"mid": "control-1", "sid": "s1"},
})
_ = c.Write(r.Context(), websocket.MessageText, frame)
// 官网控制 handler 先发起 close,随后 LWP 的 ACK 尝试通常因
// readyState=CLOSING 失败;紧接着断链也不能吞掉控制事件。
}))
defer srv.Close()
dialCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
dialed, _, err := websocket.Dial(dialCtx, wsURL(srv), nil)
if err != nil {
t.Fatal(err)
}
defer dialed.CloseNow()
conn := newConn(dialed, Config{}, nilLogger())
err = conn.ReceiveLoop(dialCtx, nil)
if !tt.matchesErr(err) {
t.Fatalf("ReceiveLoop err=%v", err)
}
})
}
}
+2
View File
@@ -28,6 +28,7 @@ func startWSEchoServer(t *testing.T, payload string) *httptest.Server {
// 构造同步推送帧:body.syncPushPackage.data[0].data = base64(payload)。
b64 := base64.StdEncoding.EncodeToString([]byte(payload))
frame := map[string]any{
"lwp": "/s/sync",
"headers": map[string]any{"mid": "m1", "sid": "s1"},
"body": map[string]any{"syncPushPackage": map[string]any{
"data": []any{map[string]any{"data": b64}},
@@ -100,6 +101,7 @@ func TestReceiveLoop_NonJSONSkipped(t *testing.T) {
c.Write(r.Context(), websocket.MessageText, []byte("not-json"))
b64 := base64.StdEncoding.EncodeToString([]byte(`{"ok":true}`))
frame := map[string]any{
"lwp": "/s/sync",
"headers": map[string]any{"mid": "m2"},
"body": map[string]any{"syncPushPackage": map[string]any{"data": []any{map[string]any{"data": b64}}}},
}