完善服务端交互日志与初始化测试

统一划分 MTOP 与 WebSocket 日志等级,增加 Token 安全指纹和请求耗时诊断;补充 init-admin 临时数据库测试;同步 README 的镜像发布说明。
This commit is contained in:
Christ committed 2026-08-08 12:05:43 +08:00
1 parent ad224bf4e9
commit d7abbfb2b6
16 files changed
+274 -74

No files matched your search

+16 -1
View File
@@ -8,6 +8,7 @@ package engine
import (
"context"
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"log/slog"
@@ -192,6 +193,7 @@ type Account struct {
tokenAcquiredAt time.Time
tokenExpiresAt time.Time
tokenRefreshAt time.Time
tokenFingerprint string // 仅用于诊断,不保存原始 Token
// 去重
dedupMu sync.Mutex
@@ -1539,12 +1541,15 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
}
now := time.Now()
expiresAt, refreshAt := tokenRotationSchedule(serverExpireAt, now)
tokenFP := tokenFingerprint(accessToken)
a.mu.Lock()
previousTokenFP := a.tokenFingerprint
a.tokenFingerprint = tokenFP
a.tokenAcquiredAt = now
a.tokenExpiresAt = expiresAt
a.tokenRefreshAt = refreshAt
a.mu.Unlock()
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second))
a.logger.Info("WS Token 获取成功", "expires_at", expiresAt, "refresh_at", refreshAt, "ttl", time.Until(expiresAt).Round(time.Second), "token_fp", tokenFP, "previous_token_fp", previousTokenFP, "token_changed", previousTokenFP == "" || previousTokenFP != tokenFP)
if a.store == nil || a.store.Tokens == nil {
return
}
@@ -1561,8 +1566,18 @@ func (a *Account) saveTokenCache(ctx context.Context, deviceID, accessToken stri
}
}
// tokenFingerprint 用不可逆摘要标识 Token,便于判断服务端是否轮换了 Token,
// 同时避免日志泄露可用于 WS 注册的凭证原文。
func tokenFingerprint(token string) string {
sum := sha256.Sum256([]byte(token))
return fmt.Sprintf("%x", sum[:6])
}
// clearTokenCache 清除账号 token 缓存(session 失效 / 短连接可疑 / cookie 被外部更新时调用)。
func (a *Account) clearTokenCache(ctx context.Context) {
a.mu.Lock()
a.tokenFingerprint = ""
a.mu.Unlock()
if a.store == nil || a.store.Tokens == nil {
return
}
+16
View File
@@ -76,3 +76,19 @@ func TestCredentialStateFingerprintIncludesAuthoritativeSnapshot(t *testing.T) {
t.Fatal("权威空 Jar 必须与没有快照的历史状态区分")
}
}
func TestTokenFingerprintIsStableNonReversibleDiagnosticID(t *testing.T) {
first := tokenFingerprint("access-token-a")
if first == "" || len(first) != 12 {
t.Fatalf("token fingerprint=%q, want 12 hex chars", first)
}
if first != tokenFingerprint("access-token-a") {
t.Fatal("same token must produce stable fingerprint")
}
if first == tokenFingerprint("access-token-b") {
t.Fatal("different tokens must produce different fingerprints")
}
if first == "access-token-a" {
t.Fatal("fingerprint must not expose the token")
}
}
+56 -1
View File
@@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
@@ -61,7 +62,10 @@ type Client interface {
// ClientImpl 是 Client 接口的 HTTP 实现。零值可用;HTTP 超时默认 30s。
// 仍导出 HTTPClient/TokenURL 等字段以便调用方覆盖(如测试注入 RoundTripper)。
type ClientImpl struct {
HTTPClient *http.Client
HTTPClient *http.Client
// Logger 记录 MTOP 请求的安全摘要(不会输出 Cookie、签名或响应正文)。
// 未设置时使用 slog.Default,测试可传入丢弃日志的 logger。
Logger *slog.Logger
TokenURL string
ConsignURL string
OrderDetailURL string
@@ -70,6 +74,57 @@ type ClientImpl struct {
LoginUserURL string
}
// httpClient 返回带统一请求/响应日志的 HTTP 客户端副本。统一放在传输层,
// 确保 token、续期、订单、商品和发布等所有 MTOP 调用都具备一致的可观测性。
func (c *ClientImpl) httpClient() *http.Client {
return c.httpClientWithTimeout(30 * time.Second)
}
func (c *ClientImpl) httpClientWithTimeout(defaultTimeout time.Duration) *http.Client {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: defaultTimeout}
}
clone := *hc
transport := hc.Transport
if transport == nil {
transport = http.DefaultTransport
}
clone.Transport = loggingTransport{base: transport, logger: c.Logger}
return &clone
}
type loggingTransport struct {
base http.RoundTripper
logger *slog.Logger
}
func (t loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
logger := t.logger
if logger == nil {
logger = slog.Default()
}
started := time.Now()
logger.Debug("MTOP 请求开始", "method", req.Method, "path", req.URL.Path)
resp, err := t.base.RoundTrip(req)
attrs := []any{"method", req.Method, "path", req.URL.Path, "duration", time.Since(started).Round(time.Millisecond)}
if err != nil {
if errors.Is(err, context.Canceled) {
logger.Debug("MTOP 请求取消", append(attrs, "err", err)...)
} else {
logger.Warn("MTOP 请求失败", append(attrs, "err", err)...)
}
return nil, err
}
responseAttrs := append(attrs, "status", resp.StatusCode, "content_length", resp.ContentLength)
if resp.StatusCode >= http.StatusBadRequest {
logger.Warn("MTOP HTTP 响应异常", responseAttrs...)
} else {
logger.Debug("MTOP 响应收到", responseAttrs...)
}
return resp, nil
}
// NewClient 构造纯 Go HTTP 的 MTOP 客户端。Chromium 只用于读取本机指纹
// 和处理滑块,不能成为登录、续期、token 或 WebSocket 的传输层。
func NewClient() *ClientImpl {
+1 -4
View File
@@ -68,10 +68,7 @@ func (c *ClientImpl) ConsignContext(ctx context.Context, cookiesStr, orderID str
}
func (c *ClientImpl) consignOnce(ctx context.Context, cookiesStr, orderID string) (ok bool, ret []string, updatedCookies string, err error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
consignURL := c.ConsignURL
if consignURL == "" {
consignURL = ConsignAPI
+1 -4
View File
@@ -49,10 +49,7 @@ func (c *ClientImpl) DetectItemMultiSpec(ctx context.Context, cookies, itemID st
req.Header.Set("Origin", "https://www.goofish.com")
req.Header.Set("Referer", documentURL)
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
resp, err := hc.Do(req)
if err != nil {
return false, fmt.Errorf("商品详情请求失败: %w", err)
+1 -4
View File
@@ -59,10 +59,7 @@ func (c *ClientImpl) FetchItemsPage(ctx context.Context, cookiesStr string, page
}
func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string, pageNumber, pageSize int) (*ItemListResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", ItemListAPI)
cookies := protocol.TransCookies(signingCookies)
userID := cookies["unb"]
+1 -4
View File
@@ -38,10 +38,7 @@ func (c *ClientImpl) CheckLoginStatusContext(ctx context.Context, cookiesStr str
if session := cookieSessionFromContext(ctx); session != nil {
cookiesStr, _, _ = session.State()
}
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 20 * time.Second}
}
hc := c.httpClientWithTimeout(20 * time.Second)
loginURL := c.LoginUserURL
if loginURL == "" {
loginURL = LoginUserAPI
+1 -4
View File
@@ -66,10 +66,7 @@ func (c *ClientImpl) FetchOrderDetail(ctx context.Context, cookiesStr, orderID s
}
func (c *ClientImpl) fetchOrderDetailOnce(ctx context.Context, cookiesStr, orderID string) (*OrderDetailResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
endpoint := c.OrderDetailURL
if endpoint == "" {
endpoint = OrderDetailAPI
+2 -8
View File
@@ -208,10 +208,7 @@ func (c *ClientImpl) RecommendPublishCategory(ctx context.Context, cookiesStr, k
}
func (c *ClientImpl) uploadPublishImage(ctx context.Context, cookiesStr string, img PublishImage) (uploadedImage, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 60 * time.Second}
}
hc := c.httpClientWithTimeout(60 * time.Second)
if img.ContentType == "" {
img.ContentType = "application/octet-stream"
}
@@ -495,10 +492,7 @@ func (c *ClientImpl) publishItemOnce(ctx context.Context, cookiesStr string, req
}
func (c *ClientImpl) callMTop(ctx context.Context, cookiesStr, endpoint, api, version, spmCnt, spmPre, logID string, data any) (map[string]any, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
rawData, _ := json.Marshal(data)
dataVal := string(rawData)
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", endpoint)
+1 -4
View File
@@ -88,10 +88,7 @@ func (c *ClientImpl) FetchSoldOrdersPage(ctx context.Context, cookies string, pa
req.Header.Set("Referer", soldOrdersReferer)
req.Header.Set("idle_site_biz_code", "COMMONPRO")
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
resp, err := hc.Do(req)
if err != nil {
return nil, fmt.Errorf("订单列表请求失败: %w", err)
+1 -4
View File
@@ -154,10 +154,7 @@ func (c *ClientImpl) RequestFreshCaptchaURLContext(ctx context.Context, cookiesS
}
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: 20 * time.Second}
}
hc := c.httpClientWithTimeout(20 * time.Second)
tokenURL := c.TokenURL
if tokenURL == "" {
+1 -4
View File
@@ -53,10 +53,7 @@ func (c *ClientImpl) FetchUserProfile(ctx context.Context, cookiesStr string) (*
}
func (c *ClientImpl) fetchUserProfileOnce(ctx context.Context, cookiesStr string) (*UserProfileResult, []string, string, error) {
hc := c.HTTPClient
if hc == nil {
hc = &http.Client{Timeout: 30 * time.Second}
}
hc := c.httpClient()
dataVal := "{}"
signingCookies, requestCookies := mtopRequestCookies(ctx, cookiesStr, "https://www.goofish.com/", UserPageNavAPI)
+29 -2
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
@@ -232,9 +233,11 @@ func openBatch(ctx context.Context, target string, cfg Config, logger *slog.Logg
if result.conn != nil {
_ = result.conn.CloseNow()
}
logger.Warn("闲鱼 WebSocket 握手失败", "url", target, "err", result.err)
return nil, fmt.Errorf("WS dial: %w", result.err)
}
result.conn.SetReadLimit(8 << 20)
logger.Info("闲鱼 WebSocket 握手成功", "url", target)
return newConn(result.conn, cfg, logger), nil
}
@@ -350,6 +353,8 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
headers["mid"] = mid
}
key := midKey(mid)
started := time.Now()
c.logger.Debug("WS 请求发送", "path", path, "mid", key)
responseCh := make(chan map[string]any, 1)
c.pendingMu.Lock()
c.pending[key] = responseCh
@@ -365,10 +370,13 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
frame["body"] = body
}
if err := c.sendJSON(requestCtx, frame); err != nil {
c.logger.Warn("WS 请求发送失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
}
select {
case response := <-responseCh:
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
case <-c.readDone:
// readPump always dispatches a decoded response before it can observe the
@@ -376,15 +384,34 @@ func (c *Conn) request(ctx context.Context, path string, headers map[string]any,
// matching browser event ordering (message before close).
select {
case response := <-responseCh:
code, _ := responseCode(response["code"])
c.logResponse(path, key, code, time.Since(started))
return response, nil
default:
}
return nil, c.connectionReadError()
err := c.connectionReadError()
c.logger.Warn("WS 请求因连接结束失败", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
return nil, err
case <-requestCtx.Done():
return nil, requestCtx.Err()
err := requestCtx.Err()
if errors.Is(err, context.Canceled) {
c.logger.Debug("WS 请求取消", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
} else {
c.logger.Warn("WS 请求超时", "path", path, "mid", key, "duration", time.Since(started).Round(time.Millisecond), "err", err)
}
return nil, err
}
}
func (c *Conn) logResponse(path, mid string, code int, duration time.Duration) {
attrs := []any{"path", path, "mid", mid, "code", code, "duration", duration.Round(time.Millisecond)}
if code >= 400 {
c.logger.Warn("WS 业务响应异常", attrs...)
return
}
c.logger.Debug("WS 响应收到", attrs...)
}
func (c *Conn) readPump() {
defer close(c.readDone)
for {