dsh-sensitive-guard 0.3.4 → 0.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.
- package/CHANGELOG.md +18 -0
- package/NOTICE +29 -0
- package/README.md +37 -16
- package/client.js +633 -79
- package/index.js +421 -26
- package/package.json +3 -3
- package/rules/gitleaks.json +3178 -0
- package/scripts/build-gitleaks.mjs +133 -0
- package/test.mjs +332 -4
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regenerate rules/gitleaks.json from the upstream gitleaks config.
|
|
3
|
+
*
|
|
4
|
+
* node scripts/build-gitleaks.mjs # fetch from jsdelivr
|
|
5
|
+
* node scripts/build-gitleaks.mjs ./gitleaks.toml # local snapshot
|
|
6
|
+
*
|
|
7
|
+
* The upstream file is MIT (Copyright (c) 2019 Zachary Rice); see NOTICE.
|
|
8
|
+
* Go/RE2 supports a few constructs JS RegExp does not, so the regexes are
|
|
9
|
+
* downgraded here and every one is compiled before it is written out.
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
|
|
15
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
16
|
+
const OUT = path.join(ROOT, 'rules', 'gitleaks.json');
|
|
17
|
+
const DEFAULT_SOURCE = 'https://cdn.jsdelivr.net/gh/gitleaks/gitleaks@master/config/gitleaks.toml';
|
|
18
|
+
const SOURCE_ARG = process.argv[2];
|
|
19
|
+
|
|
20
|
+
const LOOSE_IDS = new Set([
|
|
21
|
+
'curl-auth-header', 'curl-auth-user', 'generic-api-key',
|
|
22
|
+
'jwt-base64', 'kubernetes-secret-yaml',
|
|
23
|
+
]);
|
|
24
|
+
const SPECIAL = {
|
|
25
|
+
'1password': '1Password', oauth: 'OAuth', api: 'API', jwt: 'JWT', aws: 'AWS',
|
|
26
|
+
gcp: 'GCP', id: 'ID', url: 'URL', ssh: 'SSH', tls: 'TLS', ip: 'IP',
|
|
27
|
+
json: 'JSON', yaml: 'YAML', pem: 'PEM', sql: 'SQL', cli: 'CLI', ui: 'UI',
|
|
28
|
+
pkcs: 'PKCS', hmac: 'HMAC', sha: 'SHA', ssl: 'SSL', gpg: 'GPG', rsa: 'RSA',
|
|
29
|
+
oidc: 'OIDC', saml: 'SAML', smtp: 'SMTP', pdf: 'PDF', ca: 'CA',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
function friendlyName(id) {
|
|
33
|
+
return String(id).split(/[-_]/).map((word) => {
|
|
34
|
+
if (SPECIAL[word]) return SPECIAL[word];
|
|
35
|
+
return word.charAt(0).toUpperCase() + word.slice(1);
|
|
36
|
+
}).join(' ');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function convert(regex) {
|
|
40
|
+
const needI = /\(\?i\)|\(\?i:/.test(regex);
|
|
41
|
+
const src = regex
|
|
42
|
+
.replace(/\(\?i\)/g, '')
|
|
43
|
+
.replace(/\(\?i:/g, '(?:')
|
|
44
|
+
.replace(/\(\?-i:/g, '(?:')
|
|
45
|
+
.replace(/\(\?P</g, '(?<')
|
|
46
|
+
.split('(?s:.)').join('[\\s\\S]')
|
|
47
|
+
.split('(?s:').join('(?:');
|
|
48
|
+
return { regex: src, flags: 'gd' + (needI ? 'i' : ''), approx: /\(\?-i:/.test(regex) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function parseBlocks(text) {
|
|
52
|
+
const chunks = text.split(/^\[\[rules\]\][ \t]*$/m).slice(1);
|
|
53
|
+
return chunks.map((chunk) => chunk.split(/^\[\[/m)[0]);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function field(block, name) {
|
|
57
|
+
const m = new RegExp('^' + name + '\\s*=\\s*([^\\n]+)', 'm').exec(block);
|
|
58
|
+
return m ? m[1].trim() : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function quoted(block, name) {
|
|
62
|
+
const m = new RegExp('^' + name + '\\s*=\\s*"([^"]*)"', 'm').exec(block);
|
|
63
|
+
return m ? m[1] : null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function tripleQuoted(block, name) {
|
|
67
|
+
const m = new RegExp('^' + name + "\\s*=\\s*'''([\\s\\S]*?)'''", 'm').exec(block);
|
|
68
|
+
return m ? m[1] : null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
let text;
|
|
72
|
+
if (SOURCE_ARG) {
|
|
73
|
+
text = fs.readFileSync(path.resolve(SOURCE_ARG), 'utf8');
|
|
74
|
+
} else {
|
|
75
|
+
const res = await fetch(DEFAULT_SOURCE);
|
|
76
|
+
if (!res.ok) throw new Error(`fetch failed: ${res.status}`);
|
|
77
|
+
text = await res.text();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const blocks = parseBlocks(text);
|
|
81
|
+
const rules = [];
|
|
82
|
+
const skipped = [];
|
|
83
|
+
for (const block of blocks) {
|
|
84
|
+
const id = quoted(block, 'id');
|
|
85
|
+
if (!id) continue;
|
|
86
|
+
const raw = tripleQuoted(block, 'regex');
|
|
87
|
+
if (!raw) {
|
|
88
|
+
skipped.push({ id, reason: tripleQuoted(block, 'path') ? 'path-only rule (no text regex)' : 'no regex' });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
const kwBlock = /^keywords\s*=\s*\[([\s\S]*?)\]/m.exec(block);
|
|
92
|
+
const keywords = kwBlock ? [...kwBlock[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]) : [];
|
|
93
|
+
const entropyRaw = field(block, 'entropy');
|
|
94
|
+
const groupRaw = field(block, 'secretGroup');
|
|
95
|
+
const c = convert(raw);
|
|
96
|
+
try {
|
|
97
|
+
new RegExp(c.regex, c.flags);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
skipped.push({ id, reason: `compile: ${error.message.slice(0, 80)}` });
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const tier = c.approx ? 'approx' : LOOSE_IDS.has(id) ? 'loose' : 'core';
|
|
103
|
+
rules.push({
|
|
104
|
+
id,
|
|
105
|
+
name: friendlyName(id),
|
|
106
|
+
regex: c.regex,
|
|
107
|
+
flags: c.flags,
|
|
108
|
+
group: groupRaw ? Number(groupRaw) : 0,
|
|
109
|
+
keywords,
|
|
110
|
+
entropy: entropyRaw ? Number(entropyRaw) : null,
|
|
111
|
+
approx: c.approx,
|
|
112
|
+
tier,
|
|
113
|
+
defaultOn: tier === 'core',
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const payload = {
|
|
118
|
+
source: 'gitleaks/gitleaks config/gitleaks.toml',
|
|
119
|
+
license: 'MIT',
|
|
120
|
+
generatedAt: new Date().toISOString(),
|
|
121
|
+
total: blocks.length,
|
|
122
|
+
compiled: rules.length,
|
|
123
|
+
skipped,
|
|
124
|
+
rules,
|
|
125
|
+
};
|
|
126
|
+
fs.mkdirSync(path.dirname(OUT), { recursive: true });
|
|
127
|
+
fs.writeFileSync(OUT, `${JSON.stringify(payload, null, 2)}\n`);
|
|
128
|
+
const tiers = rules.reduce((acc, r) => ({ ...acc, [r.tier]: (acc[r.tier] || 0) + 1 }), {});
|
|
129
|
+
console.log(`blocks=${blocks.length} compiled=${rules.length} skipped=${skipped.length}`);
|
|
130
|
+
console.log('tiers:', JSON.stringify(tiers));
|
|
131
|
+
console.log('with keywords:', rules.filter((r) => r.keywords.length).length,
|
|
132
|
+
'| with entropy:', rules.filter((r) => r.entropy !== null).length);
|
|
133
|
+
console.log('bytes:', fs.statSync(OUT).size, '->', OUT);
|
package/test.mjs
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
*
|
|
5
5
|
* node test.mjs
|
|
6
6
|
*/
|
|
7
|
+
import { execFileSync } from 'node:child_process';
|
|
8
|
+
import { createHash, createHmac, randomBytes } from 'node:crypto';
|
|
7
9
|
import fs from 'node:fs';
|
|
8
10
|
import os from 'node:os';
|
|
9
11
|
import path from 'node:path';
|
|
@@ -50,7 +52,7 @@ mod.apply(ctx);
|
|
|
50
52
|
console.log('host registration');
|
|
51
53
|
check('inject is [tools]', JSON.stringify(mod.inject) === '["tools"]');
|
|
52
54
|
check('two tools registered', tools.size === 2, [...tools.keys()].join(','));
|
|
53
|
-
check('
|
|
55
|
+
check('five routes registered', routes.size === 5, [...routes.keys()].join(','));
|
|
54
56
|
check('three hooks registered', listeners.size === 3, [...listeners.keys()].join(','));
|
|
55
57
|
|
|
56
58
|
const pre = listeners.get('agent/pre-step')[0];
|
|
@@ -168,6 +170,69 @@ const lanToggle = fakeRes();
|
|
|
168
170
|
await settings.handler({ method: 'POST', socket: { remoteAddress: '203.0.113.9' }, headers: { host: 'localhost:3080' } }, lanToggle);
|
|
169
171
|
check('settings route is loopback-only', lanToggle.status === 403);
|
|
170
172
|
|
|
173
|
+
console.log('persistent disable switch');
|
|
174
|
+
const pausePath = path.join(TEMP_HOME, 'sensitive-guard', 'pause.json');
|
|
175
|
+
const disabledState = (await postSettings({ action: 'disable' })).body;
|
|
176
|
+
check('关闭保护返回 off 且没有到期时间',
|
|
177
|
+
disabledState.off === true && disabledState.paused === true && disabledState.remainingMs === null,
|
|
178
|
+
JSON.stringify(disabledState));
|
|
179
|
+
|
|
180
|
+
const duringDisable = (await pre(
|
|
181
|
+
{ messages: [{ content: `key ${SECRET}` }] },
|
|
182
|
+
async () => ({ kind: 'enter', messages: [{ content: `key ${SECRET}` }] }),
|
|
183
|
+
)).messages[0].content;
|
|
184
|
+
check('关闭期间明文原样进入上下文', duringDisable === `key ${SECRET}`, duringDisable);
|
|
185
|
+
check('关闭状态写进 pause.json', JSON.parse(fs.readFileSync(pausePath, 'utf8')).off === true);
|
|
186
|
+
|
|
187
|
+
const whileOff = (await postSettings({ action: 'resume' })).body;
|
|
188
|
+
check('resume 不会误解除持久关闭', whileOff.off === true && whileOff.paused === true, JSON.stringify(whileOff));
|
|
189
|
+
const pauseWhileOff = (await postSettings({ action: 'pause', minutes: 30 })).body;
|
|
190
|
+
check('限时暂停不会覆盖持久关闭', pauseWhileOff.off === true, JSON.stringify(pauseWhileOff));
|
|
191
|
+
|
|
192
|
+
// A fresh process re-reads pause.json from disk: this is the actual restart
|
|
193
|
+
// behaviour, not a simulation of the in-memory flag.
|
|
194
|
+
const restartProbe = [
|
|
195
|
+
"import { Readable } from 'node:stream';",
|
|
196
|
+
"const mod = await import(process.argv[1]);",
|
|
197
|
+
"const listeners = new Map(); const routes = new Map();",
|
|
198
|
+
"const ctx = { on(n,f){ if(!listeners.has(n)) listeners.set(n,[]); listeners.get(n).push(f); },",
|
|
199
|
+
" effect(fn){ try{fn()}catch{} return ()=>{}; }, tools:{register:()=>()=>{}},",
|
|
200
|
+
" webServer:{register(r){ routes.set(r.path,r); return ()=>{}; }}, inject(_d,cb){cb(ctx);} };",
|
|
201
|
+
"mod.apply(ctx);",
|
|
202
|
+
"const pre = listeners.get('agent/pre-step')[0];",
|
|
203
|
+
"const raw = 'key ' + process.argv[2];",
|
|
204
|
+
"const d = await pre({messages:[{content:raw}]}, async()=>({kind:'enter',messages:[{content:raw}]}));",
|
|
205
|
+
"const text = d.messages.length ? d.messages[0].content : raw;",
|
|
206
|
+
"const res={status:0,body:'',writeHead(c){this.status=c;},end(b){this.body=String(b||'');}};",
|
|
207
|
+
"await routes.get('/guard/settings').handler({method:'GET',socket:{remoteAddress:'127.0.0.1'},headers:{host:'localhost:3080'}}, res);",
|
|
208
|
+
"process.stdout.write(JSON.stringify({ masked: text.includes('<SG_'), state: JSON.parse(res.body||'{}') }));",
|
|
209
|
+
].join('\n');
|
|
210
|
+
const restarted = JSON.parse(execFileSync(process.execPath, [
|
|
211
|
+
'--input-type=module', '-e', restartProbe,
|
|
212
|
+
pathToFileURL(path.join(ROOT, 'index.js')).href, SECRET,
|
|
213
|
+
], { env: { ...process.env, DSH_HOME: TEMP_HOME }, encoding: 'utf8' }));
|
|
214
|
+
check('重启后 off 仍然生效', restarted.state.off === true && restarted.state.paused === true,
|
|
215
|
+
JSON.stringify(restarted.state));
|
|
216
|
+
check('重启后仍然不遮挡', restarted.masked === false, JSON.stringify(restarted));
|
|
217
|
+
|
|
218
|
+
const enabled = (await postSettings({ action: 'enable' })).body;
|
|
219
|
+
check('开启保护清除 off', enabled.off === false && enabled.paused === false, JSON.stringify(enabled));
|
|
220
|
+
const afterEnable = (await pre(
|
|
221
|
+
{ messages: [{ content: `key ${SECRET}` }] },
|
|
222
|
+
async () => ({ kind: 'enter', messages: [{ content: `key ${SECRET}` }] }),
|
|
223
|
+
)).messages[0].content;
|
|
224
|
+
check('重新开启后恢复遮挡', afterEnable.includes('<SG_'), afterEnable);
|
|
225
|
+
const savedOn = JSON.parse(fs.readFileSync(pausePath, 'utf8'));
|
|
226
|
+
check('恢复后写盘清除 off', savedOn.off === false && savedOn.until === 0, JSON.stringify(savedOn));
|
|
227
|
+
|
|
228
|
+
const lanDisable = fakeRes();
|
|
229
|
+
await settings.handler(Object.assign(Readable.from([Buffer.from(JSON.stringify({ action: 'disable' }))]), {
|
|
230
|
+
method: 'POST', socket: { remoteAddress: '203.0.113.9' }, headers: { host: 'localhost:3080' },
|
|
231
|
+
}), lanDisable);
|
|
232
|
+
check('非本机来源不能关闭保护', lanDisable.status === 403, String(lanDisable.status));
|
|
233
|
+
check('未知 action 返回 400', (await postSettings({ action: 'status-probe' })).status === 400);
|
|
234
|
+
check('被拒绝后仍然是开启状态', JSON.parse(fs.readFileSync(pausePath, 'utf8')).off === false);
|
|
235
|
+
|
|
171
236
|
/* -------------------------------------------------------------- client -- */
|
|
172
237
|
|
|
173
238
|
console.log('client');
|
|
@@ -214,6 +279,78 @@ const fullCtx = new Proxy({
|
|
|
214
279
|
api.apply(fullCtx);
|
|
215
280
|
check('inline renderer uses keyed registration', registered.some((r) => r.key === 'sensitive-guard'));
|
|
216
281
|
|
|
282
|
+
/**
|
|
283
|
+
* Render both tabs through a React stub that actually calls function
|
|
284
|
+
* components. Catches runtime errors in the new settings UI (undefined.map,
|
|
285
|
+
* bad hook order, missing dictionary keys) that `api.apply` alone cannot.
|
|
286
|
+
*/
|
|
287
|
+
const fakeVault = {
|
|
288
|
+
entries: [{
|
|
289
|
+
ph: '<SG_aaaaaaaaaaaa>', name: '测试口令', preview: 'dsh-desk…',
|
|
290
|
+
label: '公司内部凭据', rule: 'manual', createdAt: '2026-11-06T09:00:00.000Z',
|
|
291
|
+
hits: 1, pinned: true,
|
|
292
|
+
}],
|
|
293
|
+
access: { level: 'loopback' }, stats: {}, rules: {},
|
|
294
|
+
};
|
|
295
|
+
function renderSettingsTab(forcedTab, opts = {}) {
|
|
296
|
+
let stateIndex = 0;
|
|
297
|
+
const ReactStub = {
|
|
298
|
+
createElement: (type, props, ...children) => (
|
|
299
|
+
typeof type === 'function' ? type({ ...(props || {}), children }) : { type, props, children }
|
|
300
|
+
),
|
|
301
|
+
Fragment: 'Fragment',
|
|
302
|
+
useState: (initial) => {
|
|
303
|
+
stateIndex += 1;
|
|
304
|
+
let value = forcedTab === 'rules' && stateIndex === 6 ? 'rules' : initial;
|
|
305
|
+
if (opts.forceRows && stateIndex === 1) value = fakeVault;
|
|
306
|
+
if (opts.forceForm && value === false) value = true;
|
|
307
|
+
if (opts.forceCustom && value === '密码') value = '__custom__';
|
|
308
|
+
return [value, () => {}];
|
|
309
|
+
},
|
|
310
|
+
useEffect: () => {},
|
|
311
|
+
useRef: () => ({ current: 0 }),
|
|
312
|
+
useCallback: (fn) => fn,
|
|
313
|
+
};
|
|
314
|
+
let localApi = null;
|
|
315
|
+
const win = { __ModuleLoader__: { load(def) { localApi = def.factory((n) => (n === 'react' ? ReactStub : {})); } } };
|
|
316
|
+
const captured = [];
|
|
317
|
+
const localSlots = {
|
|
318
|
+
inject(_name, factory) {
|
|
319
|
+
const it = factory();
|
|
320
|
+
if (it && typeof it.next === 'function') { let s = it.next(); while (!s.done) s = it.next(); }
|
|
321
|
+
},
|
|
322
|
+
register(options, renderer) { captured.push({ options, renderer }); return () => {}; },
|
|
323
|
+
};
|
|
324
|
+
const stubCtx = new Proxy({
|
|
325
|
+
slots: localSlots,
|
|
326
|
+
effect: () => () => {},
|
|
327
|
+
locale: { register: () => () => {}, bind: () => (k) => k },
|
|
328
|
+
get: (name) => (name === 'uiConversation' ? { userText: { register: () => {} } } : undefined),
|
|
329
|
+
inject: (_deps, cb) => cb({ uiConversation: { userText: { register: () => {} } } }),
|
|
330
|
+
}, { get(t, p) { return p in t ? t[p] : undefined; } });
|
|
331
|
+
new Function('window', 'globalThis', clientSrc).call(globalThis, win, globalThis);
|
|
332
|
+
localApi.apply(stubCtx);
|
|
333
|
+
const section = captured.find((c) => c.options && c.options.name === 'settings.section');
|
|
334
|
+
if (!section) throw new Error('settings renderer missing');
|
|
335
|
+
return section.renderer();
|
|
336
|
+
}
|
|
337
|
+
const renderCases = [
|
|
338
|
+
['entries 标签', 'entries', {}],
|
|
339
|
+
['rules 标签', 'rules', {}],
|
|
340
|
+
['添加敏感数据弹窗', 'entries', { forceForm: true }],
|
|
341
|
+
['自定义分类弹窗', 'entries', { forceForm: true, forceCustom: true }],
|
|
342
|
+
['列表行与复制按钮', 'entries', { forceRows: true }],
|
|
343
|
+
];
|
|
344
|
+
for (const [name, tabName, opts] of renderCases) {
|
|
345
|
+
let thrown = null;
|
|
346
|
+
try { renderSettingsTab(tabName, opts); } catch (error) { thrown = error; }
|
|
347
|
+
check(`设置页 ${name} 渲染不抛错`, thrown === null, thrown && thrown.message);
|
|
348
|
+
}
|
|
349
|
+
// forceForm also flips confirmDisable to true, so the modal is covered above.
|
|
350
|
+
check('设置页含关闭保护入口与确认弹窗',
|
|
351
|
+
["action: 'disable'", "action: 'enable'", 'statusDisabled', 'disableTitle', 'function DisableConfirm']
|
|
352
|
+
.every((key) => clientSrc.includes(key)));
|
|
353
|
+
|
|
217
354
|
/* ------------------------------------------------------------ behaviour -- */
|
|
218
355
|
|
|
219
356
|
console.log('performance');
|
|
@@ -415,12 +552,203 @@ const withSpace = await runPre('我的密码是 123456 吗?');
|
|
|
415
552
|
const noSpace = await runPre('我的密码是123456吗');
|
|
416
553
|
const fullComma = await runPre('我的密码是123456,对吗');
|
|
417
554
|
const bare = await runPre('密码是 123456 吗');
|
|
418
|
-
|
|
419
|
-
check('
|
|
420
|
-
check('
|
|
555
|
+
const particlePh = (withSpace.match(/<SG_[0-9a-f]{12}>/) || [])[0];
|
|
556
|
+
check('语气词留在占位符外(有空格)', withSpace === `我的密码是 ${particlePh} 吗?`, withSpace);
|
|
557
|
+
check('语气词留在占位符外(无空格)', noSpace === `我的密码是${particlePh}吗`, noSpace);
|
|
558
|
+
check('全角逗号切断取值', fullComma === `我的密码是${particlePh},对吗`, fullComma);
|
|
421
559
|
check('四种写法共用同一占位符', new Set([withSpace, noSpace, fullComma, bare].map((s) => (s.match(/<SG_[0-9a-f]{12}>/) || [''])[0])).size === 1);
|
|
422
560
|
check('句尾问号不被吞进密码', (await runPre('我的密码是 abcdef?')).endsWith('<SG_') === false);
|
|
423
561
|
|
|
562
|
+
/* --------------------------------------------------- structured fields -- */
|
|
563
|
+
|
|
564
|
+
console.log('structured fields');
|
|
565
|
+
|
|
566
|
+
const jsonOne = await runPre('{"host":"db.internal","password":"Abc!23456","note":"hello"}');
|
|
567
|
+
check('JSON 文本:字段名说了算', /"password"\s*:\s*"<SG_[0-9a-f]{12}>"/.test(jsonOne), JSON.stringify(jsonOne));
|
|
568
|
+
check('JSON 文本:键名与别的值不变', jsonOne.includes('"host":"db.internal"') && jsonOne.includes('"note":"hello"'), JSON.stringify(jsonOne));
|
|
569
|
+
|
|
570
|
+
for (const [name, text] of [
|
|
571
|
+
['credential', '{"credential": "9f8e7d6c5b4a3210"}'],
|
|
572
|
+
['db_pass', '{"db_pass": "Abc!23456"}'],
|
|
573
|
+
['HTTP 头式字段名', '{"X-Auth-Credential": "9f8e7d6c5b4a3210"}'],
|
|
574
|
+
['带后缀的字段名', '{"password_hash": "9f8e7d6c5b4a3210"}'],
|
|
575
|
+
]) {
|
|
576
|
+
const out = await runPre(text);
|
|
577
|
+
check(`JSON 文本:${name}`, /<SG_[0-9a-f]{12}>/.test(out), JSON.stringify(out));
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
for (const [name, text] of [
|
|
581
|
+
['示例占位', '{"password": "your_password_here"}'],
|
|
582
|
+
['模板变量', '{"password": "${DB_PASS}"}'],
|
|
583
|
+
['尖括号占位', '{"token": "<your-token>"}'],
|
|
584
|
+
['字段名是描述', '{"password_policy": "must be 8 chars"}'],
|
|
585
|
+
]) {
|
|
586
|
+
const out = await runPre(text);
|
|
587
|
+
check(`JSON 文本不误伤:${name}`, out === text, JSON.stringify(out));
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const obj = { password: 'Abc!23456', db_pass: 'Zx9Kp2', credential: '9f8e7d6c', note: 'hello' };
|
|
591
|
+
const objOut = await runPre(obj);
|
|
592
|
+
check('已解析对象:敏感字段的值被遮', ['password', 'db_pass', 'credential'].every((k) => /^<SG_[0-9a-f]{12}>$/.test(objOut[k])), JSON.stringify(objOut));
|
|
593
|
+
check('已解析对象:键名全保留', Object.keys(objOut).join(',') === Object.keys(obj).join(','), JSON.stringify(Object.keys(objOut)));
|
|
594
|
+
check('已解析对象:普通值不变', objOut.note === 'hello', JSON.stringify(objOut));
|
|
595
|
+
|
|
596
|
+
const exampleJson = '{"password": "Abc!23456"}';
|
|
597
|
+
const exampleStream = streamFn({}, () => (async function* () { yield { type: 'text-delta', text: exampleJson }; })());
|
|
598
|
+
const exampleChunks = [];
|
|
599
|
+
for await (const c of exampleStream) exampleChunks.push(c.text);
|
|
600
|
+
check('模型输出的示例 JSON 不被改写', exampleChunks[0] === exampleJson, JSON.stringify(exampleChunks));
|
|
601
|
+
|
|
602
|
+
console.log('placeholder hardening');
|
|
603
|
+
const shortOut = await runPre('我的密码是 123456');
|
|
604
|
+
const shortPh = (shortOut.match(/<SG_[0-9a-f]{12}>/) || [])[0];
|
|
605
|
+
check('占位符不是 sha256(明文) 前缀', Boolean(shortPh) && !shortPh.includes(createHash('sha256').update('123456').digest('hex').slice(0, 12)), shortPh);
|
|
606
|
+
const vaultKey = fs.readFileSync(path.join(TEMP_HOME, 'sensitive-guard', 'vault.key'));
|
|
607
|
+
const expectedPh = `<SG_${createHmac('sha256', vaultKey).update('123456').digest('hex').slice(0, 12)}>`;
|
|
608
|
+
check('占位符 = HMAC(vault.key, 明文)', shortPh === expectedPh, `${shortPh} vs ${expectedPh}`);
|
|
609
|
+
check('同一明文仍是同一占位符', (await runPre('我的密码是 123456')).includes(shortPh));
|
|
610
|
+
|
|
611
|
+
console.log('vault aliases');
|
|
612
|
+
const aliasRes = fakeRes();
|
|
613
|
+
await routes.get('/guard/vault').handler({ method: 'GET', socket: { remoteAddress: '127.0.0.1' }, headers: { host: 'localhost:3080' } }, aliasRes);
|
|
614
|
+
const aliasBody = JSON.parse(aliasRes.body || '{}');
|
|
615
|
+
check('保管库条目带 aliases 字段', Array.isArray((aliasBody.entries[0] || {}).aliases), JSON.stringify(aliasBody.entries[0] || {}));
|
|
616
|
+
|
|
617
|
+
/* ------------------------------------------------- upgrade from 0.3.x -- */
|
|
618
|
+
|
|
619
|
+
console.log('legacy placeholder upgrade');
|
|
620
|
+
const legacySecret = '123456';
|
|
621
|
+
const legacyPh = `<SG_${createHash('sha256').update(legacySecret).digest('hex').slice(0, 12)}>`;
|
|
622
|
+
const legacyHash = createHash('sha256').update(legacySecret).digest('hex').slice(0, 12);
|
|
623
|
+
// Vault writes are debounced by 250ms; let the capture above reach disk before
|
|
624
|
+
// rewriting the entry to its 0.3.x shape.
|
|
625
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
626
|
+
const vaultPath = path.join(TEMP_HOME, 'sensitive-guard', 'vault.json');
|
|
627
|
+
const vaultRaw = JSON.parse(fs.readFileSync(vaultPath, 'utf8'));
|
|
628
|
+
const legacyEntry = vaultRaw.entries.find((e) => e.hash === legacyHash);
|
|
629
|
+
if (legacyEntry) {
|
|
630
|
+
// Pretend this entry was written by 0.3.4: old sha256 code, no aliases.
|
|
631
|
+
legacyEntry.ph = legacyPh;
|
|
632
|
+
legacyEntry.aliases = [];
|
|
633
|
+
fs.writeFileSync(vaultPath, JSON.stringify({ version: 1, entries: vaultRaw.entries }));
|
|
634
|
+
const probe = [
|
|
635
|
+
"import { Readable } from 'node:stream';",
|
|
636
|
+
"const mod = await import(process.argv[1]);",
|
|
637
|
+
"const listeners = new Map(); const routes = new Map();",
|
|
638
|
+
"const ctx = { on(n,f){ if(!listeners.has(n)) listeners.set(n,[]); listeners.get(n).push(f); },",
|
|
639
|
+
" effect(fn){ try{fn()}catch{} return ()=>{}; }, tools:{register:()=>()=>{}},",
|
|
640
|
+
" webServer:{register(r){ routes.set(r.path,r); return ()=>{}; }}, inject(_d,cb){cb(ctx);} };",
|
|
641
|
+
"mod.apply(ctx);",
|
|
642
|
+
"const pre = listeners.get('agent/pre-step')[0];",
|
|
643
|
+
"const d = await pre({messages:[{content:'我的密码是 123456'}]}, async()=>({kind:'enter',messages:[]}));",
|
|
644
|
+
"const text = d.messages.length ? d.messages[0].content : '我的密码是 123456';",
|
|
645
|
+
"const neu = (text.match(/<SG_[0-9a-f]{12}>/)||[])[0] || '';",
|
|
646
|
+
"const reveal = routes.get('/guard/reveal');",
|
|
647
|
+
"async function ask(ph){ const res={status:0,body:'',writeHead(c){this.status=c;},end(b){this.body=String(b||'');}};",
|
|
648
|
+
" await reveal.handler(Object.assign(Readable.from([Buffer.from(JSON.stringify({placeholder:ph}))]), {",
|
|
649
|
+
" method:'POST', socket:{remoteAddress:'127.0.0.1'}, headers:{host:'localhost:3080','content-type':'application/json'} }), res);",
|
|
650
|
+
" return {status:res.status, plaintext:(JSON.parse(res.body||'{}')).plaintext}; }",
|
|
651
|
+
"const old = await ask(process.argv[2]);",
|
|
652
|
+
"const fresh = await ask(neu);",
|
|
653
|
+
"process.stdout.write(JSON.stringify({ neu, old, fresh }));",
|
|
654
|
+
].join('\n');
|
|
655
|
+
const stdout = execFileSync(process.execPath, [
|
|
656
|
+
'--input-type=module', '-e', probe,
|
|
657
|
+
pathToFileURL(path.join(ROOT, 'index.js')).href, legacyPh,
|
|
658
|
+
], { env: { ...process.env, DSH_HOME: TEMP_HOME }, encoding: 'utf8' });
|
|
659
|
+
const upgraded = JSON.parse(stdout);
|
|
660
|
+
check('升级后新代号不再是旧哈希', upgraded.neu !== legacyPh && /^<SG_[0-9a-f]{12}>$/.test(upgraded.neu), upgraded.neu);
|
|
661
|
+
check('旧会话里的代号仍能解锁', upgraded.old.status === 200 && upgraded.old.plaintext === legacySecret, JSON.stringify(upgraded.old));
|
|
662
|
+
check('新代号也能解锁同一条', upgraded.fresh.status === 200 && upgraded.fresh.plaintext === legacySecret, JSON.stringify(upgraded.fresh));
|
|
663
|
+
} else {
|
|
664
|
+
check('找到用于升级测试的 vault 条目', false, `missing ${legacySecret} in ${vaultRaw.entries.map((e) => e.hash).join(',')}`);
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/* --------------------------------------------------- gitleaks catalog -- */
|
|
668
|
+
|
|
669
|
+
console.log('gitleaks catalog');
|
|
670
|
+
const catalog = JSON.parse(fs.readFileSync(path.join(ROOT, 'rules', 'gitleaks.json'), 'utf8'));
|
|
671
|
+
check('目录统计 222 / 221 / 1 跳过',
|
|
672
|
+
catalog.total === 222 && catalog.compiled === 221 && catalog.skipped.length === 1,
|
|
673
|
+
JSON.stringify({ total: catalog.total, compiled: catalog.compiled, skipped: catalog.skipped.length }));
|
|
674
|
+
check('跳过的是 pkcs12-file', Boolean(catalog.skipped[0]) && catalog.skipped[0].id === 'pkcs12-file');
|
|
675
|
+
let compileFailures = 0;
|
|
676
|
+
for (const rule of catalog.rules) {
|
|
677
|
+
try { new RegExp(rule.regex, rule.flags); } catch { compileFailures += 1; }
|
|
678
|
+
}
|
|
679
|
+
check('221 条正则全部能编译', compileFailures === 0, String(compileFailures));
|
|
680
|
+
const tiers = { core: 0, approx: 0, loose: 0 };
|
|
681
|
+
for (const rule of catalog.rules) tiers[rule.tier] += 1;
|
|
682
|
+
check('分级合计 221', tiers.core + tiers.approx + tiers.loose === 221, JSON.stringify(tiers));
|
|
683
|
+
check('approx 10 条、loose 至少 1 条', tiers.approx === 10 && tiers.loose >= 1, JSON.stringify(tiers));
|
|
684
|
+
check('只有 core 默认开', catalog.rules.every((r) => r.defaultOn === (r.tier === 'core')));
|
|
685
|
+
check('221 条都带 keywords 预筛', catalog.rules.every((r) => Array.isArray(r.keywords) && r.keywords.length > 0));
|
|
686
|
+
check('NOTICE 含 MIT 版权声明', fs.readFileSync(path.join(ROOT, 'NOTICE'), 'utf8').includes('Copyright (c) 2019 Zachary Rice'));
|
|
687
|
+
|
|
688
|
+
async function callRoute(routePath, method, payload, remote = '127.0.0.1') {
|
|
689
|
+
const res = fakeRes();
|
|
690
|
+
const req = payload === undefined
|
|
691
|
+
? { method, socket: { remoteAddress: remote }, headers: { host: 'localhost:3080' } }
|
|
692
|
+
: Object.assign(Readable.from([Buffer.from(JSON.stringify(payload))]), {
|
|
693
|
+
method, socket: { remoteAddress: remote },
|
|
694
|
+
headers: { host: 'localhost:3080', 'content-type': 'application/json' },
|
|
695
|
+
});
|
|
696
|
+
await routes.get(routePath).handler(req, res);
|
|
697
|
+
return { status: res.status, body: JSON.parse(res.body || '{}') };
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
const rulesGet = await callRoute('/guard/rules', 'GET');
|
|
701
|
+
check('规则页返回 221 条 + 1 条跳过',
|
|
702
|
+
rulesGet.status === 200 && rulesGet.body.compiled === 221 && rulesGet.body.skipped.length === 1,
|
|
703
|
+
JSON.stringify(rulesGet.body).slice(0, 130));
|
|
704
|
+
check('规则页含内置规则', rulesGet.body.rules.some((r) => r.source === 'builtin'));
|
|
705
|
+
check('规则页含 1Password Secret Key', rulesGet.body.rules.some((r) => r.name === '1Password Secret Key'));
|
|
706
|
+
const approxRule = rulesGet.body.rules.find((r) => r.tier === 'approx');
|
|
707
|
+
check('approx 规则默认关', Boolean(approxRule) && approxRule.enabled === false, approxRule && approxRule.id);
|
|
708
|
+
check('规则页分页大小 20', rulesGet.body.pageSize === 20);
|
|
709
|
+
|
|
710
|
+
const ageKey = 'AGE-SECRET-KEY-1' + 'Q'.repeat(58);
|
|
711
|
+
const ageBefore = await runPre(`key ${ageKey}`);
|
|
712
|
+
check('core 规则默认开且命中', ageBefore.includes('<SG_'), JSON.stringify(ageBefore.slice(0, 90)));
|
|
713
|
+
const lowEntropyKey = 'A3-AAAAAA-AAAAAAAAAAA-AAAAA-AAAAA-AAAAA';
|
|
714
|
+
const lowOut = await runPre(`key ${lowEntropyKey}`);
|
|
715
|
+
check('逐条 entropy 阈值挡住低熵命中', !lowOut.includes('<SG_'), JSON.stringify(lowOut.slice(0, 90)));
|
|
716
|
+
|
|
717
|
+
const id = 'gitleaks:age-secret-key';
|
|
718
|
+
const toggleOff = await callRoute('/guard/rules', 'POST', { id, enabled: false });
|
|
719
|
+
check('关闭 core 规则成功', toggleOff.status === 200 && toggleOff.body.rules.find((r) => r.id === id).enabled === false);
|
|
720
|
+
check('关闭后不再遮挡', !(await runPre(`key ${ageKey}`)).includes('<SG_'));
|
|
721
|
+
const toggleOn = await callRoute('/guard/rules', 'POST', { id, enabled: true });
|
|
722
|
+
check('重新打开成功', toggleOn.status === 200 && toggleOn.body.rules.find((r) => r.id === id).enabled === true);
|
|
723
|
+
const badToggle = await callRoute('/guard/rules', 'POST', { id: 'does-not-exist', enabled: true });
|
|
724
|
+
check('未知规则 id 被拒', badToggle.status === 400 && badToggle.body.error === 'unknown-rule');
|
|
725
|
+
const lanRuleToggle = await callRoute('/guard/rules', 'POST', { id, enabled: false }, '203.0.113.99');
|
|
726
|
+
check('非本机来源不能改规则', lanRuleToggle.status === 403, JSON.stringify(lanRuleToggle));
|
|
727
|
+
await callRoute('/guard/rules', 'POST', { id, enabled: true });
|
|
728
|
+
|
|
729
|
+
console.log('manual entries');
|
|
730
|
+
const manual = 'MANUAL-INTERNAL-778899';
|
|
731
|
+
const addedEntry = await callRoute('/guard/entries', 'POST', { action: 'add', name: '测试口令', plaintext: manual, kind: '密码' });
|
|
732
|
+
check('添加敏感数据返回占位符',
|
|
733
|
+
addedEntry.status === 200 && /^<SG_[0-9a-f]{12}>$/.test(addedEntry.body.placeholder || ''),
|
|
734
|
+
JSON.stringify(addedEntry));
|
|
735
|
+
const manualHit = await runPre(`value ${manual} end`);
|
|
736
|
+
check('手动录入的明文被遮', manualHit.includes('<SG_'), JSON.stringify(manualHit));
|
|
737
|
+
const rulesOnDisk = fs.readFileSync(path.join(TEMP_HOME, 'sensitive-guard', 'rules.json'), 'utf8');
|
|
738
|
+
check('明文不写进 rules.json', !rulesOnDisk.includes(manual));
|
|
739
|
+
const manualVault = await callRoute('/guard/vault', 'GET');
|
|
740
|
+
check('保管库条目带名称与 pinned',
|
|
741
|
+
manualVault.body.entries.some((e) => e.name === '测试口令' && e.pinned === true),
|
|
742
|
+
JSON.stringify(manualVault.body.entries.slice(0, 1)));
|
|
743
|
+
const manualReveal = await callRoute('/guard/reveal', 'POST', { placeholder: addedEntry.body.placeholder });
|
|
744
|
+
check('手动条目可解锁取回明文', manualReveal.status === 200 && manualReveal.body.plaintext === manual,
|
|
745
|
+
JSON.stringify(manualReveal.body).slice(0, 100));
|
|
746
|
+
const tooShort = await callRoute('/guard/entries', 'POST', { action: 'add', name: 'x', plaintext: 'ab' });
|
|
747
|
+
check('过短的明文被拒', tooShort.status === 400 && tooShort.body.error === 'bad-plaintext');
|
|
748
|
+
const deleted = await callRoute('/guard/entries', 'POST', { action: 'delete', placeholder: addedEntry.body.placeholder });
|
|
749
|
+
check('删除手动条目成功', deleted.status === 200);
|
|
750
|
+
check('删除后不再遮挡', !(await runPre(`value ${manual} end`)).includes('<SG_'));
|
|
751
|
+
|
|
424
752
|
/* --------------------------------------------------------------------- */
|
|
425
753
|
|
|
426
754
|
fs.rmSync(TEMP_HOME, { recursive: true, force: true });
|