修复聊天状态并完善风控浏览器诊断

修复内容:
- 持久化聊天消息已读状态与未读边界,过滤系统通知红点,修正实时消息 ID、已读回执和前端徽标显示
- 完善账号级任务、商品接口和消息调度联动,补充相关服务端与引擎测试
- 新增 token 风控诊断包,保存页面、截图、Frame、选择器、网络事件和完整指纹信息
- 规范化无头 Chromium 的 User-Agent 与 Client Hints,覆盖 Playwright 主引擎和直接 CDP 备用引擎
- 增加可选证书错误兼容开关、真实 Chromium 指纹集成测试,并同步冻结规范
- 新增 SQLite、MySQL、Postgres 聊天状态迁移并重新构建嵌入式前端
This commit is contained in:
Christ committed 2026-08-17 18:41:49 +08:00
1 parent 1185551018
commit ecfe43b5a4
43 files changed
+2244 -113

No files matched your search

@@ -121,3 +121,34 @@ func TestChatAndTaskEndpointsEnforceOwnershipAndValidation(t *testing.T) {
}
}
}
func TestFindChatPlatformMessageID(t *testing.T) {
raw := map[string]any{
"1": map[string]any{
"2": "64725235816@goofish",
"3": "4263141580162.PNM",
"10": map[string]any{
"extJson": `{"messageId":"f87f8f6dabca4eff940863ef72a393f7"}`,
},
},
}
if got := findChatPlatformMessageID(raw, "64725235816", "f87f8f6dabca4eff940863ef72a393f7"); got != "4263141580162.PNM" {
t.Fatalf("platform message id=%q", got)
}
if got := findChatPlatformMessageID(raw, "other-chat", "f87f8f6dabca4eff940863ef72a393f7"); got != "" {
t.Fatalf("跨会话错误匹配: %q", got)
}
}
func TestResolveChatReadMessageIDsMigratesLegacyID(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
raw := `{"1":{"2":"64725235816@goofish","3":"4263141580162.PNM","10":{"extJson":"{\"messageId\":\"f87f8f6dabca4eff940863ef72a393f7\"}"}}}`
if err := store.WSMessages.Add(context.Background(), db.WSMessage{CookieID: "acc1", Direction: "in", ParsedJSON: raw, ParseStatus: "decrypted"}); err != nil {
t.Fatal(err)
}
got := srv.resolveChatReadMessageIDs(context.Background(), "acc1", "64725235816", []map[string]any{{"messageId": "f87f8f6dabca4eff940863ef72a393f7"}})
if len(got) != 1 || got[0]["messageId"] != "4263141580162.PNM" {
t.Fatalf("resolved=%+v", got)
}
}
+154 -2
View File
@@ -2,7 +2,10 @@ package server
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
@@ -367,8 +370,9 @@ func (s *Server) sendChatMessage(w http.ResponseWriter, r *http.Request) {
func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
var input struct {
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
AccountID string `json:"account_id"`
ChatID string `json:"chat_id"`
MessageIDs []map[string]any `json:"message_ids"`
}
if decodeJSON(r, &input) != nil || input.ChatID == "" {
writeErr(w, http.StatusBadRequest, "请求格式错误")
@@ -378,14 +382,162 @@ func (s *Server) markChatRead(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusForbidden, "无权操作该账号")
return
}
slog.Info("收到聊天已读请求", "account", input.AccountID, "chat_id", input.ChatID, "message_count", len(input.MessageIDs))
if len(input.MessageIDs) == 0 {
// 兼容只传会话 ID 的调用方:从本地最近消息补齐平台消息 ID。
userID := auth.SessionFromContext(r.Context()).UserID
if rows, err := s.Store.Chats.ListMessages(r.Context(), userID, input.AccountID, input.ChatID, 0, 200); err == nil {
for _, row := range rows {
if row.Direction == "incoming" && row.MessageType != "system" {
input.MessageIDs = append(input.MessageIDs, map[string]any{"messageId": row.MessageKey})
}
}
}
}
// 旧版本把实时 WS 通知里的 bizTag/extJson messageId 当成了平台消息
// ID,数据库里会留下 32 位关联 ID。闲鱼的 read 接口实际要求 1.3 的
// PNM ID;这里从已保存的解密 WS 诊断帧把旧 ID 转回 PNM,避免升级后
// 仍有历史实时消息无法被标记已读。
input.MessageIDs = s.resolveChatReadMessageIDs(r.Context(), input.AccountID, input.ChatID, input.MessageIDs)
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Chats.MarkRead(r.Context(), sess.UserID, input.AccountID, input.ChatID); err != nil {
writeErr(w, http.StatusInternalServerError, "更新已读状态失败")
return
}
if s.Manager != nil {
if sender, ok := s.Manager.GetInstance(input.AccountID); ok {
if reader, ok := sender.(interface {
MarkChatRead(context.Context, string, []map[string]any) error
}); ok {
if err := reader.MarkChatRead(r.Context(), input.ChatID, input.MessageIDs); err != nil {
slog.Warn("上报闲鱼已读状态失败", "account", input.AccountID, "chat_id", input.ChatID, "err", err)
}
}
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) resolveChatReadMessageIDs(ctx context.Context, accountID, chatID string, messageIDs []map[string]any) []map[string]any {
if s == nil || s.Store == nil || s.Store.DB == nil {
return messageIDs
}
resolved := make([]map[string]any, 0, len(messageIDs))
seen := make(map[string]struct{}, len(messageIDs))
for _, item := range messageIDs {
id := strings.TrimSpace(fmt.Sprint(item["messageId"]))
if id == "" || id == "<nil>" {
continue
}
if !strings.HasSuffix(id, ".PNM") {
if platformID := s.lookupChatPlatformMessageID(ctx, accountID, chatID, id); platformID != "" {
slog.Info("已将旧聊天消息 ID 转换为平台 PNM", "account", accountID, "chat_id", chatID, "old_message_id", id, "message_id", platformID)
id = platformID
} else {
slog.Warn("未找到旧聊天消息对应的 PNM,跳过已读上报", "account", accountID, "chat_id", chatID, "message_id", id)
continue
}
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
copyItem := make(map[string]any, len(item)+1)
for key, value := range item {
copyItem[key] = value
}
copyItem["messageId"] = id
resolved = append(resolved, copyItem)
}
return resolved
}
func (s *Server) lookupChatPlatformMessageID(ctx context.Context, accountID, chatID, legacyID string) string {
rows, err := s.Store.DB.QueryContext(ctx, `SELECT parsed_json FROM ws_messages
WHERE cookie_id=? AND direction='in' AND parse_status='decrypted' AND parsed_json LIKE ?
ORDER BY id DESC LIMIT 20`, accountID, "%"+legacyID+"%")
if err != nil {
return ""
}
defer rows.Close()
for rows.Next() {
var raw string
if rows.Scan(&raw) != nil {
continue
}
var decoded any
if json.Unmarshal([]byte(raw), &decoded) != nil {
continue
}
if platformID := findChatPlatformMessageID(decoded, chatID, legacyID); platformID != "" {
return platformID
}
}
return ""
}
func findChatPlatformMessageID(value any, chatID, legacyID string) string {
var walk func(any) string
walk = func(current any) string {
switch typed := current.(type) {
case map[string]any:
if m10, ok := typed["10"]; ok && chatReadValueContainsID(m10, legacyID) {
if candidate := strings.TrimSpace(fmt.Sprint(typed["3"])); strings.HasSuffix(candidate, ".PNM") {
if cid := strings.TrimSuffix(strings.TrimSpace(fmt.Sprint(typed["2"])), "@goofish"); cid == "" || cid == chatID {
return candidate
}
}
}
for _, child := range typed {
if candidate := walk(child); candidate != "" {
return candidate
}
}
case []any:
for _, child := range typed {
if candidate := walk(child); candidate != "" {
return candidate
}
}
case string:
var nested any
if json.Unmarshal([]byte(typed), &nested) == nil {
return walk(nested)
}
}
return ""
}
return walk(value)
}
func chatReadValueContainsID(value any, legacyID string) bool {
switch typed := value.(type) {
case map[string]any:
for key, child := range typed {
if strings.EqualFold(key, "messageId") || strings.EqualFold(key, "message_id") {
if strings.TrimSpace(fmt.Sprint(child)) == legacyID {
return true
}
}
if chatReadValueContainsID(child, legacyID) {
return true
}
}
case []any:
for _, child := range typed {
if chatReadValueContainsID(child, legacyID) {
return true
}
}
case string:
var nested any
if json.Unmarshal([]byte(typed), &nested) == nil {
return chatReadValueContainsID(nested, legacyID)
}
}
return false
}
func (s *Server) chatWebSocket(w http.ResponseWriter, r *http.Request) {
if s.chat == nil {
writeErr(w, http.StatusServiceUnavailable, "聊天服务未启用")
+86 -18
View File
@@ -110,7 +110,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
defer cancel()
client := s.mtopClient()
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
publishReq := mtop.PublishItemRequest{
Title: title,
Description: description,
PriceCents: priceCents,
@@ -121,7 +121,8 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
Virtual: true,
Location: selectedLocation,
Images: images,
})
}
res, callErr := client.PublishItem(mtopCtx, cookieValue, publishReq)
runtimeCookie := ""
runtimeCookieChanged := false
var responseCookieErr error
@@ -151,25 +152,47 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
if responseCookieErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", responseCookieErr))
}
s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr)
var perr *mtop.PublishError
if errors.As(callErr, &perr) {
status := http.StatusBadGateway
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
status = http.StatusForbidden
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
// Session 失效是账号级凭证问题。续期成功后,当前发布请求仍然
// 可以安全重试一次:平台已经明确拒绝了这次业务调用,不会把
// 同一商品重复发布。重试前重新读取 Cookie,避免继续使用旧会话。
if mtop.IsSessionExpiredErr(callErr) && s.recoverExpiredMTOPSession(r.Context(), cookieID, callErr) {
retryRes, retryErr, retryCookieErr, credentialChanged := s.retryPublishItemAfterRenewal(ctx, cookieID, userID, publishReq)
if credentialChanged {
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
writeJSON(w, status, map[string]any{
"success": false,
"code": perr.Code,
"message": msg,
"ret": perr.Ret,
})
if retryErr == nil && retryRes != nil {
res = retryRes
callErr = nil
responseCookieErr = retryCookieErr
} else if retryErr != nil {
callErr = retryErr
responseCookieErr = retryCookieErr
}
}
if callErr == nil {
// The renewed attempt succeeded; continue through the normal local
// persistence and success response path below.
} else {
var perr *mtop.PublishError
if errors.As(callErr, &perr) {
status := http.StatusBadGateway
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
status = http.StatusForbidden
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
}
writeJSON(w, status, map[string]any{
"success": false,
"code": perr.Code,
"message": msg,
"ret": perr.Ret,
})
return
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
if res == nil || strings.TrimSpace(res.ItemID) == "" {
writeJSON(w, http.StatusBadGateway, map[string]any{
@@ -233,6 +256,51 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
})
}
// retryPublishItemAfterRenewal re-reads the account credential after a
// successful Session renewal and repeats one rejected publish attempt. The
// caller already owns the parsed images and request payload, so this method
// deliberately does not re-parse the multipart body.
func (s *Server) retryPublishItemAfterRenewal(
ctx context.Context,
cookieID string,
userID int64,
req mtop.PublishItemRequest,
) (result *mtop.PublishItemResult, callErr, cookieErr error, credentialChanged bool) {
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
defer credentialUnlock()
latest, err := s.Store.Cookies.GetDetails(ctx, cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
return nil, nil, nil, true
}
cookieValue := latest.Value
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
result, callErr = s.mtopClient().PublishItem(mtopCtx, cookieValue, req)
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
cookieErr = persistErr
if s.Logger != nil {
s.Logger.Error("保存重试发布响应 Cookie Jar 失败", "cookie_id", cookieID, "err", persistErr)
}
} else if handled {
if valueChanged {
s.updateRunningCookie(ctx, cookieID, value)
}
} else if callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue {
if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, result.UpdatedCookies, userID); err != nil {
cookieErr = err
if s.Logger != nil {
s.Logger.Error("保存重试发布响应 Cookie 失败", "cookie_id", cookieID, "err", err)
}
} else {
s.updateRunningCookie(ctx, cookieID, result.UpdatedCookies)
}
}
if cookieErr != nil && callErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", cookieErr))
}
return result, callErr, cookieErr, false
}
func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) {
if r.MultipartForm == nil || r.MultipartForm.File == nil {
return nil, errors.New("至少上传 1 张商品图片")
+27
View File
@@ -317,6 +317,33 @@ func TestPublishItemReportsRemoteSuccessLocalSaveFailure(t *testing.T) {
}
}
func TestRetryPublishItemAfterRenewalUsesFreshCredential(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
admin, err := store.Users.GetByUsername(context.Background(), "admin")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.UpdateValueExisting(context.Background(), "acc1", "unb=123; fresh=1"); err != nil {
t.Fatal(err)
}
var gotCookies string
srv.MTop = &stubPublishMTop{publish: func(_ context.Context, cookies string, _ mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
gotCookies = cookies
return &mtop.PublishItemResult{ItemID: "retry-item", Title: "重试商品"}, nil
}}
result, callErr, cookieErr, changed := srv.retryPublishItemAfterRenewal(
context.Background(), "acc1", admin.ID,
mtop.PublishItemRequest{Title: "重试商品", PriceCents: 100, Quantity: 1},
)
if changed || callErr != nil || cookieErr != nil || result == nil || result.ItemID != "retry-item" {
t.Fatalf("重试结果异常: result=%+v callErr=%v cookieErr=%v changed=%v", result, callErr, cookieErr, changed)
}
if !strings.Contains(gotCookies, "fresh=1") {
t.Fatalf("重试未读取续期后的 Cookie: %q", gotCookies)
}
}
// TestPublishItemStockPermissionMissing 库存权限缺失应 403。
func TestPublishItemStockPermissionMissing(t *testing.T) {
srv, _, cleanup := newTestServer(t)