agent-sanitizer 2.68.0 → 2.69.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/README.md +8 -6
- package/THREAT-MODEL.md +31 -18
- package/claude-hooks/lib/hook-fault.mjs +25 -2
- package/claude-hooks/lib/hook-io.mjs +103 -10
- package/claude-hooks/lib/invisible-alert.mjs +65 -21
- package/claude-hooks/lib/secret-drop-guard.mjs +136 -29
- package/claude-hooks/plugin-hooks.mjs +29 -24
- package/claude-hooks/pretooluse-sanitize.mjs +288 -62
- package/claude-hooks/sanitize-user-prompt.mjs +28 -15
- package/claude-hooks/scan-invisible-chars.mjs +118 -42
- package/claude-hooks/scan-loaded-instructions.mjs +36 -27
- package/package.json +1 -1
- package/src/html.mjs +17 -17
- package/src/output.mjs +5 -4
- package/src/rehydrate.mjs +36 -9
- package/types/claude-hooks/lib/hook-fault.d.mts +16 -2
- package/types/claude-hooks/lib/hook-io.d.mts +41 -6
- package/types/claude-hooks/lib/invisible-alert.d.mts +21 -7
- package/types/claude-hooks/lib/secret-drop-guard.d.mts +77 -9
- package/types/claude-hooks/pretooluse-sanitize.d.mts +28 -10
- package/types/claude-hooks/sanitize-user-prompt.d.mts +3 -2
- package/types/claude-hooks/scan-invisible-chars.d.mts +3 -3
- package/types/rehydrate.d.mts +8 -1
package/README.md
CHANGED
|
@@ -138,9 +138,10 @@ composed against the redacted view are re-anchored onto the real bytes, and
|
|
|
138
138
|
placeholders in new content resolve back to the real secrets — disk → tool
|
|
139
139
|
input only, never into the model's view. Anything ambiguous is denied rather
|
|
140
140
|
than guessed, the redactor's own map is verified against the file before any
|
|
141
|
-
splice, and a write that would persist placeholder text over a real secret
|
|
142
|
-
|
|
143
|
-
|
|
141
|
+
splice, and a write that would persist placeholder text over a real secret is
|
|
142
|
+
refused once, even when the hook's own machinery fails mid-session, and proceeds
|
|
143
|
+
with a warning when re-issued. The whole layer is opt-in — its denies and asks
|
|
144
|
+
are friction, so it
|
|
144
145
|
engages only when asked for: set `AGENT_SANITIZER_SECRETS_ENABLED=1` in the
|
|
145
146
|
environment Claude Code runs the hooks with; unset, no redactor runs and no
|
|
146
147
|
placeholders exist.
|
|
@@ -193,9 +194,10 @@ withholds a string-shaped response; the shell arm in `plugin/scripts/safe-launch
|
|
|
193
194
|
therefore also emits a top-level `decision`/`reason` pair, honored whatever
|
|
194
195
|
shape the response had, telling the model that any output still visible above
|
|
195
196
|
it is unsanitized. One carve-out to the
|
|
196
|
-
open default, with secrets enabled: a write-shaped call carrying `[REDACTED…]`
|
|
197
|
-
|
|
198
|
-
through would overwrite the real secret with the placeholder
|
|
197
|
+
open default, with secrets enabled: a write-shaped call carrying `[REDACTED…]`
|
|
198
|
+
placeholder text is refused once when the hook itself is broken, since letting
|
|
199
|
+
it through would overwrite the real secret with the placeholder; the exact
|
|
200
|
+
re-issue proceeds with a warning. Either way, a plugin that
|
|
199
201
|
never loaded at all is invisible — Claude Code reads a crashed hook as "no
|
|
200
202
|
objection" — so confirm with `/plugin` rather than reading a quiet session as a
|
|
201
203
|
working one. Neither posture touches what a sanitizer that RAN decided (see
|
package/THREAT-MODEL.md
CHANGED
|
@@ -960,20 +960,28 @@ parsed, and a layer that ran and threw.
|
|
|
960
960
|
One carve-out: when the PreToolUse hook itself fails (redactor daemon down,
|
|
961
961
|
package failed to load, a layer threw) and the call is a **write-shaped tool**
|
|
962
962
|
(Write/Edit/MultiEdit/NotebookEdit) whose input carries the `[REDACTED`
|
|
963
|
-
placeholder prefix, the hook **
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
963
|
+
placeholder prefix, the hook **refuses it once** instead of passing it through.
|
|
964
|
+
With the sanitizer down, rehydration cannot run, so the placeholder text would be
|
|
965
|
+
persisted literally over the real secret on disk: a destructive clobber, not a
|
|
966
|
+
missed scan. The refusal is releasable, never a loop: the exact same call
|
|
967
|
+
re-issued is let through with a warning that the placeholder was written
|
|
968
|
+
literally, and when the hook cannot record that confirmation (an unwritable
|
|
969
|
+
`$TMPDIR`) it lets the call through at once with the warning. The same rule
|
|
970
|
+
covers a write whose placeholder cannot be restored — a Layer-2 span missing
|
|
971
|
+
from the store, an unreadable target, a redactor map that fails validation.
|
|
972
|
+
Releasing an unhinted Edit on a file whose redactor map fails validation reopens
|
|
973
|
+
the hidden-span probing oracle the rehydrator closes, at the price of one refusal
|
|
974
|
+
per distinct probe, for as long as the redactor stays broken. An unhinted Write
|
|
975
|
+
there skips the secret-drop guard, which reads the same broken map, so its
|
|
976
|
+
refusal and warning say instead that any redacted secret it omits is removed. The check is
|
|
977
|
+
package-free (a literal-string test on the already-parsed payload), so
|
|
970
978
|
it holds even when the failure IS the missing package. Two accepted gaps: a
|
|
971
979
|
launcher-level failure (no `node`, corrupt bundle, a provisioned hook binary
|
|
972
980
|
that is missing, unexecutable or dies without a verdict) never reaches the
|
|
973
981
|
check — the launcher cannot inspect the payload and always warns — and `Bash`
|
|
974
982
|
is excluded even though shell redirection can also persist placeholder text,
|
|
975
|
-
because command strings mention `[REDACTED` benignly far too often for the
|
|
976
|
-
to hold precision. All other faults keep the open default, and
|
|
983
|
+
because command strings mention `[REDACTED` benignly far too often for the
|
|
984
|
+
refusal to hold precision. All other faults keep the open default, and
|
|
977
985
|
`AGENT_SANITIZER_FAIL_OPEN=0` behavior is unchanged.
|
|
978
986
|
|
|
979
987
|
**The open default is not enforceable against content.** Several of those
|
|
@@ -1005,13 +1013,13 @@ in `claude-hooks/sanitize-output.mjs` — so a host that wires those directly (a
|
|
|
1005
1013
|
`test/downstream-parity.test.mjs` shows) keeps strict failure semantics by
|
|
1006
1014
|
construction, with no env var to remember and none an agent could set for it.
|
|
1007
1015
|
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1016
|
+
The posture does NOT reach **detection verdicts**: it speaks only to the hook
|
|
1017
|
+
FAILING, and a working sanitizer that found an injection blocks under both
|
|
1018
|
+
settings. It does reach an unknown `--hook=` mode — static wiring corruption,
|
|
1019
|
+
from a `hooks.json` and bundle out of step: under the open default that hook
|
|
1020
|
+
exits non-blocking with a stderr line naming the mode and the fix, so every
|
|
1021
|
+
event it fires on reports the gap loudly instead of blocking the session, and
|
|
1022
|
+
under `=0` it exits 2.
|
|
1015
1023
|
|
|
1016
1024
|
The knob is operator configuration read from the process environment, so
|
|
1017
1025
|
anything that can set it for a session — `.claude/settings.json`'s `env` block,
|
|
@@ -1046,8 +1054,13 @@ extracts by walking the TypeScript AST of every shipped `.mjs` (not by matching
|
|
|
1046
1054
|
regex source with a regex), and fails on any pattern with super-linear
|
|
1047
1055
|
backtracking. A `RegExp(…)` built at runtime must be statically resolvable or
|
|
1048
1056
|
carry a written exemption, so a new dynamic pattern is a red build rather than a
|
|
1049
|
-
hole.
|
|
1050
|
-
|
|
1057
|
+
hole. No construction may read call-time data either — a parameter, tool
|
|
1058
|
+
output, `process.env` — because a pattern compiled from it is as large as that
|
|
1059
|
+
data, and past V8's size limit it throws on every call; the same walk covers a
|
|
1060
|
+
string handed to `.match`/`.matchAll`/`.search`.
|
|
1061
|
+
`tests/secrets/test_redos_static_guard.py` is the twin over the Python engine,
|
|
1062
|
+
and `tests/secrets/test_regex_size_static_guard.py` holds the Python package to
|
|
1063
|
+
the call-time rule. In `pnpm lint`, `eslint-plugin-redos` (recheck) and
|
|
1051
1064
|
`eslint-plugin-regexp`'s `no-super-linear-backtracking` and
|
|
1052
1065
|
`no-super-linear-move` read every shipped regex literal — the last of them
|
|
1053
1066
|
reports the shape that carries no backtracking at all, an **unanchored**
|
|
@@ -97,8 +97,10 @@ export const FAULT_POLICY_HOOKS = Object.freeze([
|
|
|
97
97
|
/**
|
|
98
98
|
* A hook's declared posture. There is deliberately no way for a policy to pin
|
|
99
99
|
* the CLOSED arm: AGENT_SANITIZER_FAIL_OPEN alone decides, so no hook fault can
|
|
100
|
-
* withhold a tool output
|
|
101
|
-
*
|
|
100
|
+
* withhold a tool output, block a prompt, or hold a tool call for good unless the
|
|
101
|
+
* operator set the knob to `0` (an open arm may refuse a call once, releasing the
|
|
102
|
+
* exact re-issue). A pin turns any bug in the guarded layer into every tool call
|
|
103
|
+
* failing.
|
|
102
104
|
* @typedef {{
|
|
103
105
|
* event: string | null,
|
|
104
106
|
* guarded: string,
|
|
@@ -167,6 +169,27 @@ export function defaultOpen(ctx) {
|
|
|
167
169
|
return { fields: { additionalContext: ctx.openContext } };
|
|
168
170
|
}
|
|
169
171
|
|
|
172
|
+
/**
|
|
173
|
+
* The parts of a warning for an event that cannot block (SessionStart,
|
|
174
|
+
* InstructionsLoaded): `text` goes to the operator's stderr, the user
|
|
175
|
+
* (`systemMessage`) and the model (`additionalContext`), and the hook exits 0.
|
|
176
|
+
* Exit 0 because the hook ran and reached its answer. A non-zero exit with no
|
|
177
|
+
* envelope reads to the launcher as a bundle that died, which it reports as
|
|
178
|
+
* "reinstall the plugin".
|
|
179
|
+
* @param {string} event the hook's event name
|
|
180
|
+
* @param {string} text
|
|
181
|
+
* @returns {FaultParts}
|
|
182
|
+
*/
|
|
183
|
+
export function advisoryParts(event, text) {
|
|
184
|
+
return {
|
|
185
|
+
stderr: `${text}\n`,
|
|
186
|
+
envelope: {
|
|
187
|
+
systemMessage: text,
|
|
188
|
+
hookSpecificOutput: { hookEventName: event, additionalContext: text },
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
170
193
|
/**
|
|
171
194
|
* Resolve `hook`'s response to its own failure under the caller's posture. This
|
|
172
195
|
* is the ONLY place {@link failOpenEnabled} is consulted on a hook fault, so the
|
|
@@ -680,6 +680,77 @@ export function emitHookResponse(hookEventName, fields) {
|
|
|
680
680
|
);
|
|
681
681
|
}
|
|
682
682
|
|
|
683
|
+
/**
|
|
684
|
+
* Fold several hook envelopes into the ONE that may reach stdout: `systemMessage`
|
|
685
|
+
* and `additionalContext` are joined (a later part is appended, never allowed to
|
|
686
|
+
* displace an earlier one); any other field takes the last value written.
|
|
687
|
+
* @param {Array<Record<string, any>>} envelopes non-empty
|
|
688
|
+
* @returns {Record<string, any>}
|
|
689
|
+
*/
|
|
690
|
+
function mergeEnvelopes(envelopes) {
|
|
691
|
+
/** @type {Record<string, any>} */
|
|
692
|
+
const merged = {};
|
|
693
|
+
/** @type {Record<string, any>} */
|
|
694
|
+
const specific = {};
|
|
695
|
+
/** @type {string[]} */
|
|
696
|
+
const systemMessages = [];
|
|
697
|
+
/** @type {string[]} */
|
|
698
|
+
const contexts = [];
|
|
699
|
+
for (const { hookSpecificOutput, systemMessage, ...rest } of envelopes) {
|
|
700
|
+
Object.assign(merged, rest);
|
|
701
|
+
if (systemMessage) systemMessages.push(systemMessage);
|
|
702
|
+
if (!hookSpecificOutput) continue;
|
|
703
|
+
const { additionalContext, ...fields } = hookSpecificOutput;
|
|
704
|
+
Object.assign(specific, fields);
|
|
705
|
+
if (additionalContext) contexts.push(additionalContext);
|
|
706
|
+
}
|
|
707
|
+
if (systemMessages.length > 0)
|
|
708
|
+
merged.systemMessage = systemMessages.join("\n");
|
|
709
|
+
if (contexts.length > 0) specific.additionalContext = contexts.join("\n");
|
|
710
|
+
if (Object.keys(specific).length > 0) merged.hookSpecificOutput = specific;
|
|
711
|
+
return merged;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
/**
|
|
715
|
+
* @typedef {{
|
|
716
|
+
* add: (envelope: Record<string, any>) => void,
|
|
717
|
+
* emit: (hookEventName: string, fields: Record<string, unknown>) => void,
|
|
718
|
+
* flush: () => void,
|
|
719
|
+
* }} EnvelopeBuffer
|
|
720
|
+
*/
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Collect everything a hook run wants to say on stdout and write it as exactly
|
|
724
|
+
* ONE JSON object on `flush`. Claude Code parses a hook's stdout as a single
|
|
725
|
+
* document, so two envelopes written by two reporters (a fault notice, then the
|
|
726
|
+
* slow-hook notice from the timing wrapper's `finally`) concatenate into invalid
|
|
727
|
+
* output and the host DROPS the whole response — the model never sees either
|
|
728
|
+
* warning. Every reporter in a run therefore adds here instead of writing, and
|
|
729
|
+
* the entry point flushes once, last.
|
|
730
|
+
* @param {(chunk: string) => void} [write] injectable stdout sink, for tests
|
|
731
|
+
* @returns {EnvelopeBuffer}
|
|
732
|
+
*/
|
|
733
|
+
export function createEnvelopeBuffer(
|
|
734
|
+
write = (chunk) => process.stdout.write(chunk),
|
|
735
|
+
) {
|
|
736
|
+
/** @type {Array<Record<string, any>>} */
|
|
737
|
+
const pending = [];
|
|
738
|
+
/** @param {Record<string, any>} envelope */
|
|
739
|
+
const add = (envelope) => {
|
|
740
|
+
pending.push(envelope);
|
|
741
|
+
};
|
|
742
|
+
return {
|
|
743
|
+
add,
|
|
744
|
+
emit: (hookEventName, fields) =>
|
|
745
|
+
add({ hookSpecificOutput: { hookEventName, ...fields } }),
|
|
746
|
+
flush() {
|
|
747
|
+
if (pending.length === 0) return;
|
|
748
|
+
write(JSON.stringify(mergeEnvelopes(pending)));
|
|
749
|
+
pending.length = 0;
|
|
750
|
+
},
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
|
|
683
754
|
/**
|
|
684
755
|
* The project the hooks are guarding. Every per-project $TMPDIR store is keyed to
|
|
685
756
|
* it, so it lives here — beside the other shared identity these hooks agree on —
|
|
@@ -718,7 +789,7 @@ export function resolveStateRoot(env) {
|
|
|
718
789
|
// A relative path resolves against each hook process's cwd, so two processes
|
|
719
790
|
// would disagree on the root, and it could land inside a scanned tree.
|
|
720
791
|
if (!data || !isAbsolute(data)) return tmpdir();
|
|
721
|
-
const root =
|
|
792
|
+
const root = pluginStateRoot(data);
|
|
722
793
|
for (const dir of [data, root]) {
|
|
723
794
|
try {
|
|
724
795
|
mkdirSync(dir, { mode: 0o700 });
|
|
@@ -739,6 +810,24 @@ export function resolveStateRoot(env) {
|
|
|
739
810
|
return root;
|
|
740
811
|
}
|
|
741
812
|
|
|
813
|
+
/** @param {string} data an absolute plugin data dir */
|
|
814
|
+
const pluginStateRoot = (data) => join(data, "session-state");
|
|
815
|
+
|
|
816
|
+
/**
|
|
817
|
+
* Every root a hook process given `env` can resolve STATE_ROOT to, deduplicated.
|
|
818
|
+
* Each process resolves its own root, and one whose check faulted takes $TMPDIR
|
|
819
|
+
* while the rest keep the plugin data dir, so a reader of state another hook
|
|
820
|
+
* wrote looks under each. Unchecked: the reader's own trust checks apply.
|
|
821
|
+
* @param {Record<string, string | undefined>} env
|
|
822
|
+
* @returns {string[]}
|
|
823
|
+
*/
|
|
824
|
+
export function stateRootCandidates(env) {
|
|
825
|
+
const data = env.CLAUDE_PLUGIN_DATA;
|
|
826
|
+
return data && isAbsolute(data)
|
|
827
|
+
? [pluginStateRoot(data), tmpdir()]
|
|
828
|
+
: [tmpdir()];
|
|
829
|
+
}
|
|
830
|
+
|
|
742
831
|
/** {@link resolveStateRoot} for this process, resolved once at load. */
|
|
743
832
|
export const STATE_ROOT = resolveStateRoot(process.env);
|
|
744
833
|
|
|
@@ -799,7 +888,7 @@ export function hookgateMarkerPath(
|
|
|
799
888
|
// Prefer the per-user, mode-0700 runtime dir when the harness gives an
|
|
800
889
|
// absolute one; else the world-writable /tmp, where markerIsTrusted() — not
|
|
801
890
|
// the path — defends against a squatted marker.
|
|
802
|
-
const base = runtimeDir && runtimeDir
|
|
891
|
+
const base = runtimeDir && isAbsolute(runtimeDir) ? runtimeDir : "/tmp";
|
|
803
892
|
// The flattened dir is for a human reading `ls /tmp`; the digest of the RAW
|
|
804
893
|
// dir is the identity. Flattening alone is lossy — /work/a-b, /work/a_b and
|
|
805
894
|
// "/work/a b" all collapse to one name — and two such projects on one machine
|
|
@@ -811,7 +900,7 @@ export function hookgateMarkerPath(
|
|
|
811
900
|
.digest("hex")
|
|
812
901
|
.slice(0, 8);
|
|
813
902
|
const flattened = projectDir.replace(/[^A-Za-z0-9]/g, "_");
|
|
814
|
-
return `${
|
|
903
|
+
return join(base, `${HOOKGATE_MARKER_STEM}${flattened}-${digest}`);
|
|
815
904
|
}
|
|
816
905
|
|
|
817
906
|
/**
|
|
@@ -1199,26 +1288,30 @@ export function touchLiveState(path) {
|
|
|
1199
1288
|
* file the hook's user owns. Unlink any existing entry first (removing a squatted
|
|
1200
1289
|
* symlink), then create exclusively (O_EXCL) so a symlink re-planted in the race
|
|
1201
1290
|
* window fails the open rather than being dereferenced. Content is irrelevant —
|
|
1202
|
-
* callers test only for existence — so the file is left empty.
|
|
1203
|
-
* missing/read-only $TMPDIR or a lost race
|
|
1204
|
-
*
|
|
1205
|
-
*
|
|
1291
|
+
* callers test only for existence — so the file is left empty. Never throws: a
|
|
1292
|
+
* missing/read-only $TMPDIR or a lost race leaves the sentinel absent, and the
|
|
1293
|
+
* return value says so. A caller whose refusal is released only by a later read
|
|
1294
|
+
* of this sentinel must branch on it, because a refusal that records nothing can
|
|
1295
|
+
* never be released.
|
|
1206
1296
|
* @param {string} path
|
|
1207
|
-
* @returns {
|
|
1297
|
+
* @returns {boolean} whether a sentinel this uid owns now exists at `path`
|
|
1298
|
+
* (the same test {@link markerIsTrusted} applies when a reader looks for it)
|
|
1208
1299
|
*/
|
|
1209
1300
|
export function writeSentinelFile(path) {
|
|
1210
1301
|
try {
|
|
1211
1302
|
unlinkSync(path);
|
|
1212
1303
|
} catch {
|
|
1213
1304
|
// No existing entry (the common case), or an unremovable one — either way the
|
|
1214
|
-
// exclusive create below is the real guard, and its own failure is
|
|
1305
|
+
// exclusive create below is the real guard, and its own failure is returned.
|
|
1215
1306
|
}
|
|
1216
1307
|
try {
|
|
1217
1308
|
closeSync(openSync(path, "wx"));
|
|
1218
1309
|
} catch {
|
|
1219
1310
|
// A symlink re-planted in the unlink→open window, an unwritable dir, or a
|
|
1220
|
-
// leftover entry
|
|
1311
|
+
// leftover entry.
|
|
1312
|
+
return false;
|
|
1221
1313
|
}
|
|
1314
|
+
return markerIsTrusted(path);
|
|
1222
1315
|
}
|
|
1223
1316
|
|
|
1224
1317
|
/**
|
|
@@ -36,6 +36,7 @@ import {
|
|
|
36
36
|
PROJECT_HASH,
|
|
37
37
|
scrubUntrustedText,
|
|
38
38
|
STATE_ROOT,
|
|
39
|
+
stateRootCandidates,
|
|
39
40
|
touchLiveState,
|
|
40
41
|
writeFileNoFollow,
|
|
41
42
|
writeSentinelFile,
|
|
@@ -78,6 +79,19 @@ const ALERT_STEM = ".claude-invisible-char-alert-";
|
|
|
78
79
|
*/
|
|
79
80
|
export const ALERT_BASE = join(STATE_ROOT, `${ALERT_STEM}${PROJECT_HASH}`);
|
|
80
81
|
|
|
82
|
+
/**
|
|
83
|
+
* {@link ALERT_BASE} under every root a hook of this session can resolve,
|
|
84
|
+
* this process's own first. A hook that wrote state and the gate that reads it
|
|
85
|
+
* can each have degraded to $TMPDIR while the other kept the plugin data dir.
|
|
86
|
+
*/
|
|
87
|
+
const ALERT_BASES = [
|
|
88
|
+
...new Set(
|
|
89
|
+
[STATE_ROOT, ...stateRootCandidates(process.env)].map((root) =>
|
|
90
|
+
join(root, `${ALERT_STEM}${PROJECT_HASH}`),
|
|
91
|
+
),
|
|
92
|
+
),
|
|
93
|
+
];
|
|
94
|
+
|
|
81
95
|
/**
|
|
82
96
|
* Whether `name` is a session artifact of ANY project: {@link ALERT_BASE}'s
|
|
83
97
|
* name, whatever its project hash, then `.s-`.
|
|
@@ -100,25 +114,27 @@ const isAnyProjectSessionEntry = (name) =>
|
|
|
100
114
|
* files needs neither the clear nor the ordering — past sessions' artifacts
|
|
101
115
|
* simply age out through {@link sweepStaleSessions}.
|
|
102
116
|
* @param {string} [sessionId] the harness's session identity
|
|
117
|
+
* @param {string} [base] the store's root prefix
|
|
103
118
|
* @returns {string}
|
|
104
119
|
*/
|
|
105
|
-
export function sessionPrefix(sessionId) {
|
|
120
|
+
export function sessionPrefix(sessionId, base = ALERT_BASE) {
|
|
106
121
|
// The id becomes a path component, so anything outside this class — a `/` in
|
|
107
122
|
// a hostile session id above all — is folded away rather than escaping
|
|
108
123
|
// STATE_ROOT. A host that exports no session id falls back to one shared name,
|
|
109
124
|
// whose findings and ack are bounded by FALLBACK_TTL_MS instead.
|
|
110
125
|
const key =
|
|
111
126
|
(sessionId ?? "").replace(/[^A-Za-z0-9._-]/gu, "_") || "no-session";
|
|
112
|
-
return `${
|
|
127
|
+
return `${base}.s-${key}`;
|
|
113
128
|
}
|
|
114
129
|
|
|
115
130
|
/**
|
|
116
131
|
* The directory holding this session's alert findings, one file per finding.
|
|
117
132
|
* @param {string} [sessionId]
|
|
133
|
+
* @param {string} [base] the store's root prefix
|
|
118
134
|
* @returns {string}
|
|
119
135
|
*/
|
|
120
|
-
export function alertDir(sessionId) {
|
|
121
|
-
return `${sessionPrefix(sessionId)}.alerts`;
|
|
136
|
+
export function alertDir(sessionId, base = ALERT_BASE) {
|
|
137
|
+
return `${sessionPrefix(sessionId, base)}.alerts`;
|
|
122
138
|
}
|
|
123
139
|
|
|
124
140
|
/**
|
|
@@ -137,10 +153,11 @@ export function alertAckFile(sessionId) {
|
|
|
137
153
|
* Marker the InstructionsLoaded scanner writes on every fire, so another hook
|
|
138
154
|
* can tell whether that event is being scanned at all this session.
|
|
139
155
|
* @param {string} [sessionId]
|
|
156
|
+
* @param {string} [base] the store's root prefix
|
|
140
157
|
* @returns {string}
|
|
141
158
|
*/
|
|
142
|
-
export function instructionsLoadedFile(sessionId) {
|
|
143
|
-
return `${sessionPrefix(sessionId)}.instructions-loaded`;
|
|
159
|
+
export function instructionsLoadedFile(sessionId, base = ALERT_BASE) {
|
|
160
|
+
return `${sessionPrefix(sessionId, base)}.instructions-loaded`;
|
|
144
161
|
}
|
|
145
162
|
|
|
146
163
|
/**
|
|
@@ -161,15 +178,30 @@ export function instructionsLoadedNoticeFile(sessionId) {
|
|
|
161
178
|
* it is written once at launch, so otherwise a session outliving
|
|
162
179
|
* MARKER_TTL_MS would have it swept by another session's SessionStart and read
|
|
163
180
|
* its absence as the event never having fired.
|
|
181
|
+
*
|
|
182
|
+
* A session's marker is also looked for under the other {@link ALERT_BASES},
|
|
183
|
+
* where a scanner that resolved a different STATE_ROOT wrote it. The shared
|
|
184
|
+
* no-session marker is read only under this process's root, which this
|
|
185
|
+
* process's sweep ages out; read elsewhere it could silence the notice for
|
|
186
|
+
* every later session-less run on the machine.
|
|
164
187
|
* @param {string} [sessionId]
|
|
165
188
|
* @returns {boolean}
|
|
166
189
|
*/
|
|
167
190
|
export function instructionsLoadedSeen(sessionId) {
|
|
168
191
|
const marker = instructionsLoadedFile(sessionId);
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
192
|
+
const keyed = sessionPrefix(sessionId) !== sessionPrefix();
|
|
193
|
+
if (markerIsTrusted(marker)) {
|
|
194
|
+
// Not the shared no-session marker: every session-less host would refresh
|
|
195
|
+
// it, and MARKER_TTL_MS is what keeps it from silencing every later session.
|
|
196
|
+
if (keyed) touchLiveState(marker);
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
if (!keyed) return false;
|
|
200
|
+
const elsewhere = ALERT_BASES.slice(1)
|
|
201
|
+
.map((base) => instructionsLoadedFile(sessionId, base))
|
|
202
|
+
.find((path) => markerIsTrusted(path));
|
|
203
|
+
if (elsewhere === undefined) return false;
|
|
204
|
+
touchLiveState(elsewhere);
|
|
173
205
|
return true;
|
|
174
206
|
}
|
|
175
207
|
|
|
@@ -617,28 +649,37 @@ export function recordInstructionsLoadedNotice(sessionId) {
|
|
|
617
649
|
* the one report of an unscanned instruction file unreachable. The ack stays
|
|
618
650
|
* strictly session-keyed, so the gate still asks exactly once per session. A
|
|
619
651
|
* fallback finding is read only while it is inside FALLBACK_TTL_MS, which is
|
|
620
|
-
* what keeps it from re-arming the gate for a later session.
|
|
652
|
+
* what keeps it from re-arming the gate for a later session. Both stores are
|
|
653
|
+
* read under every one of {@link ALERT_BASES}, where a writer that resolved a
|
|
654
|
+
* different STATE_ROOT left its finding.
|
|
621
655
|
* @param {string} [sessionId]
|
|
622
656
|
* @returns {string | null}
|
|
623
657
|
*/
|
|
624
658
|
export function invisibleCharAlert(sessionId) {
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
// fallback
|
|
629
|
-
|
|
659
|
+
const sessionDirs = new Set(
|
|
660
|
+
ALERT_BASES.map((base) => alertDir(sessionId, base)),
|
|
661
|
+
);
|
|
662
|
+
// A fallback store belongs to no session, so only age says whether it is
|
|
663
|
+
// still this session's business. Where the fallback IS the session's store
|
|
664
|
+
// there is nothing inherited and nothing to expire.
|
|
665
|
+
const dirs = new Set(
|
|
666
|
+
ALERT_BASES.flatMap((base) => [
|
|
667
|
+
alertDir(sessionId, base),
|
|
668
|
+
alertDir(undefined, base),
|
|
669
|
+
]),
|
|
670
|
+
);
|
|
630
671
|
const parts = [];
|
|
631
672
|
for (const dir of dirs) {
|
|
632
673
|
if (!privateDirAt(dir)) continue;
|
|
633
674
|
// A live session's findings must outlast any sweep that ages the store by
|
|
634
675
|
// its directory's timestamp: losing them lifts the gate mid-session.
|
|
635
|
-
if (dir
|
|
676
|
+
if (sessionDirs.has(dir)) touchLiveState(dir);
|
|
636
677
|
// Sorted so a multi-finding report reads the same on every call; the names
|
|
637
678
|
// are random, so the order carries no meaning beyond being stable.
|
|
638
679
|
for (const name of readdirSync(dir).sort()) {
|
|
639
680
|
const path = join(dir, name);
|
|
640
681
|
if (!markerIsTrusted(path)) continue;
|
|
641
|
-
if (dir
|
|
682
|
+
if (!sessionDirs.has(dir) && !withinFallbackTtl(path)) continue;
|
|
642
683
|
const text = readFileSync(path, "utf-8").trim();
|
|
643
684
|
if (text !== "") parts.push(text);
|
|
644
685
|
}
|
|
@@ -706,14 +747,17 @@ export function alertAcknowledged(sessionId) {
|
|
|
706
747
|
/**
|
|
707
748
|
* Record that the gate has surfaced its blocking ask, so later tool calls get a
|
|
708
749
|
* passive reminder instead of an ask on every call. Session-keyed, so the next
|
|
709
|
-
* session re-asks once without anything having to clear this.
|
|
750
|
+
* session re-asks once without anything having to clear this. Returns false
|
|
751
|
+
* when the ack could not be recorded, so the caller knows the next call will
|
|
752
|
+
* ask again: under the fail-open posture it surfaces the finding as a warning
|
|
753
|
+
* rather than asking on every tool call for the rest of the session.
|
|
710
754
|
* @param {string} [sessionId]
|
|
711
|
-
* @returns {
|
|
755
|
+
* @returns {boolean}
|
|
712
756
|
*/
|
|
713
757
|
export function acknowledgeAlert(sessionId) {
|
|
714
758
|
// Symlink-safe presence write: the ack sits at a predictable STATE_ROOT path
|
|
715
759
|
// a co-tenant could pre-plant a symlink at (see writeSentinelFile).
|
|
716
|
-
writeSentinelFile(alertAckFile(sessionId));
|
|
760
|
+
return writeSentinelFile(alertAckFile(sessionId));
|
|
717
761
|
}
|
|
718
762
|
|
|
719
763
|
// What the operator can actually DO — one bullet per kind of report the alert
|