leakshield 0.1.2 → 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.
@@ -7,26 +7,239 @@
7
7
  // never get here: `loadConfig()` rejects them (fail-closed).
8
8
  const REDOS_TIMEOUT_MS = 200;
9
9
  const REDOS_TEST_INPUT = "a".repeat(50) + "!";
10
+ /**
11
+ * Is this pattern's top level an alternation (`a|b`, not `(?:a|b)`)? Boundaries
12
+ * cannot be attached safely to each branch from outside, and `\bfoo|bar\b`
13
+ * would silently mean something else, so `word_boundary` refuses it.
14
+ */
15
+ function hasTopLevelAlternation(source) {
16
+ let depth = 0;
17
+ let escaped = false;
18
+ let inClass = false;
19
+ for (const ch of source) {
20
+ if (escaped) {
21
+ escaped = false;
22
+ continue;
23
+ }
24
+ if (ch === "\\") {
25
+ escaped = true;
26
+ continue;
27
+ }
28
+ if (inClass) {
29
+ if (ch === "]")
30
+ inClass = false;
31
+ continue;
32
+ }
33
+ if (ch === "[") {
34
+ inClass = true;
35
+ continue;
36
+ }
37
+ if (ch === "(") {
38
+ depth += 1;
39
+ continue;
40
+ }
41
+ if (ch === ")") {
42
+ depth = Math.max(0, depth - 1);
43
+ continue;
44
+ }
45
+ if (ch === "|" && depth === 0)
46
+ return true;
47
+ }
48
+ return false;
49
+ }
50
+ /** The ASCII-word test `keywordPattern` uses for its boundaries. */
51
+ function asciiWordChar(ch) {
52
+ return ch !== undefined && /^[A-Za-z0-9_]$/.test(ch);
53
+ }
54
+ /** Characters that hide the real edge (group, class, quantifier, escape). No
55
+ * boundary can be placed there safely, so none is added and `--doctor` says so. */
56
+ const HIDDEN_EDGE = new Set(["(", ")", "[", "]", "{", "}", ".", "*", "+", "?", "|", "\\"]);
57
+ /** End index (exclusive) of the escape sequence starting at `start`. */
58
+ function escapeEnd(source, start) {
59
+ const next = source[start + 1];
60
+ if (next === undefined)
61
+ return start + 1;
62
+ if (next === "x")
63
+ return Math.min(source.length, start + 4);
64
+ if (next === "u" || next === "p" || next === "P" || next === "k") {
65
+ if (source[start + 2] === "{" || source[start + 2] === "<") {
66
+ const close = source.indexOf(source[start + 2] === "{" ? "}" : ">", start + 3);
67
+ return close === -1 ? source.length : close + 1;
68
+ }
69
+ return next === "u" ? Math.min(source.length, start + 6) : start + 2;
70
+ }
71
+ // Control escapes: \cA is one token, and A is not a literal word character.
72
+ if (next === "c")
73
+ return Math.min(source.length, start + 3);
74
+ // Legacy octal: \0, \012 (at most two digits after the leading 0).
75
+ if (next === "0") {
76
+ let index = start + 1;
77
+ let digits = 0;
78
+ while (index < source.length && digits < 3 && /[0-7]/.test(source[index] ?? "")) {
79
+ index += 1;
80
+ digits += 1;
81
+ }
82
+ return index;
83
+ }
84
+ if (/[1-9]/.test(next)) {
85
+ let index = start + 1;
86
+ while (index < source.length && /[0-9]/.test(source[index] ?? ""))
87
+ index += 1;
88
+ return index;
89
+ }
90
+ return Math.min(source.length, start + 2);
91
+ }
92
+ /** End index (exclusive) of a character class starting at `start`. */
93
+ function classEnd(source, start) {
94
+ let index = start + 1;
95
+ if (source[index] === "^")
96
+ index += 1;
97
+ while (index < source.length) {
98
+ const ch = source[index];
99
+ if (ch === "\\") {
100
+ index = Math.max(escapeEnd(source, index), index + 1);
101
+ continue;
102
+ }
103
+ if (ch === "]")
104
+ return index + 1;
105
+ index += 1;
106
+ }
107
+ return source.length;
108
+ }
109
+ /** First token of the pattern: one escape, one class, or one character. */
110
+ function firstToken(source) {
111
+ const ch = source[0];
112
+ if (ch === undefined)
113
+ return "";
114
+ if (ch === "\\")
115
+ return source.slice(0, escapeEnd(source, 0));
116
+ if (ch === "[")
117
+ return source.slice(0, classEnd(source, 0));
118
+ return ch;
119
+ }
120
+ /** Last token of the pattern, walking past escapes and classes. */
121
+ function lastToken(source) {
122
+ let index = 0;
123
+ let start = 0;
124
+ while (index < source.length) {
125
+ start = index;
126
+ const ch = source[index];
127
+ if (ch === "\\") {
128
+ index = Math.max(escapeEnd(source, index), index + 1);
129
+ continue;
130
+ }
131
+ if (ch === "[") {
132
+ index = Math.max(classEnd(source, index), index + 1);
133
+ continue;
134
+ }
135
+ index += 1;
136
+ }
137
+ return source.slice(start);
138
+ }
139
+ /**
140
+ * What a boundary can do at this edge. Only a literal ASCII word character can
141
+ * take a `\b`. An escape is never assumed to end in a word character: `\D`,
142
+ * `\x21` or `\u5bc6` all end in something else, and appending `\b` would drop
143
+ * real matches (including the CJK case the acceptance criteria call out).
144
+ */
145
+ function classifyEdge(token) {
146
+ if (token === "")
147
+ return "none";
148
+ if (token === "\\b" || token === "^" || token === "$")
149
+ return "satisfied";
150
+ if (token.startsWith("\\") || token.startsWith("["))
151
+ return "hidden";
152
+ if (token.length === 1) {
153
+ if (asciiWordChar(token))
154
+ return "word";
155
+ if (HIDDEN_EDGE.has(token))
156
+ return "hidden";
157
+ return "none";
158
+ }
159
+ return "hidden";
160
+ }
161
+ const EDGE_CLASS = {
162
+ word: "added",
163
+ satisfied: "none",
164
+ hidden: "hidden",
165
+ none: "none",
166
+ };
167
+ /**
168
+ * Which edges of a rule can actually take a boundary. `word_boundary` can only
169
+ * add `\b` where the edge is a literal ASCII word character; an edge that is a
170
+ * group, class, quantifier or escape is reported as hidden rather than guessed
171
+ * at, and `--doctor` warns so the rule does not look stricter than it is.
172
+ */
173
+ export function customRuleBoundaries(rule) {
174
+ if (rule.word_boundary !== true)
175
+ return { lead: "none", trail: "none" };
176
+ return {
177
+ lead: EDGE_CLASS[classifyEdge(firstToken(rule.pattern))],
178
+ trail: EDGE_CLASS[classifyEdge(lastToken(rule.pattern))],
179
+ };
180
+ }
181
+ /**
182
+ * Pattern source with `word_boundary` applied. A `\b` is added only where the
183
+ * edge is a literal ASCII word character; an already-written `\b`/`^`/`$` is
184
+ * respected. A top-level alternation is refused because `\bfoo|bar\b` would
185
+ * silently mean `(\bfoo)|(bar\b)`; group it as `(?:foo|bar)`.
186
+ */
187
+ export function customRuleSource(rule) {
188
+ if (rule.word_boundary !== true)
189
+ return rule.pattern;
190
+ if (hasTopLevelAlternation(rule.pattern)) {
191
+ // Static example on purpose: a config error must not repeat the pattern,
192
+ // which may itself be the literal the rule exists to protect.
193
+ throw new Error(`custom rule "${rule.description}": word_boundary cannot be applied to a top-level alternation; group it as (?:foo|bar)`);
194
+ }
195
+ // One boundary decision for both enforcement and what `--doctor` reports.
196
+ const edges = customRuleBoundaries(rule);
197
+ const lead = edges.lead === "added" ? "\\b" : "";
198
+ const trail = edges.trail === "added" ? "\\b" : "";
199
+ return lead + rule.pattern + trail;
200
+ }
201
+ /** Final flags: `g` is always present; `i` stays the default so existing rules
202
+ * keep matching as they did before `flags` existed. */
203
+ export function customRuleFlags(rule) {
204
+ const requested = rule.flags ?? "i";
205
+ return Array.from(new Set(`g${requested}`)).join("");
206
+ }
207
+ /** The exact RegExp the scanner uses for a custom rule. */
208
+ export function customRulePattern(rule) {
209
+ return new RegExp(customRuleSource(rule), customRuleFlags(rule));
210
+ }
10
211
  // The timing check can land on either side of the limit from one run to the
