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
package/index.js
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
*/
|
|
26
26
|
|
|
27
27
|
import { execFileSync } from 'node:child_process';
|
|
28
|
-
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
|
28
|
+
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from 'node:crypto';
|
|
29
29
|
import fs from 'node:fs';
|
|
30
30
|
import { isIP } from 'node:net';
|
|
31
31
|
import os from 'node:os';
|
|
@@ -34,9 +34,13 @@ 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
|
-
/** Stable placeholder form: <SG_ + 12 hex chars of
|
|
43
|
+
/** Stable placeholder form: <SG_ + 12 hex chars of HMAC(vault.key, plaintext) + >. */
|
|
40
44
|
const PH_EXACT = /^<SG_[0-9a-f]{12}>$/;
|
|
41
45
|
const PH_HINT = '<SG_';
|
|
42
46
|
const HASH_EXACT = /^[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
|
}
|
|
@@ -199,10 +208,23 @@ function decrypt(payload) {
|
|
|
199
208
|
return Buffer.concat([decipher.update(Buffer.from(ctB64, 'base64')), decipher.final()]).toString('utf8');
|
|
200
209
|
}
|
|
201
210
|
|
|
211
|
+
/** Internal vault key. Never exposed: the placeholder used to be derived from
|
|
212
|
+
* this, which made short/low-entropy secrets reversible by offline dictionary.
|
|
213
|
+
*/
|
|
202
214
|
function hashOf(value) {
|
|
203
215
|
return createHash('sha256').update(value, 'utf8').digest('hex').slice(0, 12);
|
|
204
216
|
}
|
|
205
217
|
|
|
218
|
+
/**
|
|
219
|
+
* Placeholder = HMAC-SHA256(vault.key, plaintext)[:12]. Deterministic, so the
|
|
220
|
+
* same secret always gets the same code, but offline brute force no longer
|
|
221
|
+
* works without the local key — a six-digit password could previously be
|
|
222
|
+
* recovered from the code in ~100ms.
|
|
223
|
+
*/
|
|
224
|
+
function placeholderOf(value) {
|
|
225
|
+
return `<SG_${createHmac('sha256', loadKey()).update(value, 'utf8').digest('hex').slice(0, 12)}>`;
|
|
226
|
+
}
|
|
227
|
+
|
|
206
228
|
function loadVault() {
|
|
207
229
|
if (vault.loaded) return;
|
|
208
230
|
vault.loaded = true;
|
|
@@ -214,6 +236,11 @@ function loadVault() {
|
|
|
214
236
|
if (typeof entry.ph !== 'string' || !PH_EXACT.test(entry.ph)) continue;
|
|
215
237
|
vault.entries.set(entry.hash, entry);
|
|
216
238
|
vault.byPh.set(entry.ph, entry.hash);
|
|
239
|
+
// Pre-0.4.0 codes were sha256(plaintext)[:12]. Keep every historical
|
|
240
|
+
// alias resolvable so old conversations can still unlock their chips.
|
|
241
|
+
for (const alias of Array.isArray(entry.aliases) ? entry.aliases : []) {
|
|
242
|
+
if (typeof alias === 'string' && PH_EXACT.test(alias)) vault.byPh.set(alias, entry.hash);
|
|
243
|
+
}
|
|
217
244
|
}
|
|
218
245
|
} catch (error) {
|
|
219
246
|
if (error && error.code !== 'ENOENT') lastError = `vault load: ${String(error.message || error)}`;
|
|
@@ -244,6 +271,7 @@ function persistVault(immediate) {
|
|
|
244
271
|
function trimVault() {
|
|
245
272
|
if (vault.entries.size <= MAX_VAULT_ENTRIES) return;
|
|
246
273
|
const ordered = [...vault.entries.values()]
|
|
274
|
+
.filter((entry) => !entry.pinned)
|
|
247
275
|
.sort((a, b) => String(a.lastHitAt || a.createdAt).localeCompare(String(b.lastHitAt || b.createdAt)));
|
|
248
276
|
for (let i = 0; i < ordered.length && vault.entries.size > MAX_VAULT_ENTRIES; i += 1) {
|
|
249
277
|
const victim = ordered[i];
|
|
@@ -263,16 +291,29 @@ function noteAudit(kind, extra) {
|
|
|
263
291
|
function remember(plaintext, rule, origin, label) {
|
|
264
292
|
loadVault();
|
|
265
293
|
const hash = hashOf(plaintext);
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
294
|
+
const ph = placeholderOf(plaintext);
|
|
295
|
+
const existing = vault.entries.get(hash);
|
|
296
|
+
if (existing) {
|
|
297
|
+
existing.hits = (existing.hits || 0) + 1;
|
|
298
|
+
existing.lastHitAt = new Date().toISOString();
|
|
299
|
+
// Upgrade a pre-0.4.0 entry in place. The old code stays in `aliases` and
|
|
300
|
+
// in byPh, so chips already written into old session logs still resolve.
|
|
301
|
+
if (existing.ph !== ph) {
|
|
302
|
+
const aliases = Array.isArray(existing.aliases) ? existing.aliases.slice() : [];
|
|
303
|
+
if (!aliases.includes(existing.ph)) aliases.push(existing.ph);
|
|
304
|
+
existing.aliases = aliases;
|
|
305
|
+
existing.ph = ph;
|
|
306
|
+
vault.byPh.set(ph, hash);
|
|
307
|
+
for (const alias of aliases) vault.byPh.set(alias, hash);
|
|
308
|
+
noteAudit('recode', { ph });
|
|
309
|
+
persistVault();
|
|
310
|
+
}
|
|
311
|
+
return existing.ph;
|
|
271
312
|
}
|
|
272
|
-
const
|
|
273
|
-
entry = {
|
|
313
|
+
const entry = {
|
|
274
314
|
hash,
|
|
275
315
|
ph,
|
|
316
|
+
aliases: [],
|
|
276
317
|
enc: encrypt(plaintext),
|
|
277
318
|
prefix: prefixOf(plaintext),
|
|
278
319
|
preview: plaintext.length >= PREVIEW_MIN ? `${plaintext.slice(0, 8)}…` : '',
|
|
@@ -296,6 +337,9 @@ function remember(plaintext, rule, origin, label) {
|
|
|
296
337
|
function entryView(entry) {
|
|
297
338
|
return {
|
|
298
339
|
ph: entry.ph,
|
|
340
|
+
aliases: Array.isArray(entry.aliases) ? entry.aliases.slice() : [],
|
|
341
|
+
name: String(entry.name || ''),
|
|
342
|
+
pinned: Boolean(entry.pinned),
|
|
299
343
|
preview: entry.preview,
|
|
300
344
|
rule: entry.rule,
|
|
301
345
|
label: entry.label || entry.rule,
|
|
@@ -322,8 +366,114 @@ function entryViewForModel(entry) {
|
|
|
322
366
|
};
|
|
323
367
|
}
|
|
324
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
|
+
|
|
325
419
|
/* ---------------------------------------------------------------- rules -- */
|
|
326
420
|
|
|
421
|
+
/**
|
|
422
|
+
* Field names are stronger evidence than value shape: a tool result carrying
|
|
423
|
+
* {"password": "..."} is a credential even when the value has no vendor prefix.
|
|
424
|
+
* Whole name segments only, so `author`, `tokenizer`, `secretary` stay clean.
|
|
425
|
+
*/
|
|
426
|
+
const SENSITIVE_KEY_WORDS = new Set([
|
|
427
|
+
'password', 'passwd', 'pwd', 'passphrase', 'pass', 'secret', 'token',
|
|
428
|
+
'apikey', 'accesskey', 'clientsecret', 'credential', 'credentials',
|
|
429
|
+
'auth', 'authorization', 'privatekey', 'dsn', 'connectionstring',
|
|
430
|
+
'accesstoken', 'refreshtoken', 'sessionkey', 'appkey', 'appsecret',
|
|
431
|
+
]);
|
|
432
|
+
const KEY_NEGATIVE = /(?:hint|policy|count|length|type|name|label|description|enabled|required|expiry|expires|ttl|url|path|example|placeholder|regex|pattern|schema|comment|help|text|title|error|message|status|state|flag|version|format|kind|mode|index|size|boolean|number|id|ids|list|map|set)$/i;
|
|
433
|
+
const PLACEHOLDER_VALUE = /^(?:null|undefined|nil|none|n\/a|na|true|false|yes|no|unknown|empty|redacted|masked|hidden|placeholder|example|sample|dummy|fake|test|demo|todo|fixme|tbd|not[_-]?set[_-]?(?:yet)?|changeme|change[_-]?me|your[_-]?(?:password|passwd|token|key|secret|api[_-]?key)[_-]?(?:here)?|(?:password|passwd|secret|token|api[_-]?key)[_-]?(?:here|placeholder|example)?|x{2,}|\*{2,}|\.{2,}|-{2,}|\?{2,}|0{3,}|<[^>]{1,40}>|\$\{[^}]{1,60}\}|\{\{[^}]{1,60}\}\}|\$[A-Z_][A-Z0-9_]*|%\(?[a-z_]+\)?s)$/i;
|
|
434
|
+
|
|
435
|
+
/** Values that are documentation, placeholders or template variables, not secrets. */
|
|
436
|
+
function isPlaceholderValue(value) {
|
|
437
|
+
if (typeof value !== 'string') return false;
|
|
438
|
+
const v = value.trim();
|
|
439
|
+
if (v.length < 3 || v.includes(PH_HINT)) return true;
|
|
440
|
+
return PLACEHOLDER_VALUE.test(v);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function isSensitiveKey(key) {
|
|
444
|
+
if (typeof key !== 'string' || key.length > 64 || isIdentifierKey(key)) return false;
|
|
445
|
+
if (KEY_NEGATIVE.test(key)) return false;
|
|
446
|
+
if (/(密码|口令|密钥|令牌|凭证|私钥)/.test(key)) return true;
|
|
447
|
+
const parts = key.toLowerCase().replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[^a-z0-9]+/).filter(Boolean);
|
|
448
|
+
return parts.some((part) => SENSITIVE_KEY_WORDS.has(part));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function labelForKey(key) {
|
|
452
|
+
const k = String(key).toLowerCase();
|
|
453
|
+
if (/pass|密码|口令/.test(k)) return '密码';
|
|
454
|
+
if (/token|令牌|jwt|bearer|auth/.test(k)) return '令牌';
|
|
455
|
+
if (/key|secret|密钥|凭证|credential|dsn|connection/.test(k)) return '密钥';
|
|
456
|
+
return '其它';
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** "key": "value" inside a JSON *string*. Only ingress gets these hits. */
|
|
460
|
+
const STRUCT_FIELD_RE = /"(?<key>[A-Za-z0-9_.\-]{1,64})"\s*:\s*"(?<value>[^"\\]{1,200})"/gd;
|
|
461
|
+
|
|
462
|
+
function structuralHits(text) {
|
|
463
|
+
const out = [];
|
|
464
|
+
STRUCT_FIELD_RE.lastIndex = 0;
|
|
465
|
+
let match;
|
|
466
|
+
while ((match = STRUCT_FIELD_RE.exec(text)) !== null) {
|
|
467
|
+
const key = match.groups && match.groups.key;
|
|
468
|
+
const value = match.groups && match.groups.value;
|
|
469
|
+
const range = match.indices && match.indices.groups && match.indices.groups.value;
|
|
470
|
+
if (!key || !value || !range) continue;
|
|
471
|
+
if (!isSensitiveKey(key) || isPlaceholderValue(value)) continue;
|
|
472
|
+
out.push({ offset: range[0], end: range[1], value, rule: 'structured-field', label: labelForKey(key) });
|
|
473
|
+
}
|
|
474
|
+
return out;
|
|
475
|
+
}
|
|
476
|
+
|
|
327
477
|
const BUILTIN_RULES = [
|
|
328
478
|
{ id: 'openai-key', group: 0, re: /\bsk-[A-Za-z0-9_-]{16,}\b/g },
|
|
329
479
|
// A pasted key whose display soft-wrapped: the prefix and the tail land on
|
|
@@ -380,7 +530,8 @@ try {
|
|
|
380
530
|
console.warn('[sensitive-guard] rule precompile failed:', error && error.message);
|
|
381
531
|
}
|
|
382
532
|
|
|
383
|
-
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;
|
|
384
535
|
|
|
385
536
|
function reloadRules(force) {
|
|
386
537
|
const now = Date.now();
|
|
@@ -408,6 +559,9 @@ function reloadRules(force) {
|
|
|
408
559
|
fileRules.entropy = raw && raw.entropy === true;
|
|
409
560
|
fileRules.entropyThreshold = raw && Number.isFinite(raw.entropyThreshold) ? raw.entropyThreshold : 4.5;
|
|
410
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) : []);
|
|
411
565
|
// Opt-in LAN exposure for the reveal routes. Empty (the default) keeps them
|
|
412
566
|
// loopback-only. Entries are CIDRs, e.g. ["192.168.0.0/16"].
|
|
413
567
|
const wanted = Array.isArray(raw && raw.allowCidrs) ? raw.allowCidrs.map((item) => String(item).trim()) : [];
|
|
@@ -415,6 +569,7 @@ function reloadRules(force) {
|
|
|
415
569
|
const rejected = wanted.filter((item) => parseCidr(item) === null);
|
|
416
570
|
fileRules.allowCidrs = accepted;
|
|
417
571
|
fileRules.error = null;
|
|
572
|
+
allRulesCache = null;
|
|
418
573
|
if (rejected.length > 0) {
|
|
419
574
|
fileRules.error = `allowCidrs 忽略无效项: ${rejected.join(', ')}(需形如 192.168.0.0/16,且不接受 /0)`;
|
|
420
575
|
}
|
|
@@ -427,10 +582,94 @@ function disabledSet() {
|
|
|
427
582
|
return fileRules.disabled instanceof Set ? fileRules.disabled : new Set();
|
|
428
583
|
}
|
|
429
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
|
+
|
|
430
649
|
function activeRules() {
|
|
431
650
|
reloadRules(false);
|
|
432
|
-
|
|
433
|
-
|
|
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
|
+
}
|
|
434
673
|
}
|
|
435
674
|
|
|
436
675
|
/* -------------------------------------------------------------- scrubbing -- */
|
|
@@ -467,12 +706,20 @@ function entropyHits(text) {
|
|
|
467
706
|
}
|
|
468
707
|
|
|
469
708
|
/** Non-overlapping hits: [{offset, end, value, rule}]. Already-masked values are skipped. */
|
|
470
|
-
function findHits(text) {
|
|
709
|
+
function findHits(text, origin) {
|
|
471
710
|
// A pathological custom rule can backtrack for minutes on a huge blob, and this
|
|
472
711
|
// runs synchronously inside a hook — cap the window rather than freeze the host.
|
|
473
712
|
const scan = text.length > MAX_SCAN_CHARS ? text.slice(0, MAX_SCAN_CHARS) : text;
|
|
474
713
|
const hits = [];
|
|
714
|
+
let lower = null;
|
|
475
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
|
+
}
|
|
476
723
|
rule.re.lastIndex = 0;
|
|
477
724
|
let match;
|
|
478
725
|
while ((match = rule.re.exec(scan)) !== null) {
|
|
@@ -499,13 +746,32 @@ function findHits(text) {
|
|
|
499
746
|
}
|
|
500
747
|
// The keyword group (when the rule has one) says *what* leaked — password /
|
|
501
748
|
// token / key — which the rule id alone cannot express for keyword-prose.
|
|
502
|
-
|
|
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);
|
|
503
751
|
hits.push({ offset, end, value: trimmed, rule: rule.id, label });
|
|
504
752
|
}
|
|
505
753
|
}
|
|
754
|
+
// A field name is strong evidence for user input and tool output, but a model
|
|
755
|
+
// writing an example JSON is not a leak. Keep structural hits off the
|
|
756
|
+
// outbound backstop so the model's own examples are not scrambled.
|
|
757
|
+
if (origin !== 'outbound') {
|
|
758
|
+
for (const hit of structuralHits(scan)) hits.push(hit);
|
|
759
|
+
}
|
|
506
760
|
if (fileRules.entropy) {
|
|
507
761
|
for (const hit of entropyHits(scan)) hits.push(hit);
|
|
508
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
|
+
}
|
|
509
775
|
hits.sort((a, b) => a.offset - b.offset || b.end - a.end);
|
|
510
776
|
const kept = [];
|
|
511
777
|
let last = -1;
|
|
@@ -517,12 +783,17 @@ function findHits(text) {
|
|
|
517
783
|
|
|
518
784
|
function scrubText(text, origin) {
|
|
519
785
|
if (typeof text !== 'string' || text.length < 6) return [text, false];
|
|
520
|
-
const hits = findHits(text);
|
|
786
|
+
const hits = findHits(text, origin);
|
|
521
787
|
if (!hits.length) return [text, false];
|
|
522
788
|
let out = '';
|
|
523
789
|
let cursor = 0;
|
|
790
|
+
let maskedAny = false;
|
|
524
791
|
for (const hit of hits) {
|
|
792
|
+
// Obvious documentation placeholders win over every rule, including
|
|
793
|
+
// structural field names.
|
|
794
|
+
if (isPlaceholderValue(hit.value)) continue;
|
|
525
795
|
out += text.slice(cursor, hit.offset);
|
|
796
|
+
maskedAny = true;
|
|
526
797
|
try {
|
|
527
798
|
// Leave the vendor prefix in the sentence; only the authenticating tail
|
|
528
799
|
// becomes a placeholder. The vault still keys on the complete value.
|
|
@@ -538,7 +809,7 @@ function scrubText(text, origin) {
|
|
|
538
809
|
cursor = hit.end;
|
|
539
810
|
}
|
|
540
811
|
out += text.slice(cursor);
|
|
541
|
-
return [out,
|
|
812
|
+
return [out, maskedAny];
|
|
542
813
|
}
|
|
543
814
|
|
|
544
815
|
/** Identifier-shaped keys carry handles, not secrets; rewriting one breaks lookups. */
|
|
@@ -554,7 +825,22 @@ function isIdentifierKey(key) {
|
|
|
554
825
|
function scrubDeep(value, origin, key) {
|
|
555
826
|
if (typeof value === 'string') {
|
|
556
827
|
if (isIdentifierKey(key)) return [value, false];
|
|
557
|
-
|
|
828
|
+
const [scrubbed, did] = scrubText(value, origin);
|
|
829
|
+
if (did) return [scrubbed, true];
|
|
830
|
+
// Already-parsed objects: the field name is the strongest signal and the
|
|
831
|
+
// value may be a short password with no vendor prefix at all. Never do
|
|
832
|
+
// this on outbound text — a model's example JSON is not a leak.
|
|
833
|
+
if (origin !== 'outbound' && key && isSensitiveKey(key) && !isPlaceholderValue(value)) {
|
|
834
|
+
try {
|
|
835
|
+
const ph = remember(value, 'structured-field', origin, labelForKey(key));
|
|
836
|
+
stats.maskedRuns += 1;
|
|
837
|
+
return [ph, true];
|
|
838
|
+
} catch (error) {
|
|
839
|
+
lastError = `capture: ${String((error && error.message) || error)}`;
|
|
840
|
+
stats.failOpen += 1;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
return [value, false];
|
|
558
844
|
}
|
|
559
845
|
if (Array.isArray(value)) {
|
|
560
846
|
let changed = false;
|
|
@@ -1030,7 +1316,7 @@ function jsonPostOk(req, level) {
|
|
|
1030
1316
|
}
|
|
1031
1317
|
|
|
1032
1318
|
/**
|
|
1033
|
-
* Single entry gate for the
|
|
1319
|
+
* Single entry gate for the five routes. Returns the level so callers can
|
|
1034
1320
|
* branch, or null after having already sent the rejection.
|
|
1035
1321
|
*
|
|
1036
1322
|
* `allowRestricted` lets the vault route answer read-only metadata to an
|
|
@@ -1106,7 +1392,7 @@ function registerRoutes(ctx) {
|
|
|
1106
1392
|
dataDir: snap.dataDir,
|
|
1107
1393
|
lastError: snap.lastError,
|
|
1108
1394
|
outboundScrub: fileRules.outboundScrub,
|
|
1109
|
-
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 },
|
|
1110
1396
|
// Tells the UI whether this page is being served over LAN (allowCidrs).
|
|
1111
1397
|
access: {
|
|
1112
1398
|
level,
|
|
@@ -1163,8 +1449,9 @@ function registerRoutes(ctx) {
|
|
|
1163
1449
|
const ms = pausedMs();
|
|
1164
1450
|
const finite = Number.isFinite(ms);
|
|
1165
1451
|
return {
|
|
1452
|
+
off: pause.off,
|
|
1166
1453
|
paused: ms > 0,
|
|
1167
|
-
untilRestart: pause.untilRestart,
|
|
1454
|
+
untilRestart: !pause.off && pause.untilRestart,
|
|
1168
1455
|
until: finite && ms > 0 ? Date.now() + ms : null,
|
|
1169
1456
|
remainingMs: finite ? ms : null,
|
|
1170
1457
|
};
|
|
@@ -1181,7 +1468,23 @@ function registerRoutes(ctx) {
|
|
|
1181
1468
|
try { body = JSON.parse(await readBody(req, 2048) || '{}'); } catch { sendJson(res, 400, { error: 'bad-json' }); return; }
|
|
1182
1469
|
const action = String((body && body.action) || '');
|
|
1183
1470
|
|
|
1184
|
-
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.
|
|
1185
1488
|
pause.until = 0;
|
|
1186
1489
|
pause.untilRestart = false;
|
|
1187
1490
|
persistPause();
|
|
@@ -1209,6 +1512,98 @@ function registerRoutes(ctx) {
|
|
|
1209
1512
|
sendJson(res, 200, shape());
|
|
1210
1513
|
},
|
|
1211
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');
|
|
1212
1607
|
}
|
|
1213
1608
|
|
|
1214
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
|
},
|