agent-sanitizer 2.47.13 → 2.47.14

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.
@@ -11,23 +11,37 @@
11
11
  * have one definition.
12
12
  */
13
13
  import {
14
+ existsSync,
15
+ globSync,
14
16
  lstatSync,
15
17
  mkdirSync,
16
18
  readdirSync,
17
19
  readFileSync,
18
20
  rmSync,
21
+ statSync,
19
22
  } from "node:fs";
20
23
  import { randomBytes } from "node:crypto";
21
24
  import { basename, join } from "node:path";
22
- import { tmpdir, userInfo } from "node:os";
25
+ import { homedir, tmpdir, userInfo } from "node:os";
23
26
  import {
24
27
  lazyImport,
25
28
  markerIsTrusted,
29
+ PROJECT_DIR,
26
30
  PROJECT_HASH,
27
31
  scrubUntrustedText,
28
32
  writeFileNoFollow,
29
33
  writeSentinelFile,
30
34
  } from "./hook-io.mjs";
35
+ // Relative, like scan-invisible-chars.mjs's own import of this module: the
36
+ // launch scope is hook POLICY (see src/claude-context.mjs), and this table is
37
+ // pure data with no fs access of its own — the fs calls below are this
38
+ // module's, not a copy of the SessionStart hook's target-discovery glue.
39
+ import {
40
+ ancestorInstructionFiles,
41
+ CLAUDE_CONTEXT_SUBDIRS,
42
+ CLAUDE_LAUNCH_GLOBS,
43
+ excludeFromContextScan,
44
+ } from "../../src/claude-context.mjs";
31
45
 
32
46
  // Layer-1 scrubber for the untrusted alert-store contents the gate splices into a
33
47
  // permissionDecisionReason. The WELL-FORMED composition, not the bare applyLayer1:
@@ -256,13 +270,14 @@ export function sweepStaleSessions(sessionId) {
256
270
  * The ack always expires; the findings only when this session has its own store
257
271
  * and so merely INHERITED these.
258
272
  *
259
- * The two InstructionsLoaded markers under the same prefix answer "did a scan
260
- * run at all", so FALLBACK_TTL_MS must never reach them: expiring one mid-session
261
- * would render the gap notice on a session that WAS scanned. They still go, at
262
- * MARKER_TTL_MS the same age the loop above ages a real session's prefix out
263
- * at, and far past any session's life because the loop skips this prefix and
264
- * would otherwise leave a session-less host's markers in $TMPDIR forever, with
265
- * the gap notice suppressed on every later session.
273
+ * The three InstructionsLoaded markers under the same prefix answer "did a scan
274
+ * run at all" and "was launch empty", so FALLBACK_TTL_MS must never reach them:
275
+ * expiring one mid-session would render the gap notice on a session that WAS
276
+ * scanned, or re-glob a launch this session already found empty. They still go,
277
+ * at MARKER_TTL_MS the same age the loop above ages a real session's prefix
278
+ * out at, and far past any session's life because the loop skips this prefix
279
+ * and would otherwise leave a session-less host's markers in $TMPDIR forever,
280
+ * with the gap notice suppressed on every later session.
266
281
  * @param {string} [sessionId]
267
282
  * @returns {void}
268
283
  */
@@ -281,7 +296,11 @@ function sweepStaleFallback(sessionId) {
281
296
  };
282
297
  for (const path of [alertAckFile(), ...entries])
283
298
  if (!withinFallbackTtl(path)) drop(path);
284
- for (const path of [instructionsLoadedFile(), instructionsLoadedNoticeFile()])
299
+ for (const path of [
300
+ instructionsLoadedFile(),
301
+ instructionsLoadedNoticeFile(),
302
+ launchEmptyFile(),
303
+ ])
285
304
  if (!withinTtl(path, MARKER_TTL_MS)) drop(path);
286
305
  }
287
306
 
