dsh-sensitive-guard 0.4.0 → 0.5.1

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.
@@ -0,0 +1,5 @@
1
+ [
2
+ "docs/chat-masked.png",
3
+ "docs/chat-revealed.png",
4
+ "docs/settings.png"
5
+ ]
@@ -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
@@ -5,7 +5,7 @@
5
5
  * node test.mjs
6
6
  */
7
7
  import { execFileSync } from 'node:child_process';
8
- import { createHash, createHmac } from 'node:crypto';
8
+ import { createHash, createHmac, randomBytes } from 'node:crypto';
9
9
  import fs from 'node:fs';
10
10
  import os from 'node:os';
11
11
  import path from 'node:path';
@@ -52,7 +52,7 @@ mod.apply(ctx);
52
52
  console.log('host registration');
53
53
  check('inject is [tools]', JSON.stringify(mod.inject) === '["tools"]');
54
54
  check('two tools registered', tools.size === 2, [...tools.keys()].join(','));
55
- check('three routes registered', routes.size === 3, [...routes.keys()].join(','));
55
+ check('five routes registered', routes.size === 5, [...routes.keys()].join(','));
56
56
  check('three hooks registered', listeners.size === 3, [...listeners.keys()].join(','));
57
57
 
58
58
  const pre = listeners.get('agent/pre-step')[0];
@@ -170,6 +170,69 @@ const lanToggle = fakeRes();
170
170
  await settings.handler({ method: 'POST', socket: { remoteAddress: '203.0.113.9' }, headers: { host: 'localhost:3080' } }, lanToggle);
171
171
  check('settings route is loopback-only', lanToggle.status === 403);
172
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
+
173
236
  /* -------------------------------------------------------------- client -- */
174
237
 
175
238
  console.log('client');
@@ -216,6 +279,78 @@ const fullCtx = new Proxy({
216
279
  api.apply(fullCtx);
217
280
  check('inline renderer uses keyed registration', registered.some((r) => r.key === 'sensitive-guard'));
218
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
+
219
354
  /* ------------------------------------------------------------ behaviour -- */
220
355
 
221
356
  console.log('performance');
@@ -529,6 +664,91 @@ if (legacyEntry) {
529
664
  check('找到用于升级测试的 vault 条目', false, `missing ${legacySecret} in ${vaultRaw.entries.map((e) => e.hash).join(',')}`);
530
665
  }
531
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
+
532
752
  /* --------------------------------------------------------------------- */
533
753
 
534
754
  fs.rmSync(TEMP_HOME, { recursive: true, force: true });