leakshield 0.3.1 → 0.4.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 (108) hide show
  1. package/README.md +35 -5
  2. package/README.zh-TW.md +34 -5
  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} +16 -42
  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} +7 -7
  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 +66 -0
  25. package/dist/adapters/opencode/transparent.js +237 -0
  26. package/dist/adapters/opencode/v2.d.ts +20 -0
  27. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  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/plain-object.d.ts +2 -0
  46. package/dist/core/index.d.ts +9 -0
  47. package/dist/core/index.js +9 -0
  48. package/dist/core/session-guard.d.ts +61 -0
  49. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  50. package/dist/core/sse-recovery.d.ts +6 -0
  51. package/dist/core/tool-restore-policy.d.ts +153 -0
  52. package/dist/core/tool-restore-policy.js +453 -0
  53. package/dist/core/wire.d.ts +213 -0
  54. package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
  55. package/dist/core/ws.d.ts +26 -0
  56. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  57. package/dist/decision/deidentify.d.ts +63 -0
  58. package/dist/decision/ingress.d.ts +40 -0
  59. package/dist/decision/mapping-key.d.ts +91 -0
  60. package/dist/decision/mapping-store.d.ts +166 -0
  61. package/dist/decision/model.d.ts +41 -0
  62. package/dist/decision/pseudonymization.d.ts +176 -0
  63. package/dist/decision/redaction.d.ts +56 -0
  64. package/dist/decision/schema-strings.d.ts +23 -0
  65. package/dist/decision/schema-strings.js +2 -2
  66. package/dist/decision/value-search.d.ts +39 -0
  67. package/dist/doctor-capabilities.d.ts +21 -0
  68. package/dist/doctor-capabilities.js +58 -0
  69. package/dist/doctor-hosts.d.ts +18 -0
  70. package/dist/doctor-hosts.js +144 -0
  71. package/dist/doctor-report.d.ts +45 -0
  72. package/dist/doctor-report.js +111 -0
  73. package/dist/forget.d.ts +18 -0
  74. package/dist/guard-options.d.ts +45 -0
  75. package/dist/{plugin-options.js → guard-options.js} +4 -1
  76. package/dist/help.d.ts +2 -0
  77. package/dist/help.js +15 -1
  78. package/dist/i18n/en.d.ts +65 -0
  79. package/dist/i18n/index.d.ts +15 -0
  80. package/dist/i18n/zh-TW.d.ts +65 -0
  81. package/dist/index.d.ts +13 -0
  82. package/dist/index.js +1 -1
  83. package/dist/rules/builtin.d.ts +4 -0
  84. package/dist/rules/dynamic.d.ts +33 -0
  85. package/dist/scanner/allowlist.d.ts +22 -0
  86. package/dist/scanner/cidr.d.ts +39 -0
  87. package/dist/scanner/encoding.d.ts +87 -0
  88. package/dist/scanner/engine.d.ts +43 -0
  89. package/dist/scanner/exact-values.d.ts +11 -0
  90. package/dist/scanner/redaction-verifier.d.ts +24 -0
  91. package/dist/scanner/remotes.d.ts +29 -0
  92. package/dist/scanner/unicode.d.ts +57 -0
  93. package/dist/scanner/utils.d.ts +22 -0
  94. package/dist/transports/cli.d.ts +27 -0
  95. package/dist/transports/web-ui.d.ts +1 -0
  96. package/dist/transports/web-ui.js +1 -1
  97. package/dist/transports/web.d.ts +4 -0
  98. package/dist/types/capabilities.d.ts +67 -0
  99. package/dist/types/capabilities.js +133 -0
  100. package/dist/types.d.ts +149 -0
  101. package/dist/utils/files.d.ts +3 -0
  102. package/dist/utils/path-security.d.ts +18 -0
  103. package/dist/utils/win-encoding.d.ts +16 -0
  104. package/package.json +11 -3
  105. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  106. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  107. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  108. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
package/README.md CHANGED
@@ -9,8 +9,9 @@
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:
12
+ Four supported modes:
13
13
  - **OpenCode Plugin**: The enforced ingress gate for OpenCode. Use this when OpenCode sends content to a model.
14
+ - **pi adapter**: An in-process pi extension that guards the agent's provider requests through the shared wire core.
14
15
  - **CLI**: Manual or CI scanning of text, files, and directories; supports redaction.
15
16
  - **Web UI**: Local browser interface and REST endpoint for manual scanning.
16
17
 
@@ -19,6 +20,7 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
19
20
  | Mode | Start it with | Use it for |
20
21
  |------|---------------|------------|
21
22
  | 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 |
23
+ | pi adapter | `pi install /absolute/path/to/built/leakshield` (next npm release: `pi install npm:leakshield`; [setup](docs/pi.md)) | Masked pi provider requests and restored read/write/edit/bash arguments |
22
24
  | 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
25
  | Web UI | `npm run web` | Manual browser scans at `http://localhost:3000` |
24
26
 
@@ -27,6 +29,8 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
27
29
  **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
