@vessel-agent/guardrail-pii 0.0.0-stage → 2.3.0-beta.3
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/package.json +29 -4
- package/src/index.ts +285 -0
- package/src/rules.ts +197 -0
- package/README.md +0 -3
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vessel-agent/guardrail-pii",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "2.3.0-beta.3",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "src/index.ts",
|
|
6
|
+
"types": "src/index.ts",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.ts"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/egg-rolls/Vessel.git",
|
|
17
|
+
"directory": "plugins/security/guardrail-pii"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"bun": ">=1.3.9"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"typecheck": "tsc --noEmit"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@vessel-agent/core": "2.3.0-beta.3"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"typescript": "^7.0.2"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @vessel-agent/guardrail-pii - PII 守卫插件
|
|
3
|
+
* @module @vessel-agent/guardrail-pii
|
|
4
|
+
*
|
|
5
|
+
* ## 位置纪律(0.52 修 bug + 0.52 vault 迁移后的口径)
|
|
6
|
+
*
|
|
7
|
+
* 脱敏**只允许发生在 append 侧(写入上下文那一刻)**:落盘即占位符,store / 请求 / UI
|
|
8
|
+
* 共用同一份字节。**绝不许回改已经落盘 / 已经发出的消息**(append-only + 前缀缓存)。
|
|
9
|
+
*
|
|
10
|
+
* 0.52 之前本插件在 `GuardrailStage.Output` 返回 `replacement`,而 Output / ToolResult
|
|
11
|
+
* 的 replacement 会被写进会话存储 —— append-only 的 transcript 是不可逆数据,于是
|
|
12
|
+
* 「13 位毫秒时间戳被当成手机号」这条误伤直接改坏了历史正文(`1794482135404` →
|
|
13
|
+
* `179*******404`),并且改过正文与流式渲染出来的正文对不上,是「重复渲染」的触发源。
|
|
14
|
+
*
|
|
15
|
+
* 现在分成两半:
|
|
16
|
+
* - `PIIGuardrail.check()` **只检测、只报告**,永不返回 `replacement`(写侧零改写);
|
|
17
|
+
* - 真正的打码由 core 的 `pii-vault` 在 `ExecutionUnit.maskForAppend` 里完成
|
|
18
|
+
* (`vault.protect()` 句柄化,超限降级为掩码),本插件登记的 masker 作为**补充**在
|
|
19
|
+
* 同一处被调用(幂等,给第三方 masker 留扩展点)。
|
|
20
|
+
*
|
|
21
|
+
* 判定口径**委托 core 单源**(q-pii-redaction-unify P1,宪法 15):规则见 core
|
|
22
|
+
* `pii/rules.ts`;本插件 `./rules.js` 只保留配置开关 / SSN / 自定义规则扩展点。
|
|
23
|
+
* 核心规则集与句柄 vault 见 core 的 `pii/`。
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import type {
|
|
27
|
+
Guardrail,
|
|
28
|
+
GuardrailContext,
|
|
29
|
+
GuardrailResult,
|
|
30
|
+
Plugin,
|
|
31
|
+
PluginHost,
|
|
32
|
+
ReadSideMasker,
|
|
33
|
+
ToolDefinition,
|
|
34
|
+
} from '@vessel-agent/core';
|
|
35
|
+
import { createPiiRevealTool, GuardrailStage, getPiiVault } from '@vessel-agent/core';
|
|
36
|
+
import { detectPii, maskText, type PiiDetection, type PiiRuleOptions } from './rules.js';
|
|
37
|
+
|
|
38
|
+
export type { PiiDetection, PiiRuleOptions, PiiType } from './rules.js';
|
|
39
|
+
export { detectPii, isValidCnIdCard, maskText, passesLuhn } from './rules.js';
|
|
40
|
+
|
|
41
|
+
/** PII 守卫配置 */
|
|
42
|
+
export interface PIIGuardrailConfig {
|
|
43
|
+
/** 总开关(缺省 true):关掉后检测与脱敏一起停 */
|
|
44
|
+
enabled?: boolean;
|
|
45
|
+
/** 是否检测邮箱(用户安全政策 2026-12-01 起缺省 false = 放行;true = opt-in 回遮) */
|
|
46
|
+
detectEmail?: boolean;
|
|
47
|
+
/** 是否检测电话(缺省 true;低置信形状命中按 core 政策放行,高置信仍遮) */
|
|
48
|
+
detectPhone?: boolean;
|
|
49
|
+
/** 是否检测身份证号(大陆 18 位,校验位说了算) */
|
|
50
|
+
detectIdCard?: boolean;
|
|
51
|
+
/** 是否检测美国式 SSN(要求带分隔符) */
|
|
52
|
+
detectSSN?: boolean;
|
|
53
|
+
/** 是否检测信用卡号 */
|
|
54
|
+
detectCreditCard?: boolean;
|
|
55
|
+
/** 自定义正则表达式 */
|
|
56
|
+
customPatterns?: Array<{ name: string; pattern: RegExp }>;
|
|
57
|
+
/** 脱敏策略 */
|
|
58
|
+
maskingStrategy?: 'full' | 'partial' | 'hash';
|
|
59
|
+
/** 脱敏开关(缺省 true):关掉后 append 侧也不打码(真值原样落盘) */
|
|
60
|
+
maskOnRead?: boolean;
|
|
61
|
+
/**
|
|
62
|
+
* 命中后怎么办(缺省 `report`):
|
|
63
|
+
* - `report`:只记录,不改写任何东西;
|
|
64
|
+
* - `block`:直接拒绝(`allowed: false`)。
|
|
65
|
+
* 无论哪个值,写侧都不会拿到 `replacement`。
|
|
66
|
+
*/
|
|
67
|
+
action?: 'report' | 'block';
|
|
68
|
+
/**
|
|
69
|
+
* 熵启发(缺省 `false`,0.52 句柄层专用开关):
|
|
70
|
+
* 阈值保守且要求与「密钥类关键字」同行共现,宁可漏掉可疑随机串,
|
|
71
|
+
* 也不要把 hash / base64 / diff 全打码。详见 core 的 `pii/rules.ts`。
|
|
72
|
+
*/
|
|
73
|
+
entropy?: boolean;
|
|
74
|
+
/**
|
|
75
|
+
* 句柄 TTL(分钟,缺省 10;q-pii-handle-reveal-fix P1)。滑动续期:命中即续。
|
|
76
|
+
* 只调内存生命周期参数 —— 真值只活内存、审批解锁、fail-closed 硬约束不动。
|
|
77
|
+
* 合法范围 1..1440(超出钳制);长会话频繁「句柄过期」时可适度调大。
|
|
78
|
+
*/
|
|
79
|
+
handleTtlMinutes?: number;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** E1:`install(host, {config})` 的窄类型(core 尚未声明第二参数) */
|
|
83
|
+
export interface PluginInstallOptions {
|
|
84
|
+
config?: Record<string, unknown>;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 类型守卫 */
|
|
88
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
89
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 把 YAML 插件配置解析成 PIIGuardrailConfig(pattern 支持字符串或 RegExp) */
|
|
93
|
+
export function parsePiiGuardrailConfig(value: unknown): PIIGuardrailConfig {
|
|
94
|
+
if (!isRecord(value)) return {};
|
|
95
|
+
const parsed: PIIGuardrailConfig = {};
|
|
96
|
+
for (const key of [
|
|
97
|
+
'enabled',
|
|
98
|
+
'detectEmail',
|
|
99
|
+
'detectPhone',
|
|
100
|
+
'detectIdCard',
|
|
101
|
+
'detectSSN',
|
|
102
|
+
'detectCreditCard',
|
|
103
|
+
'maskOnRead',
|
|
104
|
+
'entropy',
|
|
105
|
+
] as const) {
|
|
106
|
+
if (typeof value[key] === 'boolean') parsed[key] = value[key];
|
|
107
|
+
}
|
|
108
|
+
if (
|
|
109
|
+
value.maskingStrategy === 'full' ||
|
|
110
|
+
value.maskingStrategy === 'partial' ||
|
|
111
|
+
value.maskingStrategy === 'hash'
|
|
112
|
+
) {
|
|
113
|
+
parsed.maskingStrategy = value.maskingStrategy;
|
|
114
|
+
}
|
|
115
|
+
if (value.action === 'report' || value.action === 'block') {
|
|
116
|
+
parsed.action = value.action;
|
|
117
|
+
}
|
|
118
|
+
if (typeof value.handleTtlMinutes === 'number' && Number.isFinite(value.handleTtlMinutes)) {
|
|
119
|
+
parsed.handleTtlMinutes = Math.min(1440, Math.max(1, value.handleTtlMinutes));
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
if (Array.isArray(value.customPatterns)) {
|
|
123
|
+
const customPatterns: NonNullable<PIIGuardrailConfig['customPatterns']> = [];
|
|
124
|
+
for (const item of value.customPatterns) {
|
|
125
|
+
if (!isRecord(item) || typeof item.name !== 'string') continue;
|
|
126
|
+
let pattern: RegExp | undefined;
|
|
127
|
+
if (item.pattern instanceof RegExp) {
|
|
128
|
+
pattern = new RegExp(item.pattern.source, item.pattern.flags);
|
|
129
|
+
} else if (typeof item.pattern === 'string') {
|
|
130
|
+
const rawFlags = typeof item.flags === 'string' ? item.flags : '';
|
|
131
|
+
// 非全局正则在 exec 循环里不会前进
|
|
132
|
+
const flags = rawFlags.includes('g') ? rawFlags : `${rawFlags}g`;
|
|
133
|
+
try {
|
|
134
|
+
pattern = new RegExp(item.pattern, flags);
|
|
135
|
+
} catch {
|
|
136
|
+
pattern = undefined;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
if (pattern !== undefined) customPatterns.push({ name: item.name, pattern });
|
|
140
|
+
}
|
|
141
|
+
parsed.customPatterns = customPatterns;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return parsed;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** 默认配置 */
|
|
148
|
+
const DEFAULT_CONFIG: Required<
|
|
149
|
+
Pick<PIIGuardrailConfig, 'enabled' | 'maskOnRead' | 'action' | 'maskingStrategy'>
|
|
150
|
+
> & {
|
|
151
|
+
detectEmail: boolean;
|
|
152
|
+
detectPhone: boolean;
|
|
153
|
+
detectIdCard: boolean;
|
|
154
|
+
detectSSN: boolean;
|
|
155
|
+
detectCreditCard: boolean;
|
|
156
|
+
} = {
|
|
157
|
+
enabled: true,
|
|
158
|
+
maskOnRead: true,
|
|
159
|
+
action: 'report',
|
|
160
|
+
maskingStrategy: 'partial',
|
|
161
|
+
// email 默认放行(用户安全政策 2026-12-01:phone/email 泄露风险低,保护重心
|
|
162
|
+
// API KEY/secret);显式 detectEmail: true = opt-in 回遮。phone 低置信放行由
|
|
163
|
+
// core 政策缺省生效(高置信关键字窗口仍遮)。ID/card 维持现态(校验位判据)。
|
|
164
|
+
detectEmail: false,
|
|
165
|
+
detectPhone: true,
|
|
166
|
+
detectIdCard: true,
|
|
167
|
+
detectSSN: true,
|
|
168
|
+
detectCreditCard: true,
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
/** 配置 → 规则选项 */
|
|
172
|
+
function toRuleOptions(config: PIIGuardrailConfig): PiiRuleOptions {
|
|
173
|
+
return {
|
|
174
|
+
...(config.detectEmail !== undefined ? { detectEmail: config.detectEmail } : {}),
|
|
175
|
+
...(config.detectPhone !== undefined ? { detectPhone: config.detectPhone } : {}),
|
|
176
|
+
...(config.detectIdCard !== undefined ? { detectIdCard: config.detectIdCard } : {}),
|
|
177
|
+
...(config.detectSSN !== undefined ? { detectSSN: config.detectSSN } : {}),
|
|
178
|
+
...(config.detectCreditCard !== undefined ? { detectCreditCard: config.detectCreditCard } : {}),
|
|
179
|
+
...(config.customPatterns !== undefined ? { customPatterns: config.customPatterns } : {}),
|
|
180
|
+
...(config.maskingStrategy !== undefined ? { maskingStrategy: config.maskingStrategy } : {}),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 补充脱敏器(0.52):给 core 的 `pii-vault` 打补丁用。
|
|
186
|
+
*
|
|
187
|
+
* 它被登记到 `PluginHost`,由 `ExecutionUnit.maskForAppend` 在**写入上下文那一刻**
|
|
188
|
+
* 调用(句柄化之后,幂等)。核心规则集已是超集,所以正常情况是 no-op;它存在的意义
|
|
189
|
+
* 是给「插件自定义规则」留扩展点。`enabled` / `maskOnRead` 任一为 false 时原样返回。
|
|
190
|
+
*/
|
|
191
|
+
export function createPiiMasker(config: PIIGuardrailConfig = {}): ReadSideMasker {
|
|
192
|
+
const merged: PIIGuardrailConfig = { ...DEFAULT_CONFIG, ...config };
|
|
193
|
+
const options = toRuleOptions(merged);
|
|
194
|
+
return {
|
|
195
|
+
name: 'pii',
|
|
196
|
+
mask(text: string): string {
|
|
197
|
+
if (merged.enabled === false || merged.maskOnRead === false) return text;
|
|
198
|
+
return maskText(text, options);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* PII 守卫实现:**只检测、只报告**。
|
|
205
|
+
*
|
|
206
|
+
* 关键不变量:`check()` 的返回值里永远没有 `replacement`。写侧任何阶段(Input /
|
|
207
|
+
* Output / ToolResult)拿到它都不会改写正文 —— 否则 append-only 的会话正文会被
|
|
208
|
+
* 不可逆地污染(0.52 的 bug)。
|
|
209
|
+
*/
|
|
210
|
+
export class PIIGuardrail implements Guardrail {
|
|
211
|
+
name = 'pii-guardrail';
|
|
212
|
+
stage = GuardrailStage.Output;
|
|
213
|
+
priority = 100;
|
|
214
|
+
|
|
215
|
+
private config: PIIGuardrailConfig;
|
|
216
|
+
private options: PiiRuleOptions;
|
|
217
|
+
|
|
218
|
+
constructor(config: PIIGuardrailConfig = {}) {
|
|
219
|
+
this.config = { ...DEFAULT_CONFIG, ...config };
|
|
220
|
+
this.options = toRuleOptions(this.config);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async check(value: unknown, _ctx: GuardrailContext): Promise<GuardrailResult> {
|
|
224
|
+
if (this.config.enabled === false || typeof value !== 'string') {
|
|
225
|
+
return { allowed: true };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const detections: PiiDetection[] = detectPii(value, this.options);
|
|
229
|
+
if (detections.length === 0) {
|
|
230
|
+
return { allowed: true };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const types = [...new Set(detections.map((detection) => detection.type))];
|
|
234
|
+
const reason = `pii_detected: ${detections.length} item(s) [${types.join(', ')}]`;
|
|
235
|
+
|
|
236
|
+
if (this.config.action === 'block') {
|
|
237
|
+
return { allowed: false, reason };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// report:只报告,**不返回 replacement**(脱敏在读侧,见 createPiiMasker)
|
|
241
|
+
return { allowed: true, reason };
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 创建 PII 守卫插件
|
|
247
|
+
*/
|
|
248
|
+
export function createPiiGuardrailPlugin(config?: PIIGuardrailConfig): Plugin {
|
|
249
|
+
return {
|
|
250
|
+
name: 'guardrail-pii',
|
|
251
|
+
version: '0.2.0',
|
|
252
|
+
description: 'PII detection guardrail + read-side masking',
|
|
253
|
+
install(host: PluginHost, options?: PluginInstallOptions) {
|
|
254
|
+
const merged = {
|
|
255
|
+
...(config ?? {}),
|
|
256
|
+
...parsePiiGuardrailConfig(options?.config),
|
|
257
|
+
};
|
|
258
|
+
host.registerGuardrail(new PIIGuardrail(merged));
|
|
259
|
+
// 补充脱敏器:由 core 在 append 侧调用(幂等)。旧宿主没有这个方法时退化成「只报告」,不炸。
|
|
260
|
+
if (typeof host.registerReadSideMasker === 'function') {
|
|
261
|
+
host.registerReadSideMasker(createPiiMasker(merged));
|
|
262
|
+
}
|
|
263
|
+
// 0.52 句柄 vault:与 masker 同一个开关(配置关掉就整层直通)。
|
|
264
|
+
// 句柄是真值的**唯一**内存副本,不落盘;解锁只能走 pii_reveal(人工审批)。
|
|
265
|
+
const vault = getPiiVault();
|
|
266
|
+
vault.configure({
|
|
267
|
+
enabled: merged.enabled !== false && merged.maskOnRead !== false,
|
|
268
|
+
entropy: merged.entropy === true,
|
|
269
|
+
// TTL 可配置(q-pii-handle-reveal-fix P1):缺省不传 = core 默认 10 分钟。
|
|
270
|
+
...(merged.handleTtlMinutes !== undefined
|
|
271
|
+
? { ttlMs: merged.handleTtlMinutes * 60_000 }
|
|
272
|
+
: {}),
|
|
273
|
+
});
|
|
274
|
+
// 审批解锁工具:权限判定复用现有 ask / permission 链(`checkPermission: 'ask'`)。
|
|
275
|
+
if (typeof host.registerTool === 'function') {
|
|
276
|
+
host.registerTool(createPiiRevealTool({ vault }) as ToolDefinition);
|
|
277
|
+
}
|
|
278
|
+
},
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 默认实例——现有调用方无需改动 */
|
|
283
|
+
export const piiGuardrailPlugin: Plugin = createPiiGuardrailPlugin();
|
|
284
|
+
|
|
285
|
+
export default piiGuardrailPlugin;
|
package/src/rules.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PII 规则的判定与脱敏(0.52 pii-guard;q-pii-redaction-unify P1 起**委托 core 单源**)。
|
|
3
|
+
* @module @vessel-agent/guardrail-pii
|
|
4
|
+
*
|
|
5
|
+
* 宪法 15(单源):检测规则的唯一真相源是 core 的 `pii/rules.ts`(整串分类 +
|
|
6
|
+
* 校验位 + 形态规则 + 熵启发)。本文件不再持有平行的手机号/身份证/银行卡/邮箱
|
|
7
|
+
* 规则副本——此前 `CN_MOBILE` / `CARD_SHAPES` / `scanDigitRuns` / `classifyRun`
|
|
8
|
+
* 与 core 各自演化即漂移风险(probe §1.1 实证的三副本之一)。
|
|
9
|
+
*
|
|
10
|
+
* 保留在本插件的只有**扩展点**,不是副本:
|
|
11
|
+
* 1. 配置开关(detectEmail/detectPhone/detectIdCard/detectCreditCard)⇒ 翻译成
|
|
12
|
+
* core detect 的 `excludeCategories`(显式 false 才关,缺省全开);
|
|
13
|
+
* 2. 美国式 SSN(带分隔符 `123-45-6789`):core 无此类别,插件专属扩展;
|
|
14
|
+
* 3. `customPatterns` 自定义正则扩展点;
|
|
15
|
+
* 4. 脱敏策略(full/partial/hash)——core 句柄化之后的补充打码形状。
|
|
16
|
+
*
|
|
17
|
+
* 覆盖面(secret 只增不减;phone/email 按用户政策放宽):core 规则集是原插件
|
|
18
|
+
* 副本的超集——银行卡(15-19 位任意 Luhn ⊇ 原四卡组织形状)、身份证(粗日期
|
|
19
|
+
* 校验 ⊇ 原严格日期校验)、手机号(11 位 + 86 国家码 13 位,后者已收敛进 core)。
|
|
20
|
+
* **用户安全政策(2026-12-01,main 转权威决策)**:保护重心 = API KEY/secret/
|
|
21
|
+
* credential/token(高优先强保护,全通道遮蔽 + 禁落盘,绝不削弱);phone 低置信
|
|
22
|
+
* 形状命中与 email 默认放行(泄露风险低),高置信 phone(关键字窗口)仍遮;
|
|
23
|
+
* ID/card 维持现态(校验位误报低)。secret 优先级恒高于 phone/email 形状匹配
|
|
24
|
+
* (重叠消解 secret 整段先遮,防 secret 中数字串被 phone 形状误判放行)。
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { detectPiiHits, type PiiCategory } from '@vessel-agent/core';
|
|
28
|
+
|
|
29
|
+
/** 校验位工具与 core 同源(re-export,不再另写一份)。 */
|
|
30
|
+
export { isValidCnIdCard, passesLuhn } from '@vessel-agent/core';
|
|
31
|
+
|
|
32
|
+
/** PII 类型(自定义规则的名字也落在这个位置) */
|
|
33
|
+
export type PiiType = 'email' | 'phone' | 'ssn' | 'id_card' | 'credit_card' | (string & {});
|
|
34
|
+
|
|
35
|
+
/** 一条命中:[start, end) 用原文下标,value 即原文切片 */
|
|
36
|
+
export interface PiiDetection {
|
|
37
|
+
type: PiiType;
|
|
38
|
+
value: string;
|
|
39
|
+
start: number;
|
|
40
|
+
end: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** 判定开关(缺省全开;显式 false 才关) */
|
|
44
|
+
export interface PiiRuleOptions {
|
|
45
|
+
detectEmail?: boolean;
|
|
46
|
+
detectPhone?: boolean;
|
|
47
|
+
/** 美国式 SSN:要求带分隔符,避免把长数串咬成 9 位 */
|
|
48
|
+
detectSSN?: boolean;
|
|
49
|
+
/** 大陆 18 位身份证(校验位) */
|
|
50
|
+
detectIdCard?: boolean;
|
|
51
|
+
detectCreditCard?: boolean;
|
|
52
|
+
customPatterns?: Array<{ name: string; pattern: RegExp }>;
|
|
53
|
+
maskingStrategy?: 'full' | 'partial' | 'hash';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** core 类别 → 插件类型名(历史命名 credit_card;其余类别原样透传)。 */
|
|
57
|
+
function typeOfCategory(category: PiiCategory): PiiType {
|
|
58
|
+
return category === 'bank_card' ? 'credit_card' : category;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 重叠区间消解:先出现的优先,后出现的重叠片段丢弃(宁少遮也不遮错位置) */
|
|
62
|
+
export function resolveOverlaps(detections: readonly PiiDetection[]): PiiDetection[] {
|
|
63
|
+
const sorted = [...detections].sort((a, b) => a.start - b.start || b.end - a.end);
|
|
64
|
+
const result: PiiDetection[] = [];
|
|
65
|
+
for (const detection of sorted) {
|
|
66
|
+
const previous = result[result.length - 1];
|
|
67
|
+
if (previous !== undefined && detection.start < previous.end) continue;
|
|
68
|
+
result.push(detection);
|
|
69
|
+
}
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 检测文本中的 PII(结果已排序、无重叠)。规则判定委托 core 单源。 */
|
|
74
|
+
export function detectPii(text: string, options: PiiRuleOptions = {}): PiiDetection[] {
|
|
75
|
+
const detections: PiiDetection[] = [];
|
|
76
|
+
|
|
77
|
+
// 1) core 全规则(整串数字分类 + 校验位 + 形态规则)。开关语义保持:
|
|
78
|
+
// 显式 false ⇒ 排除对应类别;缺省全开。熵启发不在此启用(vault 专属开关)。
|
|
79
|
+
// email 按用户安全政策(2026-12-01)默认放行:detectEmail 显式 true 才
|
|
80
|
+
// opt-in 回遮(core maskEmail);phone 低置信放行由 core 政策缺省生效。
|
|
81
|
+
const excludeCategories = new Set<PiiCategory>();
|
|
82
|
+
if (options.detectEmail === false) excludeCategories.add('email');
|
|
83
|
+
if (options.detectPhone === false) excludeCategories.add('phone');
|
|
84
|
+
if (options.detectIdCard === false) excludeCategories.add('id_card');
|
|
85
|
+
if (options.detectCreditCard === false) excludeCategories.add('bank_card');
|
|
86
|
+
for (const hit of detectPiiHits(text, {
|
|
87
|
+
excludeCategories,
|
|
88
|
+
...(options.detectEmail === true ? { maskEmail: true } : {}),
|
|
89
|
+
})) {
|
|
90
|
+
detections.push({
|
|
91
|
+
type: typeOfCategory(hit.category),
|
|
92
|
+
value: hit.text,
|
|
93
|
+
start: hit.start,
|
|
94
|
+
end: hit.end,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// 2) 美国式 SSN(插件专属扩展,core 无此类别):必须带分隔符 `123-45-6789`,
|
|
99
|
+
// 裸 9 位数字不判——它会咬长数串。
|
|
100
|
+
if (options.detectSSN !== false) {
|
|
101
|
+
const pattern = /(?<![0-9])[0-9]{3}-[0-9]{2}-[0-9]{4}(?![0-9])/g;
|
|
102
|
+
let match = pattern.exec(text);
|
|
103
|
+
while (match !== null) {
|
|
104
|
+
detections.push({
|
|
105
|
+
type: 'ssn',
|
|
106
|
+
value: match[0],
|
|
107
|
+
start: match.index,
|
|
108
|
+
end: match.index + match[0].length,
|
|
109
|
+
});
|
|
110
|
+
match = pattern.exec(text);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// 3) 自定义正则扩展点(原样保留)。
|
|
115
|
+
for (const custom of options.customPatterns ?? []) {
|
|
116
|
+
const flags = custom.pattern.flags.includes('g')
|
|
117
|
+
? custom.pattern.flags
|
|
118
|
+
: `${custom.pattern.flags}g`;
|
|
119
|
+
const pattern = new RegExp(custom.pattern.source, flags);
|
|
120
|
+
let match = pattern.exec(text);
|
|
121
|
+
while (match !== null) {
|
|
122
|
+
if (match[0].length === 0) {
|
|
123
|
+
pattern.lastIndex += 1;
|
|
124
|
+
} else {
|
|
125
|
+
detections.push({
|
|
126
|
+
type: custom.name,
|
|
127
|
+
value: match[0],
|
|
128
|
+
start: match.index,
|
|
129
|
+
end: match.index + match[0].length,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
match = pattern.exec(text);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return resolveOverlaps(detections);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 脱敏单个值 */
|
|
140
|
+
export function maskPiiValue(
|
|
141
|
+
value: string,
|
|
142
|
+
type: PiiType,
|
|
143
|
+
strategy: PiiRuleOptions['maskingStrategy'] = 'partial',
|
|
144
|
+
): string {
|
|
145
|
+
switch (strategy) {
|
|
146
|
+
case 'full':
|
|
147
|
+
return '*'.repeat(value.length);
|
|
148
|
+
case 'hash':
|
|
149
|
+
return `[REDACTED_${String(type).toUpperCase()}]`;
|
|
150
|
+
case 'partial':
|
|
151
|
+
default: {
|
|
152
|
+
if (type === 'email') {
|
|
153
|
+
const at = value.indexOf('@');
|
|
154
|
+
if (at <= 0) return `${value[0] ?? ''}***`;
|
|
155
|
+
return `${value.slice(0, 1)}***${value.slice(at)}`;
|
|
156
|
+
}
|
|
157
|
+
if (type === 'phone') {
|
|
158
|
+
// 保留后 4 位,其余数字打码(`13800138000` → `*******8000`)
|
|
159
|
+
const total = value.replace(/[^0-9]/g, '').length;
|
|
160
|
+
let seen = 0;
|
|
161
|
+
return value.replace(/[0-9]/g, (char) => {
|
|
162
|
+
seen += 1;
|
|
163
|
+
return seen > total - 4 ? char : '*';
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (value.length <= 4) return '*'.repeat(value.length);
|
|
167
|
+
return `${value.slice(0, 2)}${'*'.repeat(value.length - 4)}${value.slice(value.length - 2)}`;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 按命中位置脱敏整段文本(从后往前替换,避免下标漂移) */
|
|
173
|
+
export function maskWithDetections(
|
|
174
|
+
text: string,
|
|
175
|
+
detections: readonly PiiDetection[],
|
|
176
|
+
strategy: PiiRuleOptions['maskingStrategy'] = 'partial',
|
|
177
|
+
): string {
|
|
178
|
+
if (detections.length === 0) return text;
|
|
179
|
+
let result = text;
|
|
180
|
+
for (let i = detections.length - 1; i >= 0; i -= 1) {
|
|
181
|
+
const detection = detections[i];
|
|
182
|
+
if (detection === undefined) continue;
|
|
183
|
+
result =
|
|
184
|
+
result.slice(0, detection.start) +
|
|
185
|
+
maskPiiValue(detection.value, detection.type, strategy) +
|
|
186
|
+
result.slice(detection.end);
|
|
187
|
+
}
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* 读侧脱敏:检测 + 打码一步到位。
|
|
193
|
+
* 只在请求构造 / 展示投影里调用;落盘原文一个字都不许改。
|
|
194
|
+
*/
|
|
195
|
+
export function maskText(text: string, options: PiiRuleOptions = {}): string {
|
|
196
|
+
return maskWithDetections(text, detectPii(text, options), options.maskingStrategy);
|
|
197
|
+
}
|
package/README.md
DELETED