修复登录续期与数据库验证回归

- 修复密码登录、续期和账号编辑链路的边界问题
- 补齐 dbverify、后端与前端单测
- 同步 Docker 与前端构建产物
This commit is contained in:
Christ committed 2026-07-09 16:08:16 +08:00
1 parent 3436acecdc
commit 25419c027f
87 files changed
+7485 -900

No files matched your search

+336 -22
View File
@@ -3,9 +3,21 @@ package browser
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/playwright-community/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
const (
quickRenewPageLoadWait = 3 * time.Second
quickRenewAfterClick = 5 * time.Second
quickRenewTimeoutMS = 30000
quickRenewUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
)
// CookieRenew 用现有 Cookie 打开闲鱼页面,尝试通过“快速进入”刷新浏览器登录态。
@@ -13,47 +25,349 @@ import (
// 这个方法位于密码登录之前:如果 Cookie 仍保留可续期的浏览器会话,页面通常会给出
// 免输密码的快速进入入口。成功点击后提取完整 Cookie,可避免更重的账号密码登录。
func (m *Manager) CookieRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (map[string]string, error) {
if cookieStr == "" {
return nil, fmt.Errorf("Cookie为空,无法浏览器续期")
}
page, release, err := m.newPage(ctx, cookieID, cookieStr, headless)
newCookies, err := m.BrowserQuickRenew(ctx, cookieID, cookieStr, headless)
if err != nil {
return nil, err
}
return cookierefresh.ParseCookieString(newCookies), nil
}
// BrowserQuickRenew 使用持久化浏览器上下文执行“快速进入”Cookie 续期。
func (m *Manager) BrowserQuickRenew(ctx context.Context, cookieID, cookieStr string, headless bool) (string, error) {
if cookieStr == "" {
return "", fmt.Errorf("Cookie为空,无法浏览器续期")
}
bctx, release, err := m.newPersistentRenewContext(ctx, cookieID, cookieStr, nil, quickRenewHeadless(headless))
if err != nil {
return "", err
}
defer release()
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
m.logger.Warn("浏览器续期访问 IM 页面异常", "cookieID", cookieID, "err", err)
page, err := bctx.NewPage()
if err != nil {
return "", fmt.Errorf("新建 page 失败: %w", err)
}
if checkLoginSuccess(page) {
m.logger.Info("浏览器续期:已有有效登录态", "cookieID", cookieID)
return extractPageCookies(page)
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(quickRenewTimeoutMS),
}); err != nil {
m.logger.Warn("浏览器续期访问首页异常", "cookieID", cookieID, "err", err)
}
time.Sleep(quickRenewPageLoadWait)
hasQuickEnter := clickQuickEnter(page)
if hasQuickEnter {
time.Sleep(quickRenewAfterClick)
} else if !checkAlreadyLoggedIn(page) {
return "", fmt.Errorf("未找到[快速进入]按钮且未检测到登录状态,需要账号密码登录")
}
if !clickQuickEnter(page) {
return nil, fmt.Errorf("未找到快速进入入口,需要密码登录")
all, err := bctx.Cookies()
if err != nil {
return "", fmt.Errorf("提取 cookie 失败: %w", err)
}
time.Sleep(5 * time.Second)
if !checkLoginSuccess(page) {
return nil, fmt.Errorf("快速进入后仍未检测到登录态")
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", fmt.Errorf("点击[快速进入]后未获取到浏览器Cookie")
}
m.logger.Info("浏览器续期:快速进入成功", "cookieID", cookieID)
return extractPageCookies(page)
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
}
// CookiesRefreshSnapshot 执行定时 COOKIES 续期:打开首页、刷新页面并返回完整 Cookie 快照。
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快照,无法执行续期")
}
bctx, release, err := m.newEphemeralRefreshContext(ctx, cookieID, cookieStr, snapshot, cookiesRefreshHeadless(headless))
if err != nil {
return "", nil, err
}
defer release()
page, err := bctx.NewPage()
if err != nil {
return "", nil, fmt.Errorf("新建 page 失败: %w", err)
}
defer func() { _ = page.Close() }()
if _, err := page.Goto(goofishHomeURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
m.logger.Warn("COOKIES续期访问首页异常", "cookieID", cookieID, "err", err)
}
time.Sleep(2 * time.Second)
for i := 0; i < 3; i++ {
if _, err := page.Reload(playwright.PageReloadOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(60000),
}); err != nil {
m.logger.Warn("COOKIES续期 reload 异常", "cookieID", cookieID, "attempt", i+1, "err", err)
}
time.Sleep(2 * time.Second)
}
if modal, err := page.QuerySelector(".ant-modal-body"); err == nil && modal != nil {
text, _ := modal.TextContent()
if len(text) > 120 {
text = text[:120]
}
if text != "" {
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败: %s", text)
}
return "", nil, fmt.Errorf("页面存在 ant-modal-body,判定续期失败")
}
all, err := bctx.Cookies()
if err != nil {
return "", nil, fmt.Errorf("提取 cookie 失败: %w", err)
}
newSnapshot := cookieSnapshotFromPlaywright(all)
if len(newSnapshot) == 0 {
return "", nil, fmt.Errorf("页面刷新完成,但未获取到浏览器Cookie")
}
newCookies := cookierefresh.CookieStringFromSnapshot(newSnapshot)
m.logger.Info("COOKIES续期成功", "cookieID", cookieID, "cookie_count", len(newSnapshot))
return newCookies, newSnapshot, nil
}
// 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)
}
func clickQuickEnter(page playwright.Page) bool {
frames := append([]playwright.Frame{page.MainFrame()}, page.Frames()...)
for _, f := range frames {
for _, sel := range loginBtnSelectors {
for _, sel := range quickEnterSelectors {
el, err := f.QuerySelector(sel)
if err == nil && el != nil {
_ = el.Click()
if err == nil && el != nil && elementVisible(el) {
if err := el.Click(); err == nil {
return true
}
}
}
buttons, err := f.QuerySelectorAll("button")
if err != nil {
continue
}
for _, btn := range buttons {
text, _ := btn.TextContent()
if strings.Contains(strings.TrimSpace(text), "快速进入") && elementVisible(btn) {
_ = btn.Click()
return true
}
}
}
return false
}
var quickEnterSelectors = []string{
`button:has-text("快速进入")`,
`button[type="submit"]:has-text("快速进入")`,
`.fm-button:has-text("快速进入")`,
`.fn-button:has-text("快速进入")`,
}
var loggedInSelectors = []string{
"div.nick",
".header-right .nick",
".rc-virtual-list-holder-inner",
`img[src*="img.alicdn.com"][class*="avatar"]`,
`img[src*="img.alicdn.com"][style*="border-radius"]`,
`.header-container img[src*="img.alicdn.com"]`,
"#nc_1_n1z",
".nc-container",
".nc_scale",
`div:has-text("请拖动下方滑块完成验证")`,
`div:has-text("请按住滑块")`,
}
func checkAlreadyLoggedIn(page playwright.Page) bool {
for _, sel := range loggedInSelectors {
el, err := page.QuerySelector(sel)
if err == nil && el != nil && elementVisible(el) {
return true
}
}
bodyText, err := page.TextContent("body")
if err == nil && strings.Contains(bodyText, "消息") && (strings.Contains(bodyText, "订单") || strings.Contains(bodyText, "发闲置")) {
return true
}
return false
}
func elementVisible(el playwright.ElementHandle) bool {
visible, err := el.IsVisible()
return err == nil && visible
}
func cleanSingletonFiles(userDataDir string) {
for _, name := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
_ = os.Remove(filepath.Join(userDataDir, name))
}
}
func (m *Manager) newPersistentRenewContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
lock := m.accountRenewLock(cookieID)
lock.Lock()
unlock := func() { lock.Unlock() }
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
unlock()
return nil, nil, err
}
if err := m.init(); err != nil {
releaseSlot()
unlock()
return nil, nil, err
}
userDataDir := filepath.Join("browser_data", "user_"+pureUserID(cookieID))
cleanSingletonFiles(userDataDir)
var bctx playwright.BrowserContext
var lastErr error
for attempt := 1; attempt <= 2; attempt++ {
bctx, err = m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
UserAgent: playwright.String(quickRenewUA),
Viewport: &playwright.Size{Width: 1280, Height: 720},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
Timeout: playwright.Float(quickRenewTimeoutMS),
})
if err == nil {
break
}
lastErr = err
cleanSingletonFiles(userDataDir)
time.Sleep(time.Second)
}
if bctx == nil {
releaseSlot()
unlock()
return nil, nil, fmt.Errorf("启动持久化浏览器失败: %w", lastErr)
}
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(stealthScript())}); err != nil {
m.logger.Warn("注入 stealth 脚本失败", "err", err)
}
if len(snapshot) > 0 {
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
m.logger.Warn("浏览器续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
}
} else if cookieStr != "" {
if err := addCookieStr(bctx, cookieStr); err != nil {
m.logger.Warn("浏览器续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
}
}
release := func() {
_ = bctx.Close()
releaseSlot()
unlock()
}
return bctx, release, nil
}
func (m *Manager) newEphemeralRefreshContext(ctx context.Context, cookieID, cookieStr string, snapshot []cookierefresh.BrowserCookie, headless bool) (playwright.BrowserContext, func(), error) {
releaseSlot, err := m.acquireRenewSlot(ctx)
if err != nil {
return nil, nil, err
}
if err := m.init(); err != nil {
releaseSlot()
return nil, nil, err
}
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
releaseSlot()
return nil, nil, fmt.Errorf("启动 chromium 失败: %w", err)
}
bctx, err := browser.NewContext(playwright.BrowserNewContextOptions{
UserAgent: playwright.String("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
Viewport: &playwright.Size{Width: 1280, Height: 720},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
})
if err != nil {
_ = browser.Close()
releaseSlot()
return nil, nil, fmt.Errorf("创建 context 失败: %w", err)
}
if err := bctx.AddInitScript(playwright.Script{Content: playwright.String(`Object.defineProperty(navigator, 'webdriver', { get: () => undefined }); Object.defineProperty(navigator, 'languages', { get: () => ['zh-CN', 'zh', 'en'] }); window.chrome = { runtime: {} };`)}); err != nil {
m.logger.Warn("注入 COOKIES 续期 stealth 脚本失败", "cookieID", cookieID, "err", err)
}
if len(snapshot) > 0 {
if err := bctx.AddCookies(snapshotToOptionalCookies(snapshot)); err != nil {
m.logger.Warn("COOKIES续期注入 Cookie 快照失败", "cookieID", cookieID, "err", err)
}
} else if cookieStr != "" {
if err := addCookieStr(bctx, cookieStr); err != nil {
m.logger.Warn("COOKIES续期注入 Cookie 字符串失败", "cookieID", cookieID, "err", err)
}
}
release := func() {
_ = bctx.Close()
_ = browser.Close()
releaseSlot()
}
return bctx, release, nil
}
func quickRenewHeadless(headless bool) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("BROWSER_HEADLESS"))) {
case "true", "1", "yes", "on":
return true
case "false", "0", "no", "off":
return false
default:
return headless
}
}
func cookiesRefreshHeadless(headless bool) bool {
return quickRenewHeadless(headless)
}
func pureUserID(cookieID string) string {
cookieID = sanitize(cookieID)
parts := strings.Split(cookieID, "_")
if len(parts) >= 2 {
last := parts[len(parts)-1]
if len(last) >= 10 && allDigits(last) {
return strings.Join(parts[:len(parts)-1], "_")
}
}
if cookieID == "" {
return "unknown"
}
return cookieID
}
func allDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return true
}
+68 -7
View File
@@ -7,8 +7,12 @@ import (
"time"
"github.com/playwright-community/playwright-go"
"xianyu-go/internal/xianyu/cookierefresh"
)
var cookieDomains = []string{".goofish.com", ".taobao.com", ".alipay.com"}
// parseCookieStr 把 "k=v; k2=v2" 解析为 map。
func parseCookieStr(s string) map[string]string {
m := make(map[string]string)
@@ -35,7 +39,7 @@ func MarshalCookies(m map[string]string) string {
return cookieMarshal(m)
}
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie(domain .goofish.com)。
// parseCookieStrToPlaywright 把 cookie 字符串转成 playwright OptionalCookie。
func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
var cookies []playwright.OptionalCookie
for _, part := range strings.Split(s, ";") {
@@ -46,17 +50,74 @@ func parseCookieStrToPlaywright(s string) []playwright.OptionalCookie {
if name == "" {
continue
}
cookies = append(cookies, playwright.OptionalCookie{
Name: name,
Value: value,
Domain: playwright.String(goofishDot),
Path: playwright.String("/"),
})
for _, domain := range cookieDomains {
cookies = append(cookies, playwright.OptionalCookie{
Name: name,
Value: value,
Domain: playwright.String(domain),
Path: playwright.String("/"),
})
}
}
}
return cookies
}
func snapshotToOptionalCookies(snapshot []cookierefresh.BrowserCookie) []playwright.OptionalCookie {
var out []playwright.OptionalCookie
for _, c := range cookierefresh.NormalizeSnapshot(snapshot) {
domain := c.Domain
if domain == "" {
domain = goofishDot
}
path := c.Path
if path == "" {
path = "/"
}
oc := playwright.OptionalCookie{
Name: c.Name,
Value: c.Value,
Domain: playwright.String(domain),
Path: playwright.String(path),
HttpOnly: playwright.Bool(c.HTTPOnly),
Secure: playwright.Bool(c.Secure),
}
if c.Expires > 0 {
oc.Expires = playwright.Float(c.Expires)
}
switch c.SameSite {
case "Strict":
oc.SameSite = playwright.SameSiteAttributeStrict
case "Lax":
oc.SameSite = playwright.SameSiteAttributeLax
case "None":
oc.SameSite = playwright.SameSiteAttributeNone
}
out = append(out, oc)
}
return out
}
func cookieSnapshotFromPlaywright(cs []playwright.Cookie) []cookierefresh.BrowserCookie {
out := make([]cookierefresh.BrowserCookie, 0, len(cs))
for _, c := range cs {
bc := cookierefresh.BrowserCookie{
Name: c.Name,
Value: c.Value,
Domain: c.Domain,
Path: c.Path,
Expires: c.Expires,
HTTPOnly: c.HttpOnly,
Secure: c.Secure,
}
if c.SameSite != nil {
bc.SameSite = string(*c.SameSite)
}
out = append(out, bc)
}
return cookierefresh.NormalizeSnapshot(out)
}
// cookiesToMap 把 playwright Cookie 切片转成 map。
func cookiesToMap(cs []playwright.Cookie) map[string]string {
m := make(map[string]string, len(cs))
+11 -4
View File
@@ -22,17 +22,24 @@ func TestParseCookieStrRoundTrip(t *testing.T) {
func TestParseCookieStrToPlaywright(t *testing.T) {
cookies := parseCookieStrToPlaywright("a=1; b=2")
if len(cookies) != 2 {
t.Fatalf("应解析 2 个 cookie,got %d", len(cookies))
if len(cookies) != 2*len(cookieDomains) {
t.Fatalf("应按多个域名注入 cookie,got %d", len(cookies))
}
domains := make(map[string]bool)
for _, c := range cookies {
if c.Domain == nil || *c.Domain != goofishDot {
t.Fatalf("domain 应为 %s: %+v", goofishDot, c.Domain)
if c.Domain == nil {
t.Fatalf("domain 不能为空: %+v", c.Domain)
}
domains[*c.Domain] = true
if c.Path == nil || *c.Path != "/" {
t.Fatalf("path 应为 /: %+v", c.Path)
}
}
for _, domain := range cookieDomains {
if !domains[domain] {
t.Fatalf("缺少 domain %s: %+v", domain, domains)
}
}
}
func TestParseCookieStrEmpty(t *testing.T) {
+71 -15
View File
@@ -7,6 +7,8 @@ import (
"errors"
"fmt"
"log/slog"
"os"
"strings"
"sync"
"time"
@@ -18,13 +20,14 @@ import (
// 默认 UA、语言、时区与视口。
const (
defaultUA = xianyu.BrowserUA
defaultW = 1920
defaultH = 1080
defaultLang = "zh-CN"
defaultTZ = "Asia/Shanghai"
goofishDot = ".goofish.com"
goofishIMURL = "https://www.goofish.com/im"
defaultUA = xianyu.BrowserUA
defaultW = 1920
defaultH = 1080
defaultLang = "zh-CN"
defaultTZ = "Asia/Shanghai"
goofishDot = ".goofish.com"
goofishHomeURL = "https://www.goofish.com/"
goofishIMURL = "https://www.goofish.com/im"
)
// chromiumLaunchArgs 统一 Chromium 启动参数。
@@ -52,6 +55,22 @@ func chromiumLaunchArgs() []string {
}
}
func chromiumExecutablePath() *string {
if path := strings.TrimSpace(os.Getenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH")); path != "" {
return playwright.String(path)
}
return nil
}
func skipPlaywrightBrowserDownload() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD"))) {
case "1", "true", "yes", "on":
return true
default:
return false
}
}
// Manager 管理浏览器生命周期与按账号复用的上下文池。
type Manager struct {
pw *playwright.Playwright
@@ -67,6 +86,10 @@ type Manager struct {
idleTTL time.Duration
creates singleflight.Group
renewMu sync.Mutex
renewLocks map[string]*sync.Mutex
renewSlots chan struct{}
// 允许测试注入自定义 playwright / 安装函数。
installFn func() error
runFn func() (*playwright.Playwright, error)
@@ -85,15 +108,21 @@ func NewManager(logger *slog.Logger) *Manager {
logger = slog.Default()
}
return &Manager{
logger: logger,
pool: make(map[string]*poolEntry),
maxSize: 3,
idleTTL: 5 * time.Minute,
logger: logger,
pool: make(map[string]*poolEntry),
maxSize: 3,
idleTTL: 5 * time.Minute,
renewLocks: make(map[string]*sync.Mutex),
renewSlots: make(chan struct{}, 3),
installFn: func() error {
return playwright.Install(&playwright.RunOptions{
opts := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: false,
})
}
if skipPlaywrightBrowserDownload() {
opts.SkipInstallBrowsers = true
}
return playwright.Install(opts)
},
runFn: func() (*playwright.Playwright, error) {
return playwright.Run()
@@ -101,6 +130,32 @@ func NewManager(logger *slog.Logger) *Manager {
}
}
func (m *Manager) accountRenewLock(cookieID string) *sync.Mutex {
m.renewMu.Lock()
defer m.renewMu.Unlock()
if m.renewLocks == nil {
m.renewLocks = make(map[string]*sync.Mutex)
}
lock := m.renewLocks[cookieID]
if lock == nil {
lock = &sync.Mutex{}
m.renewLocks[cookieID] = lock
}
return lock
}
func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
if m.renewSlots == nil {
m.renewSlots = make(chan struct{}, 3)
}
select {
case m.renewSlots <- struct{}{}:
return func() { <-m.renewSlots }, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
// init 懒加载 playwright(首次调用时下载 driver + chromium)。
func (m *Manager) init() error {
m.once.Do(func() {
@@ -202,8 +257,9 @@ func (m *Manager) acquireEntry(cookieID, cookieStr string, headless bool) (*pool
func (m *Manager) createEntry(cookieID, cookieStr string, headless bool) (*poolEntry, error) {
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
return nil, fmt.Errorf("启动 chromium 失败: %w", err)
+202 -24
View File
@@ -2,6 +2,7 @@ package browser
import (
"context"
"encoding/base64"
"fmt"
"path/filepath"
"strings"
@@ -26,10 +27,24 @@ var loginSuccessSelectors = []string{
".rc-virtual-list-holder-inner", // IM 页面侧边栏有子元素则已登录
}
const (
passwordVerificationWaitInterval = 10 * time.Second
passwordVerificationMaxWait = 5 * time.Minute
)
// PasswordLogin 用账号密码通过浏览器登录闲鱼,返回完整 cookie map。
// 移植自 xianyu_slider_stealth.login_with_password_playwright。
// userDataDir:空字符串用临时目录,非空则持久化(跨次复用 session)。
func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool) (map[string]string, error) {
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, nil)
}
// PasswordLoginWithEvents 在密码登录过程中上报中间状态。
func (m *Manager) PasswordLoginWithEvents(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
return m.passwordLogin(ctx, account, password, cookieID, userDataDir, headless, onEvent)
}
func (m *Manager) passwordLogin(ctx context.Context, account, password, cookieID, userDataDir string, headless bool, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if err := m.init(); err != nil {
return nil, err
}
@@ -37,14 +52,16 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
if userDataDir == "" {
userDataDir = filepath.Join("browser_data", "user_"+sanitize(cookieID))
}
headless = quickRenewHeadless(headless)
bctx, err := m.pw.Chromium.LaunchPersistentContext(userDataDir, playwright.BrowserTypeLaunchPersistentContextOptions{
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
UserAgent: playwright.String(defaultUA),
Viewport: &playwright.Size{Width: 1980, Height: 1024},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
Headless: playwright.Bool(headless),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
UserAgent: playwright.String(defaultUA),
Viewport: &playwright.Size{Width: 1980, Height: 1024},
Locale: playwright.String(defaultLang),
TimezoneId: playwright.String(defaultTZ),
})
if err != nil {
return nil, fmt.Errorf("启动持久化浏览器失败: %w", err)
@@ -73,11 +90,32 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
return extractPageCookies(page)
}
if clickQuickEnter(page) {
m.logger.Info("密码登录:已点击[快速进入],等待页面刷新", "cookieID", cookieID)
time.Sleep(quickRenewAfterClick)
cookies, err := extractPageCookies(page)
if err == nil && quickEnterCookiesUsable(cookies) {
m.logger.Info("密码登录:快速进入成功,跳过账号密码输入", "cookieID", cookieID)
return cookies, nil
}
m.logger.Info("密码登录:快速进入未获取到有效 Cookie,继续账号密码登录", "cookieID", cookieID)
if _, err := page.Goto(goofishIMURL, playwright.PageGotoOptions{
WaitUntil: playwright.WaitUntilStateDomcontentloaded,
Timeout: playwright.Float(30000),
}); err != nil {
m.logger.Warn("密码登录:快速进入失败后重新访问 IM 页面异常", "cookieID", cookieID, "err", err)
}
time.Sleep(2 * time.Second)
}
// 在主页和所有 iframe 中找登录表单。
idEl, pwdEl, submitEl := findLoginForm(page)
if idEl == nil {
return nil, fmt.Errorf("未找到登录表单,可能页面结构已变更")
}
if pwdEl == nil {
return nil, fmt.Errorf("未找到密码输入框,可能页面结构已变更")
}
if err := idEl.Click(); err == nil {
_ = page.Fill(getCSSSelector(idEl, loginIDSelectors), account)
@@ -108,30 +146,170 @@ func (m *Manager) PasswordLogin(ctx context.Context, account, password, cookieID
}
if !checkLoginSuccess(page) {
// 采集错误信息。
errMsg := ""
if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
errMsg, _ = el.TextContent()
}
if errMsg == "" {
c, _ := page.Content()
for _, kw := range []string{"账密错误", "账号密码错误", "用户名或密码错误", "密码错误"} {
if strings.Contains(c, kw) {
errMsg = kw
break
}
}
}
if errMsg == "" {
errMsg = "登录失败"
}
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
return m.handlePasswordLoginPending(ctx, page, onEvent)
}
m.logger.Info("密码登录成功", "cookieID", cookieID)
return extractPageCookies(page)
}
func quickEnterCookiesUsable(cookies map[string]string) bool {
if len(cookies) == 0 {
return false
}
return strings.TrimSpace(cookies["unb"]) != ""
}
func (m *Manager) handlePasswordLoginPending(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
if msg := passwordLoginErrorFromPage(page); msg != "" {
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(msg))
}
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok {
if onEvent != nil {
onEvent(event)
}
cookies, err := waitPasswordVerification(ctx, page, onEvent)
if err == nil {
m.logger.Info("密码登录人工验证完成")
return cookies, nil
}
return nil, err
}
errMsg := "登录失败"
if onEvent != nil {
onEvent(PasswordLoginEventFromMessage(errMsg))
}
return nil, fmt.Errorf("密码登录失败: %s", errMsg)
}
func waitPasswordVerification(ctx context.Context, page playwright.Page, onEvent PasswordLoginEventHandler) (map[string]string, error) {
ticker := time.NewTicker(passwordVerificationWaitInterval)
defer ticker.Stop()
timer := time.NewTimer(passwordVerificationMaxWait)
defer timer.Stop()
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-timer.C:
return nil, fmt.Errorf("密码登录失败: 人工验证超时")
case <-ticker.C:
}
if checkLoginSuccess(page) {
return extractPageCookies(page)
}
if msg := passwordLoginErrorFromPage(page); msg != "" {
return nil, fmt.Errorf("密码登录失败: %s", msg)
}
if event, ok := passwordBaxiaEventFromPage(page); ok {
return nil, fmt.Errorf("密码登录失败: %s", event.Message)
}
if event, ok := passwordVerificationEventFromPage(page); ok && onEvent != nil {
onEvent(event)
}
}
}
func passwordLoginErrorFromPage(page playwright.Page) string {
if el, err := page.QuerySelector(".login-error-msg"); err == nil && el != nil {
if msg, _ := el.TextContent(); strings.TrimSpace(msg) != "" {
return strings.TrimSpace(msg)
}
}
for _, htmlText := range passwordLoginHTMLs(page) {
if msg := detectPasswordLoginErrorHTML(htmlText); msg != "" {
return msg
}
}
return ""
}
func passwordBaxiaEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
for _, htmlText := range passwordLoginHTMLs(page) {
if event, ok := detectPasswordBaxiaPunishHTML(htmlText); ok {
return event, true
}
}
return PasswordLoginEvent{}, false
}
func passwordVerificationEventFromPage(page playwright.Page) (PasswordLoginEvent, bool) {
if event, ok := passwordVerificationEventFromContent(pageContent(page), page.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
for _, frame := range page.Frames() {
if event, ok := passwordVerificationEventFromContent(frameContent(frame), frame.URL()); ok {
event.ScreenshotPath = firstNonEmptyString(event.ScreenshotPath, passwordVerificationScreenshot(page))
return event, true
}
}
return PasswordLoginEvent{}, false
}
func passwordVerificationEventFromContent(htmlText, frameURL string) (PasswordLoginEvent, bool) {
event, ok := detectPasswordVerificationHTML(htmlText)
if !ok {
return PasswordLoginEvent{}, false
}
if event.VerificationURL == "" && looksLikeVerificationURL(frameURL) {
event.VerificationURL = frameURL
}
return event, true
}
func passwordLoginHTMLs(page playwright.Page) []string {
htmls := []string{pageContent(page)}
for _, frame := range page.Frames() {
htmls = append(htmls, frameContent(frame))
}
return htmls
}
func pageContent(page playwright.Page) string {
content, _ := page.Content()
return content
}
func frameContent(frame playwright.Frame) string {
content, _ := frame.Content()
return content
}
func passwordVerificationScreenshot(page playwright.Page) string {
raw, err := page.Screenshot(playwright.PageScreenshotOptions{
FullPage: playwright.Bool(true),
Timeout: playwright.Float(5000),
})
if err != nil || len(raw) == 0 {
return ""
}
return "data:image/png;base64," + base64.StdEncoding.EncodeToString(raw)
}
func looksLikeVerificationURL(raw string) bool {
lower := strings.ToLower(raw)
return containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode")
}
func firstNonEmptyString(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func checkLoginSuccess(page playwright.Page) bool {
for _, sel := range loginSuccessSelectors {
el, err := page.QuerySelector(sel)
+103
View File
@@ -0,0 +1,103 @@
package browser
import (
"html"
"regexp"
"strings"
)
var (
htmlTagPattern = regexp.MustCompile(`(?is)<[^>]+>`)
scriptStylePattern = regexp.MustCompile(`(?is)<script[^>]*>.*?</script>|<style[^>]*>.*?</style>`)
verificationURLRe = regexp.MustCompile(`https?://[^\s"'<>\\]+`)
dataImageURLRe = regexp.MustCompile(`data:image/[^;"'\s<>]+;base64,[A-Za-z0-9+/=]+`)
escapedSlashPattern = strings.NewReplacer(`\/`, `/`, `\u0026`, `&`)
)
func detectPasswordBaxiaPunishHTML(htmlText string) (PasswordLoginEvent, bool) {
if !IsBaxiaPunishMessage(htmlText) {
return PasswordLoginEvent{}, false
}
msg := "触发闲鱼风控图形验证(baxia-punish),账号正常但暂时无法自动登录"
return PasswordLoginEvent{
Status: PasswordLoginStatusFailed,
Message: msg,
Error: msg,
Reason: "baxia_punish_captcha",
CooldownHours: 5,
}, true
}
func detectPasswordLoginErrorHTML(htmlText string) string {
text := normalizeHTMLText(htmlText)
for _, keyword := range []string{
"账密错误", "账号密码错误", "用户名或密码错误", "账号或密码错误", "密码错误",
"账号不存在", "账号已被冻结", "账号被冻结", "账户被冻结", "账号已锁定", "账户已锁定",
"操作过于频繁", "登录过于频繁", "暂时无法登录",
} {
if strings.Contains(text, keyword) {
return keyword
}
}
return ""
}
func detectPasswordVerificationHTML(htmlText string) (PasswordLoginEvent, bool) {
normalized := normalizeHTMLText(htmlText)
lower := strings.ToLower(htmlText)
if !containsAny(normalized,
"人脸验证", "人脸识别", "身份验证", "安全验证", "扫码验证", "验证二维码",
"请使用手机", "请在手机", "请在浏览器中完成验证",
) && !containsAny(lower,
"alibaba-login-box", "iframe_redirect", "iframeredirect", "photoverify", "iv/photoverify",
"verifyurl", "identity_verify", "normal_validate", "verifycode", "qrcode",
) {
return PasswordLoginEvent{}, false
}
msg := "密码登录需要人工验证,请在浏览器中完成验证后等待自动继续"
event := PasswordLoginEvent{
Status: PasswordLoginStatusVerificationRequired,
Message: msg,
Error: msg,
VerificationURL: extractPasswordVerificationURL(htmlText),
QRCodeURL: extractPasswordQRURL(htmlText),
}
return event, true
}
func extractPasswordVerificationURL(htmlText string) string {
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
matches := verificationURLRe.FindAllString(cleaned, -1)
for _, raw := range matches {
url := strings.TrimRight(raw, ".,);]")
lower := strings.ToLower(url)
if containsAny(lower, "passport", "verify", "photo", "iv/", "identity", "login", "qrcode") {
return url
}
}
return ""
}
func extractPasswordQRURL(htmlText string) string {
cleaned := escapedSlashPattern.Replace(html.UnescapeString(htmlText))
if match := dataImageURLRe.FindString(cleaned); match != "" {
return match
}
return ""
}
func normalizeHTMLText(htmlText string) string {
cleaned := scriptStylePattern.ReplaceAllString(htmlText, " ")
cleaned = htmlTagPattern.ReplaceAllString(cleaned, " ")
cleaned = escapedSlashPattern.Replace(html.UnescapeString(cleaned))
return strings.Join(strings.Fields(cleaned), " ")
}
func containsAny(s string, keywords ...string) bool {
for _, keyword := range keywords {
if strings.Contains(s, keyword) {
return true
}
}
return false
}
@@ -0,0 +1,61 @@
package browser
import "testing"
func TestDetectPasswordBaxiaPunishHTML(t *testing.T) {
html := `<div id="baxia-punish"><div class="captcha-question">请找两个松鼠</div></div>`
event, ok := detectPasswordBaxiaPunishHTML(html)
if !ok {
t.Fatal("应识别 baxia 图形验证")
}
if event.Status != PasswordLoginStatusFailed || event.Reason != "baxia_punish_captcha" || event.CooldownHours != 5 {
t.Fatalf("baxia 事件异常: %+v", event)
}
}
func TestPasswordEventFromMessageDoesNotTreatFaceRiskAsBaxia(t *testing.T) {
event := PasswordLoginEventFromMessage("账号触发风控,需要人脸验证")
if event.Reason == "baxia_punish_captcha" {
t.Fatalf("普通人脸验证不应按 baxia 冷却: %+v", event)
}
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("人脸验证应标记 verification_required: %+v", event)
}
}
func TestDetectPasswordLoginErrorHTML(t *testing.T) {
msg := detectPasswordLoginErrorHTML(`<div class="login-error-msg">账号或密码错误</div>`)
if msg != "账号或密码错误" {
t.Fatalf("登录错误识别=%q", msg)
}
msg = detectPasswordLoginErrorHTML(`<span>账号已被冻结,请联系平台</span>`)
if msg != "账号已被冻结" {
t.Fatalf("冻结错误识别=%q", msg)
}
}
func TestDetectPasswordVerificationHTML(t *testing.T) {
html := `<iframe id="alibaba-login-box" src="https:\/\/passport.goofish.com\/iv\/photoVerify\/index.htm?token=abc"></iframe><div>需要人脸验证,请使用手机扫码</div>`
event, ok := detectPasswordVerificationHTML(html)
if !ok {
t.Fatal("应识别人脸验证")
}
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("验证状态异常: %+v", event)
}
if event.VerificationURL != "https://passport.goofish.com/iv/photoVerify/index.htm?token=abc" {
t.Fatalf("验证 URL 提取异常: %q", event.VerificationURL)
}
}
func TestQuickEnterCookiesUsableRequiresUNB(t *testing.T) {
if quickEnterCookiesUsable(map[string]string{"_m_h5_tk": "tk"}) {
t.Fatal("快速进入未拿到 unb 不应视为成功")
}
if !quickEnterCookiesUsable(map[string]string{"unb": " 123 "}) {
t.Fatal("快速进入拿到 unb 应视为成功")
}
if quickEnterCookiesUsable(nil) {
t.Fatal("空 Cookie 不应视为成功")
}
}
+54
View File
@@ -0,0 +1,54 @@
package browser
import "strings"
const (
PasswordLoginStatusProcessing = "processing"
PasswordLoginStatusVerificationRequired = "verification_required"
PasswordLoginStatusFailed = "failed"
)
// PasswordLoginEvent 描述密码登录过程中的中间状态,供 HTTP 会话轮询接口展示。
type PasswordLoginEvent struct {
Status string
Message string
Error string
Reason string
VerificationURL string
ScreenshotPath string
QRCodeURL string
CooldownHours int
}
type PasswordLoginEventHandler func(PasswordLoginEvent)
func PasswordLoginEventFromError(err error) PasswordLoginEvent {
if err == nil {
return PasswordLoginEvent{}
}
return PasswordLoginEventFromMessage(err.Error())
}
func PasswordLoginEventFromMessage(msg string) PasswordLoginEvent {
lower := strings.ToLower(msg)
event := PasswordLoginEvent{Status: PasswordLoginStatusFailed, Message: msg, Error: msg}
switch {
case IsBaxiaPunishMessage(msg) || (strings.Contains(msg, "风控") && strings.Contains(msg, "图形验证")):
event.Reason = "baxia_punish_captcha"
event.CooldownHours = 5
case strings.Contains(msg, "人脸") || strings.Contains(lower, "verification") || strings.Contains(lower, "captcha"):
event.Status = PasswordLoginStatusVerificationRequired
}
return event
}
func IsBaxiaPunishMessage(msg string) bool {
lower := strings.ToLower(msg)
return strings.Contains(lower, "baxia") ||
strings.Contains(lower, "punish") ||
strings.Contains(lower, "scratch-captcha") ||
strings.Contains(lower, "captcha-question") ||
strings.Contains(lower, "scratch-captcha-container") ||
strings.Contains(msg, "找两个") ||
strings.Contains(msg, "松鼠")
}
@@ -0,0 +1,37 @@
package browser
import (
"errors"
"testing"
)
func TestPasswordLoginEventFromErrorVerification(t *testing.T) {
event := PasswordLoginEventFromError(errors.New("需要人脸验证"))
if event.Status != PasswordLoginStatusVerificationRequired {
t.Fatalf("status=%q want verification_required", event.Status)
}
}
func TestPasswordLoginEventFromErrorBaxia(t *testing.T) {
event := PasswordLoginEventFromError(errors.New("baxia-punish verification 风控图形验证"))
if event.Status != PasswordLoginStatusFailed || event.Reason != "baxia_punish_captcha" || event.CooldownHours != 5 {
t.Fatalf("event=%+v", event)
}
}
func TestIsBaxiaPunishMessage(t *testing.T) {
for _, msg := range []string{"baxia-punish", "scratch-captcha-container", "找两个松鼠"} {
if !IsBaxiaPunishMessage(msg) {
t.Fatalf("%q should be recognized as baxia punish", msg)
}
}
if PasswordLoginEventFromMessage("触发风控图形验证").Reason != "baxia_punish_captcha" {
t.Fatal("明确的风控图形验证应按 baxia 冷却")
}
if IsBaxiaPunishMessage("用户名或密码错误") {
t.Fatal("ordinary password error should not be recognized as baxia")
}
if IsBaxiaPunishMessage("触发风控,需要人脸验证") {
t.Fatal("ordinary face verification should not be recognized as baxia")
}
}
+80 -8
View File
@@ -1,16 +1,14 @@
package browser
import (
"testing"
)
import "testing"
// TestSanitize 特殊字符替换为下划线(用于 userDataDir 命名)。
func TestSanitize(t *testing.T) {
cases := map[string]string{
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
"acc_1": "acc_1",
"acc/1:2 3": "acc_1_2_3",
`a\b:c d`: "a_b_c_d",
"": "",
}
for in, want := range cases {
if got := sanitize(in); got != want {
@@ -31,6 +29,81 @@ func TestGetCSSSelector(t *testing.T) {
}
}
func TestPureUserIDMatchesReferenceRule(t *testing.T) {
cases := map[string]string{
"foo_1234567890": "foo",
"foo_bar_1234567890": "foo_bar",
"foo_123": "foo_123",
"foo": "foo",
"": "unknown",
"foo/bar_1234567890": "foo_bar",
}
for in, want := range cases {
if got := pureUserID(in); got != want {
t.Fatalf("pureUserID(%q)=%q want %q", in, got, want)
}
}
}
func TestQuickRenewHeadlessUsesArgumentUnlessEnvOverrides(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !quickRenewHeadless(true) {
t.Fatal("未设置环境变量时应使用传入的 headless=true")
}
if quickRenewHeadless(false) {
t.Fatal("未设置环境变量时应使用传入的 headless=false")
}
t.Setenv("BROWSER_HEADLESS", "true")
if !quickRenewHeadless(false) {
t.Fatal("BROWSER_HEADLESS=true 时应使用 headless")
}
t.Setenv("BROWSER_HEADLESS", "false")
if quickRenewHeadless(true) {
t.Fatal("BROWSER_HEADLESS=false 时应使用可视化浏览器")
}
}
func TestCookiesRefreshHeadlessUsesAccountPreference(t *testing.T) {
t.Setenv("BROWSER_HEADLESS", "")
if !cookiesRefreshHeadless(true) {
t.Fatal("定时 COOKIES 续期应尊重 headless=true")
}
if cookiesRefreshHeadless(false) {
t.Fatal("show_browser=true 时定时 COOKIES 续期应使用可视化浏览器")
}
t.Setenv("BROWSER_HEADLESS", "true")
if !cookiesRefreshHeadless(false) {
t.Fatal("环境变量应仍可强制定时 COOKIES 续期 headless")
}
}
func TestChromiumExecutablePathFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", "")
if chromiumExecutablePath() != nil {
t.Fatal("未设置 PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH 时应返回 nil")
}
t.Setenv("PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH", " /usr/bin/chromium ")
got := chromiumExecutablePath()
if got == nil || *got != "/usr/bin/chromium" {
t.Fatalf("chromiumExecutablePath=%v", got)
}
}
func TestSkipPlaywrightBrowserDownloadFromEnv(t *testing.T) {
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "")
if skipPlaywrightBrowserDownload() {
t.Fatal("默认不应跳过浏览器下载")
}
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "true")
if !skipPlaywrightBrowserDownload() {
t.Fatal("true 应跳过浏览器下载")
}
t.Setenv("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "0")
if skipPlaywrightBrowserDownload() {
t.Fatal("0 不应跳过浏览器下载")
}
}
// TestCalculateSlideDistance_Fallback nil 轨道/按钮时走兜底距离。
func TestCalculateSlideDistance_Fallback(t *testing.T) {
// 无 scratch:220-259。
@@ -44,4 +117,3 @@ func TestCalculateSlideDistance_Fallback(t *testing.T) {
t.Fatalf("scratch 兜底应 55-91,got %v err=%v", dist, err)
}
}
+3 -2
View File
@@ -26,8 +26,9 @@ func (m *Manager) QRCookieRefresh(ctx context.Context, tmpCookies, verificationU
// QR 刷新不复用账号池:一次性上下文,注入临时 cookie,访问后提取。
browser, err := m.pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(true),
Args: chromiumLaunchArgs(),
Headless: playwright.Bool(true),
Args: chromiumLaunchArgs(),
ExecutablePath: chromiumExecutablePath(),
})
if err != nil {
return "", "", fmt.Errorf("启动 chromium 失败: %w", err)