@liuhange/dsh-data-masking 2.0.0 → 2.0.2

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/lib/index.js CHANGED
@@ -1,131 +1,115 @@
1
- import { defineTool } from "@deepseek-ai/dsh-tools";
2
- import * as fs from "fs";
3
- import * as path from "path";
4
- import { AuditLogger, BusinessRulesLoader, FileFormatAdapter, PathValidator, ReportGenerator } from "@deepseek-ai/dsh-data-asset-shared";
5
- //#region lib/types/sensitiveFieldScanner.js
6
- var SensitiveFieldScanner = class {
7
- scan(lines, sensitivePatterns) {
8
- const fields = [];
9
- const typeCounts = {};
10
- const patternEntries = Object.entries(sensitivePatterns);
11
- for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
12
- const line = lines[lineIndex] ?? "";
13
- for (const [type, config] of patternEntries) {
14
- const regex = new RegExp(config.pattern, "g");
15
- let match;
16
- while ((match = regex.exec(line)) !== null) {
17
- fields.push({
18
- type,
19
- value: match[0],
20
- line: lineIndex + 1,
21
- column: match.index + 1
22
- });
23
- typeCounts[type] = (typeCounts[type] ?? 0) + 1;
24
- }
25
- }
26
- }
27
- return {
28
- fields,
29
- typeCounts
30
- };
31
- }
32
- };
33
- //#endregion
34
- //#region lib/types/maskingStrategyExecutor.js
35
- var MaskingStrategyExecutor = class {
36
- execute(value, _type, strategy) {
37
- switch (this.resolveStrategy(strategy)) {
38
- case "FULL": return "***";
39
- case "PARTIAL": return this.applyPartial(value);
40
- case "GENERALIZE": return "<脱敏数据>";
41
- }
42
- }
43
- resolveStrategy(strategy) {
44
- if (strategy === "FULL" || strategy === "PARTIAL" || strategy === "GENERALIZE") return strategy;
45
- return "PARTIAL";
46
- }
47
- applyPartial(value, keepPrefix = 3, keepSuffix = 4) {
48
- if (value.length <= keepPrefix + keepSuffix) return "***";
49
- return value.slice(0, keepPrefix) + "***" + value.slice(-keepSuffix);
50
- }
51
- };
52
- //#endregion
53
- //#region lib/types/index.js
54
- const name = "data-masking";
55
- const inject = ["tools"];
56
- function apply(ctx) {
57
- const loader = new BusinessRulesLoader();
58
- const formatAdapter = new FileFormatAdapter();
59
- const reportGenerator = new ReportGenerator();
60
- const pathValidator = new PathValidator();
61
- const auditLogger = new AuditLogger();
62
- const scanner = new SensitiveFieldScanner();
63
- const strategyExecutor = new MaskingStrategyExecutor();
64
- ctx.tools.register(defineTool({
65
- name: "mask_sensitive_data",
66
- description: "识别并脱敏数据中的敏感字段(身份证、手机号、银行卡、邮箱)",
67
- parameters: {
68
- filePath: {
69
- type: "string",
70
- required: true,
71
- description: "待处理文件的路径"
72
- },
73
- strategy: {
74
- type: "string",
75
- description: "脱敏策略: FULL | PARTIAL | GENERALIZE"
76
- }
77
- },
78
- output: {
79
- schema: { type: "string" },
80
- render: (_args, value) => [{
81
- type: "text",
82
- text: value
83
- }]
84
- },
85
- async execute(args) {
86
- const { config } = loader.load();
87
- const workingDir = process.cwd();
88
- const filePath = args.filePath;
89
- const strategy = args.strategy ?? "PARTIAL";
90
- try {
91
- pathValidator.validate(filePath, workingDir);
92
- } catch {
93
- return `错误:路径不合法 - ${filePath}`;
94
- }
95
- const fullPath = path.resolve(filePath);
96
- if (!fs.existsSync(fullPath)) return `错误:文件不存在 - ${fullPath}`;
97
- const readResult = await formatAdapter.read(fullPath);
98
- const lines = readResult.lines;
99
- const scanResult = scanner.scan(lines, config.sensitivePatterns);
100
- let maskedLines = [...lines];
101
- for (const field of scanResult.fields) {
102
- const fieldType = field.type;
103
- const fieldStrategy = config.sensitivePatterns[fieldType].level ?? strategy;
104
- const maskedValue = strategyExecutor.execute(field.value, fieldType, fieldStrategy);
105
- maskedLines = maskedLines.map((line) => line.replace(field.value, maskedValue));
106
- }
107
- const ext = path.extname(fullPath);
108
- const baseName = path.basename(fullPath, ext);
109
- const outputPath = path.join(path.dirname(fullPath), `${baseName}_masked${ext}`);
110
- await formatAdapter.write(outputPath, maskedLines, readResult.format);
111
- const report = reportGenerator.generateMaskingReport({
112
- inputPath: fullPath,
113
- outputPath,
114
- strategy: strategyExecutor.resolveStrategy(strategy),
115
- findings: scanResult.fields,
116
- fieldTypeCounts: scanResult.typeCounts
117
- });
118
- auditLogger.log({
119
- pluginName: "data-masking",
120
- operation: "mask_sensitive_data",
121
- inputPath: fullPath,
122
- outputPath,
123
- result: "SUCCESS"
124
- });
125
- return report;
126
- }
127
- }));
128
- console.log("[data-masking] 脱敏插件已加载");
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import { BusinessRulesLoader, FileFormatAdapter, ReportGenerator, PathValidator, AuditLogger, } from '@liuhange/dsh-data-asset-shared';
5
+ import { SensitiveFieldScanner } from './sensitiveFieldScanner.js';
6
+ import { MaskingStrategyExecutor } from './maskingStrategyExecutor.js';
7
+ import { AdvancedMaskingExecutor } from './advancedMaskingExecutor.js';
8
+ import { defaultAdvancedMaskingConfig } from './defaultAdvancedMaskingConfig.js';
9
+ export const name = 'data-masking';
10
+ export const inject = ['tools'];
11
+ export function apply(ctx) {
12
+ const loader = new BusinessRulesLoader();
13
+ const formatAdapter = new FileFormatAdapter();
14
+ const reportGenerator = new ReportGenerator();
15
+ const pathValidator = new PathValidator();
16
+ const auditLogger = new AuditLogger();
17
+ const scanner = new SensitiveFieldScanner();
18
+ const strategyExecutor = new MaskingStrategyExecutor();
19
+ const advancedExecutor = new AdvancedMaskingExecutor();
20
+ ctx.tools.register(defineTool({
21
+ name: 'mask_sensitive_data',
22
+ description: '识别并脱敏数据中的敏感字段(身份证、手机号、银行卡、邮箱),支持高级算法(FPE/k-匿名/差分隐私/哈希)',
23
+ parameters: {
24
+ filePath: { type: 'string', required: true, description: '待处理文件的路径' },
25
+ strategy: {
26
+ type: 'string',
27
+ description: '脱敏策略: FULL | PARTIAL | GENERALIZE',
28
+ },
29
+ algorithm: {
30
+ type: 'string',
31
+ description: '高级脱敏算法: FPE | k-anonymity | differential-privacy | hash',
32
+ },
33
+ fieldName: {
34
+ type: 'string',
35
+ description: '字段名(用于字段级算法配置覆盖)',
36
+ },
37
+ },
38
+ output: {
39
+ schema: { type: 'string' },
40
+ render: (_args, value) => [{ type: 'text', text: value }],
41
+ },
42
+ async execute(args) {
43
+ const { config } = loader.load();
44
+ const workingDir = process.cwd();
45
+ const filePath = args.filePath;
46
+ const strategy = args.strategy ?? 'PARTIAL';
47
+ const algorithm = args.algorithm;
48
+ const fieldName = args.fieldName;
49
+ try {
50
+ pathValidator.validate(filePath, workingDir);
51
+ }
52
+ catch {
53
+ return `错误:路径不合法 - ${filePath}`;
54
+ }
55
+ const fullPath = path.resolve(filePath);
56
+ if (!fs.existsSync(fullPath)) {
57
+ return `错误:文件不存在 - ${fullPath}`;
58
+ }
59
+ if (algorithm) {
60
+ const advancedConfig = config.advancedMasking ?? defaultAdvancedMaskingConfig;
61
+ const readResult = await formatAdapter.read(fullPath);
62
+ const lines = readResult.lines;
63
+ const maskedLines = [];
64
+ for (const line of lines) {
65
+ const result = advancedExecutor.execute(line, algorithm, fieldName, advancedConfig);
66
+ maskedLines.push(typeof result.maskedData === 'string' ? result.maskedData : JSON.stringify(result.maskedData));
67
+ }
68
+ const ext = path.extname(fullPath);
69
+ const baseName = path.basename(fullPath, ext);
70
+ const outputPath = path.join(path.dirname(fullPath), `${baseName}_masked${ext}`);
71
+ await formatAdapter.write(outputPath, maskedLines, readResult.format);
72
+ auditLogger.log({
73
+ pluginName: 'data-masking',
74
+ operation: 'mask_sensitive_data',
75
+ inputPath: fullPath,
76
+ outputPath,
77
+ result: 'SUCCESS',
78
+ });
79
+ return `高级脱敏完成(算法: ${algorithm})\n输入: ${fullPath}\n输出: ${outputPath}\n处理行数: ${maskedLines.length}`;
80
+ }
81
+ const readResult = await formatAdapter.read(fullPath);
82
+ const lines = readResult.lines;
83
+ const scanResult = scanner.scan(lines, config.sensitivePatterns);
84
+ let maskedLines = [...lines];
85
+ for (const field of scanResult.fields) {
86
+ const fieldType = field.type;
87
+ const patternConfig = config.sensitivePatterns[fieldType];
88
+ const fieldStrategy = patternConfig.level ?? strategy;
89
+ const maskedValue = strategyExecutor.execute(field.value, fieldType, fieldStrategy);
90
+ maskedLines = maskedLines.map(line => line.replace(field.value, maskedValue));
91
+ }
92
+ const ext = path.extname(fullPath);
93
+ const baseName = path.basename(fullPath, ext);
94
+ const outputPath = path.join(path.dirname(fullPath), `${baseName}_masked${ext}`);
95
+ await formatAdapter.write(outputPath, maskedLines, readResult.format);
96
+ const report = reportGenerator.generateMaskingReport({
97
+ inputPath: fullPath,
98
+ outputPath,
99
+ strategy: strategyExecutor.resolveStrategy(strategy),
100
+ findings: scanResult.fields,
101
+ fieldTypeCounts: scanResult.typeCounts,
102
+ });
103
+ auditLogger.log({
104
+ pluginName: 'data-masking',
105
+ operation: 'mask_sensitive_data',
106
+ inputPath: fullPath,
107
+ outputPath,
108
+ result: 'SUCCESS',
109
+ });
110
+ return report;
111
+ },
112
+ }));
113
+ console.log('[data-masking] 脱敏插件已加载');
129
114
  }
130
- //#endregion
131
- export { apply, inject, name };
115
+ //# sourceMappingURL=index.js.map
package/lib/invariant.js CHANGED
@@ -1,5 +1,4 @@
1
- //#region lib/types/invariant.js
2
- const invariant = "data-masking";
3
- function install() {}
4
- //#endregion
5
- export { install, invariant };
1
+ export const invariant = 'data-masking';
2
+ export function install() {
3
+ }
4
+ //# sourceMappingURL=invariant.js.map
@@ -1,4 +1,4 @@
1
- import type { MaskingStrategy, SensitiveFieldType } from '@deepseek-ai/dsh-data-asset-shared';
1
+ import type { MaskingStrategy, SensitiveFieldType } from '@liuhange/dsh-data-asset-shared';
2
2
  export declare class MaskingStrategyExecutor {
3
3
  execute(value: string, _type: SensitiveFieldType, strategy: MaskingStrategy): string;
4
4
  resolveStrategy(strategy: MaskingStrategy): MaskingStrategy;
@@ -1,4 +1,4 @@
1
- import type { SensitiveField, SensitivePatterns } from '@deepseek-ai/dsh-data-asset-shared';
1
+ import type { SensitiveField, SensitivePatterns } from '@liuhange/dsh-data-asset-shared';
2
2
  export interface ScanResult {
3
3
  fields: SensitiveField[];
4
4
  typeCounts: Record<string, number>;
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
- {
1
+ {
2
2
  "name": "@liuhange/dsh-data-masking",
3
3
  "description": "Data masking plugin: sensitive field identification and graded masking (FULL/PARTIAL/GENERALIZE)",
4
- "version": "2.0.0",
4
+ "version": "2.0.2",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/deepseek-ai/deepseek-harness.git",
10
+ "url": "git+https://github.com/liuhange789/data-asset-inspector.git",
11
11
  "directory": "packages/data-asset/data-masking"
12
12
  },
13
13
  "type": "module",
@@ -31,9 +31,14 @@
31
31
  "lib/types/**/*.d.ts"
32
32
  ],
33
33
  "license": "MIT",
34
+ "scripts": {
35
+ "typecheck": "tsc --noEmit",
36
+ "test": "vitest run",
37
+ "build": "tsc"
38
+ },
34
39
  "peerDependencies": {
35
- "@deepseek-ai/cordis": "^0.1.0",
36
- "@deepseek-ai/dsh-tools": "^0.1.0",
40
+ "@deepseek-ai/cordis": "^4.0.0",
41
+ "@deepseek-ai/dsh-tools": "0.0.1-rc.1",
37
42
  "@liuhange/dsh-data-asset-shared": "^2.0.0"
38
43
  }
39
44
  }