leakshield 0.1.2 → 0.1.3

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 CHANGED
@@ -468,6 +468,58 @@ After editing:
468
468
  - **OpenCode Plugin**: Restart OpenCode to reload the plugin configuration
469
469
  - **Web UI**: Restart the local server
470
470
 
471
+ ### Custom Rules
472
+
473
+ ```yaml
474
+ custom_rules:
475
+ - description: "Company token"
476
+ pattern: "MYCO_[A-Z0-9]{32}"
477
+ severity: HIGH
478
+ flags: "i" # subset of gimsuy; g is always implied
479
+ word_boundary: true # \b only at literal ASCII word edges
480
+ allow: # exact strings this rule never reports
481
+ - "MYCO_EXAMPLE0000000000000000000000000"
482
+ # path: ["src/**"] # accepted, but NOT implemented (see below)
483
+
484
+ settings:
485
+ allowlist: # exact strings no rule reports (see the bypass warning)
486
+ - "qa@example.com"
487
+ ```
488
+
489
+ - **`flags`** — any subset of `gimsuy`; `g` is always added. The default is `i`, so
490
+ existing rules keep matching case-insensitively. An unknown flag (such as `x`)
491
+ fails the config load, and the pattern is compiled with the final flags, so a
492
+ pattern that is only invalid under `u` also fails the load.
493
+ Zero-length matches are skipped (they contain no value to report or redact);
494
+ scanning continues to later nonempty matches, including under Unicode flags.
495
+ - **`word_boundary`** — adds `\b` where the pattern's edge is a literal ASCII word
496
+ character. A CJK edge (「機密」) is left alone: `\b` never holds between two
497
+ non-word characters, and wrapping it would stop the rule matching. An edge that
498
+ is a group, character class, quantifier or escape cannot take a boundary safely,
499
+ so none is added and `--doctor` warns that the rule is looser than it looks —
500
+ write `\b` in the pattern yourself, e.g. `\bEMP-\d{6}\b`. A top-level alternation
501
+ (`a|b`) is a config error; group it as `(?:a|b)`.
502
+ - **`allow` / `settings.allowlist`** — exact matches against the matched text, not
503
+ substrings and not regexes. `allow` applies to that rule; `settings.allowlist`
504
+ applies to every rule, including the built-in ones and exact `.env` values.
505
+ Caps: 32 entries per rule, 64 globally, 200 characters each.
506
+ **Allowlisting a live secret is a real bypass**: the value still leaves the
507
+ machine unmasked, and LeakShield will not report that value as a rule or
508
+ `.env` finding. Use it only for values you have decided are not sensitive.
509
+ Unicode evasion diagnostics are separate: a zero-width or look-alike-letter
510
+ warning means removing those characters exposes a finding the raw text hides,
511
+ and an allowlist on the raw text does not silence it. Cyrillic or Greek text
512
+ on its own is not flagged. `--doctor` reports how many entries exist, exercises up to eight
513
+ of them, and reports how many it could not exercise (a context-dependent
514
+ pattern can only be judged in place). Suppressions are counted rather than
515
+ silent.
516
+ - **`path`** — accepted and validated, but path scoping is **not implemented**: the
517
+ scanner has no source path for prompts or tool output. These rules currently
518
+ apply to every scanned text, and `--doctor` warns when `path` is set.
519
+
520
+ Allowlist entries are part of the config file, so they change its fingerprint
521
+ (sha256 of the file), which is what authorizations compare against.
522
+
471
523
  ---
472
524
 
473
525
  ## Practical Examples
@@ -7,14 +7,31 @@ import { z } from "zod";
7
7
  import { loadExactValueDetector } from "../scanner/exact-values.js";
8
8
  import { parseCidr } from "../scanner/cidr.js";
9
9
  import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
10
+ import { customRulePattern } from "../rules/dynamic.js";
10
11
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
11
12
  const MAX_DYNAMIC_RULE_LENGTH = 200;
12
13
  const MAX_PRIVATE_DOMAIN_LENGTH = 255;
13
14
  const MAX_ENV_FILE_PATH_LENGTH = 4096;
15
+ const MAX_ALLOW_ENTRY_LENGTH = 200;
16
+ const MAX_RULE_ALLOW_ENTRIES = 32;
17
+ const MAX_GLOBAL_ALLOW_ENTRIES = 64;
18
+ const MAX_RULE_PATH_ENTRIES = 16;
19
+ const MAX_RULE_PATH_LENGTH = 512;
20
+ // `g` is always added by the scanner; the rest is the documented subset.
21
+ const CUSTOM_FLAG_CHARS = /^[gimsuy]*$/;
22
+ const AllowEntry = z.string().min(1).max(MAX_ALLOW_ENTRY_LENGTH);
14
23
  const CustomRuleSchema = z.object({
15
24
  description: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
16
25
  pattern: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
17
26
  severity: z.enum(["HIGH", "MEDIUM", "LOW"]).default("HIGH"),
27
+ flags: z
28
+ .string()
29
+ .max(6)
30
+ .regex(CUSTOM_FLAG_CHARS, "flags must be a subset of gimsuy; g is always implied")
31
+ .optional(),
32
+ word_boundary: z.boolean().optional(),
33
+ allow: z.array(AllowEntry).max(MAX_RULE_ALLOW_ENTRIES).optional(),
34
+ path: z.array(z.string().min(1).max(MAX_RULE_PATH_LENGTH)).max(MAX_RULE_PATH_ENTRIES).optional(),
18
35
  });
19
36
  export const GuardConfigSchema = z.object({
20
37
  nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
@@ -28,6 +45,7 @@ export const GuardConfigSchema = z.object({
28
45
  env_files: z.array(z.string().min(1).max(MAX_ENV_FILE_PATH_LENGTH)).max(16).default([]),
29
46
  rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
30
47
  private_cidrs: z.array(z.string().min(1).max(64)).max(64).default([]),
48
+ allowlist: z.array(AllowEntry).max(MAX_GLOBAL_ALLOW_ENTRIES).default([]),
31
49
  }).default({}),
32
50
  }).superRefine((config, ctx) => {
33
51
  // Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
@@ -53,17 +71,19 @@ export const GuardConfigSchema = z.object({
53
71
  });
54
72
  }
55
73
  });
