修复 token 与 Cookie 绑定并完善认证恢复

This commit is contained in:
Christ committed 2026-07-15 09:03:20 +08:00
1 parent 16d63dc7c9
commit 3cc1d4094d
30 files changed
+990 -998

No files matched your search

-4
View File
@@ -237,10 +237,6 @@ var quickEnterSelectors = []string{
`.fn-button:has-text("快速进入")`,
}
func checkAlreadyLoggedIn(page playwright.Page) bool {
return verifyHomeLoginState(page) == nil
}
func verifyHomeLoginState(page playwright.Page) error {
if pageHasSecurityVerification(page) {
return ErrSecurityVerification
+53 -5
View File
@@ -23,16 +23,21 @@ func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowser
if unb == "" {
return nil, fmt.Errorf("浏览器 token 请求缺少 unb")
}
bctx, release, err := m.newPersistentRenewContext(ctx, unb, req.Cookies, nil, true, true)
credentialID := "token_credential_" + unb
lock := m.accountRenewLock(credentialID)
lock.Lock()
defer lock.Unlock()
page, release, err := m.newPage(ctx, credentialID, req.Cookies, true)
if err != nil {
return nil, err
}
defer release()
page, err := bctx.NewPage()
if err != nil {
return nil, fmt.Errorf("浏览器 token 请求新建页面: %w", err)
bctx := page.Context()
if err := syncCredentialCookies(bctx, req.Cookies); err != nil {
m.evict(credentialID)
return nil, fmt.Errorf("浏览器 token 请求同步 Cookie: %w", err)
}
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(15000),
@@ -76,3 +81,46 @@ func (m *Manager) ExecuteTokenRequest(ctx context.Context, req mtop.TokenBrowser
UpdatedCookies: cookierefresh.MergeOriginalFields(req.Cookies, browserCookies),
}, nil
}
// syncCredentialCookies updates a reused credential context without flattening
// attributes already observed from Chromium. Unknown cookies use the narrow
// goofish default only on their first import; later server updates retain their
// real domain, path, expiry, SameSite, Secure and HttpOnly fields.
func syncCredentialCookies(bctx playwright.BrowserContext, cookieStr string) error {
incoming := parseCookieStr(cookieStr)
if len(incoming) == 0 {
return fmt.Errorf("Cookie为空或格式错误")
}
existing, err := bctx.Cookies()
if err != nil {
return err
}
preserved := credentialCookieSnapshot(cookieSnapshotFromPlaywright(existing), incoming)
if err := bctx.ClearCookies(); err != nil {
return err
}
return bctx.AddCookies(snapshotToOptionalCookies(preserved))
}
func credentialCookieSnapshot(existing []cookierefresh.BrowserCookie, incoming map[string]string) []cookierefresh.BrowserCookie {
preserved := make([]cookierefresh.BrowserCookie, 0, len(incoming))
matched := make(map[string]bool, len(incoming))
for _, cookie := range existing {
value, ok := incoming[cookie.Name]
if !ok {
continue
}
cookie.Value = value
preserved = append(preserved, cookie)
matched[cookie.Name] = true
}
for name, value := range incoming {
if matched[name] {
continue
}
preserved = append(preserved, cookierefresh.BrowserCookie{
Name: name, Value: value, Domain: goofishDot, Path: "/",
})
}
return cookierefresh.NormalizeSnapshot(preserved)
}
+32
View File
@@ -0,0 +1,32 @@
package browser
import (
"testing"
"xianyu-go/internal/xianyu/cookierefresh"
)
func TestCredentialCookieSnapshotPreservesChromiumAttributes(t *testing.T) {
existing := []cookierefresh.BrowserCookie{
{Name: "cookie2", Value: "old", Domain: ".taobao.com", Path: "/", Expires: 12345, HTTPOnly: true, Secure: true, SameSite: "None"},
{Name: "stale", Value: "remove", Domain: ".goofish.com", Path: "/"},
}
got := credentialCookieSnapshot(existing, map[string]string{"cookie2": "new", "unb": "1"})
if len(got) != 2 {
t.Fatalf("snapshot length=%d want=2: %+v", len(got), got)
}
byName := map[string]cookierefresh.BrowserCookie{}
for _, cookie := range got {
byName[cookie.Name] = cookie
}
cookie2 := byName["cookie2"]
if cookie2.Value != "new" || cookie2.Domain != ".taobao.com" || cookie2.Expires != 12345 || !cookie2.HTTPOnly || !cookie2.Secure || cookie2.SameSite != "None" {
t.Fatalf("preserved cookie=%+v", cookie2)
}
if unb := byName["unb"]; unb.Domain != goofishDot || unb.Path != "/" {
t.Fatalf("new cookie defaults=%+v", unb)
}
if _, ok := byName["stale"]; ok {
t.Fatal("cookie absent from current snapshot must be removed")
}
}