diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 888ddd6..6c68977 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -95,12 +95,12 @@ app shell / routes | 1. PR CI 与测试基础 | 已完成 | 独立 CI、测试 DB 模板、可执行 race | CI、独立模板、server smoke race 和完整 race 均有验证 | | 2. 敏感数据访问边界 | 已完成 | 摘要、凭证、登录秘密和系统设置分离 | Cookie/平台运行视图、系统设置脱敏读写、已知生产敏感设置调用方审计和运维诊断输出脱敏已收口;SQLite、MySQL 8.4、PostgreSQL 17 的真实多库迁移与 CRUD 回归均通过;高频运行时仅读取窄视图、不逐次写审计,管理/一次性敏感读取均有审计和 fail-closed 测试 | | 3. HTTP API 契约 | 已完成 | 统一错误、具名 DTO、版本化路径 | 统一错误 DTO、具名成功 DTO、所有前端业务调用方版本化、旧路径兼容和最终审计均已完成 | -| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单业务服务已迁入 `internal/application/orders`,Server 仅保留订单 HTTP/基础设施适配器;商品发布、登录、聊天仍由 Server 持有,handler 的低层依赖与其他领域 Port 仍待收口 | -| 5. 应用生命周期装配 | 进行中 | 消除必需依赖 setter 回填并统一关闭边界 | 已有 Server 自有 worker 等待;待完成 Context-aware Stop、账号 StopAll 超时、删除任务登记和统一生命周期清单 | +| 4. Server 应用服务 | 进行中 | 订单、发布、登录、聊天纵向抽取 | 订单、单/批量商品发布、账号资料刷新和手动 Cookie 登录已通过应用 Port 接入;密码/扫码/更新凭证、聊天及部分商品辅助流程仍由 Server 持有,handler 的低层依赖与其他领域 Port 仍待收口 | +| 5. 应用生命周期装配 | 进行中 | 消除必需依赖 setter 回填并统一关闭边界 | Server、续期调度器、浏览器 Manager、Engine watcher、账号 Manager 的 Stop/Close 已具备 Context/fencing 与回归;统一任务清单、删除任务状态查询、通知/自动化后台运维状态仍待补齐 | | 6. Engine 与 Automation | 已完成 | facade + 独立状态组件 | Engine/Automation 组件边界、race、生命周期与冻结规范测试均已通过 | | 7. React Feature 化 | 进行中 | 页面、Hook、API、类型按领域拆分 | Rules、Items、Accounts、Cards、Orders、Notifications、Dashboard、Settings、Chat 和 AccountAutomation 的 feature/API/Hook 已拆分,App 路由懒加载和入口包体预算已收口;Provider/路由壳、完整页面行为覆盖和剩余大型页面边界仍待完成 | -| 8. DB 与事务治理 | 进行中 | 窄接口、事务执行器、方言门禁 | 已有部分 repository;待完成禁止 `sql.Tx`/`db.*` 泄露、UoW 在基础设施适配器实现、批量读写和补偿记录 | -| 9. 架构门禁与兼容清理 | 进行中 | 允许依赖图、临时例外、兼容路径退场 | 当前门禁只覆盖低层反向依赖;待完成 Server/application 允许边、Port 类型扫描、旧 API 遥测与 Sunset 条件 | +| 8. DB 与事务治理 | 进行中 | 窄接口、事务执行器、方言门禁 | 订单/商品应用 Port、批量 worker、订单 reconciliation、通知 uncertain 状态和三库迁移证据已补齐;仍有 Server 低层适配集中、`sql.Tx`/`db.*` 旧边界、更多批量读写与补偿查询待收口 | +| 9. 架构门禁与兼容清理 | 进行中 | 允许依赖图、临时例外、兼容路径退场 | `architecturecheck` 已覆盖应用 Port AST 类型和 Server 新增低层依赖;仍保留历史 Server 临时白名单,密码/扫码/聊天等 Port、旧 API 遥测和 Sunset 条件尚未完成 | | 10. 注释基线清零 | 进行中 | 全仓准确中文注释检查 | 已有字符级/AST 门禁;待完成模板短语黑名单、业务语义抽查、复杂度门禁和冻结文件精确例外 | ### 当前执行入口 @@ -797,6 +797,9 @@ npm --prefix frontend run build | 2026-08-15 | P1 手动登录凭证应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层 `account.LoginService`,输入 DTO 不含 Cookie/密码;明文 Cookie 只由 Server request-scoped `CookieWriter` 在凭证锁内完成归属校验、写入和旧 Token 清理,登录后审计/资料刷新/运行时重启通过生命周期 Port;新增成功、归属失败、写入失败和缺失依赖测试,Server/应用回归及中文注释门禁通过。密码登录、扫码登录和更新凭证流程仍待统一协调 | | 2026-08-15 | P1 账号管理器全局 Stop fencing 切片 | 已完成本切片 | `Manager.StopAllContext` 在收集账号前建立全局 stopping fence,停止期间拒绝新的 Start;单账号 Stop 超时保留 stopping 标记,防止存活实例被重启替换;全量停止完成后解除 fence,补充并发启动/停止和已取消 Context 兼容回归,account/Server 测试及 race 通过。删除任务状态查询和统一生命周期清单仍待完善 | | 2026-08-15 | P1 通知 outbox 不确定状态隔离切片 | 已完成本切片 | 新增 SQLite/MySQL/Postgres `notification_outbox.uncertain_at` 迁移及 `MarkOutboxUncertain`;通知已发送但 `CompleteOutbox` 失败时原子转 `uncertain`、清除租约并禁止自动重发,隔离失败用 `errors.Join` 记录;无效渠道清理不再吞错;新增 SQLite、通知 worker 和三库矩阵回归,notify/db race、全量门禁通过。人工核对查询与运维展示仍待补充 | +| 2026-08-15 | P1 扫码登录应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层扫码登录 DTO、凭证 Repository 和生命周期 Port;Server 仅负责平台结果转换、会话幂等和基础设施适配,扫码新建/更新、归属校验、Cookie 快照合并及旧 Token 清理由应用服务编排;新增成功、跨用户、目标不一致、写入失败、清理失败和敏感结果不泄露测试,账号/Server 回归、架构门禁和中文注释门禁通过。更新凭证及其他账号操作仍待迁移 | +| 2026-08-15 | P1 聊天历史应用 Port 闭环切片 | 已完成本切片 | 新增纯应用层聊天消息/会话分页 DTO、最小 Repository 和 Service;聊天历史 handler 完成实际接入,旧 communication service/repository 不再持有历史查询职责;新增用户归属、参数校验、未装配依赖、底层失败和会话摘要失败测试,Server、架构和中文注释门禁通过。聊天写入与实时会话编排仍待迁移 | +| 2026-08-15 | P1 通知不确定态运维可见性切片 | 已完成本切片 | 新增按用户/管理员隔离的 uncertain outbox 元数据查询、计数和版本化 HTTP 接口;响应不返回通知正文、渠道配置、错误原文或凭证;补充 SQLite 隔离、管理员汇总、非管理员 403、脱敏和 limit 回归,DB/Server、架构和中文注释门禁通过。更多统一运维任务清单和旧入口退场仍待完成 | ### 11.2 执行纠偏审计(2026-08-15) diff --git a/internal/application/account/qr_login_service.go b/internal/application/account/qr_login_service.go new file mode 100644 index 0000000..84a6cc7 --- /dev/null +++ b/internal/application/account/qr_login_service.go @@ -0,0 +1,184 @@ +package account + +import ( + "context" + "errors" + "strings" +) + +// ErrQRLoginIncomplete 表示平台扫码成功结果缺少可持久化的账号标识或 Cookie。 +var ErrQRLoginIncomplete = errors.New("扫码结果缺少账号标识或 cookies") + +// ErrQRLoginAccountMismatch 表示扫码得到的平台账号与待重新授权账号不一致。 +var ErrQRLoginAccountMismatch = errors.New("扫码账号与待重新授权账号不一致") + +// CookieSnapshot 是浏览器返回的单个 Cookie 快照;明文值只在当前凭证适配端口调用期间存在。 +type CookieSnapshot struct { + // Name 是浏览器 Cookie 名称。 + Name string + // Value 是浏览器 Cookie 明文值,禁止日志记录、序列化到 HTTP 或进入长期应用状态。 + Value string + // Domain 是浏览器返回的 Cookie 作用域。 + Domain string + // Path 是浏览器返回的 Cookie 路径。 + Path string + // Expires 是浏览器返回的 Unix 时间戳;零值表示会话 Cookie。 + Expires float64 + // HTTPOnly 表示浏览器是否禁止脚本访问该 Cookie。 + HTTPOnly bool + // Secure 表示该 Cookie 是否只允许通过安全连接发送。 + Secure bool + // SameSite 是浏览器返回的跨站请求策略。 + SameSite string + // PartitionKey 是浏览器返回的分区键,供 Cookie 快照合并时保持原样。 + PartitionKey string +} + +// QRLoginInput 是扫码登录成功后持久化用例的纯业务输入;不依赖 HTTP 或平台 DTO。 +type QRLoginInput struct { + // UserID 是发起扫码并拥有目标账号的本地用户标识。 + UserID int64 + // ScannedAccountID 是扫码结果解析出的平台账号标识。 + ScannedAccountID string + // TargetAccountID 是可选的待重新授权账号标识;为空时按扫码账号创建或更新。 + TargetAccountID string + // Cookies 是平台返回的登录 Cookie 明文,仅由凭证端口在最小作用域内消费。 + Cookies string + // Snapshot 是可选的完整浏览器 Cookie 快照;存在时由端口负责合并到加密 metadata。 + Snapshot []CookieSnapshot +} + +// QRLoginResult 是扫码登录持久化后返回的非敏感结果。 +type QRLoginResult struct { + // AccountID 是最终创建或更新的本地账号标识。 + AccountID string + // IsNew 表示本次是否创建了新账号。 + IsNew bool +} + +// QRLoginAccount 是账号归属查询返回的非敏感身份信息,不包含 Cookie、密码或 metadata。 +type QRLoginAccount struct { + // ID 是本地账号标识。 + ID string + // UserID 是账号所属本地用户标识。 + UserID int64 +} + +// QRLoginRepository 定义扫码登录成功后写凭证所需的最小端口。 +type QRLoginRepository interface { + // LockCredentials 串行化同一账号的凭证创建或更新;解锁函数必须由调用方执行。 + LockCredentials(string) func() + // FindAccount 只查询账号存在性与归属,不读取或解密任何凭证字段。 + FindAccount(context.Context, string) (QRLoginAccount, error) + // CreateCookieOwned 创建当前用户拥有的账号 Cookie;明文只在端口内部进入加密存储。 + CreateCookieOwned(context.Context, string, string, int64) error + // UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并由实现方清理旧快照。 + UpdateFlatCookieOwned(context.Context, string, string) error + // UpdateCookieSnapshotOwned 更新 Cookie 并由实现方合并完整浏览器快照到加密 metadata。 + UpdateCookieSnapshotOwned(context.Context, string, string, []CookieSnapshot) error + // ClearTokens 清理账号旧连接 Token;失败由应用生命周期端口记录,且不回滚已成功写入的 Cookie。 + ClearTokens(context.Context, string) error +} + +// QRLoginLifecycle 定义凭证写入完成后执行的审计、资料刷新和运行时同步边界。 +type QRLoginLifecycle interface { + // AfterSuccessfulQRLogin 在凭证锁释放后执行登录后续编排,禁止在实现中重新暴露凭证明文。 + AfterSuccessfulQRLogin(context.Context, int64, string) + // ReportQRLoginCleanupFailure 记录旧 Token 清理失败;该失败不改变已完成的凭证写入结果。 + ReportQRLoginCleanupFailure(context.Context, string, error) +} + +// QRLoginService 编排扫码结果校验、账号归属、凭证写入和登录后续动作。 +type QRLoginService struct { + // repository 提供不泄露凭证字段的账号持久化端口。 + repository QRLoginRepository + // lifecycle 提供凭证写入后的审计、资料刷新和运行时适配。 + lifecycle QRLoginLifecycle +} + +// NewQRLoginService 构造扫码登录应用服务并校验必需端口。 +func NewQRLoginService(repository QRLoginRepository, lifecycle QRLoginLifecycle) (*QRLoginService, error) { + if repository == nil { + return nil, errors.New("扫码登录凭证 repository 未初始化") + } + if lifecycle == nil { + return nil, errors.New("扫码登录生命周期端口未初始化") + } + return &QRLoginService{repository: repository, lifecycle: lifecycle}, nil +} + +// PersistSuccess 执行一次扫码登录成功持久化;返回值只包含账号标识和新建标记。 +func (s *QRLoginService) PersistSuccess(ctx context.Context, input QRLoginInput) (QRLoginResult, error) { + if s == nil || s.repository == nil || s.lifecycle == nil { + return QRLoginResult{}, errors.New("扫码登录服务未初始化") + } + // scannedAccountID 是去除空白后的平台账号标识,避免把格式差异带入账号主键。 + scannedAccountID := strings.TrimSpace(input.ScannedAccountID) + // targetAccountID 是去除空白后的重新授权目标账号标识。 + targetAccountID := strings.TrimSpace(input.TargetAccountID) + if scannedAccountID == "" || strings.TrimSpace(input.Cookies) == "" { + return QRLoginResult{}, ErrQRLoginIncomplete + } + // accountID 是最终用于持久化的账号标识;默认采用扫码得到的账号。 + accountID := scannedAccountID + if targetAccountID != "" { + if targetAccountID != scannedAccountID { + return QRLoginResult{}, ErrQRLoginAccountMismatch + } + accountID = targetAccountID + } + // unlock 保护从归属查询到凭证写入的完整串行区间;生命周期动作在释放后执行。 + unlock := s.repository.LockCredentials(accountID) + // account 保存不含凭证字段的账号归属查询结果。 + account, findErr := s.repository.FindAccount(ctx, accountID) + // isNew 标记本次是否需要创建账号。 + isNew := false + switch { + case errors.Is(findErr, ErrNotFound): + if targetAccountID != "" { + unlock() + return QRLoginResult{}, errors.New("待重新授权账号不存在") + } + isNew = true + // createErr 保存新账号凭证端口写入错误。 + if createErr := s.repository.CreateCookieOwned(ctx, accountID, input.Cookies, input.UserID); createErr != nil { + unlock() + return QRLoginResult{}, createErr + } + case findErr != nil: + unlock() + return QRLoginResult{}, findErr + case account.UserID != input.UserID: + unlock() + return QRLoginResult{}, ErrForbidden + default: + // updateErr 保存已有账号 Cookie 更新错误。 + if updateErr := s.updateExisting(ctx, accountID, input); updateErr != nil { + unlock() + return QRLoginResult{}, updateErr + } + } + if isNew && len(input.Snapshot) > 0 { + // snapshotErr 保存新账号完整 Cookie 快照写入错误。 + if snapshotErr := s.repository.UpdateCookieSnapshotOwned(ctx, accountID, input.Cookies, input.Snapshot); snapshotErr != nil { + unlock() + return QRLoginResult{}, snapshotErr + } + } + // clearErr 保存旧连接 Token 清理结果;凭证已写入成功,因此该尽力而为操作不阻断登录后续动作。 + clearErr := s.repository.ClearTokens(ctx, accountID) + unlock() + if clearErr != nil { + s.lifecycle.ReportQRLoginCleanupFailure(ctx, accountID, clearErr) + } + s.lifecycle.AfterSuccessfulQRLogin(ctx, input.UserID, accountID) + return QRLoginResult{AccountID: accountID, IsNew: isNew}, nil +} + +// updateExisting 更新已存在且已通过归属校验的账号凭证。 +func (s *QRLoginService) updateExisting(ctx context.Context, accountID string, input QRLoginInput) error { + if len(input.Snapshot) > 0 { + return s.repository.UpdateCookieSnapshotOwned(ctx, accountID, input.Cookies, input.Snapshot) + } + return s.repository.UpdateFlatCookieOwned(ctx, accountID, input.Cookies) +} diff --git a/internal/application/account/qr_login_service_test.go b/internal/application/account/qr_login_service_test.go new file mode 100644 index 0000000..78e8dd0 --- /dev/null +++ b/internal/application/account/qr_login_service_test.go @@ -0,0 +1,266 @@ +package account + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" +) + +// fakeQRLoginRepository 是扫码登录应用服务测试使用的凭证端口替身。 +type fakeQRLoginRepository struct { + // account 保存待返回的非敏感账号归属。 + account QRLoginAccount + // findErr 保存账号存在性查询错误。 + findErr error + // createErr 保存新账号凭证创建错误。 + createErr error + // flatErr 保存扁平 Cookie 更新错误。 + flatErr error + // snapshotErr 保存 Cookie 快照更新错误。 + snapshotErr error + // clearErr 保存旧 Token 清理错误。 + clearErr error + // createdCookies 保存新账号端口收到的 Cookie,用于验证敏感值只在端口边界出现。 + createdCookies string + // updatedCookies 保存已有账号端口收到的 Cookie,用于验证更新路径。 + updatedCookies string + // updatedSnapshot 保存端口收到的完整 Cookie 快照。 + updatedSnapshot []CookieSnapshot + // lockCount 记录凭证锁获取次数。 + lockCount int + // clearCount 记录旧 Token 清理次数。 + clearCount int +} + +// LockCredentials 记录测试服务获取凭证锁,并返回无副作用的解锁函数。 +func (r *fakeQRLoginRepository) LockCredentials(string) func() { + r.lockCount++ + return func() {} +} + +// FindAccount 返回预置账号归属或存在性错误。 +func (r *fakeQRLoginRepository) FindAccount(context.Context, string) (QRLoginAccount, error) { + return r.account, r.findErr +} + +// CreateCookieOwned 记录新账号 Cookie 写入请求。 +func (r *fakeQRLoginRepository) CreateCookieOwned(_ context.Context, _ string, cookies string, _ int64) error { + r.createdCookies = cookies + return r.createErr +} + +// UpdateFlatCookieOwned 记录已有账号的扁平 Cookie 更新。 +func (r *fakeQRLoginRepository) UpdateFlatCookieOwned(_ context.Context, _ string, cookies string) error { + r.updatedCookies = cookies + return r.flatErr +} + +// UpdateCookieSnapshotOwned 记录带完整快照的 Cookie 更新。 +func (r *fakeQRLoginRepository) UpdateCookieSnapshotOwned(_ context.Context, _ string, cookies string, snapshot []CookieSnapshot) error { + r.updatedCookies = cookies + r.updatedSnapshot = snapshot + return r.snapshotErr +} + +// ClearTokens 记录旧连接 Token 清理请求。 +func (r *fakeQRLoginRepository) ClearTokens(context.Context, string) error { + r.clearCount++ + return r.clearErr +} + +// fakeQRLoginLifecycle 是扫码登录后续动作测试用的生命周期端口替身。 +type fakeQRLoginLifecycle struct { + // calls 记录生命周期端口调用次数。 + calls int + // userID 保存生命周期端口收到的用户标识。 + userID int64 + // accountID 保存生命周期端口收到的账号标识。 + accountID string + // cleanupErr 保存生命周期端口收到的旧 Token 清理失败。 + cleanupErr error +} + +// AfterSuccessfulQRLogin 记录扫码成功后的生命周期调用参数。 +func (l *fakeQRLoginLifecycle) AfterSuccessfulQRLogin(_ context.Context, userID int64, accountID string) { + l.calls++ + l.userID = userID + l.accountID = accountID +} + +// ReportQRLoginCleanupFailure 记录旧 Token 清理失败,验证该错误不阻断登录成功结果。 +func (l *fakeQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, _ string, err error) { + l.cleanupErr = err +} + +// TestNewQRLoginServiceRequiresPorts 验证扫码登录应用服务拒绝缺失依赖。 +func TestNewQRLoginServiceRequiresPorts(t *testing.T) { + // repository 是满足凭证端口的测试替身。 + repository := &fakeQRLoginRepository{} + // lifecycle 是满足登录后续动作端口的测试替身。 + lifecycle := &fakeQRLoginLifecycle{} + // cases 保存构造阶段必须拒绝的依赖缺失场景。 + cases := []struct { + // name 是当前构造失败场景名称。 + name string + // repository 是当前场景的凭证端口。 + repository QRLoginRepository + // lifecycle 是当前场景的生命周期端口。 + lifecycle QRLoginLifecycle + }{ + {name: "缺少凭证端口", lifecycle: lifecycle}, + {name: "缺少生命周期端口", repository: repository}, + } + // testCase 表示当前遍历的构造失败场景。 + for _, testCase := range cases { + t.Run(testCase.name, func(t *testing.T) { + // err 保存当前场景的构造结果错误。 + _, err := NewQRLoginService(testCase.repository, testCase.lifecycle) + if err == nil { + t.Fatal("缺少必需端口时应构造失败") + } + }) + } +} + +// TestQRLoginPersistSuccessCreatesAccountAndHidesCookie 验证新账号成功写入及敏感值不进入结果。 +func TestQRLoginPersistSuccessCreatesAccountAndHidesCookie(t *testing.T) { + // repository 返回账号不存在,模拟首次扫码登录。 + repository := &fakeQRLoginRepository{findErr: ErrNotFound} + // lifecycle 记录成功后的审计与运行时同步调用。 + lifecycle := &fakeQRLoginLifecycle{} + // service 是待验证的扫码登录应用服务。 + service, err := NewQRLoginService(repository, lifecycle) + if err != nil { + t.Fatalf("构造扫码登录服务失败: %v", err) + } + // input 携带平台扫码成功结果;Cookie 只允许进入凭证端口。 + input := QRLoginInput{ + UserID: 7, ScannedAccountID: "unb-7", Cookies: "unb=unb-7; token=secret-cookie", + Snapshot: []CookieSnapshot{{Name: "unb", Value: "unb-7", Domain: ".example.com", Path: "/"}}, + } + // result 保存应用服务返回的非敏感成功结果。 + result, err := service.PersistSuccess(context.Background(), input) + if err != nil { + t.Fatalf("扫码登录持久化失败: %v", err) + } + if result.AccountID != "unb-7" || !result.IsNew || lifecycle.calls != 1 { + t.Fatalf("成功结果异常: result=%+v lifecycle=%+v", result, lifecycle) + } + if repository.createdCookies != input.Cookies || len(repository.updatedSnapshot) != 1 || repository.clearCount != 1 { + t.Fatalf("凭证端口调用异常: %+v", repository) + } + // encodedResult 是 HTTP 层可能序列化的应用结果,用于确认不会泄露 Cookie 明文。 + encodedResult, marshalErr := json.Marshal(result) + if marshalErr != nil { + t.Fatalf("序列化结果失败: %v", marshalErr) + } + if strings.Contains(string(encodedResult), "secret-cookie") { + t.Fatalf("应用结果泄露 Cookie: %s", encodedResult) + } +} + +// TestQRLoginPersistSuccessUpdatesOwnedAccount 验证已有账号归属通过后更新扁平 Cookie。 +func TestQRLoginPersistSuccessUpdatesOwnedAccount(t *testing.T) { + // repository 返回当前用户拥有的账号,且没有完整快照。 + repository := &fakeQRLoginRepository{account: QRLoginAccount{ID: "unb-7", UserID: 7}} + // lifecycle 记录成功后的后续动作。 + lifecycle := &fakeQRLoginLifecycle{} + // service 是待验证的扫码登录应用服务。 + service, err := NewQRLoginService(repository, lifecycle) + if err != nil { + t.Fatalf("构造扫码登录服务失败: %v", err) + } + // result 保存已有账号更新后的非敏感结果。 + result, err := service.PersistSuccess(context.Background(), QRLoginInput{ + UserID: 7, ScannedAccountID: "unb-7", Cookies: "unb=unb-7; token=rotated", + }) + if err != nil || result.AccountID != "unb-7" || result.IsNew { + t.Fatalf("已有账号更新异常: result=%+v err=%v", result, err) + } + if repository.updatedCookies == "" || lifecycle.accountID != "unb-7" { + t.Fatalf("已有账号更新端口未调用: %+v %+v", repository, lifecycle) + } +} + +// TestQRLoginPersistRejectsOwnershipAndMismatch 验证跨用户、目标不一致和不完整结果均不会写入凭证。 +func TestQRLoginPersistRejectsOwnershipAndMismatch(t *testing.T) { + // ownershipRepository 返回其他用户拥有的账号。 + ownershipRepository := &fakeQRLoginRepository{account: QRLoginAccount{ID: "unb-7", UserID: 8}} + // lifecycle 是不应被失败流程调用的生命周期替身。 + lifecycle := &fakeQRLoginLifecycle{} + // ownershipService 是待验证跨用户拒绝服务。 + ownershipService, err := NewQRLoginService(ownershipRepository, lifecycle) + if err != nil { + t.Fatalf("构造归属服务失败: %v", err) + } + // _, ownershipErr 保存跨用户写入结果。 + _, ownershipErr := ownershipService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"}) + if !errors.Is(ownershipErr, ErrForbidden) || lifecycle.calls != 0 { + t.Fatalf("跨用户账号未被拒绝: err=%v lifecycle=%d", ownershipErr, lifecycle.calls) + } + + // mismatchService 是待验证扫码账号与目标账号不一致的服务。 + mismatchService, err := NewQRLoginService(&fakeQRLoginRepository{}, lifecycle) + if err != nil { + t.Fatalf("构造不一致服务失败: %v", err) + } + // _, mismatchErr 保存账号不一致结果。 + _, mismatchErr := mismatchService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", TargetAccountID: "unb-8", Cookies: "secret"}) + if !errors.Is(mismatchErr, ErrQRLoginAccountMismatch) { + t.Fatalf("账号不一致未被拒绝: %v", mismatchErr) + } + + // incompleteService 是待验证缺少 Cookie 的服务。 + incompleteService, err := NewQRLoginService(&fakeQRLoginRepository{}, lifecycle) + if err != nil { + t.Fatalf("构造不完整结果服务失败: %v", err) + } + // _, incompleteErr 保存不完整结果错误。 + _, incompleteErr := incompleteService.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7"}) + if !errors.Is(incompleteErr, ErrQRLoginIncomplete) { + t.Fatalf("不完整扫码结果未被拒绝: %v", incompleteErr) + } +} + +// TestQRLoginPersistPropagatesWriteFailure 验证凭证写入失败时不触发生命周期动作。 +func TestQRLoginPersistPropagatesWriteFailure(t *testing.T) { + // writeErr 是测试凭证端口返回的持久化错误。 + writeErr := errors.New("凭证存储不可用") + // repository 模拟新账号写入失败。 + repository := &fakeQRLoginRepository{findErr: ErrNotFound, createErr: writeErr} + // lifecycle 记录不应发生的成功后续动作。 + lifecycle := &fakeQRLoginLifecycle{} + // service 是待验证的扫码登录服务。 + service, err := NewQRLoginService(repository, lifecycle) + if err != nil { + t.Fatalf("构造写入失败服务失败: %v", err) + } + // _, persistErr 保存凭证端口错误。 + _, persistErr := service.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"}) + if !errors.Is(persistErr, writeErr) || lifecycle.calls != 0 { + t.Fatalf("凭证写入错误未正确传播: err=%v lifecycle=%d", persistErr, lifecycle.calls) + } +} + +// TestQRLoginPersistIgnoresTokenCleanupFailure 验证凭证已保存时旧 Token 清理失败不会伪装成登录失败。 +func TestQRLoginPersistIgnoresTokenCleanupFailure(t *testing.T) { + // repository 模拟已有账号更新成功但旧 Token 清理失败。 + repository := &fakeQRLoginRepository{ + account: QRLoginAccount{ID: "unb-7", UserID: 7}, + clearErr: errors.New("旧 Token 清理失败"), + } + // lifecycle 记录凭证保存成功后的后续动作。 + lifecycle := &fakeQRLoginLifecycle{} + // service 是待验证的扫码登录服务。 + service, err := NewQRLoginService(repository, lifecycle) + if err != nil { + t.Fatalf("构造 Token 清理失败服务失败: %v", err) + } + // result、persistErr 保存凭证成功与否以及应用错误。 + result, persistErr := service.PersistSuccess(context.Background(), QRLoginInput{UserID: 7, ScannedAccountID: "unb-7", Cookies: "secret"}) + if persistErr != nil || result.AccountID != "unb-7" || lifecycle.calls != 1 { + t.Fatalf("Token 清理失败不应阻断登录: result=%+v err=%v lifecycle=%d", result, persistErr, lifecycle.calls) + } +} diff --git a/internal/application/chat/service.go b/internal/application/chat/service.go new file mode 100644 index 0000000..c54d777 --- /dev/null +++ b/internal/application/chat/service.go @@ -0,0 +1,119 @@ +// Package chat 提供聊天历史等 HTTP 用例所需的应用层编排,不依赖 HTTP 或数据库模型。 +package chat + +import ( + "context" + "errors" + "strings" +) + +// ErrInvalidInput 表示聊天历史查询缺少必要的非敏感标识。 +var ErrInvalidInput = errors.New("聊天历史查询参数无效") + +// Message 是聊天历史用例对外暴露的非敏感消息模型。 +type Message struct { + // ID 是本地消息主键。 + ID int64 + // AccountID 是消息所属账号标识,不包含账号凭证。 + AccountID string + // ChatID 是平台聊天会话标识。 + ChatID string + // MessageKey 是消息幂等键。 + MessageKey string + // Direction 是消息方向,例如 incoming 或 outgoing。 + Direction string + // SenderID 是平台发送者标识。 + SenderID string + // SenderName 是发送者展示名称。 + SenderName string + // MessageType 是消息内容类型。 + MessageType string + // Content 是文本或媒体地址,不包含平台凭证。 + Content string + // Status 是消息投递状态。 + Status string + // SentAt 是消息发送时间的 Unix 秒时间戳。 + SentAt int64 +} + +// Session 是聊天历史用例使用的会话摘要,不包含 Cookie 或其他秘密。 +type Session struct { + // AccountID 是会话所属账号标识。 + AccountID string + // ChatID 是平台聊天会话标识。 + ChatID string + // BuyerID 是买家平台标识。 + BuyerID string + // BuyerName 是买家展示名称。 + BuyerName string + // BuyerAvatar 是买家头像地址。 + BuyerAvatar string + // ItemID 是会话关联商品标识。 + ItemID string + // ItemTitle 是会话关联商品标题。 + ItemTitle string + // LastMessage 是最近消息摘要。 + LastMessage string + // LastMessageAt 是最近消息时间的 Unix 秒时间戳。 + LastMessageAt int64 + // UnreadCount 是当前会话未读消息数量。 + UnreadCount int +} + +// Page 是聊天历史查询的分页结果。 +type Page struct { + // Messages 是按时间正序排列的当前页消息。 + Messages []Message + // Session 是当前会话摘要;找不到摘要时保持零值。 + Session Session + // HasMore 表示是否可能还有更早消息。 + HasMore bool +} + +// Repository 定义聊天历史用例需要的最小持久化能力。 +type Repository interface { + // ListMessages 按用户归属查询指定账号和会话的消息。 + ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]Message, error) + // ListSessions 按用户归属查询账号的会话摘要。 + ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]Session, error) +} + +// Service 编排聊天历史查询,不持有 HTTP 请求或数据库连接。 +type Service struct { + // repository 保存由调用方注入的最小持久化端口。 + repository Repository +} + +// New 创建聊天历史应用服务;空端口会导致构造结果不可用。 +func New(repository Repository) *Service { + return &Service{repository: repository} +} + +// ListStoredMessages 查询当前用户有权访问的本地聊天历史。 +// userID 用于归属过滤,accountID/chatID 定位账号和会话,beforeID 控制向更早消息翻页,limit 控制页大小; +// 返回的 Page 只含非敏感消息和会话摘要,底层端口错误原样返回。 +func (s *Service) ListStoredMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) (Page, error) { + accountID = strings.TrimSpace(accountID) + chatID = strings.TrimSpace(chatID) + if s == nil || s.repository == nil || userID <= 0 || accountID == "" || chatID == "" { + return Page{}, ErrInvalidInput + } + // messages 保存按用户归属过滤后的聊天消息。 + messages, err := s.repository.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) + if err != nil { + return Page{}, err + } + // session 保存当前会话摘要;查询失败时保持零值。 + var session Session + // sessions 和 sessionErr 保存会话摘要列表及其查询错误;摘要失败不影响消息结果。 + if sessions, sessionErr := s.repository.ListSessions(ctx, userID, accountID, 500); sessionErr == nil { + // candidate 保存当前遍历到的会话摘要。 + for _, candidate := range sessions { + if candidate.ChatID == chatID { + session = candidate + break + } + } + } + return Page{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil +} diff --git a/internal/application/chat/service_test.go b/internal/application/chat/service_test.go new file mode 100644 index 0000000..1e27aba --- /dev/null +++ b/internal/application/chat/service_test.go @@ -0,0 +1,134 @@ +package chat + +import ( + "context" + "errors" + "testing" +) + +// fakeRepository 保存测试聊天历史数据,并记录最近一次用户归属参数。 +type fakeRepository struct { + // messages 是模拟聊天消息列表。 + messages []Message + // sessions 是模拟会话摘要列表。 + sessions []Session + // messageErr 是消息查询需要返回的错误。 + messageErr error + // sessionErr 是会话查询需要返回的错误。 + sessionErr error + // userID 保存最近一次消息查询使用的用户 ID。 + userID int64 + // allowedUserID 是允许读取测试账号的用户 ID;其他用户模拟归属拒绝。 + allowedUserID int64 +} + +// ListMessages 返回测试消息,并记录用户归属参数。 +func (r *fakeRepository) ListMessages(_ context.Context, userID int64, _ string, _ string, _ int64, _ int) ([]Message, error) { + r.userID = userID + if r.allowedUserID != 0 && userID != r.allowedUserID { + return nil, errors.New("cross-user access denied") + } + return r.messages, r.messageErr +} + +// ListSessions 返回测试会话摘要或预设错误。 +func (r *fakeRepository) ListSessions(_ context.Context, _ int64, _ string, _ int) ([]Session, error) { + return r.sessions, r.sessionErr +} + +// TestListStoredMessagesUsesUserScopedPort 验证查询会把用户 ID 传到归属端口并组装分页结果。 +func TestListStoredMessagesUsesUserScopedPort(t *testing.T) { + // repository 是带有一条消息和会话摘要的测试端口。 + repository := &fakeRepository{ + messages: []Message{{ID: 1, ChatID: "chat-1", Content: "你好"}}, + sessions: []Session{{ChatID: "chat-1", BuyerName: "买家甲"}}, + } + // service 是使用测试端口构造的聊天历史服务。 + service := New(repository) + // page 保存当前用户读取到的分页结果。 + page, err := service.ListStoredMessages(context.Background(), 42, "account-1", "chat-1", 0, 1) + if err != nil { + t.Fatalf("ListStoredMessages() error = %v", err) + } + if repository.userID != 42 || len(page.Messages) != 1 || page.Session.BuyerName != "买家甲" || !page.HasMore { + t.Fatalf("unexpected page=%+v userID=%d", page, repository.userID) + } +} + +// TestListStoredMessagesRejectsInvalidIdentity 验证无效用户或账号标识会在访问端口前失败。 +func TestListStoredMessagesRejectsInvalidIdentity(t *testing.T) { + // service 是不应被调用的测试服务。 + service := New(&fakeRepository{}) + // testCase 表示当前待验证的无效身份场景。 + for _, testCase := range []struct { + // name 是当前无效输入场景名称。 + name string + // userID 是当前请求用户标识。 + userID int64 + // accountID 是当前账号标识。 + accountID string + // chatID 是当前会话标识。 + chatID string + }{ + {name: "missing-user", userID: 0, accountID: "account-1", chatID: "chat-1"}, + {name: "missing-account", userID: 1, accountID: "", chatID: "chat-1"}, + {name: "missing-chat", userID: 1, accountID: "account-1", chatID: ""}, + } { + t.Run(testCase.name, func(t *testing.T) { + // err 保存当前无效请求返回的应用错误。 + _, err := service.ListStoredMessages(context.Background(), testCase.userID, testCase.accountID, testCase.chatID, 0, 20) + if !errors.Is(err, ErrInvalidInput) { + t.Fatalf("error = %v, want ErrInvalidInput", err) + } + }) + } +} + +// TestListStoredMessagesRejectsUnavailableService 验证未装配端口或空服务不会触发 panic。 +func TestListStoredMessagesRejectsUnavailableService(t *testing.T) { + // nilService 表示尚未完成依赖装配的聊天服务指针。 + var nilService *Service + // service 表示当前待验证的不可用聊天服务实例。 + for _, service := range []*Service{nilService, New(nil)} { + // err 保存不可用服务返回的应用错误。 + _, err := service.ListStoredMessages(context.Background(), 1, "account-1", "chat-1", 0, 20) + if !errors.Is(err, ErrInvalidInput) { + t.Fatalf("error = %v, want ErrInvalidInput", err) + } + } +} + +// TestListStoredMessagesPropagatesRepositoryFailure 验证消息持久化失败不会被伪装成成功空页。 +func TestListStoredMessagesPropagatesRepositoryFailure(t *testing.T) { + // wantErr 是模拟底层查询失败的稳定错误。 + wantErr := errors.New("repository unavailable") + // service 是返回预设错误的聊天历史服务。 + service := New(&fakeRepository{messageErr: wantErr}) + // _, err 保存应用服务返回的分页结果和错误。 + _, err := service.ListStoredMessages(context.Background(), 7, "account-1", "chat-1", 0, 20) + if !errors.Is(err, wantErr) { + t.Fatalf("error = %v, want %v", err, wantErr) + } +} + +// TestListStoredMessagesKeepsMessagesWhenSessionLookupFails 验证摘要查询失败不会丢弃已成功读取的消息。 +func TestListStoredMessagesKeepsMessagesWhenSessionLookupFails(t *testing.T) { + // service 是消息成功但会话摘要失败的聊天历史服务。 + service := New(&fakeRepository{messages: []Message{{ID: 2, ChatID: "chat-1"}}, sessionErr: errors.New("session unavailable")}) + // page 和 err 保存应用服务返回的消息页及错误。 + page, err := service.ListStoredMessages(context.Background(), 1, "account-1", "chat-1", 0, 20) + if err != nil || len(page.Messages) != 1 || page.Session.ChatID != "" { + t.Fatalf("page=%+v err=%v", page, err) + } +} + +// TestListStoredMessagesDoesNotCrossUserBoundary 验证其他用户的账号消息不会被应用服务当作空结果返回。 +func TestListStoredMessagesDoesNotCrossUserBoundary(t *testing.T) { + // service 是只允许用户 7 读取账号的聊天历史服务。 + service := New(&fakeRepository{allowedUserID: 7, messages: []Message{{ID: 1}}}) + // err 保存用户 8 尝试读取用户 7 账号时的归属错误。 + _, err := service.ListStoredMessages(context.Background(), 8, "account-1", "chat-1", 0, 20) + if err == nil || err.Error() != "cross-user access denied" { + t.Fatalf("cross-user error = %v", err) + } +} diff --git a/internal/db/notification_outbox_test.go b/internal/db/notification_outbox_test.go index 0bf6016..d4f9e9b 100644 --- a/internal/db/notification_outbox_test.go +++ b/internal/db/notification_outbox_test.go @@ -156,3 +156,95 @@ func TestNotificationOutboxPermanentRetry(t *testing.T) { t.Fatalf("status=%q want dead", status) } } + +// TestNotificationUncertainOutboxScope 验证不确定通知按用户隔离、管理员可汇总且不返回正文。 +func TestNotificationUncertainOutboxScope(t *testing.T) { + // store、cleanup 保存测试数据库及其关闭责任。 + store, cleanup := newTestDB(t) + defer cleanup() + // ctx 保存本测试使用的根上下文。 + ctx := context.Background() + // createUser 创建隔离测试用户并返回其数据库标识。 + createUser := func(username string) int64 { + // ok、err 保存用户创建结果和数据库错误。 + ok, err := store.Users.Create(ctx, username, username+"@example.com", "pw") + if err != nil || !ok { + t.Fatalf("create user %s: ok=%v err=%v", username, ok, err) + } + // user、err 保存新用户实体及查询错误。 + user, err := store.Users.GetByUsername(ctx, username) + if err != nil { + t.Fatalf("get user %s: %v", username, err) + } + return user.ID + } + // userOneID、userTwoID 保存两个相互隔离的渠道所属用户。 + userOneID, userTwoID := createUser("uncertain-one"), createUser("uncertain-two") + // createChannel 创建属于指定用户的通知渠道并返回渠道标识。 + createChannel := func(userID int64) int64 { + // result、err 保存通知渠道插入结果和数据库错误。 + result, err := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,?,?)`, "ops", "webhook", `{}`, 1, userID) + if err != nil { + t.Fatalf("create channel: %v", err) + } + // channelID、err 保存新渠道标识和读取标识错误。 + channelID, err := result.LastInsertId() + if err != nil { + t.Fatalf("channel id: %v", err) + } + return channelID + } + // channelOneID、channelTwoID 保存两个用户各自拥有的渠道。 + channelOneID, channelTwoID := createChannel(userOneID), createChannel(userTwoID) + // enqueueAndMarkUncertain 写入一条带敏感正文的 outbox 并推进到 uncertain 状态。 + enqueueAndMarkUncertain := func(channelID int64, eventType string) { + // err 保存通知 outbox 写入错误。 + if err := store.Notifications.EnqueueOutbox(ctx, []NotificationOutboxInput{{ChannelID: channelID, EventType: eventType, Body: "不应出现在运维响应中的正文"}}); err != nil { + t.Fatalf("enqueue: %v", err) + } + // claimed、err 保存 worker 抢占结果和数据库错误。 + claimed, err := store.Notifications.ClaimOutbox(ctx, "worker-"+eventType, time.Unix(100, 0), 10) + if err != nil || len(claimed) != 1 { + t.Fatalf("claim: messages=%+v err=%v", claimed, err) + } + // marked、err 保存不确定状态转移结果和数据库错误。 + marked, err := store.Notifications.MarkOutboxUncertain(ctx, claimed[0].ID, "worker-"+eventType, "含凭证的远端错误不应暴露") + if err != nil || !marked { + t.Fatalf("mark uncertain: marked=%v err=%v", marked, err) + } + } + enqueueAndMarkUncertain(channelOneID, "user-one-event") + enqueueAndMarkUncertain(channelTwoID, "user-two-event") + + // userOneItems、err 保存用户一可见摘要和查询错误。 + userOneItems, err := store.Notifications.ListUncertainOutboxForUser(ctx, userOneID, 10) + if err != nil || len(userOneItems) != 1 || userOneItems[0].OwnerUserID != userOneID || userOneItems[0].EventType != "user-one-event" || !userOneItems[0].HasError { + t.Fatalf("user scope: items=%+v err=%v", userOneItems, err) + } + // userOneTotal、err 保存用户一的不确定通知数量和统计错误。 + userOneTotal, err := store.Notifications.CountUncertainOutboxForUser(ctx, userOneID) + if err != nil || userOneTotal != 1 { + t.Fatalf("user count=%d err=%v", userOneTotal, err) + } + // defaultLimitItems、err 保存使用非法分页值时回退默认上限的结果和查询错误。 + defaultLimitItems, err := store.Notifications.ListUncertainOutboxForUser(ctx, userOneID, 0) + if err != nil || len(defaultLimitItems) != 1 { + t.Fatalf("default limit items=%+v err=%v", defaultLimitItems, err) + } + // adminItems、err 保存管理员可见的全局摘要和查询错误。 + adminItems, err := store.Notifications.ListUncertainOutboxForAdmin(ctx, 101) + if err != nil || len(adminItems) != 2 { + t.Fatalf("admin scope: items=%+v err=%v", adminItems, err) + } + // adminTotal、err 保存管理员全局统计数量和统计错误。 + adminTotal, err := store.Notifications.CountUncertainOutboxForAdmin(ctx) + if err != nil || adminTotal != 2 { + t.Fatalf("admin count=%d err=%v", adminTotal, err) + } + // item 表示当前遍历到的管理员可见通知摘要。 + for _, item := range adminItems { + if item.OwnerUserID == 0 || item.EventType == "" || item.AttemptCount == 0 || item.UncertainAt == 0 { + t.Fatalf("incomplete non-sensitive summary: %+v", item) + } + } +} diff --git a/internal/db/notifications.go b/internal/db/notifications.go index 4c56bfa..a61d5ab 100644 --- a/internal/db/notifications.go +++ b/internal/db/notifications.go @@ -43,13 +43,121 @@ type NotificationOutboxInput struct { // NotificationOutboxMessage 保存通知Outbox消息,供当前处理流程使用 type NotificationOutboxMessage struct { - ID int64 - ChannelID int64 - EventType string - Body string + // ID 是通知 outbox 记录的稳定标识,仅用于运维定位,不代表正文内容。 + ID int64 + // ChannelID 是通知渠道标识,用于按渠道归属执行权限过滤。 + ChannelID int64 + // EventType 是通知事件类型,不包含通知正文或渠道配置。 + EventType string + // Body 是发送给渠道的正文;仅供内部 worker 使用,禁止进入运维查询响应。 + Body string + // AttemptCount 是当前记录已经尝试发送的次数。 AttemptCount int } +// NotificationUncertainSummary 是外部发送完成但本地确认失败的通知摘要。 +// 该模型刻意不携带正文、渠道配置和最后错误文本,避免运维接口泄露敏感信息。 +type NotificationUncertainSummary struct { + // ID 是通知 outbox 记录的稳定标识。 + ID int64 + // ChannelID 是关联通知渠道标识。 + ChannelID int64 + // OwnerUserID 是通知渠道所属用户;普通用户查询只返回自己的记录。 + OwnerUserID int64 + // EventType 是通知事件分类。 + EventType string + // AttemptCount 是进入不确定状态前的发送尝试次数。 + AttemptCount int + // UncertainAt 是进入不确定状态的 Unix 秒时间戳。 + UncertainAt int64 + // HasError 表示数据库是否记录了本地确认错误,但不暴露错误原文。 + HasError bool +} + +// ListUncertainOutboxForUser 查询指定用户拥有渠道的不确定通知摘要。 +// 查询只返回元数据,不读取正文、加密渠道配置或凭证;limit 会被限制在 1 到 100 之间。 +func (n *Notifications) ListUncertainOutboxForUser(ctx context.Context, userID int64, limit int) ([]NotificationUncertainSummary, error) { + return n.listUncertainOutbox(ctx, &userID, limit) +} + +// ListUncertainOutboxForAdmin 查询所有用户的不确定通知摘要,供管理员运维核对使用。 +// 管理员结果包含渠道所属用户 ID,但仍不包含正文、错误原文或任何凭证。 +func (n *Notifications) ListUncertainOutboxForAdmin(ctx context.Context, limit int) ([]NotificationUncertainSummary, error) { + return n.listUncertainOutbox(ctx, nil, limit) +} + +// listUncertainOutbox 按可选用户归属读取不确定通知元数据。 +// ownerUserID 非空时强制限制到该用户;为空时仅供管理员调用并返回全局结果。 +func (n *Notifications) listUncertainOutbox(ctx context.Context, ownerUserID *int64, limit int) ([]NotificationUncertainSummary, error) { + if limit <= 0 || limit > 100 { + limit = 20 + } + // query 保存按用户隔离的不确定通知元数据查询语句,不选择正文或错误原文。 + query := `SELECT no.id, no.channel_id, COALESCE(nc.user_id,0), no.event_type, + no.attempt_count, no.uncertain_at, CASE WHEN no.last_error<>'' THEN 1 ELSE 0 END + FROM notification_outbox no + LEFT JOIN notification_channels nc ON nc.id=no.channel_id + WHERE no.status='uncertain'` + // args 保存 query 中用户归属与分页参数的绑定值。 + args := make([]any, 0, 2) + if ownerUserID != nil { + query += ` AND nc.user_id=?` + args = append(args, *ownerUserID) + } + query += ` ORDER BY no.uncertain_at DESC, no.id DESC LIMIT ?` + args = append(args, limit) + // rows 保存按权限过滤后读取到的通知摘要行;err 保存查询失败原因。 + rows, err := n.DB.QueryContext(ctx, query, args...) + if err != nil { + return nil, err + } + defer rows.Close() + // summaries 保存当前用户或管理员可见的不确定通知摘要。 + summaries := make([]NotificationUncertainSummary, 0) + for rows.Next() { + // summary 保存当前遍历到的通知不确定状态摘要;hasError 是内部错误存在标记。 + var summary NotificationUncertainSummary + // hasError 保存数据库中是否存在本地确认错误的布尔整型值。 + var hasError int + // scanErr 保存当前摘要行读取失败的数据库错误。 + if scanErr := rows.Scan(&summary.ID, &summary.ChannelID, &summary.OwnerUserID, &summary.EventType, &summary.AttemptCount, &summary.UncertainAt, &hasError); scanErr != nil { + return nil, scanErr + } + summary.HasError = hasError != 0 + summaries = append(summaries, summary) + } + return summaries, rows.Err() +} + +// CountUncertainOutboxForUser 统计指定用户拥有渠道的不确定通知数量,不读取正文或错误原文。 +func (n *Notifications) CountUncertainOutboxForUser(ctx context.Context, userID int64) (int, error) { + return n.countUncertainOutbox(ctx, &userID) +} + +// CountUncertainOutboxForAdmin 统计全局不确定通知数量,供管理员运维看板使用。 +func (n *Notifications) CountUncertainOutboxForAdmin(ctx context.Context) (int, error) { + return n.countUncertainOutbox(ctx, nil) +} + +// countUncertainOutbox 按可选渠道所属用户统计不确定通知数量。 +func (n *Notifications) countUncertainOutbox(ctx context.Context, ownerUserID *int64) (int, error) { + // query 保存不确定通知数量统计语句,不读取正文或错误原文。 + query := `SELECT COUNT(*) FROM notification_outbox no LEFT JOIN notification_channels nc ON nc.id=no.channel_id WHERE no.status='uncertain'` + // args 保存可选用户归属的绑定参数。 + args := make([]any, 0, 1) + if ownerUserID != nil { + query += ` AND nc.user_id=?` + args = append(args, *ownerUserID) + } + // count 保存满足状态与归属过滤条件的通知数量。 + var count int + // scanErr 保存读取统计结果时的数据库错误。 + if scanErr := n.DB.QueryRowContext(ctx, query, args...).Scan(&count); scanErr != nil { + return 0, scanErr + } + return count, nil +} + // NotificationBindingRow 是用户账号与通知渠道的绑定摘要。 type NotificationBindingRow struct { // ID 是绑定记录标识。 diff --git a/internal/server/account_login_repository.go b/internal/server/account_login_repository.go index 8cf41a7..42f5fbc 100644 --- a/internal/server/account_login_repository.go +++ b/internal/server/account_login_repository.go @@ -102,6 +102,53 @@ func (r storeAccountLoginRepository) UpdateFlatCookieOwned(ctx context.Context, return r.store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()) } +// FindAccount 只读取扫码登录所需的账号归属,不解密 Cookie、密码或 metadata。 +func (r storeAccountLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { + // ownerID 保存数据库返回的账号所属用户标识。 + ownerID, err := r.store.Cookies.GetOwnerID(ctx, accountID) + if err != nil { + if errors.Is(err, db.ErrNotFound) { + return accountapp.QRLoginAccount{}, accountapp.ErrNotFound + } + return accountapp.QRLoginAccount{}, err + } + return accountapp.QRLoginAccount{ID: accountID, UserID: ownerID}, nil +} + +// UpdateQRCookieFlatOwned 更新扫码登录账号的扁平 Cookie,并清除旧的完整快照。 +func (r storeAccountLoginRepository) UpdateQRCookieFlatOwned(ctx context.Context, accountID, cookies string) error { + // detail 保存平台运行视图;该窄视图只在凭证适配器内部读取 metadata。 + detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) + if err != nil { + return err + } + // metadata 保存移除旧快照后的加密 metadata 文本。 + metadata := cookierefresh.MetadataWithoutSnapshot(detail.MetadataJSON) + return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) +} + +// UpdateQRCookieSnapshotOwned 更新扫码 Cookie,并把完整快照合并进加密 metadata。 +func (r storeAccountLoginRepository) UpdateQRCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { + // detail 保存平台运行视图;完整 metadata 不向应用服务层泄露。 + detail, err := r.store.Cookies.GetCookiePlatformRuntimeData(ctx, accountID) + if err != nil { + return err + } + // browserSnapshot 保存转换后的浏览器 Cookie 快照,仅在数据库适配器内使用。 + browserSnapshot := make([]cookierefresh.BrowserCookie, 0, len(snapshot)) + // snapshotEntry 表示当前待转换的应用层 Cookie 快照。 + for _, snapshotEntry := range snapshot { + browserSnapshot = append(browserSnapshot, cookierefresh.BrowserCookie{ + Name: snapshotEntry.Name, Value: snapshotEntry.Value, Domain: snapshotEntry.Domain, + Path: snapshotEntry.Path, Expires: snapshotEntry.Expires, HTTPOnly: snapshotEntry.HTTPOnly, + Secure: snapshotEntry.Secure, SameSite: snapshotEntry.SameSite, PartitionKey: snapshotEntry.PartitionKey, + }) + } + // metadata 保存快照合并后的加密 metadata 文本。 + metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, browserSnapshot) + return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()) +} + // UpdateRenewalCookie 委托 Cookie 与 metadata 更新。 func (r storeAccountLoginRepository) UpdateRenewalCookie(ctx context.Context, accountID, cookies, metadata string, at int64) error { return r.store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, at) @@ -151,5 +198,53 @@ func newStoreAccountLoginRepository(store *db.Store) accountLoginRepository { return storeAccountLoginRepository{store: store} } +// newStoreQRLoginRepository 从完整 Store 构造扫码登录应用服务所需的窄凭证端口。 +func newStoreQRLoginRepository(store *db.Store) accountapp.QRLoginRepository { + if store == nil || store.Cookies == nil { + return nil + } + return storeQRLoginRepository{store: store} +} + +// storeQRLoginRepository 将 Store 的扫码凭证能力限制在应用服务定义的窄端口内。 +type storeQRLoginRepository struct { + // store 提供数据库凭证读写能力,仅在本适配器内部访问。 + store *db.Store +} + +// LockCredentials 串行化扫码登录对同一账号的凭证变更。 +func (r storeQRLoginRepository) LockCredentials(accountID string) func() { + return r.store.LockAccountCredentials(accountID) +} + +// FindAccount 只返回账号存在性和归属,不读取 Cookie、密码或 metadata。 +func (r storeQRLoginRepository) FindAccount(ctx context.Context, accountID string) (accountapp.QRLoginAccount, error) { + return storeAccountLoginRepository(r).FindAccount(ctx, accountID) +} + +// CreateCookieOwned 创建扫码登录得到的新账号 Cookie。 +func (r storeQRLoginRepository) CreateCookieOwned(ctx context.Context, accountID, cookies string, userID int64) error { + return r.store.Cookies.CreateOwned(ctx, accountID, cookies, userID) +} + +// UpdateFlatCookieOwned 更新已有账号的扁平 Cookie,并清除完整快照。 +func (r storeQRLoginRepository) UpdateFlatCookieOwned(ctx context.Context, accountID, cookies string) error { + return storeAccountLoginRepository(r).UpdateQRCookieFlatOwned(ctx, accountID, cookies) +} + +// UpdateCookieSnapshotOwned 更新 Cookie 并合并完整浏览器快照。 +func (r storeQRLoginRepository) UpdateCookieSnapshotOwned(ctx context.Context, accountID, cookies string, snapshot []accountapp.CookieSnapshot) error { + return storeAccountLoginRepository(r).UpdateQRCookieSnapshotOwned(ctx, accountID, cookies, snapshot) +} + +// ClearTokens 清理扫码登录前遗留的旧连接 Token。 +func (r storeQRLoginRepository) ClearTokens(ctx context.Context, accountID string) error { + // clearErr 保存旧连接 Token 清理结果;凭证已成功写入时该错误不阻断扫码登录。 + return storeAccountLoginRepository(r).ClearTokens(ctx, accountID) +} + // 确保 Store 适配器始终覆盖账号登录服务所需的全部能力。 var _ accountLoginRepository = storeAccountLoginRepository{} + +// 确保扫码凭证适配器始终覆盖应用服务定义的最小端口。 +var _ accountapp.QRLoginRepository = storeQRLoginRepository{} diff --git a/internal/server/account_login_service.go b/internal/server/account_login_service.go index 614eff6..56bc15d 100644 --- a/internal/server/account_login_service.go +++ b/internal/server/account_login_service.go @@ -10,7 +10,6 @@ import ( accountapp "xianyu-go/internal/application/account" "xianyu-go/internal/db" - "xianyu-go/internal/xianyu/cookierefresh" "xianyu-go/internal/xianyu/protocol" ) @@ -22,6 +21,8 @@ type accountLoginService struct { repository accountLoginRepository // createApplication 提供已迁移的手动 Cookie 登录应用用例。 createApplication *accountapp.LoginService + // qrApplication 提供扫码成功凭证持久化应用用例;会话幂等状态仍由 Server 适配器拥有。 + qrApplication *accountapp.QRLoginService } // serverLoginLifecyclePort 将登录成功后的审计、资料刷新和运行时重启适配到应用层端口。 @@ -75,6 +76,11 @@ func newAccountLoginCreateApplication(server *Server) (*accountapp.LoginService, return accountapp.NewLoginService(serverLoginLifecyclePort{server: server}) } +// newAccountQRLoginApplication 构造扫码登录应用服务及其凭证、生命周期适配器。 +func newAccountQRLoginApplication(server *Server) (*accountapp.QRLoginService, error) { + return accountapp.NewQRLoginService(newStoreQRLoginRepository(server.Store), serverQRLoginLifecycle{server: server}) +} + // serverAccountProfilePort 将平台资料刷新适配为账号应用层 Port。 type serverAccountProfilePort struct { // server 提供平台会话、凭证锁、资料保存和运行时同步能力。 @@ -185,13 +191,34 @@ func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountC return nil } -// PersistQRLoginSuccess 持久化扫码登录结果,复用会话级幂等锁和账号重启流程。 -func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) { - return svc.persistQRLoginSuccessCore(ctx, userID, sessionID, result, targetAccountID) +// serverQRLoginLifecycle 将扫码登录成功后的审计、资料刷新和运行时同步适配到应用端口。 +type serverQRLoginLifecycle struct { + // server 提供审计、资料刷新、自动化唤醒和账号运行时管理能力。 + server *Server } -// persistQRLoginSuccessCore 执行扫码结果校验、凭证合并、登录审计和账号重启。 -func (svc *accountLoginService) persistQRLoginSuccessCore(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) { +// AfterSuccessfulQRLogin 在凭证锁释放后执行扫码登录成功的后续编排。 +func (p serverQRLoginLifecycle) AfterSuccessfulQRLogin(ctx context.Context, userID int64, accountID string) { + if p.server == nil { + return + } + p.server.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功") + p.server.accountLoginApplication().refreshAndRestartAccount(ctx, userID, accountID) + p.server.wakeCredentialBlockedAutomation(ctx, accountID) +} + +// ReportQRLoginCleanupFailure 记录扫码登录后旧 Token 清理失败,不暴露 Cookie 内容且不回滚已写入凭证。 +func (p serverQRLoginLifecycle) ReportQRLoginCleanupFailure(_ context.Context, accountID string, err error) { + if p.server != nil && p.server.Logger != nil { + p.server.Logger.Warn("扫码登录后清理旧连接凭证失败", "cookie_id", accountID, "err", err) + } +} + +// PersistQRLoginSuccess 将 HTTP/平台 map 适配为纯应用 DTO,并复用会话级幂等锁。 +func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) { + if svc == nil || svc.server == nil || svc.qrApplication == nil { + return qrLoginPersistence{}, errors.New("扫码登录应用服务未初始化") + } // s 是当前账号登录应用服务依赖的 Server。 s := svc.server // lockValue 和 persistMu 保证同一扫码会话只执行一次持久化。 @@ -214,103 +241,44 @@ func (svc *accountLoginService) persistQRLoginSuccessCore(ctx context.Context, u return persisted, nil } s.qrMu.Unlock() - // cookies、cookieSnapshot 和 snapshotComplete 保存平台登录凭证及其完整 Cookie Jar。 + // cookies 保存平台返回的登录 Cookie 明文,仅在 Server 到应用端口的调用边界短暂存在。 cookies := qrString(result, "cookies") - // cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie Jar。 + // cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie 快照及其完整性。 cookieSnapshot, snapshotComplete := qrCookieSnapshot(result) - // scannedAccountID 是扫码结果中的平台账号标识。 + // scannedAccountID 保存从结果字段或 Cookie 解析出的平台账号标识。 scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"])) - if cookies == "" || scannedAccountID == "" { - return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb") - } - // accountID 是最终写入的账号标识。 - accountID := strings.TrimSpace(targetAccountID) - if accountID == "" { - accountID = scannedAccountID - } else if accountID != scannedAccountID { - return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖") - } - - // isNew 标记本次扫码是否创建了新账号。 - isNew := false - // credentialUnlock 保护账号凭证写入和登录审计。 - credentialUnlock := svc.repository.LockCredentials(accountID) - // saveErr 保存账号凭证、Cookie Jar 和登录审计的事务错误。 - saveErr := func() error { - defer credentialUnlock() - // detail 和 err 保存待更新账号的凭证详情。 - detail, err := s.loadCookiePlatformDetail(ctx, accountID) - switch { - case errors.Is(err, db.ErrNotFound): - if targetAccountID != "" { - return errors.New("待重新授权账号不存在") - } - isNew = true - // err 表示创建扫码账号的错误。 - if err := svc.repository.CreateCookieOwned(ctx, accountID, cookies, userID); err != nil { - return err - } - if snapshotComplete { - // metadata 是新账号的完整 Cookie Jar 元数据。 - metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot) - // err 表示保存新账号 Cookie Jar 的错误。 - if err := svc.repository.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil { - return err - } - } - case err != nil: - return err - case detail == nil: - return db.ErrNotFound - case detail.UserID != userID: - if targetAccountID != "" { - return errors.New("待重新授权账号不属于当前用户") - } - return db.ErrForbidden - default: - if snapshotComplete { - // metadata 是已有账号合并后的 Cookie Jar 元数据。 - metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot) - // err 表示保存已有账号 Cookie Jar 的错误。 - if err := svc.repository.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil { - return err - } - // err 表示合并扁平 Cookie 的错误。 - } else if err := svc.repository.UpdateFlatCookieOwned(ctx, detail, cookies); err != nil { - return err - } + // input 保存转换后的纯应用扫码登录输入;Cookie 只交给凭证端口消费。 + input := accountapp.QRLoginInput{UserID: userID, ScannedAccountID: scannedAccountID, TargetAccountID: targetAccountID, Cookies: cookies} + if snapshotComplete { + input.Snapshot = make([]accountapp.CookieSnapshot, 0, len(cookieSnapshot)) + // cookie 保存当前浏览器 Cookie 快照,转换后不再依赖平台 DTO。 + for _, cookie := range cookieSnapshot { + input.Snapshot = append(input.Snapshot, accountapp.CookieSnapshot{ + Name: cookie.Name, Value: cookie.Value, Domain: cookie.Domain, Path: cookie.Path, + Expires: cookie.Expires, HTTPOnly: cookie.HTTPOnly, Secure: cookie.Secure, + SameSite: cookie.SameSite, PartitionKey: cookie.PartitionKey, + }) } - s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功") - { - // err 表示清理旧连接凭证的错误,仅记录不阻断扫码登录。 - if err := svc.repository.ClearTokens(ctx, accountID); err != nil && s.Logger != nil { - s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err) - } + } + // resultValue 保存应用服务返回的非敏感持久化结果。 + resultValue, persistErr := svc.qrApplication.PersistSuccess(ctx, input) + if persistErr != nil { + if errors.Is(persistErr, accountapp.ErrQRLoginIncomplete) { + return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb") } - return nil - }() - if saveErr != nil { - if errors.Is(saveErr, db.ErrForbidden) { + if errors.Is(persistErr, accountapp.ErrQRLoginAccountMismatch) { + return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖") + } + if errors.Is(persistErr, accountapp.ErrForbidden) { return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户") } - if errors.Is(saveErr, db.ErrAlreadyExists) { + if errors.Is(persistErr, db.ErrAlreadyExists) { return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态") } - return qrLoginPersistence{}, saveErr - } - // detail 和 err 保存登录成功后的资料摘要查询结果。 - if detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID); err == nil { - s.refreshAccountProfile(ctx, detail) - } - s.wakeCredentialBlockedAutomation(ctx, accountID) - if s.Manager != nil && svc.repository.GetStatus(ctx, accountID) { - // err 表示扫码登录后的账号运行时重启错误。 - if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil { - s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err) - } + return qrLoginPersistence{}, persistErr } // persisted 是扫码会话幂等返回值。 - persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew, UserID: userID, CreatedAt: time.Now().UTC()} + persisted := qrLoginPersistence{AccountID: resultValue.AccountID, IsNew: resultValue.IsNew, UserID: userID, CreatedAt: time.Now().UTC()} s.qrMu.Lock() s.qrPersisted[sessionID] = persisted s.qrMu.Unlock() diff --git a/internal/server/application_services.go b/internal/server/application_services.go index 0e02d15..39d68fd 100644 --- a/internal/server/application_services.go +++ b/internal/server/application_services.go @@ -2,6 +2,7 @@ package server import ( accountapp "xianyu-go/internal/application/account" + chatapp "xianyu-go/internal/application/chat" itemapp "xianyu-go/internal/application/items" orderapp "xianyu-go/internal/application/orders" ) @@ -22,6 +23,8 @@ type applicationServices struct { accountProfile *accountapp.ProfileService // communication 是聊天、通知和账号任务应用服务。 communication *communicationService + // chat 是聊天历史查询应用服务,负责用户归属和分页编排。 + chat *chatapp.Service // analytics 是订单分析应用服务。 analytics *analyticsService } @@ -49,14 +52,25 @@ func newApplicationServices(server *Server) *applicationServices { if accountLoginCreateErr != nil { panic(accountLoginCreateErr) } + // accountQRLogin 是扫码成功凭证持久化应用服务的构造结果;零值测试 Server 暂不装配数据库端口。 + var accountQRLogin *accountapp.QRLoginService + if server.Store != nil { + // accountQRLoginErr 保存扫码应用服务装配失败原因。 + var accountQRLoginErr error + accountQRLogin, accountQRLoginErr = newAccountQRLoginApplication(server) + if accountQRLoginErr != nil { + panic(accountQRLoginErr) + } + } return &applicationServices{ orders: &orderHTTPAdapter{services: orderServices, repository: orderRepository}, itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)}, itemSinglePublish: newItemPublishApplication(server), itemBatchRunner: itemBatchRunner, - accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate}, + accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store), createApplication: accountLoginCreate, qrApplication: accountQRLogin}, accountProfile: accountProfile, communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)}, + chat: chatapp.New(newStoreChatApplicationRepository(server.Store)), analytics: &analyticsService{repository: newStoreAnalyticsRepository(server.Store)}, } } diff --git a/internal/server/chat_handlers.go b/internal/server/chat_handlers.go index fa74839..a7dfedd 100644 --- a/internal/server/chat_handlers.go +++ b/internal/server/chat_handlers.go @@ -14,6 +14,7 @@ import ( "github.com/coder/websocket/wsjson" "github.com/go-chi/chi/v5" + chatapp "xianyu-go/internal/application/chat" "xianyu-go/internal/auth" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" @@ -29,6 +30,79 @@ func (s *Server) mountChat(r chi.Router) { r.Get("/api/chat/ws", s.chatWebSocket) } +// storeChatApplicationRepository 将数据库聊天查询适配为应用层聊天端口。 +type storeChatApplicationRepository struct { + // store 保存数据库聚合入口,仅在适配器内执行窄聊天查询。 + store *db.Store +} + +// ListMessages 查询带用户归属条件的聊天消息,并转换为应用层模型。 +func (r storeChatApplicationRepository) ListMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]chatapp.Message, error) { + // rows 保存数据库返回的消息记录。 + rows, err := r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) + if err != nil { + return nil, err + } + // messages 保存脱离数据库模型的应用层消息。 + messages := make([]chatapp.Message, 0, len(rows)) + // row 表示当前待转换的数据库聊天消息。 + for _, row := range rows { + messages = append(messages, chatapp.Message{ + ID: row.ID, AccountID: row.CookieID, ChatID: row.ChatID, MessageKey: row.MessageKey, + Direction: row.Direction, SenderID: row.SenderID, SenderName: row.SenderName, + MessageType: row.MessageType, Content: row.Content, Status: row.Status, SentAt: row.SentAt, + }) + } + return messages, nil +} + +// ListSessions 查询带用户归属条件的聊天会话,并转换为应用层模型。 +func (r storeChatApplicationRepository) ListSessions(ctx context.Context, userID int64, accountID string, limit int) ([]chatapp.Session, error) { + // rows 保存数据库返回的会话记录。 + rows, err := r.store.Chats.ListSessions(ctx, userID, accountID, limit) + if err != nil { + return nil, err + } + // sessions 保存脱离数据库模型的应用层会话摘要。 + sessions := make([]chatapp.Session, 0, len(rows)) + // row 表示当前待转换的数据库聊天会话。 + for _, row := range rows { + sessions = append(sessions, chatapp.Session{ + AccountID: row.CookieID, ChatID: row.ChatID, BuyerID: row.BuyerID, + BuyerName: row.BuyerName, BuyerAvatar: row.BuyerAvatar, ItemID: row.ItemID, + ItemTitle: row.ItemTitle, LastMessage: row.LastMessage, LastMessageAt: row.LastMessageAt, + UnreadCount: row.UnreadCount, + }) + } + return sessions, nil +} + +// newStoreChatApplicationRepository 创建聊天历史应用服务使用的数据库适配器。 +func newStoreChatApplicationRepository(store *db.Store) chatapp.Repository { + if store == nil || store.Chats == nil { + return nil + } + return storeChatApplicationRepository{store: store} +} + +// dbChatSessionFromApplication 将非敏感应用会话转换为平台身份适配器可消费的数据库形状。 +func dbChatSessionFromApplication(session chatapp.Session) db.ChatSession { + return db.ChatSession{ + CookieID: session.AccountID, ChatID: session.ChatID, BuyerID: session.BuyerID, + BuyerName: session.BuyerName, BuyerAvatar: session.BuyerAvatar, ItemID: session.ItemID, + ItemTitle: session.ItemTitle, LastMessage: session.LastMessage, LastMessageAt: session.LastMessageAt, + UnreadCount: session.UnreadCount, + } +} + +// 确保数据库适配器覆盖聊天历史应用端口的全部能力。 +var _ chatapp.Repository = storeChatApplicationRepository{} + +// chatApplication 返回当前 Server 绑定的聊天历史应用服务。 +func (s *Server) chatApplication() *chatapp.Service { + return s.applicationServiceSet().chat +} + // listChatSessions 负责list聊天Sessions相关处理。 func (s *Server) listChatSessions(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 @@ -290,12 +364,17 @@ func (s *Server) listChatMessages(w http.ResponseWriter, r *http.Request) { } } // page、err 保存page、err,供当前处理流程使用 - page, err := s.communicationApplication().ListStoredChatMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit) + page, err := s.chatApplication().ListStoredMessages(r.Context(), sess.UserID, accountID, chatID, beforeID, limit) if err != nil { writeErr(w, http.StatusInternalServerError, "读取聊天消息失败") return } - writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOs(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(page.Session)}) + // session 是应用层返回的非敏感会话摘要,供平台身份适配器补齐展示名称。 + session := dbChatSessionFromApplication(page.Session) + if session.ChatID != "" { + session = s.resolveSelectedChatIdentity(r.Context(), accountID, session) + } + writeJSON(w, http.StatusOK, chatMessagePageResponse{Messages: newChatMessageDTOsFromApplication(page.Messages), HasMore: page.HasMore, Session: newChatSessionDTO(session)}) } // resolveSelectedChatIdentity 负责resolveSelected聊天Identity相关处理。 diff --git a/internal/server/communication_repository.go b/internal/server/communication_repository.go index 6a727e8..4cf9fbf 100644 --- a/internal/server/communication_repository.go +++ b/internal/server/communication_repository.go @@ -44,10 +44,6 @@ type communicationRepository interface { UpdateCookieValue(ctx context.Context, cookieID, value string) error // MarkChatRead 将聊天会话标记为已读。 MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error - // ListChatMessages 查询聊天历史消息。 - ListChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]db.ChatMessage, error) - // ListChatSessions 查询账号聊天会话列表。 - ListChatSessions(ctx context.Context, userID int64, accountID string, limit int) ([]db.ChatSession, error) } // storeCommunicationRepository 将完整 Store 适配为通信应用服务窄 repository。 @@ -146,16 +142,6 @@ func (r storeCommunicationRepository) MarkChatRead(ctx context.Context, userID i return r.store.Chats.MarkRead(ctx, userID, accountID, chatID) } -// ListChatMessages 委托聊天消息查询。 -func (r storeCommunicationRepository) ListChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) ([]db.ChatMessage, error) { - return r.store.Chats.ListMessages(ctx, userID, accountID, chatID, beforeID, limit) -} - -// ListChatSessions 委托聊天会话查询。 -func (r storeCommunicationRepository) ListChatSessions(ctx context.Context, userID int64, accountID string, limit int) ([]db.ChatSession, error) { - return r.store.Chats.ListSessions(ctx, userID, accountID, limit) -} - // newStoreCommunicationRepository 从完整 Store 构造通信应用服务窄 repository。 func newStoreCommunicationRepository(store *db.Store) communicationRepository { if store == nil || store.AccountTasks == nil || store.Notifications == nil || store.Cookies == nil || store.Chats == nil { diff --git a/internal/server/communication_service.go b/internal/server/communication_service.go index 572dd80..85e56c9 100644 --- a/internal/server/communication_service.go +++ b/internal/server/communication_service.go @@ -59,18 +59,6 @@ type chatImageInput struct { Data []byte } -// chatMessagePageResult 是聊天历史查询结果,不依赖 HTTP DTO。 -type chatMessagePageResult struct { - // Messages 是本地或远端保存的聊天消息。 - Messages []db.ChatMessage - // Session 是当前聊天会话摘要。 - Session db.ChatSession - // HasMore 表示是否还有更早消息。 - HasMore bool - // NextCursor 是远端历史分页游标。 - NextCursor int64 -} - // notificationBindingRow 是通知绑定列表的一行业务数据。 type notificationBindingRow struct { // ID 是绑定记录标识。 @@ -313,25 +301,3 @@ func (svc *communicationService) SendChatImage(ctx context.Context, input chatIm func (svc *communicationService) MarkChatRead(ctx context.Context, userID int64, accountID, chatID string) error { return svc.repository.MarkChatRead(ctx, userID, accountID, chatID) } - -// ListStoredChatMessages 查询本地聊天历史并返回会话摘要。 -func (svc *communicationService) ListStoredChatMessages(ctx context.Context, userID int64, accountID, chatID string, beforeID int64, limit int) (chatMessagePageResult, error) { - // messages 和 err 保存本地聊天历史查询结果。 - messages, err := svc.repository.ListChatMessages(ctx, userID, accountID, chatID, beforeID, limit) - if err != nil { - return chatMessagePageResult{}, err - } - // session 保存当前聊天会话摘要。 - var session db.ChatSession - // sessions 和 sessionErr 保存当前用户的聊天会话列表及查询错误。 - if sessions, sessionErr := svc.repository.ListChatSessions(ctx, userID, accountID, 500); sessionErr == nil { - // candidate 是当前遍历到的会话摘要。 - for _, candidate := range sessions { - if candidate.ChatID == chatID { - session = svc.server.resolveSelectedChatIdentity(ctx, accountID, candidate) - break - } - } - } - return chatMessagePageResult{Messages: messages, Session: session, HasMore: len(messages) == limit}, nil -} diff --git a/internal/server/communication_service_test.go b/internal/server/communication_service_test.go index 733ae56..c8c1b2d 100644 --- a/internal/server/communication_service_test.go +++ b/internal/server/communication_service_test.go @@ -39,15 +39,15 @@ func TestCommunicationServiceRejectsInvalidAccountTask(t *testing.T) { } } -// TestCommunicationServiceListsStoredChatMessages 验证聊天历史查询服务返回稳定分页结果。 -func TestCommunicationServiceListsStoredChatMessages(t *testing.T) { +// TestChatApplicationListsStoredMessages 验证聊天历史应用服务返回稳定分页结果。 +func TestChatApplicationListsStoredMessages(t *testing.T) { // srv、store 和 cleanup 构造并释放测试服务。 srv, _, cleanup := newTestServer(t) defer cleanup() // page 和 err 保存聊天历史查询结果。 - page, err := srv.communicationApplication().ListStoredChatMessages(context.Background(), 1, "acc1", "chat-missing", 0, 20) + page, err := srv.chatApplication().ListStoredMessages(context.Background(), 1, "acc1", "chat-missing", 0, 20) if err != nil { - t.Fatalf("ListStoredChatMessages error: %v", err) + t.Fatalf("ListStoredMessages error: %v", err) } if len(page.Messages) != 0 || page.Session.ChatID != "" { t.Fatalf("unexpected empty chat page: %+v", page) diff --git a/internal/server/notification_handlers.go b/internal/server/notification_handlers.go index ac92475..0e0620d 100644 --- a/internal/server/notification_handlers.go +++ b/internal/server/notification_handlers.go @@ -25,6 +25,46 @@ func (s *Server) mountNotificationsReal(r chi.Router) { r.Post("/message-notifications/{cid}", s.setAccountBindings) } +// listUncertainNotifications 返回当前用户渠道对应的不确定通知摘要,不暴露正文或凭证。 +func (s *Server) listUncertainNotifications(w http.ResponseWriter, r *http.Request) { + // sess 保存当前已认证用户,用于限制通知渠道归属范围。 + sess := authSess(r) + // limit 保存运维列表页请求的最大条数,超出范围时使用数据库默认上限。 + limit := parsePositiveInt(r.URL.Query().Get("limit"), 20) + // items 保存当前用户可见的不确定通知摘要。 + items, err := s.Store.Notifications.ListUncertainOutboxForUser(r.Context(), sess.UserID, limit) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询通知状态失败") + return + } + // total 保存当前用户渠道的不确定通知总数。 + total, err := s.Store.Notifications.CountUncertainOutboxForUser(r.Context(), sess.UserID) + if err != nil { + writeErr(w, http.StatusInternalServerError, "统计通知状态失败") + return + } + writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, false)) +} + +// listAdminUncertainNotifications 返回全局不确定通知摘要,仅管理员路由可访问。 +func (s *Server) listAdminUncertainNotifications(w http.ResponseWriter, r *http.Request) { + // limit 保存管理员运维查询的最大条数,超出范围时使用数据库默认上限。 + limit := parsePositiveInt(r.URL.Query().Get("limit"), 50) + // items 保存所有用户渠道的不确定通知摘要,但不包含正文和错误原文。 + items, err := s.Store.Notifications.ListUncertainOutboxForAdmin(r.Context(), limit) + if err != nil { + writeErr(w, http.StatusInternalServerError, "查询通知状态失败") + return + } + // total 保存全局不确定通知总数。 + total, err := s.Store.Notifications.CountUncertainOutboxForAdmin(r.Context()) + if err != nil { + writeErr(w, http.StatusInternalServerError, "统计通知状态失败") + return + } + writeJSON(w, http.StatusOK, newNotificationUncertainOutboxResponse(items, total, true)) +} + // listChannels 负责list渠道列表相关处理。 func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) { // sess 保存sess,供当前处理流程使用 diff --git a/internal/server/notification_uncertain_test.go b/internal/server/notification_uncertain_test.go new file mode 100644 index 0000000..a056b31 --- /dev/null +++ b/internal/server/notification_uncertain_test.go @@ -0,0 +1,139 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "xianyu-go/internal/db" +) + +// TestUncertainNotificationEndpointsEnforceScope 验证用户与管理员 uncertain 查询的隔离和脱敏边界。 +func TestUncertainNotificationEndpointsEnforceScope(t *testing.T) { + // srv、store、cleanup 保存 HTTP 测试服务、数据库和资源释放函数。 + srv, store, cleanup := newTestServer(t) + defer cleanup() + // ctx 保存数据库夹具使用的根上下文。 + ctx := context.Background() + // userCreated、err 保存普通用户创建结果和数据库错误。 + userCreated, err := store.Users.Create(ctx, "uncertain-http-user", "uncertain-http@example.com", "pw") + if err != nil || !userCreated { + t.Fatalf("create user: created=%v err=%v", userCreated, err) + } + // user、err 保存普通用户实体和读取错误。 + user, err := store.Users.GetByUsername(ctx, "uncertain-http-user") + if err != nil { + t.Fatalf("get user: %v", err) + } + // createChannel 创建指定用户拥有的通知渠道并返回渠道标识。 + createChannel := func(userID int64) int64 { + // result、err 保存渠道插入结果和数据库错误。 + result, err := store.DB.ExecContext(ctx, `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES (?,?,?,?,?)`, "ops", "webhook", `{}`, 1, userID) + if err != nil { + t.Fatalf("create channel: %v", err) + } + // channelID、err 保存渠道主键和读取主键错误。 + channelID, err := result.LastInsertId() + if err != nil { + t.Fatalf("channel id: %v", err) + } + return channelID + } + // adminChannelID、userChannelID 保存管理员与普通用户各自拥有的渠道。 + adminChannelID := createChannel(1) + // userChannelID 保存普通用户拥有的通知渠道标识。 + userChannelID := createChannel(user.ID) + // enqueueUncertain 写入包含敏感正文的通知并推进到 uncertain 状态。 + enqueueUncertain := func(channelID int64, eventType string) { + // body 保存仅供 worker 的测试正文,验证 HTTP 响应不会返回它。 + body := "绝不能从接口泄露的通知正文 token=super-secret" + // err 保存 outbox 写入错误。 + if err := store.Notifications.EnqueueOutbox(ctx, []db.NotificationOutboxInput{{ChannelID: channelID, EventType: eventType, Body: body}}); err != nil { + t.Fatalf("enqueue outbox: %v", err) + } + // workerToken 保存当前测试 worker 的租约标识。 + workerToken := "http-" + eventType + // claimed、err 保存 worker 抢占结果和数据库错误。 + claimed, err := store.Notifications.ClaimOutbox(ctx, workerToken, time.Unix(100, 0), 10) + if err != nil || len(claimed) != 1 { + t.Fatalf("claim outbox: messages=%+v err=%v", claimed, err) + } + // marked、err 保存 uncertain 状态转移结果和数据库错误。 + marked, err := store.Notifications.MarkOutboxUncertain(ctx, claimed[0].ID, workerToken, "credential=should-not-leak") + if err != nil || !marked { + t.Fatalf("mark uncertain: marked=%v err=%v", marked, err) + } + } + enqueueUncertain(adminChannelID, "admin-event") + enqueueUncertain(userChannelID, "user-event") + + // handler 保存当前服务的 HTTP 路由处理器。 + handler := srv.Router() + // userCookie 保存普通用户登录后的会话 Cookie。 + userCookie := loginAsHelper(t, handler, "uncertain-http-user", "pw") + // userReq、userRec 保存普通用户查询请求及响应。 + userReq := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/outbox/uncertain?limit=10", nil) + userReq.AddCookie(userCookie) + // userRec 保存普通用户查询响应。 + userRec := httptest.NewRecorder() + handler.ServeHTTP(userRec, userReq) + if userRec.Code != http.StatusOK { + t.Fatalf("user uncertain status=%d body=%s", userRec.Code, userRec.Body.String()) + } + // userResponse 保存普通用户可见的非敏感通知摘要。 + var userResponse notificationUncertainOutboxResponse + // decodeErr 保存解析普通用户响应时的 JSON 错误。 + if decodeErr := json.Unmarshal(userRec.Body.Bytes(), &userResponse); decodeErr != nil { + t.Fatalf("decode user response: %v", decodeErr) + } + if userResponse.Total != 1 || len(userResponse.Items) != 1 || userResponse.Items[0].EventType != "user-event" || userResponse.Items[0].OwnerUserID != 0 { + t.Fatalf("user response violates scope: %+v", userResponse) + } + if strings.Contains(userRec.Body.String(), "super-secret") || strings.Contains(userRec.Body.String(), "should-not-leak") { + t.Fatal("user uncertain response leaked notification body or error") + } + + // adminCookie 保存管理员登录后的会话 Cookie。 + adminCookie := loginHelper(t, handler) + // adminReq、adminRec 保存管理员查询请求及响应。 + adminReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain?limit=10", nil) + adminReq.AddCookie(adminCookie) + // adminRec 保存管理员查询响应。 + adminRec := httptest.NewRecorder() + handler.ServeHTTP(adminRec, adminReq) + if adminRec.Code != http.StatusOK { + t.Fatalf("admin uncertain status=%d body=%s", adminRec.Code, adminRec.Body.String()) + } + // adminResponse 保存管理员可见的全局摘要。 + var adminResponse notificationUncertainOutboxResponse + // decodeErr 保存解析管理员响应时的 JSON 错误。 + if decodeErr := json.Unmarshal(adminRec.Body.Bytes(), &adminResponse); decodeErr != nil { + t.Fatalf("decode admin response: %v", decodeErr) + } + if adminResponse.Total != 2 || len(adminResponse.Items) != 2 { + t.Fatalf("admin response missing global items: %+v", adminResponse) + } + // item 表示当前遍历到的管理员通知摘要。 + for _, item := range adminResponse.Items { + if item.OwnerUserID == 0 || !item.HasError { + t.Fatalf("admin response missing safe metadata: %+v", item) + } + } + if strings.Contains(adminRec.Body.String(), "super-secret") || strings.Contains(adminRec.Body.String(), "should-not-leak") { + t.Fatal("admin uncertain response leaked notification body or error") + } + + // forbiddenReq、forbiddenRec 保存普通用户访问管理员接口的请求及响应。 + forbiddenReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain", nil) + forbiddenReq.AddCookie(userCookie) + // forbiddenRec 保存普通用户访问管理员接口的响应。 + forbiddenRec := httptest.NewRecorder() + handler.ServeHTTP(forbiddenRec, forbiddenReq) + if forbiddenRec.Code != http.StatusForbidden { + t.Fatalf("non-admin admin uncertain status=%d body=%s", forbiddenRec.Code, forbiddenRec.Body.String()) + } +} diff --git a/internal/server/success_contract.go b/internal/server/success_contract.go index 101f0da..de9f23d 100644 --- a/internal/server/success_contract.go +++ b/internal/server/success_contract.go @@ -1,6 +1,7 @@ package server import ( + chatapp "xianyu-go/internal/application/chat" "xianyu-go/internal/automation" "xianyu-go/internal/db" "xianyu-go/internal/xianyu/mtop" @@ -153,6 +154,22 @@ func newChatMessageDTOs(messages []db.ChatMessage) []chatMessageDTO { return result } +// newChatMessageDTOsFromApplication 将聊天应用层消息转换为 HTTP DTO,避免响应暴露数据库模型。 +func newChatMessageDTOsFromApplication(messages []chatapp.Message) []chatMessageDTO { + // result 是转换后的聊天消息 DTO 列表。 + result := make([]chatMessageDTO, 0, len(messages)) + // message 保存当前待转换的应用层消息。 + for _, message := range messages { + result = append(result, chatMessageDTO{ + ID: message.ID, AccountID: message.AccountID, ChatID: message.ChatID, + MessageKey: message.MessageKey, Direction: message.Direction, SenderID: message.SenderID, + SenderName: message.SenderName, MessageType: message.MessageType, Content: message.Content, + Status: message.Status, SentAt: message.SentAt, + }) + } + return result +} + // chatSessionPageResponse 是聊天会话分页接口的具名响应 DTO。 type chatSessionPageResponse struct { // Sessions 是当前页聊天会话。 @@ -772,6 +789,53 @@ type accountBindingsResponse struct { ChannelIDs []int64 `json:"channel_ids"` } +// notificationUncertainOutboxItem 是不确定通知的非敏感运维摘要。 +// 该 DTO 不包含通知正文、渠道配置、凭证或最后错误原文。 +type notificationUncertainOutboxItem struct { + // ID 是通知 outbox 记录的稳定标识。 + ID int64 `json:"id"` + // ChannelID 是关联通知渠道标识。 + ChannelID int64 `json:"channel_id"` + // OwnerUserID 是渠道所属用户标识,仅管理员查询时返回。 + OwnerUserID int64 `json:"owner_user_id,omitempty"` + // EventType 是通知事件分类。 + EventType string `json:"event_type"` + // AttemptCount 是进入不确定状态前的发送尝试次数。 + AttemptCount int `json:"attempt_count"` + // UncertainAt 是进入不确定状态的 Unix 秒时间戳。 + UncertainAt int64 `json:"uncertain_at"` + // HasError 表示是否存在本地确认错误,但不暴露错误原文。 + HasError bool `json:"has_error"` +} + +// notificationUncertainOutboxResponse 是用户或管理员查询不确定通知的具名响应。 +type notificationUncertainOutboxResponse struct { + // Total 是当前权限范围内的不确定通知总数。 + Total int `json:"total"` + // Items 是按最近进入不确定状态排序的非敏感摘要列表。 + Items []notificationUncertainOutboxItem `json:"items"` +} + +// newNotificationUncertainOutboxResponse 将数据库不确定状态摘要转换为非敏感 HTTP DTO。 +// includeOwner 仅管理员列表使用,用于展示渠道所属用户但不改变正文脱敏边界。 +func newNotificationUncertainOutboxResponse(items []db.NotificationUncertainSummary, total int, includeOwner bool) notificationUncertainOutboxResponse { + // result 保存不确定通知查询的具名响应。 + result := notificationUncertainOutboxResponse{Total: total, Items: make([]notificationUncertainOutboxItem, 0, len(items))} + // item 保存当前待转换的数据库摘要。 + for _, item := range items { + // responseItem 保存当前摘要对应的非敏感 API 行。 + responseItem := notificationUncertainOutboxItem{ + ID: item.ID, ChannelID: item.ChannelID, EventType: item.EventType, + AttemptCount: item.AttemptCount, UncertainAt: item.UncertainAt, HasError: item.HasError, + } + if includeOwner { + responseItem.OwnerUserID = item.OwnerUserID + } + result.Items = append(result.Items, responseItem) + } + return result +} + // categoryRecommendationResponse 是商品类目推荐接口的具名响应 DTO。 type categoryRecommendationResponse struct { // Success 表示类目推荐是否成功。 diff --git a/internal/server/versioned_settings_card_notification_routes.go b/internal/server/versioned_settings_card_notification_routes.go index 969d37f..bb0935e 100644 --- a/internal/server/versioned_settings_card_notification_routes.go +++ b/internal/server/versioned_settings_card_notification_routes.go @@ -20,6 +20,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) { r.Put("/api/v1/settings/system", s.setSettings) r.Put("/api/v1/settings/system/{key}", s.setSetting) r.Post("/api/v1/settings/ai-models", s.listAIModels) + r.Get("/api/v1/admin/notifications/outbox/uncertain", s.listAdminUncertainNotifications) }) // 普通登录用户可访问账号 AI 设置、用户设置、卡券和通知资源。 @@ -49,6 +50,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) { r.Delete("/api/v1/notifications/channels/{channel_id}", s.deleteChannel) r.Post("/api/v1/notifications/channels/{channel_id}/test", s.testChannel) r.Get("/api/v1/notifications/messages", s.listMessageNotifications) + r.Get("/api/v1/notifications/outbox/uncertain", s.listUncertainNotifications) r.Delete("/api/v1/notifications/messages/account/{cid}", s.deleteAccountNotifications) r.Delete("/api/v1/notifications/messages/{notification_id}", s.deleteMessageNotification) r.Get("/api/v1/notifications/accounts/{cid}/bindings", s.getAccountBindings)