30
 
29
31
  - 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.
32
+ - Claude Code is supported through 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).
33
+ - pi is supported through an in-process extension that 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).
30
34
  - 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
35
  - Defaults may still change during `0.x`; see the [changelog](CHANGELOG.md).
32
36
  - Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [Apache-2.0](LICENSE).
@@ -266,12 +270,14 @@ The default `mode` is **`transparent`** (see [Transparent mode](docs/plugin/tran
266
270
 
267
271
  #### What `PARTIAL` means
268
272
 
269
- `leakshield --doctor` exits 0 for two statuses. They are install-level results, not a guarantee that nothing sensitive reaches a model.
273
+ `leakshield --doctor` exits 0 for two statuses. They are install-level results, not a guarantee that nothing sensitive reaches a model. Pass `--doctor opencode`, `--doctor claude-code` or `--doctor pi` (also `--doctor=<host>`) to check one host with its own exit code.
270
274
 
271
275
  | Status | Setup | Meaning |
272
276
  |--------|-------|---------|
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 |
277
+ | `PROTECTED` | `block` or `redact`, or transparent with `wireProtection` omitted or `true` (the v2 default), and every declared capability row covered | Install-level checks pass. In transparent mode, the final HTTP body or supported WS frame is validated too |
278
+ | `PARTIAL` | Transparent with `wireProtection: false` ([hook-first example](config/opencode.hook-first.example.json)), or a host whose [declared capability rows](docs/host-capabilities.md) include `unknown` or `outside` | Final outbound HTTP bodies are not inspected, or a declared egress is not covered; the doctor names the row and the issue that closes it |
279
+
280
+ Doctor prints `Configuration status` and `Wire protection` separately from host-wide `Coverage`. `Wire protection: enabled` describes the validated configuration, not proof of interception in a live session; block mode reports `not-applicable`, and an unknown configuration reports `unknown`. A `PARTIAL` verdict lists configuration and host-coverage reasons separately, including both when both apply. Host coverage is not filtered to your selected provider/model. Each host section also prints its declared credential handling, mapping-persistence policy and complete residual list; `opt-in` describes persistence support, not whether it is enabled in your install.
275
281
 
276
282
  With `PARTIAL`:
277
283
 
@@ -288,6 +294,7 @@ See [Wire protection](docs/plugin/wire-protection.md) for both levels.
288
294
  - [Mapping persistence](docs/plugin/persistence.md): opt-in encrypted storage, key custody, erasure
289
295
  - [Capacity and lifecycle](docs/plugin/capacity.md): budgets, session limits, retention
290
296
  - [Readonly env queries](docs/plugin/env-queries.md): opt-in tools that answer configuration questions without returning values
297
+ - [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
291
298
 
292
299
  #### Persistence risk notes (read before enabling)
293
300
 
@@ -339,7 +346,7 @@ To test the published package, use `"leakshield"` instead of the local `dist` pa
339
346
  npm run scan -- --doctor # or: leakshield --doctor after global install
340
347
  ```
341
348
 
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.
349
+ 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. Each host section is followed by the capability rows that host declares ([matrix](docs/host-capabilities.md)): an `unknown` or `outside` row keeps that host at `PARTIAL` and names the issue that closes it. 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. A separate `Claude Code:` section checks the [Claude Code proxy](docs/claude-code.md) wiring; the exit code is also 0 when Claude Code is behind a running LeakShield proxy, even without OpenCode.
343
350
 
344
351
  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
352
 
@@ -353,6 +360,29 @@ Local originals may remain in history, logs, and generated files — this protec
353
360
 
354
361
  ---
355
362
 
363
+ ### Claude Code (local proxy)
364
+
365
+ ```bash
366
+ leakshield --claude-code-proxy # listens on 127.0.0.1:8787
367
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:8787 # or the "env" block of ~/.claude/settings.json
368
+ leakshield --doctor # the "Claude Code:" section checks the wiring
369
+ ```
370
+
371
+ 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).
372
+
373
+ ---
374
+
375
+ ### pi (in-process extension)
376
+
377
+ ```bash
378
+ pi -e /path/to/node_modules/leakshield/dist/adapters/pi/extension.js # load it first
379
+ leakshield --doctor pi # checks registration, order and wire API
380
+ ```
381
+
382
+ 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 the extension has to load first. See [pi adapter](docs/pi.md).
383
+
384
+ ---
385
+
356
386
  ### CLI
357
387
 
358
388
  ```bash
package/README.zh-TW.md CHANGED
@@ -9,8 +9,9 @@
9
9
 
10
10
  **在把程式碼、文件、資料丟給 AI 服務之前,先掃描敏感內容的守門員。**
11
11
 
12
- 支援三種使用模式:
12
+ 支援四種使用模式:
13
13
  - **OpenCode Plugin**:OpenCode 的強制入口檢查;OpenCode 要把內容送往模型時使用。
14
+ - **pi adapter**:行程內的 pi extension,用共用 wire core 守住 agent 的 provider 請求。
14
15
  - **CLI**:手動或 CI 掃描文字、檔案與目錄;支援脫敏。
15
16
  - **Web UI**:本機瀏覽器介面與 REST endpoint,供手動掃描。
16
17
 
@@ -19,6 +20,7 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
19
20
  | 模式 | 啟動方式 | 適用情境 |
20
21
  |------|----------|----------|
21
22
  | OpenCode Plugin | 在 `opencode.json` 加入 `leakshield` 套件或 `dist` 目錄(OpenCode v2) | 自動且 fail-closed 地保護 OpenCode 模型輸入與工具輸出 |
23
+ | pi adapter | `pi install /absolute/path/to/built/leakshield`(下一版 npm:`pi install npm:leakshield`;[安裝說明](docs/pi.zh-TW.md)) | 遮罩 pi 的 provider 請求並還原 read/write/edit/bash 參數 |
22
24
  | CLI | `npm run scan -- --file ./path`(全域安裝或 `npm link` 後可用 `leakshield --file ./path`) | 明確的本機或 CI 掃描;不會把內容送到模型 |
23
25
  | Web UI | `npm run web` | 在 `http://localhost:3000` 手動以瀏覽器掃描 |
24
26
 
@@ -27,6 +29,8 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
27
29
  **實驗性,`0.x` 版本。** 已發佈到 npm(`leakshield`):可用 `npx leakshield --help` 查看指令,或在本機建置(`npm ci && npm run build`)再讓 OpenCode 指向 `dist` 目錄。沒有參數也沒有輸入時,CLI 會等待 stdin。
28
30
 
29
31
  - Transparent 模式已在 OpenCode v2.0.28 搭配本機替身 provider 驗證,並用真實 OpenAI 模型驗證過一次。0.3.0 的工具還原另在 OpenCode v2.2.5 用本機替身 provider、OpenChamber 的 render 工具與 `rtk` 重新驗證([紀錄](docs/evidence/2026-11-06-opencode-2.2.5-tool-restoration.md))。它**不保證**敏感內容絕不會送到模型:建議的 hook-first 設定在 `--doctor` 顯示為 `PARTIAL`,hook 之後才加入的內容,以及被允許的工具外送(curl、遠端 MCP),都不在保護範圍內。
32
+ - Claude Code 透過本機 proxy 支援(`leakshield --claude-code-proxy`,再設定 `ANTHROPIC_BASE_URL`),已用 Claude Code 2.1.321 搭配本機替身上游驗證([紀錄](docs/evidence/2026-11-21-claude-code-proxy.md))。它會遮罩模型請求並還原助理文字,但還不會在工具執行時還原 placeholder,詳見 [Claude Code](docs/claude-code.zh-TW.md)。
33
+ - pi 透過行程內 extension 支援:包住 agent 的 `fetch`,遮罩它支援的三種 wire API,並在本機還原 read/write/edit/bash 參數。已用 pi 1.6.0 搭配錄製替身上游驗證([紀錄](docs/evidence/2026-11-23-pi-extension.md));不經 fetch 的 provider(Codex WebSocket、Bedrock)會被拒絕,只有 OAuth 的帳號不支援。詳見 [pi adapter](docs/pi.zh-TW.md)。
30
34
  - 尚未驗證:Windows 與 Linux 的 OS keychain 持久化(macOS 已於 2026-10-20 驗證)、真實 Anthropic provider、其他 provider 的長對話、長時間使用([#26](https://github.com/jwcrystal/leakshield/issues/26))。
31
35
  - `0.x` 期間預設值仍可能調整,變更見 [CHANGELOG](CHANGELOG.md)。
32
36
  - 驗證紀錄:[docs/evidence](docs/evidence/README.md)。漏洞請私下回報:[SECURITY.md](SECURITY.md)。授權:[Apache-2.0](LICENSE)。
@@ -262,12 +266,14 @@ LeakShield 只支援 OpenCode v2:v2 載入套件的 `id` + `setup(ctx)` 定義
262
266
 
263
267
  #### `PARTIAL` 的意思
264
268
 
265
- `leakshield --doctor` 在兩種狀態下 exit 0。它們是安裝層的結果,不保證敏感內容絕不會送到模型。
269
+ `leakshield --doctor` 在兩種狀態下 exit 0。它們是安裝層的結果,不保證敏感內容絕不會送到模型。可用 `--doctor opencode`、`--doctor claude-code` 或 `--doctor pi`(也支援 `--doctor=<host>`)只檢查單一 host,exit code 只反映它。
266
270
 
267
271
  | 狀態 | 設定 | 意思 |
268
272
  |------|------|------|
269
- | `PROTECTED` | `block` 或 `redact`,或 transparent 且 `wireProtection` 省略或為 `true`(v2 預設) | 安裝層檢查通過。transparent 模式下也會驗證最終的 HTTP body 或支援的 WS frame |
270
- | `PARTIAL` | Transparent 且 `wireProtection: false`([hook-first 範本](config/opencode.hook-first.example.json)) | 不檢查最終出站 HTTP body |
273
+ | `PROTECTED` | `block` 或 `redact`,或 transparent 且 `wireProtection` 省略或為 `true`(v2 預設),且每個已宣告的 capability 列都被覆蓋 | 安裝層檢查通過。transparent 模式下也會驗證最終的 HTTP body 或支援的 WS frame |
274
+ | `PARTIAL` | Transparent 且 `wireProtection: false`([hook-first 範本](config/opencode.hook-first.example.json)),或該 host 的[已宣告 capability 列](docs/host-capabilities.md)包含 `unknown` 或 `outside` | 不檢查最終出站 HTTP body,或某條已宣告的出口沒有覆蓋;doctor 會指名該列與關閉它的 issue |
275
+
276
+ Doctor 會分開印出 `Configuration status`、`Wire protection` 與宿主整體的 `Coverage`。`Wire protection: enabled` 代表已驗證的設定,不是執行中 session 已成功攔截的證明;block 模式顯示 `not-applicable`,設定尚不明確時顯示 `unknown`。`PARTIAL` 會分別列出設定與宿主覆蓋的原因,兩者同時存在時都會印出。宿主覆蓋不依目前選擇的 provider/model 篩選。每個宿主區段也會印出宣告的憑證處理方式、映射持久化政策與完整 residuals;`opt-in` 表示支援選用持久化,不代表本次安裝已啟用。
271
277
 
272
278
  `PARTIAL` 時:
273
279
 
@@ -335,7 +341,7 @@ rm -rf "$SMOKE_DIR"
335
341
  leakshield --doctor # 全域安裝或 npm link 後;在 repo 內可用 npm run scan -- --doctor
336
342
  ```
337
343
 
338
- Doctor 不會把任何內容送出去。它會檢查 OpenCode host 版本、讀取 OpenCode 會套用的 `opencode.json` 或 `opencode.jsonc`(`.opencode/`、專案根目錄和一個全域目錄)、依 host 的方式合併其中的 `plugins` 陣列、確認 LeakShield 已用 plugin 本身接受的選項註冊、確認本機 `dist` 進入點真的存在(缺少時 OpenCode 會靜默記錄並跳過 plugin:session 看起來正常但沒有保護)、載入 guard 設定,並在本機跑合成 canary 的 smoke scan。Exit code 0 代表 `PROTECTED` 或 `PARTIAL`(`wireProtection: false`:不檢查最終出站 HTTP body);v1 host 會回報 `BROKEN`,修正方式是升級到 OpenCode v2;其他狀態會印出失敗的檢查項與具體修正方式,plugin 未註冊時還會附上可直接複製的註冊片段。
344
+ Doctor 不會把任何內容送出去。它會檢查 OpenCode host 版本、讀取 OpenCode 會套用的 `opencode.json` 或 `opencode.jsonc`(`.opencode/`、專案根目錄和一個全域目錄)、依 host 的方式合併其中的 `plugins` 陣列、確認 LeakShield 已用 plugin 本身接受的選項註冊、確認本機 `dist` 進入點真的存在(缺少時 OpenCode 會靜默記錄並跳過 plugin:session 看起來正常但沒有保護)、載入 guard 設定,並在本機跑合成 canary 的 smoke scan。每個 host 區段後面會印出該 host 宣告的 capability 列([總表](docs/host-capabilities.md));`unknown` 或 `outside` 會讓該 host 停在 `PARTIAL`,並指名關閉它的 issue。Exit code 0 代表 `PROTECTED` 或 `PARTIAL`(`wireProtection: false`:不檢查最終出站 HTTP body);v1 host 會回報 `BROKEN`,修正方式是升級到 OpenCode v2;其他狀態會印出失敗的檢查項與具體修正方式,plugin 未註冊時還會附上可直接複製的註冊片段。另有 `Claude Code:` 區段檢查 [Claude Code proxy](docs/claude-code.zh-TW.md) 的設定;即使沒有 OpenCode,只要 Claude Code 經過執行中的 LeakShield proxy,結束碼也是 0。
339
345
 
340
346
  Doctor 是在 host 之外執行的安裝層檢查,看不到執行中的 session。執行期的證明來自上面的 smoke test 或 `scripts/e2e/run-boundary.mjs`。
341
347
 
@@ -349,6 +355,29 @@ LeakShield 保護送往模型的對話內容:prompt、重播的歷史、工具
349
355
 
350
356
  ---
351
357
 
358
+ ### Claude Code(本機 proxy)
359
+
360
+ ```bash
361
+ leakshield --claude-code-proxy # 監聽 127.0.0.1:8787
362
+ export ANTHROPIC_BASE_URL=http://127.0.0.1:8787 # 或寫進 ~/.claude/settings.json 的 "env"
363
+ leakshield --doctor # "Claude Code:" 區段會檢查設定
364
+ ```
365
+
366
+ Proxy 會遮罩 Claude Code 送出的每個 Anthropic Messages 請求(含 `count_tokens`),還原助理 JSON 或串流文字中的 placeholder,無法遮罩的請求直接擋下,不會轉送。已用 API key 驗證;Claude Code 文件說 base URL 也適用於 claude.ai 登入,這裡尚未測試。它不會還原工具呼叫裡的 placeholder,也看不到繞過 base URL 的流量,例如 WebFetch 的網域檢查會把 hostname 送給 Anthropic。設定方式與完整的缺口清單見 [docs/claude-code.zh-TW.md](docs/claude-code.zh-TW.md)。
367
+
368
+ ---
369
+
370
+ ### pi(行程內 extension)
371
+
372
+ ```bash
373
+ pi -e /path/to/node_modules/leakshield/dist/adapters/pi/extension.js # 第一個載入
374
+ leakshield --doctor pi # 檢查註冊、順序與 wire API
375
+ ```
376
+
377
+ pi 在建立 provider client 時才解析 `fetch`,compaction 與 branch summary 也一樣,所以包住 `globalThis.fetch` 的 extension 涵蓋的流量,與 OpenCode plugin 的 wire hook 相同。每個 provider 請求都在行程內遮罩;助理文字在回覆中還原,`read`、`write`、`edit`、`bash`、`powershell` 的參數在工具執行邊界還原。session 檔留在 pi 原本的位置,`--continue`、`--resume`、`--session` 照常運作。已用 pi 1.6.0 搭配錄製替身驗證;不經 fetch 的 provider(Codex WebSocket、Bedrock、Google auth)會被拒絕,不支援只有 OAuth 的帳號,而且 extension 必須先載入。詳見 [pi adapter](docs/pi.zh-TW.md)。
378
+
379
+ ---
380
+
352
381
  ### CLI
353
382
 
354
383
  ```bash
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Claude Code's declared coverage, printed by `leakshield --doctor`.
3
+ *
4
+ * The proxy routes by endpoint, so every Messages request that reaches
5
+ * ANTHROPIC_BASE_URL is masked regardless of why Claude Code sent it. Traffic
6
+ * that never reaches the base URL (Bedrock, Vertex, Foundry, cloud sessions,
7
+ * WebFetch's domain check) has no interception point: that is `outside`, and
8
+ * the doctor warns about it. Tool-argument restoration does not exist yet,
9
+ * background requests and WebSocket traffic have no transport-level probe, so
10
+ * those rows stay `unknown` rather than claiming a coverage or an absence the
11
+ * evidence does not carry.
12
+ */
13
+ import type { HostCapabilities } from "../../types/capabilities.js";
14
+ export declare const CLAUDE_CODE_CAPABILITIES: HostCapabilities;
@@ -0,0 +1,47 @@
1
+ export const CLAUDE_CODE_CAPABILITIES = {
2
+ host: "claude-code",
3
+ verifiedVersion: "2.1.321",
4
+ interception: "loopback-proxy",
5
+ transports: {
6
+ http: {
7
+ state: "protected",
8
+ mechanism: "core.onHttpRequest / onHttpResponse on POST /v1/messages and /v1/messages/count_tokens",
9
+ evidence: "tests/claude-code-proxy.test.ts",
10
+ note: "Anthropic Messages only. A body on another route is blocked, not forwarded.",
11
+ },
12
+ websocket: {
13
+ state: "unknown",
14
+ mechanism: "no WS traffic has been observed, but no transport-level probe has looked for it",
15
+ note: "The 2026-11-21 record covers one stub-backed HTTP scenario only and leaves interactive mode unverified (#113). Not claimed as not-present without a probe.",
16
+ },
17
+ nonFetch: {
18
+ state: "outside",
19
+ mechanism: "none: Bedrock, Vertex and Foundry, and Claude Code cloud sessions, do not use ANTHROPIC_BASE_URL",
20
+ note: "The host offers no hook on these paths. The doctor warns when a provider or host-managed setting is enabled.",
21
+ },
22
+ },
23
+ surfaces: {
24
+ toolArgs: {
25
+ state: "unknown",
26
+ mechanism: "no tool gate yet: tool_use input keeps placeholders, and a tool receives the placeholder",
27
+ note: "Restoration at tool execution through Claude Code hooks is issue #91.",
28
+ },
29
+ replyDisplay: {
30
+ state: "protected",
31
+ mechanism: "core.onHttpResponse restores assistant text in JSON and SSE replies, including a split placeholder",
32
+ evidence: "tests/claude-code-proxy.test.ts",
33
+ },
34
+ background: {
35
+ state: "unknown",
36
+ mechanism: "compaction and summaries travel on /v1/messages, the same route the proxy masks",
37
+ note: "No separate probe has been run (#111), so the row is not claimed as protected.",
38
+ },
39
+ },
40
+ credentials: "separated",
41
+ persistence: "none",
42
+ residuals: [
43
+ "transports.nonFetch: Bedrock, Vertex, Foundry and Claude Code cloud sessions bypass the base URL entirely.",
44
+ "transports.http: WebFetch's domain check sends the hostname, without the path, straight to api.anthropic.com; set skipWebFetchPreflight to turn it off.",
45
+ "surfaces.replyDisplay: after a proxy restart, assistant history is masked under new placeholders and old ones can no longer be restored.",
46
+ ],
47
+ };
@@ -0,0 +1,10 @@
1
+ export interface ClaudeCodeProxyArgs {
2
+ port: number;
3
+ upstream: string;
4
+ configPath?: string;
5
+ attachments: "block" | "allow";
6
+ }
7
+ export declare function parseClaudeCodeProxyArgs(args: readonly string[]): ClaudeCodeProxyArgs | {
8
+ error: string;
9
+ };
10
+ export declare function runClaudeCodeProxy(args: readonly string[]): Promise<number>;
@@ -0,0 +1,51 @@
1
+ import { loadConfig } from "../../config/loader.js";
2
+ import { DEFAULT_PROXY_PORT, DEFAULT_UPSTREAM, startClaudeCodeProxy } from "./proxy.js";
3
+ export function parseClaudeCodeProxyArgs(args) {
4
+ const valueOf = (flag) => {
5
+ const index = args.indexOf(flag);
6
+ return index !== -1 && index + 1 < args.length ? args[index + 1] : undefined;
7
+ };
8
+ const rawPort = valueOf("--port");
9
+ const port = rawPort === undefined ? DEFAULT_PROXY_PORT : Number(rawPort);
10
+ if (!Number.isInteger(port) || port < 0 || port > 65535)
11
+ return { error: "--port must be an integer from 0 to 65535" };
12
+ const attachments = valueOf("--attachments") ?? "block";
13
+ if (attachments !== "block" && attachments !== "allow")
14
+ return { error: '--attachments must be "block" or "allow"' };
15
+ return { port, upstream: valueOf("--upstream") ?? DEFAULT_UPSTREAM, configPath: valueOf("--config"), attachments };
16
+ }
17
+ // Same forced setting as the OpenCode plugin entry, so both hosts detect the
18
+ // same encoded values.
19
+ function withEncodingDetection(config) {
20
+ return { ...config, settings: { ...config.settings, encoding_detection: true } };
21
+ }
22
+ export async function runClaudeCodeProxy(args) {
23
+ const parsed = parseClaudeCodeProxyArgs(args);
24
+ if ("error" in parsed) {
25
+ console.error(`leakshield: ${parsed.error}`);
26
+ return 2;
27
+ }
28
+ let running;
29
+ try {
30
+ const config = withEncodingDetection(loadConfig(parsed.configPath, process.cwd()));
31
+ running = await startClaudeCodeProxy({
32
+ config,
33
+ port: parsed.port,
34
+ upstream: parsed.upstream,
35
+ attachments: parsed.attachments,
36
+ });
37
+ }
38
+ catch (error) {
39
+ console.error(`leakshield: could not start the Claude Code proxy: ${error instanceof Error ? error.message : String(error)}`);
40
+ return 1;
41
+ }
42
+ console.log(`LeakShield Claude Code proxy listening on ${running.url} -> ${parsed.upstream}`);
43
+ console.log(`Point Claude Code at it: export ANTHROPIC_BASE_URL=${running.url}`);
44
+ const stop = () => {
45
+ void running.close().then(() => process.exit(0));
46
+ };
47
+ process.once("SIGINT", stop);
48
+ process.once("SIGTERM", stop);
49
+ await new Promise(() => { });
50
+ return 0;
51
+ }
@@ -0,0 +1,19 @@
1
+ import type { DoctorCheck } from "../../doctor-report.js";
2
+ export type ProxyProbe = {
3
+ ok: true;
4
+ upstream: string | null;
5
+ } | {
6
+ ok: false;
7
+ reason: "unreachable" | "not-leakshield";
8
+ };
9
+ export interface ClaudeCodeDoctorDeps {
10
+ claudeVersion(): string | null;
11
+ readIfExists(filePath: string): string | null;
12
+ probeProxy(baseUrl: string): Promise<ProxyProbe>;
13
+ env: Readonly<Record<string, string | undefined>>;
14
+ cwd: string;
15
+ home: string;
16
+ }
17
+ export declare function createClaudeCodeDoctorDeps(): ClaudeCodeDoctorDeps;
18
+ /** Claude Code checks, independent of the OpenCode checks and their status. */
19
+ export declare function runClaudeCodeDoctor(deps: ClaudeCodeDoctorDeps): Promise<DoctorCheck[]>;
@@ -0,0 +1,177 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { DEFAULT_PROXY_HOST, DEFAULT_PROXY_PORT, HEALTH_PATH, HEALTH_SERVICE } from "./proxy.js";
6
+ const PROXY_URL = `http://${DEFAULT_PROXY_HOST}:${DEFAULT_PROXY_PORT}`;
7
+ const ALTERNATE_PROVIDERS = ["CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"];
8
+ export function createClaudeCodeDoctorDeps() {
9
+ return {
10
+ claudeVersion() {
11
+ try {
12
+ const r = spawnSync("claude", ["--version"], { encoding: "utf8", timeout: 4000 });
13
+ if (r.error || (r.status !== null && r.status !== 0))
14
+ return null;
15
+ return (r.stdout || "").trim() || null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ },
21
+ readIfExists(filePath) {
22
+ try {
23
+ return fs.readFileSync(filePath, "utf8");
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ },
29
+ async probeProxy(baseUrl) {
30
+ try {
31
+ const response = await fetch(new URL(HEALTH_PATH, baseUrl), { signal: AbortSignal.timeout(2000) });
32
+ const body = await response.json().catch(() => null);
33
+ if (response.ok && typeof body === "object" && body !== null && body.service === HEALTH_SERVICE) {
34
+ const upstream = body.upstream;
35
+ return { ok: true, upstream: typeof upstream === "string" ? upstream : null };
36
+ }
37
+ return { ok: false, reason: "not-leakshield" };
38
+ }
39
+ catch {
40
+ return { ok: false, reason: "unreachable" };
41
+ }
42
+ },
43
+ env: process.env,
44
+ cwd: process.cwd(),
45
+ home: os.homedir(),
46
+ };
47
+ }
48
+ /**
49
+ * Claude Code applies settings `env` over the shell, and among settings files
50
+ * the more specific one wins: project local, then project, then user.
51
+ * Returned highest precedence first.
52
+ */
53
+ function envSources(deps) {
54
+ const configDir = deps.env.CLAUDE_CONFIG_DIR || path.join(deps.home, ".claude");
55
+ const files = [
56
+ path.join(deps.cwd, ".claude", "settings.local.json"),
57
+ path.join(deps.cwd, ".claude", "settings.json"),
58
+ path.join(configDir, "settings.json"),
59
+ ];
60
+ const sources = [];
61
+ const broken = [];
62
+ for (const file of files) {
63
+ const raw = deps.readIfExists(file);
64
+ if (raw === null)
65
+ continue;
66
+ try {
67
+ const parsed = JSON.parse(raw);
68
+ const env = typeof parsed === "object" && parsed !== null ? parsed.env : undefined;
69
+ if (typeof env === "object" && env !== null && !Array.isArray(env)) {
70
+ sources.push({ label: file, env: env });
71
+ }
72
+ }
73
+ catch {
74
+ broken.push(file);
75
+ }
76
+ }
77
+ sources.push({ label: "shell environment of this doctor run", env: { ...deps.env } });
78
+ return { sources, broken };
79
+ }
80
+ function effective(sources, key) {
81
+ for (const source of sources) {
82
+ const value = source.env[key];
83
+ if (typeof value === "string" && value.length > 0)
84
+ return { value, source: source.label };
85
+ }
86
+ return null;
87
+ }
88
+ function isLoopbackUrl(raw) {
89
+ try {
90
+ const host = new URL(raw).hostname;
91
+ return host === "127.0.0.1" || host === "localhost" || host === "[::1]";
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ }
97
+ /** Claude Code checks, independent of the OpenCode checks and their status. */
98
+ export async function runClaudeCodeDoctor(deps) {
99
+ const checks = [];
100
+ const version = deps.claudeVersion();
101
+ if (version === null) {
102
+ checks.push({ id: "claude-code", state: "skip", detail: "claude binary not found on PATH; Claude Code checks skipped." });
103
+ return checks;
104
+ }
105
+ checks.push({ id: "claude-code", state: "ok", detail: version });
106
+ const { sources, broken } = envSources(deps);
107
+ for (const file of broken) {
108
+ checks.push({
109
+ id: "claude-code-settings",
110
+ state: "warn",
111
+ detail: `${file} is not valid JSON; its env block was not read.`,
112
+ fix: "Fix the syntax, then rerun this doctor.",
113
+ });
114
+ }
115
+ const provider = ALTERNATE_PROVIDERS.map((key) => effective(sources, key)).find((hit) => hit !== null && hit.value !== "0" && hit.value !== "false");
116
+ if (provider) {
117
+ checks.push({
118
+ id: "claude-code-provider",
119
+ state: "warn",
120
+ detail: `A Bedrock/Vertex/Foundry provider is enabled (from ${provider.source}); those requests bypass ANTHROPIC_BASE_URL and the LeakShield proxy.`,
121
+ fix: "Unset it to send Claude Code through the Anthropic API and the proxy.",
122
+ });
123
+ }
124
+ if (deps.env.CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST) {
125
+ checks.push({
126
+ id: "claude-code-host-managed",
127
+ state: "warn",
128
+ detail: "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST is set in this shell; Claude Code then ignores ANTHROPIC_BASE_URL from settings files, and the embedding app decides the endpoint.",
129
+ fix: "Set ANTHROPIC_BASE_URL in the environment that launches Claude Code, or check the embedding app's provider settings.",
130
+ });
131
+ }
132
+ const baseUrl = effective(sources, "ANTHROPIC_BASE_URL");
133
+ if (baseUrl === null) {
134
+ checks.push({
135
+ id: "claude-code-proxy",
136
+ state: "warn",
137
+ detail: "ANTHROPIC_BASE_URL is not set, so Claude Code talks to Anthropic directly and is not protected.",
138
+ fix: `Run \`leakshield --claude-code-proxy\`, then set ANTHROPIC_BASE_URL=${PROXY_URL} in your shell or in the "env" block of ~/.claude/settings.json.`,
139
+ });
140
+ return checks;
141
+ }
142
+ const probe = await deps.probeProxy(baseUrl.value);
143
+ if (probe.ok) {
144
+ checks.push({
145
+ id: "claude-code-proxy",
146
+ state: "ok",
147
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) is the LeakShield proxy${probe.upstream ? `, forwarding to ${probe.upstream}` : ""}.`,
148
+ });
149
+ }
150
+ else if (probe.reason === "unreachable" && isLoopbackUrl(baseUrl.value)) {
151
+ checks.push({
152
+ id: "claude-code-proxy",
153
+ state: "fail",
154
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) points at a local address where nothing answers; Claude Code requests will fail until the proxy runs.`,
155
+ fix: "Start it with `leakshield --claude-code-proxy` (add `--port` if you changed the port).",
156
+ });
157
+ }
158
+ else {
159
+ checks.push({
160
+ id: "claude-code-proxy",
161
+ state: "warn",
162
+ detail: `ANTHROPIC_BASE_URL=${baseUrl.value} (from ${baseUrl.source}) is not the LeakShield proxy, so Claude Code is not protected.`,
163
+ fix: `Run \`leakshield --claude-code-proxy\` and set ANTHROPIC_BASE_URL=${PROXY_URL}.`,
164
+ });
165
+ }
166
+ if (sources.length > 1 && baseUrl.source !== sources[sources.length - 1].label) {
167
+ const shell = sources[sources.length - 1].env.ANTHROPIC_BASE_URL;
168
+ if (typeof shell === "string" && shell.length > 0 && shell !== baseUrl.value) {
169
+ checks.push({
170
+ id: "claude-code-env",
171
+ state: "warn",
172
+ detail: `This shell sets ANTHROPIC_BASE_URL=${shell}, but ${baseUrl.source} overrides it inside Claude Code.`,
173
+ });
174
+ }
175
+ }
176
+ return checks;
177
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Claude Code host adapter (issue #86): a loopback HTTP proxy that Claude Code
3
+ * reaches through `ANTHROPIC_BASE_URL`. Anthropic Messages requests are masked
4
+ * by the host-independent core before they leave the machine, and assistant
5
+ * text in JSON and SSE replies is restored before Claude Code shows it.
6
+ *
7
+ * Fail closed: a request the proxy cannot mask (unknown route with a body,
8
+ * unrecognised body shape, masking error) is answered locally with a 400
9
+ * Anthropic-style error and nothing is forwarded. Bodyless GET/HEAD probes
10
+ * (Claude Code sends `HEAD /api/hello`) are forwarded when their URL carries
11
+ * no finding.
12
+ *
13
+ * Not covered here: tool-execution restoration (tool_use input stays
14
+ * tokenized, so Claude Code's tools receive placeholders), and anything
15
+ * Claude Code sends outside the base URL.
16
+ */
17
+ import { type Server } from "node:http";
18
+ import type { GuardConfig } from "../../types.js";
19
+ export declare const DEFAULT_PROXY_HOST = "127.0.0.1";
20
+ export declare const DEFAULT_PROXY_PORT = 8787;
21
+ export declare const DEFAULT_UPSTREAM = "https://api.anthropic.com";
22
+ export declare const HEALTH_PATH = "/__leakshield/health";
23
+ export declare const HEALTH_SERVICE = "leakshield-claude-code-proxy";
24
+ export interface ClaudeCodeProxyOptions {
25
+ config: GuardConfig;
26
+ upstream?: string;
27
+ attachments?: "block" | "allow";
28
+ fetch?: typeof fetch;
29
+ log?: (line: string) => void;
30
+ }
31
+ export interface ClaudeCodeProxy {
32
+ readonly upstream: string;
33
+ handle(request: Request, signal?: AbortSignal): Promise<Response>;
34
+ dispose(): void;
35
+ }
36
+ /** Plain http is accepted only for a loopback upstream (a local stub or gateway). */
37
+ export declare function parseUpstream(raw: string): URL;
38
+ export declare function createClaudeCodeProxy(options: ClaudeCodeProxyOptions): ClaudeCodeProxy;
39
+ export interface RunningClaudeCodeProxy {
40
+ readonly url: string;
41
+ readonly server: Server;
42
+ close(): Promise<void>;
43
+ }
44
+ export declare function startClaudeCodeProxy(options: ClaudeCodeProxyOptions & {
45
+ port?: number;
46
+ host?: string;
47
+ }): Promise<RunningClaudeCodeProxy>;