leakshield 0.1.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +294 -173
- package/README.zh-TW.md +290 -164
- package/dist/config/loader.js +14 -10
- package/dist/config/plain-object.js +14 -0
- package/dist/decision/pseudonymization.js +133 -82
- package/dist/decision/redaction.js +2 -0
- package/dist/decision/value-search.js +250 -0
- package/dist/doctor.js +429 -138
- package/dist/i18n/en.js +4 -0
- package/dist/i18n/zh-TW.js +4 -0
- package/dist/index.js +3 -2
- package/dist/opencode-env-tools.js +0 -75
- package/dist/opencode-hooks.js +4 -73
- package/dist/opencode-transparent.js +582 -89
- package/dist/opencode.js +12 -54
- package/dist/plugin-options.js +15 -21
- package/dist/scanner/encoding.js +291 -7
- package/dist/scanner/engine.js +68 -40
- package/dist/scanner/utils.js +26 -2
- package/dist/transports/cli.js +2 -2
- package/dist/transports/web.js +3 -3
- package/dist/types.js +1 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -18,29 +18,76 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
|
|
|
18
18
|
|
|
19
19
|
| Mode | Start it with | Use it for |
|
|
20
20
|
|------|---------------|------------|
|
|
21
|
-
| OpenCode Plugin | Add the `
|
|
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 |
|
|
22
22
|
| 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
23
|
| Web UI | `npm run web` | Manual browser scans at `http://localhost:3000` |
|
|
24
24
|
|
|
25
25
|
## Project status
|
|
26
26
|
|
|
27
|
-
**Experimental,
|
|
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.
|
|
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
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
|
-
- Defaults may still change
|
|
31
|
+
- Defaults may still change during `0.x`; 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
|
|
|
34
34
|
---
|
|
35
35
|
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
Needs OpenCode v2 and Node.js 20 or later.
|
|
39
|
+
|
|
40
|
+
1. Install:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
npm install -g leakshield
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
2. Register the plugin in your project's `opencode.json`. With no options, `mode` defaults to `transparent`:
|
|
47
|
+
|
|
48
|
+
```jsonc
|
|
49
|
+
{
|
|
50
|
+
"$schema": "https://opencode.ai/config.json",
|
|
51
|
+
"plugins": [{ "package": "leakshield" }]
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
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.
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
leakshield --doctor
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
4. Run the smoke test. It uses a temporary directory and a synthetic value, not a real credential:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
SMOKE_DIR="$(mktemp -d)"
|
|
65
|
+
cat > "$SMOKE_DIR/opencode.json" <<'EOF'
|
|
66
|
+
{
|
|
67
|
+
"$schema": "https://opencode.ai/config.json",
|
|
68
|
+
"plugins": [{ "package": "leakshield", "options": { "mode": "block" } }]
|
|
69
|
+
}
|
|
70
|
+
EOF
|
|
71
|
+
(cd "$SMOKE_DIR" && opencode run --standalone \
|
|
72
|
+
"Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA")
|
|
73
|
+
rm -rf "$SMOKE_DIR"
|
|
74
|
+
```
|
|
75
|
+
|
|
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.
|
|
77
|
+
|
|
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).
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
36
82
|
## Detection Coverage
|
|
37
83
|
|
|
38
84
|
| Type | Description | Severity |
|
|
39
85
|
|------|-------------|----------|
|
|
40
|
-
| API Key | OpenAI, Anthropic, Google, AWS | 🔴 HIGH |
|
|
86
|
+
| API Key | OpenAI, Anthropic, Google, AWS, Stripe (live keys) | 🔴 HIGH |
|
|
41
87
|
| Secret / Password | Generic password assignments, AWS Secret | 🔴 HIGH |
|
|
42
|
-
| Token | GitHub
|
|
43
|
-
|
|
|
88
|
+
| Token | GitHub, Slack, Hugging Face, JWT, Bearer Token | 🔴 HIGH |
|
|
89
|
+
| Private Key | PEM private key blocks | 🔴 HIGH |
|
|
90
|
+
| DB Connection String | MongoDB, PostgreSQL, MySQL, Redis, ADO format, etc. | 🔴 HIGH |
|
|
44
91
|
| Taiwan National ID | Format validation | 🔴 HIGH |
|
|
45
92
|
| Credit Card Number | 13–19 digits, Luhn checksum required | 🔴 HIGH |
|
|
46
93
|
| IBAN | Compact or 4-char groups, mod-97 checksum required | 🔴 HIGH |
|
|
@@ -54,7 +101,7 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
|
|
|
54
101
|
| NDA Keywords | Custom (see `config/guard.config.yaml`) | 🔴 HIGH |
|
|
55
102
|
| Private Domains | Custom (see `config/guard.config.yaml`) | 🟡 MEDIUM |
|
|
56
103
|
|
|
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
|
|
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`.
|
|
58
105
|
|
|
59
106
|
---
|
|
60
107
|
|
|
@@ -77,6 +124,8 @@ The `CONFIRM` decision includes:
|
|
|
77
124
|
- `safePreview`: a masked excerpt around the first finding
|
|
78
125
|
- `redactedContent`: the full content with all sensitive spans replaced
|
|
79
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
|
+
|
|
80
129
|
### JSON Output Fields
|
|
81
130
|
|
|
82
131
|
When using `--format json`, the output includes these decision-oriented fields:
|
|
@@ -87,13 +136,26 @@ When using `--format json`, the output includes these decision-oriented fields:
|
|
|
87
136
|
| `riskLevel` | `LOW`, `MEDIUM`, `HIGH`, or `CRITICAL` |
|
|
88
137
|
| `recommendedAction` | `REVIEW` or `BLOCK` (CONFIRM only) |
|
|
89
138
|
| `findings` | Array of sanitized findings (no internal metadata) |
|
|
90
|
-
| `safePreview` | Masked excerpt (CONFIRM only) |
|
|
91
|
-
| `redactedContent` | Full redacted text (CONFIRM only) |
|
|
139
|
+
| `safePreview` | Masked excerpt (CONFIRM only; can be absent) |
|
|
140
|
+
| `redactedContent` | Full redacted text (CONFIRM only; can be absent) |
|
|
92
141
|
|
|
93
142
|
---
|
|
94
143
|
|
|
95
144
|
## Installation
|
|
96
145
|
|
|
146
|
+
Requires Node.js 20 or later. Mapping persistence needs 22.13 or later.
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
npm install -g leakshield
|
|
150
|
+
leakshield --help
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
`npx leakshield …` runs the published package without installing it. The npm
|
|
154
|
+
package ships only the compiled code, so it has no `config/` directory; see
|
|
155
|
+
[Configuration](#configuration) to add one.
|
|
156
|
+
|
|
157
|
+
To build from source:
|
|
158
|
+
|
|
97
159
|
```bash
|
|
98
160
|
git clone https://github.com/jwcrystal/leakshield.git
|
|
99
161
|
cd leakshield
|
|
@@ -101,9 +163,9 @@ npm install
|
|
|
101
163
|
npm run build
|
|
102
164
|
```
|
|
103
165
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
166
|
+
For local development, install the build globally or `npm link` it, then use
|
|
167
|
+
`leakshield` directly. `npm run scan -- ...` works from this repository without
|
|
168
|
+
installing.
|
|
107
169
|
|
|
108
170
|
### npm Scripts
|
|
109
171
|
|
|
@@ -149,9 +211,9 @@ bun build --compile --target=bun-windows-x64 ./src/cli.ts --outfile=leakshield.e
|
|
|
149
211
|
|
|
150
212
|
The output is a single executable — hand it to anyone, no dependencies required.
|
|
151
213
|
|
|
152
|
-
### Configuration for binary users
|
|
214
|
+
### Configuration for binary and npm users
|
|
153
215
|
|
|
154
|
-
The binary
|
|
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:
|
|
155
217
|
|
|
156
218
|
| Location | Scope |
|
|
157
219
|
|----------|-------|
|
|
@@ -159,9 +221,10 @@ The binary works out of the box with built-in defaults. To customize rules (NDA
|
|
|
159
221
|
| `~/.leakshield/guard.config.yaml` | All sessions (user home) |
|
|
160
222
|
|
|
161
223
|
```bash
|
|
162
|
-
# Quick start
|
|
224
|
+
# Quick start: copy config/guard.config.example.yaml from this repository,
|
|
225
|
+
# then replace its sample keywords and domains
|
|
163
226
|
mkdir -p ~/.leakshield
|
|
164
|
-
cp config/guard.config.yaml ~/.leakshield/
|
|
227
|
+
cp config/guard.config.example.yaml ~/.leakshield/guard.config.yaml
|
|
165
228
|
|
|
166
229
|
# Or per-project
|
|
167
230
|
mkdir -p ./config
|
|
@@ -174,6 +237,122 @@ See [Configuration](#configuration) section for available options.
|
|
|
174
237
|
|
|
175
238
|
## Usage
|
|
176
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.
|
|
243
|
+
|
|
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:
|
|
249
|
+
|
|
250
|
+
```jsonc
|
|
251
|
+
{
|
|
252
|
+
"$schema": "https://opencode.ai/config.json",
|
|
253
|
+
"plugins": [
|
|
254
|
+
{
|
|
255
|
+
"package": "leakshield" // or "/absolute/path/to/leakshield/dist"
|
|
256
|
+
// No options: mode defaults to "transparent" on v2.
|
|
257
|
+
// Add "options": { "mode": "block" } to refuse instead of pseudonymize.
|
|
258
|
+
}
|
|
259
|
+
]
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
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, shell argument restoration, 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.
|
|
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.
|
|
353
|
+
|
|
354
|
+
---
|
|
355
|
+
|
|
177
356
|
### CLI
|
|
178
357
|
|
|
179
358
|
```bash
|
|
@@ -217,7 +396,7 @@ Redacted output goes to **stdout**; the findings summary goes to **stderr** so t
|
|
|
217
396
|
|
|
218
397
|
| Flag | Behaviour |
|
|
219
398
|
|------|-----------|
|
|
220
|
-
| `--redact` | Replace findings with `[REDACTED_TYPE]`, write to stdout |
|
|
399
|
+
| `--redact` | Replace findings with `[REDACTED_TYPE]`, write to stdout; output is suppressed if findings remain after redaction |
|
|
221
400
|
| `--redact --dry-run` | Preview findings only, no output; exit `1` if any found |
|
|
222
401
|
| `--redact --out <path>` | Write redacted text to file instead of stdout |
|
|
223
402
|
| `--redact --format json` | Return JSON with `redacted`, `findings`, and `summary` fields |
|
|
@@ -229,6 +408,58 @@ Redacted output goes to **stdout**; the findings summary goes to **stderr** so t
|
|
|
229
408
|
| `--format json` | JSON output (CI/CD friendly) |
|
|
230
409
|
| `--min-severity high` | Only report HIGH (or `medium` / `low`) |
|
|
231
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
|
|
414
|
+
|
|
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)
|
|
448
|
+
|
|
449
|
+
# URL-encoded sensitive content
|
|
450
|
+
echo "password%3Dsecret123" | npm run scan -- --enable-encoding-detection --stdin
|
|
451
|
+
# → Detects the password keyword
|
|
452
|
+
|
|
453
|
+
# Normal text is unaffected
|
|
454
|
+
echo "This is safe content" | npm run scan -- --enable-encoding-detection --stdin
|
|
455
|
+
# → Safe, no sensitive content
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
When encoded content is found, the text and JSON summaries name the encoding types, in the language set by `LEAKSHIELD_LANG`:
|
|
459
|
+
|
|
460
|
+
```
|
|
461
|
+
[WARNING: Encoded content: Base64, URL]
|
|
462
|
+
```
|
|
232
463
|
|
|
233
464
|
#### Workspace Path Restriction
|
|
234
465
|
|
|
@@ -242,6 +473,12 @@ npm run scan -- --file ../shared.env --allow-outside
|
|
|
242
473
|
|
|
243
474
|
> ⚠️ Outside-workspace scanning is opt-in. Only use it when you explicitly need to scan a file that lives outside the project root.
|
|
244
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.
|
|
481
|
+
|
|
245
482
|
---
|
|
246
483
|
|
|
247
484
|
### Web UI
|
|
@@ -269,20 +506,27 @@ You can also call the API directly:
|
|
|
269
506
|
# Scan text
|
|
270
507
|
curl -s -X POST http://localhost:3001/scan \
|
|
271
508
|
-H 'Content-Type: application/json' \
|
|
272
|
-
-d '{"content": "sk-proj-
|
|
509
|
+
-d '{"content": "sk-proj-test1234567890abcdef my_password=\"super_secret\""}' | jq
|
|
273
510
|
|
|
274
511
|
# Response format
|
|
275
512
|
{
|
|
276
|
-
"
|
|
277
|
-
"
|
|
513
|
+
"decision": "CONFIRM",
|
|
514
|
+
"riskLevel": "CRITICAL",
|
|
515
|
+
"summary": "...",
|
|
278
516
|
"findings": [
|
|
279
|
-
{ "type": "API_KEY", "severity": "HIGH", "
|
|
517
|
+
{ "type": "API_KEY", "severity": "HIGH", "description": "OpenAI API Key", "preview": "****", "line": 1 },
|
|
518
|
+
{ "type": "SECRET", "severity": "HIGH", "description": "...", "preview": "****", "line": 1 }
|
|
280
519
|
],
|
|
281
|
-
"
|
|
282
|
-
"
|
|
520
|
+
"recommendedAction": "BLOCK",
|
|
521
|
+
"redactedContent": "[REDACTED_API_KEY] my_[REDACTED_SECRET]",
|
|
522
|
+
"redactionVerified": true,
|
|
523
|
+
"residualFindings": 0,
|
|
524
|
+
"wasTruncated": false
|
|
283
525
|
}
|
|
284
526
|
```
|
|
285
527
|
|
|
528
|
+
`redactedContent` is omitted when `redactionVerified` is `false`.
|
|
529
|
+
|
|
286
530
|
| Endpoint | Method | Description |
|
|
287
531
|
|----------|--------|-------------|
|
|
288
532
|
| `/` | GET | Web UI HTML |
|
|
@@ -290,155 +534,9 @@ curl -s -X POST http://localhost:3001/scan \
|
|
|
290
534
|
|
|
291
535
|
---
|
|
292
536
|
|
|
293
|
-
### OpenCode Plugin (recommended)
|
|
294
|
-
|
|
295
|
-
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. In transparent mode, schema annotation prose (a `description`/`title` value inside a tool input schema) that trips a scanner rule is masked to a pseudonym token like any other content; identifier positions (tool names, property keys, enum/const values, regex patterns) still refuse the whole request rather than being renamed.
|
|
296
|
-
|
|
297
|
-
The same compiled plugin supports both OpenCode major versions: v2 hosts load the package `id` + `setup(ctx)` definition, while v1 hosts (1.18.29+) call the legacy `server()` factory.
|
|
298
|
-
|
|
299
|
-
**OpenCode v2** — build the project, then point `plugins` at the `dist` directory (or use the package name after publishing to npm):
|
|
300
|
-
|
|
301
|
-
```jsonc
|
|
302
|
-
{
|
|
303
|
-
"$schema": "https://opencode.ai/config.json",
|
|
304
|
-
"plugins": [
|
|
305
|
-
{
|
|
306
|
-
"package": "/absolute/path/to/leakshield/dist"
|
|
307
|
-
// No options: mode defaults to "transparent" on v2.
|
|
308
|
-
// Add "options": { "mode": "block" } to refuse instead of pseudonymize.
|
|
309
|
-
}
|
|
310
|
-
]
|
|
311
|
-
}
|
|
312
|
-
```
|
|
313
|
-
|
|
314
|
-
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`.
|
|
315
|
-
|
|
316
|
-
**OpenCode v1 (1.18.29+)** — use the legacy `plugin` array with the compiled plugin file:
|
|
317
|
-
|
|
318
|
-
```json
|
|
319
|
-
{
|
|
320
|
-
"plugin": [
|
|
321
|
-
[
|
|
322
|
-
"file:///absolute/path/to/leakshield/dist/opencode.js",
|
|
323
|
-
{ "mode": "block" }
|
|
324
|
-
]
|
|
325
|
-
]
|
|
326
|
-
}
|
|
327
|
-
```
|
|
328
|
-
|
|
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.
|
|
330
|
-
|
|
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.
|
|
332
|
-
|
|
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).
|
|
334
|
-
|
|
335
|
-
**Final wire protection:** set `wireProtection: true` to additionally validate/remask the final HTTP request body or supported WS outbound frame content; unknown routes and unknown/mixed body shapes refuse before dispatch. Tool safety and reply-side recovery are identical in both levels. For compatibility, **omitting `wireProtection` retains this stronger legacy behavior**. With the v2 default (`mode: "transparent"`, `wireProtection` omitted) this stronger level is on; only the hook-first example chooses false explicitly. The option is valid only in transparent mode.
|
|
336
|
-
|
|
337
|
-
**AI SDK providers:** with `wireProtection: true`, providers must honor OpenCode's injected `options.fetch`; request-scoped HTTP hooks provide attribution and wire enforcement without a provider-brand allowlist. The wrapper checks HTTP/HTTPS and supported paths; missing/accessor/nonwritable fetch options refuse. With false, SG installs no SDK wrapper and imposes none of those transport requirements; only content/tool hooks and optional ingress restoration apply. Bypass transports are **outside final-wire coverage**, not guaranteed blocked. Commandcode `/alpha/generate`, including Go/403 fallback, is untouched in false and refused in true; there is no legacy response adapter. Arguments, abort signals and real provider failures remain host-owned.
|
|
338
|
-
|
|
339
|
-
In wire mode, the wrapper represents its route/content refusals as a **local HTTP 400 error response**, with `error.code: "leakshield_transport_refusal"` and a content-free WARN. Rejected requests do not reach the network. Hook-only has no such wrapper or transport admission. SDKs can distinguish a refusal from a retryable network failure; genuine network errors, aborts and provider responses remain unchanged. Responses easy-input messages may omit `type: "message"`; recognized roles and supported content are masked without inserting a type into their wire body.
|
|
340
|
-
|
|
341
|
-
**Reply-side recovery in both levels:** SG attribution or JSON/SSE/WS restoration failures stop SG rewriting rather than interrupting the host's response. Unattributed replies stay original; no session/model mapping is guessed. SSE keeps a bounded transaction of undelivered original events, releases them in order on failure, then passes subsequent bytes through without duplicates or dropped tails. Provider error events are released immediately; upstream errors and consumer cancellation still propagate. This can show literal placeholders, and invalid provider data may still fail in OpenCode. Tool arguments still pass the unchanged safety gate. WS can replace only one frame, not replay multiple held channels; see the documented WS limitations and [recovery evidence](docs/evidence/2026-10-11-experience-first-verification.md).
|
|
342
|
-
|
|
343
|
-
**Native WebSocket (experimental, Responses-family):** `/responses` over `ws:`/`wss:` accepts flat `response.create` frames, regardless of provider brand, and restores supported display deltas split across frames. Request masking reuses the HTTP Responses masker; function-call argument frames remain tokenized until the local tool gate, and encrypted reasoning stays opaque. Continuation IDs are preserved, not remasked. Different dialects/extensions are not automatically supported. OpenCode exposes no connection ID: state is isolated by session, request kind and model, then response ID and content channel. New handshakes/model switches, HTTP fallback, rejected frames and disposal invalidate old state; terminal frames release buffers. Frames, channels and aggregate buffering are bounded. A provider that omits the final text delta leaves a static warning: the complete `.done` text is restored without replacing that event with a synthetic delta, so delta-only consumers may show an incomplete reply. Unknown display tokens remain literal; unsafe or unknown write-tool mappings still refuse. The existing native OpenAI HTTP preference is retained for compatibility; explicit WS settings now work on supported routes. This is not a system network firewall or support for every WS provider. See [verification and limitations](docs/evidence/2026-10-11-responses-ws-verification.md).
|
|
344
|
-
|
|
345
|
-
**Shell argument restoration:** on macOS/Linux POSIX shells, a known placeholder may occupy a complete unquoted, single-quoted, or double-quoted argument. Existing quotes are preserved, and originals must be safe in that quote context; quoted space-containing values remain one argument. A single trailing `>`/`>>` redirect to a static literal filename is supported. Command/assignment positions, tokenized redirect filenames, expansions, quote concatenation, pipelines, inline scripts, quote-breaking originals, and leading-option values still refuse the affected tool call before mutation. Token-free commands are unchanged. The new quoting/redirect support is not enabled on Windows; it is not a general shell parser. Neither `wireProtection` setting changes this tool gate.
|
|
346
|
-
|
|
347
|
-
**Opt-in mapping persistence (W2, 2026-10-07):** set `"persistence": { "enabled": true }` in transparent mode to survive restarts — mappings persist encrypted (per-entry AES-256-GCM, AAD-bound) in a SQLite store (default `~/.local/share/leakshield/SGP.db`) and rehydrate on a session's first touch, so previously saved placeholders in resumed sessions keep restoring. Requires Node.js 22.13+ (built-in `node:sqlite`); on an older runtime the store cannot open and mappings stay memory-only with a WARN. Options: `ttlDays` (default 7; 0 = manual erasure only), `path` (store location), `keyFile`/`keyfilePath` (weaker fallback when no OS keychain exists). Key custody resolves down a ladder — OS keychain (macOS Keychain / Windows DPAPI / Linux libsecret) → explicit keyfile → memory-only degrade. Runtime logs report `persistence: active; key=os-keychain|keyfile` when the store opens successfully; later degradation emits a WARN. Missing keys do not directly refuse conversations, but an unsaved old token can still fail the tool gate. `--doctor` reports configuration/store readability as **unverified**, not runtime activation or decryptability, and never touches the real keychain. TTL cleanup runs when a writer opens the store, not on a timer; saving a changed mapping snapshot extends expiry, while reads do not. Seven days is not a hard deletion deadline. Persistence cannot recover mappings already lost before activation. Active erasure: `leakshield --forget --all` (or `--session <id>`) deletes persisted mappings, counts only in output. Erasure is logical plus in-file best effort (`secure_delete` zeroes freed pages, `forget --all` also vacuums and truncates the WAL); physical-media and backup residue (SSD wear leveling, snapshots, restores) are out of scope. Switching the key source after enabling (keychain ↔ keyfile) refuses to open the store — it degrades memory-only until `forget --all` resets — rather than silently re-keying history.
|
|
348
|
-
|
|
349
|
-
**Persistence risk notes (read before enabling):** the design is dual-secret — the DB file alone or the key alone exposes nothing; both together do. 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. 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. 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.
|
|
350
|
-
|
|
351
|
-
**Restart limitation in both levels:** replayed originals can establish new mappings, but old tokens cannot be reconstructed from token text. Some provider tool-call arguments remain tokenized when published to history, even though the local execution gate restores them before execution. Thus complete token-free history and seamless restart recovery are not established; an unresolved write/execute argument still refuses with no side effects. Local originals may remain in history, logs, and generated files — this protects the model boundary, not your disk.
|
|
352
|
-
|
|
353
|
-
**Transparent capacity and lifecycle:** the guard uses an 8 Mi UTF-16-unit combined input/output budget and 100,000 value nodes per protect/restore operation, rather than applying the standalone core's 1 Mi-unit budget to an entire history. HTTP bodies and WS frames retain their 4 MiB limits; scanner `max_chars`, depth 32, mapping-entry and aggregate mapping-memory caps remain enforced. Up to 4,096 sessions can be retained per guard instance; live mappings are never LRU-evicted to admit another session. The public V2 `session.deleted` event releases only that session's RAM, prepared-response proof and WS buffers. Idle, completed and interrupted sessions retain mappings for resume. Missing/failed lifecycle subscriptions retain mappings until unload, so capacity remains finite, not an unlimited-lifetime guarantee. Deletion does not erase encrypted persisted rows: TTL/explicit `forget` remain their retention policy. [Local verification and remaining live-test gap](docs/evidence/2026-10-14-transparent-capacity-verification.md).
|
|
354
|
-
|
|
355
|
-
**Native OpenAI transport:** wire mode retains an HTTP preference for native OpenAI providers; explicit provider configuration has higher precedence. Hook-only makes no provider transport transformation. Supported Responses-family WS ingress can restore display deltas without SG handshake/send registrations, starting from a validated `response.created` in a prepared session/kind/model scope. No endpoint, credential, or persisted configuration is changed. Real subscription authentication and complete restart recovery remain separate from local capture evidence.
|
|
356
|
-
|
|
357
|
-
**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.
|
|
358
|
-
|
|
359
|
-
```jsonc
|
|
360
|
-
{ "package": "/absolute/path/to/leakshield/dist", "options": { "mode": "redact", "deidentify": true } }
|
|
361
|
-
```
|
|
362
|
-
|
|
363
|
-
**Opt-in readonly env queries (both versions):** the `envQueries` option (default `false`) exposes three read-only tools over the files listed in `settings.env_files`, so an agent can answer configuration questions without ever seeing values. It does not work with transparent mode, so on v2 set `mode` to `block` or `redact` explicitly:
|
|
364
|
-
|
|
365
|
-
| Tool | Contract |
|
|
366
|
-
|---|---|
|
|
367
|
-
| `guard_env_list` | Opaque session-local file ids plus key names — never paths, values, lengths, or previews. |
|
|
368
|
-
| `guard_env_inspect(file_id, key)` | `missing` \| `empty` \| `nonempty`; when nonempty, a coarse lexical shape `boolean_like` \| `number_like` \| `multiline_text` \| `text`. A shape is a lexical hint, never a claim the value is a valid boolean or number. |
|
|
369
|
-
| `guard_env_compare(left_file_id, left_key, right_file_id, right_key)` | `equal` \| `different` \| `unavailable` for key-to-key, same- or cross-file equality. Missing keys and unreadable files are `unavailable`. |
|
|
370
|
-
|
|
371
|
-
```jsonc
|
|
372
|
-
{ "package": "/absolute/path/to/leakshield/dist", "options": { "mode": "block", "envQueries": true } }
|
|
373
|
-
```
|
|
374
|
-
|
|
375
|
-
Ground rules: only `settings.env_files` entries are queryable (at most 16 files, 1 MiB each). File ids are only valid in the session that listed them. Files are re-read on every call, and a comparison reads both operands in one per-call snapshot. Raw values, value lengths, previews, fingerprints, and reverse mappings never appear in any output. If the guard configuration file changes after setup, the tools return a fixed restart-required error until OpenCode restarts — they never silently fall back to the old or new authorization.
|
|
376
|
-
|
|
377
|
-
File access is best-effort pathname identity validation, not a sandbox. The workspace root is frozen at setup (resolved path plus device/inode identity); every query re-stats the root and each ancestor directory before opening and again after reading, rejects symlinks on any path component — including ancestor directories that resolve elsewhere, even inside the workspace — requires regular files, opens the fully resolved canonical path with `O_NOFOLLOW` and `O_NONBLOCK`, and binds the opened descriptor to the statted inode with pre- and post-read size and mtime checks. Limitations, stated honestly: malicious concurrent filesystem mutation by the same owner is outside this threat model — a substitution that is reverted between two checks (an ABA race on the root, an ancestor directory, or the file) is not detectable by pathname checks, hardlinks are not distinguished from the original file (provenance is not checked), in-place rewrites that preserve size and mtime are not distinguishable, and the agent can modify env files through other tools — so results describe the current file state, not a trusted baseline. Key names themselves are returned as-is and pass through the normal output/history protection. On OpenCode v1 the tools are registered through the standard v1 tool API (`@opencode-ai/plugin`), which the v1 host provides.
|
|
378
|
-
|
|
379
|
-
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 above; 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.
|
|
380
|
-
|
|
381
|
-
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.
|
|
382
|
-
|
|
383
|
-
#### Isolated smoke test (OpenCode v2)
|
|
384
|
-
|
|
385
|
-
Run this from the project root. It uses a temporary working directory and a synthetic value, not a real credential:
|
|
386
|
-
|
|
387
|
-
```bash
|
|
388
|
-
npm run build
|
|
389
|
-
SMOKE_DIR="$(mktemp -d)"
|
|
390
|
-
PROJECT_DIR="$(pwd)"
|
|
391
|
-
cat > "$SMOKE_DIR/opencode.json" <<EOF
|
|
392
|
-
{
|
|
393
|
-
"$schema": "https://opencode.ai/config.json",
|
|
394
|
-
"plugins": [
|
|
395
|
-
{ "package": "$PROJECT_DIR/dist", "options": { "mode": "block" } }
|
|
396
|
-
]
|
|
397
|
-
}
|
|
398
|
-
EOF
|
|
399
|
-
(cd "$SMOKE_DIR" && opencode run --standalone \
|
|
400
|
-
"Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA")
|
|
401
|
-
rm -rf "$SMOKE_DIR"
|
|
402
|
-
```
|
|
403
|
-
|
|
404
|
-
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.
|
|
405
|
-
|
|
406
|
-
After publishing to npm, the same plugin can be configured as `"leakshield"` instead of the local `dist` path.
|
|
407
|
-
|
|
408
|
-
#### Automated install check: `--doctor`
|
|
409
|
-
|
|
410
|
-
```bash
|
|
411
|
-
npm run scan -- --doctor # or: leakshield --doctor after global install
|
|
412
|
-
```
|
|
413
|
-
|
|
414
|
-
The doctor verifies the install without sending anything anywhere: it checks the OpenCode host version, finds `opencode.json` (workspace then global), 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` (v2) or `PARTIAL` (v1: session hooks only); any other status prints the failing check with a concrete fix, including a copy-paste registration snippet when the plugin is missing.
|
|
415
|
-
|
|
416
|
-
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`.
|
|
417
|
-
|
|
418
|
-
### What this protects — and what it does not
|
|
419
|
-
|
|
420
|
-
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.
|
|
421
|
-
|
|
422
|
-
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).
|
|
423
|
-
|
|
424
|
-
---
|
|
425
|
-
|
|
426
537
|
## Configuration
|
|
427
538
|
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
### Exact `.env` Value Detection
|
|
431
|
-
|
|
432
|
-
Enable this only for files whose values should never enter an LLM context:
|
|
433
|
-
|
|
434
|
-
```yaml
|
|
435
|
-
settings:
|
|
436
|
-
env_files:
|
|
437
|
-
- .env
|
|
438
|
-
- .env.local
|
|
439
|
-
```
|
|
440
|
-
|
|
441
|
-
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 OpenCode Plugin) query these same files and never return their values.
|
|
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.
|
|
442
540
|
|
|
443
541
|
```yaml
|
|
444
542
|
# NDA keywords (case-insensitive)
|
|
@@ -458,9 +556,10 @@ private_domains:
|
|
|
458
556
|
# - "dev.yourcompany.io"
|
|
459
557
|
|
|
460
558
|
settings:
|
|
461
|
-
max_chars: 200000 #
|
|
559
|
+
max_chars: 200000 # scan bound; transparent mode refuses past it instead of truncating
|
|
462
560
|
show_line_numbers: true
|
|
463
561
|
preview_length: 60
|
|
562
|
+
encoding_detection: false # Base64/URL/Hex decoding; off by default
|
|
464
563
|
```
|
|
465
564
|
|
|
466
565
|
After editing:
|
|
@@ -468,6 +567,19 @@ After editing:
|
|
|
468
567
|
- **OpenCode Plugin**: Restart OpenCode to reload the plugin configuration
|
|
469
568
|
- **Web UI**: Restart the local server
|
|
470
569
|
|
|
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
|
+
|
|
471
583
|
### Custom Rules
|
|
472
584
|
|
|
473
585
|
```yaml
|
|
@@ -526,6 +638,8 @@ Allowlist entries are part of the config file, so they change its fingerprint
|
|
|
526
638
|
|
|
527
639
|
### Scenario 1: Asking OpenCode to review a config file
|
|
528
640
|
|
|
641
|
+
With `mode: "block"`, shown below. In the v2 default, transparent mode, the model sees a placeholder instead and the task continues.
|
|
642
|
+
|
|
529
643
|
```
|
|
530
644
|
You (to OpenCode): Please review this config.ts for issues
|
|
531
645
|
OpenCode: [reads config.ts]
|
|
@@ -563,11 +677,18 @@ Input lengths for dynamic rules are validated when the config is loaded:
|
|
|
563
677
|
|-------|-----------|
|
|
564
678
|
| `nda_keywords` entries | 200 characters |
|
|
565
679
|
| `private_domains` entries | 255 characters |
|
|
566
|
-
|
|
567
680
|
| `custom_rules` `description` / `pattern` | 200 characters |
|
|
568
681
|
|
|
569
682
|
Values exceeding these limits will cause `loadConfig()` to throw a Zod validation error, preventing oversized patterns from entering the scanner.
|
|
570
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
|
+
|
|
571
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.
|
|
572
693
|
|
|
573
694
|
## Secret Preview Behavior
|
|
@@ -600,6 +721,6 @@ export LEAKSHIELD_LANG=zh-TW
|
|
|
600
721
|
## Notes
|
|
601
722
|
|
|
602
723
|
- This tool performs **static pattern matching** and cannot guarantee 100% coverage
|
|
603
|
-
- **Common false positives**: test
|
|
724
|
+
- **Common false positives**: literal test values long enough to match (e.g. `password: "aaaaaaaa"`), placeholder values in example code
|
|
604
725
|
- The tool is meant to **warn**, not guarantee — final judgment is always yours
|
|
605
726
|
- Keep NDA keywords focused on truly confidential terms to avoid excessive false positives
|