leakshield 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +144 -546
  2. package/README.zh-TW.md +143 -520
  3. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  4. package/dist/adapters/claude-code/capabilities.js +47 -0
  5. package/dist/adapters/claude-code/cli.d.ts +10 -0
  6. package/dist/adapters/claude-code/cli.js +51 -0
  7. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  8. package/dist/adapters/claude-code/doctor.js +177 -0
  9. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  10. package/dist/adapters/claude-code/proxy.js +348 -0
  11. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  12. package/dist/adapters/opencode/capabilities.js +48 -0
  13. package/dist/adapters/opencode/doctor.d.ts +67 -0
  14. package/dist/{doctor.js → adapters/opencode/doctor.js} +26 -44
  15. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  16. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  17. package/dist/adapters/opencode/hooks.d.ts +4 -0
  18. package/dist/adapters/opencode/plugin.d.ts +12 -0
  19. package/dist/{opencode.js → adapters/opencode/plugin.js} +43 -14
  20. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  21. package/dist/adapters/opencode/tool-policy.js +23 -0
  22. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  23. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  24. package/dist/adapters/opencode/transparent.d.ts +70 -0
  25. package/dist/adapters/opencode/transparent.js +242 -0
  26. package/dist/adapters/opencode/v2.d.ts +23 -0
  27. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +13 -8
  28. package/dist/adapters/pi/capabilities.d.ts +10 -0
  29. package/dist/adapters/pi/capabilities.js +50 -0
  30. package/dist/adapters/pi/doctor.d.ts +26 -0
  31. package/dist/adapters/pi/doctor.js +276 -0
  32. package/dist/adapters/pi/extension.d.ts +28 -0
  33. package/dist/adapters/pi/extension.js +109 -0
  34. package/dist/adapters/pi/guard.d.ts +33 -0
  35. package/dist/adapters/pi/guard.js +154 -0
  36. package/dist/adapters/pi/persistence.d.ts +9 -0
  37. package/dist/adapters/pi/persistence.js +69 -0
  38. package/dist/adapters/pi/settings.d.ts +51 -0
  39. package/dist/adapters/pi/settings.js +136 -0
  40. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  41. package/dist/adapters/pi/tool-policy.js +114 -0
  42. package/dist/cli.d.ts +18 -0
  43. package/dist/cli.js +17 -6
  44. package/dist/config/loader.d.ts +70 -0
  45. package/dist/config/loader.js +8 -0
  46. package/dist/config/plain-object.d.ts +2 -0
  47. package/dist/core/index.d.ts +9 -0
  48. package/dist/core/index.js +9 -0
  49. package/dist/core/session-guard.d.ts +62 -0
  50. package/dist/{opencode-transparent.js → core/session-guard.js} +56 -713
  51. package/dist/core/sse-recovery.d.ts +6 -0
  52. package/dist/core/tool-restore-policy.d.ts +153 -0
  53. package/dist/core/tool-restore-policy.js +453 -0
  54. package/dist/core/wire.d.ts +213 -0
  55. package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
  56. package/dist/core/ws.d.ts +26 -0
  57. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  58. package/dist/decision/deidentify.d.ts +63 -0
  59. package/dist/decision/ingress.d.ts +40 -0
  60. package/dist/decision/mapping-key.d.ts +91 -0
  61. package/dist/decision/mapping-store.d.ts +166 -0
  62. package/dist/decision/model.d.ts +41 -0
  63. package/dist/decision/pseudonymization.d.ts +176 -0
  64. package/dist/decision/redaction.d.ts +56 -0
  65. package/dist/decision/redaction.js +3 -0
  66. package/dist/decision/schema-strings.d.ts +23 -0
  67. package/dist/decision/schema-strings.js +2 -2
  68. package/dist/decision/value-search.d.ts +39 -0
  69. package/dist/doctor-capabilities.d.ts +21 -0
  70. package/dist/doctor-capabilities.js +58 -0
  71. package/dist/doctor-hosts.d.ts +18 -0
  72. package/dist/doctor-hosts.js +144 -0
  73. package/dist/doctor-report.d.ts +45 -0
  74. package/dist/doctor-report.js +111 -0
  75. package/dist/forget.d.ts +18 -0
  76. package/dist/guard-options.d.ts +45 -0
  77. package/dist/{plugin-options.js → guard-options.js} +8 -6
  78. package/dist/help.d.ts +2 -0
  79. package/dist/help.js +15 -1
  80. package/dist/i18n/en.d.ts +65 -0
  81. package/dist/i18n/index.d.ts +15 -0
  82. package/dist/i18n/zh-TW.d.ts +65 -0
  83. package/dist/index.d.ts +13 -0
  84. package/dist/index.js +1 -1
  85. package/dist/rules/builtin.d.ts +4 -0
  86. package/dist/rules/builtin.js +75 -2
  87. package/dist/rules/dynamic.d.ts +33 -0
  88. package/dist/scanner/allowlist.d.ts +22 -0
  89. package/dist/scanner/cidr.d.ts +39 -0
  90. package/dist/scanner/encoding.d.ts +87 -0
  91. package/dist/scanner/engine.d.ts +43 -0
  92. package/dist/scanner/exact-values.d.ts +11 -0
  93. package/dist/scanner/redaction-verifier.d.ts +24 -0
  94. package/dist/scanner/remotes.d.ts +29 -0
  95. package/dist/scanner/unicode.d.ts +57 -0
  96. package/dist/scanner/utils.d.ts +22 -0
  97. package/dist/transports/cli.d.ts +27 -0
  98. package/dist/transports/web-ui.d.ts +1 -0
  99. package/dist/transports/web-ui.js +1 -1
  100. package/dist/transports/web.d.ts +4 -0
  101. package/dist/types/capabilities.d.ts +67 -0
  102. package/dist/types/capabilities.js +133 -0
  103. package/dist/types.d.ts +149 -0
  104. package/dist/types.js +3 -0
  105. package/dist/utils/files.d.ts +3 -0
  106. package/dist/utils/path-security.d.ts +18 -0
  107. package/dist/utils/win-encoding.d.ts +16 -0
  108. package/package.json +15 -3
  109. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  110. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  111. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  112. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
package/README.md CHANGED
@@ -9,24 +9,35 @@
9
9
 
10
10
  **A gatekeeper that scans for sensitive content before you feed code, documents, or data to AI services.**
11
11
 
12
- Three supported modes:
13
- - **OpenCode Plugin**: The enforced ingress gate for OpenCode. Use this when OpenCode sends content to a model.
12
+ > **Design principles:** Invisible by default. Observable on demand. Fail-closed at the model boundary.
13
+ > New adapter work is built and accepted against these ([ADR 0008](docs/adr/0008-transparent-protection-and-native-ux.md)). They are a contract for adapter work, not a claim that every host meets them today; see [host capabilities](docs/host-capabilities.md) for current status.
14
+
15
+ Five entry points share one scanner and decision model:
16
+ - **OpenCode plugin**: The enforced ingress gate for OpenCode v2, at its content hooks and, in transparent mode, the final provider body.
17
+ - **pi extension**: An in-process pi extension that guards the agent's provider requests through the shared wire core and restores local tool arguments.
18
+ - **Claude Code proxy** (experimental): A local proxy behind `ANTHROPIC_BASE_URL` that masks Anthropic Messages requests and restores assistant text.
14
19
  - **CLI**: Manual or CI scanning of text, files, and directories; supports redaction.
15
20
  - **Web UI**: Local browser interface and REST endpoint for manual scanning.
