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
|
@@ -0,0 +1,1492 @@
|
|
|
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
|
+
import { types } from "node:util";
|
|
40
|
+
import { containsTokenPrefix, createPseudonymizer, } from "./decision/pseudonymization.js";
|
|
41
|
+
import { MappingForgottenError, MappingKeyMismatchError, MappingSnapshotTooLargeError, MappingStoreConflictError, openMappingStore, } from "./decision/mapping-store.js";
|
|
42
|
+
import { resolveMappingKey } from "./decision/mapping-key.js";
|
|
43
|
+
import { walkSchemaStrings } from "./decision/schema-strings.js";
|
|
44
|
+
import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./opencode-transparent-http.js";
|
|
45
|
+
import { createResponsesWebSocketAdapter } from "./opencode-transparent-ws.js";
|
|
46
|
+
import { createAISDKTransportAdmission } from "./opencode-transparent-aisdk.js";
|
|
47
|
+
import { BUILTIN_RULES } from "./rules/builtin.js";
|
|
48
|
+
// ─── Static failure messages (no content ever included) ─────────────────────
|
|
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 because a placeholder has no mapping in this session. Re-read the file, then try again.";
|
|
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
|
+
function toolRestoreError(reason) {
|
|
60
|
+
if (reason === "unknown_token" || reason === "malformed_token")
|
|
61
|
+
return TOOL_UNKNOWN_MAPPING_ERROR;
|
|
62
|
+
if (reason === "operation_limit")
|
|
63
|
+
return TOOL_RESTORE_LIMIT_ERROR;
|
|
64
|
+
return TOOL_REFUSAL_ERROR;
|
|
65
|
+
}
|
|
66
|
+
/** Shell syntax excluded from unquoted literal words. Known tokens are
|
|
67
|
+
* removed before this check; a token-shaped prefix alone grants no exemption. */
|
|
68
|
+
const UNSUPPORTED_SHELL_SYNTAX = /[\x00-\x1f\x7f'"`\\$;|&<>(){}*?\[\]!~#]/;
|
|
69
|
+
/** A deliberately small literal-word lexer, not a general shell parser.
|
|
70
|
+
* Quotes must enclose the entire word. No escape decoding, expansions, quote
|
|
71
|
+
* concatenation or control characters are accepted. Decode command/flag
|
|
72
|
+
* quotes too, so `'sh' '-c' TOKEN` cannot bypass the interpreter gate. */
|
|
73
|
+
function parseLiteralShellWords(text) {
|
|
74
|
+
if (/[\x00-\x1f\x7f]/.test(text))
|
|
75
|
+
return null;
|
|
76
|
+
// The new quote/redirection subset is POSIX-specific. Keep the previous
|
|
77
|
+
// conservative behavior on Windows, where the host may launch cmd.exe.
|
|
78
|
+
if (process.platform === "win32" && /['">]/.test(text))
|
|
79
|
+
return null;
|
|
80
|
+
const words = [];
|
|
81
|
+
let at = 0;
|
|
82
|
+
while (at < text.length) {
|
|
83
|
+
if (text[at] === " ") {
|
|
84
|
+
at += 1;
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const start = at;
|
|
88
|
+
if (text[at] === ">") {
|
|
89
|
+
at += text[at + 1] === ">" ? 2 : 1;
|
|
90
|
+
words.push({ start, end: at, value: text.slice(start, at), quote: "none", redirect: true });
|
|
91
|
+
}
|
|
92
|
+
else if (text[at] === "'" || text[at] === '"') {
|
|
93
|
+
const delimiter = text[at++];
|
|
94
|
+
const valueStart = at;
|
|
95
|
+
while (at < text.length && text[at] !== delimiter)
|
|
96
|
+
at += 1;
|
|
97
|
+
if (at === text.length)
|
|
98
|
+
return null;
|
|
99
|
+
const value = text.slice(valueStart, at++);
|
|
100
|
+
const quote = delimiter === "'" ? "single" : "double";
|
|
101
|
+
if (quote === "double" && /[`\\$!]/.test(value))
|
|
102
|
+
return null;
|
|
103
|
+
words.push({ start, end: at, value, quote, redirect: false });
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
while (at < text.length && text[at] !== " ")
|
|
107
|
+
at += 1;
|
|
108
|
+
const value = text.slice(start, at);
|
|
109
|
+
if (UNSUPPORTED_SHELL_SYNTAX.test(value.replace(TOKEN_SCAN, "TOKEN")) || value.includes(">"))
|
|
110
|
+
return null;
|
|
111
|
+
words.push({ start, end: at, value, quote: "none", redirect: false });
|
|
112
|
+
}
|
|
113
|
+
if (at < text.length && text[at] !== " ")
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return words;
|
|
117
|
+
}
|
|
118
|
+
const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
119
|
+
const SHELL_COMMAND_WRAPPERS = new Set([
|
|
120
|
+
"builtin",
|
|
121
|
+
"command",
|
|
122
|
+
"doas",
|
|
123
|
+
"env",
|
|
124
|
+
"eval",
|
|
125
|
+
"exec",
|
|
126
|
+
"nice",
|
|
127
|
+
"nohup",
|
|
128
|
+
"pkexec",
|
|
129
|
+
"runuser",
|
|
130
|
+
"setsid",
|
|
131
|
+
"source",
|
|
132
|
+
"sudo",
|
|
133
|
+
"su",
|
|
134
|
+
"time",
|
|
135
|
+
"timeout",
|
|
136
|
+
"xargs",
|
|
137
|
+
]);
|
|
138
|
+
const INLINE_SCRIPT_FLAGS = new Map([
|
|
139
|
+
["python", new Set(["-c"])],
|
|
140
|
+
["python3", new Set(["-c"])],
|
|
141
|
+
["node", new Set(["-e", "--eval", "-p", "--print"])],
|
|
142
|
+
["nodejs", new Set(["-e", "--eval", "-p", "--print"])],
|
|
143
|
+
["ruby", new Set(["-e", "-pe", "-ne"])],
|
|
144
|
+
["perl", new Set(["-e", "-pe", "-ne", "-E"])],
|
|
145
|
+
["php", new Set(["-r"])],
|
|
146
|
+
["lua", new Set(["-e"])],
|
|
147
|
+
["powershell", new Set(["-c", "-command", "-encodedcommand", "-e"])],
|
|
148
|
+
["pwsh", new Set(["-c", "-command", "-encodedcommand", "-e"])],
|
|
149
|
+
["cmd", new Set(["/c", "/k"])],
|
|
150
|
+
]);
|
|
151
|
+
const SCRIPT_ARGUMENT_INTERPRETERS = new Set(["awk", "sed", "jq"]);
|
|
152
|
+
const SHELL_INTERPRETERS = new Set(["sh", "bash", "dash", "zsh", "ksh", "ash", "csh", "tcsh", "fish"]);
|
|
153
|
+
/** Returns only ordinary arguments, never command/assignment/redirect words. */
|
|
154
|
+
function parseSupportedShellArguments(text) {
|
|
155
|
+
const parsed = parseLiteralShellWords(text);
|
|
156
|
+
if (parsed === null)
|
|
157
|
+
return null;
|
|
158
|
+
const redirectIndex = parsed.findIndex((word) => word.redirect);
|
|
159
|
+
if (redirectIndex !== -1) {
|
|
160
|
+
const target = parsed[redirectIndex + 1];
|
|
161
|
+
if (redirectIndex === 0 || redirectIndex !== parsed.length - 2 ||
|
|
162
|
+
target.redirect || target.value.length === 0 || containsTokenPrefix(target.value))
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
const words = redirectIndex === -1 ? parsed : parsed.slice(0, redirectIndex);
|
|
166
|
+
const commandIndex = words.findIndex((word) => word.quote !== "none" || !ASSIGNMENT_WORD.test(word.value));
|
|
167
|
+
if (commandIndex === -1)
|
|
168
|
+
return null;
|
|
169
|
+
const commandName = words[commandIndex].value.split("/").at(-1)?.toLowerCase() ?? "";
|
|
170
|
+
if (SHELL_COMMAND_WRAPPERS.has(commandName) || SCRIPT_ARGUMENT_INTERPRETERS.has(commandName))
|
|
171
|
+
return null;
|
|
172
|
+
const argumentsOnly = words.slice(commandIndex + 1);
|
|
173
|
+
if (SHELL_INTERPRETERS.has(commandName)) {
|
|
174
|
+
if (argumentsOnly.some((argument) => /^-[A-Za-z]*c[A-Za-z]*$/.test(argument.value)))
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
const inlineFlags = INLINE_SCRIPT_FLAGS.get(commandName) ??
|
|
178
|
+
(/^python(?:\d+(?:\.\d+)*)?$/.test(commandName) ? INLINE_SCRIPT_FLAGS.get("python") : undefined);
|
|
179
|
+
if (inlineFlags && argumentsOnly.some((argument) => inlineFlags.has(argument.value.toLowerCase())))
|
|
180
|
+
return null;
|
|
181
|
+
if (commandName === "deno" && argumentsOnly.some((argument) => argument.value === "eval"))
|
|
182
|
+
return null;
|
|
183
|
+
return argumentsOnly;
|
|
184
|
+
}
|
|
185
|
+
/** Characters forbidden inside restored shell argument words. */
|
|
186
|
+
const SHELL_UNSAFE = /[\s'"`\\$;|&<>(){}*?\[\]!~#\x00-\x1F\x7F]/;
|
|
187
|
+
/**
|
|
188
|
+
* Conservative allowlist of non-executing tools. Any tool not listed here is
|
|
189
|
+
* treated as potentially shell-like and requires shell-safe originals, so an
|
|
190
|
+
* unrecognized (or newly added) executing tool fails closed rather than
|
|
191
|
+
* receiving a value that could change its meaning.
|
|
192
|
+
*/
|
|
193
|
+
const NON_SHELL_TOOLS = new Set([
|
|
194
|
+
"read",
|
|
195
|
+
"read_file",
|
|
196
|
+
"view",
|
|
197
|
+
"write",
|
|
198
|
+
"write_file",
|
|
199
|
+
"create_file",
|
|
200
|
+
"edit",
|
|
201
|
+
"edit_file",
|
|
202
|
+
"multiedit",
|
|
203
|
+
"patch",
|
|
204
|
+
"apply_patch",
|
|
205
|
+
"str_replace",
|
|
206
|
+
"str_replace_editor",
|
|
207
|
+
"grep",
|
|
208
|
+
"glob",
|
|
209
|
+
"list",
|
|
210
|
+
"ls",
|
|
211
|
+
"find",
|
|
212
|
+
"webfetch",
|
|
213
|
+
"websearch",
|
|
214
|
+
"fetch",
|
|
215
|
+
"todowrite",
|
|
216
|
+
"todoread",
|
|
217
|
+
"notebookedit",
|
|
218
|
+
]);
|
|
219
|
+
/**
|
|
220
|
+
* Tools whose calls are observably read-only: an unresolved placeholder in
|
|
221
|
+
* their arguments reads/greps/lists against a literal string and matches
|
|
222
|
+
* nothing — no state change, no outbound transmission. Only these qualify
|
|
223
|
+
* for P1 (2026-10-06b) best-effort literal passthrough when restoration is
|
|
224
|
+
* incomplete. Everything else — writes, deletes, edits, network calls,
|
|
225
|
+
* shell, unknown tools — refuses the affected invocation.
|
|
226
|
+
*/
|
|
227
|
+
const READ_ONLY_TOOLS = new Set([
|
|
228
|
+
"read",
|
|
229
|
+
"read_file",
|
|
230
|
+
"view",
|
|
231
|
+
"grep",
|
|
232
|
+
"glob",
|
|
233
|
+
"list",
|
|
234
|
+
"ls",
|
|
235
|
+
"find",
|
|
236
|
+
"todoread",
|
|
237
|
+
]);
|
|
238
|
+
/**
|
|
239
|
+
* Content-free degradation notice for the host log: one WARN line, a fixed
|
|
240
|
+
* context word plus a count, never request content. No side files, no
|
|
241
|
+
* provider-body notices (P1, 2026-10-06b).
|
|
242
|
+
*/
|
|
243
|
+
const warnDegradation = (context) => {
|
|
244
|
+
console.warn(`[leakshield] degraded: ${context}`);
|
|
245
|
+
};
|
|
246
|
+
/** Preserve the existing quote context; never add quoting or reinterpret the
|
|
247
|
+
* original as code. Leading '-' stays forbidden even when quoted (options are
|
|
248
|
+
* interpreted after quote removal). Controls are forbidden in every context. */
|
|
249
|
+
function isShellSafeOriginal(text, quote) {
|
|
250
|
+
if (text.length === 0 || text.startsWith("-") || /[\x00-\x1f\x7f]/.test(text))
|
|
251
|
+
return false;
|
|
252
|
+
if (quote === "single")
|
|
253
|
+
return !text.includes("'");
|
|
254
|
+
if (quote === "double")
|
|
255
|
+
return !/["`\\$!]/.test(text);
|
|
256
|
+
return !SHELL_UNSAFE.test(text);
|
|
257
|
+
}
|
|
258
|
+
/** Matches a fully formed reserved token (either version), for per-token shell safety checks. */
|
|
259
|
+
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;
|
|
260
|
+
/**
|
|
261
|
+
* Bound on distinct session identities retained for disposal. The core already
|
|
262
|
+
* caps committed sessions; this bounds identities seen with safe-only content
|
|
263
|
+
* so a stream of fresh session ids cannot grow the set without limit. Beyond
|
|
264
|
+
* it, a new session fails closed.
|
|
265
|
+
*/
|
|
266
|
+
const MAX_TRACKED_SESSIONS = 4096;
|
|
267
|
+
/**
|
|
268
|
+
* The core's small standalone defaults are not a whole model-history budget.
|
|
269
|
+
* Match its mapping-session ceiling to the guard's existing bookkeeping cap.
|
|
270
|
+
* HTTP bodies and WS frames are already capped at 4 MiB; allow 8 Mi UTF-16
|
|
271
|
+
* units of combined input/output work for assembled requests. The node cap
|
|
272
|
+
* bounds schema-heavy histories independently. Per-string scanner bounds,
|
|
273
|
+
* depth and aggregate mapping-byte/entry caps remain unchanged.
|
|
274
|
+
*/
|
|
275
|
+
const TRANSPARENT_LIMITS = {
|
|
276
|
+
maxSessions: MAX_TRACKED_SESSIONS,
|
|
277
|
+
maxNodes: 100000,
|
|
278
|
+
maxUnitsPerOperation: 8 * 1024 * 1024,
|
|
279
|
+
};
|
|
280
|
+
// ─── Structural validation ───────────────────────────────────────────────────
|
|
281
|
+
function isRecordLike(value) {
|
|
282
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
283
|
+
}
|
|
284
|
+
function requireSessionID(event) {
|
|
285
|
+
if (typeof event.sessionID !== "string" || event.sessionID.length === 0) {
|
|
286
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
287
|
+
}
|
|
288
|
+
return event.sessionID;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Protocol/structural identifiers of a request snapshot: message ids and
|
|
292
|
+
* roles, part types, tool-call ids/names, tool names and the whole tool input
|
|
293
|
+
* schema. These must survive protection verbatim; the masker never renames
|
|
294
|
+
* them, and the guard refuses rather than silently renaming when one itself
|
|
295
|
+
* carries sensitive content (see assertStructuralSafe). Returned in a stable
|
|
296
|
+
* walk order so the pre- and post-protection collections can be compared.
|
|
297
|
+
*/
|
|
298
|
+
function collectStructuralStrings(event) {
|
|
299
|
+
const out = [];
|
|
300
|
+
const pushString = (value) => {
|
|
301
|
+
if (typeof value === "string")
|
|
302
|
+
out.push(value);
|
|
303
|
+
};
|
|
304
|
+
if (Array.isArray(event.system)) {
|
|
305
|
+
for (const part of event.system) {
|
|
306
|
+
if (isRecordLike(part))
|
|
307
|
+
pushString(part.type);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
if (Array.isArray(event.messages)) {
|
|
311
|
+
for (const message of event.messages) {
|
|
312
|
+
if (!isRecordLike(message))
|
|
313
|
+
continue;
|
|
314
|
+
pushString(message.id);
|
|
315
|
+
pushString(message.role);
|
|
316
|
+
if (Array.isArray(message.content)) {
|
|
317
|
+
for (const part of message.content) {
|
|
318
|
+
if (!isRecordLike(part))
|
|
319
|
+
continue;
|
|
320
|
+
pushString(part.type);
|
|
321
|
+
if (part.type === "tool-call") {
|
|
322
|
+
pushString(part.id);
|
|
323
|
+
pushString(part.name);
|
|
324
|
+
pushString(part.toolName);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (isRecordLike(event.tools)) {
|
|
331
|
+
for (const name of Object.keys(event.tools)) {
|
|
332
|
+
out.push(name);
|
|
333
|
+
const tool = event.tools[name];
|
|
334
|
+
// Schema annotation prose (description/title values) is content, not
|
|
335
|
+
// structural: it masks to a token instead of refusing the request.
|
|
336
|
+
if (isRecordLike(tool) && tool.input !== undefined)
|
|
337
|
+
walkSchemaStrings(out, tool.input);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
return out;
|
|
341
|
+
}
|
|
342
|
+
// ─── Provider-opaque state ───────────────────────────────────────────────────
|
|
343
|
+
/**
|
|
344
|
+
* Provider state the host replays verbatim (OpenAI encrypted reasoning and
|
|
345
|
+
* compaction checkpoints, Anthropic/Bedrock signatures and redacted thinking,
|
|
346
|
+
* Gemini thought signatures). It is ciphertext or a MAC over prior output: a
|
|
347
|
+
* detector false positive inside it (an `AIza` run in base64, say) rewrites
|
|
348
|
+
* bytes the provider authenticates and the request fails with
|
|
349
|
+
* `invalid_encrypted_content`. Masking it protects nothing — the plaintext it
|
|
350
|
+
* stands for is not in it — so it crosses the boundary unscanned, but only
|
|
351
|
+
* when position AND shape both say it is provider state:
|
|
352
|
+
* - position: an assistant message's reasoning/compaction `encrypted`, or a
|
|
353
|
+
* known key under any assistant part's `providerMetadata.<provider>`;
|
|
354
|
+
* - shape: a single base64/base64url run whose decoded bytes are mostly
|
|
355
|
+
* non-printable (ciphertext), so readable text — raw or merely
|
|
356
|
+
* base64-encoded — keeps being scanned like any other leaf.
|
|
357
|
+
* Everything else in those parts (reasoning text, other metadata) is masked
|
|
358
|
+
* as usual.
|
|
359
|
+
*/
|
|
360
|
+
const OPAQUE_STATE_SENTINEL = "__sg_opaque_state";
|
|
361
|
+
const OPAQUE_STATE_PART_TYPES = new Set(["reasoning", "compaction"]);
|
|
362
|
+
const OPAQUE_STATE_METADATA_KEYS = ["reasoningEncryptedContent", "encryptedContent", "signature", "redactedData", "thoughtSignature"];
|
|
363
|
+
const OPAQUE_STATE_SHAPE = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
364
|
+
const OPAQUE_STATE_MIN_LENGTH = 16;
|
|
365
|
+
/** Uniform random bytes are ~37% printable; encoded text is ~100%. */
|
|
366
|
+
const OPAQUE_STATE_MAX_PRINTABLE_RATIO = 0.75;
|
|
367
|
+
function isOpaqueStateShaped(value) {
|
|
368
|
+
if (value.length < OPAQUE_STATE_MIN_LENGTH || !OPAQUE_STATE_SHAPE.test(value))
|
|
369
|
+
return false;
|
|
370
|
+
// Node's base64 decoder accepts both the standard and url-safe alphabets.
|
|
371
|
+
const bytes = Buffer.from(value, "base64");
|
|
372
|
+
if (bytes.length === 0)
|
|
373
|
+
return false;
|
|
374
|
+
let printable = 0;
|
|
375
|
+
for (const byte of bytes) {
|
|
376
|
+
if ((byte >= 0x20 && byte <= 0x7e) || byte === 0x09 || byte === 0x0a || byte === 0x0d)
|
|
377
|
+
printable++;
|
|
378
|
+
}
|
|
379
|
+
return printable / bytes.length <= OPAQUE_STATE_MAX_PRINTABLE_RATIO;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Substitutes trusted opaque state with sentinels around the masking
|
|
383
|
+
* transaction, then writes each original back at its exact path in the
|
|
384
|
+
* protected projection. Any path that no longer holds its sentinel fails the
|
|
385
|
+
* whole request closed: nothing is restored into a moved or rewritten slot.
|
|
386
|
+
*/
|
|
387
|
+
function withOpaqueProviderState(plain, fn) {
|
|
388
|
+
const slots = [];
|
|
389
|
+
const stash = (container, key, path) => {
|
|
390
|
+
const value = container[key];
|
|
391
|
+
if (typeof value !== "string" || !isOpaqueStateShaped(value))
|
|
392
|
+
return;
|
|
393
|
+
container[key] = `${OPAQUE_STATE_SENTINEL}_${slots.length}`;
|
|
394
|
+
slots.push({ path, value });
|
|
395
|
+
};
|
|
396
|
+
if (Array.isArray(plain.messages)) {
|
|
397
|
+
plain.messages.forEach((message, messageIndex) => {
|
|
398
|
+
if (!isRecordLike(message) || message.role !== "assistant" || !Array.isArray(message.content))
|
|
399
|
+
return;
|
|
400
|
+
message.content.forEach((part, partIndex) => {
|
|
401
|
+
if (!isRecordLike(part))
|
|
402
|
+
return;
|
|
403
|
+
const base = ["messages", messageIndex, "content", partIndex];
|
|
404
|
+
if (typeof part.type === "string" && OPAQUE_STATE_PART_TYPES.has(part.type)) {
|
|
405
|
+
stash(part, "encrypted", [...base, "encrypted"]);
|
|
406
|
+
}
|
|
407
|
+
if (!isRecordLike(part.providerMetadata))
|
|
408
|
+
return;
|
|
409
|
+
for (const [provider, metadata] of Object.entries(part.providerMetadata)) {
|
|
410
|
+
if (!isRecordLike(metadata))
|
|
411
|
+
continue;
|
|
412
|
+
for (const key of OPAQUE_STATE_METADATA_KEYS) {
|
|
413
|
+
stash(metadata, key, [...base, "providerMetadata", provider, key]);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
if (slots.length === 0)
|
|
420
|
+
return fn(plain);
|
|
421
|
+
const result = fn(plain);
|
|
422
|
+
slots.forEach(({ path, value }, index) => {
|
|
423
|
+
let container = result;
|
|
424
|
+
for (const segment of path.slice(0, -1)) {
|
|
425
|
+
container = container !== null && typeof container === "object" ? container[segment] : undefined;
|
|
426
|
+
}
|
|
427
|
+
const key = path[path.length - 1];
|
|
428
|
+
if (container === null || typeof container !== "object" || container[key] !== `${OPAQUE_STATE_SENTINEL}_${index}`) {
|
|
429
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
430
|
+
}
|
|
431
|
+
container[key] = value;
|
|
432
|
+
});
|
|
433
|
+
return result;
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Replaces media/file attachment PARTS (array slots) with an explanatory text
|
|
437
|
+
* part: binary or base64 content cannot be scanned, so it never crosses the
|
|
438
|
+
* boundary — the conversation continues with a notice instead of the whole
|
|
439
|
+
* session failing. (2026-10-05 product decision, owner-approved; spec
|
|
440
|
+
* revised.) A media/file record found in a NON-part slot (a bare object
|
|
441
|
+
* value) is an unexpected shape and still fails closed.
|
|
442
|
+
*/
|
|
443
|
+
const ATTACHMENT_PLACEHOLDER_TEXT = "[leakshield: attachment omitted — binary content is never sent to the model]";
|
|
444
|
+
const ATTACHMENT_ALLOW_NOTICE_TEXT = "[leakshield: attachment(s) allowed through unscanned per configuration — the user vouches for their content]";
|
|
445
|
+
/**
|
|
446
|
+
* Applies the attachment policy to a live event field.
|
|
447
|
+
* "block": media/file parts in part arrays become omission-notice text parts
|
|
448
|
+
* (the attachment is not sent; the conversation continues).
|
|
449
|
+
* "allow": parts are left intact and ONE notice text part is appended to the
|
|
450
|
+
* field so the choice stays visible to the user and the model.
|
|
451
|
+
* A media/file record in a non-part slot (a bare object value) is an
|
|
452
|
+
* unexpected shape and fails closed in BOTH policies.
|
|
453
|
+
*/
|
|
454
|
+
function applyAttachmentPolicy(value, seen, policy) {
|
|
455
|
+
if (value === null || typeof value !== "object")
|
|
456
|
+
return false;
|
|
457
|
+
if (seen.has(value))
|
|
458
|
+
return false;
|
|
459
|
+
seen.add(value);
|
|
460
|
+
const isAttachment = (item) => isRecordLike(item) && (item.type === "media" || item.type === "file");
|
|
461
|
+
let changed = false;
|
|
462
|
+
if (Array.isArray(value)) {
|
|
463
|
+
for (let index = 0; index < value.length; index++) {
|
|
464
|
+
const item = value[index];
|
|
465
|
+
if (isAttachment(item)) {
|
|
466
|
+
if (policy === "block") {
|
|
467
|
+
value[index] = { type: "text", text: ATTACHMENT_PLACEHOLDER_TEXT };
|
|
468
|
+
changed = true;
|
|
469
|
+
}
|
|
470
|
+
// allow mode: leave the attachment intact; the caller appends the notice.
|
|
471
|
+
}
|
|
472
|
+
else if (applyAttachmentPolicy(item, seen, policy)) {
|
|
473
|
+
changed = true;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
return changed;
|
|
477
|
+
}
|
|
478
|
+
const record = value;
|
|
479
|
+
for (const key of Object.keys(record)) {
|
|
480
|
+
const item = record[key];
|
|
481
|
+
if (isAttachment(item)) {
|
|
482
|
+
// Not a parts-array slot: unexpected shape, fail closed.
|
|
483
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
484
|
+
}
|
|
485
|
+
if (applyAttachmentPolicy(item, seen, policy))
|
|
486
|
+
changed = true;
|
|
487
|
+
}
|
|
488
|
+
return changed;
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Appends ONE visible notice when allow-mode attachments are present.
|
|
492
|
+
* Only a user-role message is an eligible slot: a bare text part inside an
|
|
493
|
+
* assistant/tool message breaks the host's provider serialization ("OpenAI
|
|
494
|
+
* Chat tool messages only support tool-result content for now"). When no
|
|
495
|
+
* user message with a content array exists, the notice is skipped — the
|
|
496
|
+
* request shape is never corrupted to deliver it.
|
|
497
|
+
*/
|
|
498
|
+
function appendAllowNotice(event, found) {
|
|
499
|
+
if (!found)
|
|
500
|
+
return;
|
|
501
|
+
const messages = event.messages;
|
|
502
|
+
if (!Array.isArray(messages) || messages.length === 0)
|
|
503
|
+
return;
|
|
504
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
505
|
+
const message = messages[index];
|
|
506
|
+
if (!isRecordLike(message) || message.role !== "user" || !Array.isArray(message.content))
|
|
507
|
+
continue;
|
|
508
|
+
message.content.push({ type: "text", text: ATTACHMENT_ALLOW_NOTICE_TEXT });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function hasAttachmentPart(value, seen) {
|
|
513
|
+
if (value === null || typeof value !== "object")
|
|
514
|
+
return false;
|
|
515
|
+
if (seen.has(value))
|
|
516
|
+
return false;
|
|
517
|
+
seen.add(value);
|
|
518
|
+
if (Array.isArray(value)) {
|
|
519
|
+
return value.some((item) => (isRecordLike(item) && (item.type === "media" || item.type === "file")) ||
|
|
520
|
+
hasAttachmentPart(item, seen));
|
|
521
|
+
}
|
|
522
|
+
const record = value;
|
|
523
|
+
return Object.values(record).some((item) => (isRecordLike(item) && (item.type === "media" || item.type === "file")) ||
|
|
524
|
+
hasAttachmentPart(item, seen));
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* True when any string reachable from the tool input — as a value OR as an
|
|
528
|
+
* object key — carries the reserved token prefix (owned or foreign). Such
|
|
529
|
+
* inputs are refused before execution: with no pinned adapter there is no
|
|
530
|
+
* schema-validated, non-shell tool whose arguments may be restored. Keys are
|
|
531
|
+
* inspected too, because a token-keyed argument would otherwise escape the
|
|
532
|
+
* refusal gate.
|
|
533
|
+
*/
|
|
534
|
+
function inputCarriesToken(value, seen) {
|
|
535
|
+
if (typeof value === "string")
|
|
536
|
+
return containsTokenPrefix(value);
|
|
537
|
+
if (value === null || typeof value !== "object")
|
|
538
|
+
return false;
|
|
539
|
+
if (types.isProxy(value))
|
|
540
|
+
return true;
|
|
541
|
+
if (seen.has(value))
|
|
542
|
+
return true;
|
|
543
|
+
seen.add(value);
|
|
544
|
+
if (Object.getOwnPropertySymbols(value).length > 0)
|
|
545
|
+
return true;
|
|
546
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
547
|
+
for (const key of Object.keys(descriptors)) {
|
|
548
|
+
if (Array.isArray(value) && key === "length")
|
|
549
|
+
continue;
|
|
550
|
+
if (containsTokenPrefix(key))
|
|
551
|
+
return true;
|
|
552
|
+
const descriptor = descriptors[key];
|
|
553
|
+
if (!("value" in descriptor))
|
|
554
|
+
return true;
|
|
555
|
+
if (inputCarriesToken(descriptor.value, seen))
|
|
556
|
+
return true;
|
|
557
|
+
}
|
|
558
|
+
return false;
|
|
559
|
+
}
|
|
560
|
+
/** Runs pending disposals (best effort, reverse order) without throwing. */
|
|
561
|
+
async function runDisposals(disposals) {
|
|
562
|
+
for (let i = disposals.length - 1; i >= 0; i--) {
|
|
563
|
+
try {
|
|
564
|
+
await disposals[i]();
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
// Continue clearing remaining registrations.
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
disposals.length = 0;
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* Creates a fail-closed guard whose every hook refuses all operations. Exported
|
|
574
|
+
* so the plugin entry can arm it for transparent mode when setup fails before
|
|
575
|
+
* (or during) guard construction: a transparent fallback must cover the
|
|
576
|
+
* transport routes (http/ws/aisdk) in wire mode. Hook-only failures refuse
|
|
577
|
+
* content/tool dispatch without introducing new transport registrations.
|
|
578
|
+
*/
|
|
579
|
+
export function createFailClosedTransparentGuard(wireProtection = true) {
|
|
580
|
+
const disposals = [];
|
|
581
|
+
const refuse = () => {
|
|
582
|
+
throw new Error(INITIALIZATION_ERROR);
|
|
583
|
+
};
|
|
584
|
+
return {
|
|
585
|
+
setup: async (ctx) => {
|
|
586
|
+
try {
|
|
587
|
+
const contentHooks = ["context", "compaction", "generate", "title"];
|
|
588
|
+
const wireHooks = [
|
|
589
|
+
"http.request",
|
|
590
|
+
"http.response",
|
|
591
|
+
"experimental.ws.handshake",
|
|
592
|
+
"experimental.ws.send",
|
|
593
|
+
"experimental.ws.receive",
|
|
594
|
+
];
|
|
595
|
+
for (const name of [...contentHooks, ...(wireProtection ? wireHooks : [])]) {
|
|
596
|
+
disposals.push((await ctx.session.hook(name, refuse)).dispose);
|
|
597
|
+
}
|
|
598
|
+
if (wireProtection) {
|
|
599
|
+
disposals.push((await ctx.aisdk.hook("sdk", refuse)).dispose);
|
|
600
|
+
disposals.push((await ctx.aisdk.hook("language", refuse)).dispose);
|
|
601
|
+
}
|
|
602
|
+
disposals.push((await ctx.tool.hook("execute.before", refuse)).dispose);
|
|
603
|
+
}
|
|
604
|
+
catch (error) {
|
|
605
|
+
await runDisposals(disposals);
|
|
606
|
+
throw error;
|
|
607
|
+
}
|
|
608
|
+
},
|
|
609
|
+
dispose: () => runDisposals(disposals),
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Creates the transparent session guard for one plugin setup (= one OpenCode
|
|
614
|
+
* process): a single bounded pseudonymizer, exact-session mapping, private
|
|
615
|
+
* request attribution, and its own registrations. With persistence options
|
|
616
|
+
* the guard additionally hydrates sessions from the encrypted store on
|
|
617
|
+
* first touch and writes committed mappings back (decision §4: dispose
|
|
618
|
+
* unloads hooks but never deletes persisted mappings — forget is the only
|
|
619
|
+
* erasure path).
|
|
620
|
+
*/
|
|
621
|
+
export function createTransparentSessionGuard(config, attachmentsPolicy = "block", wireProtection = true, persistence) {
|
|
622
|
+
const created = createPseudonymizer(config, TRANSPARENT_LIMITS);
|
|
623
|
+
if (!created.ok)
|
|
624
|
+
return createFailClosedTransparentGuard(wireProtection);
|
|
625
|
+
const pseudonymizer = created;
|
|
626
|
+
const disposals = [];
|
|
627
|
+
const sessions = new Set();
|
|
628
|
+
/** Fails closed on a new session once the tracked-session budget is full. */
|
|
629
|
+
const assertTrackable = (sessionID) => {
|
|
630
|
+
if (!sessions.has(sessionID) && sessions.size >= MAX_TRACKED_SESSIONS) {
|
|
631
|
+
throw new Error(`${PROTECT_FAILED_ERROR} [stage=session.track reason=session_limit]`);
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
/**
|
|
635
|
+
* Retains a session for disposal. Called only AFTER an operation succeeds, so
|
|
636
|
+
* failed requests cannot grow the set ("failed-session IDs unbounded").
|
|
637
|
+
*/
|
|
638
|
+
const track = (sessionID) => {
|
|
639
|
+
sessions.add(sessionID);
|
|
640
|
+
};
|
|
641
|
+
/** Private correlation of a dispatched request to its session/kind/model. */
|
|
642
|
+
const attributions = new WeakMap();
|
|
643
|
+
// Latest successful host preparation, scoped to session/kind/model. This
|
|
644
|
+
// proves hook coverage, NOT that an opaque final body has been inspected.
|
|
645
|
+
const protectedContexts = new Map();
|
|
646
|
+
const notices = new Set();
|
|
647
|
+
const noticeOnce = (message) => {
|
|
648
|
+
if (notices.has(message))
|
|
649
|
+
return;
|
|
650
|
+
notices.add(message);
|
|
651
|
+
warnDegradation(message);
|
|
652
|
+
};
|
|
653
|
+
const contextScope = (event, kind = event.kind) => JSON.stringify([event.sessionID, kind]);
|
|
654
|
+
const contextModel = (event) => {
|
|
655
|
+
if (!isRecordLike(event.model) || typeof event.model.providerID !== "string" || !event.model.providerID || typeof event.model.id !== "string" || !event.model.id)
|
|
656
|
+
return undefined;
|
|
657
|
+
const key = JSON.stringify([event.model.providerID, event.model.id]);
|
|
658
|
+
return Buffer.byteLength(key, "utf8") <= 4096 ? key : undefined;
|
|
659
|
+
};
|
|
660
|
+
const hasProtectedContext = (event) => {
|
|
661
|
+
const model = contextModel(event);
|
|
662
|
+
return model !== undefined && protectedContexts.get(contextScope(event)) === model;
|
|
663
|
+
};
|
|
664
|
+
// ─── W2/B4 + R-round persistence wiring (all no-ops when store is null) ───
|
|
665
|
+
let store = null;
|
|
666
|
+
/** Bounded (F4.4): insertion-ordered attempt log, evicting the oldest. */
|
|
667
|
+
const seedAttempts = new Map();
|
|
668
|
+
const MAX_SEED_ATTEMPTS = 1024;
|
|
669
|
+
const persistedEntries = new Map();
|
|
670
|
+
/** R-round F3.2: the row version observed at seed/write time (CAS token).
|
|
671
|
+
* Absent looks encode -(generation+1); row looks carry the version. */
|
|
672
|
+
const persistVersions = new Map();
|
|
673
|
+
/** F4.2: sessions whose seed was rejected must never overwrite their
|
|
674
|
+
* previously persisted (good) snapshot with a partial re-protect. */
|
|
675
|
+
const noPersist = new Set();
|
|
676
|
+
/** R3-F7: bounded per-session bookkeeping. Live sessions (bounded by
|
|
677
|
+
* MAX_TRACKED_SESSIONS) always keep their state; only departed ids go. */
|
|
678
|
+
const MAX_BOOKKEEPING = 1024;
|
|
679
|
+
const evictStaleBookkeeping = (map) => {
|
|
680
|
+
if (map.size <= MAX_BOOKKEEPING)
|
|
681
|
+
return;
|
|
682
|
+
for (const key of map.keys()) {
|
|
683
|
+
if (map.size <= MAX_BOOKKEEPING)
|
|
684
|
+
break;
|
|
685
|
+
if (!sessions.has(key))
|
|
686
|
+
map.delete(key);
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
if (persistence !== undefined) {
|
|
690
|
+
// Test/CI seam: an injected provider skips the OS keychain ladder so
|
|
691
|
+
// integration tests never touch the developer's real keychain (F6.1);
|
|
692
|
+
// explicit null forces the memory-only bottom of the ladder.
|
|
693
|
+
const keyProvider = persistence.keyProvider !== undefined
|
|
694
|
+
? persistence.keyProvider
|
|
695
|
+
: resolveMappingKey({
|
|
696
|
+
keyFile: persistence.keyFile,
|
|
697
|
+
keyfilePath: persistence.keyfilePath,
|
|
698
|
+
warn: warnDegradation,
|
|
699
|
+
});
|
|
700
|
+
if (keyProvider !== null) {
|
|
701
|
+
try {
|
|
702
|
+
store = openMappingStore({
|
|
703
|
+
path: persistence.path,
|
|
704
|
+
keyProvider,
|
|
705
|
+
ttlDays: persistence.ttlDays,
|
|
706
|
+
});
|
|
707
|
+
console.info(`[leakshield] persistence: active; key=${keyProvider.source ?? "injected"}; ttl=${persistence.ttlDays}d; cleanup=on-store-open`);
|
|
708
|
+
}
|
|
709
|
+
catch (error) {
|
|
710
|
+
store = null;
|
|
711
|
+
warnDegradation(error instanceof MappingKeyMismatchError
|
|
712
|
+
? "persistence: resolved key does not match this store's pinned key identity; operating memory-only (forget --all resets)"
|
|
713
|
+
: "persistence: mapping store unavailable, operating memory-only");
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
else {
|
|
717
|
+
warnDegradation("persistence: no key provider, operating memory-only");
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
/** R2-8: degradation must close the handle before dropping the reference. */
|
|
721
|
+
const disableStore = (message) => {
|
|
722
|
+
if (store !== null) {
|
|
723
|
+
try {
|
|
724
|
+
store.close();
|
|
725
|
+
}
|
|
726
|
+
catch {
|
|
727
|
+
// Already-broken handle: nothing further to release.
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
store = null;
|
|
731
|
+
warnDegradation(message);
|
|
732
|
+
};
|
|
733
|
+
/**
|
|
734
|
+
* Lazy hydration on a session's first touch: seed the core from the store
|
|
735
|
+
* before any protect/restore so replayed history and tool calls resolve.
|
|
736
|
+
* A rejected seed (static reason only) degrades to memory-only for that
|
|
737
|
+
* session — never blocks the conversation. A store that THROWS mid-flight
|
|
738
|
+
* (F4.1) disables persistence for this process; the conversation continues
|
|
739
|
+
* memory-only.
|
|
740
|
+
*/
|
|
741
|
+
const ensureSeeded = (sessionID) => {
|
|
742
|
+
// R2-9: a session already LIVE in this process's registry needs no seed —
|
|
743
|
+
// and re-seeding would fail invalid_session and mis-fire noPersist. This
|
|
744
|
+
// also makes FIFO eviction of an active session's attempt harmless: its
|
|
745
|
+
// CAS state (persistVersions) is retained either way.
|
|
746
|
+
if (store === null || seedAttempts.has(sessionID) || pseudonymizer.hasSession(sessionID))
|
|
747
|
+
return;
|
|
748
|
+
if (seedAttempts.size >= MAX_SEED_ATTEMPTS) {
|
|
749
|
+
const oldest = seedAttempts.keys().next().value;
|
|
750
|
+
if (oldest !== undefined)
|
|
751
|
+
seedAttempts.delete(oldest);
|
|
752
|
+
}
|
|
753
|
+
seedAttempts.set(sessionID, true);
|
|
754
|
+
let seed;
|
|
755
|
+
try {
|
|
756
|
+
seed = store.loadSession(sessionID);
|
|
757
|
+
}
|
|
758
|
+
catch (error) {
|
|
759
|
+
disableStore("persistence: store read failed; disabled for this process, memory-only");
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (seed === null) {
|
|
763
|
+
// R3-F2: the absent look carries the session's tombstone generation —
|
|
764
|
+
// a delete that happens since (create→forget, sweep, eviction) must
|
|
765
|
+
// make this handle's insert a conflict, never a resurrection.
|
|
766
|
+
try {
|
|
767
|
+
persistVersions.set(sessionID, -(store.absentGeneration(sessionID) + 1));
|
|
768
|
+
}
|
|
769
|
+
catch {
|
|
770
|
+
// Same contract as loadSession above: a store that fails mid-flight
|
|
771
|
+
// disables persistence for the process, never the conversation.
|
|
772
|
+
disableStore("persistence: store read failed; disabled for this process, memory-only");
|
|
773
|
+
}
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
if (seed.entries.length === 0) {
|
|
777
|
+
// Row exists (possibly with undecryptable entries): remember ITS
|
|
778
|
+
// version so write-behind CASes against the real lineage.
|
|
779
|
+
persistVersions.set(sessionID, seed.version);
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const result = pseudonymizer.seedSession(sessionID, {
|
|
783
|
+
epoch: seed.epoch,
|
|
784
|
+
entries: seed.entries,
|
|
785
|
+
});
|
|
786
|
+
if (!result.ok) {
|
|
787
|
+
noPersist.add(sessionID);
|
|
788
|
+
evictStaleBookkeeping(noPersist);
|
|
789
|
+
warnDegradation(`persistence: session seed rejected (${result.reason}); memory-only for this session`);
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
// F4.3: a session hydrated only via tool:execute.before also holds core
|
|
793
|
+
// state — retain it for disposal like any tracked session.
|
|
794
|
+
sessions.add(sessionID);
|
|
795
|
+
persistedEntries.set(sessionID, seed.entries.length);
|
|
796
|
+
persistVersions.set(sessionID, seed.version);
|
|
797
|
+
};
|
|
798
|
+
/** Write-behind after successful protects; skips no-op writes. */
|
|
799
|
+
const persistIfChanged = (sessionID) => {
|
|
800
|
+
if (store === null || noPersist.has(sessionID))
|
|
801
|
+
return;
|
|
802
|
+
const snapshot = pseudonymizer.exportSession(sessionID);
|
|
803
|
+
if (snapshot === null)
|
|
804
|
+
return;
|
|
805
|
+
if (persistedEntries.get(sessionID) === snapshot.entries.length)
|
|
806
|
+
return;
|
|
807
|
+
try {
|
|
808
|
+
const storedVersion = store.putSession({
|
|
809
|
+
sessionId: sessionID,
|
|
810
|
+
epoch: snapshot.epoch,
|
|
811
|
+
entries: snapshot.entries.map((entry) => ({ ...entry })),
|
|
812
|
+
}, persistVersions.get(sessionID) ?? 0);
|
|
813
|
+
persistedEntries.set(sessionID, snapshot.entries.length);
|
|
814
|
+
persistVersions.set(sessionID, storedVersion);
|
|
815
|
+
evictStaleBookkeeping(persistedEntries);
|
|
816
|
+
evictStaleBookkeeping(persistVersions);
|
|
817
|
+
evictStaleBookkeeping(noPersist);
|
|
818
|
+
}
|
|
819
|
+
catch (error) {
|
|
820
|
+
if (error instanceof MappingStoreConflictError) {
|
|
821
|
+
// Another process holds a newer snapshot for this session; ours is
|
|
822
|
+
// stale. Never overwrite — keep serving in-memory mappings and stop
|
|
823
|
+
// write-behind for the session (the next process seeds the newer set).
|
|
824
|
+
noPersist.add(sessionID);
|
|
825
|
+
warnDegradation("persistence: concurrent writer holds a newer snapshot for this session; write-behind stopped");
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
if (error instanceof MappingForgottenError) {
|
|
829
|
+
// Explicit erasure raced this handle: persisting now would resurrect
|
|
830
|
+
// forgotten data. Close and disable the store for this process (the
|
|
831
|
+
// in-memory copy remains until this process exits — documented RAM
|
|
832
|
+
// residue).
|
|
833
|
+
disableStore("persistence: mappings were forgotten while this process was running; persistence disabled (in-memory copy remains until restart)");
|
|
834
|
+
return;
|
|
835
|
+
}
|
|
836
|
+
if (error instanceof MappingSnapshotTooLargeError) {
|
|
837
|
+
// R2-10: this single session exceeds the store-wide cap; evicting
|
|
838
|
+
// others can never fix it. Stop trying — memory-only persistence.
|
|
839
|
+
noPersist.add(sessionID);
|
|
840
|
+
warnDegradation(`persistence: ${error.message}`);
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
warnDegradation("persistence: write-behind failed; in-session mappings remain valid");
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
const kindOf = (event) => typeof event.kind === "string" ? event.kind : "";
|
|
847
|
+
/**
|
|
848
|
+
* Structural identifiers are preserved verbatim, so they are judged, not
|
|
849
|
+
* masked. P1 (2026-10-06b): marker-shaped content is never refused per se —
|
|
850
|
+
* registered-marker interiors are exempt from scanning, unregistered
|
|
851
|
+
* payloads scan as ordinary text. Clean → preserved literal with a
|
|
852
|
+
* content-free WARN. Any finding → refusal: the position cannot be masked
|
|
853
|
+
* or renamed without breaking the protocol (genuine leak-risk refusal).
|
|
854
|
+
*/
|
|
855
|
+
const detectSensitive = (text) => !pseudonymizer.isTextSafe(text);
|
|
856
|
+
const assertStructuralSafe = (text, sessionID) => {
|
|
857
|
+
if (containsTokenPrefix(text)) {
|
|
858
|
+
if (!pseudonymizer.isStructuralIdentifierSafe(sessionID, text)) {
|
|
859
|
+
throw new Error(STRUCTURAL_SENSITIVE_ERROR);
|
|
860
|
+
}
|
|
861
|
+
warnDegradation("structural identifier preserved with a literal placeholder");
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (detectSensitive(text))
|
|
865
|
+
throw new Error(STRUCTURAL_SENSITIVE_ERROR);
|
|
866
|
+
};
|
|
867
|
+
/** Rejects a snapshot whose numeric values scan as sensitive (never masked). */
|
|
868
|
+
const assertNumbersSafe = (value) => {
|
|
869
|
+
if (typeof value === "number") {
|
|
870
|
+
if (detectSensitive(String(value)))
|
|
871
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
if (value === null || typeof value !== "object")
|
|
875
|
+
return;
|
|
876
|
+
if (Array.isArray(value)) {
|
|
877
|
+
for (const item of value)
|
|
878
|
+
assertNumbersSafe(item);
|
|
879
|
+
return;
|
|
880
|
+
}
|
|
881
|
+
for (const item of Object.values(value))
|
|
882
|
+
assertNumbersSafe(item);
|
|
883
|
+
};
|
|
884
|
+
/**
|
|
885
|
+
* Field-aware transport exemption for the opt-in URL rule. Transport
|
|
886
|
+
* positions (request URL, query values, header values) are infrastructure:
|
|
887
|
+
* masking or refusing an endpoint URL would break every request once the
|
|
888
|
+
* URL rule is enabled. Neutralizing URL matches BEFORE the strict checks
|
|
889
|
+
* removes both the direct findings and the percent-decoding hazard windows
|
|
890
|
+
* that would otherwise re-surface the URL text — while non-URL secrets
|
|
891
|
+
* (e.g. an API key encoded in a query value outside a URL match) still
|
|
892
|
+
* refuse. Only active when the URL rule itself is enabled; body-content
|
|
893
|
+
* URLs are unaffected (they are masked like any other finding).
|
|
894
|
+
*/
|
|
895
|
+
const urlRule = BUILTIN_RULES.find((rule) => rule.id === "url");
|
|
896
|
+
const urlRuleId = urlRule?.id;
|
|
897
|
+
const urlRuleOptIn = urlRule?.optIn === true;
|
|
898
|
+
const urlRuleActive = urlRuleId !== undefined &&
|
|
899
|
+
(urlRuleId in (config.settings.rule_overrides ?? {})
|
|
900
|
+
? config.settings.rule_overrides?.[urlRuleId] === true
|
|
901
|
+
: !urlRuleOptIn);
|
|
902
|
+
const neutralizeTransportUrls = (text) => {
|
|
903
|
+
if (!urlRuleActive || urlRule === undefined)
|
|
904
|
+
return text;
|
|
905
|
+
// Fresh RegExp per call: the shared rule pattern is stateful (/g).
|
|
906
|
+
return text.replace(new RegExp(urlRule.pattern.source, urlRule.pattern.flags), "url");
|
|
907
|
+
};
|
|
908
|
+
const transportService = {
|
|
909
|
+
protectJsonForModel: (sid, value) => pseudonymizer.protectJsonForModel(sid, value),
|
|
910
|
+
restoreText: (sid, text) => pseudonymizer.restoreText(sid, text),
|
|
911
|
+
restoreTextForDisplay: (sid, text) => pseudonymizer.restoreTextForDisplay(sid, text),
|
|
912
|
+
detectSensitive,
|
|
913
|
+
isStructuralIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, text),
|
|
914
|
+
transportDetectSensitive: (text) => detectSensitive(neutralizeTransportUrls(text)),
|
|
915
|
+
isTransportIdentifierSafe: (sid, text) => pseudonymizer.isStructuralIdentifierSafe(sid, neutralizeTransportUrls(text)),
|
|
916
|
+
attachmentsPolicy,
|
|
917
|
+
};
|
|
918
|
+
const webSocket = createResponsesWebSocketAdapter(transportService, wireProtection, hasProtectedContext);
|
|
919
|
+
/** Release only an explicitly deleted session; persisted rows keep their TTL. */
|
|
920
|
+
const releaseSession = (sessionID) => {
|
|
921
|
+
if (!sessions.delete(sessionID))
|
|
922
|
+
return;
|
|
923
|
+
pseudonymizer.clearSession(sessionID);
|
|
924
|
+
webSocket.clearSession(sessionID);
|
|
925
|
+
for (const kind of ["primary", "compaction", "generate", "title"]) {
|
|
926
|
+
protectedContexts.delete(JSON.stringify([sessionID, kind]));
|
|
927
|
+
}
|
|
928
|
+
seedAttempts.delete(sessionID);
|
|
929
|
+
persistedEntries.delete(sessionID);
|
|
930
|
+
persistVersions.delete(sessionID);
|
|
931
|
+
noPersist.delete(sessionID);
|
|
932
|
+
};
|
|
933
|
+
const aiSDK = createAISDKTransportAdmission(wireProtection);
|
|
934
|
+
/**
|
|
935
|
+
* Publishes protected string leaves back into the live event in place. The
|
|
936
|
+
* host keeps its own (possibly class-instance) option/message objects, so we
|
|
937
|
+
* must mutate them rather than replace them with plain projections.
|
|
938
|
+
*/
|
|
939
|
+
const publishInPlace = (original, protectedValue) => {
|
|
940
|
+
if (original === null || typeof original !== "object")
|
|
941
|
+
return;
|
|
942
|
+
if (Array.isArray(original)) {
|
|
943
|
+
if (!Array.isArray(protectedValue))
|
|
944
|
+
return;
|
|
945
|
+
for (let index = 0; index < original.length; index++) {
|
|
946
|
+
const current = original[index];
|
|
947
|
+
const next = protectedValue[index];
|
|
948
|
+
if (typeof current === "string") {
|
|
949
|
+
if (typeof next === "string" && next !== current)
|
|
950
|
+
original[index] = next;
|
|
951
|
+
}
|
|
952
|
+
else {
|
|
953
|
+
publishInPlace(current, next);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
if (protectedValue === null || typeof protectedValue !== "object")
|
|
959
|
+
return;
|
|
960
|
+
const record = original;
|
|
961
|
+
const protectedRecord = protectedValue;
|
|
962
|
+
for (const key of Object.keys(protectedRecord)) {
|
|
963
|
+
if (!(key in record))
|
|
964
|
+
continue;
|
|
965
|
+
const current = record[key];
|
|
966
|
+
const next = protectedRecord[key];
|
|
967
|
+
if (typeof current === "string") {
|
|
968
|
+
if (typeof next === "string" && next !== current)
|
|
969
|
+
record[key] = next;
|
|
970
|
+
}
|
|
971
|
+
else {
|
|
972
|
+
publishInPlace(current, next);
|
|
973
|
+
}
|
|
974
|
+
}
|
|
975
|
+
};
|
|
976
|
+
/** True when two JSON values have identical key/array structure. */
|
|
977
|
+
const sameStructure = (a, b) => {
|
|
978
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
979
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
980
|
+
return false;
|
|
981
|
+
return a.every((item, index) => sameStructure(item, b[index]));
|
|
982
|
+
}
|
|
983
|
+
const aObject = a !== null && typeof a === "object";
|
|
984
|
+
const bObject = b !== null && typeof b === "object";
|
|
985
|
+
if (aObject !== bObject)
|
|
986
|
+
return false;
|
|
987
|
+
if (!aObject)
|
|
988
|
+
return true;
|
|
989
|
+
const aRecord = a;
|
|
990
|
+
const bRecord = b;
|
|
991
|
+
const aKeys = Object.keys(aRecord);
|
|
992
|
+
if (aKeys.length !== Object.keys(bRecord).length)
|
|
993
|
+
return false;
|
|
994
|
+
for (const key of aKeys) {
|
|
995
|
+
if (!(key in bRecord) || !sameStructure(aRecord[key], bRecord[key]))
|
|
996
|
+
return false;
|
|
997
|
+
}
|
|
998
|
+
return true;
|
|
999
|
+
};
|
|
1000
|
+
const assertWritableDataProperty = (record, key) => {
|
|
1001
|
+
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
1002
|
+
if (descriptor === undefined || !("value" in descriptor) || descriptor.writable !== true) {
|
|
1003
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1004
|
+
}
|
|
1005
|
+
};
|
|
1006
|
+
const assertPublishable = (value, seen) => {
|
|
1007
|
+
if (value === null || typeof value !== "object")
|
|
1008
|
+
return;
|
|
1009
|
+
if (types.isProxy(value))
|
|
1010
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1011
|
+
if (seen.has(value))
|
|
1012
|
+
return;
|
|
1013
|
+
seen.add(value);
|
|
1014
|
+
if (Object.isFrozen(value))
|
|
1015
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1016
|
+
for (let prototype = value; prototype !== null && prototype !== Object.prototype; prototype = Object.getPrototypeOf(prototype)) {
|
|
1017
|
+
if (Object.getOwnPropertyDescriptor(prototype, "toJSON") !== undefined) {
|
|
1018
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
if (Array.isArray(value)) {
|
|
1022
|
+
for (const key of Object.keys(value)) {
|
|
1023
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
1024
|
+
if (descriptor === undefined || !("value" in descriptor))
|
|
1025
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1026
|
+
const item = descriptor.value;
|
|
1027
|
+
if (typeof item === "string" && descriptor.writable !== true) {
|
|
1028
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1029
|
+
}
|
|
1030
|
+
assertPublishable(item, seen);
|
|
1031
|
+
}
|
|
1032
|
+
return;
|
|
1033
|
+
}
|
|
1034
|
+
const record = value;
|
|
1035
|
+
for (const key of Object.keys(record)) {
|
|
1036
|
+
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
1037
|
+
if (descriptor === undefined || !("value" in descriptor))
|
|
1038
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1039
|
+
const item = descriptor.value;
|
|
1040
|
+
if (typeof item === "string" && descriptor.writable !== true) {
|
|
1041
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1042
|
+
}
|
|
1043
|
+
assertPublishable(item, seen);
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
const protectRequestKind = (event, kind) => {
|
|
1047
|
+
const sessionID = requireSessionID(event);
|
|
1048
|
+
// Host preparation events omit kind; the registered hook is the authority.
|
|
1049
|
+
// Do not mutate the event or infer a primary scope from a title/generate.
|
|
1050
|
+
protectedContexts.delete(contextScope(event, kind));
|
|
1051
|
+
if (!wireProtection && contextModel(event) !== undefined) {
|
|
1052
|
+
webSocket.resetRequest({ sessionID, kind, model: event.model });
|
|
1053
|
+
}
|
|
1054
|
+
assertTrackable(sessionID);
|
|
1055
|
+
ensureSeeded(sessionID);
|
|
1056
|
+
if (types.isProxy(event))
|
|
1057
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1058
|
+
for (const field of ["system", "messages", "options", "tools"]) {
|
|
1059
|
+
if (field in event) {
|
|
1060
|
+
assertWritableDataProperty(event, field);
|
|
1061
|
+
assertPublishable(event[field], new WeakSet());
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
const allowFound = attachmentsPolicy === "allow" &&
|
|
1065
|
+
["system", "messages", "options", "tools"].some((field) => hasAttachmentPart(event[field], new WeakSet()));
|
|
1066
|
+
applyAttachmentPolicy(event.system, new WeakSet(), attachmentsPolicy);
|
|
1067
|
+
applyAttachmentPolicy(event.messages, new WeakSet(), attachmentsPolicy);
|
|
1068
|
+
applyAttachmentPolicy(event.options, new WeakSet(), attachmentsPolicy);
|
|
1069
|
+
applyAttachmentPolicy(event.tools, new WeakSet(), attachmentsPolicy);
|
|
1070
|
+
if (attachmentsPolicy === "allow")
|
|
1071
|
+
appendAllowNotice(event, allowFound);
|
|
1072
|
+
const snapshot = {
|
|
1073
|
+
system: event.system,
|
|
1074
|
+
messages: event.messages,
|
|
1075
|
+
options: event.options,
|
|
1076
|
+
};
|
|
1077
|
+
if (event.tools !== undefined)
|
|
1078
|
+
snapshot.tools = event.tools;
|
|
1079
|
+
// Project to the exact plain JSON the host will serialize (real v2 events
|
|
1080
|
+
// are class instances that strict-JSON protection refuses), then protect in
|
|
1081
|
+
// one atomic transaction and publish masked leaves back in place.
|
|
1082
|
+
let plain;
|
|
1083
|
+
try {
|
|
1084
|
+
plain = JSON.parse(JSON.stringify(snapshot));
|
|
1085
|
+
}
|
|
1086
|
+
catch {
|
|
1087
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1088
|
+
}
|
|
1089
|
+
if (!isRecordLike(plain))
|
|
1090
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1091
|
+
// Structural identifiers must be preserved verbatim. Verify them BEFORE
|
|
1092
|
+
// masking: a sensitive one (sensitive-looking id/name) refuses the whole
|
|
1093
|
+
// request rather than being silently renamed, while a placeholder-shaped
|
|
1094
|
+
// one is judged session-aware — clean markers are preserved literal with
|
|
1095
|
+
// a WARN (P1, 2026-10-06b). Numeric values are never transformed by
|
|
1096
|
+
// masking, so a sensitive one refuses.
|
|
1097
|
+
const structuralBefore = collectStructuralStrings(plain);
|
|
1098
|
+
for (const identifier of structuralBefore)
|
|
1099
|
+
assertStructuralSafe(identifier, sessionID);
|
|
1100
|
+
assertNumbersSafe(plain);
|
|
1101
|
+
// "allow" means unscanned: attachment payloads are substituted with opaque
|
|
1102
|
+
// sentinels around the masking transaction (the same mechanism the wire
|
|
1103
|
+
// remaskers use) and restored afterwards, so a real image's base64 is
|
|
1104
|
+
// never token-mangled into an unparseable payload and never trips
|
|
1105
|
+
// encoded-content detection.
|
|
1106
|
+
const protectTree = (input) => {
|
|
1107
|
+
const masked = pseudonymizer.protectJsonForModel(sessionID, input);
|
|
1108
|
+
if (!masked.ok)
|
|
1109
|
+
throw new Error(`${PROTECT_FAILED_ERROR} [stage=prepare.mask reason=${masked.reason}]`);
|
|
1110
|
+
if (!isRecordLike(masked.value))
|
|
1111
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1112
|
+
return masked.value;
|
|
1113
|
+
};
|
|
1114
|
+
// Provider-authenticated reasoning/compaction state is substituted the
|
|
1115
|
+
// same way, so a detector false positive cannot corrupt its bytes.
|
|
1116
|
+
const value = withOpaqueProviderState(plain, (input) => withOpaqueAttachments(attachmentsPolicy, input, protectTree));
|
|
1117
|
+
// Defense in depth: no structural identifier may have changed.
|
|
1118
|
+
const structuralAfter = collectStructuralStrings(value);
|
|
1119
|
+
if (structuralAfter.length !== structuralBefore.length ||
|
|
1120
|
+
structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
|
|
1121
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1122
|
+
}
|
|
1123
|
+
// Publish only after the whole transaction succeeded. When masking renamed
|
|
1124
|
+
// an object key the live container cannot be mutated in place, so that
|
|
1125
|
+
// field is replaced with the protected projection; otherwise the live
|
|
1126
|
+
// (possibly class-instance) container is mutated leaf-by-leaf.
|
|
1127
|
+
try {
|
|
1128
|
+
for (const field of ["system", "messages", "options", "tools"]) {
|
|
1129
|
+
if (!(field in snapshot))
|
|
1130
|
+
continue;
|
|
1131
|
+
const before = plain[field];
|
|
1132
|
+
const after = value[field];
|
|
1133
|
+
if (sameStructure(before, after))
|
|
1134
|
+
publishInPlace(event[field], after);
|
|
1135
|
+
else
|
|
1136
|
+
event[field] = after;
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
catch {
|
|
1140
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1141
|
+
}
|
|
1142
|
+
track(sessionID);
|
|
1143
|
+
persistIfChanged(sessionID);
|
|
1144
|
+
const model = contextModel(event);
|
|
1145
|
+
if (model !== undefined) {
|
|
1146
|
+
protectedContexts.set(contextScope(event, kind), model);
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
const onHttpRequest = async (event) => {
|
|
1150
|
+
const sessionID = requireSessionID(event);
|
|
1151
|
+
assertTrackable(sessionID);
|
|
1152
|
+
ensureSeeded(sessionID);
|
|
1153
|
+
if (types.isProxy(event))
|
|
1154
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1155
|
+
assertWritableDataProperty(event, "request");
|
|
1156
|
+
if (!(event.request instanceof Request))
|
|
1157
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1158
|
+
// HTTP fallback must not leave a previous WS request eligible to receive.
|
|
1159
|
+
if (event.model !== undefined)
|
|
1160
|
+
webSocket.resetRequest(event);
|
|
1161
|
+
// Registered only with wire protection; hook-only has no request gate.
|
|
1162
|
+
const request = await remaskModelRequest(transportService, sessionID, event.request);
|
|
1163
|
+
event.request = request;
|
|
1164
|
+
attributions.set(request, { sessionID, kind: kindOf(event), model: contextModel(event) });
|
|
1165
|
+
track(sessionID);
|
|
1166
|
+
persistIfChanged(sessionID);
|
|
1167
|
+
};
|
|
1168
|
+
const onHttpResponse = async (event) => {
|
|
1169
|
+
try {
|
|
1170
|
+
const sessionID = requireSessionID(event);
|
|
1171
|
+
assertTrackable(sessionID);
|
|
1172
|
+
if (!sessions.has(sessionID))
|
|
1173
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
1174
|
+
if (!(event.request instanceof Request) || !(event.response instanceof Response))
|
|
1175
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
1176
|
+
if (wireProtection) {
|
|
1177
|
+
const attribution = attributions.get(event.request);
|
|
1178
|
+
if (attribution === undefined || attribution.sessionID !== sessionID || attribution.kind !== kindOf(event) || attribution.model !== contextModel(event)) {
|
|
1179
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
else if (!hasProtectedContext(event)) {
|
|
1183
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
1184
|
+
}
|
|
1185
|
+
ensureSeeded(sessionID);
|
|
1186
|
+
// Hook-only routes have no response adapter. Do not guess their dialect.
|
|
1187
|
+
if (classifyModelRoute(event.request.url) === null)
|
|
1188
|
+
return;
|
|
1189
|
+
event.response = await restoreModelResponse(transportService, sessionID, event.request, event.response);
|
|
1190
|
+
track(sessionID);
|
|
1191
|
+
}
|
|
1192
|
+
catch {
|
|
1193
|
+
// Restoration is optional on ingress. Keep the original one-shot body;
|
|
1194
|
+
// upstream failures will still surface when the host reads that body.
|
|
1195
|
+
noticeOnce("HTTP reply kept original after attribution or restoration failure; placeholders may remain literal");
|
|
1196
|
+
}
|
|
1197
|
+
};
|
|
1198
|
+
/**
|
|
1199
|
+
* Restores registered tokens in a tool input leaf. For shell-like tools the
|
|
1200
|
+
* token must occupy a complete argument word AND its original must be safe
|
|
1201
|
+
* in that word's existing quote context. Command/assignment/redirect tokens,
|
|
1202
|
+
* expansion, quote-breaking and option injection refuse the whole call.
|
|
1203
|
+
*
|
|
1204
|
+
* P1 (2026-10-06b) limited best-effort: when `allowDegraded` is set (the
|
|
1205
|
+
* call is a proven read-only tool, not shell-like) a mapping failure
|
|
1206
|
+
* (unknown/malformed marker) keeps the leaf literal and records a
|
|
1207
|
+
* degradation instead of refusing — the placeholder reads as a literal
|
|
1208
|
+
* that matches nothing, the tool's own output is the in-band signal, and a
|
|
1209
|
+
* content-free WARN line is logged. Every other failure kind still refuses.
|
|
1210
|
+
*/
|
|
1211
|
+
const restoreLeaf = (sessionID, text, shellLike, allowDegraded, degraded) => {
|
|
1212
|
+
if (!containsTokenPrefix(text))
|
|
1213
|
+
return text;
|
|
1214
|
+
if (shellLike) {
|
|
1215
|
+
const argumentsOnly = parseSupportedShellArguments(text);
|
|
1216
|
+
if (argumentsOnly === null)
|
|
1217
|
+
throw new Error(TOOL_SHELL_CONTEXT_ERROR);
|
|
1218
|
+
for (const match of text.matchAll(TOKEN_SCAN)) {
|
|
1219
|
+
const end = match.index + match[0].length;
|
|
1220
|
+
const argument = argumentsOnly.find((word) => word.value === match[0] && word.start <= match.index && word.end >= end);
|
|
1221
|
+
if (argument === undefined)
|
|
1222
|
+
throw new Error(TOOL_SHELL_CONTEXT_ERROR);
|
|
1223
|
+
const restoredToken = transportService.restoreText(sessionID, match[0]);
|
|
1224
|
+
if (!restoredToken.ok)
|
|
1225
|
+
throw new Error(toolRestoreError(restoredToken.reason));
|
|
1226
|
+
if (!isShellSafeOriginal(restoredToken.text, argument.quote))
|
|
1227
|
+
throw new Error(TOOL_SHELL_CONTEXT_ERROR);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
const restored = transportService.restoreText(sessionID, text);
|
|
1231
|
+
if (restored.ok)
|
|
1232
|
+
return restored.text;
|
|
1233
|
+
if (allowDegraded &&
|
|
1234
|
+
(restored.reason === "unknown_token" || restored.reason === "malformed_token")) {
|
|
1235
|
+
degraded.count += 1;
|
|
1236
|
+
return text;
|
|
1237
|
+
}
|
|
1238
|
+
throw new Error(toolRestoreError(restored.reason));
|
|
1239
|
+
};
|
|
1240
|
+
/**
|
|
1241
|
+
* Planning pass: computes every replacement WITHOUT mutating, and rejects
|
|
1242
|
+
* frozen/unwritable containers or token-bearing keys. Nothing is written
|
|
1243
|
+
* until the whole plan is known to be applicable.
|
|
1244
|
+
*/
|
|
1245
|
+
const planToolInput = (value, sessionID, shellLike, seen, out, allowDegraded, degraded) => {
|
|
1246
|
+
if (value === null || typeof value !== "object")
|
|
1247
|
+
return;
|
|
1248
|
+
if (types.isProxy(value) || seen.has(value) || Object.isFrozen(value)) {
|
|
1249
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1250
|
+
}
|
|
1251
|
+
seen.add(value);
|
|
1252
|
+
if (Object.getOwnPropertySymbols(value).length > 0)
|
|
1253
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1254
|
+
if (Array.isArray(value)) {
|
|
1255
|
+
for (const key of Object.keys(value)) {
|
|
1256
|
+
if (!/^(0|[1-9]\d*)$/.test(key))
|
|
1257
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1258
|
+
}
|
|
1259
|
+
for (let index = 0; index < value.length; index++) {
|
|
1260
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, index);
|
|
1261
|
+
if (descriptor === undefined)
|
|
1262
|
+
continue;
|
|
1263
|
+
if (!("value" in descriptor))
|
|
1264
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1265
|
+
const item = descriptor.value;
|
|
1266
|
+
if (typeof item === "string") {
|
|
1267
|
+
const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
|
|
1268
|
+
if (next !== item)
|
|
1269
|
+
out.push({ container: value, key: index, value: next });
|
|
1270
|
+
}
|
|
1271
|
+
else {
|
|
1272
|
+
planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
const prototype = Object.getPrototypeOf(value);
|
|
1278
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
1279
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1280
|
+
const record = value;
|
|
1281
|
+
for (const key of Object.keys(record)) {
|
|
1282
|
+
if (containsTokenPrefix(key))
|
|
1283
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1284
|
+
const descriptor = Object.getOwnPropertyDescriptor(record, key);
|
|
1285
|
+
if (descriptor === undefined || !("value" in descriptor))
|
|
1286
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1287
|
+
const item = descriptor.value;
|
|
1288
|
+
if (typeof item === "string") {
|
|
1289
|
+
const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
|
|
1290
|
+
if (next !== item)
|
|
1291
|
+
out.push({ container: record, key, value: next });
|
|
1292
|
+
}
|
|
1293
|
+
else {
|
|
1294
|
+
planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
};
|
|
1298
|
+
const assertToolPlanWritable = (plan) => {
|
|
1299
|
+
for (const assignment of plan) {
|
|
1300
|
+
const descriptor = Object.getOwnPropertyDescriptor(assignment.container, assignment.key);
|
|
1301
|
+
if (descriptor === undefined || !("value" in descriptor) || descriptor.writable !== true) {
|
|
1302
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
};
|
|
1306
|
+
const applyToolPlan = (plan) => {
|
|
1307
|
+
for (const assignment of plan) {
|
|
1308
|
+
if (Array.isArray(assignment.container)) {
|
|
1309
|
+
assignment.container[assignment.key] = assignment.value;
|
|
1310
|
+
}
|
|
1311
|
+
else {
|
|
1312
|
+
assignment.container[assignment.key] = assignment.value;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
};
|
|
1316
|
+
const onToolBefore = (event) => {
|
|
1317
|
+
if (!inputCarriesToken(event.input, new WeakSet()))
|
|
1318
|
+
return;
|
|
1319
|
+
const sessionID = requireSessionID(event);
|
|
1320
|
+
ensureSeeded(sessionID);
|
|
1321
|
+
const tool = typeof event.tool === "string" ? event.tool.toLowerCase() : "";
|
|
1322
|
+
const shellLike = !NON_SHELL_TOOLS.has(tool) ||
|
|
1323
|
+
(isRecordLike(event.input) && typeof event.input.command === "string");
|
|
1324
|
+
// P1 (2026-10-06b): only proven read-only, non-shell tools may degrade to
|
|
1325
|
+
// literal placeholders; writes/deletes/outbound/unknown tools keep
|
|
1326
|
+
// refusing the affected invocation when restoration is incomplete.
|
|
1327
|
+
const allowDegraded = READ_ONLY_TOOLS.has(tool) && !shellLike;
|
|
1328
|
+
const degraded = { count: 0 };
|
|
1329
|
+
if (typeof event.input === "string") {
|
|
1330
|
+
const descriptor = Object.getOwnPropertyDescriptor(event, "input");
|
|
1331
|
+
if (descriptor === undefined || !("value" in descriptor) || descriptor.writable !== true) {
|
|
1332
|
+
throw new Error(TOOL_INPUT_SHAPE_ERROR);
|
|
1333
|
+
}
|
|
1334
|
+
event.input = restoreLeaf(sessionID, event.input, shellLike, allowDegraded, degraded);
|
|
1335
|
+
}
|
|
1336
|
+
else {
|
|
1337
|
+
const plan = [];
|
|
1338
|
+
planToolInput(event.input, sessionID, shellLike, new WeakSet(), plan, allowDegraded, degraded);
|
|
1339
|
+
assertToolPlanWritable(plan);
|
|
1340
|
+
applyToolPlan(plan);
|
|
1341
|
+
}
|
|
1342
|
+
if (degraded.count > 0) {
|
|
1343
|
+
warnDegradation(`read-only tool call kept ${degraded.count} literal placeholder(s); the tool's no-match output is the in-band signal`);
|
|
1344
|
+
}
|
|
1345
|
+
};
|
|
1346
|
+
return {
|
|
1347
|
+
setup: async (ctx) => {
|
|
1348
|
+
try {
|
|
1349
|
+
for (const kind of ["context", "compaction", "generate", "title"]) {
|
|
1350
|
+
disposals.push((await ctx.session.hook(kind, (event) => {
|
|
1351
|
+
protectRequestKind(event, kind === "context" ? "primary" : kind);
|
|
1352
|
+
})).dispose);
|
|
1353
|
+
}
|
|
1354
|
+
if (wireProtection) {
|
|
1355
|
+
disposals.push((await ctx.session.hook("http.request", (event) => {
|
|
1356
|
+
return onHttpRequest(event);
|
|
1357
|
+
})).dispose);
|
|
1358
|
+
}
|
|
1359
|
+
try {
|
|
1360
|
+
disposals.push((await ctx.session.hook("http.response", (event) => {
|
|
1361
|
+
return onHttpResponse(event);
|
|
1362
|
+
})).dispose);
|
|
1363
|
+
}
|
|
1364
|
+
catch (error) {
|
|
1365
|
+
if (wireProtection)
|
|
1366
|
+
throw error;
|
|
1367
|
+
noticeOnce("HTTP reply restoration hook unavailable; content and tool hooks remain active");
|
|
1368
|
+
}
|
|
1369
|
+
const socketHooks = wireProtection
|
|
1370
|
+
? ["experimental.ws.handshake", "experimental.ws.send", "experimental.ws.receive"]
|
|
1371
|
+
: ["experimental.ws.receive"];
|
|
1372
|
+
for (const name of socketHooks) {
|
|
1373
|
+
try {
|
|
1374
|
+
disposals.push((await ctx.session.hook(name, async (input) => {
|
|
1375
|
+
const event = input;
|
|
1376
|
+
try {
|
|
1377
|
+
const sessionID = requireSessionID(event);
|
|
1378
|
+
assertTrackable(sessionID);
|
|
1379
|
+
if (name === "experimental.ws.receive" && !sessions.has(sessionID))
|
|
1380
|
+
throw new Error(ATTRIBUTION_ERROR);
|
|
1381
|
+
ensureSeeded(sessionID);
|
|
1382
|
+
if (types.isProxy(event))
|
|
1383
|
+
throw new Error(PROTECT_FAILED_ERROR);
|
|
1384
|
+
if (name === "experimental.ws.handshake")
|
|
1385
|
+
webSocket.handshake(event);
|
|
1386
|
+
else {
|
|
1387
|
+
assertWritableDataProperty(event, "frame");
|
|
1388
|
+
event.frame = name === "experimental.ws.send" ? await webSocket.send(event)
|
|
1389
|
+
: wireProtection ? webSocket.receive(event) : webSocket.receiveOnly(event);
|
|
1390
|
+
}
|
|
1391
|
+
track(sessionID);
|
|
1392
|
+
if (name === "experimental.ws.send")
|
|
1393
|
+
persistIfChanged(sessionID);
|
|
1394
|
+
}
|
|
1395
|
+
catch (error) {
|
|
1396
|
+
if (name === "experimental.ws.receive") {
|
|
1397
|
+
try {
|
|
1398
|
+
const frame = webSocket.abandonResponse(event);
|
|
1399
|
+
if (frame !== undefined)
|
|
1400
|
+
event.frame = frame;
|
|
1401
|
+
}
|
|
1402
|
+
catch { /* Unwritable or invalid input stays untouched. */ }
|
|
1403
|
+
noticeOnce("WS reply kept original after attribution or restoration failure; placeholders may remain literal");
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
try {
|
|
1407
|
+
webSocket.reset(event);
|
|
1408
|
+
}
|
|
1409
|
+
catch { /* Invalid attribution has no lane to reset. */ }
|
|
1410
|
+
// Adapter diagnostics are static. Do not surface native URL/
|
|
1411
|
+
// Headers errors, which may embed a credential or raw value.
|
|
1412
|
+
const message = error instanceof Error && error.message.startsWith("LeakShield ")
|
|
1413
|
+
? error.message : PROTECT_FAILED_ERROR;
|
|
1414
|
+
throw new Error(`${message} [hook=${name}]`);
|
|
1415
|
+
}
|
|
1416
|
+
})).dispose);
|
|
1417
|
+
}
|
|
1418
|
+
catch (error) {
|
|
1419
|
+
if (wireProtection)
|
|
1420
|
+
throw error;
|
|
1421
|
+
noticeOnce("WS reply restoration hook unavailable; content and tool hooks remain active");
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
for (const name of wireProtection ? ["sdk", "language"] : []) {
|
|
1425
|
+
disposals.push((await ctx.aisdk.hook(name, (event) => {
|
|
1426
|
+
try {
|
|
1427
|
+
aiSDK.admit(event);
|
|
1428
|
+
}
|
|
1429
|
+
catch {
|
|
1430
|
+
throw new Error(`${UNSUPPORTED_ROUTE_ERROR} AI SDK providers must honor OpenCode's injected HTTP fetch. [hook=aisdk.${name}]`);
|
|
1431
|
+
}
|
|
1432
|
+
})).dispose);
|
|
1433
|
+
}
|
|
1434
|
+
disposals.push((await ctx.tool.hook("execute.before", (event) => {
|
|
1435
|
+
onToolBefore(event);
|
|
1436
|
+
})).dispose);
|
|
1437
|
+
// Public V2 events are an optional reclamation optimization: an absent
|
|
1438
|
+
// or failed stream retains mappings rather than evicting live state.
|
|
1439
|
+
// Subscribe only after all protection hooks have been armed.
|
|
1440
|
+
if (ctx.event?.subscribe) {
|
|
1441
|
+
const controller = new AbortController();
|
|
1442
|
+
disposals.push(async () => { controller.abort(); });
|
|
1443
|
+
void (async () => {
|
|
1444
|
+
try {
|
|
1445
|
+
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
|
|
1446
|
+
if (controller.signal.aborted)
|
|
1447
|
+
break;
|
|
1448
|
+
if (event.type === "session.deleted")
|
|
1449
|
+
releaseSession(event.data.sessionID);
|
|
1450
|
+
}
|
|
1451
|
+
if (!controller.signal.aborted)
|
|
1452
|
+
noticeOnce("session lifecycle stream ended; mappings retained until unload");
|
|
1453
|
+
}
|
|
1454
|
+
catch {
|
|
1455
|
+
if (!controller.signal.aborted)
|
|
1456
|
+
noticeOnce("session lifecycle stream unavailable; mappings retained until unload");
|
|
1457
|
+
}
|
|
1458
|
+
})();
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
catch (error) {
|
|
1462
|
+
// Registration failed partway: undo what was armed, then surface the
|
|
1463
|
+
// failure so the caller can fall back to its fail-closed setup.
|
|
1464
|
+
// R-round (F4.5): the store handle must not leak on this path.
|
|
1465
|
+
await runDisposals(disposals);
|
|
1466
|
+
webSocket.dispose();
|
|
1467
|
+
aiSDK.dispose();
|
|
1468
|
+
store?.close();
|
|
1469
|
+
store = null;
|
|
1470
|
+
throw error;
|
|
1471
|
+
}
|
|
1472
|
+
},
|
|
1473
|
+
dispose: async () => {
|
|
1474
|
+
await runDisposals(disposals);
|
|
1475
|
+
webSocket.dispose();
|
|
1476
|
+
aiSDK.dispose();
|
|
1477
|
+
for (const sessionID of sessions)
|
|
1478
|
+
pseudonymizer.clearSession(sessionID);
|
|
1479
|
+
sessions.clear();
|
|
1480
|
+
protectedContexts.clear();
|
|
1481
|
+
notices.clear();
|
|
1482
|
+
seedAttempts.clear();
|
|
1483
|
+
persistedEntries.clear();
|
|
1484
|
+
persistVersions.clear();
|
|
1485
|
+
noPersist.clear();
|
|
1486
|
+
// W2 (decision §4.4): dispose unloads hooks and in-memory state only —
|
|
1487
|
+
// persisted mappings survive until TTL expiry or an explicit forget.
|
|
1488
|
+
store?.close();
|
|
1489
|
+
store = null;
|
|
1490
|
+
},
|
|
1491
|
+
};
|
|
1492
|
+
}
|