@buka/nestjs-kit 4.4.13 → 4.6.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.
- package/CHANGELOG.md +19 -0
- package/README.md +38 -0
- package/dist/index.d.mts +27 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +49 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +50 -1
- package/dist/index.mjs.map +1 -1
- package/docs/mikro-orm.md +20 -1
- package/docs/open-bao.md +1 -1
- package/package.json +1 -1
- package/skills/nestjs-kit-coding-standards/SKILL.md +149 -0
- package/skills/nestjs-kit-coding-standards/references/controller.md +108 -0
- package/skills/nestjs-kit-coding-standards/references/dto.md +195 -0
- package/skills/nestjs-kit-coding-standards/references/entity.md +173 -0
- package/skills/nestjs-kit-coding-standards/references/query.md +222 -0
- package/skills/nestjs-kit-coding-standards/references/service.md +136 -0
- package/skills/nestjs-kit-crypto/SKILL.md +126 -0
- package/skills/nestjs-kit-exception/SKILL.md +172 -0
- package/skills/nestjs-kit-http/SKILL.md +102 -0
- package/skills/nestjs-kit-logger/SKILL.md +113 -0
- package/skills/nestjs-kit-object-storage/SKILL.md +110 -0
- package/skills/nestjs-kit-open-bao/SKILL.md +121 -0
- package/skills/nestjs-kit-swagger/SKILL.md +73 -0
- package/skills/nestjs-kit-urn/SKILL.md +79 -0
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# 实体与关系(MikroORM 集成)
|
|
2
|
+
|
|
3
|
+
> 本文件由 [nestjs-kit-coding-standards/SKILL.md](../SKILL.md) 按需加载(定义实体时读本文件)。导入来源、事务与异常红线等通用约定见 [SKILL.md 「通用约定」章](../SKILL.md#通用约定跨文件类型);目录归属见 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织)。
|
|
4
|
+
|
|
5
|
+
## 前置条件
|
|
6
|
+
|
|
7
|
+
- 项目已完成 ORM 初始化(连接、migrations 等),实体的注册经 `MikroOrmModule.forFeature([...])` 完成。
|
|
8
|
+
- 实体在 API 中的默认呈现(外键序列化为 `{ id }` 骨架、未定义字段为 undefined)由 kit 默认序列化行为提供,实体本身无需手写 Swagger 装饰器。
|
|
9
|
+
|
|
10
|
+
## 命名与放置
|
|
11
|
+
|
|
12
|
+
实体存放于 `src/modules/<module-name>/entities/<name>.entity.ts`(目录规范见 [SKILL.md 「目录组织」章](../SKILL.md#业务模块目录组织))。一个实体一个文件,后缀 `.entity.ts`。若项目使用 `@nestjs/swagger` CLI 插件,`tsconfig.json` 的 `dtoFileNameSuffix` **不要包含 `.entity.ts`**——该插件对 MikroORM `Ref/Collection` 推断出的装饰器是错误的;实体的 Swagger 一律由 `Column.*`/`Cardinality.*` 自动生成。
|
|
13
|
+
|
|
14
|
+
## 速查表
|
|
15
|
+
|
|
16
|
+
| 要做什么 | 用什么 |
|
|
17
|
+
|---|---|
|
|
18
|
+
| 声明实体类 | `@Entity()`(自 `@mikro-orm/decorators/legacy` 导入)+ 继承基类 |
|
|
19
|
+
| 普通业务实体 | `DiscreteEntity`(UUIDv7 主键) |
|
|
20
|
+
| 自增主键实体 | `LinearEntity`(BigInt string) |
|
|
21
|
+
| 无主键附加表 | `TimestampedEntity` |
|
|
22
|
+
| 标量字段 | `Column.Varchar` / `Column.Text` / `Column.Int` / `Column.Boolean` 等 |
|
|
23
|
+
| 枚举字段 | `Column.Enum({ items, enumName })` |
|
|
24
|
+
| JSON 结构字段 | `Column.Jsonb({ type: () => Dto })` |
|
|
25
|
+
| 嵌入实体 | `Column.Embedded(() => Embeddable)` |
|
|
26
|
+
| 关系字段 | `Cardinality.ManyToOne` / `OneToOne` / `OneToMany` / `ManyToMany` |
|
|
27
|
+
| 引用类型/集合类型 | `Ref<Entity>` / `Collection<Entity>`(自 `@mikro-orm/core` 导入) |
|
|
28
|
+
|
|
29
|
+
## 基类选型
|
|
30
|
+
|
|
31
|
+
| 基类 | 主键 | 时间戳 | 适用 |
|
|
32
|
+
|---|---|---|---|
|
|
33
|
+
| `DiscreteEntity` | `id: string`,uuid 列 + `uuidv7()` 默认值;校验 `@IsUUID('7')` | ✅ | **绝大多数实体**(默认选择) |
|
|
34
|
+
| `LinearEntity` | `id: string`,`BigIntType('string')`;校验 `@IsNumberString()` | ✅ | 需要 BigInt 自增时序、非敏感暴露 |
|
|
35
|
+
| `TimestampedEntity` | 无 | ✅ `createdAt`/`updatedAt` | 中间表、日志表等无主键场景 |
|
|
36
|
+
|
|
37
|
+
三者都有泛型参数 `<Optional = never>`:声明 `extends DiscreteEntity<'extra' | 'fields'>` 让 MikroORM `OptionalProps` 感知子类有默认值的属性(有默认值的字段装饰器 `default` + 属性初始化需同时声明)。
|
|
38
|
+
|
|
39
|
+
## Column 列装饰器(18 种)
|
|
40
|
+
|
|
41
|
+
一次声明自动叠加三到四层:MikroORM `@Property` 映射 + class-validator 校验 + Swagger schema + Model 元数据。所有列支持 `comment`(同时写入数据库注释与 Swagger description)、`nullable`(联动 TS 可选与 Swagger required)、`default`/`onCreate`/`onUpdate`/`defaultRaw`、`lazy`(不默认查询、不出现在 Swagger)、`example/examples`。
|
|
42
|
+
|
|
43
|
+
| 装饰器 | TS 类型 | 自动校验 | 备注 |
|
|
44
|
+
|---|---|---|---|
|
|
45
|
+
| `Column.Varchar` | `string` | `IsString` + `MaxLength(length)` | 支持 `length` |
|
|
46
|
+
| `Column.Char` | `string` | `IsString` + `MinLength` + `MaxLength` | 定长,支持 `length` |
|
|
47
|
+
| `Column.Text` | `string` | `IsString` | 长文本 |
|
|
48
|
+
| `Column.Money` | `string` | `IsCurrency` | Swagger `format: 'money'`;金额用 string 防精度丢失 |
|
|
49
|
+
| `Column.Int` | `number` | `IsInt` | |
|
|
50
|
+
| `Column.Smallint` | `number` | `IsInt` | |
|
|
51
|
+
| `Column.Tinyint` | `number` | `IsInt` | |
|
|
52
|
+
| `Column.Bigint` | `string`(默认)/`number` | `IsString` / `IsInt` | 选项 `mode: 'string' \| 'number'`,默认 string 防精度丢失 |
|
|
53
|
+
| `Column.Double` | `number` | `IsNumber` | |
|
|
54
|
+
| `Column.Numeric` | `number` | `IsNumber` | |
|
|
55
|
+
| `Column.Boolean` | `boolean` | `IsBoolean` | |
|
|
56
|
+
| `Column.Uuid` | `string` | `IsString` | 需要版本校验时叠加 `@IsUUID('7')` |
|
|
57
|
+
| `Column.Date` | `string` | `Matches` + `IsISO8601({ strict: true })` | Swagger `format: 'date'`;JS 侧是 `YYYY-MM-DD` 字符串,不是 `Date` 对象 |
|
|
58
|
+
| `Column.Timestamptz` | `Date` | `IsISO8601` | 带时区时间戳 |
|
|
59
|
+
| `Column.Enum` | 自定义 enum | `IsEnumColumn`(`array: true` 时 `IsArray` + each) | `items` 必填,见下 |
|
|
60
|
+
| `Column.Jsonb` | DTO 对象 / 数组 | 无(可选) | 见下 |
|
|
61
|
+
| `Column.Transient` | `any` | 无 | 非持久化 |
|
|
62
|
+
| `Column.Embedded` | 嵌入类 | 无 | 嵌入式实体 |
|
|
63
|
+
|
|
64
|
+
### 枚举列
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
export enum BookStatus { DRAFT = 'draft', PUBLISHED = 'published' }
|
|
68
|
+
|
|
69
|
+
@Entity()
|
|
70
|
+
export class BookEntity extends DiscreteEntity {
|
|
71
|
+
@Column.Enum({
|
|
72
|
+
items: () => BookStatus, // 必填:枚举或取值数组,函数形式避免循环引用
|
|
73
|
+
enumName: 'BOOK_STATUS', // 数据库 enum 类型名
|
|
74
|
+
comment: '状态',
|
|
75
|
+
default: BookStatus.DRAFT,
|
|
76
|
+
})
|
|
77
|
+
status!: BookStatus
|
|
78
|
+
}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### JSONB 列
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
@Entity()
|
|
85
|
+
export class BookEntity extends DiscreteEntity {
|
|
86
|
+
@Column.Jsonb({ type: () => BookMetadata, comment: '元数据' })
|
|
87
|
+
metadata!: BookMetadata // kind: 'composite'(默认)
|
|
88
|
+
|
|
89
|
+
@Column.Jsonb({ type: () => Tag, kind: 'list', comment: '标签' })
|
|
90
|
+
tags!: Tag[] // kind: 'list'(隐藏属性默认 hidden,不进入 API 响应)
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 嵌入式实体
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
@Embeddable()
|
|
98
|
+
export class Audit {
|
|
99
|
+
@Column.Varchar({ length: 64, comment: '操作人' })
|
|
100
|
+
operator!: string
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
@Entity()
|
|
104
|
+
export class BookEntity extends DiscreteEntity {
|
|
105
|
+
@Column.Embedded(() => Audit, { object: true })
|
|
106
|
+
audit!: Audit
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Cardinality 关系装饰器(4 种)
|
|
111
|
+
|
|
112
|
+
封装 MikroORM `@OneToOne/@OneToMany/@ManyToOne/@ManyToMany`,内部同步注册 Model 元数据(to-one 走 `@Composite`、to-many 走 `@List`)与 Swagger schema。
|
|
113
|
+
|
|
114
|
+
四类关系装饰器统一使用 options 对象签名:`OneToMany` **仅接受 options 签名**(不接受位置式参数),`ManyToOne`/`OneToOne`/`ManyToMany` 兼容两种签名但统一使用 options 风格以保持一致性。
|
|
115
|
+
|
|
116
|
+
| 装饰器 | ORM 关系 | 字段类型 | 默认 Swagger 形态 |
|
|
117
|
+
|---|---|---|---|
|
|
118
|
+
| `Cardinality.ManyToOne` | m:1 | `Ref<Entity>` 或 `Entity` | `PrimaryKeyType`(`{ id }` 骨架) |
|
|
119
|
+
| `Cardinality.OneToOne` | 1:1 | `Ref<Entity>` 或 `Entity` | `PrimaryKeyType`(`{ id }` 骨架) |
|
|
120
|
+
| `Cardinality.OneToMany` | 1:m | `Collection<Entity>` | 不出现在 Swagger(默认 lazy) |
|
|
121
|
+
| `Cardinality.ManyToMany` | m:n | `Collection<Entity>` | 不出现在 Swagger(默认 lazy) |
|
|
122
|
+
|
|
123
|
+
非 eager 关系在 API 中默认以主键骨架 `{ id: 'xx' }` 呈现;`eager: true` 时才是完整实体对象结构。`mappedBy`:反向关系必填(`OneToMany` 强制),`ManyToMany` 双向时在其中一侧声明。
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { Entity } from '@mikro-orm/decorators/legacy'
|
|
127
|
+
import { Collection, Ref } from '@mikro-orm/core'
|
|
128
|
+
import { Cardinality, Column, DiscreteEntity } from '@buka/nestjs-kit'
|
|
129
|
+
|
|
130
|
+
@Entity({ comment: '图书' })
|
|
131
|
+
export class BookEntity extends DiscreteEntity {
|
|
132
|
+
@Column.Varchar({ length: 64, comment: '书名' })
|
|
133
|
+
name!: string
|
|
134
|
+
|
|
135
|
+
@Cardinality.ManyToOne({
|
|
136
|
+
entity: () => AuthorEntity,
|
|
137
|
+
comment: '作者',
|
|
138
|
+
hidden: false, // true 时仅 ApiHideProperty,不注册模型元数据
|
|
139
|
+
})
|
|
140
|
+
author!: Ref<AuthorEntity>
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
@Entity({ comment: '作者' })
|
|
144
|
+
export class AuthorEntity extends DiscreteEntity {
|
|
145
|
+
@Column.Varchar({ length: 64, comment: '姓名' })
|
|
146
|
+
name!: string
|
|
147
|
+
|
|
148
|
+
@Cardinality.OneToMany({
|
|
149
|
+
entity: () => BookEntity,
|
|
150
|
+
mappedBy: 'author', // 必填
|
|
151
|
+
comment: '作品列表',
|
|
152
|
+
})
|
|
153
|
+
books = new Collection<BookEntity>(this)
|
|
154
|
+
}
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
常见选项:`entity`(必填,`() => Target` 函数形式避免循环引用)、`comment`、`nullable`、`ref: true`、`eager`(MikroORM 自动 populate + Swagger 用完整实体)、`hidden`、`mappedBy`、`pivotEntity`(`ManyToMany`,无中间表实体时可省略)、`owner`/`inversedBy`(`ManyToMany` 双向时)。
|
|
158
|
+
|
|
159
|
+
## 实体派生与类型工具
|
|
160
|
+
|
|
161
|
+
- `EntityDto(Entity)` / `PrimaryKeyType(Entity)` / `@EntityRef(() => Entity)` —— 响应 DTO 派生,见 [references/dto.md](dto.md)
|
|
162
|
+
- 类型工具(`import type { ... } from '@buka/nestjs-kit'`):
|
|
163
|
+
`ExcludeRef<T>`(解包 Ref → 实体)、`ExcludeOpt<T>`(去除 Opt/undefined)、`ExcludeHidden<T>`、`IsOpt<T>`、`IsHidden<T>`
|
|
164
|
+
|
|
165
|
+
## 注意事项
|
|
166
|
+
|
|
167
|
+
- 每个 `Column.*`/`Cardinality.*` 必须传 `comment`(中文语义;同时是数据库注释与 Swagger description)
|
|
168
|
+
- 关联默认返回 `Ref` 骨架;detail 接口才用 `EntityDto(Entity)` 派生 + 显式 `populate`;`eager: true` 只用于确需全量关联的场景
|
|
169
|
+
- `Column.Money`/`Column.Bigint`(默认 mode)类型是 `string`,属性声明为 `string` 而非 `number`
|
|
170
|
+
- 枚举列 `items` 永远用 `() => Enum` 函数形式(避免编译期循环引用问题)
|
|
171
|
+
- 基类为 `DiscreteEntity`/`LinearEntity`/`TimestampedEntity`;`BaseEntity` 类不存在于 kit 中
|
|
172
|
+
- 时间戳字段由 `TimestampedEntity` 统一提供,无需自行添加 `createdAt` 列
|
|
173
|
+
- filter/order 能力直接依赖本文件装饰器生成的元数据(见 [references/query.md](query.md))
|
|
@@ -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` 嵌入
|