leakshield 0.1.0 → 0.1.2
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 +14 -8
- package/README.zh-TW.md +10 -4
- package/dist/config/loader.js +31 -0
- package/dist/decision/ingress.js +2 -2
- package/dist/doctor.js +12 -0
- package/dist/opencode-hooks.js +2 -2
- package/dist/opencode-transparent-aisdk.js +3 -3
- package/dist/opencode-transparent-http.js +7 -7
- package/dist/opencode-transparent-ws.js +4 -4
- package/dist/opencode-transparent.js +10 -10
- package/dist/opencode-v2.js +2 -2
- package/dist/rules/builtin.js +54 -2
- package/dist/rules/dynamic.js +42 -11
- package/dist/scanner/cidr.js +96 -0
- package/dist/scanner/engine.js +25 -12
- package/dist/scanner/remotes.js +140 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -24,10 +24,10 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
|
|
|
24
24
|
|
|
25
25
|
## Project status
|
|
26
26
|
|
|
27
|
-
**Experimental, pre-release.**
|
|
27
|
+
**Experimental, pre-release.** Published to npm as `leakshield` (`0.1.x`): run `npx leakshield`, or build locally (`npm ci && npm run build`) and point OpenCode at the `dist` directory.
|
|
28
28
|
|
|
29
29
|
- Transparent mode has been verified on OpenCode v2.0.28 with local loopback providers, and once against a real OpenAI model. It is **not** a guarantee that nothing sensitive reaches a model: the recommended hook-first setup is reported as `PARTIAL` by `--doctor`, and content added after the plugin's hooks or sent by permitted tools (curl, remote MCP) is outside its coverage.
|
|
30
|
-
- Not yet verified: OS-keychain
|
|
30
|
+
- Not yet verified: OS-keychain custody on Windows and Linux (macOS verified 2026-10-20), a real Anthropic provider, long histories on other providers, long-running use ([#26](https://github.com/jwcrystal/leakshield/issues/26)).
|
|
31
31
|
- Defaults may still change before the first tagged release ([#24](https://github.com/jwcrystal/leakshield/issues/24), [#27](https://github.com/jwcrystal/leakshield/issues/27)); see the [changelog](CHANGELOG.md).
|
|
32
32
|
- Verification records: [docs/evidence](docs/evidence/README.md). Report vulnerabilities privately: [SECURITY.md](SECURITY.md). License: [MIT](LICENSE).
|
|
33
33
|
|
|
@@ -44,15 +44,17 @@ MCP server mode has been removed. It depended on the model voluntarily calling a
|
|
|
44
44
|
| Taiwan National ID | Format validation | 🔴 HIGH |
|
|
45
45
|
| Credit Card Number | 13–19 digits, Luhn checksum required | 🔴 HIGH |
|
|
46
46
|
| IBAN | Compact or 4-char groups, mod-97 checksum required | 🔴 HIGH |
|
|
47
|
-
| Public IPv4 Address | Private/loopback/CGNAT/reserved ranges excluded | 🟡 MEDIUM |
|
|
47
|
+
| Public IPv4 Address | Private/loopback/CGNAT/reserved ranges excluded; runs longer than four groups are reported whole | 🟡 MEDIUM |
|
|
48
|
+
| Private IPv4 / VPN CIDR | **Opt-in** — disabled by default (`rule_overrides["private-ipv4"]: true`); networks from `settings.private_cidrs`, default RFC 1918 + CGNAT + link-local | 🟡 MEDIUM |
|
|
48
49
|
| Email Address | All email formats | 🟡 MEDIUM |
|
|
50
|
+
| URL Embedded Credential | `scheme://user:password@host` — only the userinfo span is masked | 🔴 HIGH |
|
|
49
51
|
| Taiwan Mobile Number | **Opt-in** — disabled by default (`rule_overrides["phone-tw"]: true`); digit runs are a measured false-positive source | 🟡 MEDIUM |
|
|
50
52
|
| International Phone | **Opt-in** — disabled by default (`rule_overrides["phone-intl"]: true`); same trade-off as above | 🟢 LOW |
|
|
51
53
|
| HTTP(S) URL | **Opt-in** — disabled by default (`rule_overrides.url: true`) | 🟢 LOW |
|
|
52
54
|
| NDA Keywords | Custom (see `config/guard.config.yaml`) | 🔴 HIGH |
|
|
53
55
|
| Private Domains | Custom (see `config/guard.config.yaml`) | 🟡 MEDIUM |
|
|
54
56
|
|
|
55
|
-
> **Detection boundaries** (per `src/rules/builtin.ts`): the generic secret rule matches only the keywords `password`, `passwd`, `secret`, `private_key`, `client_secret` with a value of **8+ characters** — generic `api_key=`/`token=` assignments are not matched unless the value itself matches a vendor pattern. Credit card and IBAN matches require a valid checksum; IP matches cover only public/routable IPv4. Not covered by any rule: street/postal addresses, dates, IPv6, and values below the 8-character minimum. Every built-in rule has a stable id and can be toggled via `settings.rule_overrides` in `config/guard.config.yaml` (unknown ids fail config load); the URL rule ships disabled because always-on URL masking would flag provider endpoints. The same rule set (built-in + `config/guard.config.yaml`) applies to every mode — `block`, `redact`, and `transparent`.
|
|
57
|
+
> **Detection boundaries** (per `src/rules/builtin.ts`): the generic secret rule matches only the keywords `password`, `passwd`, `secret`, `private_key`, `client_secret` with a value of **8+ characters** — generic `api_key=`/`token=` assignments are not matched unless the value itself matches a vendor pattern. Credit card and IBAN matches require a valid checksum; IP matches cover only public/routable IPv4, and a dotted run longer than four groups is reported whole so an address embedded in it is masked instead of left behind (dotted dates such as `2026.10.21.14.32.59` therefore report as an IP run too). Not covered by any rule: street/postal addresses, dates, IPv6, and values below the 8-character minimum for generic secret assignments. SSH remote authorities (`user@host:path`, `ssh://user@host/…`) are not reported as email; private domains and path keywords still apply inside them, and the password half of `scheme://user:password@host` is reported as a URL credential instead. Private IPv4 is opt-in because the literal also matches version numbers and timestamps; `settings.private_cidrs` narrows it to the organisation's own ranges, and an entry that does not parse fails the config load. Every built-in rule has a stable id and can be toggled via `settings.rule_overrides` in `config/guard.config.yaml` (unknown ids fail config load); the URL rule ships disabled because always-on URL masking would flag provider endpoints. The same rule set (built-in + `config/guard.config.yaml`) applies to every mode — `block`, `redact`, and `transparent`.
|
|
56
58
|
|
|
57
59
|
---
|
|
58
60
|
|
|
@@ -99,9 +101,9 @@ npm install
|
|
|
99
101
|
npm run build
|
|
100
102
|
```
|
|
101
103
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
104
|
+
`npx leakshield …` runs the published package. For local development, install
|
|
105
|
+
the build globally or `npm link` it, then use `leakshield` directly.
|
|
106
|
+
`npm run scan -- ...` works from this repository without installing.
|
|
105
107
|
|
|
106
108
|
### npm Scripts
|
|
107
109
|
|
|
@@ -326,7 +328,7 @@ Note that v2 only accepts plugin *directories* (it resolves `dist/index.js`) or
|
|
|
326
328
|
|
|
327
329
|
The default `mode` depends on the host: **`transparent` on OpenCode v2** (described below) and **`block` on v1**, since transparent is v2-only. `block` replaces unsafe content with a disclosure-free notice; set `"mode": "block"` on v2 to keep that behavior. Set `mode` to `redact` only when you explicitly want recognized direct matches replaced with `[REDACTED_TYPE]` placeholders. `--doctor` shows the mode in effect and marks it `(default)` when the options omit it.
|
|
328
330
|
|
|
329
|
-
**OpenCode v2 only — transparent pseudonymization (the v2 default):** omit `mode` or set `"mode": "transparent"` to replace detected sensitive values in model-request snapshots with stable opaque placeholders — category-labelled `[SGP2:<TYPE>-xxxx-xxxx-xxxx]` since W1 (2026-10-07; the legacy `[SGP1:…]` shape stays recognized for restoring pre-upgrade in-session mappings). Reverse mappings are scoped to the OpenCode session and stay in process memory by default; encrypted persistence is opt-in below. Known placeholders are restored in tool inputs before execution and in supported assistant response text. Supported HTTP protocols are selected by URL path shape: Chat Completions, Anthropic Messages, and Responses, including streaming. Native Responses-family WebSocket is also supported as described below. Wire-mode SDKs honoring injected fetch use the same request-scoped HTTP hooks. Hook-only protects content snapshots without transport admission; it does not add adapters for unknown protocols. Transparent mode has been verified against loopback providers and one real OpenAI model;
|
|
331
|
+
**OpenCode v2 only — transparent pseudonymization (the v2 default):** omit `mode` or set `"mode": "transparent"` to replace detected sensitive values in model-request snapshots with stable opaque placeholders — category-labelled `[SGP2:<TYPE>-xxxx-xxxx-xxxx]` since W1 (2026-10-07; the legacy `[SGP1:…]` shape stays recognized for restoring pre-upgrade in-session mappings). Reverse mappings are scoped to the OpenCode session and stay in process memory by default; encrypted persistence is opt-in below. Known placeholders are restored in tool inputs before execution and in supported assistant response text. Supported HTTP protocols are selected by URL path shape: Chat Completions, Anthropic Messages, and Responses, including streaming. Native Responses-family WebSocket is also supported as described below. Wire-mode SDKs honoring injected fetch use the same request-scoped HTTP hooks. Hook-only protects content snapshots without transport admission; it does not add adapters for unknown protocols. Transparent mode has been verified against loopback providers and one real OpenAI model; OS-keychain custody is verified on macOS only, and a real Anthropic provider, long-history replay on other providers and Windows/Linux keychains are not verified yet ([#26](https://github.com/jwcrystal/leakshield/issues/26)). Routes it cannot protect are refused, not forwarded.
|
|
330
332
|
|
|
331
333
|
**Hook-only for new transparent installs:** use [the hook-first configuration example](config/opencode.hook-first.example.json), which explicitly sets `wireProtection: false`. Content hooks protect system/messages/options/tools and the tool gate restores safe known arguments. SG registers **no outbound HTTP request, WS handshake/send, or AI SDK admission hooks**, does not inspect transport metadata, and does not change provider transport settings. Unknown routes and private SDK transports do not incur SG transport refusals. Optional incoming HTTP/WS hooks restore supported display text using successful preparation for the same session/kind/model; missing hooks or restoration failures leave placeholders literal without disabling input protection. Later-added content or attachments may leave unmasked, even with `attachments: "block"`. The doctor reports `PARTIAL`, not full-wire protection. **Content-hook masking failures still refuse the affected call**, now including a safe `[stage=prepare.mask reason=…]` code; hook-only does not silently forward unprotectable raw content. See [hook-only verification](docs/evidence/2026-10-11-pure-hook-only-verification.md).
|
|
332
334
|
|
|
@@ -510,8 +512,12 @@ Input lengths for dynamic rules are validated when the config is loaded:
|
|
|
510
512
|
| `nda_keywords` entries | 200 characters |
|
|
511
513
|
| `private_domains` entries | 255 characters |
|
|
512
514
|
|
|
515
|
+
| `custom_rules` `description` / `pattern` | 200 characters |
|
|
516
|
+
|
|
513
517
|
Values exceeding these limits will cause `loadConfig()` to throw a Zod validation error, preventing oversized patterns from entering the scanner.
|
|
514
518
|
|
|
519
|
+
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.
|
|
520
|
+
|
|
515
521
|
## Secret Preview Behavior
|
|
516
522
|
|
|
517
523
|
All secret previews in scan results are **fully masked** as `****`, regardless of the secret's length. No prefix or suffix characters from the original value are preserved. This eliminates partial secret exposure in logs, CI output, and Web UI responses.
|
package/README.zh-TW.md
CHANGED
|
@@ -24,7 +24,7 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
|
|
|
24
24
|
|
|
25
25
|
## 目前狀態
|
|
26
26
|
|
|
27
|
-
**實驗性,尚未正式發佈。**
|
|
27
|
+
**實驗性,尚未正式發佈。** 已發佈到 npm(`leakshield`,`0.1.x`):可直接用 `npx leakshield`,或在本機建置(`npm ci && npm run build`)再讓 OpenCode 指向 `dist` 目錄。
|
|
28
28
|
|
|
29
29
|
- Transparent 模式已在 OpenCode v2.0.28 搭配本機替身 provider 驗證,並用真實 OpenAI 模型驗證過一次。它**不保證**敏感內容絕不會送到模型:建議的 hook-first 設定在 `--doctor` 顯示為 `PARTIAL`,hook 之後才加入的內容,以及被允許的工具外送(curl、遠端 MCP),都不在保護範圍內。
|
|
30
30
|
- 尚未驗證:OS keychain 持久化、真實 Anthropic provider、其他 provider 的長對話、長時間使用([#26](https://github.com/jwcrystal/leakshield/issues/26))。
|
|
@@ -51,8 +51,10 @@ MCP Server 模式已移除。它依賴模型在已收到相關 context 後自行
|
|
|
51
51
|
| 台灣身份證字號 | 格式驗證 | 🔴 HIGH |
|
|
52
52
|
| 信用卡號 | 13–19 位數字,需通過 Luhn 檢查碼 | 🔴 HIGH |
|
|
53
53
|
| IBAN | 緊湊或四字一組格式,需通過 mod-97 檢查碼 | 🔴 HIGH |
|
|
54
|
-
| 公共 IPv4 位址 | 排除私有/回環/CGNAT
|
|
54
|
+
| 公共 IPv4 位址 | 排除私有/回環/CGNAT/保留段;超過四段的點分數字整段回報 | 🟡 MEDIUM |
|
|
55
|
+
| 私有 IPv4/VPN 網段 | **Opt-in** —— 預設關閉(`rule_overrides: { "private-ipv4": true }` 開啟);網段由 `settings.private_cidrs` 指定,預設 RFC 1918 + CGNAT + link-local | 🟡 MEDIUM |
|
|
55
56
|
| Email 地址 | 所有 email 格式 | 🟡 MEDIUM |
|
|
57
|
+
| URL 內嵌憑證 | `scheme://user:password@host` —— 只遮罩 userinfo 這一段 | 🔴 HIGH |
|
|
56
58
|
| 台灣手機號碼 | **Opt-in** —— 預設關閉(`rule_overrides: { "phone-tw": true }` 開啟);數字段是實測的誤報來源,關閉的代價是漏偵真電話 | 🟡 MEDIUM |
|
|
57
59
|
| 國際電話 | **Opt-in** —— 預設關閉(`rule_overrides: { "phone-intl": true }` 開啟);取捨同上 | 🟢 LOW |
|
|
58
60
|
| HTTP(S) URL | **Opt-in** —— 預設關閉(`rule_overrides: { "url": true }` 開啟) | 🟢 LOW |
|
|
@@ -104,7 +106,7 @@ npm install
|
|
|
104
106
|
npm run build
|
|
105
107
|
```
|
|
106
108
|
|
|
107
|
-
|
|
109
|
+
`npx leakshield …` 會執行已發佈的套件。本機開發時,全域安裝或 `npm link` 這份 build 後即可直接使用
|
|
108
110
|
`leakshield`;在此 repository 內不用安裝,直接用 `npm run scan -- ...` 即可。
|
|
109
111
|
|
|
110
112
|
### npm scripts 速查
|
|
@@ -466,7 +468,7 @@ Doctor 是在 host 之外執行的安裝層檢查,看不到執行中的 sessio
|
|
|
466
468
|
|
|
467
469
|
LeakShield 保護送往模型的對話內容:prompt、重播的歷史、工具輸出,以及(transparent 模式下)可解析其結構的 provider 請求 body。它**不是**工具對外連線的防火牆:被允許的本機工具仍可透過 `curl`、遠端 MCP server 或任何其他管道把原文傳出去。要管控工具的目的地,需要此 plugin 之外的權限層。
|
|
468
470
|
|
|
469
|
-
偵測也有已知缺口:街道/郵遞地址、日期、IPv6,以及關鍵字清單之外或短於 8 字元的一般賦值都不會被偵測。信用卡與 IBAN 只有在檢查碼驗證通過時才會命中;IP 偵測只涵蓋公開 IPv4
|
|
471
|
+
偵測也有已知缺口:街道/郵遞地址、日期、IPv6,以及關鍵字清單之外或短於 8 字元的一般賦值都不會被偵測。信用卡與 IBAN 只有在檢查碼驗證通過時才會命中;IP 偵測只涵蓋公開 IPv4(超過四段的點分數字會整段回報,避免內嵌位址漏遮;`2026.10.21.14.32.59` 這類點分日期也會回報);URL 偵測存在但需手動開啟,見[偵測範圍](#偵測範圍)。
|
|
470
472
|
|
|
471
473
|
## 設定檔
|
|
472
474
|
|
|
@@ -551,8 +553,12 @@ fi
|
|
|
551
553
|
| `nda_keywords` 每個項目 | 200 字元 |
|
|
552
554
|
| `private_domains` 每個項目 | 255 字元 |
|
|
553
555
|
|
|
556
|
+
| `custom_rules` 的 `description` / `pattern` | 200 字元 |
|
|
557
|
+
|
|
554
558
|
超過長度限制的值會導致 `loadConfig()` 拋出 Zod 驗證錯誤,避免過長的 pattern 進入掃描器。
|
|
555
559
|
|
|
560
|
+
`custom_rules` 的 pattern 若無法編譯成正規表示式,`loadConfig()` 也會拋錯,並指出規則的索引和 `description`(不會印出 pattern):無法執行的規則不能載入。可以編譯、但在固定測試輸入上跑得太慢的 pattern 會被當成疑似 ReDoS 而略過,stderr 會印警告,`leakshield --doctor` 也會出現 `custom-rules` 警告。這個檢查只是計時啟發式,不是保證:它只執行 pattern 一次,而且無法中斷執行,所以不能證明 pattern 安全。
|
|
561
|
+
|
|
556
562
|
## 敏感資訊預覽行為
|
|
557
563
|
|
|
558
564
|
掃描結果中所有敏感資訊的預覽一律顯示為 `****`,不論原始值長度為何,不保留任何前後綴字元。這樣可避免在日誌、CI 輸出或 Web UI 回應中洩漏部分機密內容。
|
package/dist/config/loader.js
CHANGED
|
@@ -5,6 +5,7 @@ import * as yaml from "js-yaml";
|
|
|
5
5
|
import { fileURLToPath } from "url";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
import { loadExactValueDetector } from "../scanner/exact-values.js";
|
|
8
|
+
import { parseCidr } from "../scanner/cidr.js";
|
|
8
9
|
import { BUILTIN_RULE_IDS } from "../rules/builtin.js";
|
|
9
10
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
11
|
const MAX_DYNAMIC_RULE_LENGTH = 200;
|
|
@@ -26,6 +27,7 @@ export const GuardConfigSchema = z.object({
|
|
|
26
27
|
encoding_detection: z.boolean().default(false),
|
|
27
28
|
env_files: z.array(z.string().min(1).max(MAX_ENV_FILE_PATH_LENGTH)).max(16).default([]),
|
|
28
29
|
rule_overrides: z.record(z.string().min(1), z.boolean()).default({}),
|
|
30
|
+
private_cidrs: z.array(z.string().min(1).max(64)).max(64).default([]),
|
|
29
31
|
}).default({}),
|
|
30
32
|
}).superRefine((config, ctx) => {
|
|
31
33
|
// Unknown rule ids in `rule_overrides` fail the parse (fail-closed): a typo
|
|
@@ -40,6 +42,35 @@ export const GuardConfigSchema = z.object({
|
|
|
40
42
|
});
|
|
41
43
|
}
|
|
42
44
|
}
|
|
45
|
+
// A private network list that does not parse fails the load: a typo would
|
|
46
|
+
// otherwise narrow the rule to nothing while it still reported "enabled".
|
|
47
|
+
(config.settings.private_cidrs ?? []).forEach((entry, index) => {
|
|
48
|
+
if (parseCidr(entry) === null) {
|
|
49
|
+
ctx.addIssue({
|
|
50
|
+
code: z.ZodIssueCode.custom,
|
|
51
|
+
path: ["settings", "private_cidrs", index],
|
|
52
|
+
message: `private_cidrs[${index}] is not a valid IPv4 CIDR (expected a.b.c.d/prefix)`,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
// A custom rule whose pattern does not compile fails the parse too: the
|
|
57
|
+
// scanner would otherwise drop it and report clean text as safe.
|
|
58
|
+
config.custom_rules.forEach((rule, index) => {
|
|
59
|
+
try {
|
|
60
|
+
new RegExp(rule.pattern, "gi");
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
// V8 messages embed the pattern ("Invalid regular expression: /…/gi:
|
|
64
|
+
// reason"); keep only the reason, since a pattern may itself be a
|
|
65
|
+
// literal the rule exists to protect.
|
|
66
|
+
const reason = error.message.split(": ").pop();
|
|
67
|
+
ctx.addIssue({
|
|
68
|
+
code: z.ZodIssueCode.custom,
|
|
69
|
+
path: ["custom_rules", index, "pattern"],
|
|
70
|
+
message: `custom_rules[${index}] "${rule.description}": pattern does not compile (${reason})`,
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
});
|
|
43
74
|
});
|
|
44
75
|
function finalizeConfig(config, workspaceRoot) {
|
|
45
76
|
return {
|
package/dist/decision/ingress.js
CHANGED
|
@@ -4,7 +4,7 @@ import { redactAndVerify } from "../scanner/redaction-verifier.js";
|
|
|
4
4
|
const DEFAULT_CACHE_SIZE = 512;
|
|
5
5
|
export function blockedText(context, totalFindings) {
|
|
6
6
|
const count = totalFindings === 0 ? "unscanned" : `${totalFindings} sensitive item(s)`;
|
|
7
|
-
return `[LeakShield blocked ${context}: ${count}.
|
|
7
|
+
return `[LeakShield blocked ${context}: ${count}. The original was not sent to the model.]`;
|
|
8
8
|
}
|
|
9
9
|
/**
|
|
10
10
|
* Returns text that is safe to place in an LLM context. Content that exceeds
|
|
@@ -121,7 +121,7 @@ export function protectUnknownStrings(value, config, options, protector = protec
|
|
|
121
121
|
return copy;
|
|
122
122
|
}
|
|
123
123
|
if (!isPlainRecord(value)) {
|
|
124
|
-
return "[LeakShield blocked unsupported metadata value.]";
|
|
124
|
+
return "[LeakShield blocked an unsupported metadata value.]";
|
|
125
125
|
}
|
|
126
126
|
const copy = {};
|
|
127
127
|
seen.set(value, copy);
|
package/dist/doctor.js
CHANGED
|
@@ -25,6 +25,7 @@ import { loadConfig } from "./config/loader.js";
|
|
|
25
25
|
import { defaultKeyfilePath, defaultStorePath } from "./decision/mapping-key.js";
|
|
26
26
|
import { InMemoryMappingKeyProvider, openMappingStore } from "./decision/mapping-store.js";
|
|
27
27
|
import { validatePluginOptions } from "./plugin-options.js";
|
|
28
|
+
import { skippedCustomRules } from "./rules/dynamic.js";
|
|
28
29
|
import { scanText } from "./scanner/engine.js";
|
|
29
30
|
const SMOKE_CANARY = "Smoke test only. Do not reveal or use this token: sk-AAAAAAAAAAAAAAAAAAAA";
|
|
30
31
|
export function createDoctorDeps() {
|
|
@@ -369,6 +370,17 @@ export async function runDoctor(deps) {
|
|
|
369
370
|
});
|
|
370
371
|
return { status: "BROKEN", hostVersion: host.version, hostGeneration: host.generation, configPath, checks };
|
|
371
372
|
}
|
|
373
|
+
// Custom rules the scanner skips (the ReDoS timing heuristic; uncompileable
|
|
374
|
+
// patterns already failed the load above). Descriptions only, never patterns.
|
|
375
|
+
const skipped = skippedCustomRules(guardConfig);
|
|
376
|
+
if (skipped.length > 0) {
|
|
377
|
+
checks.push({
|
|
378
|
+
id: "custom-rules",
|
|
379
|
+
state: "warn",
|
|
380
|
+
detail: `${skipped.length} custom rule(s) disabled and not enforced: ${skipped.map((rule) => `"${rule.description}" (${rule.reason === "invalid" ? "pattern does not compile" : "disabled by ReDoS check"})`).join(", ")}. The ReDoS check is a timing heuristic, not a guarantee.`,
|
|
381
|
+
fix: "Rewrite the pattern without nested or overlapping quantifiers, such as (a+)+ or (a|a)*.",
|
|
382
|
+
});
|
|
383
|
+
}
|
|
372
384
|
// Smoke: the local scanner must flag a synthetic credential
|
|
373
385
|
const smoke = deps.smokeScan(SMOKE_CANARY, guardConfig);
|
|
374
386
|
if (smoke.findings > 0) {
|
package/dist/opencode-hooks.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { ContentHashCache, protectUnknownStrings, } from "./decision/ingress.js";
|
|
2
|
-
const INITIALIZATION_ERROR = "LeakShield initialization failed
|
|
2
|
+
const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
3
3
|
function blockedAttachment(part) {
|
|
4
4
|
return {
|
|
5
5
|
id: part.id,
|
|
6
6
|
sessionID: part.sessionID,
|
|
7
7
|
messageID: part.messageID,
|
|
8
8
|
type: "text",
|
|
9
|
-
text: "[LeakShield blocked an attachment
|
|
9
|
+
text: "[LeakShield blocked an attachment: its content cannot be scanned, so it was not sent.]",
|
|
10
10
|
synthetic: true,
|
|
11
11
|
};
|
|
12
12
|
}
|
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
* the supported contract (including any private sockets/global-fetch path). */
|
|
6
6
|
import { types } from "node:util";
|
|
7
7
|
import { classifyModelRoute } from "./opencode-transparent-http.js";
|
|
8
|
-
const ADMISSION_ERROR = "LeakShield
|
|
9
|
-
const DISPOSED_ERROR = "LeakShield
|
|
10
|
-
const PROTECTION_ERROR = "LeakShield
|
|
8
|
+
const ADMISSION_ERROR = "LeakShield blocked an unsupported route. The provider must use the fetch OpenCode injects.";
|
|
9
|
+
const DISPOSED_ERROR = "LeakShield blocked a request on an inactive AI SDK transport.";
|
|
10
|
+
const PROTECTION_ERROR = "LeakShield blocked an AI SDK request. Check its protocol, metadata and content, then try again.";
|
|
11
11
|
function optionsOf(event) {
|
|
12
12
|
if (types.isProxy(event))
|
|
13
13
|
throw new Error(ADMISSION_ERROR);
|
|
@@ -48,13 +48,13 @@ import { createRecoveringSseStream } from "./opencode-transparent-stream.js";
|
|
|
48
48
|
const warnDegradation = (context) => {
|
|
49
49
|
console.warn(`[leakshield] degraded: ${context}`);
|
|
50
50
|
};
|
|
51
|
-
const UNSUPPORTED_REQUEST_BODY = "LeakShield
|
|
52
|
-
const UNSUPPORTED_TRANSPORT = "LeakShield
|
|
53
|
-
const MASK_FAILURE = "LeakShield
|
|
54
|
-
const UNSUPPORTED_RESPONSE = "LeakShield
|
|
55
|
-
const RESTORE_FAILURE = "LeakShield
|
|
56
|
-
const MALFORMED_STREAM = "LeakShield
|
|
57
|
-
const STREAM_BUFFER_LIMIT = "LeakShield
|
|
51
|
+
const UNSUPPORTED_REQUEST_BODY = "LeakShield blocked the request because its body is unsupported or could not be identified.";
|
|
52
|
+
const UNSUPPORTED_TRANSPORT = "LeakShield blocked a request on an unsupported route.";
|
|
53
|
+
const MASK_FAILURE = "LeakShield blocked the request because it could not be masked safely.";
|
|
54
|
+
const UNSUPPORTED_RESPONSE = "LeakShield blocked a response it could not restore safely.";
|
|
55
|
+
const RESTORE_FAILURE = "LeakShield blocked the response because it could not be restored safely.";
|
|
56
|
+
const MALFORMED_STREAM = "LeakShield blocked a malformed or incomplete stream.";
|
|
57
|
+
const STREAM_BUFFER_LIMIT = "LeakShield blocked an oversized stream buffer.";
|
|
58
58
|
/**
|
|
59
59
|
* Content-free refusal classification (2026-10-08): every request refusal
|
|
60
60
|
* appends a fixed code naming WHICH check failed — the refusal-policy spec
|
|
@@ -4,10 +4,10 @@
|
|
|
4
4
|
* OpenCode exposes no connection ID; attribution uses the hook's session,
|
|
5
5
|
* kind and model lane, then the provider's response ID. */
|
|
6
6
|
import { admitModelRequest, classifyModelRoute, remaskResponsesRequest, RESPONSES_TEXT_DELTA_TYPES, RESPONSES_TEXT_DONE_TYPES, restoreDisplayText, restoreResponsesEventDisplay, splitRestorable, } from "./opencode-transparent-http.js";
|
|
7
|
-
const ROUTE_ERROR = "LeakShield
|
|
8
|
-
const FRAME_ERROR = "LeakShield
|
|
9
|
-
const ATTRIBUTION_ERROR = "LeakShield
|
|
10
|
-
const LIMIT_ERROR = "LeakShield
|
|
7
|
+
const ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
|
|
8
|
+
const FRAME_ERROR = "LeakShield blocked an unsupported or malformed WebSocket frame.";
|
|
9
|
+
const ATTRIBUTION_ERROR = "LeakShield blocked a WebSocket frame that could not be matched to a request.";
|
|
10
|
+
const LIMIT_ERROR = "LeakShield blocked an oversized WebSocket buffer.";
|
|
11
11
|
const MAX_FRAME_BYTES = 4 * 1024 * 1024;
|
|
12
12
|
const MAX_LANES = 1024;
|
|
13
13
|
const MAX_CHANNELS = 256;
|
|
@@ -46,16 +46,16 @@ import { createResponsesWebSocketAdapter } from "./opencode-transparent-ws.js";
|
|
|
46
46
|
import { createAISDKTransportAdmission } from "./opencode-transparent-aisdk.js";
|
|
47
47
|
import { BUILTIN_RULES } from "./rules/builtin.js";
|
|
48
48
|
// ─── Static failure messages (no content ever included) ─────────────────────
|
|
49
|
-
const INITIALIZATION_ERROR = "LeakShield initialization failed
|
|
50
|
-
const PROTECT_FAILED_ERROR = "LeakShield
|
|
51
|
-
const ATTRIBUTION_ERROR = "LeakShield
|
|
52
|
-
const UNSUPPORTED_ROUTE_ERROR = "LeakShield
|
|
53
|
-
const TOOL_REFUSAL_ERROR = "LeakShield
|
|
54
|
-
const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield
|
|
55
|
-
const TOOL_RESTORE_LIMIT_ERROR = "LeakShield
|
|
56
|
-
const TOOL_SHELL_CONTEXT_ERROR = "LeakShield
|
|
57
|
-
const TOOL_INPUT_SHAPE_ERROR = "LeakShield
|
|
58
|
-
const STRUCTURAL_SENSITIVE_ERROR = "LeakShield
|
|
49
|
+
const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
50
|
+
const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
|
|
51
|
+
const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
|
|
52
|
+
const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
|
|
53
|
+
const TOOL_REFUSAL_ERROR = "LeakShield blocked this tool call because its arguments could not be restored safely. Re-read the file and try again.";
|
|
54
|
+
const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield blocked this tool call before execution: a placeholder has no mapping in this session. The tool did not run. Reread the source and rebuild the affected arguments from current references; rereading does not make an old placeholder valid. If it is refused again, stop retrying and ask the user.";
|
|
55
|
+
const TOOL_RESTORE_LIMIT_ERROR = "LeakShield blocked this tool call because its arguments are too large to restore safely. Use smaller arguments and try again.";
|
|
56
|
+
const TOOL_SHELL_CONTEXT_ERROR = "LeakShield blocked this tool call because the shell command's quoting is not supported. Use a simple command with plain arguments, or a different tool.";
|
|
57
|
+
const TOOL_INPUT_SHAPE_ERROR = "LeakShield blocked this tool call because its argument structure cannot be safely restored. Use plain JSON values and try again.";
|
|
58
|
+
const STRUCTURAL_SENSITIVE_ERROR = "LeakShield blocked this request because a structural identifier (message or tool id, name, role, or part type) scans as sensitive and cannot be masked. Change it or adjust the matching rule, then try again.";
|
|
59
59
|
function toolRestoreError(reason) {
|
|
60
60
|
if (reason === "unknown_token" || reason === "malformed_token")
|
|
61
61
|
return TOOL_UNKNOWN_MAPPING_ERROR;
|
package/dist/opencode-v2.js
CHANGED
|
@@ -2,8 +2,8 @@ import { createHmac } from "node:crypto";
|
|
|
2
2
|
import { ContentHashCache, protectUnknownStrings, } from "./decision/ingress.js";
|
|
3
3
|
import { deidentifyText } from "./decision/deidentify.js";
|
|
4
4
|
import { registerV2EnvTools } from "./opencode-env-tools.js";
|
|
5
|
-
const INITIALIZATION_ERROR = "LeakShield initialization failed
|
|
6
|
-
const BLOCKED_ATTACHMENT_NOTICE = "[LeakShield blocked an attachment
|
|
5
|
+
const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
6
|
+
const BLOCKED_ATTACHMENT_NOTICE = "[LeakShield blocked an attachment: its content cannot be scanned, so it was not sent.]";
|
|
7
7
|
function isRecordLike(value) {
|
|
8
8
|
return typeof value === "object" && value !== null;
|
|
9
9
|
}
|
package/dist/rules/builtin.js
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
import { containsAddressInRun, ipv4Windows, parseCidrList } from "../scanner/cidr.js";
|
|
2
|
+
/** Networks used when a rule is evaluated without a loaded config. */
|
|
3
|
+
const DEFAULT_PRIVATE_NETWORKS = parseCidrList(undefined);
|
|
4
|
+
/**
|
|
5
|
+
* A dotted run of four or more octets.
|
|
6
|
+
*
|
|
7
|
+
* Four groups is an address. A longer run is matched whole on purpose: with
|
|
8
|
+
* the old four-group pattern, `10.1.2.3.4` yielded `10.1.2.3` and the public
|
|
9
|
+
* `1.2.3.4` inside it was never reported — which the masker then caught as
|
|
10
|
+
* residual plaintext and turned into a refusal for the whole request.
|
|
11
|
+
*/
|
|
12
|
+
const IPV4_DOTTED_RUN = /\b[0-9]{1,3}(?:\.[0-9]{1,3}){3,}\b/g;
|
|
13
|
+
import { classifyTransportSpan } from "../scanner/remotes.js";
|
|
1
14
|
/** Luhn checksum(ISO/IEC 7812-1);信用卡號形狀相符後必須通過才命中。 */
|
|
2
15
|
function luhnValid(raw) {
|
|
3
16
|
const digits = raw.replace(/[^0-9]/g, "");
|
|
@@ -36,6 +49,11 @@ function ibanValid(raw) {
|
|
|
36
49
|
/** 僅公共可路由 IPv4 視為敏感;私有/回環/鏈路本地/CGNAT/保留段不命中(config 常見值)。 */
|
|
37
50
|
function publicIPv4(raw) {
|
|
38
51
|
const octets = raw.split(".").map(Number);
|
|
52
|
+
// A run longer than four octets is reported whole when any window is a
|
|
53
|
+
// public address, so a suffix like the 1.2.3.4 in 10.1.2.3.4 is never left
|
|
54
|
+
// unmasked.
|
|
55
|
+
if (octets.length > 4)
|
|
56
|
+
return ipv4Windows(raw).some((window) => publicIPv4(window));
|
|
39
57
|
if (octets.length !== 4 || octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255))
|
|
40
58
|
return false;
|
|
41
59
|
const [a, b] = octets;
|
|
@@ -134,6 +152,18 @@ export const BUILTIN_RULES = [
|
|
|
134
152
|
// (?!\$\{) 排除環境變數參照 ${VAR};(?!\*) 排除遮罩值 ********
|
|
135
153
|
pattern: /(?:password|passwd|secret|private_key|client_secret)\s*[:=]\s*(?:['"](?!\$\{)[^'"]{8,}['"]|(?!['"\$\*])\S{8,})/gi,
|
|
136
154
|
},
|
|
155
|
+
{
|
|
156
|
+
id: "url-userinfo",
|
|
157
|
+
type: "SECRET",
|
|
158
|
+
severity: "HIGH",
|
|
159
|
+
description: "URL 內嵌憑證(user:password@)",
|
|
160
|
+
// 取到 authority 內最後一個 `@` 為止的完整 userinfo:`https://u:pa@ss@host`
|
|
161
|
+
// 若停在第一個 `@`,`ss` 會留在遮罩之外。前置 group 不吃 `:`,且以 `://`
|
|
162
|
+
// 起頭(skipPrefix 只回報 userinfo),避免可變長度 lookbehind 在每個位置
|
|
163
|
+
// 重掃造成二次方成長。
|
|
164
|
+
pattern: /:\/\/[^\s/?#:]*:[^\s/?#]*@/gi,
|
|
165
|
+
skipPrefix: 3,
|
|
166
|
+
},
|
|
137
167
|
{
|
|
138
168
|
id: "jwt",
|
|
139
169
|
type: "TOKEN",
|
|
@@ -193,7 +223,16 @@ export const BUILTIN_RULES = [
|
|
|
193
223
|
type: "PII_EMAIL",
|
|
194
224
|
severity: "MEDIUM",
|
|
195
225
|
description: "Email 地址",
|
|
196
|
-
|
|
226
|
+
// The local part is capped at 64 octets, the RFC 5321 limit. Unbounded
|
|
227
|
+
// `+` made the rule quadratic on a long token with no `@`: every start
|
|
228
|
+
// position consumed the rest of the run before failing.
|
|
229
|
+
pattern: /[a-zA-Z0-9._%+\-]{1,64}@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}/g,
|
|
230
|
+
// `user@host:path` and `ssh://user@host/…` are Git transports, not
|
|
231
|
+
// mailboxes (#34). The password half of `scheme://user:password@host` is
|
|
232
|
+
// a credential, reported by `url-userinfo` instead. Only this rule skips
|
|
233
|
+
// those spans; private domains, path keywords and URL credentials keep
|
|
234
|
+
// their own findings.
|
|
235
|
+
validate: (match, context) => classifyTransportSpan(context.text, context.index, match.length) === null,
|
|
197
236
|
},
|
|
198
237
|
{
|
|
199
238
|
id: "phone-tw",
|
|
@@ -264,9 +303,22 @@ export const BUILTIN_RULES = [
|
|
|
264
303
|
severity: "MEDIUM",
|
|
265
304
|
description: "公共 IPv4 位址",
|
|
266
305
|
// 私有/回環/CGNAT/保留段由 validate 排除,避免 config 常數誤報
|
|
267
|
-
pattern:
|
|
306
|
+
pattern: IPV4_DOTTED_RUN,
|
|
268
307
|
validate: publicIPv4,
|
|
269
308
|
},
|
|
309
|
+
{
|
|
310
|
+
id: "private-ipv4",
|
|
311
|
+
type: "PII_IP",
|
|
312
|
+
severity: "MEDIUM",
|
|
313
|
+
description: "私有 IPv4 位址",
|
|
314
|
+
// Opt-in:內網拓撲通常敏感,但位址字面值對版本號、時間戳的誤報也高。
|
|
315
|
+
// 要開啟:settings.rule_overrides["private-ipv4"]: true。預設涵蓋
|
|
316
|
+
// RFC 1918、CGNAT 與 link-local;settings.private_cidrs 可縮小範圍。
|
|
317
|
+
optIn: true,
|
|
318
|
+
pattern: IPV4_DOTTED_RUN,
|
|
319
|
+
// getRules 會以 settings.private_cidrs 換掉這個 validator。
|
|
320
|
+
validate: (match) => containsAddressInRun(DEFAULT_PRIVATE_NETWORKS, match),
|
|
321
|
+
},
|
|
270
322
|
{
|
|
271
323
|
id: "url",
|
|
272
324
|
type: "PII_URL",
|
package/dist/rules/dynamic.js
CHANGED
|
@@ -1,26 +1,54 @@
|
|
|
1
|
-
// ReDoS
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// ReDoS heuristic: run the compiled regex once against a fixed input and
|
|
2
|
+
// measure wall-clock time after exec() returns. This is a heuristic, not a
|
|
3
|
+
// guarantee: Node.js is single-threaded, so exec() cannot be interrupted, and
|
|
4
|
+
// a pattern that backtracks catastrophically on this input blocks until it
|
|
5
|
+
// finishes. Patterns that return under REDOS_TIMEOUT_MS are accepted; slower
|
|
6
|
+
// ones are skipped and reported by `--doctor`. Patterns that do not compile
|
|
7
|
+
// never get here: `loadConfig()` rejects them (fail-closed).
|
|
6
8
|
const REDOS_TIMEOUT_MS = 200;
|
|
7
9
|
const REDOS_TEST_INPUT = "a".repeat(50) + "!";
|
|
8
|
-
|
|
10
|
+
// The timing check can land on either side of the limit from one run to the
|
|
11
|
+
// next, so the first verdict for a pattern is kept for the life of the
|
|
12
|
+
// process: `--doctor` and the scanner it smoke-tests then agree on which
|
|
13
|
+
// rules are enforced. Bounded so a long-lived process cannot grow it forever.
|
|
14
|
+
const MAX_REMEMBERED_VERDICTS = 1024;
|
|
15
|
+
const verdicts = new Map();
|
|
16
|
+
export function checkCustomPattern(pattern) {
|
|
17
|
+
const remembered = verdicts.get(pattern);
|
|
18
|
+
if (remembered !== undefined)
|
|
19
|
+
return remembered;
|
|
20
|
+
const verdict = probeCustomPattern(pattern);
|
|
21
|
+
if (verdicts.size >= MAX_REMEMBERED_VERDICTS)
|
|
22
|
+
verdicts.clear();
|
|
23
|
+
verdicts.set(pattern, verdict);
|
|
24
|
+
return verdict;
|
|
25
|
+
}
|
|
26
|
+
function probeCustomPattern(pattern) {
|
|
9
27
|
let compiled;
|
|
10
28
|
try {
|
|
11
29
|
compiled = new RegExp(pattern, "gi");
|
|
12
30
|
}
|
|
13
31
|
catch {
|
|
14
|
-
return
|
|
32
|
+
return "invalid";
|
|
15
33
|
}
|
|
16
34
|
const start = Date.now();
|
|
17
35
|
try {
|
|
18
36
|
compiled.exec(REDOS_TEST_INPUT);
|
|
19
37
|
}
|
|
20
38
|
catch {
|
|
21
|
-
return
|
|
39
|
+
return "redos-suspect";
|
|
40
|
+
}
|
|
41
|
+
return Date.now() - start < REDOS_TIMEOUT_MS ? "ok" : "redos-suspect";
|
|
42
|
+
}
|
|
43
|
+
/** Descriptions of the custom rules `buildDynamicRules` skips, in config order. */
|
|
44
|
+
export function skippedCustomRules(config) {
|
|
45
|
+
const skipped = [];
|
|
46
|
+
for (const rule of config.custom_rules ?? []) {
|
|
47
|
+
const verdict = checkCustomPattern(rule.pattern);
|
|
48
|
+
if (verdict !== "ok")
|
|
49
|
+
skipped.push({ description: rule.description, reason: verdict });
|
|
22
50
|
}
|
|
23
|
-
return
|
|
51
|
+
return skipped;
|
|
24
52
|
}
|
|
25
53
|
export function buildDynamicRules(config) {
|
|
26
54
|
const rules = [];
|
|
@@ -53,8 +81,11 @@ export function buildDynamicRules(config) {
|
|
|
53
81
|
});
|
|
54
82
|
}
|
|
55
83
|
for (const rule of config.custom_rules) {
|
|
56
|
-
|
|
57
|
-
|
|
84
|
+
const verdict = checkCustomPattern(rule.pattern);
|
|
85
|
+
if (verdict !== "ok") {
|
|
86
|
+
console.warn(verdict === "invalid"
|
|
87
|
+
? `[leakshield] custom_rules: 略過無法編譯的 pattern —「${rule.description}」`
|
|
88
|
+
: `[leakshield] custom_rules: 略過疑似 ReDoS 的 pattern(計時啟發式檢查,非保證)—「${rule.description}」`);
|
|
58
89
|
continue;
|
|
59
90
|
}
|
|
60
91
|
rules.push({
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* IPv4 CIDR helpers for the private-range rule.
|
|
3
|
+
*
|
|
4
|
+
* Password-strength regex cannot express "address inside 172.16.0.0/12": a
|
|
5
|
+
* pattern that covers the range also covers version strings, and one that is
|
|
6
|
+
* narrow enough to avoid them misses octets. Membership is therefore a
|
|
7
|
+
* numeric comparison, and the network list is validated when the config
|
|
8
|
+
* loads so a typo cannot silently weaken the rule.
|
|
9
|
+
*/
|
|
10
|
+
/** Ranges the rule covers when `settings.private_cidrs` is empty. */
|
|
11
|
+
export const DEFAULT_PRIVATE_CIDRS = [
|
|
12
|
+
"10.0.0.0/8",
|
|
13
|
+
"172.16.0.0/12",
|
|
14
|
+
"192.168.0.0/16",
|
|
15
|
+
"100.64.0.0/10",
|
|
16
|
+
"169.254.0.0/16",
|
|
17
|
+
];
|
|
18
|
+
/** Dotted-quad to a 32-bit unsigned integer, or null when it is not an address. */
|
|
19
|
+
export function ipv4ToInt(raw) {
|
|
20
|
+
const parts = raw.split(".");
|
|
21
|
+
if (parts.length !== 4)
|
|
22
|
+
return null;
|
|
23
|
+
let value = 0;
|
|
24
|
+
for (const part of parts) {
|
|
25
|
+
if (!/^\d{1,3}$/.test(part))
|
|
26
|
+
return null;
|
|
27
|
+
const octet = Number(part);
|
|
28
|
+
if (octet > 255)
|
|
29
|
+
return null;
|
|
30
|
+
value = value * 256 + octet;
|
|
31
|
+
}
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
/** Parse `a.b.c.d/prefix`; returns null for anything else. */
|
|
35
|
+
export function parseCidr(text) {
|
|
36
|
+
const parts = text.trim().split("/");
|
|
37
|
+
if (parts.length !== 2)
|
|
38
|
+
return null;
|
|
39
|
+
const [address, prefixText] = parts;
|
|
40
|
+
if (!/^\d{1,2}$/.test(prefixText))
|
|
41
|
+
return null;
|
|
42
|
+
const prefix = Number(prefixText);
|
|
43
|
+
if (prefix > 32)
|
|
44
|
+
return null;
|
|
45
|
+
const addressValue = ipv4ToInt(address);
|
|
46
|
+
if (addressValue === null)
|
|
47
|
+
return null;
|
|
48
|
+
const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0;
|
|
49
|
+
return { base: (addressValue & mask) >>> 0, mask };
|
|
50
|
+
}
|
|
51
|
+
/** Parse a configured list, falling back to the documented defaults. */
|
|
52
|
+
export function parseCidrList(entries) {
|
|
53
|
+
const source = entries !== undefined && entries.length > 0 ? entries : DEFAULT_PRIVATE_CIDRS;
|
|
54
|
+
const parsed = [];
|
|
55
|
+
for (const entry of source) {
|
|
56
|
+
const cidr = parseCidr(entry);
|
|
57
|
+
if (cidr !== null)
|
|
58
|
+
parsed.push(cidr);
|
|
59
|
+
}
|
|
60
|
+
return parsed;
|
|
61
|
+
}
|
|
62
|
+
/** True when the dotted-quad address falls inside one of the networks. */
|
|
63
|
+
export function containsAddress(cidrs, raw) {
|
|
64
|
+
const value = ipv4ToInt(raw);
|
|
65
|
+
if (value === null)
|
|
66
|
+
return false;
|
|
67
|
+
return cidrs.some((cidr) => ((value & cidr.mask) >>> 0) === cidr.base);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Every four-octet window in a dotted run, in order.
|
|
71
|
+
*
|
|
72
|
+
* `10.1.2.3.4` is not an address, but it contains `1.2.3.4`. A regex finds
|
|
73
|
+
* only the first four groups, so the runner is what keeps detection
|
|
74
|
+
* consistent for the addresses hiding behind that prefix.
|
|
75
|
+
*/
|
|
76
|
+
export function ipv4Windows(raw) {
|
|
77
|
+
const parts = raw.split(".");
|
|
78
|
+
const windows = [];
|
|
79
|
+
for (let start = 0; start + 4 <= parts.length; start += 1) {
|
|
80
|
+
windows.push(parts.slice(start, start + 4).join("."));
|
|
81
|
+
}
|
|
82
|
+
return windows;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* True when `raw` is inside one of the networks, including when it is a
|
|
86
|
+
* dotted run longer than four octets: the run is reported whole if any of
|
|
87
|
+
* its four-octet windows matches.
|
|
88
|
+
*/
|
|
89
|
+
export function containsAddressInRun(cidrs, raw) {
|
|
90
|
+
const groups = raw.split(".").length;
|
|
91
|
+
if (groups === 4)
|
|
92
|
+
return containsAddress(cidrs, raw);
|
|
93
|
+
if (groups > 4)
|
|
94
|
+
return ipv4Windows(raw).some((window) => containsAddress(cidrs, window));
|
|
95
|
+
return false;
|
|
96
|
+
}
|
package/dist/scanner/engine.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BUILTIN_RULES } from "../rules/builtin.js";
|
|
2
2
|
import { buildDynamicRules } from "../rules/dynamic.js";
|
|
3
|
+
import { containsAddressInRun, parseCidrList } from "./cidr.js";
|
|
3
4
|
import { redact, getLineCol, getIgnoredLines } from "./utils.js";
|
|
4
5
|
import { t } from "../i18n/index.js";
|
|
5
6
|
import * as encoding from "./encoding.js";
|
|
@@ -18,7 +19,14 @@ function getRules(config) {
|
|
|
18
19
|
// builtin without an id would silently become always-on — tests forbid that.
|
|
19
20
|
const overrides = config.settings.rule_overrides ?? {};
|
|
20
21
|
const activeBuiltins = BUILTIN_RULES.filter((rule) => (rule.id !== undefined && rule.id in overrides ? overrides[rule.id] : !rule.optIn));
|
|
21
|
-
|
|
22
|
+
// The private-range rule is the only builtin whose verdict depends on
|
|
23
|
+
// configuration. Bind the configured networks here so the shared rule object
|
|
24
|
+
// stays constant and an empty list still means the documented defaults.
|
|
25
|
+
const privateNetworks = parseCidrList(config.settings.private_cidrs);
|
|
26
|
+
const configuredBuiltins = activeBuiltins.map((rule) => rule.id === "private-ipv4"
|
|
27
|
+
? { ...rule, validate: (match) => containsAddressInRun(privateNetworks, match) }
|
|
28
|
+
: rule);
|
|
29
|
+
return [...configuredBuiltins, ...dynamic];
|
|
22
30
|
}
|
|
23
31
|
function hasMatchingRange(findings, index, length) {
|
|
24
32
|
return findings.some((finding) => finding.match_start === index && finding.match_end === index + length);
|
|
@@ -85,14 +93,16 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
|
85
93
|
rule.pattern.lastIndex = 0;
|
|
86
94
|
let match;
|
|
87
95
|
while ((match = rule.pattern.exec(text)) !== null) {
|
|
88
|
-
const
|
|
89
|
-
|
|
96
|
+
const offset = rule.skipPrefix ?? 0;
|
|
97
|
+
const matchedText = match[0].slice(offset);
|
|
98
|
+
const start = match.index + offset;
|
|
99
|
+
if (rule.validate !== undefined && !rule.validate(matchedText, { text, index: start }))
|
|
90
100
|
continue;
|
|
91
|
-
const key = `${rule.type}:${
|
|
101
|
+
const key = `${rule.type}:${start}`;
|
|
92
102
|
if (seen.has(key))
|
|
93
103
|
continue;
|
|
94
104
|
seen.add(key);
|
|
95
|
-
const { line, col } = getLineCol(text,
|
|
105
|
+
const { line, col } = getLineCol(text, start);
|
|
96
106
|
if (ignoredLines.has(line))
|
|
97
107
|
continue;
|
|
98
108
|
const preview = redact(matchedText, config.settings.preview_length);
|
|
@@ -103,8 +113,8 @@ function collectRuleFindings(text, rules, config, ignoredLines) {
|
|
|
103
113
|
column: config.settings.show_line_numbers ? col : undefined,
|
|
104
114
|
preview,
|
|
105
115
|
description: rule.description,
|
|
106
|
-
match_start:
|
|
107
|
-
match_end: match.index +
|
|
116
|
+
match_start: start,
|
|
117
|
+
match_end: match.index + match[0].length,
|
|
108
118
|
match_text: matchedText,
|
|
109
119
|
});
|
|
110
120
|
}
|
|
@@ -279,18 +289,21 @@ protectedSpans = []) {
|
|
|
279
289
|
rule.pattern.lastIndex = 0;
|
|
280
290
|
let match;
|
|
281
291
|
while ((match = rule.pattern.exec(truncated)) !== null) {
|
|
282
|
-
|
|
292
|
+
const offset = rule.skipPrefix ?? 0;
|
|
293
|
+
const start = match.index + offset;
|
|
294
|
+
const end = match.index + match[0].length;
|
|
295
|
+
if (rule.validate !== undefined && !rule.validate(match[0].slice(offset), { text: truncated, index: start }))
|
|
283
296
|
continue;
|
|
284
|
-
if (overlapsSpan(
|
|
297
|
+
if (overlapsSpan(start, end, protectedSpans))
|
|
285
298
|
continue;
|
|
286
|
-
const key = `${
|
|
299
|
+
const key = `${start}:${end - start}`;
|
|
287
300
|
if (seen.has(key))
|
|
288
301
|
continue;
|
|
289
302
|
seen.add(key);
|
|
290
|
-
const { line } = getLineCol(truncated,
|
|
303
|
+
const { line } = getLineCol(truncated, start);
|
|
291
304
|
if (ignoredLines.has(line))
|
|
292
305
|
continue;
|
|
293
|
-
matches.push({ index:
|
|
306
|
+
matches.push({ index: start, length: end - start, type: rule.type });
|
|
294
307
|
}
|
|
295
308
|
}
|
|
296
309
|
const detector = config.exact_value_detector;
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-aware classification for email-shaped spans.
|
|
3
|
+
*
|
|
4
|
+
* A Git remote written the way SSH expects it (`user@host:path`) and the
|
|
5
|
+
* userinfo of an authenticated URL (`scheme://user:password@host`) both
|
|
6
|
+
* contain a `user@host` run that the email rule would happily report as PII.
|
|
7
|
+
* Reporting it is wrong twice over: a public host gets pseudonymized for no
|
|
8
|
+
* privacy gain, and the password half of a credential is labelled as personal
|
|
9
|
+
* data instead of a secret.
|
|
10
|
+
*
|
|
11
|
+
* The classifier reads the first scheme of the whitespace-delimited run and
|
|
12
|
+
* parses that URL's authority once. The scheme does not have to start the run,
|
|
13
|
+
* so a wrapped URL (`{"url": "https://…"}`, `url=https://…`) is recognised.
|
|
14
|
+
*
|
|
15
|
+
* Every expansion is bounded. When a boundary cannot be proven within the
|
|
16
|
+
* window the span is reported: an unproven exemption must never hide an
|
|
17
|
+
* address. The scp fallback is not attempted in that case, because it would
|
|
18
|
+
* turn a truncated run into an exemption.
|
|
19
|
+
*
|
|
20
|
+
* What it does NOT do: whitelist hosts, paths, files or commands. It only
|
|
21
|
+
* tells the email rule that this span belongs to a different construct. Every
|
|
22
|
+
* other rule still scans the same bytes.
|
|
23
|
+
*/
|
|
24
|
+
const SSH_SCHEMES = new Set(["ssh", "ssh+git", "git+ssh"]);
|
|
25
|
+
/** A run ends at whitespace; an authority cannot contain it. */
|
|
26
|
+
const RUN_BREAK = /\s/;
|
|
27
|
+
/** Characters that close an SSH host, but may appear inside a password. */
|
|
28
|
+
const FRAMING_BREAK = /["'`<>()[\]{}]/;
|
|
29
|
+
/** An SSH host is letters, digits, dot, dash, underscore, with an optional port. */
|
|
30
|
+
const SSH_HOST = /^[A-Za-z0-9._-]+(?::\d{1,5})?/;
|
|
31
|
+
/** An SSH user name; anything else means the `@` belongs to following prose. */
|
|
32
|
+
const SSH_USER = /^[A-Za-z0-9._-]+$/;
|
|
33
|
+
/** First character of an scp path. Excludes whitespace, quotes and brackets. */
|
|
34
|
+
const PATH_START = /[A-Za-z0-9._~\-/]/;
|
|
35
|
+
/** `host:2222` is a port, not an scp path; the lookahead covers `)` or EOL. */
|
|
36
|
+
const PORT_AFTER_COLON = /^\d{1,5}(?![A-Za-z0-9])/;
|
|
37
|
+
/**
|
|
38
|
+
* A scheme name must not be preceded by another scheme character, otherwise
|
|
39
|
+
* `123ssh://…` would be read as `ssh`.
|
|
40
|
+
*/
|
|
41
|
+
const SCHEME_BEFORE = /(?:^|[^A-Za-z0-9+.-])([A-Za-z][A-Za-z0-9+.-]*)$/;
|
|
42
|
+
/**
|
|
43
|
+
* Bound on every expansion. A scheme, authority or token longer than this is
|
|
44
|
+
* not a real remote; when the bound is hit without proof, report the span.
|
|
45
|
+
*/
|
|
46
|
+
const WINDOW = 512;
|
|
47
|
+
/**
|
|
48
|
+
* Start of the surrounding run, or null when its edge is farther than the
|
|
49
|
+
* window. A truncated run cannot prove which URL encloses the candidate.
|
|
50
|
+
*/
|
|
51
|
+
function runStart(text, index) {
|
|
52
|
+
const floor = Math.max(0, index - WINDOW);
|
|
53
|
+
let start = index;
|
|
54
|
+
while (start > floor && !RUN_BREAK.test(text[start - 1]))
|
|
55
|
+
start -= 1;
|
|
56
|
+
if (start === 0)
|
|
57
|
+
return 0;
|
|
58
|
+
return RUN_BREAK.test(text[start - 1]) ? start : null;
|
|
59
|
+
}
|
|
60
|
+
/** Token start, or -1 when the token edge is farther than the window. */
|
|
61
|
+
function tokenStart(text, index) {
|
|
62
|
+
const floor = Math.max(0, index - WINDOW);
|
|
63
|
+
let start = index;
|
|
64
|
+
while (start > floor && !FRAMING_BREAK.test(text[start - 1]) && !RUN_BREAK.test(text[start - 1])) {
|
|
65
|
+
start -= 1;
|
|
66
|
+
}
|
|
67
|
+
if (start === floor && floor > 0) {
|
|
68
|
+
const previous = text[start - 1];
|
|
69
|
+
if (!FRAMING_BREAK.test(previous) && !RUN_BREAK.test(previous))
|
|
70
|
+
return -1;
|
|
71
|
+
}
|
|
72
|
+
return start;
|
|
73
|
+
}
|
|
74
|
+
/** End of the authority: `/`, `?`, `#`, whitespace, or the window bound. */
|
|
75
|
+
function authorityLimit(text, authorityStart) {
|
|
76
|
+
const cap = Math.min(text.length, authorityStart + WINDOW);
|
|
77
|
+
for (let at = authorityStart; at < cap; at += 1) {
|
|
78
|
+
const char = text[at];
|
|
79
|
+
if (char === "/" || char === "?" || char === "#" || RUN_BREAK.test(char))
|
|
80
|
+
return at;
|
|
81
|
+
}
|
|
82
|
+
return cap;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Classify the span `text.slice(index, index + length)`, or return null when it
|
|
86
|
+
* is an ordinary address that the email rule should keep reporting.
|
|
87
|
+
*/
|
|
88
|
+
export function classifyTransportSpan(text, index, length) {
|
|
89
|
+
const start = runStart(text, index);
|
|
90
|
+
// Unproven run boundary: report. Falling through to scp here would exempt an
|
|
91
|
+
// address inside a URL whose start we could not see.
|
|
92
|
+
if (start === null)
|
|
93
|
+
return null;
|
|
94
|
+
// The first scheme in the run owns it. A later `://` inside the path
|
|
95
|
+
// (`https://a.example/(ssh://b/…)`) does not start a new remote.
|
|
96
|
+
const marker = text.indexOf("://", start);
|
|
97
|
+
if (marker >= 0 && marker < index) {
|
|
98
|
+
const name = SCHEME_BEFORE.exec(text.slice(Math.max(start, marker - 32), marker));
|
|
99
|
+
if (name !== null) {
|
|
100
|
+
const scheme = name[1].toLowerCase();
|
|
101
|
+
const authorityStart = marker + 3;
|
|
102
|
+
const limit = authorityLimit(text, authorityStart);
|
|
103
|
+
if (index < authorityStart || index >= limit)
|
|
104
|
+
return null;
|
|
105
|
+
const firstAt = text.indexOf("@", authorityStart);
|
|
106
|
+
if (firstAt < 0 || firstAt >= limit)
|
|
107
|
+
return null;
|
|
108
|
+
// `user:password@` — punctuation is legal inside the password, so the
|
|
109
|
+
// userinfo closes at the last `@` before the authority ends.
|
|
110
|
+
const userinfo = text.slice(authorityStart, firstAt);
|
|
111
|
+
if (userinfo.includes(":"))
|
|
112
|
+
return "url-credential";
|
|
113
|
+
if (!SSH_SCHEMES.has(scheme))
|
|
114
|
+
return null;
|
|
115
|
+
// A host-only URL has no userinfo; the first `@` then belongs to the
|
|
116
|
+
// prose after it. Only a plain SSH user name is accepted, so a separator
|
|
117
|
+
// (em dash, quote, comma) leaves the following address reported.
|
|
118
|
+
if (!SSH_USER.test(userinfo))
|
|
119
|
+
return null;
|
|
120
|
+
// The exemption covers the host only. A whitelist of host characters is
|
|
121
|
+
// deliberate: any other character ends the host.
|
|
122
|
+
const host = SSH_HOST.exec(text.slice(firstAt + 1, limit));
|
|
123
|
+
if (host === null)
|
|
124
|
+
return null;
|
|
125
|
+
return index < firstAt + 1 + host[0].length ? "ssh-authority" : null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
// scp-like form. The address must open its token: `foo=user@host:path` is
|
|
129
|
+
// left alone rather than guessed.
|
|
130
|
+
const tokenEdge = tokenStart(text, index);
|
|
131
|
+
if (tokenEdge !== index)
|
|
132
|
+
return null;
|
|
133
|
+
if (text[index + length] !== ":")
|
|
134
|
+
return null;
|
|
135
|
+
const after = text.slice(index + length + 1, index + length + 8);
|
|
136
|
+
if (PORT_AFTER_COLON.test(after))
|
|
137
|
+
return null;
|
|
138
|
+
const first = after[0];
|
|
139
|
+
return first !== undefined && PATH_START.test(first) ? "ssh-authority" : null;
|
|
140
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "leakshield",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "OpenCode plugin, CLI, and web scanner for sensitive content before sending it to AI",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"node": ">=20"
|
|
35
35
|
},
|
|
36
36
|
"bin": {
|
|
37
|
-
"leakshield": "
|
|
37
|
+
"leakshield": "dist/cli.js"
|
|
38
38
|
},
|
|
39
39
|
"scripts": {
|
|
40
40
|
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
|