11
212
  // next, so the first verdict for a pattern is kept for the life of the
12
213
  // process: `--doctor` and the scanner it smoke-tests then agree on which
13
214
  // rules are enforced. Bounded so a long-lived process cannot grow it forever.
14
215
  const MAX_REMEMBERED_VERDICTS = 1024;
15
216
  const verdicts = new Map();
16
- export function checkCustomPattern(pattern) {
17
- const remembered = verdicts.get(pattern);
217
+ export function checkCustomPattern(pattern, flags = "gi") {
218
+ const key = `${flags}\u0000${pattern}`;
219
+ const remembered = verdicts.get(key);
18
220
  if (remembered !== undefined)
19
221
  return remembered;
20
- const verdict = probeCustomPattern(pattern);
222
+ const verdict = probeCustomPattern(pattern, flags);
21
223
  if (verdicts.size >= MAX_REMEMBERED_VERDICTS)
22
224
  verdicts.clear();
23
- verdicts.set(pattern, verdict);
225
+ verdicts.set(key, verdict);
24
226
  return verdict;
25
227
  }
26
- function probeCustomPattern(pattern) {
228
+ /** Probe the rule's final pattern (flags and boundaries included). */
229
+ export function checkCustomRule(rule) {
230
+ let compiled;
231
+ try {
232
+ compiled = customRulePattern(rule);
233
+ }
234
+ catch {
235
+ return "invalid";
236
+ }
237
+ return checkCustomPattern(compiled.source, compiled.flags);
238
+ }
239
+ function probeCustomPattern(pattern, flags) {
27
240
  let compiled;
28
241
  try {
29
- compiled = new RegExp(pattern, "gi");
242
+ compiled = new RegExp(pattern, flags);
30
243
  }
31
244
  catch {
32
245
  return "invalid";
@@ -44,7 +257,7 @@ function probeCustomPattern(pattern) {
44
257
  export function skippedCustomRules(config) {
45
258
  const skipped = [];
46
259
  for (const rule of config.custom_rules ?? []) {
47
- const verdict = checkCustomPattern(rule.pattern);
260
+ const verdict = checkCustomRule(rule);
48
261
  if (verdict !== "ok")
49
262
  skipped.push({ description: rule.description, reason: verdict });
50
263
  }
@@ -81,18 +294,20 @@ export function buildDynamicRules(config) {
81
294
  });
82
295
  }
83
296
  for (const rule of config.custom_rules) {
84
- const verdict = checkCustomPattern(rule.pattern);
297
+ const verdict = checkCustomRule(rule);
85
298
  if (verdict !== "ok") {
86
299
  console.warn(verdict === "invalid"
87
300
  ? `[leakshield] custom_rules: 略過無法編譯的 pattern —「${rule.description}」`
88
301
  : `[leakshield] custom_rules: 略過疑似 ReDoS 的 pattern(計時啟發式檢查,非保證)—「${rule.description}」`);
89
302
  continue;
90
303
  }
304
+ const allow = (rule.allow ?? []).filter((value) => value.length > 0);
91
305
  rules.push({
92
306
  type: "CUSTOM",
93
307
  severity: rule.severity,
94
308
  description: rule.description,
95
- pattern: new RegExp(rule.pattern, "gi"),
309
+ pattern: customRulePattern(rule),
310
+ ...(allow.length > 0 ? { allow: new Set(allow) } : {}),
96
311
  });
97
312
  }
98
313
  return rules;
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Exact-match allowlists (issue #32).
3
+ *
4
+ * An allowlist entry suppresses a finding only when the matched text is exactly
5
+ * that string. It is not a pattern, it is not a substring test, and it does not
6
+ * rewrite anything: the content still leaves the machine as-is. That makes it a
7
+ * real bypass, which is why every suppression is counted here and surfaced by
8
+ * `--doctor`, and why the entry lists are capped at config load.
9
+ *
10
+ * The counter is process-wide and monotonic. It is diagnostic evidence ("how
11
+ * often did the allowlist actually fire?"), not a metric to optimize.
12
+ */
13
+ /** Values that never produce a finding, for one rule or for every rule. */
14
+ export function allowSet(values) {
15
+ return new Set((values ?? []).filter((value) => value.length > 0));
16
+ }
17
+ /** True when `matchedText` is exactly an allowlisted value. */
18
+ export function isAllowlisted(matchedText, globalAllow, ruleAllow) {
19
+ if (globalAllow.size === 0 && (ruleAllow === undefined || ruleAllow.size === 0))
20
+ return false;
21
+ return globalAllow.has(matchedText) || ruleAllow?.has(matchedText) === true;
22
+ }
23
+ let suppressions = 0;
24
+ const MAX_COUNT = Number.MAX_SAFE_INTEGER;
25
+ /** Record one suppressed finding. Bounded so a long-lived process cannot wrap. */
26
+ export function noteAllowlistSuppression() {
27
+ if (suppressions < MAX_COUNT)
28
+ suppressions += 1;
29
+ }
30
+ /** Findings suppressed by an allowlist since this module was loaded. */
31
+ export function allowlistSuppressions() {
32
+ return suppressions;
33
+ }
34
+ /** Test seam only: reset the counter between cases. */
35
+ export function resetAllowlistSuppressionsForTests() {
36
+ suppressions = 0;
37
+ }
@@ -3,6 +3,10 @@
3
3
  * Prevents attackers from bypassing detection using Base64, URL encoding, etc.
4
4
  */
5
5
  import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
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;
6
10
  // ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
7
11
  /**
8
12
  * Detects potential Base64 encoded strings.
@@ -12,7 +16,7 @@ import { ZERO_WIDTH_CHARS, scanTextInternal } from "./engine.js";
12
16
  * - Proper padding (0-2 '=' chars at end)
13
17
  * - Even length when padded
14
18
  */
15
- function detectBase64(text) {
19
+ function detectBase64Matches(text) {
16
20
  const candidates = [];
17
21
  // Pattern for Base64 strings (16+ chars, lowered threshold for security)
18
22
  const base64Pattern = /[A-Za-z0-9+/]{16,}={0,2}/g;
@@ -33,10 +37,13 @@ function detectBase64(text) {
33
37
  // Low entropy suggests it's not Base64 (e.g., "AAAAAAAAAA...")
34
38
  if (entropy < 0.3)
35
39
  continue;
36
- candidates.push(candidate);
40
+ candidates.push({ text: candidate, index: match.index });
37
41
  }
38
42
  return candidates;
39
43
  }
44
+ function detectBase64(text) {
45
+ return detectBase64Matches(text).map((c) => c.text);
46
+ }
40
47
  /**
41
48
  * Attempts to decode a Base64 string and validate the result.
42
49
  * Returns null if decoding fails or result doesn't look like text.
@@ -53,7 +60,7 @@ function tryDecodeBase64(encoded) {
53
60
  if (!/[a-zA-Z]{2,}/.test(decoded))
54
61
  return null;
55
62
  // Check for common sensitive patterns in decoded text
56
- const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
63
+ const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
57
64
  return {
58
65
  decoded,
59
66
  encoding_type: 'Base64',
@@ -92,7 +99,7 @@ function tryDecodeUrl(encoded) {
92
99
  const decoded = decodeURIComponent(encoded.replace(/\+/g, ' '));
93
100
  if (decoded === encoded)
94
101
  return null; // Nothing was decoded
95
- const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
102
+ const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
96
103
  return {
97
104
  decoded,
98
105
  encoding_type: 'URL',
@@ -107,16 +114,19 @@ function tryDecodeUrl(encoded) {
107
114
  /**
108
115
  * Detects potential hex-encoded strings.
109
116
  */
110
- function detectHexEncoding(text) {
117
+ function detectHexMatches(text) {
111
118
  const candidates = [];
112
119
  // Look for sequences of hex pairs
113
120
  const hexPattern = /(?:\\x[0-9a-fA-F]{2}|[0-9a-fA-F]{32,})/g;
114
121
  const matches = text.matchAll(hexPattern);
115
122
  for (const match of matches) {
116
- candidates.push(match[0]);
123
+ candidates.push({ text: match[0], index: match.index });
117
124
  }
118
125
  return candidates;
119
126
  }
127
+ function detectHexEncoding(text) {
128
+ return detectHexMatches(text).map((c) => c.text);
129
+ }
120
130
  /**
121
131
  * Attempts to decode hex-encoded text.
122
132
  */
@@ -135,7 +145,7 @@ function tryDecodeHex(encoded) {
135
145
  }
136
146
  if (decoded.length < 10)
137
147
  return null;
138
- const hasSensitivePattern = /(?:api|key|secret|token|password|sk-|ghp_|gho_)/i.test(decoded);
148
+ const hasSensitivePattern = SENSITIVE_HINT.test(decoded);
139
149
  return {
140
150
  decoded,
141
151
  encoding_type: 'Hex',
@@ -160,7 +170,10 @@ export function scanTextWithDecoding(text, config, opts) {
160
170
  // (a ZWSP in Base64 or hex), so decode the stripped form as well. Each
161
171
  // candidate is decoded once even when both forms contain it.
162
172
  const stripped = text.replace(ZERO_WIDTH_CHARS, "");
163
- const sources = stripped === text ? [text] : [text, stripped];
173
+ // A Cyrillic/Greek look-alike swapped into an encoded run hides it the same
174
+ // way, so decode the folded form too (#46). Decoding never recurses.
175
+ const folded = foldConfusables(stripped);
176
+ const sources = [...new Set([text, stripped, folded])];
164
177
  const decodedCandidates = new Set();
165
178
  const firstSighting = (kind, candidate) => {
166
179
  const id = `${kind}\0${candidate}`;
@@ -272,3 +285,278 @@ function mergeScanResults(results, config, encodingTypesFound) {
272
285
  findings: deduplicated,
273
286
  };
274
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
+ }