kb-server 0.0.12-beta.1 → 0.0.13
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/dist/common/api-middleware.d.ts +0 -1
- package/dist/common/api-middleware.js +18 -12
- package/dist/common/create-server.d.ts +1 -0
- package/dist/common/create-server.js +1 -1
- package/dist/common/sanitize-traceinfo.d.ts +35 -0
- package/dist/common/sanitize-traceinfo.js +115 -0
- package/dist/tests/sanitize-traceinfo.test.d.ts +5 -0
- package/dist/tests/sanitize-traceinfo.test.js +104 -0
- package/package.json +1 -1
|
@@ -26,7 +26,6 @@ export interface APIErrorResponse {
|
|
|
26
26
|
export type AuthFunction = (action: string, req: express.Request) => Promise<Record<string, any> | boolean> | boolean | Record<string, any>;
|
|
27
27
|
interface IPackAPIOptions {
|
|
28
28
|
authFn?: AuthFunction;
|
|
29
|
-
log?: boolean;
|
|
30
29
|
}
|
|
31
30
|
/**
|
|
32
31
|
* API包装函数
|
|
@@ -4,13 +4,14 @@ exports.packAPI = void 0;
|
|
|
4
4
|
const create_errors_1 = require("./create-errors");
|
|
5
5
|
const uuid_1 = require("uuid");
|
|
6
6
|
const logger_1 = require("../helper/logger");
|
|
7
|
+
const sanitize_traceinfo_1 = require("./sanitize-traceinfo");
|
|
7
8
|
/**
|
|
8
9
|
* API包装函数
|
|
9
10
|
* @param apis API列表
|
|
10
11
|
* @returns
|
|
11
12
|
*/
|
|
12
13
|
const packAPI = (apis, options) => {
|
|
13
|
-
const { authFn
|
|
14
|
+
const { authFn } = options || {};
|
|
14
15
|
return async (req, res) => {
|
|
15
16
|
// 生成API映射
|
|
16
17
|
const apiMap = new Map(Object.entries(apis).map(([action, execution]) => [action, execution]));
|
|
@@ -24,19 +25,21 @@ const packAPI = (apis, options) => {
|
|
|
24
25
|
RequestId: requestId,
|
|
25
26
|
};
|
|
26
27
|
// API 解析 - 将Action定义移到try块外部,以便在catch块中也能访问
|
|
27
|
-
const { Action, ...params } = req.body || {};
|
|
28
|
+
const { Action, TraceInfo, ...params } = req.body || {};
|
|
28
29
|
try {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
30
|
+
// 安全处理TraceInfo
|
|
31
|
+
const safeTraceInfo = TraceInfo ? (0, sanitize_traceinfo_1.sanitizeTraceInfo)(TraceInfo) : undefined;
|
|
32
|
+
logger_1.logger.info({
|
|
33
|
+
requestId,
|
|
34
|
+
action: Action,
|
|
35
|
+
params,
|
|
36
|
+
path: req.path,
|
|
37
|
+
method: req.method,
|
|
38
|
+
traceInfo: safeTraceInfo,
|
|
39
|
+
}, "收到请求");
|
|
38
40
|
// 接口未定义
|
|
39
41
|
if (!Action) {
|
|
42
|
+
logger_1.logger.warn({ requestId, action: Action }, "接口未定义");
|
|
40
43
|
throw new create_errors_1.CommonErrors.InvalidParameter.EmptyAPIRequest();
|
|
41
44
|
}
|
|
42
45
|
// 处理鉴权函数
|
|
@@ -44,8 +47,10 @@ const packAPI = (apis, options) => {
|
|
|
44
47
|
if (typeof authFn !== "function") {
|
|
45
48
|
throw new create_errors_1.CommonErrors.ResourceNotFound.AuthFunctionNotFound();
|
|
46
49
|
}
|
|
50
|
+
logger_1.logger.info({ requestId, action: Action }, "开始执行框架权限检查");
|
|
47
51
|
const authResult = await authFn(Action, req);
|
|
48
52
|
if (!authResult) {
|
|
53
|
+
logger_1.logger.warn({ requestId, action: Action }, "框架权限检查不通过");
|
|
49
54
|
throw new create_errors_1.CommonErrors.FailOperation.NoPermission();
|
|
50
55
|
}
|
|
51
56
|
if (typeof authResult !== "boolean") {
|
|
@@ -53,6 +58,7 @@ const packAPI = (apis, options) => {
|
|
|
53
58
|
ctx.AuthInfo = authResult || {};
|
|
54
59
|
}
|
|
55
60
|
}
|
|
61
|
+
logger_1.logger.info({ requestId, action: Action, authInfo: ctx.AuthInfo }, "框架权限检查通过");
|
|
56
62
|
// API 处理
|
|
57
63
|
const execution = apiMap.get(Action);
|
|
58
64
|
if (typeof execution !== "function") {
|
|
@@ -69,7 +75,7 @@ const packAPI = (apis, options) => {
|
|
|
69
75
|
};
|
|
70
76
|
// 完成响应
|
|
71
77
|
took = Date.now() - start;
|
|
72
|
-
logger_1.logger.info({ requestId, action: Action, response, took }, "
|
|
78
|
+
logger_1.logger.info({ requestId, action: Action, response, took }, "执行响应");
|
|
73
79
|
return res.send(response);
|
|
74
80
|
}
|
|
75
81
|
catch (rawError) {
|
|
@@ -43,7 +43,7 @@ function createServer(params, options) {
|
|
|
43
43
|
// 注入SSE
|
|
44
44
|
handlers && app.use((0, sse_middleware_1.packSSE)(handlers, { authFn, log, ...resetSSE }));
|
|
45
45
|
// 注入API
|
|
46
|
-
app.use((0, api_middleware_1.packAPI)(apis, { authFn
|
|
46
|
+
app.use((0, api_middleware_1.packAPI)(apis, { authFn }));
|
|
47
47
|
return app;
|
|
48
48
|
}
|
|
49
49
|
exports.createServer = createServer;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 安全处理工具模块
|
|
3
|
+
* 用于对用户输入的数据进行安全清理,防止日志注入、敏感信息泄露等问题
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* 安全处理配置选项
|
|
7
|
+
*/
|
|
8
|
+
export interface SanitizeOptions {
|
|
9
|
+
/** 最大嵌套深度,防止循环引用 */
|
|
10
|
+
maxDepth?: number;
|
|
11
|
+
/** 最大数组长度,防止数据过大 */
|
|
12
|
+
maxArrayLength?: number;
|
|
13
|
+
/** 最大对象属性数量 */
|
|
14
|
+
maxObjectKeys?: number;
|
|
15
|
+
/** 最大字符串长度 */
|
|
16
|
+
maxStringLength?: number;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 安全处理TraceInfo,防止安全漏洞
|
|
20
|
+
*
|
|
21
|
+
* @param traceInfo - 需要清理的数据
|
|
22
|
+
* @param options - 配置选项
|
|
23
|
+
* @returns 清理后的安全数据
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* const safeData = sanitizeTraceInfo({
|
|
28
|
+
* username: 'test',
|
|
29
|
+
* password: 'secret',
|
|
30
|
+
* apiTrace: []
|
|
31
|
+
* });
|
|
32
|
+
* // 结果: { username: 'test', password: '[REDACTED]', apiTrace: [] }
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
export declare function sanitizeTraceInfo(traceInfo: unknown, options?: SanitizeOptions): any;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* 安全处理工具模块
|
|
4
|
+
* 用于对用户输入的数据进行安全清理,防止日志注入、敏感信息泄露等问题
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.sanitizeTraceInfo = void 0;
|
|
8
|
+
/**
|
|
9
|
+
* 需要脱敏的敏感字段列表
|
|
10
|
+
*/
|
|
11
|
+
const SENSITIVE_KEYS = [
|
|
12
|
+
'password',
|
|
13
|
+
'token',
|
|
14
|
+
'secret',
|
|
15
|
+
'key',
|
|
16
|
+
'auth',
|
|
17
|
+
'credential',
|
|
18
|
+
'cookie',
|
|
19
|
+
];
|
|
20
|
+
/**
|
|
21
|
+
* 默认配置
|
|
22
|
+
*/
|
|
23
|
+
const DEFAULT_OPTIONS = {
|
|
24
|
+
maxDepth: 5,
|
|
25
|
+
maxArrayLength: 100,
|
|
26
|
+
maxObjectKeys: 50,
|
|
27
|
+
maxStringLength: 1000,
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* 安全处理TraceInfo,防止安全漏洞
|
|
31
|
+
*
|
|
32
|
+
* @param traceInfo - 需要清理的数据
|
|
33
|
+
* @param options - 配置选项
|
|
34
|
+
* @returns 清理后的安全数据
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```typescript
|
|
38
|
+
* const safeData = sanitizeTraceInfo({
|
|
39
|
+
* username: 'test',
|
|
40
|
+
* password: 'secret',
|
|
41
|
+
* apiTrace: []
|
|
42
|
+
* });
|
|
43
|
+
* // 结果: { username: 'test', password: '[REDACTED]', apiTrace: [] }
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
function sanitizeTraceInfo(traceInfo, options = {}) {
|
|
47
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
48
|
+
return sanitizeValue(traceInfo, opts, 0);
|
|
49
|
+
}
|
|
50
|
+
exports.sanitizeTraceInfo = sanitizeTraceInfo;
|
|
51
|
+
/**
|
|
52
|
+
* 递归清理数据
|
|
53
|
+
*/
|
|
54
|
+
function sanitizeValue(value, options, currentDepth) {
|
|
55
|
+
// 深度限制,防止循环引用导致的栈溢出
|
|
56
|
+
if (currentDepth > options.maxDepth) {
|
|
57
|
+
return '[MaxDepthReached]';
|
|
58
|
+
}
|
|
59
|
+
// 空值处理
|
|
60
|
+
if (value === null || value === undefined) {
|
|
61
|
+
return value;
|
|
62
|
+
}
|
|
63
|
+
// 原始类型直接处理字符串
|
|
64
|
+
if (typeof value !== 'object') {
|
|
65
|
+
return sanitizeString(value, options.maxStringLength);
|
|
66
|
+
}
|
|
67
|
+
// 数组处理
|
|
68
|
+
if (Array.isArray(value)) {
|
|
69
|
+
return value.map((item, index) => {
|
|
70
|
+
if (index >= options.maxArrayLength) {
|
|
71
|
+
return `[Array truncated, total length: ${value.length}]`;
|
|
72
|
+
}
|
|
73
|
+
return sanitizeValue(item, options, currentDepth + 1);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
// 对象处理
|
|
77
|
+
const sanitized = {};
|
|
78
|
+
let keyCount = 0;
|
|
79
|
+
for (const key of Object.keys(value)) {
|
|
80
|
+
// 限制对象属性数量
|
|
81
|
+
if (keyCount >= options.maxObjectKeys) {
|
|
82
|
+
sanitized['__truncated__'] = `Object truncated, total keys: ${Object.keys(value).length}`;
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
keyCount++;
|
|
86
|
+
const lowerKey = key.toLowerCase();
|
|
87
|
+
// 敏感字段脱敏
|
|
88
|
+
if (SENSITIVE_KEYS.some((sk) => lowerKey.includes(sk))) {
|
|
89
|
+
sanitized[key] = '[REDACTED]';
|
|
90
|
+
}
|
|
91
|
+
else {
|
|
92
|
+
sanitized[key] = sanitizeValue(value[key], options, currentDepth + 1);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return sanitized;
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* 清理字符串值,防止日志注入
|
|
99
|
+
*
|
|
100
|
+
* @param value - 需要清理的值
|
|
101
|
+
* @param maxLength - 最大长度限制
|
|
102
|
+
* @returns 清理后的字符串
|
|
103
|
+
*/
|
|
104
|
+
function sanitizeString(value, maxLength) {
|
|
105
|
+
if (typeof value !== 'string') {
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
// 移除控制字符和转义特殊字符,防止日志注入
|
|
109
|
+
return value
|
|
110
|
+
.replace(/[\x00-\x1F\x7F]/g, '') // 移除控制字符
|
|
111
|
+
.replace(/\n/g, '\\n') // 转义换行
|
|
112
|
+
.replace(/\r/g, '\\r') // 转义回车
|
|
113
|
+
.replace(/\t/g, '\\t') // 转义制表符
|
|
114
|
+
.substring(0, maxLength); // 限制字符串长度
|
|
115
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* TraceInfo安全处理测试
|
|
4
|
+
* 运行方式: npx tsx src/tests/sanitize-traceinfo.test.ts
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
const sanitize_traceinfo_1 = require("../common/sanitize-traceinfo");
|
|
8
|
+
console.log("=== TraceInfo安全处理测试 ===\n");
|
|
9
|
+
// 测试1: 敏感字段脱敏
|
|
10
|
+
console.log("测试1: 敏感字段脱敏");
|
|
11
|
+
const test1 = {
|
|
12
|
+
username: 'testuser',
|
|
13
|
+
password: 'secret123',
|
|
14
|
+
accessToken: 'token123',
|
|
15
|
+
normalField: 'normal value'
|
|
16
|
+
};
|
|
17
|
+
const result1 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test1);
|
|
18
|
+
console.log("输入:", test1);
|
|
19
|
+
console.log("输出:", result1);
|
|
20
|
+
console.log("✓ password已脱敏:", result1.password === '[REDACTED]');
|
|
21
|
+
console.log("✓ accessToken已脱敏:", result1.accessToken === '[REDACTED]');
|
|
22
|
+
console.log("✓ normalField保留:", result1.normalField === 'normal value');
|
|
23
|
+
console.log("\n---\n");
|
|
24
|
+
// 测试2: 日志注入防护
|
|
25
|
+
console.log("测试2: 日志注入防护(控制字符清理)");
|
|
26
|
+
const test2 = {
|
|
27
|
+
name: 'test\x00name',
|
|
28
|
+
description: 'line1\nline2\rline3\ttab'
|
|
29
|
+
};
|
|
30
|
+
const result2 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test2);
|
|
31
|
+
console.log("输入:", test2);
|
|
32
|
+
console.log("输出:", result2);
|
|
33
|
+
console.log("✓ 控制字符已移除:", !result2.name.includes('\x00'));
|
|
34
|
+
console.log("✓ 换行符已转义:", result2.description.includes('\\n'));
|
|
35
|
+
console.log("\n---\n");
|
|
36
|
+
// 测试3: 大小限制
|
|
37
|
+
console.log("测试3: 大小限制(数组和对象)");
|
|
38
|
+
const test3 = {
|
|
39
|
+
items: Array.from({ length: 200 }, (_, i) => i),
|
|
40
|
+
largeObject: {}
|
|
41
|
+
};
|
|
42
|
+
for (let i = 0; i < 100; i++) {
|
|
43
|
+
test3.largeObject[`key${i}`] = i;
|
|
44
|
+
}
|
|
45
|
+
const result3 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test3);
|
|
46
|
+
console.log("数组长度限制:", result3.items.length, "(原始200, 限制100)");
|
|
47
|
+
console.log("对象属性数量:", Object.keys(result3).length, "(包含截断标记)");
|
|
48
|
+
console.log("✓ 数组已截断:", result3.items.length === 100);
|
|
49
|
+
console.log("✓ 对象已截断:", result3.largeObject.__truncated__ !== undefined);
|
|
50
|
+
console.log("\n---\n");
|
|
51
|
+
// 测试4: 深度限制
|
|
52
|
+
console.log("测试4: 深度限制");
|
|
53
|
+
const createDeepObject = (depth) => {
|
|
54
|
+
if (depth === 0)
|
|
55
|
+
return 'value';
|
|
56
|
+
return { level: createDeepObject(depth - 1) };
|
|
57
|
+
};
|
|
58
|
+
const test4 = createDeepObject(10);
|
|
59
|
+
const result4 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test4);
|
|
60
|
+
console.log("✓ 深度限制已生效:", JSON.stringify(result4).includes('[MaxDepthReached]'));
|
|
61
|
+
console.log("\n---\n");
|
|
62
|
+
// 测试5: 字符串长度限制
|
|
63
|
+
console.log("测试5: 字符串长度限制");
|
|
64
|
+
const test5 = { long: 'a'.repeat(2000) };
|
|
65
|
+
const result5 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test5);
|
|
66
|
+
console.log("✓ 长字符串已截断:", result5.long.length === 1000);
|
|
67
|
+
console.log("\n---\n");
|
|
68
|
+
// 测试6: 实际TraceInfo场景
|
|
69
|
+
console.log("测试6: 实际TraceInfo场景");
|
|
70
|
+
const test6 = {
|
|
71
|
+
sessionId: 'session_123456',
|
|
72
|
+
userId: 'user_789',
|
|
73
|
+
entryPage: '/home',
|
|
74
|
+
currentPage: '/profile',
|
|
75
|
+
apiTrace: [
|
|
76
|
+
{ action: 'GetUser', pageFrom: '/home', duration: 150, status: 'success' },
|
|
77
|
+
{ action: 'UpdateProfile', pageFrom: '/profile', duration: 200, status: 'success' }
|
|
78
|
+
],
|
|
79
|
+
deviceInfo: {
|
|
80
|
+
ua: 'Mozilla/5.0...',
|
|
81
|
+
platform: 'Mac'
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const result6 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test6);
|
|
85
|
+
console.log("输入:", JSON.stringify(test6, null, 2));
|
|
86
|
+
console.log("输出:", JSON.stringify(result6, null, 2));
|
|
87
|
+
console.log("✓ 正常TraceInfo保留完整");
|
|
88
|
+
console.log("\n---\n");
|
|
89
|
+
// 测试7: 自定义配置
|
|
90
|
+
console.log("测试7: 自定义配置");
|
|
91
|
+
const test7 = {
|
|
92
|
+
password: 'secret',
|
|
93
|
+
data: Array.from({ length: 10 }, (_, i) => i)
|
|
94
|
+
};
|
|
95
|
+
const result7 = (0, sanitize_traceinfo_1.sanitizeTraceInfo)(test7, {
|
|
96
|
+
maxDepth: 3,
|
|
97
|
+
maxArrayLength: 5,
|
|
98
|
+
maxObjectKeys: 2,
|
|
99
|
+
maxStringLength: 100
|
|
100
|
+
});
|
|
101
|
+
console.log("自定义配置结果:", result7);
|
|
102
|
+
console.log("✓ 自定义配置生效");
|
|
103
|
+
console.log("\n---\n");
|
|
104
|
+
console.log("✅ 所有测试完成!");
|