leakshield 0.1.3 → 0.2.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/README.md +294 -173
- package/README.zh-TW.md +290 -164
- package/dist/config/loader.js +14 -10
- package/dist/config/plain-object.js +14 -0
- package/dist/decision/pseudonymization.js +133 -82
- package/dist/decision/redaction.js +2 -0
- package/dist/decision/value-search.js +250 -0
- package/dist/doctor.js +429 -138
- package/dist/i18n/en.js +4 -0
- package/dist/i18n/zh-TW.js +4 -0
- package/dist/index.js +3 -2
- package/dist/opencode-env-tools.js +0 -75
- package/dist/opencode-hooks.js +4 -73
- package/dist/opencode-transparent.js +16 -1
- package/dist/opencode.js +12 -54
- package/dist/plugin-options.js +15 -21
- package/dist/scanner/encoding.js +291 -7
- package/dist/scanner/engine.js +68 -40
- package/dist/scanner/utils.js +26 -2
- package/dist/transports/cli.js +2 -2
- package/dist/transports/web.js +3 -3
- package/dist/types.js +1 -0
- package/package.json +3 -3
package/dist/scanner/encoding.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
|
|
6
6
|
import { foldConfusables } from "./unicode.js";
|
|
7
|
+
import { getLineCol } from "./utils.js";
|
|
8
|
+
/** Decoded text that hints at a credential; raises the decoder's confidence. */
|
|
9
|
+
const SENSITIVE_HINT = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i;
|
|
7
10
|
// ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
|
|
8
11
|
/**
|
|
9
12
|
* Detects potential Base64 encoded strings.
|
|
@@ -13,7 +16,7 @@ import { foldConfusables } from "./unicode.js";
|
|
|
13
16
|
* - Proper padding (0-2 '=' chars at end)
|
|
14
17
|
* - Even length when padded
|
|
15
18
|
*/
|
|
16
|
-
function
|
|
19
|
+
function detectBase64Matches(text) {
|
|
17
20
|
const candidates = [];
|
|
18
21
|
// Pattern for Base64 strings (16+ chars, lowered threshold for security)
|
|
19
22
|
const base64Pattern = /[A-Za-z0-9+/]{16,}={0,2}/g;
|
|
@@ -34,10 +37,13 @@ function detectBase64(text) {
|
|
|
34
37
|
// Low entropy suggests it's not Base64 (e.g., "AAAAAAAAAA...")
|
|
35
38
|
if (entropy < 0.3)
|
|
36
39
|
continue;
|
|
37
|
-
candidates.push(candidate);
|
|
40
|
+
candidates.push({ text: candidate, index: match.index });
|
|
38
41
|
}
|
|
39
42
|
return candidates;
|
|
40
43
|
}
|
|
44
|
+
function detectBase64(text) {
|
|
45
|
+
return detectBase64Matches(text).map((c) => c.text);
|
|
46
|
+
}
|
|
41
47
|
/**
|
|
42
48
|
* Attempts to decode a Base64 string and validate the result.
|
|
43
49
|
* Returns null if decoding fails or result doesn't look like text.
|
|
@@ -54,7 +60,7 @@ function tryDecodeBase64(encoded) {
|
|
|
54
60
|
if (!/[a-zA-Z]{2,}/.test(decoded))
|
|
55
61
|
return null;
|
|
56
62
|
// Check for common sensitive patterns in decoded text
|
|
57
|
-
const hasSensitivePattern =
|
|
63
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
58
64
|
return {
|
|
59
65
|
decoded,
|
|
60
66
|
encoding_type: 'Base64',
|
|
@@ -93,7 +99,7 @@ function tryDecodeUrl(encoded) {
|
|
|
93
99
|
const decoded = decodeURIComponent(encoded.replace(/\+/g, ' '));
|
|
94
100
|
if (decoded === encoded)
|
|
95
101
|
return null; // Nothing was decoded
|
|
96
|
-
const hasSensitivePattern =
|
|
102
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
97
103
|
return {
|
|
98
104
|
decoded,
|
|
99
105
|
encoding_type: 'URL',
|
|
@@ -108,16 +114,19 @@ function tryDecodeUrl(encoded) {
|
|
|
108
114
|
/**
|
|
109
115
|
* Detects potential hex-encoded strings.
|
|
110
116
|
*/
|
|
111
|
-
function
|
|
117
|
+
function detectHexMatches(text) {
|
|
112
118
|
const candidates = [];
|
|
113
119
|
// Look for sequences of hex pairs
|
|
114
120
|
const hexPattern = /(?:\\x[0-9a-fA-F]{2}|[0-9a-fA-F]{32,})/g;
|
|
115
121
|
const matches = text.matchAll(hexPattern);
|
|
116
122
|
for (const match of matches) {
|
|
117
|
-
candidates.push(match[0]);
|
|
123
|
+
candidates.push({ text: match[0], index: match.index });
|
|
118
124
|
}
|
|
119
125
|
return candidates;
|
|
120
126
|
}
|
|
127
|
+
function detectHexEncoding(text) {
|
|
128
|
+
return detectHexMatches(text).map((c) => c.text);
|
|
129
|
+
}
|
|
121
130
|
/**
|
|
122
131
|
* Attempts to decode hex-encoded text.
|
|
123
132
|
*/
|
|
@@ -136,7 +145,7 @@ function tryDecodeHex(encoded) {
|
|
|
136
145
|
}
|
|
137
146
|
if (decoded.length < 10)
|
|
138
147
|
return null;
|
|
139
|
-
const hasSensitivePattern =
|
|
148
|
+
const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
|
|
140
149
|
return {
|
|
141
150
|
decoded,
|
|
142
151
|
encoding_type: 'Hex',
|
|
@@ -276,3 +285,278 @@ function mergeScanResults(results, config, encodingTypesFound) {
|
|
|
276
285
|
findings: deduplicated,
|
|
277
286
|
};
|
|
278
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* True when masking the runs located in `text` accounts for EVERY decoded
|
|
290
|
+
* finding in `decodedMatches` (the match_text values the whole-segment
|
|
291
|
+
* decoding scan reported). Three checks:
|
|
292
|
+
* - Normalization: any zero-width or look-alike character in `text` returns
|
|
293
|
+
* false, wherever it sits. The generic decoder also decodes the stripped and
|
|
294
|
+
* folded sources, whose runs the locator cannot map back, so partial
|
|
295
|
+
* masking of the raw source could erase the evidence that a hidden part
|
|
296
|
+
* remains.
|
|
297
|
+
* - Evasion: a located decoded form that reports a Unicode evasion returns
|
|
298
|
+
* false. The same character can be percent-encoded, which the normalization
|
|
299
|
+
* check cannot see, and the finding it hides has no source span.
|
|
300
|
+
* - Coverage: each decoded match must equal, or be a substring of, a decoded
|
|
301
|
+
* match of a located run or a direct match (substring because the generic
|
|
302
|
+
* decoder's +/-50 windows can clip a value the locator sees in full). Direct
|
|
303
|
+
* matches count because those windows also re-report plain findings near any
|
|
304
|
+
* percent run, and the direct findings are masked anyway.
|
|
305
|
+
*/
|
|
306
|
+
export function decodedFindingsAttributable(text, config, opts, decodedMatches, directMatches) {
|
|
307
|
+
if (foldConfusables(text.replace(ZERO_WIDTH_CHARS, "")) !== text)
|
|
308
|
+
return false;
|
|
309
|
+
const { runs, evasion } = locateEncoded(text, config, opts);
|
|
310
|
+
if (evasion)
|
|
311
|
+
return false;
|
|
312
|
+
const located = new Set(directMatches);
|
|
313
|
+
for (const run of runs) {
|
|
314
|
+
for (const match of run.decodedMatches)
|
|
315
|
+
located.add(match);
|
|
316
|
+
}
|
|
317
|
+
for (const wanted of new Set(decodedMatches)) {
|
|
318
|
+
if (located.has(wanted))
|
|
319
|
+
continue;
|
|
320
|
+
let covered = false;
|
|
321
|
+
for (const match of located) {
|
|
322
|
+
if (match.includes(wanted)) {
|
|
323
|
+
covered = true;
|
|
324
|
+
break;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
if (!covered)
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
/** What makes two findings distinct: dropping one must never lose a severity. */
|
|
333
|
+
function findingIdentity(finding) {
|
|
334
|
+
return JSON.stringify([finding.type, finding.severity, finding.description, finding.match_text]);
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* Re-expresses the encoded findings of a decoding scan as spans of `text`.
|
|
338
|
+
* scanTextWithDecoding reports decoded findings at offsets of the DECODED
|
|
339
|
+
* string, which redaction would apply to the source. Here each located run
|
|
340
|
+
* contributes its decoded findings at the run's exact source span, so a
|
|
341
|
+
* placeholder replaces the whole run.
|
|
342
|
+
*
|
|
343
|
+
* When the decoded findings cannot all be attributed to located runs (a
|
|
344
|
+
* hidden run, a Unicode evasion, a finding without text), it fails closed:
|
|
345
|
+
* every encoded finding loses its offsets, so no redacted content or safe
|
|
346
|
+
* preview is built for the result. `encoding_detected` is kept either way,
|
|
347
|
+
* which the redaction verifier and deidentify rely on to stay fail-closed.
|
|
348
|
+
*/
|
|
349
|
+
export function anchorDecodedFindings(text, scan, config, opts) {
|
|
350
|
+
if (scan.decoded.length === 0)
|
|
351
|
+
return scan.findings;
|
|
352
|
+
const decodedFindings = scan.decoded.flatMap((r) => r.findings);
|
|
353
|
+
const decodedMatches = [];
|
|
354
|
+
let attributable = true;
|
|
355
|
+
for (const finding of decodedFindings) {
|
|
356
|
+
if (typeof finding.match_text !== "string" || finding.unicode_detected !== undefined) {
|
|
357
|
+
attributable = false;
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
decodedMatches.push(finding.match_text);
|
|
361
|
+
}
|
|
362
|
+
if (attributable) {
|
|
363
|
+
const directMatches = scan.original.findings.flatMap((f) => (typeof f.match_text === "string" ? [f.match_text] : []));
|
|
364
|
+
attributable = decodedFindingsAttributable(text, config, opts, decodedMatches, directMatches);
|
|
365
|
+
}
|
|
366
|
+
if (!attributable) {
|
|
367
|
+
// Read scan.decoded, not the merged findings: the merge drops a decoded
|
|
368
|
+
// finding whose decoded offsets equal a direct finding's, and the direct
|
|
369
|
+
// finding alone would still produce a redaction that misses the run.
|
|
370
|
+
const seen = new Set();
|
|
371
|
+
const stripped = [];
|
|
372
|
+
for (const finding of decodedFindings) {
|
|
373
|
+
const key = findingIdentity(finding);
|
|
374
|
+
if (seen.has(key))
|
|
375
|
+
continue;
|
|
376
|
+
seen.add(key);
|
|
377
|
+
const { match_start: _start, match_end: _end, ...rest } = finding;
|
|
378
|
+
stripped.push(rest);
|
|
379
|
+
}
|
|
380
|
+
return [...scan.original.findings, ...stripped];
|
|
381
|
+
}
|
|
382
|
+
const anchored = [];
|
|
383
|
+
const seen = new Set();
|
|
384
|
+
// Every finding of a run shares the run's span, so the span alone cannot
|
|
385
|
+
// tell them apart: identity comes from the decoded match, taken before
|
|
386
|
+
// match_text is rewritten to the source slice.
|
|
387
|
+
const add = (finding, identity) => {
|
|
388
|
+
const key = `${finding.match_start}:${finding.match_end}:${identity}`;
|
|
389
|
+
if (seen.has(key))
|
|
390
|
+
return;
|
|
391
|
+
seen.add(key);
|
|
392
|
+
anchored.push(finding);
|
|
393
|
+
};
|
|
394
|
+
for (const finding of scan.original.findings)
|
|
395
|
+
add(finding, findingIdentity(finding));
|
|
396
|
+
for (const run of locateEncodedRuns(text, config, opts)) {
|
|
397
|
+
const { line, col } = getLineCol(text, run.start);
|
|
398
|
+
for (const finding of run.findings) {
|
|
399
|
+
add({
|
|
400
|
+
...finding,
|
|
401
|
+
line,
|
|
402
|
+
column: col,
|
|
403
|
+
match_start: run.start,
|
|
404
|
+
match_end: run.end,
|
|
405
|
+
match_text: text.slice(run.start, run.end),
|
|
406
|
+
}, findingIdentity(finding));
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
return anchored;
|
|
410
|
+
}
|
|
411
|
+
const SEVERITY_ORDER = { HIGH: 3, MEDIUM: 2, LOW: 1 };
|
|
412
|
+
function highestSeverity(findings) {
|
|
413
|
+
let best = "LOW";
|
|
414
|
+
for (const finding of findings) {
|
|
415
|
+
if (SEVERITY_ORDER[finding.severity] > SEVERITY_ORDER[best])
|
|
416
|
+
best = finding.severity;
|
|
417
|
+
}
|
|
418
|
+
return best;
|
|
419
|
+
}
|
|
420
|
+
const PERCENT_RUNS = /(?:%[0-9A-Fa-f]{2})+/g;
|
|
421
|
+
/**
|
|
422
|
+
* Locates the encoded runs of `text` whose decoded form holds a finding, as
|
|
423
|
+
* exact spans of `text` itself. This is the ONLY place decoded offsets are
|
|
424
|
+
* mapped back to the source, and it works on `text` alone: the zero-width
|
|
425
|
+
* stripped and confusable-folded sources that scanTextWithDecoding also
|
|
426
|
+
* decodes have offsets that do not map back, so runs hidden that way are not
|
|
427
|
+
* located (the caller's strict rescan keeps refusing them).
|
|
428
|
+
*
|
|
429
|
+
* - Base64 and hex: the span is the whole candidate match, decoded with the
|
|
430
|
+
* same functions and confidence thresholds as scanTextWithDecoding.
|
|
431
|
+
* - URL: the generic decoder's +/-50 window is NOT used, because a clipped
|
|
432
|
+
* window would mask part of a value and leak the rest. The text is split
|
|
433
|
+
* into percent runs and literal pieces and decoded into one string with a
|
|
434
|
+
* decoded-unit to source-range map: literal units map one to one, every
|
|
435
|
+
* unit of a decoded run maps to the WHOLE run. A finding becomes a span
|
|
436
|
+
* only if it covers a decoded-run unit or a "+" turned into a space (the
|
|
437
|
+
* direct scan already handles the rest) and its offsets are exact.
|
|
438
|
+
*/
|
|
439
|
+
export function locateEncodedRuns(text, config, opts) {
|
|
440
|
+
return locateEncoded(text, config, opts).runs;
|
|
441
|
+
}
|
|
442
|
+
function hasUnicodeEvasion(findings) {
|
|
443
|
+
return findings.some((f) => f.unicode_detected !== undefined);
|
|
444
|
+
}
|
|
445
|
+
function locateEncoded(text, config, opts) {
|
|
446
|
+
const runs = [];
|
|
447
|
+
let evasion = false;
|
|
448
|
+
const locate = (candidates, decode, minConfidence) => {
|
|
449
|
+
for (const candidate of candidates) {
|
|
450
|
+
const decoded = decode(candidate.text);
|
|
451
|
+
if (!decoded || decoded.confidence < minConfidence)
|
|
452
|
+
continue;
|
|
453
|
+
const result = scanTextInternal(decoded.decoded, config, opts);
|
|
454
|
+
if (!result.safe) {
|
|
455
|
+
if (hasUnicodeEvasion(result.findings))
|
|
456
|
+
evasion = true;
|
|
457
|
+
const type = decoded.encoding_type;
|
|
458
|
+
const encoding_detected = type === "Base64"
|
|
459
|
+
? { type, confidence: decoded.confidence, encoded_length: candidate.text.length, decoded_length: decoded.decoded.length }
|
|
460
|
+
: { type, confidence: decoded.confidence };
|
|
461
|
+
runs.push({
|
|
462
|
+
start: candidate.index,
|
|
463
|
+
end: candidate.index + candidate.text.length,
|
|
464
|
+
severity: highestSeverity(result.findings),
|
|
465
|
+
decodedMatches: result.findings.flatMap((f) => (typeof f.match_text === "string" ? [f.match_text] : [])),
|
|
466
|
+
findings: result.findings.map((f) => ({ ...f, encoding_detected: { ...encoding_detected } })),
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
locate(detectBase64Matches(text), tryDecodeBase64, 0.6);
|
|
472
|
+
locate(detectHexMatches(text), tryDecodeHex, 0.5);
|
|
473
|
+
const locateUrl = (plusAsSpace) => {
|
|
474
|
+
const url = locateUrlRuns(text, config, plusAsSpace, opts);
|
|
475
|
+
runs.push(...url.runs);
|
|
476
|
+
if (url.evasion)
|
|
477
|
+
evasion = true;
|
|
478
|
+
};
|
|
479
|
+
locateUrl(true);
|
|
480
|
+
// "+" is ambiguous: as a space it splits "a+b%40example.com" and would leave
|
|
481
|
+
// "a+" unmasked, so also locate with "+" kept literal. Callers merge overlaps.
|
|
482
|
+
if (text.includes("+"))
|
|
483
|
+
locateUrl(false);
|
|
484
|
+
return { runs, evasion };
|
|
485
|
+
}
|
|
486
|
+
function locateUrlRuns(text, config, plusAsSpace, opts) {
|
|
487
|
+
const pieces = [];
|
|
488
|
+
// Per decoded UTF-16 unit: the source range it maps to, and whether it came
|
|
489
|
+
// from a decoded run or a "+" (only those can hide a finding from the scan).
|
|
490
|
+
const unitStart = [];
|
|
491
|
+
const unitEnd = [];
|
|
492
|
+
const unitHot = [];
|
|
493
|
+
let anyHot = false;
|
|
494
|
+
const addLiteral = (from, to) => {
|
|
495
|
+
for (let i = from; i < to; i += 1) {
|
|
496
|
+
const plus = plusAsSpace && text[i] === "+";
|
|
497
|
+
pieces.push(plus ? " " : text[i]);
|
|
498
|
+
unitStart.push(i);
|
|
499
|
+
unitEnd.push(i + 1);
|
|
500
|
+
unitHot.push(plus);
|
|
501
|
+
if (plus)
|
|
502
|
+
anyHot = true;
|
|
503
|
+
}
|
|
504
|
+
};
|
|
505
|
+
let cursor = 0;
|
|
506
|
+
for (const match of text.matchAll(PERCENT_RUNS)) {
|
|
507
|
+
const start = match.index;
|
|
508
|
+
const end = start + match[0].length;
|
|
509
|
+
addLiteral(cursor, start);
|
|
510
|
+
cursor = end;
|
|
511
|
+
let decoded;
|
|
512
|
+
try {
|
|
513
|
+
decoded = decodeURIComponent(match[0]);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
if (!(error instanceof URIError))
|
|
517
|
+
throw error;
|
|
518
|
+
addLiteral(start, end); // malformed run stays literal
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
pieces.push(decoded);
|
|
522
|
+
for (let i = 0; i < decoded.length; i += 1) {
|
|
523
|
+
unitStart.push(start);
|
|
524
|
+
unitEnd.push(end);
|
|
525
|
+
unitHot.push(true);
|
|
526
|
+
}
|
|
527
|
+
anyHot = true;
|
|
528
|
+
}
|
|
529
|
+
addLiteral(cursor, text.length);
|
|
530
|
+
if (!anyHot)
|
|
531
|
+
return { runs: [], evasion: false };
|
|
532
|
+
const decodedText = pieces.join("");
|
|
533
|
+
const result = scanTextInternal(decodedText, config, opts);
|
|
534
|
+
if (result.safe || result.was_truncated)
|
|
535
|
+
return { runs: [], evasion: false };
|
|
536
|
+
const runs = [];
|
|
537
|
+
for (const finding of result.findings) {
|
|
538
|
+
const start = finding.match_start;
|
|
539
|
+
const end = finding.match_end;
|
|
540
|
+
const matched = finding.match_text;
|
|
541
|
+
if (typeof start !== "number" || typeof end !== "number" || typeof matched !== "string" ||
|
|
542
|
+
!Number.isInteger(start) || !Number.isInteger(end) ||
|
|
543
|
+
start < 0 || start >= end || end > decodedText.length ||
|
|
544
|
+
decodedText.slice(start, end) !== matched) {
|
|
545
|
+
continue; // synthetic or clipped finding: not attributable
|
|
546
|
+
}
|
|
547
|
+
let hot = false;
|
|
548
|
+
for (let i = start; i < end && !hot; i += 1)
|
|
549
|
+
hot = unitHot[i];
|
|
550
|
+
if (!hot)
|
|
551
|
+
continue;
|
|
552
|
+
const encoding_detected = { type: "URL", confidence: SENSITIVE_HINT.test(decodedText) ? 0.85 : 0.5 };
|
|
553
|
+
runs.push({
|
|
554
|
+
start: unitStart[start],
|
|
555
|
+
end: unitEnd[end - 1],
|
|
556
|
+
severity: finding.severity,
|
|
557
|
+
decodedMatches: [matched],
|
|
558
|
+
findings: [{ ...finding, encoding_detected }],
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
return { runs, evasion: hasUnicodeEvasion(result.findings) };
|
|
562
|
+
}
|
package/dist/scanner/engine.js
CHANGED
|
@@ -2,7 +2,7 @@ import { BUILTIN_RULES } from "../rules/builtin.js";
|
|
|
2
2
|
import { buildDynamicRules } from "../rules/dynamic.js";
|
|
3
3
|
import { allowSet, isAllowlisted, noteAllowlistSuppression } from "./allowlist.js";
|
|
4
4
|
import { containsAddressInRun, parseCidrList } from "./cidr.js";
|
|
5
|
-
import { redact,
|
|
5
|
+
import { redact, createLineIndex, lineColAt, getIgnoredLines } from "./utils.js";
|
|
6
6
|
import { t } from "../i18n/index.js";
|
|
7
7
|
import * as encoding from "./encoding.js";
|
|
8
8
|
import { foldConfusables } from "./unicode.js";
|
|
@@ -29,8 +29,8 @@ function getRules(config) {
|
|
|
29
29
|
: rule);
|
|
30
30
|
return [...configuredBuiltins, ...dynamic];
|
|
31
31
|
}
|
|
32
|
-
function
|
|
33
|
-
return findings.some((finding) => finding.match_start === index && finding.match_end === index + length);
|
|
32
|
+
function hasHighFindingAtRange(findings, index, length) {
|
|
33
|
+
return findings.some((finding) => finding.severity === "HIGH" && finding.match_start === index && finding.match_end === index + length);
|
|
34
34
|
}
|
|
35
35
|
function collapseOverlappingMatches(matches) {
|
|
36
36
|
const sorted = [...matches].sort((left, right) => left.index - right.index || right.length - left.length);
|
|
@@ -56,15 +56,17 @@ function collapseOverlappingMatches(matches) {
|
|
|
56
56
|
}))
|
|
57
57
|
.sort((left, right) => right.index - left.index);
|
|
58
58
|
}
|
|
59
|
-
function addExactValueFindings(text, config, ignoredLines, findings) {
|
|
59
|
+
function addExactValueFindings(text, lineStarts, config, ignoredLines, findings) {
|
|
60
60
|
const detector = config.exact_value_detector;
|
|
61
61
|
if (!detector)
|
|
62
62
|
return;
|
|
63
63
|
const globalAllow = allowSet(config.settings.allowlist);
|
|
64
64
|
for (const match of detector.findAll(text)) {
|
|
65
|
-
|
|
65
|
+
// A HIGH rule finding already says all ENV_SECRET would. A weaker one must
|
|
66
|
+
// not hide it, or the decision drops and --min-severity high loses the match.
|
|
67
|
+
if (hasHighFindingAtRange(findings, match.index, match.length))
|
|
66
68
|
continue;
|
|
67
|
-
const { line, col } =
|
|
69
|
+
const { line, col } = lineColAt(lineStarts, match.index);
|
|
68
70
|
if (ignoredLines.has(line))
|
|
69
71
|
continue;
|
|
70
72
|
const matchedText = text.slice(match.index, match.index + match.length);
|
|
@@ -90,10 +92,17 @@ function honorDirectives(opts) {
|
|
|
90
92
|
}
|
|
91
93
|
/** Invisible format characters that can splice a value so the rules miss it. */
|
|
92
94
|
export const ZERO_WIDTH_CHARS = /[\u200B-\u200D\uFEFF\u2060\u180E]/g;
|
|
93
|
-
|
|
95
|
+
const SEVERITY_RANK = { HIGH: 3, MEDIUM: 2, LOW: 1 };
|
|
96
|
+
/**
|
|
97
|
+
* Rule and exact-value findings for one text, in rule order. Rules of one type
|
|
98
|
+
* matching at one offset report one finding: the highest severity, over the
|
|
99
|
+
* longest span. Rule order must not decide either, or a LOW rule listed first
|
|
100
|
+
* would downgrade the decision and leave the tail of a longer match unmasked.
|
|
101
|
+
*/
|
|
94
102
|
function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
103
|
+
const lineStarts = createLineIndex(text);
|
|
95
104
|
const findings = [];
|
|
96
|
-
const
|
|
105
|
+
const findingAtOffset = new Map();
|
|
97
106
|
const globalAllow = allowSet(config.settings.allowlist);
|
|
98
107
|
for (const rule of rules) {
|
|
99
108
|
// Start from the beginning. matchAll advances after empty matches (by a
|
|
@@ -109,10 +118,8 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
|
109
118
|
const start = match.index + offset;
|
|
110
119
|
if (rule.validate !== undefined && !rule.validate(matchedText, { text, index: start }))
|
|
111
120
|
continue;
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
continue;
|
|
115
|
-
const { line, col } = getLineCol(text, start);
|
|
121
|
+
const end = match.index + match[0].length;
|
|
122
|
+
const { line, col } = lineColAt(lineStarts, start);
|
|
116
123
|
if (ignoredLines.has(line))
|
|
117
124
|
continue;
|
|
118
125
|
if (isAllowlisted(matchedText, globalAllow, rule.allow)) {
|
|
@@ -121,9 +128,22 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
|
121
128
|
// at the same offset, and suppressing the short one must not hide it.
|
|
122
129
|
continue;
|
|
123
130
|
}
|
|
124
|
-
seen.add(key);
|
|
125
131
|
const preview = redact(matchedText, config.settings.preview_length);
|
|
126
|
-
|
|
132
|
+
const key = `${rule.type}:${start}`;
|
|
133
|
+
const earlier = findingAtOffset.get(key);
|
|
134
|
+
if (earlier) {
|
|
135
|
+
if (SEVERITY_RANK[rule.severity] > SEVERITY_RANK[earlier.severity]) {
|
|
136
|
+
earlier.severity = rule.severity;
|
|
137
|
+
earlier.description = rule.description;
|
|
138
|
+
}
|
|
139
|
+
if (end > (earlier.match_end ?? 0)) {
|
|
140
|
+
earlier.preview = preview;
|
|
141
|
+
earlier.match_end = end;
|
|
142
|
+
earlier.match_text = matchedText;
|
|
143
|
+
}
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const finding = {
|
|
127
147
|
type: rule.type,
|
|
128
148
|
severity: rule.severity,
|
|
129
149
|
line: config.settings.show_line_numbers ? line : undefined,
|
|
@@ -131,12 +151,14 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
|
131
151
|
preview,
|
|
132
152
|
description: rule.description,
|
|
133
153
|
match_start: start,
|
|
134
|
-
match_end:
|
|
154
|
+
match_end: end,
|
|
135
155
|
match_text: matchedText,
|
|
136
|
-
}
|
|
156
|
+
};
|
|
157
|
+
findingAtOffset.set(key, finding);
|
|
158
|
+
findings.push(finding);
|
|
137
159
|
}
|
|
138
160
|
}
|
|
139
|
-
addExactValueFindings(text, config, ignoredLines, findings);
|
|
161
|
+
addExactValueFindings(text, lineStarts, config, ignoredLines, findings);
|
|
140
162
|
return findings;
|
|
141
163
|
}
|
|
142
164
|
/**
|
|
@@ -192,6 +214,10 @@ function homoglyphHidesFinding(text, rawFindings, rules, config, ignoredLines) {
|
|
|
192
214
|
const fold = (value) => foldConfusables(stripZeroWidth(value));
|
|
193
215
|
return transformHidesFinding(text, fold, rawFindings, rules, config, ignoredLines);
|
|
194
216
|
}
|
|
217
|
+
/** Appends the ` [WARNING: a, b]` suffix to a summary; no suffix when there is none. */
|
|
218
|
+
export function appendWarnings(summary, warnings) {
|
|
219
|
+
return warnings !== undefined && warnings.length > 0 ? `${summary} [WARNING: ${warnings.join(", ")}]` : summary;
|
|
220
|
+
}
|
|
195
221
|
/**
|
|
196
222
|
* Internal scan function without encoding detection.
|
|
197
223
|
* Used by scanTextWithDecoding to avoid infinite recursion.
|
|
@@ -248,36 +274,37 @@ function scanTextInternal(text, config, opts) {
|
|
|
248
274
|
// Add warnings for Unicode issues and truncation
|
|
249
275
|
const warnings = [];
|
|
250
276
|
if (zeroWidthEvasion)
|
|
251
|
-
warnings.push("
|
|
277
|
+
warnings.push(t("scan.warning_zero_width"));
|
|
252
278
|
if (homoglyphEvasion)
|
|
253
|
-
warnings.push("
|
|
279
|
+
warnings.push(t("scan.warning_suspicious_unicode"));
|
|
254
280
|
if (wasTruncated)
|
|
255
|
-
warnings.push("
|
|
256
|
-
const finalSummary = warnings.length > 0
|
|
257
|
-
? summary + ` [WARNING: ${warnings.join(', ')}]`
|
|
258
|
-
: summary;
|
|
281
|
+
warnings.push(t("scan.warning_truncated"));
|
|
259
282
|
return {
|
|
260
283
|
safe,
|
|
261
284
|
total_findings: findings.length,
|
|
262
285
|
findings,
|
|
263
|
-
summary:
|
|
286
|
+
summary: appendWarnings(summary, warnings),
|
|
264
287
|
recommendation,
|
|
265
288
|
was_truncated: wasTruncated || undefined,
|
|
289
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
266
290
|
};
|
|
267
291
|
}
|
|
268
292
|
export function scanText(text, config, opts) {
|
|
269
293
|
// If encoding detection is enabled, use the enhanced scanner
|
|
270
294
|
if (config.settings.encoding_detection) {
|
|
271
295
|
const result = encoding.scanTextWithDecoding(text, config, opts);
|
|
272
|
-
//
|
|
273
|
-
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
const
|
|
296
|
+
// Decoded findings carry offsets of the decoded string; anchor them to
|
|
297
|
+
// spans of `text` so redaction and previews apply to the right bytes.
|
|
298
|
+
const findings = encoding.anchorDecodedFindings(text, result, config, opts);
|
|
299
|
+
// Generate proper summary based on the anchored results
|
|
300
|
+
const safe = findings.length === 0;
|
|
301
|
+
const highCount = findings.filter((f) => f.severity === "HIGH").length;
|
|
302
|
+
const medCount = findings.filter((f) => f.severity === "MEDIUM").length;
|
|
303
|
+
const lowCount = findings.length - highCount - medCount;
|
|
277
304
|
const summary = safe
|
|
278
305
|
? t("scan.safe_summary")
|
|
279
306
|
: t("scan.unsafe_summary", {
|
|
280
|
-
count:
|
|
307
|
+
count: findings.length,
|
|
281
308
|
high: highCount,
|
|
282
309
|
med: medCount,
|
|
283
310
|
low: lowCount,
|
|
@@ -288,21 +315,19 @@ export function scanText(text, config, opts) {
|
|
|
288
315
|
// Add warnings for encoding detection and truncation
|
|
289
316
|
const warnings = [];
|
|
290
317
|
if (result.was_decoded) {
|
|
291
|
-
warnings.push(
|
|
318
|
+
warnings.push(t("scan.warning_encoded", { types: result.encoding_types_found.join(", ") }));
|
|
292
319
|
}
|
|
293
320
|
if (result.original.was_truncated) {
|
|
294
|
-
warnings.push("
|
|
321
|
+
warnings.push(t("scan.warning_truncated"));
|
|
295
322
|
}
|
|
296
|
-
const finalSummary = warnings.length > 0
|
|
297
|
-
? summary + ` [WARNING: ${warnings.join(', ')}]`
|
|
298
|
-
: summary;
|
|
299
323
|
return {
|
|
300
324
|
safe,
|
|
301
|
-
total_findings:
|
|
302
|
-
findings
|
|
303
|
-
summary:
|
|
325
|
+
total_findings: findings.length,
|
|
326
|
+
findings,
|
|
327
|
+
summary: appendWarnings(summary, warnings),
|
|
304
328
|
recommendation,
|
|
305
329
|
was_truncated: result.original.was_truncated,
|
|
330
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
306
331
|
};
|
|
307
332
|
}
|
|
308
333
|
// Otherwise, use internal scan without encoding detection
|
|
@@ -326,6 +351,7 @@ protectedSpans = []) {
|
|
|
326
351
|
const truncated = text.slice(0, config.settings.max_chars);
|
|
327
352
|
const allRules = getRules(config);
|
|
328
353
|
const ignoredLines = honorDirectives(opts) ? getIgnoredLines(truncated) : new Set();
|
|
354
|
+
const truncatedLineStarts = createLineIndex(truncated);
|
|
329
355
|
const matches = [];
|
|
330
356
|
const seen = new Set();
|
|
331
357
|
const globalAllow = allowSet(config.settings.allowlist);
|
|
@@ -346,7 +372,7 @@ protectedSpans = []) {
|
|
|
346
372
|
const key = `${start}:${end - start}`;
|
|
347
373
|
if (seen.has(key))
|
|
348
374
|
continue;
|
|
349
|
-
const { line } =
|
|
375
|
+
const { line } = lineColAt(truncatedLineStarts, start);
|
|
350
376
|
if (ignoredLines.has(line))
|
|
351
377
|
continue;
|
|
352
378
|
// An allowlisted literal is left as written, exactly as the scanner leaves
|
|
@@ -362,9 +388,11 @@ protectedSpans = []) {
|
|
|
362
388
|
for (const match of detector.findAll(truncated)) {
|
|
363
389
|
if (overlapsSpan(match.index, match.index + match.length, protectedSpans))
|
|
364
390
|
continue;
|
|
391
|
+
// Only the mask is decided here, so any match on this range already covers
|
|
392
|
+
// it. Severity is reported by the scanText call below.
|
|
365
393
|
if (matches.some((entry) => entry.index === match.index && entry.length === match.length))
|
|
366
394
|
continue;
|
|
367
|
-
const { line } =
|
|
395
|
+
const { line } = lineColAt(truncatedLineStarts, match.index);
|
|
368
396
|
if (ignoredLines.has(line))
|
|
369
397
|
continue;
|
|
370
398
|
const matchedText = truncated.slice(match.index, match.index + match.length);
|
package/dist/scanner/utils.js
CHANGED
|
@@ -7,8 +7,32 @@ export function redact(_value, _previewLen) {
|
|
|
7
7
|
}
|
|
8
8
|
export function getLineCol(text, index) {
|
|
9
9
|
const before = text.slice(0, index);
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
return lineColAt(createLineIndex(before), before.length);
|
|
11
|
+
}
|
|
12
|
+
/** Start offset of every line in a text; a line break is `\r?\n`, so only `\n` ends a line. */
|
|
13
|
+
export function createLineIndex(text) {
|
|
14
|
+
const starts = [0];
|
|
15
|
+
let from = 0;
|
|
16
|
+
for (;;) {
|
|
17
|
+
const nl = text.indexOf("\n", from);
|
|
18
|
+
if (nl === -1)
|
|
19
|
+
return starts;
|
|
20
|
+
from = nl + 1;
|
|
21
|
+
starts.push(from);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Line (1-based) and column (1-based) of `index`, given the starts from createLineIndex of the same text. */
|
|
25
|
+
export function lineColAt(lineStarts, index) {
|
|
26
|
+
let lo = 0;
|
|
27
|
+
let hi = lineStarts.length - 1;
|
|
28
|
+
while (lo < hi) {
|
|
29
|
+
const mid = (lo + hi + 1) >> 1;
|
|
30
|
+
if (lineStarts[mid] <= index)
|
|
31
|
+
lo = mid;
|
|
32
|
+
else
|
|
33
|
+
hi = mid - 1;
|
|
34
|
+
}
|
|
35
|
+
return { line: lo + 1, col: index - lineStarts[lo] + 1 };
|
|
12
36
|
}
|
|
13
37
|
/**
|
|
14
38
|
* Multiple ignore patterns to prevent bypass attempts.
|
package/dist/transports/cli.js
CHANGED
|
@@ -2,7 +2,7 @@ import * as fs from "fs";
|
|
|
2
2
|
import * as path from "path";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import { loadConfig } from "../config/loader.js";
|
|
5
|
-
import { scanText, redactText } from "../scanner/engine.js";
|
|
5
|
+
import { scanText, redactText, appendWarnings } from "../scanner/engine.js";
|
|
6
6
|
import { redactAndVerify } from "../scanner/redaction-verifier.js";
|
|
7
7
|
import { sanitizeRedactResultForExport } from "../decision/redaction.js";
|
|
8
8
|
import { toDecisionResult } from "../decision/model.js";
|
|
@@ -28,7 +28,7 @@ export function filterBySeverity(result, min) {
|
|
|
28
28
|
med: medCount,
|
|
29
29
|
low: findings.length - highCount - medCount,
|
|
30
30
|
});
|
|
31
|
-
return { ...result, findings, total_findings: findings.length, safe, summary };
|
|
31
|
+
return { ...result, findings, total_findings: findings.length, safe, summary: appendWarnings(summary, result.warnings) };
|
|
32
32
|
}
|
|
33
33
|
// ─── Decision-aware CLI formatting ──────────────────────────────────────────
|
|
34
34
|
const SEPARATOR = "─".repeat(60);
|
package/dist/transports/web.js
CHANGED
|
@@ -147,7 +147,8 @@ function handleScanRequest(req, res, config) {
|
|
|
147
147
|
: undefined;
|
|
148
148
|
writeJson(res, 200, {
|
|
149
149
|
...decision,
|
|
150
|
-
|
|
150
|
+
// Replaces the decision's copy too: only text the verifier passed is returned.
|
|
151
|
+
redactedContent: redaction?.verified ? redaction.redacted : undefined,
|
|
151
152
|
redactionVerified: redaction?.verified,
|
|
152
153
|
residualFindings: redaction?.residualFindings,
|
|
153
154
|
wasTruncated: redaction?.wasTruncated ?? scan.was_truncated ?? false,
|
|
@@ -164,8 +165,7 @@ function handleScanRequest(req, res, config) {
|
|
|
164
165
|
res.destroy();
|
|
165
166
|
});
|
|
166
167
|
}
|
|
167
|
-
export function createWebServer() {
|
|
168
|
-
const config = loadConfig();
|
|
168
|
+
export function createWebServer(config = loadConfig()) {
|
|
169
169
|
return http.createServer((req, res) => {
|
|
170
170
|
if (!isAllowedHost(req.headers.host)) {
|
|
171
171
|
writeError(res, 403, "不允許的 Host");
|