leakshield 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +546 -2
- package/README.zh-TW.md +565 -0
- package/dist/cli.js +61 -0
- package/dist/config/loader.js +94 -0
- package/dist/decision/deidentify.js +195 -0
- package/dist/decision/ingress.js +136 -0
- package/dist/decision/mapping-key.js +318 -0
- package/dist/decision/mapping-store.js +555 -0
- package/dist/decision/model.js +76 -0
- package/dist/decision/pseudonymization.js +1230 -0
- package/dist/decision/redaction.js +185 -0
- package/dist/decision/schema-strings.js +42 -0
- package/dist/doctor.js +438 -0
- package/dist/env-queries.js +584 -0
- package/dist/forget.js +56 -0
- package/dist/help.js +37 -0
- package/dist/i18n/en.js +71 -0
- package/dist/i18n/index.js +28 -0
- package/dist/i18n/zh-TW.js +71 -0
- package/dist/index.js +12 -0
- package/dist/opencode-env-tools.js +243 -0
- package/dist/opencode-hooks.js +84 -0
- package/dist/opencode-transparent-aisdk.js +100 -0
- package/dist/opencode-transparent-http.js +2315 -0
- package/dist/opencode-transparent-stream.js +192 -0
- package/dist/opencode-transparent-ws.js +298 -0
- package/dist/opencode-transparent.js +1492 -0
- package/dist/opencode-v2.js +216 -0
- package/dist/opencode.js +175 -0
- package/dist/plugin-options.js +100 -0
- package/dist/rules/builtin.js +283 -0
- package/dist/rules/dynamic.js +68 -0
- package/dist/scanner/encoding.js +274 -0
- package/dist/scanner/engine.js +321 -0
- package/dist/scanner/exact-values.js +99 -0
- package/dist/scanner/redaction-verifier.js +82 -0
- package/dist/scanner/unicode.js +157 -0
- package/dist/scanner/utils.js +60 -0
- package/dist/transports/cli.js +447 -0
- package/dist/transports/web-ui.js +540 -0
- package/dist/transports/web.js +200 -0
- package/dist/types.js +23 -0
- package/dist/utils/files.js +36 -0
- package/dist/utils/path-security.js +30 -0
- package/dist/utils/win-encoding.js +45 -0
- package/package.json +71 -4
package/dist/i18n/en.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export const en = {
|
|
2
|
+
// engine — scan
|
|
3
|
+
"scan.safe_summary": "✅ No sensitive content detected, safe to send.",
|
|
4
|
+
"scan.unsafe_summary": "🚨 Found {count} potential sensitive item(s) (HIGH: {high}, MEDIUM: {med}, LOW: {low})",
|
|
5
|
+
"scan.safe_recommendation": "Content looks safe, but please verify there are no business-logic secrets.",
|
|
6
|
+
"scan.unsafe_recommendation": "⛔ Please address the above sensitive items before sending to AI services. Use placeholder data or remove sensitive fields, then retry.",
|
|
7
|
+
// engine — redact
|
|
8
|
+
"redact.safe_summary": "✅ No sensitive content detected, nothing to redact.",
|
|
9
|
+
"redact.unsafe_summary": "🔒 Redacted {count} sensitive item(s).",
|
|
10
|
+
// cli — print result
|
|
11
|
+
"cli.scan_target": "📋 Scan target: {label}",
|
|
12
|
+
"cli.hits": "{count} hit(s)",
|
|
13
|
+
"cli.location": " (line {line}, col {col})",
|
|
14
|
+
"cli.preview": " Preview: {preview}",
|
|
15
|
+
"cli.more_of_type": " … {count} more of the same type",
|
|
16
|
+
// cli — errors
|
|
17
|
+
"cli.error_file_not_found": "❌ File not found: {path}",
|
|
18
|
+
"cli.error_dir_not_found": "❌ Directory not found: {path}",
|
|
19
|
+
"cli.error_redact_no_input": "❌ --redact requires --text, --file, or --stdin",
|
|
20
|
+
"cli.error_path": "❌ {error}",
|
|
21
|
+
// cli — redact / dry-run
|
|
22
|
+
"cli.dryrun_header": "\n[DRY-RUN] Would redact {count} finding(s) in {label}:",
|
|
23
|
+
"cli.dryrun_safe": " ✅ No sensitive content detected, nothing to redact.",
|
|
24
|
+
"cli.dryrun_location": " line {line}, col {col}",
|
|
25
|
+
"cli.dryrun_preview": " preview: {preview} → [REDACTED_{type}]",
|
|
26
|
+
"cli.redact_written": "✅ Redacted content written to: {path}",
|
|
27
|
+
"cli.redact_footer": "[leakshield] {summary}",
|
|
28
|
+
"cli.redact_incomplete": "⛔ Redaction incomplete: {residual} residual finding(s) remain after redaction. Output suppressed.",
|
|
29
|
+
"cli.redact_verified": "✅ Redaction verified — no residual findings.",
|
|
30
|
+
// cli — dir mode
|
|
31
|
+
"cli.scan_dir": "\n🔍 Scanning directory: {path}",
|
|
32
|
+
"cli.ext_filter": " Extension filter: {exts}",
|
|
33
|
+
"cli.found_files": " Found {count} file(s)\n",
|
|
34
|
+
"cli.skipped_files": " Skipped {count} unreadable file(s)\n",
|
|
35
|
+
"cli.dir_complete": "✅ Scan complete, {count} file(s) all clean.\n",
|
|
36
|
+
// cli — inline label
|
|
37
|
+
"cli.inline_label": "(inline text)",
|
|
38
|
+
// cli — decision-aware output
|
|
39
|
+
"cli.decision_warn_header": "Reminder — {risk} risk: {count} sensitive item(s) detected",
|
|
40
|
+
"cli.decision_confirm_header": "Warning — {risk} risk: {count} sensitive item(s) detected (recommended: {action})",
|
|
41
|
+
"cli.confirm_next_step": "Next: use --format json to get redactedContent, or --redact for sanitized output. Exit code 1 = blocked.",
|
|
42
|
+
// cli — usage
|
|
43
|
+
"cli.usage_title": "\n🛡️ leakshield — Sensitive content guard\n",
|
|
44
|
+
"cli.usage_heading": "Usage:",
|
|
45
|
+
"cli.usage_text": " leakshield --text 'your content'",
|
|
46
|
+
"cli.usage_file": " leakshield --file ./path/to/file.ts",
|
|
47
|
+
"cli.usage_dir": " leakshield --dir ./src",
|
|
48
|
+
"cli.usage_dir_ext": " leakshield --dir ./src --ext .ts .env .json",
|
|
49
|
+
"cli.usage_stdin": " cat file.ts | leakshield --stdin",
|
|
50
|
+
"cli.usage_web": " leakshield --web [--port 3000] Start local Web UI",
|
|
51
|
+
"cli.usage_redact_heading": "\nRedact mode:",
|
|
52
|
+
"cli.usage_redact_text": " leakshield --redact --text 'your content'",
|
|
53
|
+
"cli.usage_redact_file": " leakshield --redact --file ./secret.env",
|
|
54
|
+
"cli.usage_redact_out": " leakshield --redact --file ./secret.env --out ./redacted.env",
|
|
55
|
+
"cli.usage_redact_stdin": " cat file.ts | leakshield --redact --stdin",
|
|
56
|
+
"cli.usage_redact_dryrun": " leakshield --redact --dry-run --file ./secret.env # preview only, no output",
|
|
57
|
+
"cli.usage_options_heading": "\nOptions:",
|
|
58
|
+
"cli.usage_opt_format": " --format json JSON output (suitable for CI/CD)",
|
|
59
|
+
"cli.usage_opt_severity": " --min-severity high Report HIGH only (or medium / low)",
|
|
60
|
+
"cli.usage_opt_redact": " --redact Redact mode (output sanitized text)",
|
|
61
|
+
"cli.usage_opt_dryrun": " --dry-run Preview only, no output (use with --redact)",
|
|
62
|
+
"cli.usage_opt_out": " --out <path> Output path (use with --redact --file)",
|
|
63
|
+
"cli.usage_opt_outside": " --allow-outside Allow scanning paths outside the working directory (disabled by default)",
|
|
64
|
+
"cli.usage_opt_web": " --web Start local Web UI (default port 3000)",
|
|
65
|
+
"cli.usage_opt_port": " --port <port> Web UI port (use with --web)",
|
|
66
|
+
"cli.usage_opt_encoding": " --enable-encoding-detection Enable Base64/URL/Hex decoding detection (disabled by default)",
|
|
67
|
+
// web — server start
|
|
68
|
+
"web.server_title": "🛡️ leakshield web UI",
|
|
69
|
+
"web.server_url": " http://localhost:{port}",
|
|
70
|
+
"web.server_stop": " Press Ctrl+C to stop",
|
|
71
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { en } from "./en.js";
|
|
2
|
+
import { zhTW } from "./zh-TW.js";
|
|
3
|
+
const SUPPORTED_LOCALES = ["en", "zh-TW"];
|
|
4
|
+
function resolveLocale() {
|
|
5
|
+
const lang = process.env.LEAKSHIELD_LANG ?? "en";
|
|
6
|
+
if (lang === "zh-TW" || lang === "zh")
|
|
7
|
+
return "zh-TW";
|
|
8
|
+
return "en";
|
|
9
|
+
}
|
|
10
|
+
const locale = resolveLocale();
|
|
11
|
+
const catalog = locale === "zh-TW" ? zhTW : en;
|
|
12
|
+
/**
|
|
13
|
+
* Translate a message key, interpolating `{param}` placeholders.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* t("scan.safe_summary")
|
|
17
|
+
* t("cli.found_files", { count: 12 })
|
|
18
|
+
*/
|
|
19
|
+
export function t(key, params) {
|
|
20
|
+
let msg = catalog[key] ?? en[key] ?? key;
|
|
21
|
+
if (params) {
|
|
22
|
+
for (const [k, v] of Object.entries(params)) {
|
|
23
|
+
msg = msg.replaceAll(`{${k}}`, String(v));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return msg;
|
|
27
|
+
}
|
|
28
|
+
export { locale };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export const zhTW = {
|
|
2
|
+
// engine — scan
|
|
3
|
+
"scan.safe_summary": "✅ 未偵測到敏感內容,可以安全傳送。",
|
|
4
|
+
"scan.unsafe_summary": "🚨 發現 {count} 個潛在敏感項目(HIGH: {high}, MEDIUM: {med}, LOW: {low})",
|
|
5
|
+
"scan.safe_recommendation": "內容看起來安全,但仍請確認沒有業務邏輯上的機密資訊。",
|
|
6
|
+
"scan.unsafe_recommendation": "⛔ 建議先處理上述敏感項目後再傳送給 AI 服務。請用假資料、佔位符或移除敏感欄位後再重試。",
|
|
7
|
+
// engine — redact
|
|
8
|
+
"redact.safe_summary": "✅ 未偵測到敏感內容,無需脫敏。",
|
|
9
|
+
"redact.unsafe_summary": "🔒 已脫敏 {count} 個敏感項目。",
|
|
10
|
+
// cli — print result
|
|
11
|
+
"cli.scan_target": "📋 掃描目標:{label}",
|
|
12
|
+
"cli.hits": "{count} 個命中",
|
|
13
|
+
"cli.location": " (第 {line} 行, 欄 {col})",
|
|
14
|
+
"cli.preview": " 預覽:{preview}",
|
|
15
|
+
"cli.more_of_type": " … 還有 {count} 個相同類型",
|
|
16
|
+
// cli — errors
|
|
17
|
+
"cli.error_file_not_found": "❌ 找不到檔案:{path}",
|
|
18
|
+
"cli.error_dir_not_found": "❌ 找不到目錄:{path}",
|
|
19
|
+
"cli.error_redact_no_input": "❌ --redact 需搭配 --text、--file 或 --stdin",
|
|
20
|
+
"cli.error_path": "❌ {error}",
|
|
21
|
+
// cli — redact / dry-run
|
|
22
|
+
"cli.dryrun_header": "\n[DRY-RUN] 將脫敏 {count} 個敏感項目於 {label}:",
|
|
23
|
+
"cli.dryrun_safe": " ✅ 未偵測到敏感內容,無需脫敏。",
|
|
24
|
+
"cli.dryrun_location": " 第 {line} 行, 欄 {col}",
|
|
25
|
+
"cli.dryrun_preview": " 預覽:{preview} → [REDACTED_{type}]",
|
|
26
|
+
"cli.redact_written": "✅ 已將脫敏內容寫入:{path}",
|
|
27
|
+
"cli.redact_footer": "[leakshield] {summary}",
|
|
28
|
+
"cli.redact_incomplete": "⛔ 脫敏不完整:redact 後仍有 {residual} 個殘留命中。輸出已停止。",
|
|
29
|
+
"cli.redact_verified": "✅ 脫敏已驗證 — 無殘留命中。",
|
|
30
|
+
// cli — dir mode
|
|
31
|
+
"cli.scan_dir": "\n🔍 掃描目錄:{path}",
|
|
32
|
+
"cli.ext_filter": " 副檔名篩選:{exts}",
|
|
33
|
+
"cli.found_files": " 找到 {count} 個檔案\n",
|
|
34
|
+
"cli.skipped_files": " 跳過 {count} 個無法讀取的檔案\n",
|
|
35
|
+
"cli.dir_complete": "✅ 掃描完成,{count} 個檔案均未發現敏感內容。\n",
|
|
36
|
+
// cli — inline label
|
|
37
|
+
"cli.inline_label": "(直接輸入文字)",
|
|
38
|
+
// cli — decision-aware output
|
|
39
|
+
"cli.decision_warn_header": "提醒 — {risk} 風險:偵測到 {count} 個敏感項目",
|
|
40
|
+
"cli.decision_confirm_header": "警告 — {risk} 風險:偵測到 {count} 個敏感項目(建議操作:{action})",
|
|
41
|
+
"cli.confirm_next_step": "下一步:使用 --format json 取得 redactedContent,或用 --redact 輸出脫敏版本。Exit code 1 = 已攔截。",
|
|
42
|
+
// cli — usage
|
|
43
|
+
"cli.usage_title": "\n🛡️ leakshield — 敏感內容守門員\n",
|
|
44
|
+
"cli.usage_heading": "用法:",
|
|
45
|
+
"cli.usage_text": " leakshield --text '你的內容'",
|
|
46
|
+
"cli.usage_file": " leakshield --file ./path/to/file.ts",
|
|
47
|
+
"cli.usage_dir": " leakshield --dir ./src",
|
|
48
|
+
"cli.usage_dir_ext": " leakshield --dir ./src --ext .ts .env .json",
|
|
49
|
+
"cli.usage_stdin": " cat file.ts | leakshield --stdin",
|
|
50
|
+
"cli.usage_web": " leakshield --web [--port 3000] 啟動本機 Web UI",
|
|
51
|
+
"cli.usage_redact_heading": "\n脫敏模式:",
|
|
52
|
+
"cli.usage_redact_text": " leakshield --redact --text '你的內容'",
|
|
53
|
+
"cli.usage_redact_file": " leakshield --redact --file ./secret.env",
|
|
54
|
+
"cli.usage_redact_out": " leakshield --redact --file ./secret.env --out ./redacted.env",
|
|
55
|
+
"cli.usage_redact_stdin": " cat file.ts | leakshield --redact --stdin",
|
|
56
|
+
"cli.usage_redact_dryrun": " leakshield --redact --dry-run --file ./secret.env # 只預覽,不輸出",
|
|
57
|
+
"cli.usage_options_heading": "\n選項:",
|
|
58
|
+
"cli.usage_opt_format": " --format json 輸出 JSON(適合 CI/CD)",
|
|
59
|
+
"cli.usage_opt_severity": " --min-severity high 只回報 HIGH(或 medium / low)",
|
|
60
|
+
"cli.usage_opt_redact": " --redact 脫敏模式(輸出替換後文字)",
|
|
61
|
+
"cli.usage_opt_dryrun": " --dry-run 搭配 --redact,只預覽不輸出",
|
|
62
|
+
"cli.usage_opt_out": " --out <path> 搭配 --redact --file,指定輸出路徑",
|
|
63
|
+
"cli.usage_opt_outside": " --allow-outside 允許掃描工作目錄以外的路徑(預設禁止)",
|
|
64
|
+
"cli.usage_opt_web": " --web 啟動本機 Web UI(預設 port 3000)",
|
|
65
|
+
"cli.usage_opt_port": " --port <port> 指定 Web UI 埠號(搭配 --web)",
|
|
66
|
+
"cli.usage_opt_encoding": " --enable-encoding-detection 啟用 Base64/URL/Hex 解碼檢測(預設關閉)",
|
|
67
|
+
// web — server start
|
|
68
|
+
"web.server_title": "🛡️ leakshield web UI",
|
|
69
|
+
"web.server_url": " http://localhost:{port}",
|
|
70
|
+
"web.server_stop": " Ctrl+C 停止",
|
|
71
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Package entrypoint for the OpenCode plugin loaders.
|
|
3
|
+
*
|
|
4
|
+
* - OpenCode v2 resolves the package `main` (or `<dir>/index.js` when the dist
|
|
5
|
+
* directory is configured directly) to this file.
|
|
6
|
+
* - The default export is the dual-version plugin definition: v2 hosts read
|
|
7
|
+
* `id` + `setup(ctx)`, v1 hosts (1.18.29+) call `server(input, options)`.
|
|
8
|
+
*
|
|
9
|
+
* The CLI/web entrypoint lives in `./cli.js` (published as the `leakshield`
|
|
10
|
+
* bin) so importing this module never starts an interactive process.
|
|
11
|
+
*/
|
|
12
|
+
export { default } from "./opencode.js";
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { MAX_FILE_ID_LENGTH, MAX_KEY_NAME_LENGTH } from "./env-queries.js";
|
|
2
|
+
const FAILURE_MESSAGES = {
|
|
3
|
+
disabled: "Env queries are disabled because the guard configuration changed. Restart OpenCode.",
|
|
4
|
+
unknown_file_id: "Unknown file id. File ids are session-local and issued by guard_env_list.",
|
|
5
|
+
invalid_arguments: "Invalid arguments.",
|
|
6
|
+
};
|
|
7
|
+
const INTERNAL_ERROR = "Env query failed.";
|
|
8
|
+
function safePayload(run) {
|
|
9
|
+
try {
|
|
10
|
+
return run();
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return { error: INTERNAL_ERROR };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function onFailure(failure) {
|
|
17
|
+
return { error: FAILURE_MESSAGES[failure.code] };
|
|
18
|
+
}
|
|
19
|
+
const LIST_DESCRIPTION = "List the env files enabled for readonly querying and their key names. " +
|
|
20
|
+
"Returns one opaque session-local file id per enabled file plus its key names — never values, lengths, or previews. " +
|
|
21
|
+
"File ids are only valid in this session. Unreadable files are reported with fixed reason codes.";
|
|
22
|
+
const INSPECT_DESCRIPTION = "Inspect one key in an enabled env file without revealing its value. " +
|
|
23
|
+
"Returns status missing | empty | nonempty and, when nonempty, a coarse lexical shape: boolean_like | number_like | multiline_text | text. " +
|
|
24
|
+
"A shape is a lexical hint only, never a claim that the value is a valid boolean or number.";
|
|
25
|
+
const COMPARE_DESCRIPTION = "Compare the values of two keys in enabled env files (same file or cross-file) without revealing them. " +
|
|
26
|
+
"Returns equal | different | unavailable. Both operands must be existing keys of enabled files; missing keys or unreadable files are unavailable. " +
|
|
27
|
+
"Raw values are never returned.";
|
|
28
|
+
function listPayload(service, sessionID) {
|
|
29
|
+
const result = service.listFiles(sessionID);
|
|
30
|
+
return result.ok ? { files: result.files } : onFailure(result);
|
|
31
|
+
}
|
|
32
|
+
function inspectPayload(service, sessionID, fileId, key) {
|
|
33
|
+
const result = service.inspectKey(sessionID, fileId, key);
|
|
34
|
+
return result.ok ? inspectOutcomePayload(result) : onFailure(result);
|
|
35
|
+
}
|
|
36
|
+
function inspectOutcomePayload(outcome) {
|
|
37
|
+
switch (outcome.status) {
|
|
38
|
+
case "unavailable":
|
|
39
|
+
return { status: "unavailable", reason: outcome.reason };
|
|
40
|
+
case "nonempty":
|
|
41
|
+
return { status: "nonempty", shape: outcome.shape };
|
|
42
|
+
default:
|
|
43
|
+
return { status: outcome.status };
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function comparePayload(service, sessionID, left, right) {
|
|
47
|
+
const result = service.compareKeys(sessionID, left, right);
|
|
48
|
+
if (!result.ok)
|
|
49
|
+
return onFailure(result);
|
|
50
|
+
const outcome = result;
|
|
51
|
+
return outcome.result === "unavailable"
|
|
52
|
+
? { result: "unavailable", ...(outcome.reason ? { reason: outcome.reason } : {}) }
|
|
53
|
+
: { result: outcome.result };
|
|
54
|
+
}
|
|
55
|
+
function isRecordLike(value) {
|
|
56
|
+
return typeof value === "object" && value !== null;
|
|
57
|
+
}
|
|
58
|
+
function readStringField(input, field, maxLength) {
|
|
59
|
+
if (!isRecordLike(input))
|
|
60
|
+
return undefined;
|
|
61
|
+
const value = input[field];
|
|
62
|
+
if (typeof value !== "string" || value.length === 0 || value.length > maxLength)
|
|
63
|
+
return undefined;
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
/** Runtime validation for v2, where tool input arrives as unknown. */
|
|
67
|
+
function readInspectArgs(input) {
|
|
68
|
+
const file_id = readStringField(input, "file_id", MAX_FILE_ID_LENGTH);
|
|
69
|
+
const key = readStringField(input, "key", MAX_KEY_NAME_LENGTH);
|
|
70
|
+
return file_id && key ? { file_id, key } : undefined;
|
|
71
|
+
}
|
|
72
|
+
function readCompareArgs(input) {
|
|
73
|
+
const left_file_id = readStringField(input, "left_file_id", MAX_FILE_ID_LENGTH);
|
|
74
|
+
const left_key = readStringField(input, "left_key", MAX_KEY_NAME_LENGTH);
|
|
75
|
+
const right_file_id = readStringField(input, "right_file_id", MAX_FILE_ID_LENGTH);
|
|
76
|
+
const right_key = readStringField(input, "right_key", MAX_KEY_NAME_LENGTH);
|
|
77
|
+
return left_file_id && left_key && right_file_id && right_key
|
|
78
|
+
? { left_file_id, left_key, right_file_id, right_key }
|
|
79
|
+
: undefined;
|
|
80
|
+
}
|
|
81
|
+
// ─── OpenCode v1 ─────────────────────────────────────────────────────────────
|
|
82
|
+
/** Builds the v1 tool map for `Hooks["tool"]` when `envQueries` is enabled. */
|
|
83
|
+
export async function createV1EnvTools(service) {
|
|
84
|
+
// Runtime dependency on the v1 SDK's tool helper; loaded dynamically so a
|
|
85
|
+
// v2 host never needs the v1 SDK package. A v1 host always provides it.
|
|
86
|
+
const { tool } = await import("@opencode-ai/plugin/tool");
|
|
87
|
+
const z = tool.schema;
|
|
88
|
+
const guardEnvList = tool({
|
|
89
|
+
description: LIST_DESCRIPTION,
|
|
90
|
+
args: {},
|
|
91
|
+
async execute(_args, context) {
|
|
92
|
+
return {
|
|
93
|
+
title: "guard_env_list",
|
|
94
|
+
output: JSON.stringify(safePayload(() => listPayload(service, context.sessionID))),
|
|
95
|
+
};
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
const guardEnvInspect = tool({
|
|
99
|
+
description: INSPECT_DESCRIPTION,
|
|
100
|
+
args: {
|
|
101
|
+
file_id: z
|
|
102
|
+
.string()
|
|
103
|
+
.min(1)
|
|
104
|
+
.max(MAX_FILE_ID_LENGTH)
|
|
105
|
+
.describe("Session-local file id issued by guard_env_list."),
|
|
106
|
+
key: z
|
|
107
|
+
.string()
|
|
108
|
+
.min(1)
|
|
109
|
+
.max(MAX_KEY_NAME_LENGTH)
|
|
110
|
+
.describe("Key name as listed by guard_env_list."),
|
|
111
|
+
},
|
|
112
|
+
async execute(args, context) {
|
|
113
|
+
return {
|
|
114
|
+
title: "guard_env_inspect",
|
|
115
|
+
output: JSON.stringify(safePayload(() => inspectPayload(service, context.sessionID, args.file_id, args.key))),
|
|
116
|
+
};
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
const guardEnvCompare = tool({
|
|
120
|
+
description: COMPARE_DESCRIPTION,
|
|
121
|
+
args: {
|
|
122
|
+
left_file_id: z
|
|
123
|
+
.string()
|
|
124
|
+
.min(1)
|
|
125
|
+
.max(MAX_FILE_ID_LENGTH)
|
|
126
|
+
.describe("Session-local file id of the left operand."),
|
|
127
|
+
left_key: z
|
|
128
|
+
.string()
|
|
129
|
+
.min(1)
|
|
130
|
+
.max(MAX_KEY_NAME_LENGTH)
|
|
131
|
+
.describe("Key name of the left operand."),
|
|
132
|
+
right_file_id: z
|
|
133
|
+
.string()
|
|
134
|
+
.min(1)
|
|
135
|
+
.max(MAX_FILE_ID_LENGTH)
|
|
136
|
+
.describe("Session-local file id of the right operand."),
|
|
137
|
+
right_key: z
|
|
138
|
+
.string()
|
|
139
|
+
.min(1)
|
|
140
|
+
.max(MAX_KEY_NAME_LENGTH)
|
|
141
|
+
.describe("Key name of the right operand."),
|
|
142
|
+
},
|
|
143
|
+
async execute(args, context) {
|
|
144
|
+
return {
|
|
145
|
+
title: "guard_env_compare",
|
|
146
|
+
output: JSON.stringify(safePayload(() => comparePayload(service, context.sessionID, { fileId: args.left_file_id, key: args.left_key }, { fileId: args.right_file_id, key: args.right_key }))),
|
|
147
|
+
};
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
return {
|
|
151
|
+
guard_env_list: guardEnvList,
|
|
152
|
+
guard_env_inspect: guardEnvInspect,
|
|
153
|
+
guard_env_compare: guardEnvCompare,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
// ─── OpenCode v2 ─────────────────────────────────────────────────────────────
|
|
157
|
+
/**
|
|
158
|
+
* Registers the env query tools on an OpenCode v2 plugin context via
|
|
159
|
+
* `ctx.tool.transform(editor => editor.add(...))`. Tool inputs are literal
|
|
160
|
+
* JSON Schemas; `execute` validates the raw input at runtime.
|
|
161
|
+
*/
|
|
162
|
+
export async function registerV2EnvTools(ctx, service) {
|
|
163
|
+
await ctx.tool.transform((editor) => {
|
|
164
|
+
editor.add({
|
|
165
|
+
name: "guard_env_list",
|
|
166
|
+
description: LIST_DESCRIPTION,
|
|
167
|
+
input: { type: "object", properties: {}, required: [], additionalProperties: false },
|
|
168
|
+
output: { type: "object" },
|
|
169
|
+
async execute(_input, context) {
|
|
170
|
+
const payload = safePayload(() => listPayload(service, context.sessionID));
|
|
171
|
+
return { output: payload, content: JSON.stringify(payload) };
|
|
172
|
+
},
|
|
173
|
+
});
|
|
174
|
+
editor.add({
|
|
175
|
+
name: "guard_env_inspect",
|
|
176
|
+
description: INSPECT_DESCRIPTION,
|
|
177
|
+
input: {
|
|
178
|
+
type: "object",
|
|
179
|
+
properties: {
|
|
180
|
+
file_id: {
|
|
181
|
+
type: "string",
|
|
182
|
+
maxLength: MAX_FILE_ID_LENGTH,
|
|
183
|
+
description: "Session-local file id issued by guard_env_list.",
|
|
184
|
+
},
|
|
185
|
+
key: {
|
|
186
|
+
type: "string",
|
|
187
|
+
maxLength: MAX_KEY_NAME_LENGTH,
|
|
188
|
+
description: "Key name as listed by guard_env_list.",
|
|
189
|
+
},
|
|
190
|
+
},
|
|
191
|
+
required: ["file_id", "key"],
|
|
192
|
+
additionalProperties: false,
|
|
193
|
+
},
|
|
194
|
+
output: { type: "object" },
|
|
195
|
+
async execute(input, context) {
|
|
196
|
+
const args = readInspectArgs(input);
|
|
197
|
+
const payload = safePayload(() => args
|
|
198
|
+
? inspectPayload(service, context.sessionID, args.file_id, args.key)
|
|
199
|
+
: onFailure({ ok: false, code: "invalid_arguments" }));
|
|
200
|
+
return { output: payload, content: JSON.stringify(payload) };
|
|
201
|
+
},
|
|
202
|
+
});
|
|
203
|
+
editor.add({
|
|
204
|
+
name: "guard_env_compare",
|
|
205
|
+
description: COMPARE_DESCRIPTION,
|
|
206
|
+
input: {
|
|
207
|
+
type: "object",
|
|
208
|
+
properties: {
|
|
209
|
+
left_file_id: {
|
|
210
|
+
type: "string",
|
|
211
|
+
maxLength: MAX_FILE_ID_LENGTH,
|
|
212
|
+
description: "Session-local file id of the left operand.",
|
|
213
|
+
},
|
|
214
|
+
left_key: {
|
|
215
|
+
type: "string",
|
|
216
|
+
maxLength: MAX_KEY_NAME_LENGTH,
|
|
217
|
+
description: "Key name of the left operand.",
|
|
218
|
+
},
|
|
219
|
+
right_file_id: {
|
|
220
|
+
type: "string",
|
|
221
|
+
maxLength: MAX_FILE_ID_LENGTH,
|
|
222
|
+
description: "Session-local file id of the right operand.",
|
|
223
|
+
},
|
|
224
|
+
right_key: {
|
|
225
|
+
type: "string",
|
|
226
|
+
maxLength: MAX_KEY_NAME_LENGTH,
|
|
227
|
+
description: "Key name of the right operand.",
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
required: ["left_file_id", "left_key", "right_file_id", "right_key"],
|
|
231
|
+
additionalProperties: false,
|
|
232
|
+
},
|
|
233
|
+
output: { type: "object" },
|
|
234
|
+
async execute(input, context) {
|
|
235
|
+
const args = readCompareArgs(input);
|
|
236
|
+
const payload = safePayload(() => args
|
|
237
|
+
? comparePayload(service, context.sessionID, { fileId: args.left_file_id, key: args.left_key }, { fileId: args.right_file_id, key: args.right_key })
|
|
238
|
+
: onFailure({ ok: false, code: "invalid_arguments" }));
|
|
239
|
+
return { output: payload, content: JSON.stringify(payload) };
|
|
240
|
+
},
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { ContentHashCache, protectUnknownStrings, } from "./decision/ingress.js";
|
|
2
|
+
const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
3
|
+
function blockedAttachment(part) {
|
|
4
|
+
return {
|
|
5
|
+
id: part.id,
|
|
6
|
+
sessionID: part.sessionID,
|
|
7
|
+
messageID: part.messageID,
|
|
8
|
+
type: "text",
|
|
9
|
+
text: "[LeakShield blocked an attachment: its content cannot be scanned, so it was not sent.]",
|
|
10
|
+
synthetic: true,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function protectParts(parts, config, mode, protector) {
|
|
14
|
+
return parts.map((part) => {
|
|
15
|
+
if (part.type === "file")
|
|
16
|
+
return blockedAttachment(part);
|
|
17
|
+
if (part.type === "text") {
|
|
18
|
+
const protectedText = protector(part.text, config, { mode, context: "message text" });
|
|
19
|
+
return { ...part, text: protectedText.text };
|
|
20
|
+
}
|
|
21
|
+
if (part.type === "reasoning") {
|
|
22
|
+
const protectedText = protector(part.text, config, { mode, context: "reasoning text" });
|
|
23
|
+
return { ...part, text: protectedText.text };
|
|
24
|
+
}
|
|
25
|
+
if (part.type === "tool") {
|
|
26
|
+
return {
|
|
27
|
+
...part,
|
|
28
|
+
state: protectUnknownStrings(part.state, config, { mode, context: "tool history" }, protector),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
if (part.type === "subtask") {
|
|
32
|
+
const protectedPrompt = protector(part.prompt, config, { mode, context: "subtask prompt" });
|
|
33
|
+
const protectedDescription = protector(part.description, config, { mode, context: "subtask description" });
|
|
34
|
+
return { ...part, prompt: protectedPrompt.text, description: protectedDescription.text };
|
|
35
|
+
}
|
|
36
|
+
if (part.type === "retry") {
|
|
37
|
+
return {
|
|
38
|
+
...part,
|
|
39
|
+
error: protectUnknownStrings(part.error, config, { mode, context: "retry error" }, protector),
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return part;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
export function createHooks(config, mode) {
|
|
46
|
+
const cache = new ContentHashCache();
|
|
47
|
+
const protectWithCache = (text, currentConfig, options) => cache.protect(text, currentConfig, options);
|
|
48
|
+
return {
|
|
49
|
+
"chat.message": async (_input, output) => {
|
|
50
|
+
output.parts.splice(0, output.parts.length, ...protectParts(output.parts, config, mode, protectWithCache));
|
|
51
|
+
},
|
|
52
|
+
"tool.execute.after": async (_input, output) => {
|
|
53
|
+
const protectedTitle = protectWithCache(output.title, config, { mode, context: "tool title" });
|
|
54
|
+
const protectedOutput = protectWithCache(output.output, config, { mode, context: "tool output" });
|
|
55
|
+
output.title = protectedTitle.text;
|
|
56
|
+
output.output = protectedOutput.text;
|
|
57
|
+
output.metadata = protectUnknownStrings(output.metadata, config, { mode, context: "tool metadata" }, protectWithCache);
|
|
58
|
+
},
|
|
59
|
+
"experimental.chat.messages.transform": async (_input, output) => {
|
|
60
|
+
for (const message of output.messages) {
|
|
61
|
+
message.parts.splice(0, message.parts.length, ...protectParts(message.parts, config, mode, protectWithCache));
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"experimental.chat.system.transform": async (_input, output) => {
|
|
65
|
+
output.system.splice(0, output.system.length, ...output.system.map((text) => protectWithCache(text, config, { mode, context: "system prompt" }).text));
|
|
66
|
+
},
|
|
67
|
+
"tool.definition": async (_input, output) => {
|
|
68
|
+
output.description = protectWithCache(output.description, config, { mode, context: "tool description" }).text;
|
|
69
|
+
output.parameters = protectUnknownStrings(output.parameters, config, { mode, context: "tool parameters" }, protectWithCache);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export function createFailClosedHooks() {
|
|
74
|
+
const blockRequest = async () => {
|
|
75
|
+
throw new Error(INITIALIZATION_ERROR);
|
|
76
|
+
};
|
|
77
|
+
return {
|
|
78
|
+
"chat.message": blockRequest,
|
|
79
|
+
"tool.execute.after": blockRequest,
|
|
80
|
+
"experimental.chat.messages.transform": blockRequest,
|
|
81
|
+
"experimental.chat.system.transform": blockRequest,
|
|
82
|
+
"tool.definition": blockRequest,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/** Admit SDKs that honor OpenCode's injected HTTP fetch. SDK initialization
|
|
2
|
+
* has no session identity or wire body: content masking/restoration remains
|
|
3
|
+
* in the request-scoped HTTP hooks, not in a provider-brand allowlist.
|
|
4
|
+
* This is NOT a network sandbox: SDKs that ignore options.fetch are outside
|
|
5
|
+
* the supported contract (including any private sockets/global-fetch path). */
|
|
6
|
+
import { types } from "node:util";
|
|
7
|
+
import { classifyModelRoute } from "./opencode-transparent-http.js";
|
|
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
|
+
function optionsOf(event) {
|
|
12
|
+
if (types.isProxy(event))
|
|
13
|
+
throw new Error(ADMISSION_ERROR);
|
|
14
|
+
const descriptor = Object.getOwnPropertyDescriptor(event, "options");
|
|
15
|
+
const value = descriptor && "value" in descriptor ? descriptor.value : undefined;
|
|
16
|
+
if (typeof value !== "object" || value === null || Array.isArray(value) || types.isProxy(value)) {
|
|
17
|
+
throw new Error(ADMISSION_ERROR);
|
|
18
|
+
}
|
|
19
|
+
return value;
|
|
20
|
+
}
|
|
21
|
+
/** Check protocol and, in strict mode, route before the host fetch. In false,
|
|
22
|
+
* unknown HTTP routes still require the host's scoped preparation proof;
|
|
23
|
+
* initialization is not admission. The host owns credentials and lifetime. */
|
|
24
|
+
function assertSupportedFetchInput(input, wireProtection) {
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
if (typeof input === "object" && input !== null && types.isProxy(input))
|
|
28
|
+
throw new Error();
|
|
29
|
+
if (typeof input === "string")
|
|
30
|
+
url = new URL(input);
|
|
31
|
+
else if (input instanceof Request)
|
|
32
|
+
url = new URL(input.url);
|
|
33
|
+
else if (input instanceof URL)
|
|
34
|
+
url = new URL(input.href);
|
|
35
|
+
else
|
|
36
|
+
throw new Error();
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
throw new Error(ADMISSION_ERROR);
|
|
40
|
+
}
|
|
41
|
+
if (!["http:", "https:"].includes(url.protocol) || (wireProtection && classifyModelRoute(url.href) === null)) {
|
|
42
|
+
throw new Error(ADMISSION_ERROR);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export function createAISDKTransportAdmission(wireProtection = true) {
|
|
46
|
+
const wrappers = new WeakSet();
|
|
47
|
+
const notices = new Set();
|
|
48
|
+
let active = true;
|
|
49
|
+
const refuse = (message) => {
|
|
50
|
+
if (!notices.has(message)) {
|
|
51
|
+
notices.add(message);
|
|
52
|
+
console.warn(`[leakshield] local AI SDK HTTP 400 refusal: ${message}`);
|
|
53
|
+
}
|
|
54
|
+
// SDKs classify thrown fetch errors as retryable network failures. A local
|
|
55
|
+
// non-2xx response makes the refusal actionable/non-retryable; it is NOT
|
|
56
|
+
// returned through the network or represented as a provider success.
|
|
57
|
+
return new Response(JSON.stringify({ type: "error", error: {
|
|
58
|
+
type: "invalid_request_error", code: "leakshield_transport_refusal", message,
|
|
59
|
+
} }), { status: 400, headers: { "content-type": "application/json", "x-leakshield-refusal": "1" } });
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
admit(event) {
|
|
63
|
+
if (!active)
|
|
64
|
+
throw new Error(DISPOSED_ERROR);
|
|
65
|
+
const options = optionsOf(event);
|
|
66
|
+
const descriptor = Object.getOwnPropertyDescriptor(options, "fetch");
|
|
67
|
+
if (!descriptor || !("value" in descriptor) || typeof descriptor.value !== "function" || types.isProxy(descriptor.value)) {
|
|
68
|
+
throw new Error(ADMISSION_ERROR);
|
|
69
|
+
}
|
|
70
|
+
if (wrappers.has(descriptor.value))
|
|
71
|
+
return;
|
|
72
|
+
if (descriptor.writable !== true)
|
|
73
|
+
throw new Error(ADMISSION_ERROR);
|
|
74
|
+
const original = descriptor.value;
|
|
75
|
+
const admitted = async function (input, init) {
|
|
76
|
+
if (!active)
|
|
77
|
+
return refuse(DISPOSED_ERROR);
|
|
78
|
+
try {
|
|
79
|
+
assertSupportedFetchInput(input, wireProtection);
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return refuse(ADMISSION_ERROR);
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return await Reflect.apply(original, this, [input, init]);
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
// Only SG's static refusal family is converted. Genuine networking,
|
|
89
|
+
// cancellation and provider failures keep their original behavior.
|
|
90
|
+
if (error instanceof Error && error.message.startsWith("LeakShield "))
|
|
91
|
+
return refuse(PROTECTION_ERROR);
|
|
92
|
+
throw error;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
Object.defineProperty(options, "fetch", { ...descriptor, value: admitted });
|
|
96
|
+
wrappers.add(admitted);
|
|
97
|
+
},
|
|
98
|
+
dispose() { active = false; },
|
|
99
|
+
};
|
|
100
|
+
}
|