@@ -311,32 +330,143 @@ export function recordInstructionsLoaded(sessionId) {
311
330
  const EVENT_MIN_CLI_VERSION = "2.1.69";
312
331
 
313
332
  /**
314
- * The one-time context line for a session where no InstructionsLoaded scan ran,
315
- * or null when the scan has been seen or the notice was already surfaced this
316
- * session.
333
+ * Companion marker: this session already found the LAUNCH set empty that set
334
+ * (which files load at session start) cannot change mid-session, so a second
335
+ * glob of `dir` can never change that half of the answer. It says nothing about
336
+ * a directory touched later; {@link instructionsLoadedGapNotice}'s `touchedDir`
337
+ * covers that half fresh on every call instead.
338
+ * @param {string} [sessionId]
339
+ * @returns {string}
340
+ */
341
+ export function launchEmptyFile(sessionId) {
342
+ return `${instructionsLoadedFile(sessionId)}.launch-empty`;
343
+ }
344
+
345
+ /**
346
+ * Every file Claude Code loads as model context AT LAUNCH from `dir`: its own
347
+ * instruction files, its `.claude/` context tree, and the CLAUDE.md /
348
+ * CLAUDE.local.md of every directory above it. THE SSOT scan-invisible-chars.mjs
349
+ * reads too (re-exported there as `findInstructionFiles`) — sharing the one
350
+ * function is what keeps the SessionStart scan's targets and this module's
351
+ * launch-emptiness check from drifting into two different answers for "what
352
+ * loads at launch". See src/claude-context.mjs for why this is the shallow
353
+ * launch scope and not a whole-tree walk.
354
+ * @param {string} dir
355
+ * @returns {string[]}
356
+ */
357
+ export function launchInstructionFiles(dir) {
358
+ return [
359
+ ...globSync([...CLAUDE_LAUNCH_GLOBS], {
360
+ cwd: dir,
361
+ exclude: excludeFromContextScan,
362
+ }).map((name) => join(dir, name)),
363
+ // Filtered, unlike the glob's matches: almost every parent directory holds
364
+ // neither memory file, so the unfiltered chain would file ~10 phantom
365
+ // targets per session into scan-invisible-chars.mjs's operator-facing
366
+ // "absent" bucket. A file that appears after this check was not loaded at
367
+ // launch either, so nothing is lost by not listing it.
368
+ ...ancestorInstructionFiles(dir).filter((file) => existsSync(file)),
369
+ ];
370
+ }
371
+
372
+ /**
373
+ * Whether anything Claude Code loads at launch from `dir` actually has bytes.
374
+ * An existing but EMPTY file (a freshly `touch`ed `~/.claude/CLAUDE.md`) is
375
+ * nothing to load: Claude Code 2.1.246 fires no InstructionsLoaded event when
376
+ * a launch has nothing in it, so the missing event is expected there, not a
377
+ * sign the scanner is unwired.
378
+ *
379
+ * A file this uid cannot even STAT (EACCES, EISDIR, ELOOP…) is unvetted
380
+ * context, not evidence of absence — the same split scan-invisible-chars.mjs's
381
+ * classifyReadFailure makes between ABSENT and SKIPPED. Reading such a failure
382
+ * as "no content" would suppress the notice over a file that may carry a real,
383
+ * unscanned payload, so only ENOENT counts as nothing there; anything else
384
+ * counts as content and leaves the notice free to fire.
385
+ * @param {string} dir
386
+ * @returns {boolean}
387
+ */
388
+ function launchHasContent(dir) {
389
+ for (const file of launchInstructionFiles(dir)) {
390
+ try {
391
+ if (statSync(file).size > 0) return true;
392
+ } catch (err) {
393
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT")
394
+ return true;
395
+ }
396
+ }
397
+ return false;
398
+ }
399
+
400
+ /**
401
+ * Whether the USER-GLOBAL `~/.claude` memory and rules — a second root Claude
402
+ * Code loads at launch regardless of the project directory (see
403
+ * scan-loaded-instructions.mjs's header) — has any bytes. `launchHasContent`
404
+ * cannot see this root on its own: it is `dir`-relative, and `~/.claude` is
405
+ * outside `dir`'s own tree whenever the project is not `$HOME` itself, exactly
406
+ * the case a project opened anywhere but home is in.
317
407
  *
318
- * PURE: it does not record that the notice was handed out. The caller records
319
- * separately, once the notice has actually landed in a responsea deny
320
- * assembled after this call discards the notice, and a marker written here would
321
- * have burned the session's one chance to report the loss.
408
+ * Honours `CLAUDE_CONFIG_DIR` the way plugin/scripts/enable-auto-update.mjs's
409
+ * own resolution does, since that root not always `~/.claude`is where
410
+ * Claude Code actually reads this content from.
411
+ * @param {Record<string, string | undefined>} [env]
412
+ * @returns {boolean}
413
+ */
414
+ function userGlobalLaunchHasContent(env = process.env) {
415
+ const configDir = env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
416
+ const candidates = globSync(
417
+ ["*.md", ...CLAUDE_CONTEXT_SUBDIRS.map((sub) => `${sub}/**/*.md`)],
418
+ { cwd: configDir, exclude: excludeFromContextScan },
419
+ ).map((name) => join(configDir, name));
420
+ for (const file of candidates) {
421
+ try {
422
+ if (statSync(file).size > 0) return true;
423
+ } catch (err) {
424
+ if (/** @type {NodeJS.ErrnoException} */ (err).code !== "ENOENT")
425
+ return true;
426
+ }
427
+ }
428
+ return false;
429
+ }
430
+
431
+ /**
432
+ * The one-time context line for a session where no InstructionsLoaded scan ran,
433
+ * or null when the scan has been seen, the notice already ran this session, or
434
+ * neither launch nor `touchedDir` could have fired the event.
322
435
  *
323
- * The loss it names is real and otherwise invisible: SessionStart scans the
324
- * instruction files that load at launch, and everything a subdirectory loads
325
- * later is scanned by the event. No scan, and nothing says so.
436
+ * PURE for the notice: nothing is recorded until the caller confirms it landed
437
+ * in a returned response. Launch-emptiness is cached once found fixed for the
438
+ * session but `touchedDir` is re-checked every call: the claim below is about
439
+ * SUBDIRECTORY files, so an empty launch must not silence a later call whose
440
+ * tool touched a directory that DOES carry real, unscanned content.
326
441
  *
327
- * The notice names the OBSERVABLE no scan ran and all three causes, because
328
- * the marker cannot tell them apart: a host that never wired the event to
329
- * scan-loaded-instructions, a Claude Code older than EVENT_MIN_CLI_VERSION, and
330
- * the hook switched off in AGENT_SANITIZER_DISABLED_HOOKS; asserting one sends a
331
- * reader who is in another to the wrong fix. The wiring cause leads because it is
332
- * the only one the reader can repair in this session, and nothing else reports it.
333
- * @param {string} [sessionId] the harness's session identity, so the answer
334
- * belongs to THIS session (see instructionsLoadedFile)
442
+ * SessionStart scans what loads at launch; a subdirectory's file is scanned by
443
+ * the event; no scan means nothing says so unless nothing touched so far had
444
+ * anything to scan either. The notice names all three remaining causes, since
445
+ * the marker cannot tell them apart: an unwired event, a Claude Code older than
446
+ * EVENT_MIN_CLI_VERSION, or the hook disabled via AGENT_SANITIZER_DISABLED_HOOKS.
447
+ * @param {string} [sessionId] the harness's session identity (see
448
+ * instructionsLoadedFile)
449
+ * @param {string} [dir] the project root to check (injectable; defaults to
450
+ * the real project)
451
+ * @param {string} [touchedDir] this tool call's own target directory, when
452
+ * known — re-checked every call, never cached
335
453
  * @returns {string | null}
336
454
  */
337
- export function instructionsLoadedGapNotice(sessionId) {
455
+ export function instructionsLoadedGapNotice(
456
+ sessionId,
457
+ dir = PROJECT_DIR,
458
+ touchedDir,
459
+ ) {
338
460
  if (instructionsLoadedSeen(sessionId)) return null;
339
461
  if (markerIsTrusted(instructionsLoadedNoticeFile(sessionId))) return null;
462
+ const launchCached = markerIsTrusted(launchEmptyFile(sessionId));
463
+ const launchHasBytes =
464
+ !launchCached && (launchHasContent(dir) || userGlobalLaunchHasContent());
465
+ if (!launchCached && !launchHasBytes)
466
+ writeSentinelFile(launchEmptyFile(sessionId));
467
+ const touchedHasBytes =
468
+ touchedDir !== undefined && launchHasContent(touchedDir);
469
+ if (!launchHasBytes && !touchedHasBytes) return null;
340
470
  return (
341
471
  "agent-sanitizer: no InstructionsLoaded scan has run this session, so " +
342
472
  "instruction files loaded from SUBDIRECTORIES (a nested CLAUDE.md, a " +
@@ -29,6 +29,7 @@
29
29
  */
30
30
  import { createRequire } from "node:module";
31
31
  import { readFileSync } from "node:fs";
32
+ import { dirname } from "node:path";
32
33
  import {
33
34
  isMain,
34
35
  lazyImport,
@@ -424,6 +425,40 @@ export function preToolUseLayers(rehydrate, env = process.env) {
424
425
  : layers;
425
426
  }
426
427
 
428
+ // The tools whose path field Claude Code sends as an absolute path by
429
+ // contract, so reading it needs no cwd to resolve against. Bounded to these:
430
+ // Glob/Grep's `path` can be relative or omitted (defaults to a cwd this
431
+ // payload does not carry), and Bash has no reliable target at all — the same
432
+ // carve-out WRITE_SHAPED_TOOLS below takes for Bash writes.
433
+ const PATH_FIELD_BY_TOOL = /** @type {Record<string, string>} */ (
434
+ Object.freeze({
435
+ Read: "file_path",
436
+ Edit: "file_path",
437
+ Write: "file_path",
438
+ MultiEdit: "file_path",
439
+ NotebookEdit: "notebook_path",
440
+ })
441
+ );
442
+
443
+ /**
444
+ * The directory THIS tool call targets, for the InstructionsLoaded gap-notice
445
+ * check — or undefined when the tool carries no reliable absolute path. An
446
+ * imprecise guess here only ever WIDENS coverage (see instructionsLoadedGapNotice's
447
+ * `touchedDir`): missing a real target loses nothing this check did not
448
+ * already lack, and there is no wrong-directory case that suppresses a real
449
+ * finding.
450
+ * @param {string} tool
451
+ * @param {any} toolInput
452
+ * @returns {string | undefined}
453
+ */
454
+ function toolTargetDir(tool, toolInput) {
455
+ const field = PATH_FIELD_BY_TOOL[tool];
456
+ const path = field && toolInput?.[field];
457
+ return typeof path === "string" && path.startsWith("/")
458
+ ? dirname(path)
459
+ : undefined;
460
+ }
461
+
427
462
  /**
428
463
  * Compose the four protections. Returns the `hookSpecificOutput` fields to
429
464
  * emit, or null for a clean no-op. Throws only if a layer's engine throws; the
@@ -468,7 +503,11 @@ export async function buildPreToolUseResponse(
468
503
  // the notice was surfaced: a rehydrate deny below returns before the response
469
504
  // is assembled, and recording here would burn the session's one report on a
470
505
  // call that never carried it.
471
- const gapNotice = instructionsLoadedGapNotice(input.session_id);
506
+ const gapNotice = instructionsLoadedGapNotice(
507
+ input.session_id,
508
+ undefined,
509
+ toolTargetDir(tool, toolInput),
510
+ );
472
511
  if (gapNotice !== null) contexts.push(gapNotice);
473
512
 
474
513
  // Layers 2-4, run by the declared pipeline: the driver — not this call order —
@@ -21,8 +21,8 @@
21
21
  * false positive the SSOT had already fixed, and its clean path was a bare
22
22
  * `writeFileSync` with none of cleanFile's symlink/UTF-8/TOCTOU guards.
23
23
  */
24
- import { existsSync, readFileSync, globSync } from "node:fs";
25
- import { join, relative, resolve } from "node:path";
24
+ import { readFileSync } from "node:fs";
25
+ import { relative, resolve } from "node:path";
26
26
  import {
27
27
  awaitLazyDependency,
28
28
  emitHookResponse,
@@ -45,6 +45,7 @@ import {
45
45
  alertAckFile,
46
46
  alertDir,
47
47
  appendAlert,
48
+ launchInstructionFiles,
48
49
  sweepStaleSessions,
49
50
  } from "./lib/invisible-alert.mjs";
50
51
  import { formatReport } from "./lib/invisible-report.mjs";
@@ -59,11 +60,9 @@ import { reportSlowHook, startHookTimer } from "./lib/hook-timing.mjs";
59
60
  // so importing it statically carries none of the fail-open hazard lazyImport
60
61
  // exists to cover.
61
62
  import {
62
- ancestorInstructionFiles,
63
63
  CLAUDE_CONTEXT_SUBDIRS,
64
64
  CLAUDE_INSTRUCTION_GLOBS,
65
65
  CLAUDE_LAUNCH_GLOBS,
66
- excludeFromContextScan,
67
66
  isInsideDir,
68
67
  } from "../src/claude-context.mjs";
69
68
 
@@ -234,26 +233,14 @@ function decodeRun(run) {
234
233
  * files load when a tool reads their directory, and scan-loaded-instructions
235
234
  * scans each one at that moment.
236
235
  *
237
- * The scope itself which globs, and which directories the walk must prune is
238
- * the library's (see src/claude-context.mjs for why it is imported relatively
239
- * rather than through the `agent-sanitizer` specifier the plugin bundle pins).
236
+ * lib/invisible-alert.mjs's `launchInstructionFiles` IS this functionshared
237
+ * so its InstructionsLoaded gap-notice check reads the identical target set
238
+ * this scan does, rather than a second enumeration that could drift.
240
239
  * @param {string} dir
241
240
  * @returns {string[]}
242
241
  */
243
242
  function findInstructionFiles(dir) {
244
- return [
245
- ...globSync([...CLAUDE_LAUNCH_GLOBS], {
246
- cwd: dir,
247
- exclude: excludeFromContextScan,
248
- }).map((name) => join(dir, name)),
249
- // Filtered, unlike the glob's matches: almost every parent directory holds
250
- // neither memory file, so the unfiltered chain would file ~10 phantom
251
- // targets per session into the `absent` bucket and bury the one thing that
252
- // bucket reports — a target that existed when the scan listed it and was
253
- // gone by the read. A file that appears after this check was not loaded at
254
- // launch either, so nothing is lost by not listing it.
255
- ...ancestorInstructionFiles(dir).filter((file) => existsSync(file)),
256
- ];
243
+ return launchInstructionFiles(dir);
257
244
  }
258
245
 
259
246
  // Scanner
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-sanitizer",
3
- "version": "2.47.13",
3
+ "version": "2.47.14",
4
4
  "description": "Defend an agent against hidden-content injection: strip payload-capable invisible Unicode and ANSI, splice out human-invisible HTML, and flag data-exfil URLs in untrusted text before any model sees it.",
5
5
  "type": "module",
6
6
  "repository": {
@@ -74,31 +74,54 @@ export function sweepStaleSessions(sessionId?: string): void;
74
74
  * @returns {void}
75
75
  */
76
76
  export function recordInstructionsLoaded(sessionId?: string): void;
77
+ /**
78
+ * Companion marker: this session already found the LAUNCH set empty — that set
79
+ * (which files load at session start) cannot change mid-session, so a second
80
+ * glob of `dir` can never change that half of the answer. It says nothing about
81
+ * a directory touched later; {@link instructionsLoadedGapNotice}'s `touchedDir`
82
+ * covers that half fresh on every call instead.
83
+ * @param {string} [sessionId]
84
+ * @returns {string}
85
+ */
86
+ export function launchEmptyFile(sessionId?: string): string;
87
+ /**
88
+ * Every file Claude Code loads as model context AT LAUNCH from `dir`: its own
89
+ * instruction files, its `.claude/` context tree, and the CLAUDE.md /
90
+ * CLAUDE.local.md of every directory above it. THE SSOT scan-invisible-chars.mjs
91
+ * reads too (re-exported there as `findInstructionFiles`) — sharing the one
92
+ * function is what keeps the SessionStart scan's targets and this module's
93
+ * launch-emptiness check from drifting into two different answers for "what
94
+ * loads at launch". See src/claude-context.mjs for why this is the shallow
95
+ * launch scope and not a whole-tree walk.
96
+ * @param {string} dir
97
+ * @returns {string[]}
98
+ */
99
+ export function launchInstructionFiles(dir: string): string[];
77
100
  /**
78
101
  * The one-time context line for a session where no InstructionsLoaded scan ran,
79
- * or null when the scan has been seen or the notice was already surfaced this
80
- * session.
81
- *
82
- * PURE: it does not record that the notice was handed out. The caller records
83
- * separately, once the notice has actually landed in a response — a deny
84
- * assembled after this call discards the notice, and a marker written here would
85
- * have burned the session's one chance to report the loss.
102
+ * or null when the scan has been seen, the notice already ran this session, or
103
+ * neither launch nor `touchedDir` could have fired the event.
86
104
  *
87
- * The loss it names is real and otherwise invisible: SessionStart scans the
88
- * instruction files that load at launch, and everything a subdirectory loads
89
- * later is scanned by the event. No scan, and nothing says so.
105
+ * PURE for the notice: nothing is recorded until the caller confirms it landed
106
+ * in a returned response. Launch-emptiness is cached once found fixed for the
107
+ * session but `touchedDir` is re-checked every call: the claim below is about
108
+ * SUBDIRECTORY files, so an empty launch must not silence a later call whose
109
+ * tool touched a directory that DOES carry real, unscanned content.
90
110
  *
91
- * The notice names the OBSERVABLE no scan ran and all three causes, because
92
- * the marker cannot tell them apart: a host that never wired the event to
93
- * scan-loaded-instructions, a Claude Code older than EVENT_MIN_CLI_VERSION, and
94
- * the hook switched off in AGENT_SANITIZER_DISABLED_HOOKS; asserting one sends a
95
- * reader who is in another to the wrong fix. The wiring cause leads because it is
96
- * the only one the reader can repair in this session, and nothing else reports it.
97
- * @param {string} [sessionId] the harness's session identity, so the answer
98
- * belongs to THIS session (see instructionsLoadedFile)
111
+ * SessionStart scans what loads at launch; a subdirectory's file is scanned by
112
+ * the event; no scan means nothing says so unless nothing touched so far had
113
+ * anything to scan either. The notice names all three remaining causes, since
114
+ * the marker cannot tell them apart: an unwired event, a Claude Code older than
115
+ * EVENT_MIN_CLI_VERSION, or the hook disabled via AGENT_SANITIZER_DISABLED_HOOKS.
116
+ * @param {string} [sessionId] the harness's session identity (see
117
+ * instructionsLoadedFile)
118
+ * @param {string} [dir] the project root to check (injectable; defaults to
119
+ * the real project)
120
+ * @param {string} [touchedDir] this tool call's own target directory, when
121
+ * known — re-checked every call, never cached
99
122
  * @returns {string | null}
100
123
  */
101
- export function instructionsLoadedGapNotice(sessionId?: string): string | null;
124
+ export function instructionsLoadedGapNotice(sessionId?: string, dir?: string, touchedDir?: string): string | null;
102
125
  /**
103
126
  * Record that the gap notice above was surfaced, so it rides on ONE tool call
104
127
  * rather than every one — the per-call repeat is what trains a reader to skip it.
@@ -116,9 +116,9 @@ export function decodeRun(run: string): {
116
116
  * files load when a tool reads their directory, and scan-loaded-instructions
117
117
  * scans each one at that moment.
118
118
  *
119
- * The scope itself which globs, and which directories the walk must prune is
120
- * the library's (see src/claude-context.mjs for why it is imported relatively
121
- * rather than through the `agent-sanitizer` specifier the plugin bundle pins).
119
+ * lib/invisible-alert.mjs's `launchInstructionFiles` IS this functionshared
120
+ * so its InstructionsLoaded gap-notice check reads the identical target set
121
+ * this scan does, rather than a second enumeration that could drift.
122
122
  * @param {string} dir
123
123
  * @returns {string[]}
124
124
  */