dsh-sensitive-guard 0.4.0 → 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 +11 -0
- package/NOTICE +29 -0
- package/README.md +29 -13
- package/client.js +625 -78
- package/index.js +294 -13
- package/package.json +3 -3
- package/rules/gitleaks.json +3178 -0
- package/scripts/build-gitleaks.mjs +133 -0
- package/test.mjs +222 -2
package/index.js
CHANGED
|
@@ -34,7 +34,11 @@ import path from 'node:path';
|
|
|
34
34
|
const VAULT_ROUTE = '/guard/vault';
|
|
35
35
|
const REVEAL_ROUTE = '/guard/reveal';
|
|
36
36
|
const SETTINGS_ROUTE = '/guard/settings';
|
|
37
|
-
const
|
|
37
|
+
const RULES_ROUTE = '/guard/rules';
|
|
38
|
+
const ENTRIES_ROUTE = '/guard/entries';
|
|
39
|
+
const PLUGIN_VERSION = '0.5.0';
|
|
40
|
+
const CATALOG_FILE = new URL('./rules/gitleaks.json', import.meta.url);
|
|
41
|
+
const PAGE_SIZE = 20;
|
|
38
42
|
|
|
39
43
|
/** Stable placeholder form: <SG_ + 12 hex chars of HMAC(vault.key, plaintext) + >. */
|
|
40
44
|
const PH_EXACT = /^<SG_[0-9a-f]{12}>$/;
|
|
@@ -100,11 +104,13 @@ const audit = [];
|
|
|
100
104
|
let lastError = null;
|
|
101
105
|
|
|
102
106
|
/**
|
|
103
|
-
* Protection
|
|
107
|
+
* Protection state, persisted in pause.json except `untilRestart`.
|
|
104
108
|
* - `until` a timestamp (auto-resumes, survives a restart)
|
|
105
109
|
* - `untilRestart` (deliberately not persisted — a restart re-arms the guard)
|
|
110
|
+
* - `off` a deliberate, persistent disable: survives restarts and never
|
|
111
|
+
* auto-resumes. Only an explicit `enable` action re-arms protection.
|
|
106
112
|
*/
|
|
107
|
-
const pause = { until: 0, untilRestart: false };
|
|
113
|
+
const pause = { until: 0, untilRestart: false, off: false };
|
|
108
114
|
|
|
109
115
|
function pauseFile() { return path.join(dataDir(), 'pause.json'); }
|
|
110
116
|
|
|
@@ -113,20 +119,23 @@ function loadPause() {
|
|
|
113
119
|
const raw = JSON.parse(fs.readFileSync(pauseFile(), 'utf8'));
|
|
114
120
|
// `untilRestart` is deliberately not restored: a restart re-arms the guard.
|
|
115
121
|
if (raw && Number.isFinite(raw.until) && raw.until > Date.now()) pause.until = raw.until;
|
|
122
|
+
// `off` IS restored — that is the whole point of the disable switch.
|
|
123
|
+
if (raw && raw.off === true) pause.off = true;
|
|
116
124
|
} catch { /* no pause file yet */ }
|
|
117
125
|
}
|
|
118
126
|
|
|
119
127
|
function persistPause() {
|
|
120
128
|
try {
|
|
121
129
|
fs.mkdirSync(dataDir(), { recursive: true });
|
|
122
|
-
fs.writeFileSync(pauseFile(), JSON.stringify({ until: pause.until }), { mode: 0o600 });
|
|
130
|
+
fs.writeFileSync(pauseFile(), JSON.stringify({ until: pause.until, off: pause.off }), { mode: 0o600 });
|
|
123
131
|
} catch (error) {
|
|
124
132
|
lastError = `pause persist: ${String((error && error.message) || error)}`;
|
|
125
133
|
}
|
|
126
134
|
}
|
|
127
135
|
|
|
128
|
-
/** @returns remaining ms while
|
|
136
|
+
/** @returns remaining ms while protection is inactive, 0 when active. */
|
|
129
137
|
function pausedMs() {
|
|
138
|
+
if (pause.off) return Number.POSITIVE_INFINITY;
|
|
130
139
|
if (pause.untilRestart) return Number.POSITIVE_INFINITY;
|
|
131
140
|
return Math.max(0, pause.until - Date.now());
|
|
132
141
|
}
|
|
@@ -262,6 +271,7 @@ function persistVault(immediate) {
|
|
|
262
271
|
function trimVault() {
|
|
263
272
|
if (vault.entries.size <= MAX_VAULT_ENTRIES) return;
|
|
264
273
|
const ordered = [...vault.entries.values()]
|
|
274
|
+
.filter((entry) => !entry.pinned)
|
|
265
275
|
.sort((a, b) => String(a.lastHitAt || a.createdAt).localeCompare(String(b.lastHitAt || b.createdAt)));
|
|
266
276
|
for (let i = 0; i < ordered.length && vault.entries.size > MAX_VAULT_ENTRIES; i += 1) {
|
|
267
277
|
const victim = ordered[i];
|
|
@@ -328,6 +338,8 @@ function entryView(entry) {
|
|
|
328
338
|
return {
|
|
329
339
|
ph: entry.ph,
|
|
330
340
|
aliases: Array.isArray(entry.aliases) ? entry.aliases.slice() : [],
|
|
341
|
+
name: String(entry.name || ''),
|
|
342
|
+
pinned: Boolean(entry.pinned),
|
|
331
343
|
preview: entry.preview,
|
|
332
344
|
rule: entry.rule,
|
|
333
345
|
label: entry.label || entry.rule,
|
|
@@ -354,6 +366,56 @@ function entryViewForModel(entry) {
|
|
|
354
366
|
};
|
|
355
367
|
}
|
|
356
368
|
|
|
369
|
+
/**
|
|
370
|
+
* Values added by hand in Settings are pinned vault entries. Their plaintext is
|
|
371
|
+
* decrypted into memory once (never written to rules.json) so the scanner can
|
|
372
|
+
* match them literally.
|
|
373
|
+
*/
|
|
374
|
+
let manualSecrets = null;
|
|
375
|
+
function manualValues() {
|
|
376
|
+
if (manualSecrets) return manualSecrets;
|
|
377
|
+
loadVault();
|
|
378
|
+
manualSecrets = [];
|
|
379
|
+
for (const entry of vault.entries.values()) {
|
|
380
|
+
if (!entry.pinned) continue;
|
|
381
|
+
try {
|
|
382
|
+
const value = decrypt(entry.enc);
|
|
383
|
+
if (value) manualSecrets.push(value);
|
|
384
|
+
} catch { /* unreadable entry: keep it out of the matcher */ }
|
|
385
|
+
}
|
|
386
|
+
return manualSecrets;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function addManualEntry(name, plaintext, kind) {
|
|
390
|
+
const ph = remember(plaintext, 'manual', 'user', kind || name || '手动录入');
|
|
391
|
+
const entry = vault.entries.get(hashOf(plaintext));
|
|
392
|
+
if (entry) {
|
|
393
|
+
entry.pinned = true;
|
|
394
|
+
entry.name = String(name || '');
|
|
395
|
+
persistVault(true);
|
|
396
|
+
}
|
|
397
|
+
const list = manualValues();
|
|
398
|
+
if (!list.includes(plaintext)) list.push(plaintext);
|
|
399
|
+
noteAudit('manual-add', { ph });
|
|
400
|
+
return ph;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function removeManualEntry(ph) {
|
|
404
|
+
loadVault();
|
|
405
|
+
const hash = vault.byPh.get(ph);
|
|
406
|
+
const entry = hash && vault.entries.get(hash);
|
|
407
|
+
if (!entry) return false;
|
|
408
|
+
let plaintext = '';
|
|
409
|
+
try { plaintext = decrypt(entry.enc); } catch { /* still remove the row */ }
|
|
410
|
+
vault.entries.delete(hash);
|
|
411
|
+
vault.byPh.delete(ph);
|
|
412
|
+
for (const alias of Array.isArray(entry.aliases) ? entry.aliases : []) vault.byPh.delete(alias);
|
|
413
|
+
if (manualSecrets && plaintext) manualSecrets = manualSecrets.filter((v) => v !== plaintext);
|
|
414
|
+
persistVault(true);
|
|
415
|
+
noteAudit('manual-remove', { ph });
|
|
416
|
+
return true;
|
|
417
|
+
}
|
|
418
|
+
|
|
357
419
|
/* ---------------------------------------------------------------- rules -- */
|
|
358
420
|
|
|
359
421
|
/**
|
|
@@ -468,7 +530,8 @@ try {
|
|
|
468
530
|
console.warn('[sensitive-guard] rule precompile failed:', error && error.message);
|
|
469
531
|
}
|
|
470
532
|
|
|
471
|
-
let fileRules = { list: [], outboundScrub: true, entropy: false, entropyThreshold: 4.5, allowCidrs: [], error: null, mtime: 0, checkedAt: 0 };
|
|
533
|
+
let fileRules = { list: [], outboundScrub: true, entropy: false, entropyThreshold: 4.5, allowCidrs: [], enabledRules: [], error: null, mtime: 0, checkedAt: 0 };
|
|
534
|
+
let allRulesCache = null;
|
|
472
535
|
|
|
473
536
|
function reloadRules(force) {
|
|
474
537
|
const now = Date.now();
|
|
@@ -496,6 +559,9 @@ function reloadRules(force) {
|
|
|
496
559
|
fileRules.entropy = raw && raw.entropy === true;
|
|
497
560
|
fileRules.entropyThreshold = raw && Number.isFinite(raw.entropyThreshold) ? raw.entropyThreshold : 4.5;
|
|
498
561
|
fileRules.disabled = new Set(Array.isArray(raw && raw.disabled) ? raw.disabled.map(String) : []);
|
|
562
|
+
// Rules graded `approx` / `loose` ship off by default; this list turns
|
|
563
|
+
// individual ones on without having to hand-edit the file.
|
|
564
|
+
fileRules.enabledRules = new Set(Array.isArray(raw && raw.enabledRules) ? raw.enabledRules.map(String) : []);
|
|
499
565
|
// Opt-in LAN exposure for the reveal routes. Empty (the default) keeps them
|
|
500
566
|
// loopback-only. Entries are CIDRs, e.g. ["192.168.0.0/16"].
|
|
501
567
|
const wanted = Array.isArray(raw && raw.allowCidrs) ? raw.allowCidrs.map((item) => String(item).trim()) : [];
|
|
@@ -503,6 +569,7 @@ function reloadRules(force) {
|
|
|
503
569
|
const rejected = wanted.filter((item) => parseCidr(item) === null);
|
|
504
570
|
fileRules.allowCidrs = accepted;
|
|
505
571
|
fileRules.error = null;
|
|
572
|
+
allRulesCache = null;
|
|
506
573
|
if (rejected.length > 0) {
|
|
507
574
|
fileRules.error = `allowCidrs 忽略无效项: ${rejected.join(', ')}(需形如 192.168.0.0/16,且不接受 /0)`;
|
|
508
575
|
}
|
|
@@ -515,10 +582,94 @@ function disabledSet() {
|
|
|
515
582
|
return fileRules.disabled instanceof Set ? fileRules.disabled : new Set();
|
|
516
583
|
}
|
|
517
584
|
|
|
585
|
+
function enabledSet() {
|
|
586
|
+
return fileRules.enabledRules instanceof Set ? fileRules.enabledRules : new Set();
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Upstream gitleaks rules ship as a pre-converted JSON file (see NOTICE and
|
|
591
|
+
* scripts/build-gitleaks.mjs). Load lazily: a missing catalog must never stop
|
|
592
|
+
* the built-in rules from working.
|
|
593
|
+
*/
|
|
594
|
+
let catalogCache = null;
|
|
595
|
+
function loadCatalog() {
|
|
596
|
+
if (catalogCache) return catalogCache;
|
|
597
|
+
try {
|
|
598
|
+
const raw = JSON.parse(fs.readFileSync(CATALOG_FILE, 'utf8'));
|
|
599
|
+
catalogCache = {
|
|
600
|
+
meta: {
|
|
601
|
+
total: raw.total,
|
|
602
|
+
compiled: raw.compiled,
|
|
603
|
+
skipped: Array.isArray(raw.skipped) ? raw.skipped : [],
|
|
604
|
+
license: raw.license || 'MIT',
|
|
605
|
+
source: raw.source || '',
|
|
606
|
+
},
|
|
607
|
+
rules: raw.rules.map((item) => ({
|
|
608
|
+
id: `gitleaks:${item.id}`,
|
|
609
|
+
group: Number.isInteger(item.group) ? item.group : 0,
|
|
610
|
+
re: new RegExp(item.regex, item.flags),
|
|
611
|
+
keywords: (item.keywords || []).map((k) => String(k).toLowerCase()),
|
|
612
|
+
entropy: Number.isFinite(item.entropy) ? item.entropy : null,
|
|
613
|
+
approx: Boolean(item.approx),
|
|
614
|
+
tier: item.tier,
|
|
615
|
+
defaultOn: item.defaultOn !== false,
|
|
616
|
+
label: item.name,
|
|
617
|
+
name: item.name,
|
|
618
|
+
source: 'gitleaks',
|
|
619
|
+
detectors: ['关键词', '正则', ...(Number.isFinite(item.entropy) ? ['熵值'] : [])],
|
|
620
|
+
})),
|
|
621
|
+
};
|
|
622
|
+
} catch (error) {
|
|
623
|
+
lastError = `catalog: ${String((error && error.message) || error)}`;
|
|
624
|
+
catalogCache = { meta: { total: 0, compiled: 0, skipped: [], license: 'MIT', source: '' }, rules: [] };
|
|
625
|
+
}
|
|
626
|
+
return catalogCache;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
function allRules() {
|
|
630
|
+
if (allRulesCache) return allRulesCache;
|
|
631
|
+
const builtin = BUILTIN_RULES.map((rule) => ({
|
|
632
|
+
...rule, defaultOn: true, source: 'builtin', name: rule.id,
|
|
633
|
+
tier: 'core', approx: false, detectors: ['正则'],
|
|
634
|
+
}));
|
|
635
|
+
const custom = fileRules.list.map((rule) => ({
|
|
636
|
+
...rule, defaultOn: true, source: 'custom', name: rule.id,
|
|
637
|
+
tier: 'core', approx: false, detectors: ['正则'],
|
|
638
|
+
}));
|
|
639
|
+
allRulesCache = [...builtin, ...loadCatalog().rules, ...custom];
|
|
640
|
+
return allRulesCache;
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
function ruleEnabled(rule) {
|
|
644
|
+
if (disabledSet().has(rule.id)) return false;
|
|
645
|
+
if (!rule.defaultOn && !enabledSet().has(rule.id)) return false;
|
|
646
|
+
return true;
|
|
647
|
+
}
|
|
648
|
+
|
|
518
649
|
function activeRules() {
|
|
519
650
|
reloadRules(false);
|
|
520
|
-
|
|
521
|
-
|
|
651
|
+
return allRules().filter(ruleEnabled);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/** Merge a small edit into rules.json without clobbering hand-written config. */
|
|
655
|
+
function writeRulesPatch(mutate) {
|
|
656
|
+
try {
|
|
657
|
+
fs.mkdirSync(dataDir(), { recursive: true });
|
|
658
|
+
let raw = {};
|
|
659
|
+
try {
|
|
660
|
+
const parsed = JSON.parse(fs.readFileSync(rulesFile(), 'utf8'));
|
|
661
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) raw = parsed;
|
|
662
|
+
} catch { /* missing or broken file: start from a clean object */ }
|
|
663
|
+
mutate(raw);
|
|
664
|
+
const tmp = `${rulesFile()}.tmp`;
|
|
665
|
+
fs.writeFileSync(tmp, `${JSON.stringify(raw, null, 2)}\n`, { mode: 0o600 });
|
|
666
|
+
fs.renameSync(tmp, rulesFile());
|
|
667
|
+
hardenFilePermissions(rulesFile());
|
|
668
|
+
return true;
|
|
669
|
+
} catch (error) {
|
|
670
|
+
lastError = `rules patch: ${String((error && error.message) || error)}`;
|
|
671
|
+
return false;
|
|
672
|
+
}
|
|
522
673
|
}
|
|
523
674
|
|
|
524
675
|
/* -------------------------------------------------------------- scrubbing -- */
|
|
@@ -560,7 +711,15 @@ function findHits(text, origin) {
|
|
|
560
711
|
// runs synchronously inside a hook — cap the window rather than freeze the host.
|
|
561
712
|
const scan = text.length > MAX_SCAN_CHARS ? text.slice(0, MAX_SCAN_CHARS) : text;
|
|
562
713
|
const hits = [];
|
|
714
|
+
let lower = null;
|
|
563
715
|
for (const rule of activeRules()) {
|
|
716
|
+
// gitleaks rules carry keywords precisely so their regex is only run on
|
|
717
|
+
// text that could match it — 221 regexes per message would blow the hook
|
|
718
|
+
// budget otherwise.
|
|
719
|
+
if (rule.keywords && rule.keywords.length) {
|
|
720
|
+
if (lower === null) lower = scan.toLowerCase();
|
|
721
|
+
if (!rule.keywords.some((k) => lower.includes(k))) continue;
|
|
722
|
+
}
|
|
564
723
|
rule.re.lastIndex = 0;
|
|
565
724
|
let match;
|
|
566
725
|
while ((match = rule.re.exec(scan)) !== null) {
|
|
@@ -587,7 +746,8 @@ function findHits(text, origin) {
|
|
|
587
746
|
}
|
|
588
747
|
// The keyword group (when the rule has one) says *what* leaked — password /
|
|
589
748
|
// token / key — which the rule id alone cannot express for keyword-prose.
|
|
590
|
-
|
|
749
|
+
if (rule.entropy != null && shannon(trimmed) < rule.entropy) continue;
|
|
750
|
+
const label = rule.name || (rule.group > 1 && typeof match[1] === 'string' ? match[1] : rule.id);
|
|
591
751
|
hits.push({ offset, end, value: trimmed, rule: rule.id, label });
|
|
592
752
|
}
|
|
593
753
|
}
|
|
@@ -600,6 +760,18 @@ function findHits(text, origin) {
|
|
|
600
760
|
if (fileRules.entropy) {
|
|
601
761
|
for (const hit of entropyHits(scan)) hits.push(hit);
|
|
602
762
|
}
|
|
763
|
+
// Values the user added through "添加敏感数据" live encrypted in the vault,
|
|
764
|
+
// never in rules.json. Match them literally on every ingress/outbound path.
|
|
765
|
+
for (const secret of manualValues()) {
|
|
766
|
+
if (!secret || secret.length < 3) continue;
|
|
767
|
+
let from = 0;
|
|
768
|
+
for (;;) {
|
|
769
|
+
const at = scan.indexOf(secret, from);
|
|
770
|
+
if (at < 0) break;
|
|
771
|
+
hits.push({ offset: at, end: at + secret.length, value: secret, rule: 'manual', label: '手动录入' });
|
|
772
|
+
from = at + secret.length;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
603
775
|
hits.sort((a, b) => a.offset - b.offset || b.end - a.end);
|
|
604
776
|
const kept = [];
|
|
605
777
|
let last = -1;
|
|
@@ -1144,7 +1316,7 @@ function jsonPostOk(req, level) {
|
|
|
1144
1316
|
}
|
|
1145
1317
|
|
|
1146
1318
|
/**
|
|
1147
|
-
* Single entry gate for the
|
|
1319
|
+
* Single entry gate for the five routes. Returns the level so callers can
|
|
1148
1320
|
* branch, or null after having already sent the rejection.
|
|
1149
1321
|
*
|
|
1150
1322
|
* `allowRestricted` lets the vault route answer read-only metadata to an
|
|
@@ -1220,7 +1392,7 @@ function registerRoutes(ctx) {
|
|
|
1220
1392
|
dataDir: snap.dataDir,
|
|
1221
1393
|
lastError: snap.lastError,
|
|
1222
1394
|
outboundScrub: fileRules.outboundScrub,
|
|
1223
|
-
rules: { builtin: BUILTIN_RULES.length, custom: fileRules.list.length, error: fileRules.error },
|
|
1395
|
+
rules: { builtin: BUILTIN_RULES.length, catalog: loadCatalog().meta.compiled, custom: fileRules.list.length, error: fileRules.error },
|
|
1224
1396
|
// Tells the UI whether this page is being served over LAN (allowCidrs).
|
|
1225
1397
|
access: {
|
|
1226
1398
|
level,
|
|
@@ -1277,8 +1449,9 @@ function registerRoutes(ctx) {
|
|
|
1277
1449
|
const ms = pausedMs();
|
|
1278
1450
|
const finite = Number.isFinite(ms);
|
|
1279
1451
|
return {
|
|
1452
|
+
off: pause.off,
|
|
1280
1453
|
paused: ms > 0,
|
|
1281
|
-
untilRestart: pause.untilRestart,
|
|
1454
|
+
untilRestart: !pause.off && pause.untilRestart,
|
|
1282
1455
|
until: finite && ms > 0 ? Date.now() + ms : null,
|
|
1283
1456
|
remainingMs: finite ? ms : null,
|
|
1284
1457
|
};
|
|
@@ -1295,7 +1468,23 @@ function registerRoutes(ctx) {
|
|
|
1295
1468
|
try { body = JSON.parse(await readBody(req, 2048) || '{}'); } catch { sendJson(res, 400, { error: 'bad-json' }); return; }
|
|
1296
1469
|
const action = String((body && body.action) || '');
|
|
1297
1470
|
|
|
1298
|
-
if (action === '
|
|
1471
|
+
if (action === 'disable') {
|
|
1472
|
+
// Deliberate, persistent off switch. Unlike a pause this survives a
|
|
1473
|
+
// restart and never auto-resumes; only `enable` re-arms protection.
|
|
1474
|
+
pause.off = true;
|
|
1475
|
+
pause.until = 0;
|
|
1476
|
+
pause.untilRestart = false;
|
|
1477
|
+
persistPause();
|
|
1478
|
+
noteAudit('disable', {});
|
|
1479
|
+
} else if (action === 'enable') {
|
|
1480
|
+
pause.off = false;
|
|
1481
|
+
pause.until = 0;
|
|
1482
|
+
pause.untilRestart = false;
|
|
1483
|
+
persistPause();
|
|
1484
|
+
noteAudit('enable', {});
|
|
1485
|
+
} else if (action === 'resume') {
|
|
1486
|
+
// Resume only clears a timed pause; it never silently lifts a
|
|
1487
|
+
// deliberate disable.
|
|
1299
1488
|
pause.until = 0;
|
|
1300
1489
|
pause.untilRestart = false;
|
|
1301
1490
|
persistPause();
|
|
@@ -1323,6 +1512,98 @@ function registerRoutes(ctx) {
|
|
|
1323
1512
|
sendJson(res, 200, shape());
|
|
1324
1513
|
},
|
|
1325
1514
|
}), 'sensitive-guard: settings route');
|
|
1515
|
+
|
|
1516
|
+
// Rule catalogue: the client does search / filter / pagination, and toggles
|
|
1517
|
+
// one rule at a time (written into rules.json, never into the vault).
|
|
1518
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1519
|
+
kind: 'exact',
|
|
1520
|
+
path: RULES_ROUTE,
|
|
1521
|
+
handler: async (req, res) => {
|
|
1522
|
+
const level = guard(req, res, { origin: true });
|
|
1523
|
+
if (level === null) return;
|
|
1524
|
+
const view = () => {
|
|
1525
|
+
const meta = loadCatalog().meta;
|
|
1526
|
+
return {
|
|
1527
|
+
ok: true,
|
|
1528
|
+
total: meta.total,
|
|
1529
|
+
compiled: meta.compiled,
|
|
1530
|
+
pageSize: PAGE_SIZE,
|
|
1531
|
+
skipped: meta.skipped,
|
|
1532
|
+
license: meta.license,
|
|
1533
|
+
source: meta.source,
|
|
1534
|
+
rules: allRules().map((rule) => ({
|
|
1535
|
+
id: rule.id,
|
|
1536
|
+
name: rule.name,
|
|
1537
|
+
source: rule.source,
|
|
1538
|
+
tier: rule.tier,
|
|
1539
|
+
defaultOn: rule.defaultOn,
|
|
1540
|
+
enabled: ruleEnabled(rule),
|
|
1541
|
+
approx: Boolean(rule.approx),
|
|
1542
|
+
detectors: rule.detectors || ['正则'],
|
|
1543
|
+
keywords: rule.keywords || [],
|
|
1544
|
+
entropy: rule.entropy === undefined ? null : rule.entropy,
|
|
1545
|
+
})),
|
|
1546
|
+
};
|
|
1547
|
+
};
|
|
1548
|
+
if (req.method === 'GET' || req.method === 'HEAD') {
|
|
1549
|
+
reloadRules(false);
|
|
1550
|
+
sendJson(res, 200, view());
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
if (req.method !== 'POST') { sendJson(res, 405, { error: 'method' }); return; }
|
|
1554
|
+
if (!jsonPostOk(req, level)) { sendJson(res, 403, { error: 'content-type' }); return; }
|
|
1555
|
+
let body;
|
|
1556
|
+
try { body = JSON.parse(await readBody(req, 4096) || '{}'); } catch { sendJson(res, 400, { error: 'bad-json' }); return; }
|
|
1557
|
+
const id = String((body && body.id) || '');
|
|
1558
|
+
const rule = allRules().find((r) => r.id === id);
|
|
1559
|
+
if (!rule) { sendJson(res, 400, { error: 'unknown-rule' }); return; }
|
|
1560
|
+
const want = body && typeof body.enabled === 'boolean' ? body.enabled : !ruleEnabled(rule);
|
|
1561
|
+
const wrote = writeRulesPatch((raw) => {
|
|
1562
|
+
const disabled = new Set(Array.isArray(raw.disabled) ? raw.disabled.map(String) : []);
|
|
1563
|
+
const enabledRules = new Set(Array.isArray(raw.enabledRules) ? raw.enabledRules.map(String) : []);
|
|
1564
|
+
if (want) { disabled.delete(id); if (!rule.defaultOn) enabledRules.add(id); }
|
|
1565
|
+
else { enabledRules.delete(id); if (rule.defaultOn) disabled.add(id); }
|
|
1566
|
+
raw.disabled = [...disabled];
|
|
1567
|
+
raw.enabledRules = [...enabledRules];
|
|
1568
|
+
});
|
|
1569
|
+
if (!wrote) { sendJson(res, 500, { error: 'write-failed' }); return; }
|
|
1570
|
+
reloadRules(true);
|
|
1571
|
+
noteAudit(want ? 'rule-on' : 'rule-off', { id });
|
|
1572
|
+
sendJson(res, 200, view());
|
|
1573
|
+
},
|
|
1574
|
+
}), 'sensitive-guard: rules route');
|
|
1575
|
+
|
|
1576
|
+
// "添加敏感数据": plaintext goes straight into the encrypted vault, never
|
|
1577
|
+
// into rules.json. Delete removes the vault row and the in-memory matcher.
|
|
1578
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1579
|
+
kind: 'exact',
|
|
1580
|
+
path: ENTRIES_ROUTE,
|
|
1581
|
+
handler: async (req, res) => {
|
|
1582
|
+
const level = guard(req, res, { origin: true });
|
|
1583
|
+
if (level === null) return;
|
|
1584
|
+
if (req.method !== 'POST') { sendJson(res, 405, { error: 'method' }); return; }
|
|
1585
|
+
if (!jsonPostOk(req, level)) { sendJson(res, 403, { error: 'content-type' }); return; }
|
|
1586
|
+
let body;
|
|
1587
|
+
try { body = JSON.parse(await readBody(req, 8192) || '{}'); } catch { sendJson(res, 400, { error: 'bad-json' }); return; }
|
|
1588
|
+
const action = String((body && body.action) || 'add');
|
|
1589
|
+
if (action === 'delete') {
|
|
1590
|
+
const ph = String((body && body.placeholder) || '').trim();
|
|
1591
|
+
if (!PH_EXACT.test(ph)) { sendJson(res, 400, { error: 'bad-placeholder' }); return; }
|
|
1592
|
+
if (!removeManualEntry(ph)) { sendJson(res, 404, { error: 'not-found' }); return; }
|
|
1593
|
+
sendJson(res, 200, { ok: true });
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
if (action !== 'add') { sendJson(res, 400, { error: 'unknown-action' }); return; }
|
|
1597
|
+
const name = String((body && body.name) || '').trim().slice(0, 64);
|
|
1598
|
+
const plaintext = typeof (body && body.plaintext) === 'string' ? body.plaintext : '';
|
|
1599
|
+
const kind = String((body && body.kind) || '').trim().slice(0, 32);
|
|
1600
|
+
if (plaintext.length < 3 || plaintext.length > 2000 || plaintext.includes(PH_HINT)) {
|
|
1601
|
+
sendJson(res, 400, { error: 'bad-plaintext' }); return;
|
|
1602
|
+
}
|
|
1603
|
+
const ph = addManualEntry(name, plaintext, kind);
|
|
1604
|
+
sendJson(res, 200, { ok: true, placeholder: ph, name });
|
|
1605
|
+
},
|
|
1606
|
+
}), 'sensitive-guard: entries route');
|
|
1326
1607
|
}
|
|
1327
1608
|
|
|
1328
1609
|
/* ----------------------------------------------------------------- apply -- */
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-sensitive-guard",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "敏感保护:进入模型上下文前把密钥/令牌/密码替换为 <SG_>
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "敏感保护:进入模型上下文前把密钥/令牌/密码替换为 <SG_> 占位符,内置 221 条 gitleaks 检测规则与结构化字段判定;明文加密存本地保管库,设置页与对话内提供小锁点击还原,工具可将明文导出为 0600 文件供命令执行时使用。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "wangxinyu",
|
|
7
7
|
"repository": {
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"./locale/*.json": "./locale/*.json",
|
|
26
26
|
"./icon": "./icon.svg"
|
|
27
27
|
},
|
|
28
|
-
"files": ["index.js", "client.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE", "test.mjs"],
|
|
28
|
+
"files": ["index.js", "client.js", "cordis.patch.yml", "locale/*.json", "icon.svg", "README.md", "CHANGELOG.md", "LICENSE", "NOTICE", "test.mjs", "rules/*.json", "scripts/build-gitleaks.mjs"],
|
|
29
29
|
"scripts": {
|
|
30
30
|
"test": "node test.mjs"
|
|
31
31
|
},
|