leakshield 0.1.1 → 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
@@ -27,7 +27,7 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
27
27
  **Experimental, pre-release.** Published to npm as `leakshield` (`0.1.x`): run `npx leakshield`, or build locally (`npm ci && npm run build`) and point OpenCode at the `dist` directory.
28
28
 
29
29
  - Transparent mode has been verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. It is **not** a guarantee that nothing sensitive reaches a model: the recommended hook-first setup is reported as `PARTIAL` by `--doctor`, and content added after the plugin's hooks or sent by permitted tools (curl, remote MCP) is outside its coverage.
30
- - Not yet verified: OS-keychain persistence, a real Anthropic provider, long histories on other providers, long-running use ([#26](https://github.com/jwcrystal/leakshield/issues/26)).
30
+ - Not yet verified: OS-keychain custody on Windows and Linux (macOS verified 2026-10-20), a real Anthropic provider, long histories on other providers, long-running use ([#26](https://github.com/jwcrystal/leakshield/issues/26)).
31
31
  - Defaults may still change before the first tagged release ([#24](https://github.com/jwcrystal/leakshield/issues/24), [#27](https://github.com/jwcrystal/leakshield/issues/27)); see the [changelog](CHANGELOG.md).
32
32
  - Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [MIT](LICENSE).
33
33
 
@@ -44,15 +44,17 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
44
44
  | Taiwan National ID | Format validation | 🔴 HIGH |
45
45
  | Credit Card Number | 13–19 digits, Luhn checksum required | 🔴 HIGH |
46
46
  | IBAN | Compact or 4-char groups, mod-97 checksum required | 🔴 HIGH |
47
- | Public IPv4 Address | Private/loopback/CGNAT/reserved ranges excluded | 🟡 MEDIUM |
47
+ | Public IPv4 Address | Private/loopback/CGNAT/reserved ranges excluded; runs longer than four groups are reported whole | 🟡 MEDIUM |
48
+ | Private IPv4 / VPN CIDR | **Opt-in** — disabled by default (`rule_overrides["private-ipv4"]: true`); networks from `settings.private_cidrs`, default RFC 1918 + CGNAT + link-local | 🟡 MEDIUM |
48
49
  | Email Address | All email formats | 🟡 MEDIUM |
50
+ | URL Embedded Credential | `scheme://user:password@host` — only the userinfo span is masked | 🔴 HIGH |
49
51
  | Taiwan Mobile Number | **Opt-in** — disabled by default (`rule_overrides["phone-tw"]: true`); digit runs are a measured false-positive source | 🟡 MEDIUM |
50
52
  | International Phone | **Opt-in** — disabled by default (`rule_overrides["phone-intl"]: true`); same trade-off as above | 🟢 LOW |
51
53
  | HTTP(S) URL | **Opt-in** — disabled by default (`rule_overrides.url: true`) | 🟢 LOW |
52
54
  | NDA Keywords | Custom (see `config/guard.config.yaml`) | 🔴 HIGH |
53
55
  | Private Domains | Custom (see `config/guard.config.yaml`) | 🟡 MEDIUM |
54
56
 
55
- > **Detection boundaries** (per `src/rules/builtin.ts`): the generic secret rule matches only the keywords `password`, `passwd`, `secret`, `private_key`, `client_secret` with a value of **8+ characters** — generic `api_key=`/`token=` assignments are not matched unless the value itself matches a vendor pattern. Credit card and IBAN matches require a valid checksum; IP matches cover only public/routable IPv4. Not covered by any rule: street/postal addresses, dates, IPv6, and values below the 8-character minimum. Every built-in rule has a stable id and can be toggled via `settings.rule_overrides` in `config/guard.config.yaml` (unknown ids fail config load); the URL rule ships disabled because always-on URL masking would flag provider endpoints. The same rule set (built-in + `config/guard.config.yaml`) applies to every mode — `block`, `redact`, and `transparent`.
57
+ > **Detection boundaries** (per `src/rules/builtin.ts`): the generic secret rule matches only the keywords `password`, `passwd`, `secret`, `private_key`, `client_secret` with a value of **8+ characters** — generic `api_key=`/`token=` assignments are not matched unless the value itself matches a vendor pattern. Credit card and IBAN matches require a valid checksum; IP matches cover only public/routable IPv4, and a dotted run longer than four groups is reported whole so an address embedded in it is masked instead of left behind (dotted dates such as `2026.10.21.14.32.59` therefore report as an IP run too). Not covered by any rule: street/postal addresses, dates, IPv6, and values below the 8-character minimum for generic secret assignments. SSH remote authorities (`user@host:path`, `ssh://user@host/…`) are not reported as email; private domains and path keywords still apply inside them, and the password half of `scheme://user:password@host` is reported as a URL credential instead. Private IPv4 is opt-in because the literal also matches version numbers and timestamps; `settings.private_cidrs` narrows it to the organisation's own ranges, and an entry that does not parse fails the config load. Every built-in rule has a stable id and can be toggled via `settings.rule_overrides` in `config/guard.config.yaml` (unknown ids fail config load); the URL rule ships disabled because always-on URL masking would flag provider endpoints. The same rule set (built-in + `config/guard.config.yaml`) applies to every mode — `block`, `redact`, and `transparent`.
56
58
 
57
59
  ---
58
60
 
@@ -326,7 +328,7 @@ Note that v2 only accepts plugin *directories* (it resolves `dist/index.js`) or
326
328
 
327
329
  The default `mode` depends on the host: **`transparent` on OpenCode v2** (described below) and **`block` on v1**, since transparent is v2-only. `block` replaces unsafe content with a disclosure-free notice; set `"mode": "block"` on v2 to keep that behavior. Set `mode` to `redact` only when you explicitly want recognized direct matches replaced with `[REDACTED_TYPE]` placeholders. `--doctor` shows the mode in effect and marks it `(default)` when the options omit it.
328
330
 
329
- **OpenCode v2 only — transparent pseudonymization (the v2 default):** omit `mode` or set `"mode": "transparent"` to replace detected sensitive values in model-request snapshots with stable opaque placeholders — category-labelled `[SGP2:<TYPE>-xxxx-xxxx-xxxx]` since W1 (2026-10-07; the legacy `[SGP1:…]` shape stays recognized for restoring pre-upgrade in-session mappings). Reverse mappings are scoped to the OpenCode session and stay in process memory by default; encrypted persistence is opt-in below. Known placeholders are restored in tool inputs before execution and in supported assistant response text. Supported HTTP protocols are selected by URL path shape: Chat Completions, Anthropic Messages, and Responses, including streaming. Native Responses-family WebSocket is also supported as described below. Wire-mode SDKs honoring injected fetch use the same request-scoped HTTP hooks. Hook-only protects content snapshots without transport admission; it does not add adapters for unknown protocols. Transparent mode has been verified against loopback providers and one real OpenAI model; real OS keychains, a real Anthropic provider and long-history replay on other providers are not verified yet ([#26](https://github.com/jwcrystal/leakshield/issues/26)). Routes it cannot protect are refused, not forwarded.
331
+ **OpenCode v2 only — transparent pseudonymization (the v2 default):** omit `mode` or set `"mode": "transparent"` to replace detected sensitive values in model-request snapshots with stable opaque placeholders — category-labelled `[SGP2:<TYPE>-xxxx-xxxx-xxxx]` since W1 (2026-10-07; the legacy `[SGP1:…]` shape stays recognized for restoring pre-upgrade in-session mappings). Reverse mappings are scoped to the OpenCode session and stay in process memory by default; encrypted persistence is opt-in below. Known placeholders are restored in tool inputs before execution and in supported assistant response text. Supported HTTP protocols are selected by URL path shape: Chat Completions, Anthropic Messages, and Responses, including streaming. Native Responses-family WebSocket is also supported as described below. Wire-mode SDKs honoring injected fetch use the same request-scoped HTTP hooks. Hook-only protects content snapshots without transport admission; it does not add adapters for unknown protocols. Transparent mode has been verified against loopback providers and one real OpenAI model; OS-keychain custody is verified on macOS only, and a real Anthropic provider, long-history replay on other providers and Windows/Linux keychains are not verified yet ([#26](https://github.com/jwcrystal/leakshield/issues/26)). Routes it cannot protect are refused, not forwarded.
330
332
 
331
333
  **Hook-only for new transparent installs:** use [the hook-first configuration example](config/opencode.hook-first.example.json), which explicitly sets `wireProtection: false`. Content hooks protect system/messages/options/tools and the tool gate restores safe known arguments. SG registers **no outbound HTTP request, WS handshake/send, or AI SDK admission hooks**, does not inspect transport metadata, and does not change provider transport settings. Unknown routes and private SDK transports do not incur SG transport refusals. Optional incoming HTTP/WS hooks restore supported display text using successful preparation for the same session/kind/model; missing hooks or restoration failures leave placeholders literal without disabling input protection. Later-added content or attachments may leave unmasked, even with `attachments: "block"`. The doctor reports `PARTIAL`, not full-wire protection. **Content-hook masking failures still refuse the affected call**, now including a safe `[stage=prepare.mask reason=…]` code; hook-only does not silently forward unprotectable raw content. See [hook-only verification](docs/evidence/2026-10-11-pure-hook-only-verification.md).
332
334
 
@@ -466,6 +468,58 @@ After editing:
466
468
  - **OpenCode Plugin**: Restart OpenCode to reload the plugin configuration
467
469
  - **Web UI**: Restart the local server
468
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
+
469
523
  ---
470
524
 
471
525
  ## Practical Examples
@@ -510,8 +564,12 @@ Input lengths for dynamic rules are validated when the config is loaded:
510
564
  | `nda_keywords` entries | 200 characters |
511
565
  | `private_domains` entries | 255 characters |
512
566
 
567
+ | `custom_rules` `description` / `pattern` | 200 characters |
568
+
513
569
  Values exceeding these limits will cause `loadConfig()` to throw a Zod validation error, preventing oversized patterns from entering the scanner.
514
570
 
571
+ A `custom_rules` pattern that does not compile as a regular expression also makes `loadConfig()` throw, naming the rule's index and `description` (not the pattern): a rule that cannot be enforced must not load. A pattern that compiles but runs slowly on a fixed probe input is skipped as a ReDoS suspect, with a warning on stderr and a `custom-rules` warning in `leakshield --doctor`. That check is a timing heuristic, not a guarantee: it runs the pattern once and cannot interrupt it, so it cannot prove a pattern safe.
572
+
515
573
  ## Secret Preview Behavior
516
574
 
517
575
  All secret previews in scan results are **fully masked** as `****`, regardless of the secret's length. No prefix or suffix characters from the original value are preserved. This eliminates partial secret exposure in logs, CI output, and Web UI responses.
package/README.zh-TW.md CHANGED
@@ -51,8 +51,10 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
51
51
  | 台灣身份證字號 | 格式驗證 | 🔴 HIGH |
52
52
  | 信用卡號 | 13–19 位數字,需通過 Luhn 檢查碼 | 🔴 HIGH |
53
53
  | IBAN | 緊湊或四字一組格式,需通過 mod-97 檢查碼 | 🔴 HIGH |
54
- | 公共 IPv4 位址 | 排除私有/回環/CGNAT/保留段 | 🟡 MEDIUM |
54
+ | 公共 IPv4 位址 | 排除私有/回環/CGNAT/保留段;超過四段的點分數字整段回報 | 🟡 MEDIUM |
55
+ | 私有 IPv4/VPN 網段 | **Opt-in** —— 預設關閉(`rule_overrides: { "private-ipv4": true }` 開啟);網段由 `settings.private_cidrs` 指定,預設 RFC 1918 + CGNAT + link-local | 🟡 MEDIUM |
55
56
  | Email 地址 | 所有 email 格式 | 🟡 MEDIUM |
57
+ | URL 內嵌憑證 | `scheme://user:password@host` —— 只遮罩 userinfo 這一段 | 🔴 HIGH |
56
58
  | 台灣手機號碼 | **Opt-in** —— 預設關閉(`rule_overrides: { "phone-tw": true }` 開啟);數字段是實測的誤報來源,關閉的代價是漏偵真電話 | 🟡 MEDIUM |
57
59
  | 國際電話 | **Opt-in** —— 預設關閉(`rule_overrides: { "phone-intl": true }` 開啟);取捨同上 | 🟢 LOW |
58
60
  | HTTP(S) URL | **Opt-in** —— 預設關閉(`rule_overrides: { "url": true }` 開啟) | 🟢 LOW |
@@ -466,7 +468,7 @@ Doctor 是在 host 之外執行的安裝層檢查,看不到執行中的 sessio
466
468
 
467
469
  LeakShield 保護送往模型的對話內容:prompt、重播的歷史、工具輸出,以及(transparent 模式下)可解析其結構的 provider 請求 body。它**不是**工具對外連線的防火牆:被允許的本機工具仍可透過 `curl`、遠端 MCP server 或任何其他管道把原文傳出去。要管控工具的目的地,需要此 plugin 之外的權限層。
468
470
 
469
- 偵測也有已知缺口:街道/郵遞地址、日期、IPv6,以及關鍵字清單之外或短於 8 字元的一般賦值都不會被偵測。信用卡與 IBAN 只有在檢查碼驗證通過時才會命中;IP 偵測只涵蓋公開 IPv4;URL 偵測存在但需手動開啟,見[偵測範圍](#偵測範圍)。
471
+ 偵測也有已知缺口:街道/郵遞地址、日期、IPv6,以及關鍵字清單之外或短於 8 字元的一般賦值都不會被偵測。信用卡與 IBAN 只有在檢查碼驗證通過時才會命中;IP 偵測只涵蓋公開 IPv4(超過四段的點分數字會整段回報,避免內嵌位址漏遮;`2026.10.21.14.32.59` 這類點分日期也會回報);URL 偵測存在但需手動開啟,見[偵測範圍](#偵測範圍)。
470
472
 
471
473
  ## 設定檔
472
474
 
@@ -551,8 +553,12 @@ fi
551
553
  | `nda_keywords` 每個項目 | 200 字元 |
552
554
  | `private_domains` 每個項目 | 255 字元 |
553
555
 
556
+ | `custom_rules` 的 `description` / `pattern` | 200 字元 |
557
+
554
558
  超過長度限制的值會導致 `loadConfig()` 拋出 Zod 驗證錯誤,避免過長的 pattern 進入掃描器。
555
559
 
560
+ `custom_rules` 的 pattern 若無法編譯成正規表示式,`loadConfig()` 也會拋錯,並指出規則的索引和 `description`(不會印出 pattern):無法執行的規則不能載入。可以編譯、但在固定測試輸入上跑得太慢的 pattern 會被當成疑似 ReDoS 而略過,stderr 會印警告,`leakshield --doctor` 也會出現 `custom-rules` 警告。這個檢查只是計時啟發式,不是保證:它只執行 pattern 一次,而且無法中斷執行,所以不能證明 pattern 安全。
561
+
556
562
  ## 敏感資訊預覽行為
557
563
 
558
564
  掃描結果中所有敏感資訊的預覽一律顯示為 `****`,不論原始值長度為何,不保留任何前後綴字元。這樣可避免在日誌、CI 輸出或 Web UI 回應中洩漏部分機密內容。
@@ -5,15 +5,33 @@ import * as yaml from "js-yaml";
5
5
  import { fileURLToPath } from "url";
6
6
  import { z } from "zod";
7
7
  import { loadExactValueDetector } from "../scanner/exact-values.js";
8
+ import { parseCidr } from "../scanner/cidr.js";
8
9
  import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
10
+ import { customRulePattern } from "../rules/dynamic.js";
9
11
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
10
12
  const MAX_DYNAMIC_RULE_LENGTH = 200;
11
13
  const MAX_PRIVATE_DOMAIN_LENGTH = 255;
12
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);
13
23
  const CustomRuleSchema = z.object({
14
24
  description: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
15
25
  pattern: z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH),
16
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(),
17
35
  });
18
36
  export const GuardConfigSchema = z.object({
19
37
  nda_keywords: z.array(z.string().min(1).max(MAX_DYNAMIC_RULE_LENGTH)).default(["CONFIDENTIAL", "INTERNAL ONLY", "DO NOT SHARE", "NDA"]),
@@ -26,6 +44,8 @@ export const GuardConfigSchema = z.object({
26
44
  encoding_detection: z.boolean().default(false),
27
45
  env_files: z.array(z.string().min(1).max(MAX_ENV_FILE_PATH_LENGTH)).max(16).default([]),
28
46
  rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
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([]),
29
49
  }).default({}),
30
50
  }).superRefine((config, ctx) => {
31
51
  // Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
@@ -40,6 +60,37 @@ export const GuardConfigSchema = z.object({
40
60
  });
41
61
  }
42
62
  }
63
+ // A private network list that does not parse fails the load: a typo would
64
+ // otherwise narrow the rule to nothing while it still reported "enabled".
65
+ (config.settings.private_cidrs ?? []).forEach((entry, index) => {
66
+ if (parseCidr(entry) === null) {
67
+ ctx.addIssue({
68
+ code: z.ZodIssueCode.custom,
69
+ path: ["settings", "private_cidrs", index],
70
+ message: `private_cidrs[${index}] is not a valid IPv4 CIDR (expected a.b.c.d/prefix)`,
71
+ });
72
+ }
73
+ });
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.
77
+ config.custom_rules.forEach((rule, index) => {
78
+ try {
79
+ customRulePattern(rule);
80
+ }
81
+ catch (error) {
82
+ // V8 messages embed the pattern ("Invalid regular expression: /…/gi:
83
+ // reason"); keep only the reason, since a pattern may itself be a
84
+ // literal the rule exists to protect.
85
+ const message = error.message;
86
+ const reason = message.includes(": ") ? message.split(": ").pop() : message;
87
+ ctx.addIssue({
88
+ code: z.ZodIssueCode.custom,
89
+ path: ["custom_rules", index, "pattern"],
90
+ message: `custom_rules[${index}] "${rule.description}": pattern does not compile (${reason})`,
91
+ });
92
+ }
93
+ });
43
94
  });
44
95
  function finalizeConfig(config, workspaceRoot) {
45
96
  return {
@@ -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,8 +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 { BUILTIN_RULE_IDS } from "./rules/builtin.js";
29
+ import { skippedCustomRules, customRuleBoundaries } from "./rules/dynamic.js";
30
+ import { allowlistSuppressions } from "./scanner/allowlist.js";
28
31
  import { scanText } from "./scanner/engine.js";
29
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
+ }
30
50
  export function createDoctorDeps() {
31
51
  return {
32
52
  opencodeVersion() {
@@ -71,6 +91,9 @@ export function createDoctorDeps() {
71
91
  const result = scanText(text, config);
72
92
  return { findings: result.findings.filter((f) => f.severity === "HIGH").length };
73
93
  },
94
+ probeScan(text, config) {
95
+ return defaultProbeScan(text, config);
96
+ },
74
97
  cwd: process.cwd(),
75
98
  home: os.homedir(),
76
99
  xdgConfigHome: process.env.XDG_CONFIG_HOME,
@@ -369,6 +392,141 @@ export async function runDoctor(deps) {
369
392
  });
370
393
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
371
394
  }
395
+ // Custom rules the scanner skips (the ReDoS timing heuristic; uncompileable
396
+ // patterns already failed the load above). Descriptions only, never patterns.
397
+ const skipped = skippedCustomRules(guardConfig);
398
+ if (skipped.length > 0) {
399
+ checks.push({
400
+ id: "custom-rules",
401
+ state: "warn",
402
+ detail: `${skipped.length} custom rule(s) disabled and not enforced: ${skipped.map((rule) => `"${rule.description}" (${rule.reason === "invalid" ? "pattern does not compile" : "disabled by ReDoS check"})`).join(", ")}. The ReDoS check is a timing heuristic, not a guarantee.`,
403
+ fix: "Rewrite the pattern without nested or overlapping quantifiers, such as (a+)+ or (a|a)*.",
404
+ });
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
+ }
372
530
  // Smoke: the local scanner must flag a synthetic credential
373
531
  const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
374
532
  if (smoke.findings > 0) {
@@ -383,6 +541,12 @@ export async function runDoctor(deps) {
383
541
  });
384
542
  return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
385
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
+ }
386
550
  if (host.generation === "v1") {
387
551
  checks.push({
388
552
  id: "coverage",
@@ -398,6 +562,9 @@ export async function runDoctor(deps) {
398
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.`,
399
563
  });
400
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.)
401
568
  checks.push({
402
569
  id: "runtime",
403
570
  state: "warn",
@@ -51,7 +51,7 @@ const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it coul
51
51
  const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
52
52
  const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
53
53
  const TOOL_REFUSAL_ERROR = "LeakShield blocked this tool call because its arguments could not be restored safely. Re-read the file and try again.";
54
- const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield blocked this tool call because a placeholder has no mapping in this session. Re-read the file, then try again.";
54
+ const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield blocked this tool call before execution: a placeholder has no mapping in this session. The tool did not run. Reread the source and rebuild the affected arguments from current references; rereading does not make an old placeholder valid. If it is refused again, stop retrying and ask the user.";
55
55
  const TOOL_RESTORE_LIMIT_ERROR = "LeakShield blocked this tool call because its arguments are too large to restore safely. Use smaller arguments and try again.";
56
56
  const TOOL_SHELL_CONTEXT_ERROR = "LeakShield blocked this tool call because the shell command's quoting is not supported. Use a simple command with plain arguments, or a different tool.";
57
57
  const TOOL_INPUT_SHAPE_ERROR = "LeakShield blocked this tool call because its argument structure cannot be safely restored. Use plain JSON values and try again.";