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.
- package/README.md +35 -5
- package/README.zh-TW.md +34 -5
- package/dist/adapters/claude-code/capabilities.d.ts +14 -0
- package/dist/adapters/claude-code/capabilities.js +47 -0
- package/dist/adapters/claude-code/cli.d.ts +10 -0
- package/dist/adapters/claude-code/cli.js +51 -0
- package/dist/adapters/claude-code/doctor.d.ts +19 -0
- package/dist/adapters/claude-code/doctor.js +177 -0
- package/dist/adapters/claude-code/proxy.d.ts +47 -0
- package/dist/adapters/claude-code/proxy.js +348 -0
- package/dist/adapters/opencode/capabilities.d.ts +10 -0
- package/dist/adapters/opencode/capabilities.js +48 -0
- package/dist/adapters/opencode/doctor.d.ts +67 -0
- package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
- package/dist/adapters/opencode/env-queries.d.ts +133 -0
- package/dist/adapters/opencode/env-tools.d.ts +20 -0
- package/dist/adapters/opencode/hooks.d.ts +4 -0
- package/dist/adapters/opencode/plugin.d.ts +12 -0
- package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
- package/dist/adapters/opencode/tool-policy.d.ts +2 -0
- package/dist/adapters/opencode/tool-policy.js +23 -0
- package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
- package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
- package/dist/adapters/opencode/transparent.d.ts +66 -0
- package/dist/adapters/opencode/transparent.js +237 -0
- package/dist/adapters/opencode/v2.d.ts +20 -0
- package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
- package/dist/adapters/pi/capabilities.d.ts +10 -0
- package/dist/adapters/pi/capabilities.js +50 -0
- package/dist/adapters/pi/doctor.d.ts +26 -0
- package/dist/adapters/pi/doctor.js +276 -0
- package/dist/adapters/pi/extension.d.ts +28 -0
- package/dist/adapters/pi/extension.js +109 -0
- package/dist/adapters/pi/guard.d.ts +33 -0
- package/dist/adapters/pi/guard.js +154 -0
- package/dist/adapters/pi/persistence.d.ts +9 -0
- package/dist/adapters/pi/persistence.js +69 -0
- package/dist/adapters/pi/settings.d.ts +51 -0
- package/dist/adapters/pi/settings.js +136 -0
- package/dist/adapters/pi/tool-policy.d.ts +11 -0
- package/dist/adapters/pi/tool-policy.js +114 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +17 -6
- package/dist/config/loader.d.ts +70 -0
- package/dist/config/plain-object.d.ts +2 -0
- package/dist/core/index.d.ts +9 -0
- package/dist/core/index.js +9 -0
- package/dist/core/session-guard.d.ts +61 -0
- package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
- package/dist/core/sse-recovery.d.ts +6 -0
- package/dist/core/tool-restore-policy.d.ts +153 -0
- package/dist/core/tool-restore-policy.js +453 -0
- package/dist/core/wire.d.ts +213 -0
- package/dist/{opencode-transparent-http.js → core/wire.js} +125 -42
- package/dist/core/ws.d.ts +26 -0
- package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
- package/dist/decision/deidentify.d.ts +63 -0
- package/dist/decision/ingress.d.ts +40 -0
- package/dist/decision/mapping-key.d.ts +91 -0
- package/dist/decision/mapping-store.d.ts +166 -0
- package/dist/decision/model.d.ts +41 -0
- package/dist/decision/pseudonymization.d.ts +176 -0
- package/dist/decision/redaction.d.ts +56 -0
- package/dist/decision/schema-strings.d.ts +23 -0
- package/dist/decision/schema-strings.js +2 -2
- package/dist/decision/value-search.d.ts +39 -0
- package/dist/doctor-capabilities.d.ts +21 -0
- package/dist/doctor-capabilities.js +58 -0
- package/dist/doctor-hosts.d.ts +18 -0
- package/dist/doctor-hosts.js +144 -0
- package/dist/doctor-report.d.ts +45 -0
- package/dist/doctor-report.js +111 -0
- package/dist/forget.d.ts +18 -0
- package/dist/guard-options.d.ts +45 -0
- package/dist/{plugin-options.js → guard-options.js} +4 -1
- package/dist/help.d.ts +2 -0
- package/dist/help.js +15 -1
- package/dist/i18n/en.d.ts +65 -0
- package/dist/i18n/index.d.ts +15 -0
- package/dist/i18n/zh-TW.d.ts +65 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +1 -1
- package/dist/rules/builtin.d.ts +4 -0
- package/dist/rules/dynamic.d.ts +33 -0
- package/dist/scanner/allowlist.d.ts +22 -0
- package/dist/scanner/cidr.d.ts +39 -0
- package/dist/scanner/encoding.d.ts +87 -0
- package/dist/scanner/engine.d.ts +43 -0
- package/dist/scanner/exact-values.d.ts +11 -0
- package/dist/scanner/redaction-verifier.d.ts +24 -0
- package/dist/scanner/remotes.d.ts +29 -0
- package/dist/scanner/unicode.d.ts +57 -0
- package/dist/scanner/utils.d.ts +22 -0
- package/dist/transports/cli.d.ts +27 -0
- package/dist/transports/web-ui.d.ts +1 -0
- package/dist/transports/web-ui.js +1 -1
- package/dist/transports/web.d.ts +4 -0
- package/dist/types/capabilities.d.ts +67 -0
- package/dist/types/capabilities.js +133 -0
- package/dist/types.d.ts +149 -0
- package/dist/utils/files.d.ts +3 -0
- package/dist/utils/path-security.d.ts +18 -0
- package/dist/utils/win-encoding.d.ts +16 -0
- package/package.json +11 -3
- /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
- /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
- /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
- /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
|
@@ -1,67 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenCode v2 transparent pseudonymization session guard (issue #22).
|
|
3
|
-
*
|
|
4
|
-
* One guard owns exactly ONE pseudonymizer service (bounded per setup, no
|
|
5
|
-
* session fallback, no TTL, no eviction) and its own hook registrations and
|
|
6
|
-
* disposal. Protection model:
|
|
7
|
-
*
|
|
8
|
-
* - The four model-request kinds (`context`, `compaction`, `generate`,
|
|
9
|
-
* `title`) protect an atomic snapshot (system, messages, options, tools
|
|
10
|
-
* schema) with `protectJson` and publish it back only after the whole
|
|
11
|
-
* transaction succeeds — never piecewise in place, never partial.
|
|
12
|
-
* - Wire protection registers outbound HTTP/WS and SDK admission hooks.
|
|
13
|
-
* Explicit false is hook-only: none of those outbound hooks is registered.
|
|
14
|
-
* Inbound HTTP/WS restoration is best-effort in both modes; hook-only uses
|
|
15
|
-
* the host's session/kind/model and successful content preparation, not an
|
|
16
|
-
* outgoing transport registration, to select the local mapping.
|
|
17
|
-
* - Native Responses-family WebSocket routes restore display frames; the same
|
|
18
|
-
* wireProtection switch controls outbound admission and masking. Unknown
|
|
19
|
-
* inbound protocols stay literal. SDKs honoring injected HTTP fetch reuse
|
|
20
|
-
* the wire-protected HTTP hooks; hook-only makes no transport guarantee.
|
|
21
|
-
* - `tool:execute.before` restores registered tokens in tool arguments so local
|
|
22
|
-
* tools run with the real values (the model never sees them). Restoration is
|
|
23
|
-
* deep over the argument tree and keeps keys/types. Shell-like tools accept
|
|
24
|
-
* complete literal argument words in a single simple command; POSIX quoting
|
|
25
|
-
* and one static trailing output redirect are supported. Expansion, control
|
|
26
|
-
* syntax, unsafe quote-breaking originals and tokenized redirect targets
|
|
27
|
-
* refuse the affected call. Token-free calls pass through unchanged.
|
|
28
|
-
*
|
|
29
|
-
* Deliberately NOT registered in transparent mode: `session:prompt` (prompt
|
|
30
|
-
* admission and local persistence keep originals by design — protection is at
|
|
31
|
-
* the model boundary), `session:model.request` (routing/headers only; no
|
|
32
|
-
* content is exposed there to scan), `tool:execute.after` (local tool results
|
|
33
|
-
* stay original; their outbound replay is protected by the request kinds).
|
|
34
|
-
*
|
|
35
|
-
* The public V2 `session.deleted` event releases that session's memory and
|
|
36
|
-
* response attribution. Idle/completed sessions retain mappings for resume;
|
|
37
|
-
* there is no TTL or LRU eviction of live mappings. Disposal clears all RAM.
|
|
38
|
-
*/
|
|
39
1
|
import { types } from "node:util";
|
|
40
|
-
import { containsTokenPrefix, createPseudonymizer, } from "
|
|
41
|
-
import { MappingForgottenError, MappingKeyMismatchError, MappingSnapshotTooLargeError, MappingStoreConflictError, openMappingStore, } from "
|
|
42
|
-
import { resolveMappingKey } from "
|
|
43
|
-
import { walkSchemaStrings } from "
|
|
44
|
-
import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./
|
|
45
|
-
import {
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
48
|
-
import { BUILTIN_RULES } from "./rules/builtin.js";
|
|
2
|
+
import { containsTokenPrefix, createPseudonymizer, } from "../decision/pseudonymization.js";
|
|
3
|
+
import { MappingForgottenError, MappingKeyMismatchError, MappingSnapshotTooLargeError, MappingStoreConflictError, openMappingStore, } from "../decision/mapping-store.js";
|
|
4
|
+
import { resolveMappingKey } from "../decision/mapping-key.js";
|
|
5
|
+
import { walkSchemaStrings } from "../decision/schema-strings.js";
|
|
6
|
+
import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./wire.js";
|
|
7
|
+
import { createResponsesWebSocketAdapter } from "./ws.js";
|
|
8
|
+
import { parseSupportedShellArguments, warnDegradation, isShellSafeOriginal, commandAllowsEmbeddedTokens, isWgetExecuteCommand, TOKEN_SCAN, NEAR_MISS_V2_HEAD, NEAR_MISS_V2_SEGMENT_LETTERS, NEAR_MISS_V2_CATEGORIES, collectNearMissLetters, createInertPositionCheck, } from "./tool-restore-policy.js";
|
|
9
|
+
import { BUILTIN_RULES } from "../rules/builtin.js";
|
|
49
10
|
// ─── Static failure messages (no content ever included) ─────────────────────
|
|
50
|
-
const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
51
|
-
const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
|
|
52
|
-
const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
|
|
53
|
-
const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
|
|
11
|
+
export const INITIALIZATION_ERROR = "LeakShield initialization failed, so the request was blocked before anything was sent.";
|
|
12
|
+
export const PROTECT_FAILED_ERROR = "LeakShield blocked a model request because it could not be masked safely.";
|
|
13
|
+
export const ATTRIBUTION_ERROR = "LeakShield blocked a response because it could not be matched to a request.";
|
|
14
|
+
export const UNSUPPORTED_ROUTE_ERROR = "LeakShield blocked a request on an unsupported route.";
|
|
54
15
|
const TOOL_REFUSAL_ERROR = "LeakShield blocked this tool call because its arguments could not be restored safely. Re-read the file and try again.";
|
|
55
16
|
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.";
|
|
56
17
|
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.";
|
|
57
18
|
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.";
|
|
58
19
|
const TOOL_CODE_CONTEXT_ERROR = "LeakShield blocked this tool call because a protected value cannot be safely inserted into code. Pass the value through a plain argument or a file instead, or ask the user.";
|
|
59
20
|
const TOOL_CODE_POSITION_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- Allowed: a placeholder in a plain single-line quoted string with no interpolation, outside any multi-line string or line continuation.\n- Fix: copy the placeholder exactly as it appears in this conversation, including its brackets, into such a string, assign that to a variable, and reference the variable.\n- Do not replace the placeholder with other text, and do not ask for or write the real value. If refused again, stop and ask the user.";
|
|
60
|
-
/**
|
|
61
|
-
* OpenCode's built-in Code Mode tool (v2.2.5): custom tools are reachable only
|
|
62
|
-
* through it, with input `{code: string}`.
|
|
63
|
-
*/
|
|
64
|
-
const CODE_MODE_TOOL = "execute";
|
|
65
21
|
/**
|
|
66
22
|
* Refusal for `fetch` inside Code Mode source that holds a protected value.
|
|
67
23
|
* This only avoids a misleading result: the inner fetch would send the
|
|
@@ -97,457 +53,6 @@ function prepareMaskError(reason, config) {
|
|
|
97
53
|
const maxChars = config.settings.max_chars;
|
|
98
54
|
return `${marker} A string, before or after masking, exceeded settings.max_chars (${maxChars}). Raise settings.max_chars or split the content.`;
|
|
99
55
|
}
|
|
100
|
-
/** Shell syntax excluded from unquoted literal words. Known tokens are
|
|
101
|
-
* removed before this check; a token-shaped prefix alone grants no exemption. */
|
|
102
|
-
const UNSUPPORTED_SHELL_SYNTAX = /[\x00-\x1f\x7f'"`\\$;|&<>(){}*?\[\]!~#]/;
|
|
103
|
-
/** A deliberately small literal-word lexer, not a general shell parser.
|
|
104
|
-
* Quotes must enclose the entire word. No escape decoding, expansions, quote
|
|
105
|
-
* concatenation or control characters are accepted. Decode command/flag
|
|
106
|
-
* quotes too, so `'sh' '-c' TOKEN` cannot bypass the interpreter gate. */
|
|
107
|
-
function parseLiteralShellWords(text) {
|
|
108
|
-
if (/[\x00-\x1f\x7f]/.test(text))
|
|
109
|
-
return null;
|
|
110
|
-
// The new quote/redirection subset is POSIX-specific. Keep the previous
|
|
111
|
-
// conservative behavior on Windows, where the host may launch cmd.exe.
|
|
112
|
-
if (process.platform === "win32" && /['">]/.test(text))
|
|
113
|
-
return null;
|
|
114
|
-
const words = [];
|
|
115
|
-
let at = 0;
|
|
116
|
-
while (at < text.length) {
|
|
117
|
-
if (text[at] === " ") {
|
|
118
|
-
at += 1;
|
|
119
|
-
continue;
|
|
120
|
-
}
|
|
121
|
-
const start = at;
|
|
122
|
-
if (text[at] === ">") {
|
|
123
|
-
at += text[at + 1] === ">" ? 2 : 1;
|
|
124
|
-
words.push({ start, end: at, value: text.slice(start, at), quote: "none", redirect: true });
|
|
125
|
-
}
|
|
126
|
-
else if (text[at] === "'" || text[at] === '"') {
|
|
127
|
-
const delimiter = text[at++];
|
|
128
|
-
const valueStart = at;
|
|
129
|
-
while (at < text.length && text[at] !== delimiter)
|
|
130
|
-
at += 1;
|
|
131
|
-
if (at === text.length)
|
|
132
|
-
return null;
|
|
133
|
-
const value = text.slice(valueStart, at++);
|
|
134
|
-
const quote = delimiter === "'" ? "single" : "double";
|
|
135
|
-
if (quote === "double" && /[`\\$!]/.test(value))
|
|
136
|
-
return null;
|
|
137
|
-
words.push({ start, end: at, value, quote, redirect: false });
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
while (at < text.length && text[at] !== " ")
|
|
141
|
-
at += 1;
|
|
142
|
-
const value = text.slice(start, at);
|
|
143
|
-
if (UNSUPPORTED_SHELL_SYNTAX.test(value.replace(TOKEN_SCAN, "TOKEN")) || value.includes(">"))
|
|
144
|
-
return null;
|
|
145
|
-
words.push({ start, end: at, value, quote: "none", redirect: false });
|
|
146
|
-
}
|
|
147
|
-
if (at < text.length && text[at] !== " ")
|
|
148
|
-
return null;
|
|
149
|
-
}
|
|
150
|
-
return words;
|
|
151
|
-
}
|
|
152
|
-
const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
153
|
-
const SHELL_COMMAND_WRAPPERS = new Set([
|
|
154
|
-
"builtin",
|
|
155
|
-
"command",
|
|
156
|
-
"doas",
|
|
157
|
-
"env",
|
|
158
|
-
"eval",
|
|
159
|
-
"exec",
|
|
160
|
-
"nice",
|
|
161
|
-
"nohup",
|
|
162
|
-
"pkexec",
|
|
163
|
-
"runuser",
|
|
164
|
-
"setsid",
|
|
165
|
-
"source",
|
|
166
|
-
"sudo",
|
|
167
|
-
"su",
|
|
168
|
-
"time",
|
|
169
|
-
"timeout",
|
|
170
|
-
"xargs",
|
|
171
|
-
]);
|
|
172
|
-
const INLINE_SCRIPT_FLAGS = new Map([
|
|
173
|
-
["python", new Set(["-c"])],
|
|
174
|
-
["python3", new Set(["-c"])],
|
|
175
|
-
["node", new Set(["-e", "--eval", "-p", "--print"])],
|
|
176
|
-
["nodejs", new Set(["-e", "--eval", "-p", "--print"])],
|
|
177
|
-
["ruby", new Set(["-e", "-pe", "-ne"])],
|
|
178
|
-
["perl", new Set(["-e", "-pe", "-ne", "-E"])],
|
|
179
|
-
["php", new Set(["-r"])],
|
|
180
|
-
["lua", new Set(["-e"])],
|
|
181
|
-
["powershell", new Set(["-c", "-command", "-encodedcommand", "-e"])],
|
|
182
|
-
["pwsh", new Set(["-c", "-command", "-encodedcommand", "-e"])],
|
|
183
|
-
["cmd", new Set(["/c", "/k"])],
|
|
184
|
-
]);
|
|
185
|
-
const SCRIPT_ARGUMENT_INTERPRETERS = new Set(["awk", "sed", "jq"]);
|
|
186
|
-
const SHELL_INTERPRETERS = new Set(["sh", "bash", "dash", "zsh", "ksh", "ash", "csh", "tcsh", "fish"]);
|
|
187
|
-
/**
|
|
188
|
-
* `rtk` is a command-output wrapper: `rtk <command> <args>` runs the command
|
|
189
|
-
* and condenses its output, so the command actually executed is the word
|
|
190
|
-
* after it. Without this, `rtk sh -c T` would be judged as plain arguments to
|
|
191
|
-
* `rtk` and restore a token into a second shell parse. These subcommands run
|
|
192
|
-
* another command themselves (`rtk err sh -c T`, `rtk proxy sh -c T`), so the
|
|
193
|
-
* word after them cannot be judged as the executed command and the form is
|
|
194
|
-
* refused. The list comes from `rtk --help` for rtk 1.1.0; a new rtk release
|
|
195
|
-
* may add runners. `rtk` counts however it's spelled (a path, quotes, any case),
|
|
196
|
-
* as the other command checks do.
|
|
197
|
-
*/
|
|
198
|
-
const RTK_COMMAND_RUNNERS = new Set(["err", "test", "summary", "run", "bypass", "proxy", "pipe"]);
|
|
199
|
-
/**
|
|
200
|
-
* Index of the word that names the command actually executed: the first
|
|
201
|
-
* non-assignment word, or the word after a leading `rtk`. Returns -1 when
|
|
202
|
-
* there is no such word or the form must be refused (`rtk` alone, an option
|
|
203
|
-
* after `rtk`, `rtk` wrapping `rtk`, or an rtk subcommand that runs another
|
|
204
|
-
* command).
|
|
205
|
-
*/
|
|
206
|
-
function resolveExecutedCommandIndex(words) {
|
|
207
|
-
const commandIndex = words.findIndex((word) => word.quote !== "none" || !ASSIGNMENT_WORD.test(word.value));
|
|
208
|
-
if (commandIndex === -1)
|
|
209
|
-
return -1;
|
|
210
|
-
const command = words[commandIndex];
|
|
211
|
-
if (command.redirect || command.value.split("/").at(-1)?.toLowerCase() !== "rtk")
|
|
212
|
-
return commandIndex;
|
|
213
|
-
const next = words[commandIndex + 1];
|
|
214
|
-
if (next === undefined || next.redirect || next.value.startsWith("-"))
|
|
215
|
-
return -1;
|
|
216
|
-
if (next.value.split("/").at(-1)?.toLowerCase() === "rtk")
|
|
217
|
-
return -1;
|
|
218
|
-
if (RTK_COMMAND_RUNNERS.has(next.value.toLowerCase()))
|
|
219
|
-
return -1;
|
|
220
|
-
return commandIndex + 1;
|
|
221
|
-
}
|
|
222
|
-
/** Returns only ordinary arguments, never command/assignment/redirect words. */
|
|
223
|
-
function parseSupportedShellArguments(text) {
|
|
224
|
-
const parsed = parseLiteralShellWords(text);
|
|
225
|
-
if (parsed === null)
|
|
226
|
-
return null;
|
|
227
|
-
const redirectIndex = parsed.findIndex((word) => word.redirect);
|
|
228
|
-
if (redirectIndex !== -1) {
|
|
229
|
-
const target = parsed[redirectIndex + 1];
|
|
230
|
-
if (redirectIndex === 0 || redirectIndex !== parsed.length - 2 ||
|
|
231
|
-
target.redirect || target.value.length === 0 || containsTokenPrefix(target.value))
|
|
232
|
-
return null;
|
|
233
|
-
}
|
|
234
|
-
const words = redirectIndex === -1 ? parsed : parsed.slice(0, redirectIndex);
|
|
235
|
-
const commandIndex = resolveExecutedCommandIndex(words);
|
|
236
|
-
if (commandIndex === -1)
|
|
237
|
-
return null;
|
|
238
|
-
const commandName = words[commandIndex].value.split("/").at(-1)?.toLowerCase() ?? "";
|
|
239
|
-
if (SHELL_COMMAND_WRAPPERS.has(commandName) || SCRIPT_ARGUMENT_INTERPRETERS.has(commandName))
|
|
240
|
-
return null;
|
|
241
|
-
const argumentsOnly = words.slice(commandIndex + 1);
|
|
242
|
-
if (SHELL_INTERPRETERS.has(commandName)) {
|
|
243
|
-
if (argumentsOnly.some((argument) => /^-[A-Za-z]*c[A-Za-z]*$/.test(argument.value)))
|
|
244
|
-
return null;
|
|
245
|
-
}
|
|
246
|
-
const inlineFlags = INLINE_SCRIPT_FLAGS.get(commandName) ??
|
|
247
|
-
(/^python(?:\d+(?:\.\d+)*)?$/.test(commandName) ? INLINE_SCRIPT_FLAGS.get("python") : undefined);
|
|
248
|
-
if (inlineFlags && argumentsOnly.some((argument) => inlineFlags.has(argument.value.toLowerCase())))
|
|
249
|
-
return null;
|
|
250
|
-
if (commandName === "deno" && argumentsOnly.some((argument) => argument.value === "eval"))
|
|
251
|
-
return null;
|
|
252
|
-
return argumentsOnly;
|
|
253
|
-
}
|
|
254
|
-
/** Characters forbidden inside restored shell argument words. */
|
|
255
|
-
const SHELL_UNSAFE = /[\s'"`\\$;|&<>(){}*?\[\]!~#\x00-\x1F\x7F]/;
|
|
256
|
-
/**
|
|
257
|
-
* Restore policy is decided per field, not per tool. A tool name that is in
|
|
258
|
-
* SHELL_TOOLS or has a shell-interpreter segment (bash, shell, sh, zsh, pwsh,
|
|
259
|
-
* powershell) makes every field "shell". Otherwise a field named like a
|
|
260
|
-
* command (command, cmd, commands, argv, ...) is "shell", a field named like
|
|
261
|
-
* code (code, script, ...) is "inert" (no parsing; originals with
|
|
262
|
-
* shell-unsafe characters are refused), and any other field restores
|
|
263
|
-
* verbatim. The list is built into the source, not configurable; an executing
|
|
264
|
-
* tool using other field names is not detected.
|
|
265
|
-
*/
|
|
266
|
-
const SHELL_TOOLS = new Set([
|
|
267
|
-
"bash",
|
|
268
|
-
"shell",
|
|
269
|
-
"sh",
|
|
270
|
-
"zsh",
|
|
271
|
-
"exec",
|
|
272
|
-
"command",
|
|
273
|
-
"run",
|
|
274
|
-
"pwsh",
|
|
275
|
-
"powershell",
|
|
276
|
-
]);
|
|
277
|
-
/** Splits on non-alphanumerics and camelCase boundaries; lowercase segments. */
|
|
278
|
-
const nameSegments = (raw) => raw
|
|
279
|
-
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
|
280
|
-
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
|
|
281
|
-
.split(/[^A-Za-z0-9]+/)
|
|
282
|
-
.filter((segment) => segment.length > 0)
|
|
283
|
-
.map((segment) => segment.toLowerCase());
|
|
284
|
-
const SHELL_TOOL_SEGMENTS = new Set(["bash", "shell", "sh", "zsh", "pwsh", "powershell"]);
|
|
285
|
-
const METADATA_KEYS = new Set(["description", "title", "label"]);
|
|
286
|
-
const SHELL_KEY_LAST_SEGMENTS = new Set(["command", "commands", "cmd", "cmds"]);
|
|
287
|
-
const SHELL_KEYS_JOINED = new Set(["shell", "commandline", "cmdline", "argv"]);
|
|
288
|
-
const CODE_KEYS_JOINED = new Set(["code", "script", "scripts", "sourcecode", "codesnippet", "inlinescript"]);
|
|
289
|
-
const isShellTool = (rawTool) => SHELL_TOOLS.has(rawTool.toLowerCase()) || nameSegments(rawTool).some((segment) => SHELL_TOOL_SEGMENTS.has(segment));
|
|
290
|
-
const isShellKey = (key) => {
|
|
291
|
-
const segments = nameSegments(key);
|
|
292
|
-
return ((segments.length > 0 && SHELL_KEY_LAST_SEGMENTS.has(segments[segments.length - 1])) ||
|
|
293
|
-
SHELL_KEYS_JOINED.has(segments.join("")));
|
|
294
|
-
};
|
|
295
|
-
const isCodeKey = (key) => CODE_KEYS_JOINED.has(nameSegments(key).join(""));
|
|
296
|
-
const keyPolicy = (key, inherited) => {
|
|
297
|
-
const segments = nameSegments(key);
|
|
298
|
-
if (segments.length === 1 && METADATA_KEYS.has(segments[0]))
|
|
299
|
-
return "verbatim";
|
|
300
|
-
if (isShellKey(key))
|
|
301
|
-
return "shell";
|
|
302
|
-
if (isCodeKey(key))
|
|
303
|
-
return inherited === "shell" ? "shell" : "inert";
|
|
304
|
-
return inherited;
|
|
305
|
-
};
|
|
306
|
-
/**
|
|
307
|
-
* Tools whose calls are observably read-only: an unresolved placeholder in
|
|
308
|
-
* their arguments reads/greps/lists against a literal string and matches
|
|
309
|
-
* nothing — no state change, no outbound transmission. Only these qualify
|
|
310
|
-
* for P1 (2026-10-06b) best-effort literal passthrough when restoration is
|
|
311
|
-
* incomplete. Everything else — writes, deletes, edits, network calls,
|
|
312
|
-
* shell, unknown tools — refuses the affected invocation.
|
|
313
|
-
*/
|
|
314
|
-
const READ_ONLY_TOOLS = new Set([
|
|
315
|
-
"read",
|
|
316
|
-
"read_file",
|
|
317
|
-
"view",
|
|
318
|
-
"grep",
|
|
319
|
-
"glob",
|
|
320
|
-
"list",
|
|
321
|
-
"ls",
|
|
322
|
-
"find",
|
|
323
|
-
"todoread",
|
|
324
|
-
]);
|
|
325
|
-
/**
|
|
326
|
-
* Content-free degradation notice for the host log: one WARN line, a fixed
|
|
327
|
-
* context word plus a count, never request content. No side files, no
|
|
328
|
-
* provider-body notices (P1, 2026-10-06b).
|
|
329
|
-
*/
|
|
330
|
-
const warnDegradation = (context) => {
|
|
331
|
-
console.warn(`[leakshield] degraded: ${context}`);
|
|
332
|
-
};
|
|
333
|
-
/** Preserve the existing quote context; never add quoting or reinterpret the
|
|
334
|
-
* original as code. Leading '-' stays forbidden even when quoted (options are
|
|
335
|
-
* interpreted after quote removal). Controls are forbidden in every context. */
|
|
336
|
-
function isShellSafeOriginal(text, quote) {
|
|
337
|
-
if (text.length === 0 || text.startsWith("-") || /[\x00-\x1f\x7f]/.test(text))
|
|
338
|
-
return false;
|
|
339
|
-
if (quote === "single")
|
|
340
|
-
return !text.includes("'");
|
|
341
|
-
if (quote === "double")
|
|
342
|
-
return !/["`\\$!]/.test(text);
|
|
343
|
-
return !SHELL_UNSAFE.test(text);
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* HTTP clients that take credentials inside an argument (`-H 'x-api-key: T'`,
|
|
347
|
-
* `-u user:T`, `--header=x:T`). `wget` is deliberately not listed: its `-e`
|
|
348
|
-
* option family keeps producing bypasses, so it follows the whole-word rule.
|
|
349
|
-
* `isShellSafeOriginal` only covers the first
|
|
350
|
-
* shell parse; commands such as `sh -c`, `python -c`, `ssh` and `eval` parse
|
|
351
|
-
* their arguments again, so embedding is decided by the command that actually
|
|
352
|
-
* executes: the first word, unquoted, exactly one of these names. Paths,
|
|
353
|
-
* quoted names, assignments and wrappers (`env`, `sudo`) do not qualify.
|
|
354
|
-
* `rtk curl ...` does not qualify either: rtk records command lines in its
|
|
355
|
-
* local history database in plaintext, so a restored secret would persist
|
|
356
|
-
* there. Under `rtk` only whole-word placeholders restore.
|
|
357
|
-
*/
|
|
358
|
-
const EMBEDDED_PLACEHOLDER_COMMANDS = new Set(["curl", "http"]);
|
|
359
|
-
function commandAllowsEmbeddedTokens(text) {
|
|
360
|
-
const first = parseLiteralShellWords(text)?.[0];
|
|
361
|
-
return (first !== undefined &&
|
|
362
|
-
first.quote === "none" &&
|
|
363
|
-
!first.redirect &&
|
|
364
|
-
EMBEDDED_PLACEHOLDER_COMMANDS.has(first.value));
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* `wget -e CMD` / `--execute CMD` hands its value to wgetrc parsing, a second
|
|
368
|
-
* parse that `isShellSafeOriginal` does not cover (the value can set
|
|
369
|
-
* `output_document`, `post_file` and the like). This check stays although
|
|
370
|
-
* `wget` no longer holds embedded tokens: `wget -e T u` would otherwise
|
|
371
|
-
* restore a whole-word token into wgetrc parsing. The command must be
|
|
372
|
-
* `wget` however it's spelled (a path, quotes, leading assignments), resolved
|
|
373
|
-
* as in `parseSupportedShellArguments`. `curl -e` is a referer and
|
|
374
|
-
* `curl -K`/`--config` only name a file.
|
|
375
|
-
* GNU long options accept unique abbreviations (`--exec`), so any prefix of
|
|
376
|
-
* `--execute` counts; the shorter ambiguous ones make wget exit with an error.
|
|
377
|
-
*/
|
|
378
|
-
function isWgetExecuteCommand(text) {
|
|
379
|
-
const words = parseLiteralShellWords(text);
|
|
380
|
-
if (words === null)
|
|
381
|
-
return false;
|
|
382
|
-
const commandIndex = resolveExecutedCommandIndex(words);
|
|
383
|
-
if (commandIndex === -1)
|
|
384
|
-
return false;
|
|
385
|
-
if (words[commandIndex].value.split("/").at(-1)?.toLowerCase() !== "wget")
|
|
386
|
-
return false;
|
|
387
|
-
return words.slice(commandIndex + 1).some((word) => {
|
|
388
|
-
if (word.redirect)
|
|
389
|
-
return false;
|
|
390
|
-
const optionName = word.value.split("=", 1)[0];
|
|
391
|
-
return /^-[A-Za-z0-9]*e/.test(word.value) || (optionName.length >= 3 && "--execute".startsWith(optionName));
|
|
392
|
-
});
|
|
393
|
-
}
|
|
394
|
-
/** Matches a fully formed reserved token (either version), for per-token shell safety checks. */
|
|
395
|
-
const TOKEN_SCAN = /\[SGP1:[0-9a-f]{32}-\d{8,12}\]|\[SGP2:[A-Z][A-Z_]{0,31}-[a-z]{4}-[a-z]{4}-[a-z]{4}\]/g;
|
|
396
|
-
/**
|
|
397
|
-
* Relaxed (brackets optional, separators up to 4 non-alphanumerics, any case)
|
|
398
|
-
* forms of the SGP2 placeholder, used only to spot a placeholder the
|
|
399
|
-
* model reformatted. Every quantifier is bounded and there is no nested
|
|
400
|
-
* unbounded group. A candidate counts only if its canonical form restores in
|
|
401
|
-
* the session, so no token enumeration is needed.
|
|
402
|
-
*
|
|
403
|
-
* SGP2 reads the letters after the `SGP2` head, tolerating separator runs of
|
|
404
|
-
* up to 4 non-alphanumerics between letters (changed separators) or none at
|
|
405
|
-
* all (removed separators), and stopping at a digit, a longer run or about 80
|
|
406
|
-
* letters. Each known category, compared without underscores, is tried as a
|
|
407
|
-
* prefix of those letters; the next 12 letters become the three segments. The
|
|
408
|
-
* text after a stripped token is often more short words, which this ignores
|
|
409
|
-
* because only exactly 12 letters follow the category.
|
|
410
|
-
*/
|
|
411
|
-
const NEAR_MISS_V2_HEAD = /(?<![A-Za-z0-9])SGP2/gi;
|
|
412
|
-
const NEAR_MISS_V2_MAX_SEPARATOR = 4;
|
|
413
|
-
const NEAR_MISS_V2_MAX_LETTERS = 80;
|
|
414
|
-
const NEAR_MISS_V2_SEGMENT_LETTERS = 12;
|
|
415
|
-
const NEAR_MISS_V2_CATEGORIES = new Map(FINDING_TYPES.map((label) => [label.replaceAll("_", "").toUpperCase(), label]));
|
|
416
|
-
/** Letters following `from`, skipping short separator runs; stops at a digit or a long run. */
|
|
417
|
-
function collectNearMissLetters(text, from) {
|
|
418
|
-
let letters = "";
|
|
419
|
-
let at = from;
|
|
420
|
-
while (at < text.length && letters.length < NEAR_MISS_V2_MAX_LETTERS) {
|
|
421
|
-
const char = text[at];
|
|
422
|
-
if (/[A-Za-z]/.test(char)) {
|
|
423
|
-
letters += char;
|
|
424
|
-
at += 1;
|
|
425
|
-
}
|
|
426
|
-
else if (/[0-9]/.test(char)) {
|
|
427
|
-
break;
|
|
428
|
-
}
|
|
429
|
-
else {
|
|
430
|
-
let run = 0;
|
|
431
|
-
while (at + run < text.length && /[^A-Za-z0-9]/.test(text[at + run]))
|
|
432
|
-
run += 1;
|
|
433
|
-
if (run > NEAR_MISS_V2_MAX_SEPARATOR)
|
|
434
|
-
break;
|
|
435
|
-
at += run;
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
return letters;
|
|
439
|
-
}
|
|
440
|
-
/**
|
|
441
|
-
* Builds the position check for the placeholders of one code/script field.
|
|
442
|
-
* Call the result with each token's [start, end) in increasing order; it keeps
|
|
443
|
-
* its state between calls, so the whole field costs one forward pass however
|
|
444
|
-
* many tokens it holds, and a false result ends the field's check. A token's
|
|
445
|
-
* position passes unless `crossesLineBoundary` or `isInPlainStringLiteral`
|
|
446
|
-
* rejects it.
|
|
447
|
-
*
|
|
448
|
-
* Conservative, language-agnostic, line-based heuristic; it is not a parser
|
|
449
|
-
* and does not confirm the match is in a string. It can both over-refuse and
|
|
450
|
-
* miss. It guards the restoration context only and is not egress protection:
|
|
451
|
-
* code can still print, send or re-interpret the restored value.
|
|
452
|
-
*/
|
|
453
|
-
function createInertPositionCheck(text) {
|
|
454
|
-
const lineBreak = /[\n\r\u2028\u2029]/g;
|
|
455
|
-
// Current line is [lineStart, lineEnd); lineEnd sits on its separator.
|
|
456
|
-
let lineStart = 0;
|
|
457
|
-
let lineEnd = -1;
|
|
458
|
-
// Triple quotes in text[0, countedTo). A separator ends any run of quotes, so
|
|
459
|
-
// per-line counts add up to the non-overlapping count over the whole prefix.
|
|
460
|
-
let countedTo = 0;
|
|
461
|
-
let doubleTriples = 0;
|
|
462
|
-
let singleTriples = 0;
|
|
463
|
-
let crossesLineBoundary = false;
|
|
464
|
-
// Quote scan of the current line, resumed from `cursor` for each token.
|
|
465
|
-
let cursor = 0;
|
|
466
|
-
let quote = null;
|
|
467
|
-
let introducerInString = false;
|
|
468
|
-
let closingQuote = -1;
|
|
469
|
-
const enterLineOf = (index) => {
|
|
470
|
-
while (lineEnd < index) {
|
|
471
|
-
lineStart = lineEnd + 1;
|
|
472
|
-
lineBreak.lastIndex = lineStart;
|
|
473
|
-
lineEnd = lineBreak.exec(text)?.index ?? text.length;
|
|
474
|
-
}
|
|
475
|
-
const uncounted = text.slice(countedTo, lineStart);
|
|
476
|
-
doubleTriples += uncounted.match(/"""/g)?.length ?? 0;
|
|
477
|
-
singleTriples += uncounted.match(/'''/g)?.length ?? 0;
|
|
478
|
-
countedTo = lineStart;
|
|
479
|
-
const line = text.slice(lineStart, lineEnd);
|
|
480
|
-
// True when the line may belong to a multi-line construct, so the
|
|
481
|
-
// line-based string check cannot be trusted: the line holds a triple quote,
|
|
482
|
-
// an odd number of non-overlapping triple quotes precedes the line (inside
|
|
483
|
-
// an open multi-line string), or the previous line ends in a backslash
|
|
484
|
-
// (continuation; doubled backslashes are not distinguished, so refuse).
|
|
485
|
-
// Deliberately not a whole-field ban, so a script with a balanced docstring
|
|
486
|
-
// above the assignment still works.
|
|
487
|
-
crossesLineBoundary =
|
|
488
|
-
line.includes('"""') ||
|
|
489
|
-
line.includes("'''") ||
|
|
490
|
-
doubleTriples % 2 === 1 ||
|
|
491
|
-
singleTriples % 2 === 1 ||
|
|
492
|
-
/\\(?:\r\n|[\n\r\u2028\u2029])$/.test(text.slice(Math.max(0, lineStart - 3), lineStart));
|
|
493
|
-
cursor = lineStart;
|
|
494
|
-
quote = null;
|
|
495
|
-
introducerInString = false;
|
|
496
|
-
};
|
|
497
|
-
/**
|
|
498
|
-
* True when [start, end) looks like it sits inside an ordinary quoted string
|
|
499
|
-
* that opens and closes on the current line, with no interpolation or escape
|
|
500
|
-
* introducer between the opening quote and the token.
|
|
501
|
-
*/
|
|
502
|
-
const isInPlainStringLiteral = (start, end) => {
|
|
503
|
-
while (cursor < start) {
|
|
504
|
-
const c = text[cursor];
|
|
505
|
-
if (quote === null) {
|
|
506
|
-
if (c === "'" || c === '"') {
|
|
507
|
-
quote = c;
|
|
508
|
-
introducerInString = false;
|
|
509
|
-
}
|
|
510
|
-
else if (c === "`" || c === "#" || text.startsWith("//", cursor) || text.startsWith("/*", cursor) || text.startsWith("--", cursor)) {
|
|
511
|
-
return false;
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
else if (c === "\\") {
|
|
515
|
-
introducerInString = true;
|
|
516
|
-
cursor++;
|
|
517
|
-
}
|
|
518
|
-
else if (c === quote) {
|
|
519
|
-
quote = null;
|
|
520
|
-
}
|
|
521
|
-
else if (c === "{" || c === "$" || c === "`") {
|
|
522
|
-
introducerInString = true;
|
|
523
|
-
}
|
|
524
|
-
cursor++;
|
|
525
|
-
}
|
|
526
|
-
if (quote === null || introducerInString)
|
|
527
|
-
return false;
|
|
528
|
-
// A token holds no quote or backslash, so a search from an earlier token
|
|
529
|
-
// in this string walked through this one: its answer still holds, and each
|
|
530
|
-
// string on the line is searched once.
|
|
531
|
-
if (closingQuote >= end)
|
|
532
|
-
return true;
|
|
533
|
-
for (let i = end; i < lineEnd; i++) {
|
|
534
|
-
if (text[i] === "\\") {
|
|
535
|
-
i++;
|
|
536
|
-
continue;
|
|
537
|
-
}
|
|
538
|
-
if (text[i] === quote) {
|
|
539
|
-
closingQuote = i;
|
|
540
|
-
return true;
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
return false;
|
|
544
|
-
};
|
|
545
|
-
return (start, end) => {
|
|
546
|
-
if (start > lineEnd)
|
|
547
|
-
enterLineOf(start);
|
|
548
|
-
return !crossesLineBoundary && isInPlainStringLiteral(start, end);
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
56
|
/**
|
|
552
57
|
* Bound on distinct session identities retained for disposal. The core already
|
|
553
58
|
* caps committed sessions; this bounds identities seen with safe-only content
|
|
@@ -572,7 +77,7 @@ const TRANSPARENT_LIMITS = {
|
|
|
572
77
|
function isRecordLike(value) {
|
|
573
78
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
574
79
|
}
|
|
575
|
-
function requireSessionID(event) {
|
|
80
|
+
export function requireSessionID(event) {
|
|
576
81
|
if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
|
|
577
82
|
throw new Error(PROTECT_FAILED_ERROR);
|
|
578
83
|
}
|
|
@@ -848,73 +353,20 @@ function inputCarriesToken(value, seen) {
|
|
|
848
353
|
}
|
|
849
354
|
return false;
|
|
850
355
|
}
|
|
851
|
-
/** Runs pending disposals (best effort, reverse order) without throwing. */
|
|
852
|
-
async function runDisposals(disposals) {
|
|
853
|
-
for (let i = disposals.length - 1; i >= 0; i--) {
|
|
854
|
-
try {
|
|
855
|
-
await disposals[i]();
|
|
856
|
-
}
|
|
857
|
-
catch {
|
|
858
|
-
// Continue clearing remaining registrations.
|
|
859
|
-
}
|
|
860
|
-
}
|
|
861
|
-
disposals.length = 0;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* Creates a fail-closed guard whose every hook refuses all operations. Exported
|
|
865
|
-
* so the plugin entry can arm it for transparent mode when setup fails before
|
|
866
|
-
* (or during) guard construction: a transparent fallback must cover the
|
|
867
|
-
* transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
|
|
868
|
-
* content/tool dispatch without introducing new transport registrations.
|
|
869
|
-
*/
|
|
870
|
-
export function createFailClosedTransparentGuard(wireProtection = true) {
|
|
871
|
-
const disposals = [];
|
|
872
|
-
const refuse = () => {
|
|
873
|
-
throw new Error(INITIALIZATION_ERROR);
|
|
874
|
-
};
|
|
875
|
-
return {
|
|
876
|
-
setup: async (ctx) => {
|
|
877
|
-
try {
|
|
878
|
-
const contentHooks = ["context", "compaction", "generate", "title"];
|
|
879
|
-
const wireHooks = [
|
|
880
|
-
"http.request",
|
|
881
|
-
"http.response",
|
|
882
|
-
"experimental.ws.handshake",
|
|
883
|
-
"experimental.ws.send",
|
|
884
|
-
"experimental.ws.receive",
|
|
885
|
-
];
|
|
886
|
-
for (const name of [...contentHooks, ...(wireProtection ? wireHooks : [])]) {
|
|
887
|
-
disposals.push((await ctx.session.hook(name, refuse)).dispose);
|
|
888
|
-
}
|
|
889
|
-
if (wireProtection) {
|
|
890
|
-
disposals.push((await ctx.aisdk.hook("sdk", refuse)).dispose);
|
|
891
|
-
disposals.push((await ctx.aisdk.hook("language", refuse)).dispose);
|
|
892
|
-
}
|
|
893
|
-
disposals.push((await ctx.tool.hook("execute.before", refuse)).dispose);
|
|
894
|
-
}
|
|
895
|
-
catch (error) {
|
|
896
|
-
await runDisposals(disposals);
|
|
897
|
-
throw error;
|
|
898
|
-
}
|
|
899
|
-
},
|
|
900
|
-
dispose: () => runDisposals(disposals),
|
|
901
|
-
};
|
|
902
|
-
}
|
|
903
356
|
/**
|
|
904
|
-
* Creates the
|
|
905
|
-
* process): a single bounded pseudonymizer, exact-session mapping
|
|
906
|
-
* request attribution
|
|
907
|
-
* the
|
|
908
|
-
* first touch and writes committed mappings back (decision
|
|
909
|
-
* unloads hooks but never deletes persisted mappings — forget is
|
|
910
|
-
* erasure path).
|
|
357
|
+
* Creates the host-independent guard core for one plugin setup (= one OpenCode
|
|
358
|
+
* process): a single bounded pseudonymizer, exact-session mapping and private
|
|
359
|
+
* request attribution. The host layer registers hooks that call its handlers.
|
|
360
|
+
* With persistence options the core additionally hydrates sessions from the
|
|
361
|
+
* encrypted store on first touch and writes committed mappings back (decision
|
|
362
|
+
* §4: dispose unloads hooks but never deletes persisted mappings — forget is
|
|
363
|
+
* the only erasure path). Returns null when the pseudonymizer cannot be built.
|
|
911
364
|
*/
|
|
912
|
-
export function
|
|
365
|
+
export function createGuardCore(config, attachmentsPolicy = "block", wireProtection = true, persistence, dialect = {}, hostToolPolicy) {
|
|
913
366
|
const created = createPseudonymizer(config, TRANSPARENT_LIMITS);
|
|
914
367
|
if (!created.ok)
|
|
915
|
-
return
|
|
368
|
+
return null;
|
|
916
369
|
const pseudonymizer = created;
|
|
917
|
-
const disposals = [];
|
|
918
370
|
const sessions = new Set();
|
|
919
371
|
/** Fails closed on a new session once the tracked-session budget is full. */
|
|
920
372
|
const assertTrackable = (sessionID) => {
|
|
@@ -1205,6 +657,7 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1205
657
|
transportDetectSensitive: (text) => detectSensitive(neutralizeTransportUrls(text)),
|
|
1206
658
|
isTransportIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, neutralizeTransportUrls(text)),
|
|
1207
659
|
attachmentsPolicy,
|
|
660
|
+
anthropicThinking: dialect.anthropicThinking ?? "refuse",
|
|
1208
661
|
};
|
|
1209
662
|
const webSocket = createResponsesWebSocketAdapter(transportService, wireProtection, hasProtectedContext);
|
|
1210
663
|
/** Release only an explicitly deleted session; persisted rows keep their TTL. */
|
|
@@ -1221,7 +674,6 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1221
674
|
persistVersions.delete(sessionID);
|
|
1222
675
|
noPersist.delete(sessionID);
|
|
1223
676
|
};
|
|
1224
|
-
const aiSDK = createAISDKTransportAdmission(wireProtection);
|
|
1225
677
|
/**
|
|
1226
678
|
* Publishes protected string leaves back into the live event in place. The
|
|
1227
679
|
* host keeps its own (possibly class-instance) option/message objects, so we
|
|
@@ -1710,7 +1162,7 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1710
1162
|
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
1711
1163
|
if (descriptor === undefined || !("value" in descriptor))
|
|
1712
1164
|
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1713
|
-
plan(descriptor.value,
|
|
1165
|
+
plan(descriptor.value, hostToolPolicy.classifyField(key, policy), key);
|
|
1714
1166
|
}
|
|
1715
1167
|
}
|
|
1716
1168
|
if (changes.length === 0)
|
|
@@ -1762,15 +1214,18 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1762
1214
|
}
|
|
1763
1215
|
}
|
|
1764
1216
|
};
|
|
1765
|
-
/** Classifies without running a getter or proxy trap: only an own string data property counts. */
|
|
1766
|
-
const isCodeModeCall = (event) => {
|
|
1767
|
-
if (event.tool !== CODE_MODE_TOOL || !isRecordLike(event.input) || types.isProxy(event.input))
|
|
1768
|
-
return false;
|
|
1769
|
-
const descriptor = Object.getOwnPropertyDescriptor(event.input, "code");
|
|
1770
|
-
return descriptor !== undefined && "value" in descriptor && typeof descriptor.value === "string";
|
|
1771
|
-
};
|
|
1772
1217
|
const onToolBefore = (event) => {
|
|
1773
|
-
|
|
1218
|
+
// A host with no explicit restoration policy must never infer that a
|
|
1219
|
+
// token-bearing tool invocation is safe to execute.
|
|
1220
|
+
if (!hostToolPolicy) {
|
|
1221
|
+
const sessionID = typeof event.sessionID === "string" ? event.sessionID : "";
|
|
1222
|
+
const hasNearMiss = sessionID.length > 0 && inputHasNearMiss(sessionID, event.input, false);
|
|
1223
|
+
if (inputCarriesToken(event.input, new WeakSet()) || hasNearMiss) {
|
|
1224
|
+
throw new Error(TOOL_REFUSAL_ERROR);
|
|
1225
|
+
}
|
|
1226
|
+
return;
|
|
1227
|
+
}
|
|
1228
|
+
const codeMode = hostToolPolicy.isCodeModeCall(event);
|
|
1774
1229
|
// Placeholders whose format the model changed would reach the tool as junk
|
|
1775
1230
|
// with no error; refuse them before anything is restored or mutated.
|
|
1776
1231
|
if (typeof event.sessionID === "string" && event.sessionID.length > 0) {
|
|
@@ -1804,15 +1259,12 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1804
1259
|
// "verbatim" otherwise; each key may then switch the policy for its value
|
|
1805
1260
|
// (shell/command-like keys -> "shell", code/script keys -> "inert",
|
|
1806
1261
|
// description/title/label -> "verbatim").
|
|
1807
|
-
const shellTool = isShellTool(rawTool);
|
|
1262
|
+
const shellTool = hostToolPolicy.isShellTool(rawTool);
|
|
1808
1263
|
const rootPolicy = shellTool ? "shell" : "verbatim";
|
|
1809
1264
|
// P1 (2026-10-06b): only proven read-only tools without shell/code fields
|
|
1810
1265
|
// may degrade to literal placeholders; everything else refuses the
|
|
1811
1266
|
// affected invocation when restoration is incomplete.
|
|
1812
|
-
const allowDegraded =
|
|
1813
|
-
!shellTool &&
|
|
1814
|
-
!(isRecordLike(event.input) &&
|
|
1815
|
-
Object.keys(event.input).some((key) => isShellKey(key) || isCodeKey(key)));
|
|
1267
|
+
const allowDegraded = hostToolPolicy.allowsDegradedRestore(rawTool, event.input);
|
|
1816
1268
|
const degraded = { count: 0 };
|
|
1817
1269
|
if (typeof event.input === "string") {
|
|
1818
1270
|
const descriptor = Object.getOwnPropertyDescriptor(event, "input");
|
|
@@ -1837,136 +1289,26 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
|
|
|
1837
1289
|
}
|
|
1838
1290
|
};
|
|
1839
1291
|
return {
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
catch (error) {
|
|
1858
|
-
if (wireProtection)
|
|
1859
|
-
throw error;
|
|
1860
|
-
noticeOnce("HTTP reply restoration hook unavailable; content and tool hooks remain active");
|
|
1861
|
-
}
|
|
1862
|
-
const socketHooks = wireProtection
|
|
1863
|
-
? ["experimental.ws.handshake", "experimental.ws.send", "experimental.ws.receive"]
|
|
1864
|
-
: ["experimental.ws.receive"];
|
|
1865
|
-
for (const name of socketHooks) {
|
|
1866
|
-
try {
|
|
1867
|
-
disposals.push((await ctx.session.hook(name, async (input) => {
|
|
1868
|
-
const event = input;
|
|
1869
|
-
try {
|
|
1870
|
-
const sessionID = requireSessionID(event);
|
|
1871
|
-
assertTrackable(sessionID);
|
|
1872
|
-
if (name === "experimental.ws.receive" && !sessions.has(sessionID))
|
|
1873
|
-
throw new Error(ATTRIBUTION_ERROR);
|
|
1874
|
-
ensureSeeded(sessionID);
|
|
1875
|
-
if (types.isProxy(event))
|
|
1876
|
-
throw new Error(PROTECT_FAILED_ERROR);
|
|
1877
|
-
if (name === "experimental.ws.handshake")
|
|
1878
|
-
webSocket.handshake(event);
|
|
1879
|
-
else {
|
|
1880
|
-
assertWritableDataProperty(event, "frame");
|
|
1881
|
-
event.frame = name === "experimental.ws.send" ? await webSocket.send(event)
|
|
1882
|
-
: wireProtection ? webSocket.receive(event) : webSocket.receiveOnly(event);
|
|
1883
|
-
}
|
|
1884
|
-
track(sessionID);
|
|
1885
|
-
if (name === "experimental.ws.send")
|
|
1886
|
-
persistIfChanged(sessionID);
|
|
1887
|
-
}
|
|
1888
|
-
catch (error) {
|
|
1889
|
-
if (name === "experimental.ws.receive") {
|
|
1890
|
-
try {
|
|
1891
|
-
const frame = webSocket.abandonResponse(event);
|
|
1892
|
-
if (frame !== undefined)
|
|
1893
|
-
event.frame = frame;
|
|
1894
|
-
}
|
|
1895
|
-
catch { /* Unwritable or invalid input stays untouched. */ }
|
|
1896
|
-
noticeOnce("WS reply kept original after attribution or restoration failure; placeholders may remain literal");
|
|
1897
|
-
return;
|
|
1898
|
-
}
|
|
1899
|
-
try {
|
|
1900
|
-
webSocket.reset(event);
|
|
1901
|
-
}
|
|
1902
|
-
catch { /* Invalid attribution has no lane to reset. */ }
|
|
1903
|
-
// Adapter diagnostics are static. Do not surface native URL/
|
|
1904
|
-
// Headers errors, which may embed a credential or raw value.
|
|
1905
|
-
const message = error instanceof Error && error.message.startsWith("LeakShield ")
|
|
1906
|
-
? error.message : PROTECT_FAILED_ERROR;
|
|
1907
|
-
throw new Error(`${message} [hook=${name}]`);
|
|
1908
|
-
}
|
|
1909
|
-
})).dispose);
|
|
1910
|
-
}
|
|
1911
|
-
catch (error) {
|
|
1912
|
-
if (wireProtection)
|
|
1913
|
-
throw error;
|
|
1914
|
-
noticeOnce("WS reply restoration hook unavailable; content and tool hooks remain active");
|
|
1915
|
-
}
|
|
1916
|
-
}
|
|
1917
|
-
for (const name of wireProtection ? ["sdk", "language"] : []) {
|
|
1918
|
-
disposals.push((await ctx.aisdk.hook(name, (event) => {
|
|
1919
|
-
try {
|
|
1920
|
-
aiSDK.admit(event);
|
|
1921
|
-
}
|
|
1922
|
-
catch {
|
|
1923
|
-
throw new Error(`${UNSUPPORTED_ROUTE_ERROR} AI SDK providers must honor OpenCode's injected HTTP fetch. [hook=aisdk.${name}]`);
|
|
1924
|
-
}
|
|
1925
|
-
})).dispose);
|
|
1926
|
-
}
|
|
1927
|
-
disposals.push((await ctx.tool.hook("execute.before", (event) => {
|
|
1928
|
-
onToolBefore(event);
|
|
1929
|
-
})).dispose);
|
|
1930
|
-
// Public V2 events are an optional reclamation optimization: an absent
|
|
1931
|
-
// or failed stream retains mappings rather than evicting live state.
|
|
1932
|
-
// Subscribe only after all protection hooks have been armed.
|
|
1933
|
-
if (ctx.event?.subscribe) {
|
|
1934
|
-
const controller = new AbortController();
|
|
1935
|
-
disposals.push(async () => { controller.abort(); });
|
|
1936
|
-
void (async () => {
|
|
1937
|
-
try {
|
|
1938
|
-
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
1939
|
-
if (controller.signal.aborted)
|
|
1940
|
-
break;
|
|
1941
|
-
if (event.type === "session.deleted")
|
|
1942
|
-
releaseSession(event.data.sessionID);
|
|
1943
|
-
}
|
|
1944
|
-
if (!controller.signal.aborted)
|
|
1945
|
-
noticeOnce("session lifecycle stream ended; mappings retained until unload");
|
|
1946
|
-
}
|
|
1947
|
-
catch {
|
|
1948
|
-
if (!controller.signal.aborted)
|
|
1949
|
-
noticeOnce("session lifecycle stream unavailable; mappings retained until unload");
|
|
1950
|
-
}
|
|
1951
|
-
})();
|
|
1952
|
-
}
|
|
1953
|
-
}
|
|
1954
|
-
catch (error) {
|
|
1955
|
-
// Registration failed partway: undo what was armed, then surface the
|
|
1956
|
-
// failure so the caller can fall back to its fail-closed setup.
|
|
1957
|
-
// R-round (F4.5): the store handle must not leak on this path.
|
|
1958
|
-
await runDisposals(disposals);
|
|
1959
|
-
webSocket.dispose();
|
|
1960
|
-
aiSDK.dispose();
|
|
1961
|
-
store?.close();
|
|
1962
|
-
store = null;
|
|
1963
|
-
throw error;
|
|
1964
|
-
}
|
|
1292
|
+
hasSession: (sessionID) => sessions.has(sessionID),
|
|
1293
|
+
assertTrackable,
|
|
1294
|
+
ensureSeeded,
|
|
1295
|
+
track,
|
|
1296
|
+
persistIfChanged,
|
|
1297
|
+
protectRequestKind,
|
|
1298
|
+
onHttpRequest,
|
|
1299
|
+
onHttpResponse,
|
|
1300
|
+
onToolBefore,
|
|
1301
|
+
releaseSession,
|
|
1302
|
+
noticeOnce,
|
|
1303
|
+
webSocket,
|
|
1304
|
+
assertWritableDataProperty,
|
|
1305
|
+
closeResources: () => {
|
|
1306
|
+
webSocket.dispose();
|
|
1307
|
+
store?.close();
|
|
1308
|
+
store = null;
|
|
1965
1309
|
},
|
|
1966
|
-
dispose:
|
|
1967
|
-
await runDisposals(disposals);
|
|
1310
|
+
dispose: () => {
|
|
1968
1311
|
webSocket.dispose();
|
|
1969
|
-
aiSDK.dispose();
|
|
1970
1312
|
for (const sessionID of sessions)
|
|
1971
1313
|
pseudonymizer.clearSession(sessionID);
|
|
1972
1314
|
sessions.clear();
|