16
21
 
17
- MCP server mode has been removed. It depended on the model voluntarily calling a scan tool after it had already received the relevant context, so it cannot provide the plugin's security boundary.
22
+ MCP server mode has been removed. It depended on the model voluntarily calling a scan tool after it had already received the relevant context, so it cannot provide a model-boundary guarantee.
18
23
 
19
- | Mode | Start it with | Use it for |
24
+ | Entry point | Start it with | Use it for |
20
25
  |------|---------------|------------|
21
- | OpenCode Plugin | Add the `leakshield` package or the `dist` directory to `opencode.json` (OpenCode v2) | Automatic, fail-closed protection for OpenCode model inputs and tool outputs |
26
+ | OpenCode plugin | Add the `leakshield` package or the `dist` directory to `opencode.json` (OpenCode v2; [guide](docs/opencode.md)) | Automatic, fail-closed protection for OpenCode model inputs and tool outputs |
27
+ | pi extension | `pi install npm:leakshield` (0.4.0+, or `pi install /absolute/path/to/built/leakshield` for a local build; [guide](docs/pi.md)) | Masked pi provider requests and restored read/write/edit/bash arguments |
28
+ | Claude Code proxy | `leakshield --claude-code-proxy`, then `ANTHROPIC_BASE_URL=http://127.0.0.1:8787` ([guide](docs/claude-code.md)) | Masked Claude Code model requests and restored assistant text; tool arguments are not restored yet |
22
29
  | CLI | `npm run scan -- --file ./path` (or `leakshield --file ./path` after a global install / `npm link`) | Explicit local or CI scans; it never sends content to a model |
23
30
  | Web UI | `npm run web` | Manual browser scans at `http://localhost:3000` |
24
31
 
25
32
  ## Project status
26
33
 
27
- **Experimental, `0.x`.** Published to npm as `leakshield`: run `npx leakshield --help` to see the commands, or build locally (`npm ci && npm run build`) and point OpenCode at the `dist` directory. Without arguments or input, the CLI waits on stdin.
34
+ **Experimental, `0.x`.** Published to npm as `leakshield`: run `npx leakshield --help` to see the commands, or build locally (`npm ci && npm run build`) and point a host at the build. Run without arguments in a terminal, the CLI prints usage. When stdin is not a terminal (a pipe, CI or a script), it reads stdin until EOF, so close or redirect stdin there.
35
+
36
+ None of the hosts is a guarantee that nothing sensitive reaches a model. `leakshield --doctor <host>` prints each host's declared coverage and residuals; the [host capability matrix](docs/host-capabilities.md) summarizes them.
28
37
 
29
- - Transparent mode has been verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. The 0.3.0 tool restoration was rechecked on OpenCode v2.2.5 with a loopback provider, the OpenChamber render tool and `rtk` ([record](docs/evidence/2026-11-06-opencode-2.2.5-tool-restoration.md)). 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.
38
+ - **OpenCode**: transparent mode verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. The 0.3.0 tool restoration was rechecked on OpenCode v2.2.5 with a loopback provider, the OpenChamber render tool and `rtk` ([record](docs/evidence/2026-11-06-opencode-2.2.5-tool-restoration.md)). The 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. See [OpenCode plugin](docs/opencode.md).
39
+ - **pi**: an in-process extension wraps the agent's `fetch`, masks the three wire APIs it supports, and restores read/write/edit/bash arguments locally. Verified against pi 1.6.0 with a recording stub upstream ([record](docs/evidence/2026-11-23-pi-extension.md)); providers whose transport bypasses fetch (Codex WebSocket, Bedrock) are refused, and OAuth-only accounts are not supported. See [pi adapter](docs/pi.md).
40
+ - **Claude Code** (experimental): a local proxy (`leakshield --claude-code-proxy`, then `ANTHROPIC_BASE_URL`), verified with Claude Code 2.1.321 against a loopback stub upstream ([record](docs/evidence/2026-11-21-claude-code-proxy.md)). It masks model requests and restores assistant text, but does not restore placeholders at tool execution yet. See [Claude Code](docs/claude-code.md).
30
41
  - 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
42
  - Defaults may still change during `0.x`; see the [changelog](CHANGELOG.md).
32
43
  - Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [Apache-2.0](LICENSE).
@@ -35,15 +46,17 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
35
46
 
36
47
  ## Quickstart
37
48
 
38
- Needs OpenCode v2 and Node.js 20 or later.
49
+ Install once (Node.js 20 or later; the pi extension needs Node.js 22.19 or later):
39
50
 
40
- 1. Install:
51
+ ```bash
52
+ npm install -g leakshield
53
+ ```
41
54
 
42
- ```bash
43
- npm install -g leakshield
44
- ```
55
+ Then connect the host you use and check it with `leakshield --doctor <host>`. Exit code 0 means `PROTECTED` or `PARTIAL`. The doctor checks the install outside the host and cannot see inside a live session, so finish with a synthetic-value test before using real data. Never use a real credential for that test.
45
56
 
46
- 2. Register the plugin in your project's `opencode.json`. With no options, `mode` defaults to `transparent`:
57
+ ### OpenCode v2
58
+
59
+ 1. Register the plugin in your project's `opencode.json`. With no options, `mode` defaults to `transparent`:
47
60
 
48
61
  ```jsonc
49
62
  {
@@ -52,30 +65,74 @@ Needs OpenCode v2 and Node.js 20 or later.
52
65
  }
53
66
  ```
54
67
 