56
- // A custom rule whose pattern does not compile fails the parse too: the
57
- // scanner would otherwise drop it and report clean text as safe.
74
+ // A custom rule whose final pattern (flags and word boundaries included) does
75
+ // not compile fails the parse too: the scanner would otherwise drop it and
76
+ // report clean text as safe.
58
77
  config.custom_rules.forEach((rule, index) => {
59
78
  try {
60
- new RegExp(rule.pattern, "gi");
79
+ customRulePattern(rule);
61
80
  }
62
81
  catch (error) {
63
82
  // V8 messages embed the pattern ("Invalid regular expression: /…/gi:
64
83
  // reason"); keep only the reason, since a pattern may itself be a
65
84
  // literal the rule exists to protect.
66
- const reason = error.message.split(": ").pop();
85
+ const message = error.message;
86
+ const reason = message.includes(": ") ? message.split(": ").pop() : message;
67
87
  ctx.addIssue({
68
88
  code: z.ZodIssueCode.custom,
69
89
  path: ["custom_rules", index, "pattern"],
@@ -474,6 +474,57 @@ function validateFindingSpans(text, findings) {
474
474
  }
475
475
  return { ok: true, spans: deduped };
476
476
  }
477
+ /**
478
+ * Other occurrences of detected values that the rules did not report (#52).
479
+ * Most rules depend on context — `\b` boundaries, validators that look at
480
+ * neighbours — so the same characters can be a finding in one place and not
481
+ * in another (`1318289051000.1` vs `1318289051000n`). The absence check below
482
+ * would then refuse the whole string. Masking those occurrences with the same
483
+ * token masks strictly more, so they are added here instead. An occurrence
484
+ * that overlaps a finding, a validated token or a preserved marker is left
485
+ * alone and still fails the absence check.
486
+ */
487
+ function repeatOccurrences(text, sources, blocked) {
488
+ // One flag per UTF-16 unit: overlap checks cost the span's length, not the
489
+ // number of spans already taken. Searching each distinct value once costs
490
+ // the same as the absence check that follows.
491
+ const taken = new Uint8Array(text.length);
492
+ const mark = (span) => {
493
+ taken.fill(1, span.start, span.end);
494
+ };
495
+ const free = (span) => {
496
+ for (let i = span.start; i < span.end; i++)
497
+ if (taken[i] === 1)
498
+ return false;
499
+ return true;
500
+ };
501
+ for (const span of blocked)
502
+ mark(span);
503
+ const repeats = [];
504
+ const seen = new Set();
505
+ // Longest value first, so a shorter value never splits a longer repeat.
506
+ const ordered = [...sources].sort((a, b) => b.value.length - a.value.length);
507
+ for (const source of ordered) {
508
+ if (source.value.length === 0 || seen.has(source.value))
509
+ continue;
510
+ seen.add(source.value);
511
+ let from = 0;
512
+ for (;;) {
513
+ const at = text.indexOf(source.value, from);
514
+ if (at === -1)
515
+ break;
516
+ const span = { start: at, end: at + source.value.length };
517
+ if (!free(span)) {
518
+ from = at + 1;
519
+ continue;
520
+ }
521
+ repeats.push({ ...span, value: source.value, type: source.type, severity: source.severity });
522
+ mark(span);
523
+ from = span.end;
524
+ }
525
+ }
526
+ return repeats;
527
+ }
477
528
  /** Every occurrence of `original` must sit inside a validated token span. */
478
529
  function absenceHolds(text, original, tokenSpans) {
479
530
  let from = 0;
@@ -591,6 +642,23 @@ function protectStringTx(tx, config, limits, text, chargedUnits, preserveUnknown
591
642
  return fail("token_overlap");
592
643
  }
593
644
  }
645
+ for (const span of [...actionable, ...candidates]) {
646
+ if (!tx.detectedValues.has(span.value)) {
647
+ tx.detectedValues.set(span.value, { type: span.type, severity: span.severity });
648
+ }
649
+ }
650
+ const known = [];
651
+ for (const [value, category] of tx.detectedValues)
652
+ known.push({ start: 0, end: 0, value, ...category });
653
+ const repeats = repeatOccurrences(text, known, [
654
+ ...actionable,
655
+ ...owned.spans,
656
+ ...owned.preserved,
657
+ ]);
658
+ if (repeats.length > 0) {
659
+ actionable.push(...repeats);
660
+ actionable.sort((a, b) => a.start - b.start);
661
+ }
594
662
  for (const finding of candidates)
595
663
  tx.detectedOriginals.add(finding.value);
596
664
  for (const span of actionable)
@@ -953,6 +1021,7 @@ function buildService(config, limits) {
953
1021
  staged: undefined,
954
1022
  baseline: { entries: 0, units: 0 },
955
1023
  detectedOriginals: new Set(),
1024
+ detectedValues: new Map(),
956
1025
  outputStrings: [],
957
1026
  });
958
1027
  const isTextSafe = (text) => {
@@ -1036,28 +1105,46 @@ function buildService(config, limits) {
1036
1105
  if (!isValidSessionId(sessionId))
1037
1106
  return fail("invalid_session");
1038
1107
  try {
1039
- const tx = newTransaction(sessionId);
1040
- const budget = { nodes: 0, units: 0 };
1041
- const result = walkStrictJson(value, 0, new Set(), budget, limits, (text) => {
1042
- const protectedString = protectStringTx(tx, config, limits, text, budget.units, preserveUnknownMarkers);
1043
- if (protectedString.ok)
1044
- tx.outputStrings.push(protectedString.text);
1045
- return protectedString;
1046
- });
1047
- if (!result.ok)
1048
- return result;
1049
- for (const outputString of tx.outputStrings) {
1050
- const tokenSpans = scanOwnedTokenSpans(outputString, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
1051
- if (!tokenSpans.ok)
1052
- return tokenSpans;
1053
- for (const original of tx.detectedOriginals) {
1054
- if (!absenceHolds(outputString, original, tokenSpans.spans)) {
1055
- return fail("residual_sensitive_content");
1108
+ // One pass masks a repeat only in strings walked after the value was
1109
+ // detected. If an earlier string still holds one, the cross-string check
1110
+ // refuses; a single retry seeded with every value the first pass found
1111
+ // covers it (#52). Nothing is committed until a pass verifies.
1112
+ let seed;
1113
+ for (let attempt = 0; attempt < 2; attempt++) {
1114
+ const tx = newTransaction(sessionId);
1115
+ if (seed !== undefined)
1116
+ tx.detectedValues = new Map(seed);
1117
+ const budget = { nodes: 0, units: 0 };
1118
+ const result = walkStrictJson(value, 0, new Set(), budget, limits, (text) => {
1119
+ const protectedString = protectStringTx(tx, config, limits, text, budget.units, preserveUnknownMarkers);
1120
+ if (protectedString.ok)
1121
+ tx.outputStrings.push(protectedString.text);
1122
+ return protectedString;
1123
+ });
1124
+ if (!result.ok)
1125
+ return result;
1126
+ let residual = false;
1127
+ for (const outputString of tx.outputStrings) {
1128
+ const tokenSpans = scanOwnedTokenSpans(outputString, (token) => tx.live?.reverse.get(token) !== undefined || tx.staged?.reverse.get(token) !== undefined, preserveUnknownMarkers);
1129
+ if (!tokenSpans.ok)
1130
+ return tokenSpans;
1131
+ for (const original of tx.detectedOriginals) {
1132
+ if (!absenceHolds(outputString, original, tokenSpans.spans)) {
1133
+ residual = true;
1134
+ break;
1135
+ }
1056
1136
  }
1137
+ if (residual)
1138
+ break;
1057
1139
  }
1140
+ if (residual) {
1141
+ seed = tx.detectedValues;
1142
+ continue;
1143
+ }
1144
+ commitTransaction(tx);
1145
+ return result;
1058
1146
  }
1059
- commitTransaction(tx);
1060
- return result;
1147
+ return fail("residual_sensitive_content");
1061
1148
  }
1062
1149
  catch {
1063
1150
  return fail("internal_failure");
package/dist/doctor.js CHANGED
@@ -25,9 +25,28 @@ import { loadConfig } from "./config/loader.js";
25
25
  import { defaultKeyfilePath, defaultStorePath } from "./decision/mapping-key.js";
26
26
  import { InMemoryMappingKeyProvider, openMappingStore } from "./decision/mapping-store.js";
27
27
  import { validatePluginOptions } from "./plugin-options.js";
28
- import { skippedCustomRules } from "./rules/dynamic.js";
28
+ import { BUILTIN_RULE_IDS } from "./rules/builtin.js";
29
+ import { skippedCustomRules, customRuleBoundaries } from "./rules/dynamic.js";
30
+ import { allowlistSuppressions } from "./scanner/allowlist.js";
29
31
  import { scanText } from "./scanner/engine.js";
30
32
  const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
33
+ /**
34
+ * Severity-agnostic probe for the allowlist diagnostics: every finding, plus
35
+ * the ones whose matched text is exactly the input. Findings carrying
36
+ * `unicode_detected` are tagged because an allowlist cannot suppress them.
37
+ */
38
+ function defaultProbeScan(text, config) {
39
+ const result = scanText(text, config);
40
+ return {
41
+ findings: result.findings.length,
42
+ exact: result.findings
43
+ .filter((finding) => finding.match_text === text)
44
+ .map((finding) => ({
45
+ description: finding.description ?? null,
46
+ unicodeWarning: finding.unicode_detected !== undefined,
47
+ })),
48
+ };
49
+ }
31
50
  export function createDoctorDeps() {
32
51
  return {
33
52
  opencodeVersion() {
@@ -72,6 +91,9 @@ export function createDoctorDeps() {
72
91
  const result = scanText(text, config);
73
92
  return { findings: result.findings.filter((f) => f.severity === "HIGH").length };
74
93
  },
94
+ probeScan(text, config) {
95
+ return defaultProbeScan(text, config);
96
+ },
75
97
  cwd: process.cwd(),
76
98
  home: os.homedir(),
77
99
  xdgConfigHome: process.env.XDG_CONFIG_HOME,
@@ -381,6 +403,130 @@ export async function runDoctor(deps) {
381
403
  fix: "Rewrite the pattern without nested or overlapping quantifiers, such as (a+)+ or (a|a)*.",
382
404
  });
383
405
  }
406
+ // Allowlists (issue #32) are an exact-match bypass, so they are surfaced
407
+ // rather than silent: which entries exist, whether each still suppresses the
408
+ // literal it names, and how many suppressions this process counted.
409
+ const globalAllow = guardConfig.settings?.allowlist ?? [];
410
+ const customRules = guardConfig.custom_rules ?? [];
411
+ const ruleAllow = customRules.flatMap((rule) => rule.allow ?? []);
412
+ const entries = [];
413
+ const seenEntry = new Set();
414
+ for (const value of globalAllow) {
415
+ const key = `global\u0000${value}`;
416
+ if (seenEntry.has(key))
417
+ continue;
418
+ seenEntry.add(key);
419
+ entries.push({ value, ruleIndex: -1 });
420
+ }
421
+ customRules.forEach((rule, ruleIndex) => {
422
+ for (const value of rule.allow ?? []) {
423
+ const key = `rule${ruleIndex}\u0000${value}`;
424
+ if (seenEntry.has(key))
425
+ continue;
426
+ seenEntry.add(key);
427
+ entries.push({ value, ruleIndex });
428
+ }
429
+ });
430
+ if (entries.length > 0) {
431
+ const scan = deps.probeScan ?? defaultProbeScan;
432
+ // An allowlist only suppresses a rule's own finding or an exact env value.
433
+ // A Unicode evasion warning (zero-width or look-alike letters) is not a rule match,
434
+ // so it must neither count as suppression nor as a broken filter.
435
+ const suppressible = (exact, ruleDescription) => exact.filter((finding) => !finding.unicodeWarning && (ruleDescription === undefined || finding.description === ruleDescription));
436
+ const withoutAllowlists = (config) => ({
437
+ ...config,
438
+ settings: { ...(config.settings ?? {}), allowlist: [] },
439
+ custom_rules: (config.custom_rules ?? []).map((rule) => ({ ...rule, allow: undefined })),
440
+ });
441
+ const sample = entries.slice(0, 8);
442
+ let broken = 0;
443
+ let exercised = 0;
444
+ let unverified = 0;
445
+ // A per-rule entry must be judged against that rule alone: leaving built-in
446
+ // detectors in place would report a correct suppression as BROKEN when the
447
+ // same literal is also an email, a keyword or an env value.
448
+ const isolateRule = (ruleIndex) => ({
449
+ nda_keywords: [],
450
+ private_domains: [],
451
+ custom_rules: [customRules[ruleIndex]],
452
+ exact_value_detector: undefined,
453
+ settings: {
454
+ ...(guardConfig.settings ?? {}),
455
+ allowlist: [],
456
+ env_files: [],
457
+ encoding_detection: false,
458
+ private_cidrs: [],
459
+ rule_overrides: Object.fromEntries([...BUILTIN_RULE_IDS].map((id) => [id, false])),
460
+ },
461
+ });
462
+ for (const entry of sample) {
463
+ const scope = entry.ruleIndex < 0 ? guardConfig : isolateRule(entry.ruleIndex);
464
+ const ruleDescription = entry.ruleIndex < 0 ? undefined : customRules[entry.ruleIndex].description;
465
+ // Only an exact matched span can be suppressed, so the baseline must ask
466
+ // for one: a rule matching a substring of the entry says nothing about it.
467
+ const baseline = scan(entry.value, withoutAllowlists(scope));
468
+ const withAllow = scan(entry.value, scope);
469
+ if (suppressible(withAllow.exact, ruleDescription).length > 0)
470
+ broken += 1;
471
+ else if (suppressible(baseline.exact, ruleDescription).length > 0)
472
+ exercised += 1;
473
+ else
474
+ unverified += 1;
475
+ }
476
+ const entryCount = entries.length === 1 ? "1 allowlist entry" : `${entries.length} allowlist entries`;
477
+ const coverage = sample.length === entries.length ? "all" : `${sample.length} of them`;
478
+ const counter = `${allowlistSuppressions()} suppression(s) counted in this process`;
479
+ if (broken > 0) {
480
+ checks.push({
481
+ id: "allowlist",
482
+ state: "fail",
483
+ detail: `${broken} allowlisted literal(s) still produce a finding under their own scope. The exact-match filter is not working, so those values are not actually quiet. ${entryCount} total; ${counter}.`,
484
+ fix: "Do not rely on those entries. Re-run the scanner with `--text` on the exact value and report it: an allowlisted literal must produce no rule or env finding (a standing Unicode warning is separate).",
485
+ });
486
+ }
487
+ else if (unverified > 0) {
488
+ checks.push({
489
+ id: "allowlist",
490
+ state: "warn",
491
+ detail: `${entryCount} (global ${globalAllow.length}, per-rule ${ruleAllow.length}), exact match only; ${exercised} suppress when exercised, ${unverified} could not be exercised as a bare literal (a context-dependent pattern is judged only in place). ${coverage} exercised; ${counter}.`,
492
+ fix: "Review the entries that doctor could not exercise; it cannot prove a context-dependent entry, and an entry that no longer matches anything is only risk.",
493
+ });
494
+ }
495
+ else {
496
+ checks.push({
497
+ id: "allowlist",
498
+ state: "ok",
499
+ detail: `${entryCount} (global ${globalAllow.length}, per-rule ${ruleAllow.length}), exact match only; ${coverage} exercised, all suppress; ${counter}.`,
500
+ });
501
+ }
502
+ }
503
+ // `word_boundary` can only add \b at literal ASCII word edges. Where the edge
504
+ // is a group/class/quantifier the rule is looser than it looks; say so.
505
+ const boundaryHidden = customRules.filter((rule) => {
506
+ if (rule.word_boundary !== true)
507
+ return false;
508
+ const edges = customRuleBoundaries(rule);
509
+ return edges.lead === "hidden" || edges.trail === "hidden";
510
+ });
511
+ if (boundaryHidden.length > 0) {
512
+ checks.push({
513
+ id: "custom-rule-boundaries",
514
+ state: "warn",
515
+ detail: `${boundaryHidden.length} custom rule(s) set word_boundary but end or start with a group, class, quantifier or escape, where no \\b can be added: ${boundaryHidden.map((rule) => `"${rule.description}"`).join(", ")}. Those edges match inside larger words.`,
516
+ fix: "Write \\b in the pattern yourself, e.g. \\bEMP-\\d{6}\\b, or finish the pattern with a literal word character.",
517
+ });
518
+ }
519
+ // `path` is accepted but not implemented: the scanner has no source path for
520
+ // chat or tool text. Say so instead of letting a rule look scoped when it is not.
521
+ const pathRules = customRules.filter((rule) => (rule.path ?? []).length > 0);
522
+ if (pathRules.length > 0) {
523
+ checks.push({
524
+ id: "custom-rule-paths",
525
+ state: "warn",
526
+ detail: `${pathRules.length} custom rule(s) set \`path\`, but path scoping is not implemented: they apply to every scanned text, including prompts and tool output.`,
527
+ fix: "Remove `path` from those rules, or rely on the rule's pattern alone, until path scoping ships.",
528
+ });
529
+ }
384
530
  // Smoke: the local scanner must flag a synthetic credential
385
531
  const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
386
532
  if (smoke.findings > 0) {
@@ -395,6 +541,12 @@ export async function runDoctor(deps) {
395
541
  });
396
542
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
397
543
  }
544
+ // A failed check must not still read as PARTIAL or PROTECTED: an allowlist
545
+ // failure is a "do not trust this install" signal, like a missing canary.
546
+ // This runs before the v1 early return so a v1 host cannot mask it either.
547
+ if (checks.some((check) => check.state === "fail")) {
548
+ return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
549
+ }
398
550
  if (host.generation === "v1") {
399
551
  checks.push({
400
552
  id: "coverage",
@@ -410,6 +562,9 @@ export async function runDoctor(deps) {
410
562
  detail: `${options.wireProtection === false ? "transparent hook-only: content hooks protect their snapshots; no outbound HTTP/WS/SDK admission, transport metadata checks, injected-fetch requirement or provider transport transform. Final bodies/frames are not inspected or remasked. Unknown routes, including /alpha/generate, are not gated. Optional incoming HTTP/WS hooks restore known display protocols after successful scoped host preparation for the same session/kind/model; unsupported or unverified replies remain literal. Tool safety remains. Content added after hooks may be unmasked, including late-added attachments." : "transparent mode protects three HTTP protocols by wire shape (Chat Completions, Anthropic Messages, Responses) and native Responses-family WS frames; unknown outbound dialects and intercepted routes, including /alpha/generate, are refused (fail-closed), not passed. AI SDK providers must honor OpenCode's injected HTTP fetch; missing or unsafe fetch options refuse. Bypass transports are outside coverage, not a proven blocked transport."} Both levels stop rewriting on reply-side SG failures and keep literal originals; provider errors and cancellation still propagate. Content-hook masking failures still refuse the affected model call with a safe reason/stage, never silently send raw content. Attachments policy at content hooks: ${options.attachments === "allow" ? "ALLOW — attachments pass through unscanned with a visible notice (you vouch for their content)" : "block — replaced with an omission notice"}. Complete original-history/restart restoration is not verified.`,
411
563
  });
412
564
  }
565
+ // A failed check must not still read as PROTECTED: the allowlist failure is a
566
+ // real "do not trust this install" signal, like a missing smoke canary.
567
+ // (Handled before the v1 return above.)
413
568
  checks.push({
414
569
  id: "runtime",
415
570
  state: "warn",
@@ -71,6 +71,81 @@ function publicIPv4(raw) {
71
71
  return false; // multicast / reserved
72
72
  return true;
73
73
  }
74
+ /**
75
+ * Values on the right of `password:` / `secret =` that are source code, not a
76
+ * literal: environment lookups, a method-call chain, or a member read off a
77
+ * config-like object (issue #49). Only the unquoted branch of generic-secret
78
+ * reaches this, and every form here is narrow on purpose: a bare
79
+ * `word.word` could be a real password, so it is not exempt.
80
+ */
81
+ // Call arguments and bracket keys may hold identifiers, numbers or an
82
+ // ENV_NAME-style string, never another literal: `decrypt("hunter2hunter2")`
83
+ // keeps being reported.
84
+ // Backticks and `=` are excluded too, so a template literal or a keyword
85
+ // argument (`hash(pw=…)`) never qualifies.
86
+ const ARG = `(?:[^()'"\`=\\[\\]]|'[A-Z][A-Z0-9_]*'|"[A-Z][A-Z0-9_]*")*`;
87
+ const IDENT = "[A-Za-z_$][\\w$]*";
88
+ const STEP = `(?:\\??\\.${IDENT}|\\[${ARG}\\]|\\(${ARG}\\))`;
89
+ const TAIL = "[;,)]*$";
90
+ /**
91
+ * A member/call chain: `z.string().min(6)`, `getPassword()`, `os.getenv("DB_PASS")`.
92
+ * Every STEP alternative starts with a different character, so matching is
93
+ * linear; "contains a call" is checked separately rather than with a second
94
+ * quantified group that would backtrack.
95
+ */
96
+ const CODE_CHAIN = new RegExp(`^${IDENT}${STEP}*${TAIL}`);
97
+ /** A member read off an env or config-like root: `process.env.X`, `config.clientSecret`. */
98
+ const CONFIG_MEMBER = new RegExp(`^(?:process\\.env|import\\.meta\\.env|os\\.environ|ENV|this|self|config|cfg|conf|settings|options|opts|props|params|args|req|request|ctx|context|env|secrets)${STEP}+${TAIL}`);
99
+ /** Longer values are not exempted; a real expression on one line is short. */
100
+ const MAX_EXPRESSION_LENGTH = 256;
101
+ function isCodeExpressionValue(match) {
102
+ const value = match.replace(/^[^:=]*[:=]\s*/, "");
103
+ if (value.length > MAX_EXPRESSION_LENGTH)
104
+ return false;
105
+ if (value.startsWith("'") || value.startsWith('"'))
106
+ return false;
107
+ return (value.includes("(") && CODE_CHAIN.test(value)) || CONFIG_MEMBER.test(value);
108
+ }
109
+ /**
110
+ * A whole-token template placeholder that only names a variable:
111
+ * `${pass}`, `${cfg.db.password}`, `{{ password }}`, `<password>`. An
112
+ * interpolation holding a literal (`${"S3cr3tPass"}`) is not a placeholder.
113
+ */
114
+ const PLACEHOLDER = /^(?:\$\{\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\}|\{\{\s*[A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*\s*\}\}|<[A-Za-z][\w -]*>)$/;
115
+ /**
116
+ * True when the password part of `user:password@` is a template placeholder,
117
+ * as in `mongodb://${user}:${pass}@host` or `postgres://<user>:<password>@…`.
118
+ * `userinfo` runs from just after `://` to (and possibly including) the `@`.
119
+ */
120
+ function placeholderPassword(userinfo) {
121
+ const at = userinfo.lastIndexOf("@");
122
+ const body = at === -1 ? userinfo : userinfo.slice(0, at);
123
+ const colon = body.indexOf(":");
124
+ if (colon === -1)
125
+ return false;
126
+ return PLACEHOLDER.test(body.slice(colon + 1));
127
+ }
128
+ const UUID_SHAPE = /[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}/g;
129
+ /** True when [index, index+length) lies inside a UUID-shaped run in `text`. */
130
+ function insideUuid(text, index, length) {
131
+ const from = Math.max(0, index - 36);
132
+ const window = text.slice(from, index + length + 36);
133
+ for (const uuid of window.matchAll(UUID_SHAPE)) {
134
+ const start = from + uuid.index;
135
+ if (start <= index && index + length <= start + uuid[0].length)
136
+ return true;
137
+ }
138
+ return false;
139
+ }
140
+ /** Luhn plus shape checks: not one repeated digit, not part of a UUID (#49). */
141
+ function creditCardValid(match, context) {
142
+ const digits = match.replace(/[^0-9]/g, "");
143
+ if (/^(\d)\1*$/.test(digits))
144
+ return false;
145
+ if (insideUuid(context.text, context.index, match.length))
146
+ return false;
147
+ return luhnValid(match);
148
+ }
74
149
  export const BUILTIN_RULES = [
75
150
  // ── API Keys / Secrets / Tokens ──────────────────────────────────────────
76
151
  {
@@ -151,6 +226,8 @@ export const BUILTIN_RULES = [
151
226
  // 同時涵蓋有引號(YAML/JSON)與無引號(.env)寫法
152
227
  // (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
153
228
  pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
229
+ // 無引號值若是程式碼表達式(process.env.X、z.string()、config.secret)不算機密(#49)
230
+ validate: (match) => !isCodeExpressionValue(match),
154
231
  },
155
232
  {
156
233
  id: "url-userinfo",
@@ -163,6 +240,8 @@ export const BUILTIN_RULES = [
163
240
  // 重掃造成二次方成長。
164
241
  pattern: /:\/\/[^\s/?#:]*:[^\s/?#]*@/gi,
165
242
  skipPrefix: 3,
243
+ // 密碼段是 ${…}/{{…}}/<…> 模板佔位時不是憑證(#49)
244
+ validate: (match) => !placeholderPassword(match),
166
245
  },
167
246
  {
168
247
  id: "jwt",
@@ -269,6 +348,8 @@ export const BUILTIN_RULES = [
269
348
  severity: "HIGH",
270
349
  description: "資料庫連線字串(含密碼)",
271
350
  pattern: /(?:mongodb(?:\+srv)?|postgresql|postgres|mysql|redis|mssql):\/\/[^:\s]+:[^@\s]+@[^\s"']+/gi,
351
+ // 密碼段是模板佔位時不是憑證(#49)
352
+ validate: (match) => !placeholderPassword(match.slice(match.indexOf("://") + 3)),
272
353
  },
273
354
  {
274
355
  id: "db-connection-ado",
@@ -286,7 +367,7 @@ export const BUILTIN_RULES = [
286
367
  description: "信用卡號(Luhn 驗證)",
287
368
  // 13–19 位數字,允許空格或連字號分隔;Luhn 不過由 validate 排除
288
369
  pattern: /\b(?:[0-9][ -]?){12,18}[0-9]\b/g,
289
- validate: luhnValid,
370
+ validate: creditCardValid,
290
371
  },
291
372
  {
292
373
  id: "iban",
@@ -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,7 @@
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";
6
7
  // ─── Base64 Detection & Decoding ─────────────────────────────────────────────────
7
8
  /**
8
9
  * Detects potential Base64 encoded strings.
@@ -160,7 +161,10 @@ export function scanTextWithDecoding(text, config, opts) {
160
161
  // (a ZWSP in Base64 or hex), so decode the stripped form as well. Each
161
162
  // candidate is decoded once even when both forms contain it.
162
163
  const stripped = text.replace(ZERO_WIDTH_CHARS, "");
163
- const sources = stripped === text ? [text] : [text, stripped];
164
+ // A Cyrillic/Greek look-alike swapped into an encoded run hides it the same
165
+ // way, so decode the folded form too (#46). Decoding never recurses.
166
+ const folded = foldConfusables(stripped);
167
+ const sources = [...new Set([text, stripped, folded])];
164
168
  const decodedCandidates = new Set();
165
169
  const firstSighting = (kind, candidate) => {
166
170
  const id = `${kind}\0${candidate}`;
@@ -1,10 +1,11 @@
1
1
  import { BUILTIN_RULES } from "../rules/builtin.js";
2
2
  import { buildDynamicRules } from "../rules/dynamic.js";
3
+ import { allowSet, isAllowlisted, noteAllowlistSuppression } from "./allowlist.js";
3
4
  import { containsAddressInRun, parseCidrList } from "./cidr.js";
4
5
  import { redact, getLineCol, getIgnoredLines } from "./utils.js";
5
6
  import { t } from "../i18n/index.js";
6
7
  import * as encoding from "./encoding.js";
7
- import { detectSuspiciousUnicode } from "./unicode.js";
8
+ import { foldConfusables } from "./unicode.js";
8
9
  // Dynamic rules are derived from config; cache per config object so they are
9
10
  // rebuilt only when the config reference changes (e.g. after reload_config).
10
11
  const dynamicCache = new WeakMap();
@@ -59,12 +60,18 @@ function addExactValueFindings(text, config, ignoredLines, findings) {
59
60
  const detector = config.exact_value_detector;
60
61
  if (!detector)
61
62
  return;
63
+ const globalAllow = allowSet(config.settings.allowlist);
62
64
  for (const match of detector.findAll(text)) {
63
65
  if (hasMatchingRange(findings, match.index, match.length))
64
66
  continue;
65
67
  const { line, col } = getLineCol(text, match.index);
66
68
  if (ignoredLines.has(line))
67
69
  continue;
70
+ const matchedText = text.slice(match.index, match.index + match.length);
71
+ if (isAllowlisted(matchedText, globalAllow, undefined)) {
72
+ noteAllowlistSuppression();
73
+ continue;
74
+ }
68
75
  findings.push({
69
76
  type: "ENV_SECRET",
70
77
  severity: "HIGH",
@@ -74,7 +81,7 @@ function addExactValueFindings(text, config, ignoredLines, findings) {
74
81
  description: "Value from configured env file",
75
82
  match_start: match.index,
76
83
  match_end: match.index + match.length,
77
- match_text: text.slice(match.index, match.index + match.length),
84
+ match_text: matchedText,
78
85
  });
79
86
  }
80
87
  }
@@ -87,12 +94,16 @@ export const ZERO_WIDTH_CHARS = /[\u200B-\u200D\uFEFF\u2060\u180E]/g;
87
94
  function collectRuleFindings(text, rules, config, ignoredLines) {
88
95
  const findings = [];
89
96
  const seen = new Set();
97
+ const globalAllow = allowSet(config.settings.allowlist);
90
98
  for (const rule of rules) {
91
- // Reuse the compiled RegExp; reset lastIndex before each scan so the
92
- // stateful global flag starts from the beginning of the input.
99
+ // Start from the beginning. matchAll advances after empty matches (by a
100
+ // code point under /u); exec alone leaves lastIndex unchanged and can hang.
93
101
  rule.pattern.lastIndex = 0;
94
- let match;
95
- while ((match = rule.pattern.exec(text)) !== null) {
102
+ for (const match of text.matchAll(rule.pattern)) {
103
+ // A zero-width match contains no value to report or mask. Skip it before
104
+ // dedupe, validation or suppression, without losing later real matches.
105
+ if (match[0].length === 0)
106
+ continue;
96
107
  const offset = rule.skipPrefix ?? 0;
97
108
  const matchedText = match[0].slice(offset);
98
109
  const start = match.index + offset;
@@ -101,10 +112,16 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
101
112
  const key = `${rule.type}:${start}`;
102
113
  if (seen.has(key))
103
114
  continue;
104
- seen.add(key);
105
115
  const { line, col } = getLineCol(text, start);
106
116
  if (ignoredLines.has(line))
107
117
  continue;
118
+ if (isAllowlisted(matchedText, globalAllow, rule.allow)) {
119
+ noteAllowlistSuppression();
120
+ // Do NOT reserve the dedupe key: another rule may match a longer span
121
+ // at the same offset, and suppressing the short one must not hide it.
122
+ continue;
123
+ }
124
+ seen.add(key);
108
125
  const preview = redact(matchedText, config.settings.preview_length);
109
126
  findings.push({
110
127
  type: rule.type,
@@ -123,24 +140,22 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
123
140
  return findings;
124
141
  }
125
142
  /**
126
- * Zero-width characters are common in harmless text: emoji ZWJ sequences, a
127
- * BOM at the start of a file, ZWNJ in Persian. They only matter when they
128
- * splice a sensitive value so the rules miss it (`pass\u200Dword=…`, a key
129
- * split by ZWSP). Strip them, rescan, and report only when the stripped text
130
- * yields a finding the raw text does not. Line breaks are untouched, so the
131
- * raw text's ignored lines still apply.
143
+ * True when `transform` (an evasion-undoing normalization that never moves
144
+ * line breaks) makes the rules find something the raw text does not. Raw
145
+ * findings are compared by type and transformed matched text, so a value that
146
+ * is already detected raw does not count twice.
132
147
  */
133
- function zeroWidthHidesFinding(text, rawFindings, rules, config, ignoredLines) {
134
- const stripped = text.replace(ZERO_WIDTH_CHARS, "");
135
- if (stripped === text)
148
+ function transformHidesFinding(text, transform, rawFindings, rules, config, ignoredLines) {
149
+ const transformed = transform(text);
150
+ if (transformed === text)
136
151
  return false;
137
- const identity = (finding) => `${finding.type}\0${(finding.match_text ?? "").replace(ZERO_WIDTH_CHARS, "")}`;
152
+ const identity = (finding) => `${finding.type}\0${transform(finding.match_text ?? "")}`;
138
153
  const unmatched = new Map();
139
154
  for (const finding of rawFindings) {
140
155
  const id = identity(finding);
141
156
  unmatched.set(id, (unmatched.get(id) ?? 0) + 1);
142
157
  }
143
- for (const finding of collectRuleFindings(stripped, rules, config, ignoredLines)) {
158
+ for (const finding of collectRuleFindings(transformed, rules, config, ignoredLines)) {
144
159
  const id = identity(finding);
145
160
  const remaining = unmatched.get(id) ?? 0;
146
161
  if (remaining === 0)
@@ -149,6 +164,34 @@ function zeroWidthHidesFinding(text, rawFindings, rules, config, ignoredLines) {
149
164
  }
150
165
  return false;
151
166
  }
167
+ const stripZeroWidth = (value) => value.replace(ZERO_WIDTH_CHARS, "");
168
+ /**
169
+ * Zero-width characters are common in harmless text: emoji ZWJ sequences, a
170
+ * BOM at the start of a file, ZWNJ in Persian. They only matter when they
171
+ * splice a sensitive value so the rules miss it (`pass\u200Dword=…`, a key
172
+ * split by ZWSP). Strip them, rescan, and report only when the stripped text
173
+ * yields a finding the raw text does not. Line breaks are untouched, so the
174
+ * raw text's ignored lines still apply.
175
+ */
176
+ function zeroWidthHidesFinding(text, rawFindings, rules, config, ignoredLines) {
177
+ return transformHidesFinding(text, stripZeroWidth, rawFindings, rules, config, ignoredLines);
178
+ }
179
+ /**
180
+ * Cyrillic and Greek text is common and harmless in source code: locale
181
+ * files, comments, UI strings, math. Look-alike letters only matter when they
182
+ * disguise a sensitive value (`рassword=…` with a Cyrillic `р`, an `sk-` key
183
+ * with a Greek `κ`). Fold confusables to Latin (zero-width characters removed
184
+ * too, so a combined splice is caught), rescan, and report only when the
185
+ * folded text yields a finding the raw text does not (issue #46).
186
+ */
187
+ function homoglyphHidesFinding(text, rawFindings, rules, config, ignoredLines) {
188
+ // Text with zero-width characters but no look-alikes was already judged by
189
+ // zeroWidthHidesFinding; skip the identical rescan.
190
+ if (foldConfusables(text) === text)
191
+ return false;
192
+ const fold = (value) => foldConfusables(stripZeroWidth(value));
193
+ return transformHidesFinding(text, fold, rawFindings, rules, config, ignoredLines);
194
+ }
152
195
  /**
153
196
  * Internal scan function without encoding detection.
154
197
  * Used by scanTextWithDecoding to avoid infinite recursion.
@@ -164,13 +207,13 @@ function scanTextInternal(text, config, opts) {
164
207
  const ruleFindings = collectRuleFindings(truncated, allRules, config, ignoredLines);
165
208
  // Step 3: Flag suspicious Unicode only when it is an actual threat. This
166
209
  // doesn't modify the text, just detects issues.
167
- const suspicious = detectSuspiciousUnicode(truncated);
168
210
  const zeroWidthEvasion = zeroWidthHidesFinding(truncated, ruleFindings, allRules, config, ignoredLines);
211
+ const homoglyphEvasion = !zeroWidthEvasion && homoglyphHidesFinding(truncated, ruleFindings, allRules, config, ignoredLines);
169
212
  const findings = [];
170
- if (zeroWidthEvasion || suspicious.hasHomographs) {
213
+ if (zeroWidthEvasion || homoglyphEvasion) {
171
214
  findings.push({
172
215
  type: "CUSTOM",
173
- severity: zeroWidthEvasion ? "HIGH" : "MEDIUM",
216
+ severity: "HIGH",
174
217
  line: 1,
175
218
  column: 1,
176
219
  preview: "****",
@@ -182,8 +225,8 @@ function scanTextInternal(text, config, opts) {
182
225
  match_text: truncated.substring(0, 50), // Only store first 50 chars
183
226
  unicode_detected: {
184
227
  had_zero_width: zeroWidthEvasion,
185
- had_homographs: suspicious.hasHomographs,
186
- details: suspicious.details,
228
+ had_homographs: homoglyphEvasion,
229
+ details: [zeroWidthEvasion ? "zero-width characters hide a finding" : "look-alike letters hide a finding"],
187
230
  },
188
231
  });
189
232
  }
@@ -206,7 +249,7 @@ function scanTextInternal(text, config, opts) {
206
249
  const warnings = [];
207
250
  if (zeroWidthEvasion)
208
251
  warnings.push("零寬字符");
209
- if (suspicious.hasHomographs)
252
+ if (homoglyphEvasion)
210
253
  warnings.push("可疑 Unicode");
211
254
  if (wasTruncated)
212
255
  warnings.push("內容截斷");
@@ -285,24 +328,32 @@ protectedSpans = []) {
285
328
  const ignoredLines = honorDirectives(opts) ? getIgnoredLines(truncated) : new Set();
286
329
  const matches = [];
287
330
  const seen = new Set();
331
+ const globalAllow = allowSet(config.settings.allowlist);
288
332
  for (const rule of allRules) {
289
333
  rule.pattern.lastIndex = 0;
290
- let match;
291
- while ((match = rule.pattern.exec(truncated)) !== null) {
334
+ // Keep the same progress and empty-span contract as collectRuleFindings.
335
+ for (const match of truncated.matchAll(rule.pattern)) {
336
+ if (match[0].length === 0)
337
+ continue;
292
338
  const offset = rule.skipPrefix ?? 0;
293
339
  const start = match.index + offset;
294
340
  const end = match.index + match[0].length;
295
- if (rule.validate !== undefined && !rule.validate(match[0].slice(offset), { text: truncated, index: start }))
341
+ const matchedText = match[0].slice(offset);
342
+ if (rule.validate !== undefined && !rule.validate(matchedText, { text: truncated, index: start }))
296
343
  continue;
297
344
  if (overlapsSpan(start, end, protectedSpans))
298
345
  continue;
299
346
  const key = `${start}:${end - start}`;
300
347
  if (seen.has(key))
301
348
  continue;
302
- seen.add(key);
303
349
  const { line } = getLineCol(truncated, start);
304
350
  if (ignoredLines.has(line))
305
351
  continue;
352
+ // An allowlisted literal is left as written, exactly as the scanner leaves
353
+ // it unreported; redacting it would contradict the bypass the user chose.
354
+ if (isAllowlisted(matchedText, globalAllow, rule.allow))
355
+ continue;
356
+ seen.add(key);
306
357
  matches.push({ index: start, length: end - start, type: rule.type });
307
358
  }
308
359
  }
@@ -316,6 +367,9 @@ protectedSpans = []) {
316
367
  const { line } = getLineCol(truncated, match.index);
317
368
  if (ignoredLines.has(line))
318
369
  continue;
370
+ const matchedText = truncated.slice(match.index, match.index + match.length);
371
+ if (isAllowlisted(matchedText, globalAllow, undefined))
372
+ continue;
319
373
  matches.push({ index: match.index, length: match.length, type: "ENV_SECRET" });
320
374
  }
321
375
  }
@@ -155,3 +155,33 @@ export function sanitizeForScanning(text) {
155
155
  },
156
156
  };
157
157
  }
158
+ /**
159
+ * Cyrillic and Greek letters that render like a Latin letter in common fonts,
160
+ * mapped to that Latin letter. One UTF-16 unit in, one out, so offsets and
161
+ * line numbers of the folded text match the original.
162
+ */
163
+ const CONFUSABLE_TO_LATIN = {
164
+ // Cyrillic lowercase
165
+ "а": "a", "е": "e", "о": "o", "р": "p", "с": "c",
166
+ "х": "x", "у": "y", "і": "i", "ј": "j", "ѕ": "s",
167
+ "ԁ": "d", "һ": "h", "ӏ": "l", "ԛ": "q", "ԝ": "w",
168
+ // Cyrillic uppercase
169
+ "А": "A", "В": "B", "Е": "E", "К": "K", "М": "M",
170
+ "Н": "H", "О": "O", "Р": "P", "С": "C", "Т": "T",
171
+ "Х": "X", "У": "Y", "І": "I", "Ј": "J", "Ѕ": "S",
172
+ // Greek lowercase
173
+ "α": "a", "ο": "o", "ρ": "p", "ν": "v", "ι": "i",
174
+ "κ": "k", "υ": "u", "χ": "x",
175
+ // Greek uppercase
176
+ "Α": "A", "Β": "B", "Ε": "E", "Ζ": "Z", "Η": "H",
177
+ "Ι": "I", "Κ": "K", "Μ": "M", "Ν": "N", "Ο": "O",
178
+ "Ρ": "P", "Τ": "T", "Υ": "Y", "Χ": "X",
179
+ };
180
+ const CONFUSABLE_PATTERN = new RegExp(`[${Object.keys(CONFUSABLE_TO_LATIN).join("")}]`, "g");
181
+ /**
182
+ * Replaces Cyrillic/Greek look-alike letters with their Latin counterparts.
183
+ * Length-preserving; returns the input unchanged when it has none.
184
+ */
185
+ export function foldConfusables(text) {
186
+ return text.replace(CONFUSABLE_PATTERN, (char) => CONFUSABLE_TO_LATIN[char] ?? char);
187
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leakshield",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "OpenCode plugin, CLI, and web scanner for sensitive content before sending it to AI",
5
5
  "license": "MIT",
6
6
  "repository": {