diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 7d9badd..5130c80 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -126,7 +126,8 @@ app shell / routes - 已完成阶段 2 后续切片:`internal/engine/account.go` 的 `reloadCookieFromDB` 已改用 `GetCookieRuntimeData`,只读取外部 Cookie 更新检测所需的 Cookie 与 metadata,保持运行时替换、token 清理和错误行为,并补充损坏登录密码回归测试; - 已完成阶段 2 当前 PR 切片四“Engine/账号运行时凭证边界”:`cookieSnapshotMatchesDB`、`UpdateCookie` 和账号管理器 `Restart` 已分别改用 `GetCookieRuntimeData` 或 `GetValue`,只读取运行实例所需的 Cookie 数据;损坏登录密码回归测试覆盖 WS 注册前校验、运行时同步和重启路径,且三项修改合并为一个可回滚提交; - 已完成阶段 2 当前 PR 切片五“平台凭证流程统一窄查询”:新增不含用户名和登录密码的 `CookiePlatformRuntimeData`,并将 `internal/adapter` 的 token 风控、订单详情、协议续期以及 `internal/renewal` 的迟到 Cookie 合并统一迁移到该视图;损坏登录密码回归测试覆盖四条平台流程,且整批修改合并为一个可回滚提交; -- 阶段 2 下一 PR 切片为“Server 剩余平台凭证流程审计”:集中复核 `internal/server` 仍使用完整账号详情的真实凭证调用,按用途迁移到平台运行视图或其他专用窄查询,完成该切片内所有调用方后再统一提交,禁止按单个函数拆分提交; +- 已完成阶段 2 当前 PR 切片六“Server 平台凭证流程审计”:Server 的订单、发布、商品同步、二维码登录、长登录、资料刷新和账号生命周期路径已改用平台运行视图或非敏感摘要;完整 `CookieDetail` 仅保留给账号设置和登录信息更新这两个确实需要登录秘密的流程,新增 Server 窄查询回归测试并通过全量门禁,整批修改合并为一个可回滚提交; +- 阶段 2 下一 PR 切片为“敏感数据边界最终审计”:复核生产代码完整详情读取白名单、补充跨数据库窄查询回归、确认所有权与凭证锁不变量,并在阶段 2 证据完整后再进入阶段 3 API 契约,不拆分单个调用提交; - 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。 ## 6. 阶段 0:治理文档与强约束 @@ -500,4 +501,4 @@ npm --prefix frontend run build | 2026-08-14 | `refreshTokenWithMinGap` 改用 `GetCookieMetadata` | token 请求只解密 Cookie 快照 metadata;快照上下文和 token 刷新行为保持不变,回归测试通过 | 迁移 `adoptTokenResponseCookies` 的 metadata 读取 | | 2026-08-14 | `adoptTokenResponseCookies` 改用 `GetCookieMetadata` | token 响应合并只解密 metadata;快照持久化和错误语义保持不变,回归测试通过 | 迁移 `databaseCredentialFingerprint` 的运行时凭证读取 | | 2026-08-14 | `databaseCredentialFingerprint` 改用 `GetCookieRuntimeData` | token 凭证一致性校验只解密 Cookie 与 metadata;空值、指纹和错误语义保持不变,回归测试通过 | 迁移 `reloadCookieFromDB` 的运行时凭证读取 | -| 2026-08-14 | 完成阶段 2 当前 PR 切片“平台凭证流程统一窄查询” | 新增 `CookiePlatformRuntimeData`;adapter 的 token 风控、订单详情、协议续期和 renewal 迟到 Cookie 合并均不再读取完整账号详情;损坏登录密码回归测试及全量门禁通过 | 集中审计 server 剩余完整账号详情调用后再提交下一 PR 切片 | +| 2026-08-14 | 完成阶段 2 当前 PR 切片“Server 平台凭证流程审计” | Server 平台、订单、发布、二维码和资料流程均不再读取完整账号详情;完整详情仅保留给登录设置与登录信息更新;窄查询回归测试、全量测试、race、vet、lint 和注释门禁通过 | 进行敏感数据边界最终审计,确认阶段 2 完成证据后进入阶段 3 | diff --git a/internal/server/cookie_handlers.go b/internal/server/cookie_handlers.go index 11e8296..03f1b54 100644 --- a/internal/server/cookie_handlers.go +++ b/internal/server/cookie_handlers.go @@ -47,7 +47,7 @@ func (s *Server) getLongLoginSettings(w http.ResponseWriter, r *http.Request) { return } credentialUnlock := s.Store.LockAccountCredentials(cid) - detail, err := s.Store.Cookies.GetDetails(r.Context(), cid) + detail, err := s.loadCookiePlatformDetail(r.Context(), cid) if err != nil || detail == nil || detail.UserID != ownedDetail.UserID { credentialUnlock() writeErr(w, http.StatusNotFound, "账号不存在") @@ -91,7 +91,7 @@ func (s *Server) setLongLoginSettings(w http.ResponseWriter, r *http.Request) { return } credentialUnlock := s.Store.LockAccountCredentials(cid) - detail, err := s.Store.Cookies.GetDetails(r.Context(), cid) + detail, err := s.loadCookiePlatformDetail(r.Context(), cid) if err != nil || detail == nil || detail.UserID != ownedDetail.UserID { credentialUnlock() writeErr(w, http.StatusNotFound, "账号不存在") @@ -228,7 +228,7 @@ type updateCookieSettingsRequest struct { // updateCookieSettings 原子保存编辑弹窗中的账号字段和通知绑定。 func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) { cid := chi.URLParam(r, "cid") - detail, ok := s.requireCookieOwner(w, r, cid) + detail, ok := s.requireCookieSecretOwner(w, r, cid) if !ok { return } @@ -447,7 +447,7 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusForbidden, "无权限操作该账号") return } - d, err := s.Store.Cookies.GetDetails(r.Context(), cid) // d 和 err 是账号凭证详情及查询错误。 + d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cid) // d 和 err 是资料刷新所需的非敏感摘要及查询错误。 if err != nil { writeErr(w, http.StatusNotFound, "账号不存在") return @@ -513,7 +513,7 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) { } s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功") credentialUnlock() - if d, err := s.Store.Cookies.GetDetails(r.Context(), req.ID); err == nil { + if d, err := s.loadCookiePlatformDetail(r.Context(), req.ID); err == nil { s.refreshAccountProfile(r.Context(), d) } if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) { @@ -541,7 +541,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { } sess := auth.SessionFromContext(r.Context()) credentialUnlock := s.Store.LockAccountCredentials(cid) - detail, err := s.Store.Cookies.GetDetails(r.Context(), cid) + detail, err := s.loadCookiePlatformDetail(r.Context(), cid) if err != nil || detail == nil || detail.UserID != ownedDetail.UserID || detail.UserID != sess.UserID { credentialUnlock() writeErr(w, http.StatusNotFound, "账号不存在") @@ -565,7 +565,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功") } credentialUnlock() - if d, err := s.Store.Cookies.GetDetails(r.Context(), cid); err == nil { + if d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cid); err == nil { s.refreshAccountProfile(r.Context(), d) } if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) { @@ -579,7 +579,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) { // updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。 func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) { cid := chi.URLParam(r, "cid") - detail, ok := s.requireCookieOwner(w, r, cid) + detail, ok := s.requireCookieSecretOwner(w, r, cid) if !ok { return } @@ -629,7 +629,7 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) { reason = db.DisableReasonManual } credentialUnlock := s.Store.LockAccountCredentials(cid) - latest, err := s.Store.Cookies.GetDetails(r.Context(), cid) + latest, err := s.loadCookiePlatformDetail(r.Context(), cid) if err != nil || latest == nil || latest.UserID != ownedDetail.UserID { credentialUnlock() writeErr(w, http.StatusNotFound, "账号不存在") @@ -645,7 +645,7 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) { if s.Manager != nil { if req.Enabled { // 重启拉取最新 cookie。 - if _, e := s.Store.Cookies.GetDetails(r.Context(), cid); e == nil { + if _, e := s.loadCookiePlatformDetail(r.Context(), cid); e == nil { if err := s.Manager.Restart(r.Context(), cid); err != nil { s.Logger.Error("启用后重启账号失败", "cookie_id", cid, "err", err) } @@ -665,7 +665,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) { return } credentialUnlock := s.Store.LockAccountCredentials(cid) - latest, err := s.Store.Cookies.GetDetails(r.Context(), cid) + latest, err := s.loadCookiePlatformDetail(r.Context(), cid) if err != nil || latest == nil || latest.UserID != ownedDetail.UserID { credentialUnlock() writeErr(w, http.StatusNotFound, "账号不存在") @@ -679,8 +679,8 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) { credentialUnlock() s.Logger.Info("账号已删除", "cookie_id", cid, - "nickname", cachedAccountNickname(latest), - "user_id", latest.UserID, + "nickname", cachedAccountNickname(ownedDetail), + "user_id", ownedDetail.UserID, ) // Stop 可能需要等待运行中任务收尾,不应阻塞删除 HTTP 请求。 // 数据库事务已完成,先向前端确认删除,再在后台精确停止该 cid 的实例。 @@ -796,7 +796,7 @@ func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) } credentialUnlock := s.Store.LockAccountCredentials(d.ID) - latest, latestErr := s.Store.Cookies.GetDetails(ctx, d.ID) + latest, latestErr := s.loadCookiePlatformDetail(ctx, d.ID) if latestErr != nil || latest == nil || latest.UserID != d.UserID { credentialUnlock() if latestErr == nil { diff --git a/internal/server/item_handlers.go b/internal/server/item_handlers.go index 5375db3..2bd029d 100644 --- a/internal/server/item_handlers.go +++ b/internal/server/item_handlers.go @@ -99,7 +99,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) { selectedLocation = &location } credentialUnlock := s.Store.LockAccountCredentials(cookieID) - latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID) + latest, err := s.loadCookiePlatformDetail(r.Context(), cookieID) if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { credentialUnlock() writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") @@ -355,7 +355,7 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) { return } credentialUnlock := s.Store.LockAccountCredentials(req.CookieID) - latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID) + latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID) if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { credentialUnlock() writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") @@ -458,7 +458,7 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request return } credentialUnlock := s.Store.LockAccountCredentials(req.CookieID) - latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID) + latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID) if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { credentialUnlock() writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go index 9086beb..1c81371 100644 --- a/internal/server/item_publish_batch_handlers.go +++ b/internal/server/item_publish_batch_handlers.go @@ -135,7 +135,7 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req s.updateRunningCookie(context.Background(), req.CookieID, runtimeCookie) } }() - latest, err := s.Store.Cookies.GetDetails(r.Context(), req.CookieID) + latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID) if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) { writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") return @@ -923,7 +923,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop. res, err = func() (*mtop.PublishItemResult, error) { credentialUnlock := s.Store.LockAccountCredentials(row.CookieID) defer credentialUnlock() - latest, latestErr := s.Store.Cookies.GetDetails(ctx, row.CookieID) + latest, latestErr := s.loadCookiePlatformDetail(ctx, row.CookieID) if latestErr != nil { return nil, latestErr } diff --git a/internal/server/order_handlers.go b/internal/server/order_handlers.go index da9e495..b4f13ec 100644 --- a/internal/server/order_handlers.go +++ b/internal/server/order_handlers.go @@ -194,7 +194,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { if fetcher, ok := s.mtopClient().(mtop.SoldOrderFetcher); ok { for _, cid := range cookieIDs { // cid 是当前待刷新的账号 ID。 credentialUnlock := s.Store.LockAccountCredentials(cid) - latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid) + latest, latestErr := s.loadCookiePlatformDetail(r.Context(), cid) if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) { credentialUnlock() if latestErr == nil { @@ -323,7 +323,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) { accountSessionExpired := false for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) { credentialUnlock := s.Store.LockAccountCredentials(cid) - latest, latestErr := s.Store.Cookies.GetDetails(r.Context(), cid) + latest, latestErr := s.loadCookiePlatformDetail(r.Context(), cid) if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) { credentialUnlock() failed += len(chunk) @@ -527,7 +527,7 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { } }() sess := auth.SessionFromContext(r.Context()) - latest, err := s.Store.Cookies.GetDetails(r.Context(), cookieID) + latest, err := s.loadCookiePlatformDetail(r.Context(), cookieID) if err != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) { writeErr(w, http.StatusConflict, "账号凭证已变化,请重试") return @@ -867,7 +867,7 @@ 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) + detail, err := s.loadCookiePlatformDetail(ctx, cookieID) if err != nil { return false, nil, "", false, err } diff --git a/internal/server/ownership_helpers.go b/internal/server/ownership_helpers.go index 9f38d28..8c1f39d 100644 --- a/internal/server/ownership_helpers.go +++ b/internal/server/ownership_helpers.go @@ -13,7 +13,7 @@ func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cook writeErr(w, http.StatusUnauthorized, "未授权访问") return nil, false } - d, err := s.Store.Cookies.GetDetails(r.Context(), cookieID) + d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cookieID) if err != nil { writeErr(w, http.StatusNotFound, "账号不存在") return nil, false @@ -25,6 +25,22 @@ func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cook return d, true } +// requireCookieSecretOwner 校验账号归属后读取登录设置所需的完整详情,仅供需要密码的管理流程使用。 +func (s *Server) requireCookieSecretOwner(w http.ResponseWriter, r *http.Request, cookieID string) (*db.CookieDetail, bool) { + // ownerOK 表示当前会话是否通过账号所有权校验。 + _, ownerOK := s.requireCookieOwner(w, r, cookieID) + if !ownerOK { + return nil, false + } + // detail 是登录设置流程需要的用户名、密码和浏览器显示设置。 + detail, err := s.Store.Cookies.GetDetails(r.Context(), cookieID) + if err != nil || detail == nil { + writeErr(w, http.StatusNotFound, "账号不存在") + return nil, false + } + return detail, true +} + // requireCookieOwnership 校验当前会话是否拥有账号,只读取账号所有权元数据,不解密凭证。 func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request, cookieID string) bool { // sess 是当前请求经过认证中间件注入的会话。 diff --git a/internal/server/platform_runtime.go b/internal/server/platform_runtime.go new file mode 100644 index 0000000..7227e40 --- /dev/null +++ b/internal/server/platform_runtime.go @@ -0,0 +1,51 @@ +package server + +import ( + "context" + + "xianyu-go/internal/db" +) + +// loadCookiePlatformDetail 读取平台请求所需的最小 Cookie 状态,并转换为 Server 内部已有的会话适配模型。 +func (s *Server) loadCookiePlatformDetail(ctx context.Context, cookieID string) (*db.CookieDetail, error) { + // platformData 是 repository 返回的不含登录密码的平台运行视图。 + platformData, err := s.Store.Cookies.GetCookiePlatformRuntimeData(ctx, cookieID) + if err != nil { + return nil, err + } + // detail 是仅供 Cookie Session 适配器使用的浅层模型,不包含用户名、密码或账号设置。 + detail := &db.CookieDetail{ + ID: platformData.ID, + UserID: platformData.UserID, + Value: platformData.Value, + MetadataJSON: platformData.MetadataJSON, + } + return detail, nil +} + +// loadCookieSummaryDetail 读取账号非敏感摘要并转换为 Server 内部的兼容模型。 +func (s *Server) loadCookieSummaryDetail(ctx context.Context, userID int64, cookieID string) (*db.CookieDetail, error) { + // summary 是按当前用户与账号 ID 联合过滤得到的非敏感摘要。 + summary, err := s.Store.Cookies.GetSummaryOwned(ctx, userID, cookieID) + if err != nil { + return nil, err + } + // detail 是只包含摘要字段的兼容模型,不携带任何 Cookie、metadata 或登录密码。 + detail := &db.CookieDetail{ + ID: summary.ID, + UserID: summary.UserID, + AutoConfirm: summary.AutoConfirm, + Remark: summary.Remark, + PauseDuration: summary.PauseDuration, + PausedUntil: summary.PausedUntil, + Username: summary.Username, + ShowBrowser: summary.ShowBrowser, + Nickname: summary.Nickname, + AvatarURL: summary.AvatarURL, + LastRefreshAt: summary.LastRefreshAt, + LoginMethod: summary.LoginMethod, + LastLoginAt: summary.LastLoginAt, + CreatedAt: summary.CreatedAt, + } + return detail, nil +} diff --git a/internal/server/platform_runtime_scope_test.go b/internal/server/platform_runtime_scope_test.go new file mode 100644 index 0000000..e5cb1f2 --- /dev/null +++ b/internal/server/platform_runtime_scope_test.go @@ -0,0 +1,35 @@ +package server + +import ( + "context" + "testing" +) + +// TestServerPlatformRuntimeDetailSkipsLoginSecrets 验证 Server 平台适配模型不解密登录密码。 +func TestServerPlatformRuntimeDetailSkipsLoginSecrets(t *testing.T) { + // srv、store 和 cleanup 分别是测试服务器、数据库和资源清理函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 是平台适配模型测试共用的上下文。 + ctx := context.Background() + // corruptErr 表示写入故意损坏的登录密码密文失败的原因。 + if _, corruptErr := store.DB.ExecContext(ctx, + `UPDATE cookies SET password=? WHERE id=?`, "not-a-password-ciphertext", "acc1"); corruptErr != nil { + t.Fatalf("corrupt password: %v", corruptErr) + } + // platformDetail 是商品、订单和登录平台调用共享的浅层凭证适配模型。 + platformDetail, platformErr := srv.loadCookiePlatformDetail(ctx, "acc1") + if platformErr != nil || platformDetail == nil || platformDetail.ID != "acc1" || platformDetail.Value == "" { + t.Fatalf("platform detail=%+v err=%v", platformDetail, platformErr) + } + // ownerID 是测试账号的实际所有者 ID,避免依赖固定用户编号。 + ownerID, ownerErr := store.Cookies.GetOwnerID(ctx, "acc1") + if ownerErr != nil { + t.Fatalf("get owner: %v", ownerErr) + } + // summaryDetail 是 ownership 和资料刷新使用的非敏感摘要适配模型。 + summaryDetail, summaryErr := srv.loadCookieSummaryDetail(ctx, ownerID, "acc1") + if summaryErr != nil || summaryDetail == nil || summaryDetail.ID != "acc1" || summaryDetail.UserID != ownerID { + t.Fatalf("summary detail=%+v err=%v", summaryDetail, summaryErr) + } +} diff --git a/internal/server/qrlogin_handlers.go b/internal/server/qrlogin_handlers.go index c858a8b..a08052a 100644 --- a/internal/server/qrlogin_handlers.go +++ b/internal/server/qrlogin_handlers.go @@ -226,7 +226,7 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses credentialUnlock := s.Store.LockAccountCredentials(accountID) saveErr := func() error { defer credentialUnlock() - detail, err := s.Store.Cookies.GetDetails(ctx, accountID) + detail, err := s.loadCookiePlatformDetail(ctx, accountID) switch { case errors.Is(err, db.ErrNotFound): if targetAccountID != "" { @@ -278,7 +278,7 @@ func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, ses } return qrLoginPersistence{}, saveErr } - if d, err := s.Store.Cookies.GetDetails(ctx, accountID); err == nil { + if d, err := s.loadCookieSummaryDetail(ctx, userID, accountID); err == nil { s.refreshAccountProfile(ctx, d) } s.wakeCredentialBlockedAutomation(ctx, accountID)