leakshield 0.2.0 → 0.3.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.
@@ -42,6 +42,7 @@ import { MappingForgottenError, MappingKeyMismatchError, MappingSnapshotTooLarge
42
42
  import { resolveMappingKey } from "./decision/mapping-key.js";
43
43
  import { walkSchemaStrings } from "./decision/schema-strings.js";
44
44
  import { classifyModelRoute, remaskModelRequest, restoreModelResponse, withOpaqueAttachments, } from "./opencode-transparent-http.js";
45
+ import { FINDING_TYPES } from "./types.js";
45
46
  import { createResponsesWebSocketAdapter } from "./opencode-transparent-ws.js";
46
47
  import { createAISDKTransportAdmission } from "./opencode-transparent-aisdk.js";
47
48
  import { BUILTIN_RULES } from "./rules/builtin.js";
@@ -54,7 +55,25 @@ const TOOL_REFUSAL_ERROR = "LeakShield blocked this tool call because its argume
54
55
  const TOOL_UNKNOWN_MAPPING_ERROR = "LeakShield blocked this tool call before execution: a placeholder has no mapping in this session. The tool did not run. Reread the source and rebuild the affected arguments from current references; rereading does not make an old placeholder valid. If it is refused again, stop retrying and ask the user.";
55
56
  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
57
  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 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
+ 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
+ /**
66
+ * Refusal for `fetch` inside Code Mode source that holds a protected value.
67
+ * This only avoids a misleading result: the inner fetch would send the
68
+ * placeholder, the remote would answer with an error, and the model would read
69
+ * that as a verdict on the real value. It is NOT a security boundary: it is a
70
+ * text match on the source, not a network control, so other spellings are not
71
+ * caught (and then send only the placeholder).
72
+ */
73
+ const TOOL_CODE_FETCH_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- Reason: fetch inside execute cannot use protected values, because it would send the placeholder rather than the real value, so a failed response says nothing about the value.\n- Fix: use a tool call instead, or tell the user this cannot be done here.\n- Do not report the value as invalid, and do not ask for or write the real value.";
74
+ /** Refusal for a value recognisably derived from this session's placeholder whose format was changed. */
75
+ const TOOL_PLACEHOLDER_NEAR_MISS_ERROR = "LeakShield blocked this tool call; the tool did not run.\n- A value looks like a placeholder from this conversation, but its format was changed.\n- Fix: copy it exactly as it appears, including its brackets; do not replace it with other text.\n- Do not ask for or write the real value. If refused again, stop and ask the user.";
76
+ const TOOL_INPUT_SHAPE_ERROR = "LeakShield blocked this tool call because the structure of one argument could not be restored. This is not about what the value looks like or contains. Use plain JSON values (strings, numbers, booleans, arrays and plain objects) and try again.";
58
77
  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
78
  function toolRestoreError(reason) {
60
79
  if (reason === "unknown_token" || reason === "malformed_token")
@@ -165,6 +184,41 @@ const INLINE_SCRIPT_FLAGS = new Map([
165
184
  ]);
166
185
  const SCRIPT_ARGUMENT_INTERPRETERS = new Set(["awk", "sed", "jq"]);
167
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
+ }
168
222
  /** Returns only ordinary arguments, never command/assignment/redirect words. */
169
223
  function parseSupportedShellArguments(text) {
170
224
  const parsed = parseLiteralShellWords(text);
@@ -178,7 +232,7 @@ function parseSupportedShellArguments(text) {
178
232
  return null;
179
233
  }
180
234
  const words = redirectIndex === -1 ? parsed : parsed.slice(0, redirectIndex);
181
- const commandIndex = words.findIndex((word) => word.quote !== "none" || !ASSIGNMENT_WORD.test(word.value));
235
+ const commandIndex = resolveExecutedCommandIndex(words);
182
236
  if (commandIndex === -1)
183
237
  return null;
184
238
  const commandName = words[commandIndex].value.split("/").at(-1)?.toLowerCase() ?? "";
@@ -200,37 +254,55 @@ function parseSupportedShellArguments(text) {
200
254
  /** Characters forbidden inside restored shell argument words. */
201
255
  const SHELL_UNSAFE = /[\s'"`\\$;|&<>(){}*?\[\]!~#\x00-\x1F\x7F]/;
202
256
  /**
203
- * Conservative allowlist of non-executing tools. Any tool not listed here is
204
- * treated as potentially shell-like and requires shell-safe originals, so an
205
- * unrecognized (or newly added) executing tool fails closed rather than
206
- * receiving a value that could change its meaning.
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.
207
265
  */
208
- const NON_SHELL_TOOLS = new Set([
209
- "read",
210
- "read_file",
211
- "view",
212
- "write",
213
- "write_file",
214
- "create_file",
215
- "edit",
216
- "edit_file",
217
- "multiedit",
218
- "patch",
219
- "apply_patch",
220
- "str_replace",
221
- "str_replace_editor",
222
- "grep",
223
- "glob",
224
- "list",
225
- "ls",
226
- "find",
227
- "webfetch",
228
- "websearch",
229
- "fetch",
230
- "todowrite",
231
- "todoread",
232
- "notebookedit",
266
+ const SHELL_TOOLS = new Set([
267
+ "bash",
268
+ "shell",
269
+ "sh",
270
+ "zsh",
271
+ "exec",
272
+ "command",
273
+ "run",
274
+ "pwsh",
275
+ "powershell",
233
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
+ };
234
306
  /**
235
307
  * Tools whose calls are observably read-only: an unresolved placeholder in
236
308
  * their arguments reads/greps/lists against a literal string and matches
@@ -270,8 +342,212 @@ function isShellSafeOriginal(text, quote) {
270
342
  return !/["`\\$!]/.test(text);
271
343
  return !SHELL_UNSAFE.test(text);
272
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
+ }
273
394
  /** Matches a fully formed reserved token (either version), for per-token shell safety checks. */
274
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
+ }
275
551
  /**
276
552
  * Bound on distinct session identities retained for disposal. The core already
277
553
  * caps committed sessions; this bounds identities seen with safe-only content
@@ -1211,30 +1487,148 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1211
1487
  }
1212
1488
  };
1213
1489
  /**
1214
- * Restores registered tokens in a tool input leaf. For shell-like tools the
1215
- * token must occupy a complete argument word AND its original must be safe
1216
- * in that word's existing quote context. Command/assignment/redirect tokens,
1217
- * expansion, quote-breaking and option injection refuse the whole call.
1490
+ * True when at least one placeholder in `text` belongs to this session.
1491
+ * Shell quoting rules only matter when a placeholder is actually replaced;
1492
+ * an unmapped literal must fall through to the mapping policy instead of
1493
+ * being reported as an unsupported shell construct.
1494
+ */
1495
+ const containsMappedToken = (sessionID, text) => {
1496
+ for (const match of text.matchAll(TOKEN_SCAN)) {
1497
+ if (transportService.restoreText(sessionID, match[0]).ok)
1498
+ return true;
1499
+ }
1500
+ return false;
1501
+ };
1502
+ /**
1503
+ * True when `text` holds a placeholder of this session whose format was
1504
+ * changed (brackets dropped or half-dropped, separators swapped, case
1505
+ * lowered, separators changed or removed). Exact canonical tokens are blanked first; partially masked forms
1506
+ * and tokens unknown to the session never qualify.
1507
+ */
1508
+ const textHasNearMiss = (sessionID, text) => {
1509
+ if (!/sgp2/i.test(text))
1510
+ return false;
1511
+ const rest = text.replace(TOKEN_SCAN, " ");
1512
+ for (const head of rest.matchAll(NEAR_MISS_V2_HEAD)) {
1513
+ const letters = collectNearMissLetters(rest, head.index + head[0].length);
1514
+ const upper = letters.toUpperCase();
1515
+ for (const [compact, label] of NEAR_MISS_V2_CATEGORIES) {
1516
+ if (!upper.startsWith(compact) || letters.length - compact.length < NEAR_MISS_V2_SEGMENT_LETTERS)
1517
+ continue;
1518
+ const body = letters.slice(compact.length, compact.length + NEAR_MISS_V2_SEGMENT_LETTERS).toLowerCase();
1519
+ const canonical = `[SGP2:${label}-${body.slice(0, 4)}-${body.slice(4, 8)}-${body.slice(8, 12)}]`;
1520
+ ensureSeeded(sessionID);
1521
+ if (transportService.restoreText(sessionID, canonical).ok)
1522
+ return true;
1523
+ }
1524
+ }
1525
+ return false;
1526
+ };
1527
+ /**
1528
+ * Read-only walk over every string leaf and object key of a tool input.
1529
+ * Never throws and never runs getters: proxies, accessors, symbols and
1530
+ * non-plain objects are skipped silently, cycles are guarded, frozen objects
1531
+ * are scanned. `skipCode` leaves the top-level `code` string of a Code Mode
1532
+ * call alone.
1533
+ */
1534
+ const inputHasNearMiss = (sessionID, input, skipCode) => {
1535
+ try {
1536
+ if (typeof input === "string")
1537
+ return textHasNearMiss(sessionID, input);
1538
+ const seen = new WeakSet();
1539
+ const stack = [{ value: input, top: true }];
1540
+ while (stack.length > 0) {
1541
+ const { value, top } = stack.pop();
1542
+ if (value === null || typeof value !== "object")
1543
+ continue;
1544
+ if (types.isProxy(value) || seen.has(value))
1545
+ continue;
1546
+ seen.add(value);
1547
+ const isArray = Array.isArray(value);
1548
+ if (!isArray) {
1549
+ const prototype = Object.getPrototypeOf(value);
1550
+ if (prototype !== Object.prototype && prototype !== null)
1551
+ continue;
1552
+ }
1553
+ const descriptors = Object.getOwnPropertyDescriptors(value);
1554
+ for (const key of Object.keys(descriptors)) {
1555
+ if (isArray && key === "length")
1556
+ continue;
1557
+ if (!isArray && textHasNearMiss(sessionID, key))
1558
+ return true;
1559
+ const descriptor = descriptors[key];
1560
+ if (!("value" in descriptor))
1561
+ continue;
1562
+ if (skipCode && top && key === "code" && typeof descriptor.value === "string")
1563
+ continue;
1564
+ if (typeof descriptor.value === "string") {
1565
+ if (textHasNearMiss(sessionID, descriptor.value))
1566
+ return true;
1567
+ }
1568
+ else {
1569
+ stack.push({ value: descriptor.value, top: false });
1570
+ }
1571
+ }
1572
+ }
1573
+ }
1574
+ catch {
1575
+ return false;
1576
+ }
1577
+ return false;
1578
+ };
1579
+ /**
1580
+ * Restores registered tokens in a tool input leaf according to its policy.
1581
+ * "shell": the token must occupy a complete argument word AND its original
1582
+ * must be safe in that word's quote context; command/assignment/redirect
1583
+ * tokens, expansion, quote-breaking and option injection refuse the call.
1584
+ * "inert" (code/script fields): every restorable token's original must be
1585
+ * free of shell-unsafe characters (spaces included), and the token must sit
1586
+ * look like it sits in an ordinary single-line quoted string without
1587
+ * interpolation, outside any multi-line string or line continuation
1588
+ * (conservative heuristic, not a parser: it can over-refuse and miss, and
1589
+ * does not confirm the token is in a string; it guards the restoration
1590
+ * context, not egress). Otherwise the call is refused. "verbatim": plain restore.
1218
1591
  *
1219
1592
  * P1 (2026-10-06b) limited best-effort: when `allowDegraded` is set (the
1220
- * call is a proven read-only tool, not shell-like) a mapping failure
1221
- * (unknown/malformed marker) keeps the leaf literal and records a
1222
- * degradation instead of refusing — the placeholder reads as a literal
1223
- * that matches nothing, the tool's own output is the in-band signal, and a
1224
- * content-free WARN line is logged. Every other failure kind still refuses.
1593
+ * call is a proven read-only tool with no shell/code fields) and the leaf is
1594
+ * "verbatim", a mapping failure (unknown/malformed marker) keeps the leaf
1595
+ * literal and records a degradation instead of refusing. Every other
1596
+ * failure kind still refuses.
1225
1597
  */
1226
- const restoreLeaf = (sessionID, text, shellLike, allowDegraded, degraded) => {
1598
+ const restoreLeaf = (sessionID, text, policy, allowDegraded, degraded) => {
1227
1599
  if (!containsTokenPrefix(text))
1228
1600
  return text;
1229
- if (shellLike) {
1601
+ if (policy === "inert" && containsMappedToken(sessionID, text)) {
1602
+ const isAllowedPosition = createInertPositionCheck(text);
1603
+ for (const match of text.matchAll(TOKEN_SCAN)) {
1604
+ const restoredToken = transportService.restoreText(sessionID, match[0]);
1605
+ if (!restoredToken.ok)
1606
+ continue;
1607
+ if (!isShellSafeOriginal(restoredToken.text, "none"))
1608
+ throw new Error(TOOL_CODE_CONTEXT_ERROR);
1609
+ if (!isAllowedPosition(match.index, match.index + match[0].length))
1610
+ throw new Error(TOOL_CODE_POSITION_ERROR);
1611
+ }
1612
+ }
1613
+ if (policy === "shell" && containsMappedToken(sessionID, text)) {
1230
1614
  const argumentsOnly = parseSupportedShellArguments(text);
1231
1615
  if (argumentsOnly === null)
1232
1616
  throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1617
+ const embedded = commandAllowsEmbeddedTokens(text);
1618
+ if (isWgetExecuteCommand(text))
1619
+ throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1233
1620
  for (const match of text.matchAll(TOKEN_SCAN)) {
1234
1621
  const end = match.index + match[0].length;
1235
- const argument = argumentsOnly.find((word) => word.value === match[0] && word.start <= match.index && word.end >= end);
1622
+ const argument = argumentsOnly.find((word) => (embedded || word.value === match[0]) && word.start <= match.index && word.end >= end);
1236
1623
  if (argument === undefined)
1237
1624
  throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1625
+ // In a word starting with `-`, only `--name=value` may hold a token. Short
1626
+ // options cluster, with punctuation flags too (`-#`, `-:`), so restored
1627
+ // text could become an option and its value (`-#T/tmp/x` uploads a file).
1628
+ const valueStart = argument.start + (argument.quote === "none" ? 0 : 1);
1629
+ const before = text.slice(valueStart, match.index);
1630
+ if (before.startsWith("-") && !/^--[A-Za-z0-9-]+=/.test(before))
1631
+ throw new Error(TOOL_SHELL_CONTEXT_ERROR);
1238
1632
  const restoredToken = transportService.restoreText(sessionID, match[0]);
1239
1633
  if (!restoredToken.ok)
1240
1634
  throw new Error(toolRestoreError(restoredToken.reason));
@@ -1246,6 +1640,7 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1246
1640
  if (restored.ok)
1247
1641
  return restored.text;
1248
1642
  if (allowDegraded &&
1643
+ policy === "verbatim" &&
1249
1644
  (restored.reason === "unknown_token" || restored.reason === "malformed_token")) {
1250
1645
  degraded.count += 1;
1251
1646
  return text;
@@ -1254,61 +1649,100 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1254
1649
  };
1255
1650
  /**
1256
1651
  * Planning pass: computes every replacement WITHOUT mutating, and rejects
1257
- * frozen/unwritable containers or token-bearing keys. Nothing is written
1258
- * until the whole plan is known to be applicable.
1652
+ * proxies, shared/cyclic references, symbol keys, accessors, odd prototypes,
1653
+ * non-index array keys and token-bearing keys anywhere in the tree.
1654
+ *
1655
+ * A writable container gets its replacements pushed onto `out`. A frozen
1656
+ * container is never written: when its subtree needs a change it is rebuilt
1657
+ * as a new plain container and RETURNED, so the caller (the nearest writable
1658
+ * ancestor, or an enclosing frozen copy) takes it in place of the original.
1659
+ * It returns `undefined` when the value needs no replacement.
1259
1660
  */
1260
- const planToolInput = (value, sessionID, shellLike, seen, out, allowDegraded, degraded) => {
1661
+ const planToolInput = (value, sessionID, policy, seen, out, allowDegraded, degraded) => {
1261
1662
  if (value === null || typeof value !== "object")
1262
- return;
1263
- if (types.isProxy(value) || seen.has(value) || Object.isFrozen(value)) {
1663
+ return undefined;
1664
+ if (types.isProxy(value) || seen.has(value))
1264
1665
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1265
- }
1266
1666
  seen.add(value);
1667
+ const frozen = Object.isFrozen(value);
1267
1668
  if (Object.getOwnPropertySymbols(value).length > 0)
1268
1669
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1269
- if (Array.isArray(value)) {
1270
- for (const key of Object.keys(value)) {
1670
+ const isArray = Array.isArray(value);
1671
+ const changes = [];
1672
+ const plan = (item, itemPolicy, key) => {
1673
+ if (typeof item === "string") {
1674
+ const next = restoreLeaf(sessionID, item, itemPolicy, allowDegraded, degraded);
1675
+ if (next !== item)
1676
+ changes.push({ key, next });
1677
+ }
1678
+ else {
1679
+ const next = planToolInput(item, sessionID, itemPolicy, seen, out, allowDegraded, degraded);
1680
+ if (next !== undefined)
1681
+ changes.push({ key, next });
1682
+ }
1683
+ };
1684
+ if (isArray) {
1685
+ const array = value;
1686
+ for (const key of Object.keys(array)) {
1271
1687
  if (!/^(0|[1-9]\d*)$/.test(key))
1272
1688
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1273
1689
  }
1274
- for (let index = 0; index < value.length; index++) {
1275
- const descriptor = Object.getOwnPropertyDescriptor(value, index);
1690
+ for (let index = 0; index < array.length; index++) {
1691
+ const descriptor = Object.getOwnPropertyDescriptor(array, index);
1276
1692
  if (descriptor === undefined)
1277
1693
  continue;
1278
- if (!("value" in descriptor))
1694
+ if (!("value" in descriptor) || !descriptor.enumerable)
1279
1695
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1280
- const item = descriptor.value;
1281
- if (typeof item === "string") {
1282
- const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
1283
- if (next !== item)
1284
- out.push({ container: value, key: index, value: next });
1285
- }
1286
- else {
1287
- planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
1288
- }
1696
+ plan(descriptor.value, policy, index);
1289
1697
  }
1290
- return;
1291
1698
  }
1292
- const prototype = Object.getPrototypeOf(value);
1293
- if (prototype !== Object.prototype && prototype !== null)
1294
- throw new Error(TOOL_INPUT_SHAPE_ERROR);
1295
- const record = value;
1296
- for (const key of Object.keys(record)) {
1297
- if (containsTokenPrefix(key))
1699
+ else {
1700
+ const prototype = Object.getPrototypeOf(value);
1701
+ if (prototype !== Object.prototype && prototype !== null)
1298
1702
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1299
- const descriptor = Object.getOwnPropertyDescriptor(record, key);
1300
- if (descriptor === undefined || !("value" in descriptor))
1703
+ const record = value;
1704
+ // A copy keeps enumerable keys only, so a hidden property would vanish from it.
1705
+ if (Object.getOwnPropertyNames(record).length !== Object.keys(record).length)
1301
1706
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1302
- const item = descriptor.value;
1303
- if (typeof item === "string") {
1304
- const next = restoreLeaf(sessionID, item, shellLike, allowDegraded, degraded);
1305
- if (next !== item)
1306
- out.push({ container: record, key, value: next });
1707
+ for (const key of Object.keys(record)) {
1708
+ if (containsTokenPrefix(key))
1709
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1710
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
1711
+ if (descriptor === undefined || !("value" in descriptor))
1712
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1713
+ plan(descriptor.value, keyPolicy(key, policy), key);
1307
1714
  }
1308
- else {
1309
- planToolInput(item, sessionID, shellLike, seen, out, allowDegraded, degraded);
1715
+ }
1716
+ if (changes.length === 0)
1717
+ return undefined;
1718
+ if (!frozen) {
1719
+ for (const change of changes) {
1720
+ out.push({ container: value, key: change.key, value: change.next });
1721
+ }
1722
+ return undefined;
1723
+ }
1724
+ // Frozen: copy only this container, keeping key order and array positions.
1725
+ const replaced = new Map(changes.map((change) => [change.key, change.next]));
1726
+ if (isArray) {
1727
+ const source = value;
1728
+ const copy = new Array(source.length);
1729
+ for (const key of Object.keys(source)) {
1730
+ const index = Number(key);
1731
+ copy[index] = replaced.has(index) ? replaced.get(index) : source[index];
1310
1732
  }
1733
+ return copy;
1311
1734
  }
1735
+ const source = value;
1736
+ const copy = Object.create(Object.getPrototypeOf(source));
1737
+ for (const key of Object.keys(source)) {
1738
+ Object.defineProperty(copy, key, {
1739
+ value: replaced.has(key) ? replaced.get(key) : source[key],
1740
+ writable: true,
1741
+ enumerable: true,
1742
+ configurable: true,
1743
+ });
1744
+ }
1745
+ return copy;
1312
1746
  };
1313
1747
  const assertToolPlanWritable = (plan) => {
1314
1748
  for (const assignment of plan) {
@@ -1328,29 +1762,73 @@ export function createTransparentSessionGuard(config, attachmentsPolicy = "block
1328
1762
  }
1329
1763
  }
1330
1764
  };
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
+ };
1331
1772
  const onToolBefore = (event) => {
1773
+ const codeMode = isCodeModeCall(event);
1774
+ // Placeholders whose format the model changed would reach the tool as junk
1775
+ // with no error; refuse them before anything is restored or mutated.
1776
+ if (typeof event.sessionID === "string" && event.sessionID.length > 0) {
1777
+ if (inputHasNearMiss(event.sessionID, event.input, codeMode)) {
1778
+ throw new Error(TOOL_PLACEHOLDER_NEAR_MISS_ERROR);
1779
+ }
1780
+ if (codeMode) {
1781
+ const code = event.input.code;
1782
+ if (/\bfetch\b/.test(code) && /sgp[12]/i.test(code)) {
1783
+ ensureSeeded(event.sessionID);
1784
+ if (containsMappedToken(event.sessionID, code) || textHasNearMiss(event.sessionID, code)) {
1785
+ throw new Error(TOOL_CODE_FETCH_ERROR);
1786
+ }
1787
+ }
1788
+ }
1789
+ }
1332
1790
  if (!inputCarriesToken(event.input, new WeakSet()))
1333
1791
  return;
1334
1792
  const sessionID = requireSessionID(event);
1335
1793
  ensureSeeded(sessionID);
1336
- const tool = typeof event.tool === "string" ? event.tool.toLowerCase() : "";
1337
- const shellLike = !NON_SHELL_TOOLS.has(tool) ||
1338
- (isRecordLike(event.input) && typeof event.input.command === "string");
1339
- // P1 (2026-10-06b): only proven read-only, non-shell tools may degrade to
1340
- // literal placeholders; writes/deletes/outbound/unknown tools keep
1341
- // refusing the affected invocation when restoration is incomplete.
1342
- const allowDegraded = READ_ONLY_TOOLS.has(tool) && !shellLike;
1794
+ const rawTool = typeof event.tool === "string" ? event.tool : "";
1795
+ const tool = rawTool.toLowerCase();
1796
+ // Code Mode source is JavaScript and the host re-fires this hook for each
1797
+ // inner tool call with evaluated arguments; that is where restoration and
1798
+ // the shell/inert/verbatim rules apply. A placeholder in the source stays
1799
+ // literal. Any other shape or name falls through to the logic below.
1800
+ if (codeMode) {
1801
+ return;
1802
+ }
1803
+ // Field-level model: the root policy is "shell" for shell tools and
1804
+ // "verbatim" otherwise; each key may then switch the policy for its value
1805
+ // (shell/command-like keys -> "shell", code/script keys -> "inert",
1806
+ // description/title/label -> "verbatim").
1807
+ const shellTool = isShellTool(rawTool);
1808
+ const rootPolicy = shellTool ? "shell" : "verbatim";
1809
+ // P1 (2026-10-06b): only proven read-only tools without shell/code fields
1810
+ // may degrade to literal placeholders; everything else refuses the
1811
+ // affected invocation when restoration is incomplete.
1812
+ const allowDegraded = READ_ONLY_TOOLS.has(tool) &&
1813
+ !shellTool &&
1814
+ !(isRecordLike(event.input) &&
1815
+ Object.keys(event.input).some((key) => isShellKey(key) || isCodeKey(key)));
1343
1816
  const degraded = { count: 0 };
1344
1817
  if (typeof event.input === "string") {
1345
1818
  const descriptor = Object.getOwnPropertyDescriptor(event, "input");
1346
1819
  if (descriptor === undefined || !("value" in descriptor) || descriptor.writable !== true) {
1347
1820
  throw new Error(TOOL_INPUT_SHAPE_ERROR);
1348
1821
  }
1349
- event.input = restoreLeaf(sessionID, event.input, shellLike, allowDegraded, degraded);
1822
+ event.input = restoreLeaf(sessionID, event.input, rootPolicy, allowDegraded, degraded);
1350
1823
  }
1351
1824
  else {
1825
+ // The root is the one container that is never copied: it is the host's
1826
+ // own event object slot, so a frozen root stays refused.
1827
+ if (event.input !== null && typeof event.input === "object" && (types.isProxy(event.input) || Object.isFrozen(event.input))) {
1828
+ throw new Error(TOOL_INPUT_SHAPE_ERROR);
1829
+ }
1352
1830
  const plan = [];
1353
- planToolInput(event.input, sessionID, shellLike, new WeakSet(), plan, allowDegraded, degraded);
1831
+ planToolInput(event.input, sessionID, rootPolicy, new WeakSet(), plan, allowDegraded, degraded);
1354
1832
  assertToolPlanWritable(plan);
1355
1833
  applyToolPlan(plan);
1356
1834
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "leakshield",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "OpenCode plugin, CLI, and web scanner for sensitive content before sending it to AI",
5
5
  "license": "MIT",
6
6
  "repository": {