55
- 3. Check the install. Exit code 0 means `PROTECTED` or `PARTIAL`; see [what `PARTIAL` means](#what-partial-means). This check cannot see inside a live session, so run step 4 as well.
68
+ 2. Check the install; see [what `PARTIAL` means](docs/opencode.md#what-partial-means):
56
69
 
57
70
  ```bash
58
- leakshield --doctor
71
+ leakshield --doctor opencode
59
72
  ```
60
73
 
61
- 4. Run the smoke test. It uses a temporary directory and a synthetic value, not a real credential:
74
+ 3. Run the smoke test. It uses a temporary directory and a synthetic value:
62
75
 
63
76
  ```bash
64
77
  SMOKE_DIR="$(mktemp -d)"
65
- cat > "$SMOKE_DIR/opencode.json" <<'EOF'
78
+ cat > "$SMOKE_DIR/opencode.json" <<'JSON'
66
79
  {
67
80
  "$schema": "https://opencode.ai/config.json",
68
81
  "plugins": [{ "package": "leakshield", "options": { "mode": "block" } }]
69
82
  }
70
- EOF
83
+ JSON
71
84
  (cd "$SMOKE_DIR" && opencode run --standalone \
72
85
  "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA")
73
86
  rm -rf "$SMOKE_DIR"
74
87
  ```
75
88
 
76
- The model-facing message must contain the LeakShield block notice and must not contain the synthetic token. Do not use a real credential for this test.
89
+ The model-facing message must contain the LeakShield block notice and must not contain the synthetic token.
90
+
91
+ ### pi
92
+
93
+ 1. Install the pi package (it registers the extension in `settings.packages`):
94
+
95
+ ```bash
96
+ pi install npm:leakshield
97
+ ```
98
+
99
+ 2. Check the install. A package install reports `PARTIAL` because pi's load order cannot be verified; for `PROTECTED`, register the extension first in `settings.extensions` instead ([explicit path](docs/pi.md#explicit-extension-path)):
77
100
 
78
- Before relying on it, read [what this protects — and what it does not](#what-this-protects--and-what-it-does-not). For source builds and other options, see [Installation](#installation) and [OpenCode Plugin](#opencode-plugin-recommended). New contributors: [3-minute onboarding](docs/ONBOARDING.zh-TW.md) (Traditional Chinese only).
101
+ ```bash
102
+ leakshield --doctor pi
103
+ ```
104
+
105
+ 3. Send pi a synthetic value such as `sk-AAAAAAAAAAAAAAAAAAAA` and confirm the provider receives a placeholder. See [pi adapter](docs/pi.md) for the provider APIs it supports.
106
+
107
+ ### Claude Code (experimental)
108
+
109
+ 1. Start the proxy and leave it running:
110
+
111
+ ```bash
112
+ leakshield --claude-code-proxy # listens on 127.0.0.1:8787
113
+ ```
114
+
115
+ 2. Point Claude Code at it, in the shell or in the `env` block of `~/.claude/settings.json`:
116
+
117
+ ```bash
118
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:8787
119
+ ```
120
+
121
+ 3. Check the wiring:
122
+
123
+ ```bash
124
+ leakshield --doctor claude-code
125
+ ```
126
+
127
+ Tool-call arguments are not restored yet, and traffic that bypasses the base URL is not covered; see [Claude Code](docs/claude-code.md).
128
+
129
+ ### CLI only
130
+
131
+ ```bash
132
+ leakshield --file ./path/to/file
133
+ ```
134
+
135
+ Before relying on any host, read [what this protects — and what it does not](#what-this-protects--and-what-it-does-not). For source builds and other options, see [Installation](#installation). New contributors: [3-minute onboarding](docs/ONBOARDING.zh-TW.md) (Traditional Chinese only).
79
136
 
80
137
  ---
81
138
 
@@ -89,61 +146,28 @@ Before relying on it, read [what this protects — and what it does not](#what-t
89
146
  | Private Key | PEM private key blocks | 🔴 HIGH |
90
147
  | DB Connection String | MongoDB, PostgreSQL, MySQL, Redis, ADO format, etc. | 🔴 HIGH |
91
148
  | Taiwan National ID | Format validation | 🔴 HIGH |
149
+ | Passport (MRZ) | TD3 line 2 only: 44 uppercase characters plus four ICAO 9303 check digits | 🔴 HIGH |
150
+ | US SSN | **Opt-in** — `rule_overrides["ssn-us"]: true`; hyphenated form only, invalid areas, groups and serials excluded | 🔴 HIGH |
151
+ | Taiwan Business No | **Opt-in** — `rule_overrides["tw-business-no"]: true`; 8 digits, divisible-by-5 checksum (2023 rule); about one in five random numbers passes, so dates can match | 🟡 MEDIUM |
92
152
  | Credit Card Number | 13–19 digits, Luhn checksum required | 🔴 HIGH |
93
153
  | IBAN | Compact or 4-char groups, mod-97 checksum required | 🔴 HIGH |
94
154
  | Public IPv4 Address | Private/loopback/CGNAT/reserved ranges excluded; runs longer than four groups are reported whole | 🟡 MEDIUM |
95
155
  | 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 |
96
156
  | Email Address | All email formats | 🟡 MEDIUM |
97
157
  | URL Embedded Credential | `scheme://user:password@host` — only the userinfo span is masked | 🔴 HIGH |
98
- | Taiwan Mobile Number | **Opt-in** — disabled by default (`rule_overrides["phone-tw"]: true`); digit runs are a measured false-positive source | 🟡 MEDIUM |
99
- | International Phone | **Opt-in** — disabled by default (`rule_overrides["phone-intl"]: true`); same trade-off as above | 🟢 LOW |
158
+ | Taiwan Mobile Number | **Opt-in** — disabled by default (`rule_overrides["phone-tw"]: true`); `09xx` or `+886 9xx`, with optional spaces or hyphens; digit runs are a measured false-positive source | 🟡 MEDIUM |
159
+ | International Phone | **Opt-in** — disabled by default (`rule_overrides["phone-intl"]: true`); `+` and 7–15 digits, one space or hyphen allowed between digits; same trade-off as above | 🟢 LOW |
100
160
  | HTTP(S) URL | **Opt-in** — disabled by default (`rule_overrides.url: true`) | 🟢 LOW |
101
- | NDA Keywords | Custom (see `config/guard.config.yaml`) | 🔴 HIGH |
102
- | Private Domains | Custom (see `config/guard.config.yaml`) | 🟡 MEDIUM |
161
+ | NDA Keywords | Defaults plus your own (see [Configuration](#configuration)) | 🔴 HIGH |
162
+ | Private Domains | Your own (see [Configuration](#configuration)) | 🟡 MEDIUM |
103
163
 
104
- > **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. It also skips an unquoted value that is a code expression, such as `process.env.DB_PASSWORD` or `z.string().min(6)`; a call whose arguments hold another string literal is still reported. Credit card and IBAN matches require a valid checksum, and the credit card rule skips a run of one repeated digit and digits inside a UUID. The URL credential and DB connection rules skip a password that is a `${…}`, `{{…}}` or `<…>` placeholder. 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`.
105
-
106
- ---
107
-
108
- ## Decision Model
109
-
110
- Every scan produces a **decision** that tells the caller how to handle the content:
111
-
112
- | Decision | When | Risk Level | Meaning |
113
- |----------|------|-----------|---------|
114
- | `ALLOW` | No findings | LOW | Content is clean — safe to send |
115
- | `WARN` | LOW-severity findings only | MEDIUM | Minor items detected — reminder shown, content can be sent |
116
- | `CONFIRM` | MEDIUM or HIGH findings | HIGH / CRITICAL | Sensitive content detected — user must explicitly confirm |
117
-
118
- ### CONFIRM Handling
119
-
120
- When the decision is `CONFIRM`, the CLI is non-interactive: it prints a warning card and a next-step hint, and does not prompt you to choose. The hint points to `--format json` (read `redactedContent`) or `--redact` (sanitized output). Exit code `1` means the content was blocked.
121
-
122
- The `CONFIRM` decision includes:
123
- - `recommendedAction`: `REVIEW` (MEDIUM findings) or `BLOCK` (HIGH findings)
124
- - `safePreview`: a masked excerpt around the first finding
125
- - `redactedContent`: the full content with all sensitive spans replaced
126
-
127
- `safePreview` and `redactedContent` are left out when a sensitive span cannot be located exactly, such as an encoded run split by a zero-width character. A missing field means no safe version is available.
128
-
129
- ### JSON Output Fields
130
-
131
- When using `--format json`, the output includes these decision-oriented fields:
132
-
133
- | Field | Description |
134
- |-------|-------------|
135
- | `decision` | `ALLOW`, `WARN`, or `CONFIRM` |
136
- | `riskLevel` | `LOW`, `MEDIUM`, `HIGH`, or `CRITICAL` |
137
- | `recommendedAction` | `REVIEW` or `BLOCK` (CONFIRM only) |
138
- | `findings` | Array of sanitized findings (no internal metadata) |
139
- | `safePreview` | Masked excerpt (CONFIRM only; can be absent) |
140
- | `redactedContent` | Full redacted text (CONFIRM only; can be absent) |
164
+ > **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. It also skips an unquoted value that is a code expression, such as `process.env.DB_PASSWORD` or `z.string().min(6)`; a call whose arguments hold another string literal is still reported. Credit card and IBAN matches require a valid checksum, and the credit card rule skips a run of one repeated digit and digits inside a UUID. The URL credential and DB connection rules skip a password that is a `${…}`, `{{…}}` or `<…>` placeholder. 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). Passport detection reads the MRZ line only, so a bare passport number beside a label needs a custom rule, and SSN detection requires the hyphenated 3-2-4 form. 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` replaces its default networks, for example with your 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 your config file ([ids](docs/configuration.md#built-in-rule-ids); 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 rules plus your config) applies to every mode — `block`, `redact`, and `transparent` — and every host.
141
165
 
142
166
  ---
143
167
 
144
168
  ## Installation
145
169
 
146
- Requires Node.js 20 or later. Mapping persistence needs 22.13 or later.
170
+ Requires Node.js 20 or later. Mapping persistence needs 22.13 or later, and the pi extension needs 22.19 or later.
147
171
 
148
172
  ```bash
149
173
  npm install -g leakshield
@@ -167,85 +191,25 @@ For local development, install the build globally or `npm link` it, then use
167
191
  `leakshield` directly. `npm run scan -- ...` works from this repository without
168
192
  installing.
169
193
 
170
- ### npm Scripts
171
-
172
- | Command | Description |
173
- |---------|-------------|
174
- | `npm run build` | Clean, then compile TypeScript → `dist/` |
175
- | `npm run clean` | Remove `dist/` |
176
- | `npm start` | Run the built CLI (`node dist/cli.js --cli`) |
177
- | `npm run dev` | CLI mode (no build needed) |
178
- | `npm run scan` | CLI scan (no build needed) |
179
- | `npm run web` | Start the local Web UI (no build needed) |
180
- | `npm test` | Run unit tests |
181
- | `npm run test:watch` | Run tests in watch mode |
182
- | `npm run binary` | Build standalone binary for current platform (macOS ARM) |
183
- | `npm run binary:win` | Cross-compile for Windows x64 |
184
- | `npm run binary:linux` | Cross-compile for Linux x64 |
185
- | `npm run binary:mac-intel` | Cross-compile for macOS Intel |
186
- | `npm run binary:win-icon` | Build the Windows binary with the app icon (`scripts/build-win.js`) |
187
- | `npm run binary:all` | Build all platforms at once |
188
- | `npm run bundle:mac` | Build the binary and package a macOS bundle (`scripts/bundle-mac.sh`) |
194
+ To run without Node.js, build a standalone binary of the CLI with Bun: see [Build it yourself](BINARY-GUIDE.md#build-it-yourself). Development scripts are listed in [CONTRIBUTING](CONTRIBUTING.md#npm-scripts).
189
195
 
190
196
  ---
191
197
 
192
- ## Standalone Binary
193
-
194
- Can't use Node.js or npm? Build a standalone binary with [Bun](https://bun.sh) — no runtime needed on the target machine.
195
-
196
- ```bash
197
- # One-command build for current platform
198
- npm run binary
199
-
200
- # Cross-compile for other platforms
201
- npm run binary:win # Windows x64 → leakshield.exe
202
- npm run binary:linux # Linux x64 → leakshield-linux
203
- npm run binary:all # All platforms
204
- ```
205
-
206
- Or directly with Bun:
207
-
208
- ```bash
209
- bun build --compile --target=bun-windows-x64 ./src/cli.ts --outfile=leakshield.exe
210
- ```
211
-
212
- The output is a single executable — hand it to anyone, no dependencies required.
213
-
214
- ### Configuration for binary and npm users
215
-
216
- The binary and the npm package work out of the box with built-in defaults. To customize rules (NDA keywords, private domains, custom regex patterns), place a config file in one of these locations:
198
+ ## Usage
217
199
 
218
- | Location | Scope |
219
- |----------|-------|
220
- | `./config/guard.config.yaml` | Current working directory |
221
- | `~/.leakshield/guard.config.yaml` | All sessions (user home) |
200
+ ### What this protects — and what it does not
222
201
 
223
- ```bash
224
- # Quick start: copy config/guard.config.example.yaml from this repository,
225
- # then replace its sample keywords and domains
226
- mkdir -p ~/.leakshield
227
- cp config/guard.config.example.yaml ~/.leakshield/guard.config.yaml
202
+ LeakShield protects model-conversation content: prompts, replayed history, tool outputs, and provider-bound request bodies whose shape it can parse. How much of that each host covers differs; `leakshield --doctor <host>` and the [host capability matrix](docs/host-capabilities.md) list it. It is **not** a tool-egress firewall: a permitted local tool can still transmit originals over the network via `curl`, a remote MCP server, or any other channel. Controlling tool destinations requires a separate permission layer outside LeakShield. Since 0.3.0, `curl` and `http` may also hold a placeholder inside an argument, so a tool can call an API with the protected value; the original then leaves the machine by design.
228
203
 
229
- # Or per-project
230
- mkdir -p ./config
231
- # Create/edit ./config/guard.config.yaml as needed
232
- ```
204
+ Detection also has known gaps: street/postal addresses, dates, IPv6, and generic assignments outside the keyword list or below the 8-character minimum pass through undetected. Credit card and IBAN numbers are detected only when the checksum validates; IP detection covers public IPv4 only; passport detection reads the MRZ line only; United States SSN, Taiwan business-number, phone and URL detection are opt-in — see [Detection Coverage](#detection-coverage).
233
205
 
234
- See [Configuration](#configuration) section for available options.
206
+ Local originals may remain in history, logs, and generated files — this protects the model boundary, not your disk.
235
207
 
236
208
  ---
237
209
 
238
- ## Usage
239
-
240
- ### OpenCode Plugin (recommended)
241
-
242
- When loaded successfully, the OpenCode plugin is the enforced integration. It scans and blocks user text before OpenCode persists or sends it to a model, sanitizes system prompts and tool definitions, protects tool output before the next model turn, and re-scans history before replay. It always enables encoded-content detection. Invalid plugin options or scanner configuration make every protected hook fail closed and abort the model request. A bounded SHA-256 decision cache avoids repeatedly scanning unchanged history without retaining original or redacted content.
210
+ ### OpenCode plugin
243
211
 
244
- Transparent mode details: [Encoded content and tool schemas](docs/plugin/transparent-mode.md#encoded-content-and-tool-schemas).
245
-
246
- LeakShield supports OpenCode v2 only. v2 hosts load the package `id` + `setup(ctx)` definition. OpenCode v1 is no longer supported: a v1 host that loads the package gets hooks that fail closed and abort every model request, and `leakshield --doctor` reports `BROKEN`. Upgrade to OpenCode v2.
247
-
248
- **OpenCode v2** — point `plugins` at the published package, or at the `dist` directory of a local build:
212
+ When loaded successfully, the OpenCode plugin is the enforced integration. It scans and blocks user text before OpenCode persists or sends it to a model, sanitizes system prompts and tool definitions, protects tool output before the next model turn, and re-scans history before replay. In transparent mode (the default) it also validates the final provider body. Invalid plugin options or scanner configuration make every protected hook fail closed and abort the model request. OpenCode v2 only.
249
213
 
250
214
  ```jsonc
251
215
  {
@@ -253,470 +217,104 @@ LeakShield supports OpenCode v2 only. v2 hosts load the package `id` + `setup(ct
253
217
  "plugins": [
254
218
  {
255
219
  "package": "leakshield" // or "/absolute/path/to/leakshield/dist"
256
- // No options: mode defaults to "transparent" on v2.
257
220
  // Add "options": { "mode": "block" } to refuse instead of pseudonymize.
258
221
  }
259
222
  ]
260
223
  }
261
224
  ```
262
225
 
263
- Note that v2 only accepts plugin *directories* (it resolves `dist/index.js`) or package names; a `file://` URL to a single `.js` file is rejected with `configured plugin path must be a directory`.
264
-
265
- The default `mode` is **`transparent`** (see [Transparent mode](docs/plugin/transparent-mode.md)). `block` replaces unsafe content with a disclosure-free notice; set `"mode": "block"` to use it. 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.
266
-
267
- #### What `PARTIAL` means
268
-
269
- `leakshield --doctor` exits 0 for two statuses. They are install-level results, not a guarantee that nothing sensitive reaches a model.
270
-
271
- | Status | Setup | Meaning |
272
- |--------|-------|---------|
273
- | `PROTECTED` | `block` or `redact`, or transparent with `wireProtection` omitted or `true` (the v2 default) | Install-level checks pass. In transparent mode, the final HTTP body or supported WS frame is validated too |
274
- | `PARTIAL` | Transparent with `wireProtection: false` ([hook-first example](config/opencode.hook-first.example.json)) | Final outbound HTTP bodies are not inspected |
275
-
276
- With `PARTIAL`:
277
-
278
- - Later-added content or attachments may leave unmasked, even with `attachments: "block"`.
279
- - **Content-hook masking failures still refuse the affected call**; hook-only does not silently forward unprotectable raw content.
280
-
281
- See [Wire protection](docs/plugin/wire-protection.md) for both levels.
282
-
283
- #### Detailed guides
284
-
285
- - [Transparent mode](docs/plugin/transparent-mode.md): placeholders, supported protocols, tool argument restoration (per field, `code`/`script` fields, Code Mode, `curl`, `rtk`), restart limitation
286
- - [Wire protection](docs/plugin/wire-protection.md): hook-only and final wire levels, AI SDK providers, refusals, reply-side recovery
287
- - [Native WebSocket](docs/plugin/websocket.md): experimental Responses-family support and its limits
288
- - [Mapping persistence](docs/plugin/persistence.md): opt-in encrypted storage, key custody, erasure
289
- - [Capacity and lifecycle](docs/plugin/capacity.md): budgets, session limits, retention
290
- - [Readonly env queries](docs/plugin/env-queries.md): opt-in tools that answer configuration questions without returning values
291
-
292
- #### Persistence risk notes (read before enabling)
293
-
294
- Mapping persistence is opt-in; see [Mapping persistence](docs/plugin/persistence.md).
295
-
296
- - The design is dual-secret — the DB file alone or the key alone exposes nothing; both together do.
297
- - Backups (Time Machine, cloud sync) copy `SGP.db`: `forget` cannot reclaim what a backup already captured, and a restored backup plus a surviving key can re-identify old sessions — treat backup retention accordingly.
298
- - The keychain defends offline file theft (stolen disk, stolen backups, a copied `SGP.db`); it does not defend malware already running inside your login session.
299
- - The keyfile option lowers the bar to "both files from the same directory tree" and is intended for headless/server environments without a keychain service.
300
-
301
- **OpenCode v2 only — email de-identification trial:** the opt-in `deidentify` option (valid only together with `mode: "redact"`) additionally replaces repeated MEDIUM email findings with stable, opaque `[SG-EMAIL-…]` placeholders so an agent can correlate records without seeing the addresses. The mapping key is generated once per plugin setup (one OpenCode session), held in memory only, and never persisted — placeholders are stable within a live session but change after a restart, and no reverse mapping exists. Everything else keeps its existing disposition: HIGH credentials are still redacted/blocked, and truncated, encoded, or unverifiable content blocks the whole unit.
302
-
303
- ```jsonc
304
- { "package": "/absolute/path/to/leakshield/dist", "options": { "mode": "redact", "deidentify": true } }
305
- ```
306
-
307
- Attachments: transparent mode supports an `attachments` policy (plural; `attachment` is not recognized). **`"block"` (default)** omits media/file parts at content hooks and replaces them with a notice; the model cannot read those omitted images. Final wire protection also refuses residual wire attachment parts; hook-first does not inspect late-added attachments. **`"allow"`** sends attachments through unscanned and appends a visible notice part — an explicit decision that you vouch for their content (`"allow"` requires `mode: "transparent"`). In block/redact modes attachments are blocked as before. Existing conversations can replay originals, subject to the [restart limitations](docs/plugin/transparent-mode.md#restart-limitation); starting a new conversation is not a substitute for verifying recovery. The plugin protects OpenCode model requests only, not other AI clients or local tools.
308
-
309
- OpenCode currently logs and skips modules that fail before their plugin factory can run, such as a missing package or JavaScript syntax error. After installation or upgrade, run a smoke test with a synthetic key matching `sk-` followed by at least 20 letters or digits and verify that LeakShield replaces the message before using real sensitive data.
310
-
311
- #### Isolated smoke test (OpenCode v2)
312
-
313
- Run this from the project root. It uses a temporary working directory and a synthetic value, not a real credential:
314
-
315
- ```bash
316
- npm run build
317
- SMOKE_DIR="$(mktemp -d)"
318
- PROJECT_DIR="$(pwd)"
319
- cat > "$SMOKE_DIR/opencode.json" <<EOF
320
- {
321
- "$schema": "https://opencode.ai/config.json",
322
- "plugins": [
323
- { "package": "$PROJECT_DIR/dist", "options": { "mode": "block" } }
324
- ]
325
- }
326
- EOF
327
- (cd "$SMOKE_DIR" && opencode run --standalone \
328
- "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA")
329
- rm -rf "$SMOKE_DIR"
330
- ```
331
-
332
- The model-facing message must contain the LeakShield block notice and must not contain the synthetic token. Do not use a real credential for this test.
333
-
334
- To test the published package, use `"leakshield"` instead of the local `dist` path.
335
-
336
- #### Automated install check: `--doctor`
337
-
338
- ```bash
339
- npm run scan -- --doctor # or: leakshield --doctor after global install
340
- ```
341
-
342
- The doctor verifies the install without sending anything anywhere: it checks the OpenCode host version, reads the `opencode.json` or `opencode.jsonc` files OpenCode applies (`.opencode/`, the project root and one global directory), combines their `plugins` arrays the way the host does, confirms LeakShield is registered with options that the plugin itself would accept, verifies a local `dist` entry point actually exists (a missing one makes OpenCode silently log-and-skip the plugin — sessions look normal but are unprotected), loads the guard config, and runs the synthetic-canary smoke scan locally. Exit code 0 means `PROTECTED` or `PARTIAL` (`wireProtection: false`: final outbound HTTP bodies are not inspected); a v1 host is reported `BROKEN` with a fix that says to upgrade to OpenCode v2; any other status prints the failing check with a concrete fix, including a copy-paste registration snippet when the plugin is missing.
343
-
344
- Doctor is an install-level check that runs outside the host — it cannot see inside a live session. Runtime proof comes from the smoke test above or `scripts/e2e/run-boundary.mjs`.
345
-
346
- ### What this protects — and what it does not
347
-
348
- LeakShield protects model-conversation content: prompts, replayed history, tool outputs, and (in transparent mode) provider-bound request bodies whose shape it can parse. It is **not** a tool-egress firewall: a permitted local tool can still transmit originals over the network via `curl`, a remote MCP server, or any other channel. Controlling tool destinations requires a separate permission layer outside this plugin. Since 0.3.0, `curl` and `http` may also hold a placeholder inside an argument, so a tool can call an API with the protected value; the original then leaves the machine by design.
349
-
350
- Detection also has known gaps: street/postal addresses, dates, IPv6, and generic assignments outside the keyword list or below the 8-character minimum pass through undetected. Credit card and IBAN numbers are detected only when the checksum validates; IP detection covers public IPv4 only; URL detection exists but is opt-in — see [Detection Coverage](#detection-coverage).
351
-
352
- Local originals may remain in history, logs, and generated files — this protects the model boundary, not your disk.
226
+ Modes, `PARTIAL`, attachments, email de-identification, the isolated smoke test and what `--doctor` checks: [OpenCode plugin](docs/opencode.md). Feature guides: [transparent mode](docs/plugin/transparent-mode.md), [wire protection](docs/plugin/wire-protection.md), [native WebSocket](docs/plugin/websocket.md), [mapping persistence](docs/plugin/persistence.md), [capacity](docs/plugin/capacity.md), [readonly env queries](docs/plugin/env-queries.md).
353
227
 
354
228
  ---
355
229
 
356
- ### CLI
230
+ ### pi (in-process extension)
357
231
 
358
232
  ```bash
359
- # Scan text
360
- npm run scan -- --text 'sk-proj-test1234567890abcdef my_password="super_secret"'
361
-
362
- # Scan a single file
363
- npm run scan -- --file ./src/config.ts
364
-
365
- # Scan an entire directory
366
- npm run scan -- --dir ./src
367
-
368
- # Scan specific file extensions only
369
- npm run scan -- --dir ./src --ext .ts .env .json
370
-
371
- # Read from stdin
372
- cat .env | npm run scan -- --stdin
373
-
374
- # Global installation
375
- leakshield --file ./config.ts
233
+ pi install npm:leakshield # or: pi -e /path/to/leakshield/dist/adapters/pi/extension.js
234
+ leakshield --doctor pi # checks registration, order and wire API
376
235
  ```
377
236
 
378
- Exit codes: `0` = safe (ALLOW), `1` = findings detected (WARN or CONFIRM), `2` = file not found
237
+ pi resolves `fetch` when it builds a provider client, including compaction and branch summaries, so an extension that wraps `globalThis.fetch` covers the same traffic the OpenCode plugin covers through its wire hook. Every provider request is masked in-process; assistant text is restored in the reply, and `read`, `write`, `edit`, `bash` and `powershell` arguments are restored at the local execution boundary. Session files stay with pi, so `--continue`, `--resume` and `--session` keep working. Verified against pi 1.6.0 with a recording stub; providers that bypass fetch (Codex WebSocket, Bedrock, Google auth) are refused, OAuth-only accounts are not supported, and loading the extension first keeps other extensions from holding the raw fetch. See [pi adapter](docs/pi.md).
379
238
 
380
- #### Redaction Mode
239
+ ---
381
240
 
382
- Replace sensitive content with `[REDACTED_TYPE]` placeholders instead of just reporting it:
241
+ ### Claude Code (local proxy, experimental)
383
242
 
384
243
  ```bash
385
- # Redact stdin and print to stdout
386
- echo 'token=sk-proj-test1234567890abcdef' | npm run scan -- --redact --stdin
387
-
388
- # Redact a file and write result to a new file
389
- npm run scan -- --redact --file .env --out .env.redacted
390
-
391
- # Dry-run: preview what would be redacted without producing any output
392
- npm run scan -- --redact --dry-run --file .env
244
+ leakshield --claude-code-proxy # listens on 127.0.0.1:8787
245
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:8787 # or the "env" block of ~/.claude/settings.json
246
+ leakshield --doctor claude-code # checks the wiring
393
247
  ```
394
248
 
395
- Redacted output goes to **stdout**; the findings summary goes to **stderr** so they can be separated in pipelines.
396
-
397
- | Flag | Behaviour |
398
- |------|-----------|
399
- | `--redact` | Replace findings with `[REDACTED_TYPE]`, write to stdout; output is suppressed if findings remain after redaction |
400
- | `--redact --dry-run` | Preview findings only, no output; exit `1` if any found |
401
- | `--redact --out <path>` | Write redacted text to file instead of stdout |
402
- | `--redact --format json` | Return JSON with `redacted`, `findings`, and `summary` fields |
403
-
404
- #### CLI Options
405
-
406
- | Option | Description |
407
- |--------|-------------|
408
- | `--format json` | JSON output (CI/CD friendly) |
409
- | `--min-severity high` | Only report HIGH (or `medium` / `low`) |
410
- | `--allow-outside` | Allow scanning paths outside the current working directory (disabled by default) |
411
- | `--enable-encoding-detection` | Also decode Base64, URL-encoded and hex content before scanning (disabled by default) |
412
-
413
- #### Encoding Detection
249
+ The proxy masks every Anthropic Messages request Claude Code sends (and `count_tokens`), restores placeholders in the assistant's JSON or streamed text, and blocks anything it cannot mask instead of forwarding it. It is verified with an API key; Claude Code documents that the base URL also applies to a claude.ai login, which has not been tested here. It does not restore placeholders inside tool calls, and it cannot see traffic that bypasses the base URL, such as WebFetch's domain check, which sends the hostname to Anthropic. Setup and the full list of gaps: [docs/claude-code.md](docs/claude-code.md).
414
250
 
415
- **Why encoding detection?**
416
-
417
- Encoding tricks can bypass sensitive-data detection:
418
- - **Base64 encoding**: an API key or password is encoded before it is sent
419
- - **URL encoding**: formats such as `%20` hide keywords
420
- - **Hex encoding**: hexadecimal encoding evades pattern matching
421
-
422
- **Enabling**
423
-
424
- ```bash
425
- # Enable encoding detection
426
- npm run scan -- --enable-encoding-detection --text "c2stcHJvai10ZXN0MTIzNDU2Nzg5MGFiY2RlZg=="
427
-
428
- # Combine with other options
429
- npm run scan -- --enable-encoding-detection --file ./config.yaml --format json
430
-
431
- # Enable when scanning a directory
432
- npm run scan -- --enable-encoding-detection --dir ./src --ext .ts .env
433
- ```
434
-
435
- **Performance**
436
-
437
- Decoding and rescanning can add 10-30% to scan time. Recommendations:
438
- - **Off by default**: ordinary scans can use the default
439
- - **Enable on demand**: turn it on for external or unknown content
440
- - **CI/CD**: recommended in CI pipelines to catch encoding attacks
441
-
442
- **Examples**
443
-
444
- ```bash
445
- # Base64-encoded API key
446
- echo "c2stcHJvai10ZXN0MTIzNDU2Nzg5MGFiY2RlZg==" | npm run scan -- --enable-encoding-detection --stdin
447
- # → Detects an OpenAI API Key (synthetic value)
251
+ ---
448
252
 
449
- # URL-encoded sensitive content
450
- echo "password%3Dsecret123" | npm run scan -- --enable-encoding-detection --stdin
451
- # → Detects the password keyword
253
+ ### Across hosts
452
254
 
453
- # Normal text is unaffected
454
- echo "This is safe content" | npm run scan -- --enable-encoding-detection --stdin
455
- # → Safe, no sensitive content
456
- ```
255
+ - [Host capability matrix](docs/host-capabilities.md): per-host declaration of which model egress and surfaces are protected, refused, absent, or outside interception, and the invariants a new adapter must satisfy
256
+ - [Agent hook coverage](docs/hooks.md): how OpenCode, pi and Claude Code expose hooks, and which hook points can mask a request or restore a placeholder
457
257
 
458
- When encoded content is found, the text and JSON summaries name the encoding types, in the language set by `LEAKSHIELD_LANG`:
258
+ #### Persistence risk notes (read before enabling)
459
259
 
460
- ```
461
- [WARNING: Encoded content: Base64, URL]
462
- ```
260
+ Mapping persistence is opt-in for the OpenCode plugin ([setup](docs/plugin/persistence.md)) and pi (`LEAKSHIELD_PI_PERSIST`, [setup](docs/pi.md#sessions-and-persistence)). The Claude Code proxy keeps mappings in memory only.
463
261
 
464
- #### Workspace Path Restriction
262
+ - The design is dual-secret — the DB file alone or the key alone exposes nothing; both together do.
263
+ - Backups (Time Machine, cloud sync) copy `SGP.db`: `forget` cannot reclaim what a backup already captured, and a restored backup plus a surviving key can re-identify old sessions — treat backup retention accordingly.
264
+ - The keychain defends offline file theft (stolen disk, stolen backups, a copied `SGP.db`); it does not defend malware already running inside your login session.
265
+ - The keyfile option lowers the bar to "both files from the same directory tree" and is intended for headless/server environments without a keychain service.
465
266
 
466
- By default, `--file` and `--dir` only accept paths **inside the current working directory**. Attempts to scan outside (e.g. `../shared.env` or `/etc/passwd`) will be rejected with an error.
267
+ ---
467
268
 
468
- To intentionally scan a path outside the workspace, pass `--allow-outside`:
269
+ ### CLI and Web UI
469
270
 
470
271
  ```bash
471
- npm run scan -- --file ../shared.env --allow-outside
272
+ leakshield --file ./src/config.ts # scan a file (also --text, --dir, --stdin)
273
+ leakshield --redact --file .env --out .env.redacted
274
+ leakshield --web # local browser UI at http://localhost:3000
472
275
  ```
473
276
 
474
- > ⚠️ Outside-workspace scanning is opt-in. Only use it when you explicitly need to scan a file that lives outside the project root.
475
-
476
- #### Ignore Directives
477
-
478
- The CLI and Web UI skip any line containing `leakshield-ignore`, `guard:skip`, `guard:ignore`, `sg-ignore`, `no-scan` or `skip-guard` (case-insensitive). A real secret on that line reports as `ALLOW`.
479
-
480
- > ⚠️ Anyone who can edit a scanned file can add a directive, so a CLI scan is not a gate against untrusted changes. The OpenCode plugin does not honor directives.
277
+ Exit codes: `0` = safe, `1` = findings, `2` = path error. Options, redaction, encoding detection, ignore directives, the REST API, the decision model and JSON fields: [CLI and Web UI](docs/cli.md).
481
278
 
482
279
  ---
483
280
 
484
- ### Web UI
485
-
486
- Start a local web server and use it in your browser:
487
-
488
- ```bash
489
- # Default port 3000
490
- npx tsx src/cli.ts --web
491
-
492
- # Custom port
493
- npx tsx src/cli.ts --web --port 3001
494
-
495
- # Built version
496
- node dist/cli.js --web --port 3001
497
- ```
498
-
499
- Open `http://localhost:3001` in your browser, paste content, and press **Scan** or `Ctrl+Enter`.
281
+ ## Configuration
500
282
 
501
- #### REST API
283
+ LeakShield loads the first config file it finds: `./config/guard.config.yaml`, then `config/guard.config.yaml` in the LeakShield directory (source builds only), then `~/.leakshield/guard.config.yaml`. With no file, the built-in defaults apply. The OpenCode plugin also accepts a `configPath` option. The repository does not ship a `config/guard.config.yaml`, and Git ignores one you create there, so your keywords stay local. To start a new file, copy [`config/guard.config.example.yaml`](config/guard.config.example.yaml) and add your own keywords and domains. Listing `nda_keywords` replaces the four defaults (`CONFIDENTIAL`, `INTERNAL ONLY`, `DO NOT SHARE`, `NDA`); the example keeps them.
502
284
 
503
- You can also call the API directly:
285
+ Without a checkout (npm or binary install), download the example into your home directory:
504
286
 
505
287
  ```bash
506
- # Scan text
507
- curl -s -X POST http://localhost:3001/scan \
508
- -H 'Content-Type: application/json' \
509
- -d '{"content": "sk-proj-test1234567890abcdef my_password=\"super_secret\""}' | jq
510
-
511
- # Response format
512
- {
513
- "decision": "CONFIRM",
514
- "riskLevel": "CRITICAL",
515
- "summary": "...",
516
- "findings": [
517
- { "type": "API_KEY", "severity": "HIGH", "description": "OpenAI API Key", "preview": "****", "line": 1 },
518
- { "type": "SECRET", "severity": "HIGH", "description": "...", "preview": "****", "line": 1 }
519
- ],
520
- "recommendedAction": "BLOCK",
521
- "redactedContent": "[REDACTED_API_KEY] my_[REDACTED_SECRET]",
522
- "redactionVerified": true,
523
- "residualFindings": 0,
524
- "wasTruncated": false
525
- }
526
- ```
527
-
528
- `redactedContent` is omitted when `redactionVerified` is `false`.
529
-
530
- | Endpoint | Method | Description |
531
- |----------|--------|-------------|
532
- | `/` | GET | Web UI HTML |
533
- | `/scan` | POST | Scan `{ "content": string }`, returns JSON |
534
-
535
- ---
536
-
537
- ## Configuration
538
-
539
- LeakShield loads the first config file it finds: `./config/guard.config.yaml`, then `config/guard.config.yaml` in the LeakShield directory (source builds only), then `~/.leakshield/guard.config.yaml`. With no file, the built-in defaults apply. The OpenCode plugin also accepts a `configPath` option. To start a new file, copy [`config/guard.config.example.yaml`](config/guard.config.example.yaml) and replace its sample keywords and domains.
540
-
541
- ```yaml
542
- # NDA keywords (case-insensitive)
543
- nda_keywords:
544
- - "CONFIDENTIAL"
545
- - "INTERNAL ONLY"
546
- - "DO NOT SHARE"
547
- - "NDA"
548
- - "PROPRIETARY"
549
- # Add your own internal keywords:
550
- # - "Project Phoenix"
551
- # - "MyCompany Internal"
552
-
553
- # Private domains
554
- private_domains:
555
- - "internal.mycompany.com"
556
- # - "dev.yourcompany.io"
557
-
558
- settings:
559
- max_chars: 200000 # scan bound; transparent mode refuses past it instead of truncating
560
- show_line_numbers: true
561
- preview_length: 60
562
- encoding_detection: false # Base64/URL/Hex decoding; off by default
288
+ mkdir -p ~/.leakshield
289
+ curl -fsSL https://raw.githubusercontent.com/jwcrystal/leakshield/main/config/guard.config.example.yaml \
290
+ -o ~/.leakshield/guard.config.yaml
291
+ leakshield --doctor # confirms the file loads
563
292
  ```
564
293
 
565
294
  After editing:
566
295
  - **CLI**: Reloaded automatically on next run
567
296
  - **OpenCode Plugin**: Restart OpenCode to reload the plugin configuration
297
+ - **pi extension**: Restart pi (`LEAKSHIELD_CONFIG` selects another file)
298
+ - **Claude Code proxy**: Restart the proxy (`--config` selects another file)
568
299
  - **Web UI**: Restart the local server
569
300
 
570
- ### Exact `.env` Value Detection
571
-
572
- Enable this only for files whose values should never enter an LLM context:
573
-
574
- ```yaml
575
- settings:
576
- env_files:
577
- - .env
578
- - .env.local
579
- ```
580
-
581
- Paths are relative to the workspace root and must remain inside it. LeakShield reads non-empty values of at least eight characters, then detects exact occurrences in text sent to the model. It does not automatically read `.env`, process environment variables, or send, log, or serialize the loaded values. Restart OpenCode after changing an enabled env file. The opt-in `envQueries` plugin tools (see [Readonly env queries](docs/plugin/env-queries.md)) query these same files and never return their values.
582
-
583
- ### Custom Rules
584
-
585
- ```yaml
586
- custom_rules:
587
- - description: "Company token"
588
- pattern: "MYCO_[A-Z0-9]{32}"
589
- severity: HIGH
590
- flags: "i" # subset of gimsuy; g is always implied
591
- word_boundary: true # \b only at literal ASCII word edges
592
- allow: # exact strings this rule never reports
593
- - "MYCO_EXAMPLE0000000000000000000000000"
594
- # path: ["src/**"] # accepted, but NOT implemented (see below)
595
-
596
- settings:
597
- allowlist: # exact strings no rule reports (see the bypass warning)
598
- - "qa@example.com"
599
- ```
600
-
601
- - **`flags`** — any subset of `gimsuy`; `g` is always added. The default is `i`, so
602
- existing rules keep matching case-insensitively. An unknown flag (such as `x`)
603
- fails the config load, and the pattern is compiled with the final flags, so a
604
- pattern that is only invalid under `u` also fails the load.
605
- Zero-length matches are skipped (they contain no value to report or redact);
606
- scanning continues to later nonempty matches, including under Unicode flags.
607
- - **`word_boundary`** — adds `\b` where the pattern's edge is a literal ASCII word
608
- character. A CJK edge (「機密」) is left alone: `\b` never holds between two
609
- non-word characters, and wrapping it would stop the rule matching. An edge that
610
- is a group, character class, quantifier or escape cannot take a boundary safely,
611
- so none is added and `--doctor` warns that the rule is looser than it looks —
612
- write `\b` in the pattern yourself, e.g. `\bEMP-\d{6}\b`. A top-level alternation
613
- (`a|b`) is a config error; group it as `(?:a|b)`.
614
- - **`allow` / `settings.allowlist`** — exact matches against the matched text, not
615
- substrings and not regexes. `allow` applies to that rule; `settings.allowlist`
616
- applies to every rule, including the built-in ones and exact `.env` values.
617
- Caps: 32 entries per rule, 64 globally, 200 characters each.
618
- **Allowlisting a live secret is a real bypass**: the value still leaves the
619
- machine unmasked, and LeakShield will not report that value as a rule or
620
- `.env` finding. Use it only for values you have decided are not sensitive.
621
- Unicode evasion diagnostics are separate: a zero-width or look-alike-letter
622
- warning means removing those characters exposes a finding the raw text hides,
623
- and an allowlist on the raw text does not silence it. Cyrillic or Greek text
624
- on its own is not flagged. `--doctor` reports how many entries exist, exercises up to eight
625
- of them, and reports how many it could not exercise (a context-dependent
626
- pattern can only be judged in place). Suppressions are counted rather than
627
- silent.
628
- - **`path`** — accepted and validated, but path scoping is **not implemented**: the
629
- scanner has no source path for prompts or tool output. These rules currently
630
- apply to every scanned text, and `--doctor` warns when `path` is set.
631
-
632
- Allowlist entries are part of the config file, so they change its fingerprint
633
- (sha256 of the file), which is what authorizations compare against.
301
+ Every key, the built-in rule ids, `.env` value detection, custom rules and limits: [Configuration reference](docs/configuration.md).
634
302
 
635
303
  ---
636
304
 
637
- ## Practical Examples
638
-
639
- ### Scenario 1: Asking OpenCode to review a config file
640
-
641
- With `mode: "block"`, shown below. In the v2 default, transparent mode, the model sees a placeholder instead and the task continues.
642
-
643
- ```
644
- You (to OpenCode): Please review this config.ts for issues
645
- OpenCode: [reads config.ts]
646
- → Tool output contains an API_KEY
647
- → Plugin replaces it before the next model turn
648
- → OpenCode receives a block notice instead of the secret
649
- You: Replace line 12 with a dummy key, then continue
650
- ```
651
-
652
- ### Scenario 2: CLI scan before submitting a project
653
-
654
- ```bash
655
- npm run scan -- --dir ./my-project
656
- # If exit code = 1, there are findings — fix them before sharing with AI
657
- ```
658
-
659
- ### Scenario 3: CI/CD integration (block sensitive prompts from the pipeline)
660
-
661
- ```bash
662
- # Add to your CI script
663
- node dist/cli.js --cli --dir ./prompts
664
- if [ $? -ne 0 ]; then
665
- echo "❌ Sensitive content detected — stopping pipeline"
666
- exit 1
667
- fi
668
- ```
669
-
670
- ---
671
-
672
- ## Configuration Validation
673
-
674
- Input lengths for dynamic rules are validated when the config is loaded:
675
-
676
- | Field | Max length |
677
- |-------|-----------|
678
- | `nda_keywords` entries | 200 characters |
679
- | `private_domains` entries | 255 characters |
680
- | `custom_rules` `description` / `pattern` | 200 characters |
681
-
682
- Values exceeding these limits will cause `loadConfig()` to throw a Zod validation error, preventing oversized patterns from entering the scanner.
683
-
684
- List sizes are capped too, and a config over a cap fails the load:
685
-
686
- | Field | Max entries |
687
- |-------|-------------|
688
- | `nda_keywords` | 4096 |
689
- | `private_domains` | 4096 |
690
- | `custom_rules` | 1024 |
691
-
692
- 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.
693
-
694
- ## Secret Preview Behavior
695
-
696
- 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.
697
-
698
- ## Internationalization (i18n)
699
-
700
- CLI output language is controlled by the `LEAKSHIELD_LANG` environment variable.
701
-
702
- | Value | Language |
703
- |-------|----------|
704
- | `en` (default) | English |
705
- | `zh-TW` or `zh` | Traditional Chinese |
706
-
707
- ```bash
708
- # English output (default)
709
- npm run scan -- --text "your content"
710
-
711
- # Traditional Chinese output
712
- LEAKSHIELD_LANG=zh-TW npm run scan -- --text "你的內容"
713
- ```
714
-
715
- You can also set it persistently in your shell profile:
716
-
717
- ```bash
718
- export LEAKSHIELD_LANG=zh-TW
719
- ```
305
+ ## Documentation
306
+
307
+ | Topic | Page |
308
+ |-------|------|
309
+ | OpenCode plugin | [docs/opencode.md](docs/opencode.md) |
310
+ | pi extension | [docs/pi.md](docs/pi.md) |
311
+ | Claude Code proxy | [docs/claude-code.md](docs/claude-code.md) |
312
+ | CLI and Web UI | [docs/cli.md](docs/cli.md) |
313
+ | Configuration reference | [docs/configuration.md](docs/configuration.md) |
314
+ | Host capability matrix | [docs/host-capabilities.md](docs/host-capabilities.md) |
315
+ | Standalone binary | [BINARY-GUIDE.md](BINARY-GUIDE.md) |
316
+ | Verification records | [docs/evidence](docs/evidence/README.md) |
317
+ | Contributing | [CONTRIBUTING.md](CONTRIBUTING.md) |
720
318
 
721
319
  ## Notes
722
320