@buka/nestjs-kit 4.4.12 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,222 @@
1
+ # list 查询三件套(过滤 / 排序 / 分页)
2
+
3
+ > 本文件由 [nestjs-kit-coding-standards/SKILL.md](../SKILL.md) 按需加载(实现 list 查询时读本文件)。导入来源、事务与异常红线等通用约定见 [SKILL.md 「通用约定」章](../SKILL.md#通用约定跨文件类型);目录归属见 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织)。
4
+
5
+ ## 命名与放置
6
+
7
+ 过滤 DTO(`XxxFilterQueryDto`)、排序类(`XxxOrderQuery`)与分页参数类型随请求参数 DTO 存放于 `dto/requests/`(命名与拆分规则见 [references/dto.md](dto.md) 与 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织))。
8
+
9
+ ## 速查表
10
+
11
+ | 要做什么 | 用什么 |
12
+ |---|---|
13
+ | Controller 接收 filter 参数 | `@FilterQuery(cls)` + 类型 `IFilterQuery<T>` |
14
+ | Service 接收过滤条件 | `IFilter<T>`(= `IFilterQuery<T>['filter']`) |
15
+ | 限制某字段可用操作符 | `@FilterQueryOperators(['eq', 'ne'])` |
16
+ | Controller 接收排序参数 | `OrderQueryType(cls)` 派生类 + `@Query()` |
17
+ | Controller 接收分页参数 | `@PageQuery(mode?)` / `@OptionalPageQuery(mode?)` + `IPageQuery<T>` |
18
+ | Service 分页容器 | `Slice<T>`(`fromOffset` / `fromCursor` / `map`) |
19
+ | 路由 ID 校验 | `ParseUUIDv7Pipe` |
20
+
21
+ ## 核心机制
22
+
23
+ **HTTP 操作符无 `$` 前缀,Controller 内自动加 `$` 前缀**:
24
+
25
+ ```
26
+ GET /students?filter={"name":{"eq":"Alice"},"age":{"gte":18}}&orderBy={"age":"desc"}...
27
+ query.filter?.name?.$eq === 'Alice' // 管道已经转换
28
+ query.filter?.age?.$gte === 18
29
+ ```
30
+
31
+ `filter` 参数可以是 URL 编码的 JSON 字符串,也可以是嵌套对象(qs 风格)。`@FilterQuery` 内部管道:解析 → 用生成的过滤类做 `whitelist + forbidNonWhitelisted` 校验(不合法返回 `BadRequestException`)→ 递归加 `$` 前缀。
32
+
33
+ ## Filter 过滤
34
+
35
+ ### 定义过滤 DTO(约定)
36
+
37
+ 过滤字段的取值 DTO 用 `PartialType(PickType(...))` 派生(DRY + 全可选):
38
+
39
+ ```typescript
40
+ import { PartialType, PickType } from '@buka/nestjs-kit'
41
+
42
+ // 从已有 DTO 选取可过滤字段
43
+ export class CourseFilterQueryDto extends PartialType(
44
+ PickType(CourseBriefDto, ['status', 'teacher']),
45
+ ) {}
46
+ ```
47
+
48
+ ### Controller 与 Service
49
+
50
+ ```typescript
51
+ import { FilterQuery, IFilterQuery, IFilter } from '@buka/nestjs-kit'
52
+
53
+ @Get()
54
+ async listCourses(
55
+ @FilterQuery(CourseFilterQueryDto) query: IFilterQuery<CourseFilterQueryDto>,
56
+ ) {
57
+ return this.courseService.list(query.filter) // 把 filter 透传给 service
58
+ }
59
+
60
+ // Service
61
+ async list(filter?: IFilter<Course>) {
62
+ return this.repo.findAndCount(filter ?? {}, {}) // filter 直接可用作 MikroORM where
63
+ }
64
+ ```
65
+
66
+ **类型边界**:Controller 用 `IFilterQuery<T>`(`{ filter?: ... }` 包装),Service 用 `IFilter<T>`(`... | undefined`)。`IFilter<T>` 根据 T 的每个属性**推导**可用操作符:
67
+
68
+ | 属性类型(来自实体/模型声明) | 可用操作符 |
69
+ |---|---|
70
+ | 标量(string/number/boolean/Date) | `$eq` `$ne` `$lt` `$gt` `$lte` `$gte` `$in` `$nin` |
71
+ | `Ref<Entity>`(关联 to-one) | 以上标量操作符,作用于主键值 |
72
+ | `Collection<Entity>` / 数组 | `$some` `$every` `$none`(内嵌嵌套条件对象) |
73
+ | 嵌套对象(@Composite/@Model) | 递归展开其属性的操作符 |
74
+
75
+ 集合操作符示例:`GET /books?filter={"chapters":{"some":{"title":{"eq":"序章"}}}}`。
76
+
77
+ service 入参与 controller 职责的完整约定见 [references/service.md](service.md) 与 [references/controller.md](controller.md)。
78
+
79
+ ### 收窄操作符
80
+
81
+ ```typescript
82
+ import { FilterQueryOperators, Model, Property } from '@buka/nestjs-kit'
83
+
84
+ @Model()
85
+ class CourseBriefDto {
86
+ @Property()
87
+ @FilterQueryOperators(['eq', 'ne', 'in'])
88
+ status!: CourseStatus // 只允许这三种操作符,其余在生成 schema 中剔除、校验时拒绝
89
+ }
90
+ ```
91
+
92
+ ## Order 排序
93
+
94
+ ```typescript
95
+ import { OrderQueryType } from '@buka/nestjs-kit'
96
+
97
+ export class CourseOrderQuery extends OrderQueryType(Course) {}
98
+
99
+ @Get()
100
+ async listCourses(@Query() query: CourseOrderQuery) {
101
+ // query.orderBy === { createdAt: 'desc' }
102
+ // 或数组形式: [{ createdAt: 'desc' }, { id: 'asc' }]
103
+ return this.courseService.list({}, query.orderBy)
104
+ }
105
+
106
+ // Service: orderBy 直接作为 MikroORM orderBy
107
+ this.repo.find({}, { orderBy })
108
+ ```
109
+
110
+ `IOrderQuery<T>` 的 `orderBy?: QueryOrderMap<T> | QueryOrderMap<T>[]`,只允许模型中声明的字段,JSON Schema 校验由全局验证管道完成。
111
+
112
+ ## 分页
113
+
114
+ ### 参数形态(HTTP → Controller 参数)
115
+
116
+ | 模式 | HTTP `page` | 管道输出 `page` | 校验规则 |
117
+ |---|---|---|---|
118
+ | offset | `{ limit, offset }` | `{ limit, offset }`(number 化) | `limit` 正整数,`offset` 非负整数 |
119
+ | cursor 向前 | `{ first, after? }` | `{ first, after }` | `first` 正整数;首屏 `after` 可缺省 |
120
+ | cursor 向后 | `{ last, before? }` | `{ last, before }` | `last` 正整数 |
121
+
122
+ - `@PageQuery('offset' | 'cursor')` 限定模式;不传 `mode` 同时支持三种形态
123
+ - 混合 offset 与 cursor 参数、或 `after/first` 与 `before/last` 混用 → `BadRequestException`
124
+ - `@OptionalPageQuery(mode?)`:不传 `page` 时不报错(`page` 可能为 undefined)
125
+ - 参数类型用 `IPageQuery<'offset'>` / `IPageQuery<'cursor'>`(形状 `{ page: {...} }`)
126
+
127
+ ### Service 返回 `Slice<T>`
128
+
129
+ ```typescript
130
+ import { Slice } from '@buka/nestjs-kit'
131
+ import { Cursor } from '@mikro-orm/core'
132
+
133
+ // offset 模式
134
+ const [items, total] = await this.courseRepo.findAndCount({}, {
135
+ limit: page.page.limit,
136
+ offset: page.page.offset,
137
+ })
138
+ return Slice.fromOffset(items, total, page.page) // 参数 { limit, offset }
139
+
140
+ // cursor 模式(MikroORM v7)
141
+ const cursor: Cursor<Course> = await this.courseRepo.findByCursor({}, {
142
+ first: page.page.first,
143
+ after: page.page.after, // 形如 'tx_offset' 的 opaque cursor;首屏传 undefined
144
+ })
145
+ return Slice.fromCursor(cursor)
146
+ ```
147
+
148
+ ### Controller 出参
149
+
150
+ ```typescript
151
+ import { ListResponseBodyType, PageQuery, IPageQuery } from '@buka/nestjs-kit'
152
+
153
+ export class ListCoursesResponseDto extends ListResponseBodyType(CourseBriefDto, 'offset') {}
154
+
155
+ @Get()
156
+ async listCourses(@PageQuery('offset') page: IPageQuery<'offset'>): Promise<ListCoursesResponseDto> {
157
+ const slice = await this.courseService.list(page)
158
+ return ListCoursesResponseDto.fromSlice(slice) // meta.pagination = { total, limit, offset }
159
+ }
160
+ ```
161
+
162
+ - `OffsetPagination`:`{ total, limit, offset }`
163
+ - `CursorPagination`:`{ total?, limit, startCursor, endCursor, hasNextPage, hasPrevPage }`(`em.findByCursor` 时 `total` 来自 `totalCount`,不查总数时为 undefined)
164
+ - 响应包装与 `toJSON` 序列化见 [references/dto.md](dto.md);`Slice.map(item => dto)` 可保留分页信息做元素转换
165
+
166
+ ## 端到端模板
167
+
168
+ ```typescript
169
+ // course.controller.ts
170
+ @Controller('courses')
171
+ export class CourseController {
172
+ constructor(private readonly courseService: CourseService) {}
173
+
174
+ /** 课程列表 */
175
+ @Get()
176
+ async listCourses(
177
+ @FilterQuery(CourseFilterQueryDto) filterQuery: IFilterQuery<CourseFilterQueryDto>,
178
+ @Query() order: CourseOrderQuery,
179
+ @PageQuery() page: IPageQuery,
180
+ ): Promise<ListCoursesResponseDto> {
181
+ const slice = await this.courseService.list({
182
+ filter: filterQuery.filter,
183
+ orderBy: order.orderBy,
184
+ page: page.page, // controller 负责 DTO 参数 → command 的映射
185
+ })
186
+ return ListCoursesResponseDto.fromSlice(slice)
187
+ }
188
+ }
189
+
190
+ // course.service.ts
191
+ // ListCoursesCommand:聚合 filter/orderBy/page 的 command interface(放 commands/ 目录,见 references/service.md)
192
+ async list(command: ListCoursesCommand) {
193
+ const { filter, orderBy, page } = command
194
+ // offset 分支
195
+ const [items, total] = await this.repo.findAndCount(filter ?? {}, {
196
+ orderBy,
197
+ limit: page?.limit ?? 20,
198
+ offset: page?.offset ?? 0,
199
+ })
200
+ return Slice.fromOffset(items, total, { limit: page?.limit ?? 20, offset: page?.offset ?? 0 })
201
+ }
202
+ ```
203
+
204
+ ## ParseUUIDv7Pipe
205
+
206
+ ```typescript
207
+ @Get(':studentId')
208
+ findOne(@Param('studentId', ParseUUIDv7Pipe) studentId: string) {
209
+ // 非 UUIDv7 → BadRequestException('Validation failed (UUIDv7 is expected)')
210
+ }
211
+ ```
212
+
213
+ ## 注意事项
214
+
215
+ - 分页管道输出形状是 `{ page: {...} }`:`@PageQuery` 参数拿到的是包装对象(`IPageQuery` 类型),传给 service 时取 `page.page`
216
+ - `filter` HTTP 传 JSON 字符串时注意 URL 编码(`encodeURIComponent(JSON.stringify(...))`);qs 嵌套对象两种都被支持
217
+ - filter 校验在管道内 `whitelist + forbidNonWhitelisted`:传了模型里没有的字段/操作符会整体 400
218
+ - cursor 的 `after/before` 是 `Slice.fromCursor` 输出的 `endCursor/startCursor` 原样回传的 opaque 字符串,无需自行拼装
219
+ - 过滤字段记得收窄操作符(`@FilterQueryOperators`),状态/枚举类字段通常只需 `eq/in`
220
+ - 基础过滤+排序+分页直接用 `findAndCount`/`findByCursor`,无需手写 SQL 或 QueryBuilder
221
+ - `FilterQueryType` 工厂是内部实现,**未从包导出**,不要 import 它(公开 API 是 `@FilterQuery` 装饰器 + `IFilter`/`IFilterQuery` 类型)
222
+ - Swagger UI 中 object 型 query 参数渲染见 [nestjs-kit-swagger](../../nestjs-kit-swagger/SKILL.md)
@@ -0,0 +1,136 @@
1
+ # Service 编写与事务约定(业务逻辑层)
2
+
3
+ > 本文件由 [nestjs-kit-coding-standards/SKILL.md](../SKILL.md) 按需加载(写 service 时读本文件)。导入来源、事务与异常红线等通用约定见 [SKILL.md 「通用约定」章](../SKILL.md#通用约定跨文件类型);目录归属见 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织)。
4
+
5
+ ## 前置条件
6
+
7
+ - 实体已通过 `MikroOrmModule.forFeature([...])` 注册(BukaModule 已注册全局 `BukaValidationPipe`)。
8
+ - 请求体嵌套对象已由 `BukaValidationPipe` 转成 wrapped `Ref`(机制见 [SKILL.md 前置条件](../SKILL.md#前置条件),细节见 [references/dto.md](dto.md) 的实体派生 DTO 章)。
9
+ - 事务提交点在 controller 末尾统一 `em.flush()`(见 [references/controller.md](controller.md));service 只在例外场景 flush(见下方「em.flush 与事务约定」)。
10
+
11
+ ## 命名与放置
12
+
13
+ - `services/<module-name>.service.ts` 主 service
14
+ - `services/<subresource>.service.ts` 子 service
15
+ - `commands/<action>.command.ts`(只放 interface,不放 handler)
16
+ - 目录归属与命名约定见 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织)
17
+
18
+ ## 速查表
19
+
20
+ | 要做什么 | 用什么 |
21
+ |---|---|
22
+ | 声明 service | 普通 `@Injectable()`(无需继承基类) |
23
+ | 注入 EntityManager | `constructor(private readonly em: EntityManager)`(`@mikro-orm/core`) |
24
+ | 获取仓储 | `@InjectRepository(X)` 或 `this.em.getRepository(X)`;注入属性命名 `{EntityName}Repo`(如 `courseRepo`,见 [SKILL.md 命名约定](../SKILL.md#命名约定)) |
25
+ | 公共方法参数 | 只允许一个参数——多参聚合为 command interface(放 `commands/`) |
26
+ | 传递实体引用 | `Ref<Entity>`(`@mikro-orm/core`),非特殊情况不传 Entity 裸对象 |
27
+ | 提交事务 | 非特殊情况不执行 `em.flush()`——提交点在 controller 末尾 |
28
+ | 依赖注入 | constructor 注入 `em` + 协作 service(由 NestJS DI 完成实例化) |
29
+
30
+ ## 基本形态
31
+
32
+ service 是业务逻辑的唯一所在,不写 HTTP 包装、不做参数校验(已由 BukaValidationPipe 完成)、不直接操作 controller 特有的装饰器。一个公共方法一个职责;返回业务结构(实体 / `Slice<T>` / 数据值)而非 `{ data, meta }` 包装。
33
+
34
+ ```typescript
35
+ import { Injectable } from '@nestjs/common'
36
+ import { InjectRepository } from '@mikro-orm/nestjs'
37
+ import { EntityManager, EntityRepository, Ref } from '@mikro-orm/core'
38
+ import { Course, Enrollment } from '../entities'
39
+
40
+ @Injectable()
41
+ export class CourseService {
42
+ constructor(
43
+ private readonly em: EntityManager,
44
+ private readonly courseRepo: EntityRepository<Course>,
45
+ private readonly notificationService: NotificationService, // 协作 service
46
+ ) {}
47
+
48
+ async enrollStudent(command: EnrollStudentCommand): Promise<Enrollment> {
49
+ const enrollment = this.em.create(Enrollment, {
50
+ course: command.course, // command.course 已是 wrapped Ref<Course>
51
+ student: command.student, // 同上
52
+ source: command.source,
53
+ })
54
+ this.em.persist(enrollment)
55
+ // 不在此处 flush——提交点在 controller 末尾
56
+ return enrollment // 追踪的实体,controller flush 后落库
57
+ }
58
+ }
59
+ ```
60
+
61
+ ## service 拆分设计(按复杂度)
62
+
63
+ 不以"聚合编排"为唯一职责——拆分准绳是**复杂度**,简单 service 不拆。
64
+
65
+ ### 拆分信号(满足任一即考虑拆分)
66
+
67
+ | 信号 | 拆分方式 |
68
+ |---|---|
69
+ | 子资源具备多个功能(如课程报名包含报名/取消/查询/审批) | 独立 `XxxSubresourceService`(如 `CourseEnrollmentService`) |
70
+ | 可独立理解的复杂职责(通知发送、审计日志、外部同步) | 独立 provider(`@Injectable()`),由主 service 注入 |
71
+ | 公共方法逼近 10 个,且可按资源/职责切出明确主题组 | 按主题拆子 service |
72
+ | 单文件数百行仍持续膨胀 | 切分 |
73
+ | 多模块共需的能力(如权限判断、ID 生成) | 下沉到公共层目录(`src/shared/`) |
74
+
75
+ ### 不拆信号(保持单 service)
76
+
77
+ | 信号 | 做法 |
78
+ |---|---|
79
+ | service 简单:三五个方法、逻辑直白 | 保持单 service |
80
+ | 只是同一资源 CRUD 变体(增删改查 + 一二个衍生查询) | 同 service 多方法即可 |
81
+ | 仅单个方法"看起来复杂" | 提取私有辅助函数,不拆新 service |
82
+ | 子资源只有一个功能 | 一个方法留在主 service |
83
+
84
+ ### 命名与注入
85
+
86
+ - controller 注入主 service;按子资源拆 controller 时对应注入子 service(见 [references/controller.md](controller.md))
87
+ - 子 service 间尽量不互注,跨 service 协作由主 service 编排
88
+
89
+ ## command 设计
90
+
91
+ **每个 public 方法只允许一个参数**(无参也不写裸多参)。多参聚合为 command interface,放 `commands/` 目录,只放 interface,不放 handler 或 DTO。
92
+
93
+ ```typescript
94
+ // commands/enroll-student.command.ts
95
+ import type { Ref } from '@mikro-orm/core'
96
+ import type { Course, Student } from '../entities'
97
+
98
+ export interface EnrollStudentCommand {
99
+ /** 课程 */
100
+ course: Ref<Course>
101
+ /** 学生 */
102
+ student: Ref<Student>
103
+ /** 报名来源 */
104
+ source: EnrollSource
105
+ }
106
+ ```
107
+
108
+ **参数含 Entity 时非特殊情况传 `Ref<Entity>`**(`Ref` 自 `@mikro-orm/core` 导入——kit 不重导出)。与 DTO 的衔接:请求体中的 `@EntityRef`/`PrimaryKeyType` 字段已被 `BukaValidationPipe` 转为 wrapped `Ref`,controller 原样放入 command;路径参数引用的实体用 `this.em.getReference(Course, courseId, { wrapped: true })` 转成 wrapped `Ref` 再放进 command。
109
+
110
+ **command 与 DTO 的边界**:DTO 是 HTTP 层带校验装饰器的对象(`dto/requests/`),command 是 service 层的入参契约(`commands/`),controller 负责 DTO → command 的映射。
111
+
112
+ ## em.flush 与事务约定
113
+
114
+ **service 非特殊情况不执行 `em.flush()`**。提供 `DatabaseConfig` 默认 `flushMode: FlushMode.COMMIT`(查询前隐式 flush 已跟踪变更)让实体追踪无需手动 flush,一次请求一个提交单元,controller 末尾统一提交(见 [references/controller.md](controller.md))。
115
+
116
+ **允许的例外**:计数器/序号自增等必须立即落库且与请求成败无关的原子场景,须就地注释理由:
117
+
118
+ ```typescript
119
+ // 必须立即落库以防并发冲突
120
+ const counter = await this.em.findOneOrFail(Counter, { key: 'invoice' })
121
+ counter.value += 1
122
+ await this.em.flush() // 例外:计数器自增须立即落库
123
+ return counter.value
124
+ ```
125
+
126
+ service 只通过 `em.create`/`em.persist`/`em.remove` 跟踪变更,把"何时提交"交给 controller。
127
+
128
+ ## 注意事项
129
+
130
+ - `Ref` 自 `@mikro-orm/core` 导入——kit 不重导出
131
+ - command 只放 interface(枚举/常量放 `constants/` 目录)
132
+ - 改 command 字段时同步 controller 映射
133
+ - service 入参一律经 command 显式声明,单方法只接受一个参数
134
+ - 返回业务结构不返回 HTTP 包装(`{ data, meta }` 包装在 controller 侧完成)
135
+ - 例外 flush 必须注释理由
136
+ - 移动/重命名文件时同步检查清单见 [SKILL.md 注意事项](../SKILL.md#注意事项)
@@ -0,0 +1,126 @@
1
+ ---
2
+ name: nestjs-kit-crypto
3
+ description: >
4
+ 本 skill 覆盖 @buka/nestjs-kit 的加密三件套。当用户加密存储敏感字段(EnvelopeEncryptionModule 信封加密、
5
+ KeyEnvelope/EncryptedPayload)、为加密字段建立等值查询(BlindIndexModule 盲索引)、
6
+ 存储密码或凭证(SaltedHashModule 加盐哈希)、在实体中嵌入加密列(Column.Embedded)、
7
+ 或用 reencrypt 执行密钥轮换时使用本 skill。
8
+ 信封加密依赖 OpenBao transit 前置注册,见 nestjs-kit-open-bao;实体与嵌入列声明见 nestjs-kit-coding-standards。
9
+ ---
10
+
11
+ # 加密三件套(信封加密 / 盲索引 / 加盐哈希)
12
+
13
+ 三个模块互相独立;**信封加密依赖 OpenBaoModule**(前置条件:项目已注册 OpenBaoModule,其内部通过 transit 生成/加解密 DEK,见 [nestjs-kit-open-bao](../nestjs-kit-open-bao/SKILL.md))。
14
+
15
+ ## 选型对照
16
+
17
+ | 场景 | 用什么 | 说明 |
18
+ |---|---|---|
19
+ | 密码/凭证存储,只需校验不需还原 | `SaltedHash`(bcrypt) | 抗彩虹表 |
20
+ | 敏感字段需要**等值查询**(邮箱/手机号) | `BlindIndex`(SHA-256 确定性哈希) | 不能还原;有彩虹表风险,**配合信封加密存明文** |
21
+ | 字段级机密需要**还原明文** | `EnvelopeEncryption`(AES-256-GCM,KEK/DEK) | KEK 托管于 OpenBao Transit |
22
+ | 加密字段 + 等值查询的组合 | `EncryptedPayload` + `BlindIndex` 同表存 | 查索引、解密取明文 |
23
+
24
+ 各可嵌入实体字段默认 `hidden`,不会被序列化进 API 响应。
25
+
26
+ ## 加盐哈希(SaltedHashModule)
27
+
28
+ ```typescript
29
+ import { SaltedHashService, SaltedHash, DiscreteEntity, Column } from '@buka/nestjs-kit'
30
+
31
+ @Module({ imports: [SaltedHashModule] })
32
+ export class AppModule {}
33
+
34
+ @Entity()
35
+ export class UserEntity extends DiscreteEntity {
36
+ @Column.Embedded(() => SaltedHash)
37
+ password!: SaltedHash
38
+ }
39
+
40
+ // service
41
+ const saltedHash = await this.saltedHashService.hash('my-password')
42
+ // saltedHash.hash → bcrypt 字符串;saltedHash.version → 1
43
+ const ok = await this.saltedHashService.verify('my-password', savedHash)
44
+ ```
45
+
46
+ - V1:bcrypt,cost 10(约 100ms),盐内嵌于哈希串,无需单独存盐
47
+ - `verify` 按 `version` 路由 hasher,历史数据在算法升级后仍可验证
48
+
49
+ ## 盲索引(BlindIndexModule)
50
+
51
+ ```typescript
52
+ import { BlindIndexService, BlindIndex } from '@buka/nestjs-kit'
53
+
54
+ @Entity()
55
+ export class UserEntity extends DiscreteEntity {
56
+ @Column.Embedded(() => BlindIndex)
57
+ emailIndex!: BlindIndex
58
+ }
59
+
60
+ // 写:入库前生成索引
61
+ const index = await this.blindIndexService.generate(email)
62
+ // 查:对输入做同样计算后等值匹配
63
+ const idx = await this.blindIndexService.generate(inputEmail)
64
+ await this.userRepo.findOne({ emailIndex: { value: idx.value } })
65
+ ```
66
+
67
+ - `generate(data: JsonValue)` → `{ value: char(64) hex, version }`;对象输入先 `stableStringify`(键排序)再哈希,属性顺序不影响结果
68
+ - `data` 不能为 `null`/`undefined`(抛 TypeError)
69
+ - **确定性哈希可被彩虹表反查**:高敏感数据(邮箱等)将明文经信封加密存 `EncryptedPayload`,盲索引仅用于查询定位
70
+
71
+ ## 信封加密(EnvelopeEncryptionModule)
72
+
73
+ 两把钥匙:DEK(每次加密随机生成,加密数据)→ 由 KEK(OpenBao Transit 管理,永不出 OpenBao)加密后随数据存储。数据库泄露时攻击者拿不到 KEK 就无法解密。
74
+
75
+ ```typescript
76
+ // 注册(前置条件:模块所在 AppModule 已注册 OpenBaoModule)
77
+ @Module({ imports: [EnvelopeEncryptionModule.register({ version: 1 })] })
78
+ export class AppModule {}
79
+
80
+ // 加密(string 或 Buffer)
81
+ import { EnvelopeEncryptionService } from '@buka/nestjs-kit'
82
+
83
+ const [envelope, payload] = await this.encryption.encrypt({
84
+ kekId: 'user-secrets', // KEK 标识(对应 OpenBao transit key)
85
+ plaintext: '敏感数据',
86
+ extraAad: { userId: '123' }, // 可选:绑定业务上下文
87
+ })
88
+
89
+ // 解密
90
+ const buffer = await this.encryption.decrypt({ envelope, payload, extraAad: { userId: '123' } })
91
+ const text = await this.encryption.decryptToString({ envelope, payload, extraAad: { userId: '123' } })
92
+
93
+ // 密钥轮换
94
+ const [newEnvelope, newPayload] = await this.encryption.reencrypt({
95
+ envelope, payload, keyId: 'new-kek-id', extraAad: { userId: '123' },
96
+ })
97
+ ```
98
+
99
+ 可嵌入实体:
100
+
101
+ ```typescript
102
+ @Entity()
103
+ export class UserSecretEntity extends DiscreteEntity {
104
+ @Column.Embedded(() => KeyEnvelope) // kekId varchar(64) / kekVersion / dek bytea
105
+ envelope!: KeyEnvelope
106
+
107
+ @Column.Embedded(() => EncryptedPayload) // ciphertext / cipherIv / cipherTag / cipherVersion smallint
108
+ payload!: EncryptedPayload
109
+ }
110
+ ```
111
+
112
+ V1 实现:AES-256-GCM;IV 12 字节随机、认证标签 16 字节;AAD 由 `kekId + extraAad` 稳定序列化组成(密文与 KEK/业务上下文绑定,防密文替换);DEK 用后立即内存清零;`cipherVersion` 驱动向后兼容。
113
+
114
+ ## 注意事项
115
+
116
+ - 密码存储统一走 `SaltedHash`:自实现 `crypto.createHash('sha256')` 无盐,无法抵御彩虹表;SaltedHash 的 bcrypt 自带盐与版本路由
117
+ - 加密字段在实体上统一用可嵌入实体(`KeyEnvelope`+`EncryptedPayload` / `BlindIndex` / `SaltedHash`),字段自动 `hidden`,即使手写 DTO 也要确认不暴露
118
+ - **`extraAad` 加密与解密必须完全一致**(不一致 GCM 认证失败);用它绑定 owner(如 `{ userId }`),防止把 A 的密文拿到 B 的请求里解
119
+ - `reencrypt` 用于 KEK 轮换/迁移,轮换是逐条进行的,安排后台任务批量执行
120
+ - 盲索引是可复现的确定性哈希(不可还原),仅供等值查询定位;同一输入恒得同一索引值,存在彩虹表反查风险——敏感语义字段将明文存入信封加密的 `EncryptedPayload`,盲索引仅作查询入口
121
+ - `generate`/`hash` 输入先做规范化(邮箱 lowercase/trim)再哈希,否则等值查询对不准
122
+
123
+ ## 相关 skills
124
+
125
+ - [nestjs-kit-open-bao](../nestjs-kit-open-bao/SKILL.md) — OpenBao 注册(信封加密前置)
126
+ - [nestjs-kit-coding-standards](../nestjs-kit-coding-standards/references/entity.md) — `Column.Embedded` 嵌入
@@ -0,0 +1,172 @@
1
+ ---
2
+ name: nestjs-kit-exception
3
+ description: >
4
+ 本 skill 定义 @buka/nestjs-kit 的结构化业务异常与错误码体系。当用户声明或修改模块错误码(@ModuleExceptions)、
5
+ 用 9 个异常工厂抛出业务异常(BusinessException/SystemException/ThirdPartyException/AuthException/
6
+ ValidationException/ConflictException/FeatureException/RateLimitException/DegradeException)、
7
+ 构造统一错误响应 {error:{code,message,details}}、编写 ExceptionDetail 结构化详情、
8
+ 为二方包认领 moduleId、或查询 GET /error-codes 错误码时使用本 skill。
9
+ 写业务代码时选择抛哪种异常、异常声明文件的位置同时涉及 nestjs-kit-coding-standards;
10
+ 上游服务响应转异常涉及 nestjs-kit-http。
11
+ ---
12
+
13
+ # 异常与错误码(ExceptionModule)
14
+
15
+ 错误码规范由 `@buka/error-codes` / `@buka/exception` 定义。ExceptionModule 注册后自动装配全局 `ErrorCodeExceptionFilter` 并注册 `GET /error-codes` 错误码查询接口。
16
+
17
+ ## 速查表
18
+
19
+ | 要做什么 | 用什么 |
20
+ |---|---|
21
+ | 注册统一异常处理 | `ExceptionModule.register({ systemId })` |
22
+ | 按模块组织异常定义 | `@ModuleExceptions({ moduleId })` + 9 个工厂 |
23
+ | 业务逻辑错误 | `BusinessException`(默认 400) |
24
+ | 系统/内部错误 | `SystemException`(默认 500) |
25
+ | 第三方服务失败 | `ThirdPartyException`(默认 502) |
26
+ | 认证/权限 | `AuthException`(401) / `FeatureException`(403) |
27
+ | 资源冲突 | `ConflictException`(409) |
28
+ | 参数校验错误 | `ValidationException`(400) |
29
+ | 限流/降级 | `RateLimitException`(429) / `DegradeException`(503) |
30
+ | 直接抛内置常用异常 | `BukaExceptions.NotFound` 等 |
31
+ | 结构化错误详情 | `ExceptionDetail`(details 参数) |
32
+
33
+ ## 文件位置
34
+
35
+ 模块专属异常集中声明于模块根目录的 `<module-name>.exceptions.ts`(所有 `@ModuleExceptions` 类写在这一个文件里,目录规范见 [nestjs-kit-coding-standards 「目录组织」章](../nestjs-kit-coding-standards/SKILL.md#业务模块目录组织))。
36
+
37
+ ## 注册
38
+
39
+ ```typescript
40
+ import { ExceptionModule } from '@buka/nestjs-kit'
41
+
42
+ @Module({ imports: [ExceptionModule.register({ systemId: 'Z9' })] })
43
+ export class AppModule {}
44
+ ```
45
+
46
+ - `systemId`(0-1048575,十进制或 Crockford Base32)全局唯一标识一个服务,接入时从错误码登记处获取,业务代码不自行编造
47
+ - 注册后自动装配全局 `ErrorCodeExceptionFilter`(恒装配、不可禁用——没有 `useGlobalFilter` 选项),并注册 `GET /error-codes` 错误码查询接口
48
+ - 一个进程只注册一个 systemId
49
+
50
+ ## 9 个异常工厂
51
+
52
+ | 工厂 | 类别 | 默认 HTTP | 适用场景 |
53
+ |---|---|---|---|
54
+ | `SystemException` | SYSTEM | 500 | 系统级错误(数据库故障、内部异常) |
55
+ | `BusinessException` | BUSINESS | 400 | 业务逻辑错误(资源不存在、状态不合法) |
56
+ | `ValidationException` | VALIDATION | 400 | 参数校验错误 |
57
+ | `ThirdPartyException` | THIRD_PARTY | 502 | 第三方服务调用失败 |
58
+ | `AuthException` | AUTH | 401 | 认证/授权 |
59
+ | `RateLimitException` | RATE_LIMIT | 429 | 限流 |
60
+ | `DegradeException` | DEGRADE | 503 | 服务降级 |
61
+ | `ConflictException` | CONFLICT | 409 | 资源状态冲突(并发修改等) |
62
+ | `FeatureException` | FEATURE | 403 | 功能未开放/权限不足 |
63
+
64
+ 工厂选项:`{ sequenceId, message | messageFactory, httpStatus?, description? }`。**工厂不含 `moduleId` 选项**——moduleId 唯一来源是 `@ModuleExceptions` 装饰器。
65
+
66
+ ### 固定消息 vs 消息工厂
67
+
68
+ ```typescript
69
+ import { ModuleExceptions, BusinessException } from '@buka/nestjs-kit'
70
+
71
+ @ModuleExceptions({ moduleId: '1000' })
72
+ export class StudentExceptions {
73
+ // 固定消息:未指定 description 时默认取 message 的值
74
+ static readonly NotFound = BusinessException({
75
+ sequenceId: 1,
76
+ message: '学生不存在',
77
+ description: '根据条件未找到学生,请确认学号是否正确',
78
+ })
79
+
80
+ // 消息工厂:构造参数参与生成消息
81
+ static readonly NotFoundById = BusinessException({
82
+ sequenceId: 2,
83
+ messageFactory: (studentId: string) => `学生 ${studentId} 不存在`,
84
+ })
85
+ }
86
+
87
+ throw new StudentExceptions.NotFound() // 默认消息
88
+ throw new StudentExceptions.NotFound('自定义消息') // 覆盖消息
89
+ throw new StudentExceptions.NotFoundById('abc-123') // 工厂消息
90
+ ```
91
+
92
+ - `sequenceId`(0-32767)在**同 moduleId + 同类别**内唯一,重复会在启动注册时直接报错(fail-fast)
93
+ - 异常的类 `name` 自动设为 `ModuleName.PropertyName`(如 `StudentExceptions.NotFound`),日志与排障友好
94
+
95
+ ## @ModuleExceptions
96
+
97
+ - `moduleId`(0-1048575):支持十进制或 Crockford Base32 两种等价写法(示例中的 `'1000'` 是 Base32 写法、对应十进制 32768,错误码与 registry 均以 Base32 呈现)。**`moduleId: 0` 为系统保留**(内置异常映射),业务模块在 `1000`-`FZZZ` 范围内声明
98
+ - 工厂返回 `PendingException`,必须由 `@ModuleExceptions` 转正;未装饰即实例化会在编码阶段立即抛错,报错信息包含正确写法示例(属 fail-fast 预期行为)
99
+ - `getExceptionModuleId(ExceptionClass)` 可查询已绑定异常类的 moduleId
100
+
101
+ ## 统一响应与内置异常
102
+
103
+ 响应体结构(filter 输出):
104
+
105
+ ```json
106
+ { "error": { "code": "B0-AAAB-AAAB-001", "message": "资源不存在", "details": [] } }
107
+ ```
108
+
109
+ `ErrorCodeExceptionFilter` 处理三类:kit 抛出的带码异常(用自己的 code);NestJS 内置 `HttpException`(映射到 `moduleId: 0` 的预留 code);未知异常(SYSTEM 500)。
110
+
111
+ `BukaExceptions` 是与 `moduleId: 0` 映射一一对应的内置异常,抛标准异常时直接用:
112
+
113
+ ```typescript
114
+ throw new BukaExceptions.NotFound()
115
+ throw new BukaExceptions.BadRequest('自定义消息')
116
+ ```
117
+
118
+ 完整列表:`BadRequest`(400)、`Unauthorized`(401)、`Forbidden`(403)、`NotFound`(404)、`Conflict`(409)、`UnsupportedMediaType`(415)、`TooManyRequests`(429)、`InternalServerError`(500)、`BadGateway`(502)、`GatewayTimeout`(504)、`ServiceUnavailable`(503)。
119
+
120
+ > 内置 NestJS HttpException 也能被 filter 隐式映射,但业务代码统一走 `@ModuleExceptions` 工厂——错误码可检索、类别可控,裸 `throw new HttpException`(NestJS 内建类)跳过了错误码体系。
121
+
122
+ ## 结构化详情(ExceptionDetail)
123
+
124
+ ```typescript
125
+ import { ExceptionDetail } from '@buka/nestjs-kit'
126
+
127
+ class FieldErrorDetail implements ExceptionDetail {
128
+ readonly type = 'field_error'
129
+ constructor(
130
+ public readonly field: string,
131
+ public readonly reason: string,
132
+ ) {}
133
+ }
134
+
135
+ throw new StudentExceptions.Invalid('Invalid input', [
136
+ new FieldErrorDetail('age', 'must be positive'),
137
+ ])
138
+ ```
139
+
140
+ 固定消息模式构造第二参为 details;消息工厂模式最后一个参数为 details。详情进入响应体 `error.details`,是前端展示与排障的结构化材料,推荐对复杂校验/冲突场景提供。
141
+
142
+ ## 二方包定义异常
143
+
144
+ 二方包(业务 SDK)不关心 `systemId`,只认领自己的 `moduleId`:
145
+
146
+ ```typescript
147
+ // @buka/payment-sdk/payment.exceptions.ts
148
+ import { ModuleExceptions, ThirdPartyException } from '@buka/nestjs-kit'
149
+
150
+ @ModuleExceptions({ moduleId: '016G' }) // 公司统一分配给本包
151
+ export class PaymentExceptions {
152
+ static readonly GatewayTimeout = ThirdPartyException({
153
+ sequenceId: 1,
154
+ messageFactory: (orderId: string) => `支付网关超时: ${orderId}`,
155
+ })
156
+ }
157
+ ```
158
+
159
+ 宿主业务项目 `ExceptionModule.register({ systemId })` 后,抛出的 `PaymentExceptions.GatewayTimeout` 错误码自动带上宿主的 systemId。
160
+
161
+ ## 注意事项
162
+
163
+ - 必须先登记再使用:`sequenceId` 模块内自增管理;`moduleId` 业务模块在 1000-FZZZ 范围内声明(跨服务复用的模块保持一致)
164
+ - `description` 必写——它是 `GET /error-codes` 错误码查询接口的排障材料
165
+ - 内部错误使用 `SystemException`;第三方调用失败使用 `ThirdPartyException`(保留上游原始错误码,不包装成 SYSTEM,以正确告警归类)
166
+ - 找不到资源用 `BusinessException`/`BukaExceptions.NotFound`
167
+ - 全局 filter 恒装配,没有 `useGlobalFilter` 选项可禁用
168
+
169
+ ## 相关 skills
170
+
171
+ - [nestjs-kit-http](../nestjs-kit-http/SKILL.md) — keq 调上游时响应错误自动转成带码异常
172
+ - [nestjs-kit-swagger](../nestjs-kit-swagger/SKILL.md) — `unifyExceptionResponses` 同步异常响应文档