passcontrol 1.7.2 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/passcontrol.mjs +51 -0
- package/cli/codex-hooks.mjs +2 -2
- package/cli/memory-custody-sidecar.d.mts +19 -0
- package/cli/memory-custody-sidecar.mjs +470 -0
- package/cli/memory-custody.d.mts +24 -0
- package/cli/memory-custody.mjs +444 -0
- package/cli/memory-inventory.d.mts +15 -0
- package/cli/memory-inventory.mjs +390 -0
- package/cli/memory-review.d.mts +3 -0
- package/cli/memory-review.mjs +65 -0
- package/cli/menu.mjs +1 -0
- package/cli/mission-tools.d.mts +27 -0
- package/cli/mission-tools.mjs +373 -0
- package/cli/sidecar.mjs +138 -2
- package/cli/subscription-gate.mjs +9 -1
- package/cli/tool-gate.mjs +45 -3
- package/cli/tripwire-scan.d.mts +20 -0
- package/cli/tripwire-scan.mjs +279 -0
- package/cli/tripwire-sidecar.d.mts +10 -0
- package/cli/tripwire-sidecar.mjs +84 -0
- package/cli/tripwires.d.mts +21 -0
- package/cli/tripwires.mjs +208 -0
- package/package.json +1 -1
|
@@ -0,0 +1,373 @@
|
|
|
1
|
+
// Mission-bound visas (idea 11): the LOCAL-TOOL half of a mission envelope.
|
|
2
|
+
//
|
|
3
|
+
// One file for both sides, like tool-rules.mjs: the sidecar classifies a Claude Code
|
|
4
|
+
// PreToolUse call with it, the gateway validates a mission's `tools` section with it,
|
|
5
|
+
// and the replay measurement uses the same classifier on the sanitised feed. The
|
|
6
|
+
// three can never disagree about what an item admits.
|
|
7
|
+
//
|
|
8
|
+
// ── HONEST LIMIT, said in every copy that shows this section ────────────────────
|
|
9
|
+
// Hooks are a GUARD RAIL, not a boundary. The sidecar sees what Claude Code tells
|
|
10
|
+
// it. A script file, an alias, `sh -c`, an interpreter one-liner or a process the
|
|
11
|
+
// agent starts outside Claude Code gets round anything here. The gateway is the
|
|
12
|
+
// boundary for models and services, because it holds the credential; this file
|
|
13
|
+
// only adds friction to the owner's own sessions.
|
|
14
|
+
//
|
|
15
|
+
// Item vocabulary (typed, so a whole repository is ONE item, not many paths):
|
|
16
|
+
// { kind: "workspace", root: "/abs/dir", write: bool } file tools under root
|
|
17
|
+
// { kind: "shell", class: <SHELL_CLASSES> } a class of shell command
|
|
18
|
+
// { kind: "host", host: "exact.host", via: "web"|"browser"|"shell" }
|
|
19
|
+
// { kind: "tool", name: "ExactToolName" } one named tool
|
|
20
|
+
// { kind: "memory_write" } writes to agent memory files
|
|
21
|
+
//
|
|
22
|
+
// Classes that are NEVER admitted by a template or by history, only by the owner for
|
|
23
|
+
// this one mission: network, opaque, vcs_push, rm_rf, container, memory writes (NEVER_LEARNED).
|
|
24
|
+
|
|
25
|
+
export const SHELL_CLASSES = [
|
|
26
|
+
"inspect",
|
|
27
|
+
"build",
|
|
28
|
+
"vcs_local",
|
|
29
|
+
"process",
|
|
30
|
+
"fs_mutate",
|
|
31
|
+
"container",
|
|
32
|
+
"network",
|
|
33
|
+
"opaque",
|
|
34
|
+
"vcs_push",
|
|
35
|
+
"rm_rf",
|
|
36
|
+
];
|
|
37
|
+
// container: `docker run -v /:/host` is a full escape, so a container class learned from
|
|
38
|
+
// history admitted it (red team round 1, L24 under strategy D).
|
|
39
|
+
export const NEVER_LEARNED = new Set(["shell:network", "shell:opaque", "shell:vcs_push", "shell:rm_rf", "shell:container", "memory_write"]);
|
|
40
|
+
export const HOST_VIA = ["web", "browser", "shell"];
|
|
41
|
+
|
|
42
|
+
const INSPECT = new Set(
|
|
43
|
+
"cd ls cat head tail grep rg egrep fgrep sed awk wc find echo pwd which file stat diff sort uniq cut tr jq less more tree du df date true false test [ printf basename dirname realpath readlink type command whoami uname hostname id cmp comm column nl od xxd shasum sha256sum md5 md5sum base64 strings".split(" ")
|
|
44
|
+
);
|
|
45
|
+
const BUILD = new Set(
|
|
46
|
+
"npm npx node python python3 pip pip3 tsc vitest jest make cargo go deno bun pnpm yarn pytest ruff eslint prettier psql sqlite3 swift xcodebuild gradle mvn java javac ruby bundle rake".split(" ")
|
|
47
|
+
);
|
|
48
|
+
const PROCESS = new Set("kill pkill ps lsof sleep wait jobs pgrep top fg bg disown".split(" "));
|
|
49
|
+
const FS_MUTATE = new Set("cp mv mkdir touch rm rmdir ln chmod chown tee install unzip tar gzip gunzip zip".split(" "));
|
|
50
|
+
const CONTAINER = new Set("docker docker-compose podman kubectl colima".split(" "));
|
|
51
|
+
const NETWORK = new Set("curl wget gh ssh scp sftp rsync nc ncat telnet ftp open http https dig nslookup ping".split(" "));
|
|
52
|
+
// A command that runs ANOTHER command or arbitrary code is opaque: what it does is not
|
|
53
|
+
// in its first word.
|
|
54
|
+
const OPAQUE = new Set(
|
|
55
|
+
"bash sh zsh dash fish eval exec source . env sudo doas xargs nohup timeout time watch nice osascript perl for while until if case function select coproc { (".split(" ")
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
/** Tools that act only on the agent's own task list, plans or questions to the owner. */
|
|
59
|
+
export const INTERNAL_TOOLS = new Set([
|
|
60
|
+
"TaskCreate",
|
|
61
|
+
"TaskUpdate",
|
|
62
|
+
"TaskGet",
|
|
63
|
+
"TaskList",
|
|
64
|
+
"TaskStop",
|
|
65
|
+
"TaskOutput",
|
|
66
|
+
"TodoWrite",
|
|
67
|
+
"ToolSearch",
|
|
68
|
+
"AskUserQuestion",
|
|
69
|
+
"ReadNotifications",
|
|
70
|
+
"Monitor",
|
|
71
|
+
"ListAgents",
|
|
72
|
+
"EnterPlanMode",
|
|
73
|
+
"ExitPlanMode",
|
|
74
|
+
"BashOutput",
|
|
75
|
+
"KillShell",
|
|
76
|
+
]);
|
|
77
|
+
const READ_TOOLS = new Set(["Read", "Glob", "Grep", "LS", "NotebookRead"]);
|
|
78
|
+
const WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
79
|
+
const PATH_FIELD = { Read: "file_path", Edit: "file_path", MultiEdit: "file_path", Write: "file_path", NotebookEdit: "notebook_path", Glob: "path", Grep: "path", LS: "path", NotebookRead: "notebook_path" };
|
|
80
|
+
const BROWSER_NAV = /^mcp__claude-in-chrome__navigate$/u;
|
|
81
|
+
|
|
82
|
+
const HOST = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/u;
|
|
83
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/u;
|
|
84
|
+
const MEMORY_FILE = /(?:^|\/)(?:CLAUDE\.md|CLAUDE\.local\.md|AGENTS\.md|MEMORY\.md|\.claude\/(?:settings(?:\.local)?\.json|memory\/[^/]+|agents\/[^/]+|commands\/[^/]+|skills\/.+))$/u;
|
|
85
|
+
|
|
86
|
+
const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
87
|
+
|
|
88
|
+
/** An absolute, normalised POSIX directory: no `.`/`..`, no `//`, no trailing `/`, not `/`. */
|
|
89
|
+
export function validRoot(root) {
|
|
90
|
+
if (typeof root !== "string" || root.length < 2 || root.length > 1024 || !root.startsWith("/")) return false;
|
|
91
|
+
if (root.endsWith("/") || root.includes("//") || root.includes("\\") || /[\u0000-\u001f\u007f]/u.test(root)) return false;
|
|
92
|
+
const parts = root.slice(1).split("/");
|
|
93
|
+
return parts.every((p) => p !== "" && p !== "." && p !== "..");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Lexical normalisation of an absolute path. Null when it is not absolute or escapes /. */
|
|
97
|
+
export function normalisePath(path) {
|
|
98
|
+
if (typeof path !== "string" || !path.startsWith("/") || path.length > 4096) return null;
|
|
99
|
+
if (path.includes("\\") || /[\u0000-\u001f\u007f]/u.test(path)) return null;
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const part of path.split("/")) {
|
|
102
|
+
if (part === "" || part === ".") continue;
|
|
103
|
+
if (part === "..") {
|
|
104
|
+
if (out.length === 0) return null;
|
|
105
|
+
out.pop();
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
out.push(part);
|
|
109
|
+
}
|
|
110
|
+
return `/${out.join("/")}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Is `path` (already normalised) `root` itself or under it, on a segment boundary? */
|
|
114
|
+
export function within(root, path) {
|
|
115
|
+
return path === root || path.startsWith(`${root}/`);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function normaliseHost(raw) {
|
|
119
|
+
if (typeof raw !== "string") return null;
|
|
120
|
+
let host = raw.trim().toLowerCase();
|
|
121
|
+
if (host.endsWith(".")) host = host.slice(0, -1);
|
|
122
|
+
return HOST.test(host) ? host : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A single tool item, validated. Returns a fresh canonical object or null. */
|
|
126
|
+
export function parseToolItem(item) {
|
|
127
|
+
if (!isRecord(item)) return null;
|
|
128
|
+
const keys = Object.keys(item).sort().join(",");
|
|
129
|
+
switch (item.kind) {
|
|
130
|
+
case "workspace":
|
|
131
|
+
if (keys !== "kind,root,write" || !validRoot(item.root) || typeof item.write !== "boolean") return null;
|
|
132
|
+
return { kind: "workspace", root: item.root, write: item.write };
|
|
133
|
+
case "shell":
|
|
134
|
+
if (keys !== "class,kind" || !SHELL_CLASSES.includes(item.class)) return null;
|
|
135
|
+
return { kind: "shell", class: item.class };
|
|
136
|
+
case "host":
|
|
137
|
+
if (keys !== "host,kind,via" || !HOST_VIA.includes(item.via)) return null;
|
|
138
|
+
if (typeof item.host !== "string" || normaliseHost(item.host) !== item.host) return null;
|
|
139
|
+
return { kind: "host", host: item.host, via: item.via };
|
|
140
|
+
case "tool":
|
|
141
|
+
if (keys !== "kind,name" || typeof item.name !== "string" || !TOOL_NAME.test(item.name)) return null;
|
|
142
|
+
return { kind: "tool", name: item.name };
|
|
143
|
+
case "memory_write":
|
|
144
|
+
if (keys !== "kind") return null;
|
|
145
|
+
return { kind: "memory_write" };
|
|
146
|
+
default:
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Does item `outer` admit everything item `inner` admits? Conservative: unknown → false. */
|
|
152
|
+
export function toolItemContains(outer, inner) {
|
|
153
|
+
if (!outer || !inner || outer.kind !== inner.kind) return false;
|
|
154
|
+
switch (outer.kind) {
|
|
155
|
+
case "workspace":
|
|
156
|
+
return within(outer.root, inner.root) && (outer.write || !inner.write);
|
|
157
|
+
case "shell":
|
|
158
|
+
return outer.class === inner.class;
|
|
159
|
+
case "host":
|
|
160
|
+
return outer.host === inner.host && outer.via === inner.via;
|
|
161
|
+
case "tool":
|
|
162
|
+
return outer.name === inner.name;
|
|
163
|
+
case "memory_write":
|
|
164
|
+
return true;
|
|
165
|
+
default:
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A stable key for an item, used for sets and for "learned from history". */
|
|
171
|
+
export function toolItemKey(item) {
|
|
172
|
+
switch (item.kind) {
|
|
173
|
+
case "workspace":
|
|
174
|
+
return `workspace:${item.write ? "rw" : "r"}:${item.root}`;
|
|
175
|
+
case "shell":
|
|
176
|
+
return `shell:${item.class}`;
|
|
177
|
+
case "host":
|
|
178
|
+
return `host:${item.via}:${item.host}`;
|
|
179
|
+
case "tool":
|
|
180
|
+
return `tool:${item.name}`;
|
|
181
|
+
case "memory_write":
|
|
182
|
+
return "memory_write";
|
|
183
|
+
default:
|
|
184
|
+
return "unknown";
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** The shell class of one simple command's first word (after assignments). */
|
|
189
|
+
export function shellClassOf(word) {
|
|
190
|
+
if (typeof word !== "string" || word === "") return "opaque";
|
|
191
|
+
const base = word.includes("/") ? word.slice(word.lastIndexOf("/") + 1) : word;
|
|
192
|
+
if (base === "git") return "vcs_local";
|
|
193
|
+
if (INSPECT.has(base)) return "inspect";
|
|
194
|
+
if (BUILD.has(base)) return "build";
|
|
195
|
+
if (PROCESS.has(base)) return "process";
|
|
196
|
+
if (FS_MUTATE.has(base)) return "fs_mutate";
|
|
197
|
+
if (CONTAINER.has(base)) return "container";
|
|
198
|
+
if (NETWORK.has(base)) return "network";
|
|
199
|
+
if (OPAQUE.has(base)) return "opaque";
|
|
200
|
+
return "opaque";
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/u;
|
|
204
|
+
// An interpreter handed code inline runs whatever that code says, so it is opaque, not
|
|
205
|
+
// a build step (red team round 1: `python3 -c "urlopen(evil)"` was admitted as build).
|
|
206
|
+
const INTERPRETERS = new Set(["python", "python3", "node", "perl", "ruby", "php", "deno", "bun", "osascript", "pwsh", "powershell"]);
|
|
207
|
+
const INLINE_CODE = new Set(["-c", "-e", "--eval", "-p", "--print", "-r", "-m", "-E", "-x", "eval", "--command"]);
|
|
208
|
+
const REDIRECT = /^(?:\d?[<>]{1,2}|&>|<<<?)$/u;
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Does an interpreter invocation run code the hook cannot see in its arguments?
|
|
212
|
+
* Inline code (-c, -e, --eval=…, combined -Ic), code from STDIN (no script argument,
|
|
213
|
+
* `-`, /dev/stdin: `echo … | python3`, `python3 - < x`), or code from a URL
|
|
214
|
+
* (`deno run https://…`). Red team round 3 found the stdin and URL forms admitted as
|
|
215
|
+
* build. A script FILE (`python3 x.py`) stays build: what the file does is the named
|
|
216
|
+
* guard-rail limit (RED-TEAM.md L30).
|
|
217
|
+
*/
|
|
218
|
+
function interpreterRunsUnseenCode(rest) {
|
|
219
|
+
if (rest.length === 1 && ["--version", "-v", "-V", "--help"].includes(rest[0])) return false;
|
|
220
|
+
if (rest.some((a) => INLINE_CODE.has(a) || /^-[a-zA-Z]*[ce]$/u.test(a) || /^--(?:eval|print|command)=/u.test(a))) return true;
|
|
221
|
+
if (rest.some((a) => /^['"]?https?:\/\//u.test(a))) return true;
|
|
222
|
+
const positional = [];
|
|
223
|
+
for (let i = 0; i < rest.length; i++) {
|
|
224
|
+
const a = rest[i];
|
|
225
|
+
if (REDIRECT.test(a)) {
|
|
226
|
+
i++; // the redirect's target is not a script
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (/^[<>]/u.test(a)) continue; // `<file` written without a space
|
|
230
|
+
if (a.startsWith("-") && a !== "-") continue;
|
|
231
|
+
positional.push(a);
|
|
232
|
+
}
|
|
233
|
+
if (positional.length === 0) return true;
|
|
234
|
+
// `deno run x.ts`, `bun run x`: the subcommand is not the script.
|
|
235
|
+
const script = ["run", "x", "exec"].includes(positional[0]) ? positional[1] : positional[0];
|
|
236
|
+
return script === undefined || script === "-" || script === "/dev/stdin";
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Split a shell command into simple commands and classify each. Deliberately
|
|
241
|
+
* pessimistic: command substitution, backticks, process substitution, a heredoc or
|
|
242
|
+
* an unbalanced quote make the WHOLE command opaque, because what runs is not in
|
|
243
|
+
* the words we can see. Returns the set of items the command needs.
|
|
244
|
+
*/
|
|
245
|
+
export function classifyShell(command) {
|
|
246
|
+
const items = new Map();
|
|
247
|
+
const add = (cls) => items.set(`shell:${cls}`, { kind: "shell", class: cls });
|
|
248
|
+
if (typeof command !== "string" || command.length === 0 || command.length > 100_000) {
|
|
249
|
+
add("opaque");
|
|
250
|
+
return [...items.values()];
|
|
251
|
+
}
|
|
252
|
+
if (/\$\(|`|<\(|>\(|<<|\beval\b/u.test(command)) add("opaque");
|
|
253
|
+
// Quote-aware split on ; & | && || and newlines.
|
|
254
|
+
const segments = [];
|
|
255
|
+
let current = "";
|
|
256
|
+
let quote = null;
|
|
257
|
+
for (let i = 0; i < command.length; i++) {
|
|
258
|
+
const c = command[i];
|
|
259
|
+
if (quote) {
|
|
260
|
+
if (c === quote) quote = null;
|
|
261
|
+
else if (c === "\\" && quote === '"') {
|
|
262
|
+
current += c + (command[i + 1] ?? "");
|
|
263
|
+
i++;
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
current += c;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
if (c === "'" || c === '"') {
|
|
270
|
+
quote = c;
|
|
271
|
+
current += c;
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (c === "\\") {
|
|
275
|
+
current += c + (command[i + 1] ?? "");
|
|
276
|
+
i++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (c === ";" || c === "&" || c === "|" || c === "\n") {
|
|
280
|
+
segments.push(current);
|
|
281
|
+
current = "";
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
current += c;
|
|
285
|
+
}
|
|
286
|
+
if (quote) add("opaque");
|
|
287
|
+
segments.push(current);
|
|
288
|
+
for (const segment of segments) {
|
|
289
|
+
const words = segment.trim().split(/\s+/u).filter(Boolean);
|
|
290
|
+
let w = 0;
|
|
291
|
+
while (w < words.length && ASSIGNMENT.test(words[w])) w++;
|
|
292
|
+
if (w >= words.length) continue; // assignments only, or empty
|
|
293
|
+
const first = words[w].replace(/^['"]|['"]$/gu, "");
|
|
294
|
+
const rest = words.slice(w + 1);
|
|
295
|
+
const base = first.includes("/") ? first.slice(first.lastIndexOf("/") + 1) : first;
|
|
296
|
+
const inline = INTERPRETERS.has(base) && interpreterRunsUnseenCode(rest);
|
|
297
|
+
const cls = inline ? "opaque" : shellClassOf(first);
|
|
298
|
+
if (first === "git" && rest.includes("push")) add("vcs_push");
|
|
299
|
+
else if ((first === "rm" || first.endsWith("/rm")) && rest.some((a) => /^-[a-zA-Z]*[rR][a-zA-Z]*$/u.test(a) || a === "--recursive")) add("rm_rf");
|
|
300
|
+
else add(cls);
|
|
301
|
+
if (cls === "network") {
|
|
302
|
+
for (const arg of rest) {
|
|
303
|
+
const m = /^['"]?https?:\/\/([^/:'"\s?#]+)/u.exec(arg);
|
|
304
|
+
const host = m ? normaliseHost(m[1]) : null;
|
|
305
|
+
if (host) items.set(`host:shell:${host}`, { kind: "host", host, via: "shell" });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
// An append or write to a memory file through the shell.
|
|
309
|
+
if (rest.some((a, i) => (a === ">>" || a === ">") && MEMORY_FILE.test(rest[i + 1] ?? "")) || rest.some((a) => /^>>?\S/u.test(a) && MEMORY_FILE.test(a.replace(/^>>?/u, "")))) {
|
|
310
|
+
items.set("memory_write", { kind: "memory_write" });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
if (items.size === 0) add("inspect");
|
|
314
|
+
return [...items.values()];
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Every item a PreToolUse call needs. A call with no recognisable shape needs the
|
|
319
|
+
* item for its tool name, so an unknown tool is held until the owner names it.
|
|
320
|
+
*/
|
|
321
|
+
export function itemsForToolCall(input) {
|
|
322
|
+
const tool = typeof input?.tool_name === "string" ? input.tool_name : "";
|
|
323
|
+
const ti = isRecord(input?.tool_input) ? input.tool_input : {};
|
|
324
|
+
if (tool === "Bash") return classifyShell(typeof ti.command === "string" ? ti.command : "");
|
|
325
|
+
if (READ_TOOLS.has(tool) || WRITE_TOOLS.has(tool)) {
|
|
326
|
+
const field = PATH_FIELD[tool];
|
|
327
|
+
const raw = typeof ti[field] === "string" ? ti[field] : READ_TOOLS.has(tool) && tool !== "Read" ? null : "";
|
|
328
|
+
const write = WRITE_TOOLS.has(tool);
|
|
329
|
+
if (raw === null) return [{ kind: "tool", name: tool }]; // Glob/Grep with no path: the cwd, unknown here
|
|
330
|
+
const path = normalisePath(raw);
|
|
331
|
+
if (path === null) return [{ kind: "tool", name: `${tool}:unresolved-path` }];
|
|
332
|
+
const items = [{ kind: "workspace", root: path, write }];
|
|
333
|
+
if (write && MEMORY_FILE.test(path)) items.push({ kind: "memory_write" });
|
|
334
|
+
return items;
|
|
335
|
+
}
|
|
336
|
+
if (tool === "WebFetch") {
|
|
337
|
+
let host = null;
|
|
338
|
+
try {
|
|
339
|
+
host = normaliseHost(new URL(String(ti.url ?? "")).hostname);
|
|
340
|
+
} catch {
|
|
341
|
+
host = null;
|
|
342
|
+
}
|
|
343
|
+
return [host ? { kind: "host", host, via: "web" } : { kind: "tool", name: "WebFetch:unresolved-host" }];
|
|
344
|
+
}
|
|
345
|
+
if (BROWSER_NAV.test(tool)) {
|
|
346
|
+
let host = null;
|
|
347
|
+
try {
|
|
348
|
+
host = normaliseHost(new URL(String(ti.url ?? "")).hostname);
|
|
349
|
+
} catch {
|
|
350
|
+
host = null;
|
|
351
|
+
}
|
|
352
|
+
return [host ? { kind: "host", host, via: "browser" } : { kind: "tool", name: `${tool}:unresolved-host` }];
|
|
353
|
+
}
|
|
354
|
+
if (TOOL_NAME.test(tool)) return [{ kind: "tool", name: tool }];
|
|
355
|
+
return [{ kind: "tool", name: "unknown-tool" }];
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Items a mission admits for free: the agent's own task list. Never effects. */
|
|
359
|
+
export function internalItem(item) {
|
|
360
|
+
return item.kind === "tool" && INTERNAL_TOOLS.has(item.name);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The decision for a tool call against a mission's `tools` section.
|
|
365
|
+
* `inside` when every needed item is contained in some mission item; otherwise
|
|
366
|
+
* `outside` with the items that were missing. Workspace items of the CALL carry the
|
|
367
|
+
* exact path as `root`, so containment is "the path is under an admitted root".
|
|
368
|
+
*/
|
|
369
|
+
export function evaluateMissionTools(missionTools, input) {
|
|
370
|
+
const needed = itemsForToolCall(input);
|
|
371
|
+
const missing = needed.filter((n) => !internalItem(n) && !missionTools.some((m) => toolItemContains(m, n)));
|
|
372
|
+
return missing.length ? { state: "outside", missing } : { state: "inside", missing: [] };
|
|
373
|
+
}
|
package/cli/sidecar.mjs
CHANGED
|
@@ -9,12 +9,15 @@ import { declaredLineage, declaredSession } from "./declared-session.mjs";
|
|
|
9
9
|
import { defaultJournalDir, openJournal } from "./journal.mjs";
|
|
10
10
|
import { heldUnderTaint } from "./injection-hold.mjs";
|
|
11
11
|
import { findingsFromHook, gapFromOversizedHook } from "./injection-sidecar.mjs";
|
|
12
|
+
import { plantedDigests } from "./tripwires.mjs";
|
|
13
|
+
import { createTripwireReporter, decoyInHeaders, decoysInHook, TRIPWIRE_PATH } from "./tripwire-sidecar.mjs";
|
|
12
14
|
import { answer, createWatchFeed, hostIsThisListener, isNotACall, isLocalCaller, LOCAL_PREFIX, peekText, providerOf, refusalCode, requestModel } from "./watch-feed.mjs";
|
|
13
15
|
import { createStopGate, HOOK_PATH, SELF_READ_TIMEOUT_MS, selfAnswerState } from "./subscription-gate.mjs";
|
|
14
16
|
import { createToolGate } from "./tool-gate.mjs";
|
|
15
17
|
import { OTLP_LOGS_PATH, readClaudeCodeEvents } from "./otlp-logs.mjs";
|
|
16
18
|
import { CLIENT_EVENTS_PATH, CLIENT_EVENTS_SOURCE, createCallUploader } from "./client-events-upload.mjs";
|
|
17
19
|
import { heldUsageWindow, WINDOW_PATH } from "./usage-window.mjs";
|
|
20
|
+
import { createMemoryCustody } from "./memory-custody-sidecar.mjs";
|
|
18
21
|
|
|
19
22
|
// Hop-by-hop headers plus the ones the sidecar rebuilds itself. `proxy-connection`
|
|
20
23
|
// and friends only appear once something is used as a FORWARD proxy, which is
|
|
@@ -158,6 +161,9 @@ export function createSidecar({
|
|
|
158
161
|
// Subscription mode, Phase 1b: upload the calls Claude Code reports to the
|
|
159
162
|
// gateway's agent page (cli/client-events-upload.mjs). `--no-report-calls` turns it off.
|
|
160
163
|
reportCalls = true,
|
|
164
|
+
// Idea 12: the digests of the decoys `configure tripwires` planted on this machine.
|
|
165
|
+
// Read once at start; a re-run of configure takes effect on the next sidecar start.
|
|
166
|
+
tripwireDigests = plantedDigests(),
|
|
161
167
|
}) {
|
|
162
168
|
// The upstream URL below is built from this, not from the argument: the
|
|
163
169
|
// sidecar forwards a bearer visa on every proxied request, so its destination
|
|
@@ -216,6 +222,7 @@ export function createSidecar({
|
|
|
216
222
|
})]);
|
|
217
223
|
const answer = await Promise.race([deadline, selfAnswerState(response)]);
|
|
218
224
|
if (answer.state === "open") {
|
|
225
|
+
memoryCustody.setView(answer.memory);
|
|
219
226
|
readHighVersion = Math.max(readHighVersion, highAtStart);
|
|
220
227
|
readRelayVersion = Math.max(readRelayVersion, relayAtStart);
|
|
221
228
|
if (answer.injection?.mode === "hold" && !reportCalls && !holdOptOutWarned) {
|
|
@@ -230,6 +237,29 @@ export function createSidecar({
|
|
|
230
237
|
}
|
|
231
238
|
const stopGate = createStopGate({ readSelf, dashboardUrl: `${origin}/dashboard` });
|
|
232
239
|
|
|
240
|
+
// Idea 13: memory custody (cli/memory-custody-sidecar.mjs). Hashes and kinds only.
|
|
241
|
+
const MEMORY_CUSTODY_PATH = "/api/v1/memory-custody";
|
|
242
|
+
const MEMORY_CUSTODY_TIMEOUT_MS = 4_000;
|
|
243
|
+
async function sendMemoryCustody(payload) {
|
|
244
|
+
const response = await visas.fetchWithVisa((visa) =>
|
|
245
|
+
fetch(`${origin}${MEMORY_CUSTODY_PATH}`, {
|
|
246
|
+
method: "POST",
|
|
247
|
+
redirect: "manual",
|
|
248
|
+
headers: {
|
|
249
|
+
"content-type": "application/json",
|
|
250
|
+
authorization: `Bearer ${visa}`,
|
|
251
|
+
"x-passcontrol-run": runId,
|
|
252
|
+
"x-passcontrol-proof": visas.createProof(visa, "POST", new URL(MEMORY_CUSTODY_PATH, origin)),
|
|
253
|
+
"accept-encoding": "identity",
|
|
254
|
+
},
|
|
255
|
+
body: JSON.stringify(payload),
|
|
256
|
+
signal: AbortSignal.timeout(MEMORY_CUSTODY_TIMEOUT_MS),
|
|
257
|
+
})
|
|
258
|
+
);
|
|
259
|
+
return { status: response.status, body: await response.json().catch(() => null) };
|
|
260
|
+
}
|
|
261
|
+
const memoryCustody = createMemoryCustody({ send: sendMemoryCustody, onWarn: (m) => warn(m) });
|
|
262
|
+
|
|
233
263
|
// Phase 2's `ask_owner` tool rules: the gateway asks the owner (their alert
|
|
234
264
|
// destination is in its Vault) and holds each request a few seconds; this asks
|
|
235
265
|
// again until the owner answers or the tool gate's wait runs out.
|
|
@@ -311,6 +341,36 @@ export function createSidecar({
|
|
|
311
341
|
}
|
|
312
342
|
const injectionSeen = new Set();
|
|
313
343
|
const uploader = reportCalls ? createCallUploader({ send: sendReportedCalls }) : null;
|
|
344
|
+
// Idea 12. Reports go as this agent, through the same visa path as every upload.
|
|
345
|
+
async function sendTripwire(body) {
|
|
346
|
+
const response = await visas.fetchWithVisa((visa) =>
|
|
347
|
+
fetch(`${origin}${TRIPWIRE_PATH}`, {
|
|
348
|
+
method: "POST",
|
|
349
|
+
redirect: "manual",
|
|
350
|
+
headers: {
|
|
351
|
+
"content-type": "application/json",
|
|
352
|
+
authorization: `Bearer ${visa}`,
|
|
353
|
+
"x-passcontrol-run": runId,
|
|
354
|
+
"x-passcontrol-proof": visas.createProof(visa, "POST", new URL(TRIPWIRE_PATH, origin)),
|
|
355
|
+
"accept-encoding": "identity",
|
|
356
|
+
},
|
|
357
|
+
body: JSON.stringify(body),
|
|
358
|
+
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
|
|
359
|
+
})
|
|
360
|
+
);
|
|
361
|
+
return { status: response.status };
|
|
362
|
+
}
|
|
363
|
+
const tripwires = tripwireDigests.size > 0 ? createTripwireReporter({ send: sendTripwire }) : null;
|
|
364
|
+
const lastTools = [];
|
|
365
|
+
const TOOL_NAME = /^[A-Za-z0-9_.-]{1,128}$/;
|
|
366
|
+
function noteTools(input) {
|
|
367
|
+
const calls = input.hook_event_name === "PostToolBatch" && Array.isArray(input.tool_calls) ? input.tool_calls : [input];
|
|
368
|
+
for (const c of calls) {
|
|
369
|
+
if (typeof c?.tool_name === "string" && TOOL_NAME.test(c.tool_name)) lastTools.push(c.tool_name);
|
|
370
|
+
}
|
|
371
|
+
while (lastTools.length > 5) lastTools.shift();
|
|
372
|
+
}
|
|
373
|
+
const recentTools = () => [...lastTools];
|
|
314
374
|
// Its decisions reach the agent's page with the reported calls (same opt-out).
|
|
315
375
|
const toolGate = createToolGate({
|
|
316
376
|
askOwner,
|
|
@@ -444,6 +504,22 @@ export function createSidecar({
|
|
|
444
504
|
res.end();
|
|
445
505
|
}
|
|
446
506
|
|
|
507
|
+
// Idea 13: `passcontrol memory review` asks here, from this machine only.
|
|
508
|
+
const MEMORY_REVIEW_PATH = "/_passcontrol/memory";
|
|
509
|
+
async function serveMemoryReview(req, res) {
|
|
510
|
+
const port = server.address()?.port;
|
|
511
|
+
req.resume();
|
|
512
|
+
if (req.method !== "GET") return answer(res, 405, "method_not_allowed", "GET only.");
|
|
513
|
+
if (!isLocalCaller(req, port)) return answer(res, 403, "memory_refused", "For this machine only.");
|
|
514
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
515
|
+
const cwd = url.searchParams.get("cwd");
|
|
516
|
+
if (!cwd || !cwd.startsWith("/")) return answer(res, 400, "memory_cwd", "Pass the workspace as ?cwd=/absolute/path.");
|
|
517
|
+
const out = await memoryCustody.review(cwd, url.searchParams.get("client") === "codex" ? "codex" : "claude-code").catch(() => ({ state: "unavailable", items: [] }));
|
|
518
|
+
const body = JSON.stringify(out);
|
|
519
|
+
res.writeHead(200, { "content-type": "application/json", "content-length": Buffer.byteLength(body), "cache-control": "no-store" });
|
|
520
|
+
res.end(body);
|
|
521
|
+
}
|
|
522
|
+
|
|
447
523
|
function serveHook(req, res) {
|
|
448
524
|
const port = server.address()?.port;
|
|
449
525
|
if (req.method !== "POST") {
|
|
@@ -500,6 +576,18 @@ export function createSidecar({
|
|
|
500
576
|
// Bounded by HOOK_BODY_LIMIT; 8 MB of hostile text scans in under half a second
|
|
501
577
|
// (measured 2026-10-31). Only the upload is asynchronous.
|
|
502
578
|
if (input.hook_event_name === "PostToolBatch" || input.hook_event_name === "PostToolUse") {
|
|
579
|
+
// Idea 12: a planted decoy in what a tool returned to the model is Seen. Digests
|
|
580
|
+
// only leave; the upload is not awaited and never changes the hook answer.
|
|
581
|
+
if (tripwires) {
|
|
582
|
+
try {
|
|
583
|
+
noteTools(input);
|
|
584
|
+
const seenDecoys = decoysInHook(input, tripwireDigests);
|
|
585
|
+
if (seenDecoys.length) tripwires.seen(seenDecoys).catch(() => {});
|
|
586
|
+
tripwires.heartbeat().catch(() => {});
|
|
587
|
+
} catch {
|
|
588
|
+
// Local telemetry must never change the hook answer.
|
|
589
|
+
}
|
|
590
|
+
}
|
|
503
591
|
try {
|
|
504
592
|
for (const event of findingsFromHook(input, { seen: injectionSeen })) {
|
|
505
593
|
// A gap holds like a strong finding (1.7.1).
|
|
@@ -513,6 +601,14 @@ export function createSidecar({
|
|
|
513
601
|
// Local telemetry must never change the hook answer.
|
|
514
602
|
}
|
|
515
603
|
}
|
|
604
|
+
// Idea 13: memory custody sees the event first, so a check that arms the hold has
|
|
605
|
+
// armed it before the tool gate decides this very tool.
|
|
606
|
+
const hookParams = new URL(req.url ?? "/", "http://127.0.0.1").searchParams;
|
|
607
|
+
await memoryCustody.hook(input, {
|
|
608
|
+
client: hookParams.get("client") === "codex" ? "codex" : "claude-code",
|
|
609
|
+
// API mode's own hooks (configure writes `mode=api` on its tool hook, `note=only` on its prompt hook).
|
|
610
|
+
api: hookParams.get("mode") === "api" || hookParams.get("note") === "only",
|
|
611
|
+
});
|
|
516
612
|
let out;
|
|
517
613
|
try {
|
|
518
614
|
if (input.hook_event_name === "PreToolUse") await freshInjectionFor(input.tool_name);
|
|
@@ -531,7 +627,7 @@ export function createSidecar({
|
|
|
531
627
|
// must not outrun its taint (cloud review 2026-11-03, SC-B). The gateway then
|
|
532
628
|
// decides: no taint there answers `not_ask_owner`, and the tool goes.
|
|
533
629
|
const unconfirmed = stopGate.injectionHoldMode() && heldUnderTaint(input.tool_name) && highVersion > readHighVersion;
|
|
534
|
-
tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), unconfirmed ? "tainted" : stopGate.injection());
|
|
630
|
+
tool = await toolGate.decide(input, stopGate.toolRules(), hookTimeoutS(req.url), unconfirmed ? "tainted" : stopGate.injection(), memoryCustody.state(input.session_id));
|
|
535
631
|
} catch {
|
|
536
632
|
tool = {};
|
|
537
633
|
}
|
|
@@ -545,6 +641,31 @@ export function createSidecar({
|
|
|
545
641
|
req.on("error", () => res.destroy());
|
|
546
642
|
}
|
|
547
643
|
|
|
644
|
+
// Idea 13, API mode: the tool results and memory sections a model request carries.
|
|
645
|
+
// Bounded: past the wait the call goes on and the hold is armed (fail closed).
|
|
646
|
+
async function memoryCustodyOfRequest(req, body) {
|
|
647
|
+
if (!body || memoryCustody.state() === "off") return null;
|
|
648
|
+
const session = lineageOf(req.headers)?.session;
|
|
649
|
+
const withhold = memoryCustody.mode() === "withhold";
|
|
650
|
+
if (body.length > 16 * 1024 * 1024) return withhold ? memoryCustody.fallback(session, null) : null;
|
|
651
|
+
let parsed;
|
|
652
|
+
try {
|
|
653
|
+
parsed = JSON.parse(body.toString("utf8"));
|
|
654
|
+
} catch {
|
|
655
|
+
return null; // not a JSON model request: there is no memory in it to cut
|
|
656
|
+
}
|
|
657
|
+
if (!session && !withhold) return null;
|
|
658
|
+
let timer;
|
|
659
|
+
const result = await Promise.race([
|
|
660
|
+
memoryCustody.modelRequest(session, parsed).then((b) => ({ done: true, b })),
|
|
661
|
+
new Promise((resolve) => { timer = setTimeout(() => resolve({ done: false }), 5_000); }),
|
|
662
|
+
]).finally(() => clearTimeout(timer));
|
|
663
|
+
// Withhold mode never forwards what it did not finish checking: on a timeout every memory
|
|
664
|
+
// section is cut and the session is held (fail closed).
|
|
665
|
+
const next = result.done ? result.b : withhold ? memoryCustody.fallback(session, parsed) : null;
|
|
666
|
+
return next ? Buffer.from(JSON.stringify(next)) : null;
|
|
667
|
+
}
|
|
668
|
+
|
|
548
669
|
const localBaseUrl = () => {
|
|
549
670
|
const address = server?.listening ? server.address() : null;
|
|
550
671
|
return `http://${host}:${address?.port ?? port}`;
|
|
@@ -693,6 +814,7 @@ export function createSidecar({
|
|
|
693
814
|
if (String(req.url ?? "").startsWith(LOCAL_PREFIX)) {
|
|
694
815
|
const localPath = String(req.url).split("?")[0];
|
|
695
816
|
if (localPath === HOOK_PATH) return serveHook(req, res);
|
|
817
|
+
if (localPath === MEMORY_REVIEW_PATH) return void serveMemoryReview(req, res);
|
|
696
818
|
if (localPath === OTLP_LOGS_PATH) return serveOtlpLogs(req, res);
|
|
697
819
|
if (localPath === WINDOW_PATH) return serveWindow(req, res);
|
|
698
820
|
feed.serve(req, res, { port: server.address()?.port });
|
|
@@ -713,8 +835,22 @@ export function createSidecar({
|
|
|
713
835
|
let watch = null;
|
|
714
836
|
try {
|
|
715
837
|
const body = await readBody(req);
|
|
838
|
+
// Idea 12: a planted decoy in a credential header is Used. The sidecar would strip
|
|
839
|
+
// it and send its own visa, so the gateway would never see it: refuse here with the
|
|
840
|
+
// answer an unknown key gets, and report it first, so the stop happens before the
|
|
841
|
+
// answer. A report that fails still refuses; nothing is forwarded either way.
|
|
842
|
+
const decoy = tripwires ? decoyInHeaders(req.headers, tripwireDigests, isStripped) : null;
|
|
843
|
+
if (decoy) {
|
|
844
|
+
await tripwires.used(decoy, recentTools());
|
|
845
|
+
feed.record({ outcome: "denied", code: "invalid_credential", status: 401, lineage: lineageOf(req.headers), startedAt });
|
|
846
|
+
res.writeHead(401, { "content-type": "application/json" });
|
|
847
|
+
res.end(JSON.stringify({ error: "invalid_credential" }));
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
716
850
|
watch = watchCall(req, verdict.path, body, startedAt);
|
|
717
|
-
|
|
851
|
+
// Idea 13: in withhold mode the body may come back with pending memory cut out.
|
|
852
|
+
const sent = (await memoryCustodyOfRequest(req, body)) ?? body;
|
|
853
|
+
const upstream = await visas.fetchWithVisa((visa) => fetchUpstream(req, verdict.path, sent, visa));
|
|
718
854
|
writeResponse(res, upstream, req.headers, watch);
|
|
719
855
|
} catch (e) {
|
|
720
856
|
upstreamFailed(res, watch, req, verdict.path, e);
|
|
@@ -146,7 +146,12 @@ export function createStopGate({
|
|
|
146
146
|
if (answer.state === "open" && answer.self) latest = { self: answer.self, at: now() };
|
|
147
147
|
if (answer.state === "open") {
|
|
148
148
|
injectionEntry = { value: answer.injection, at: now() };
|
|
149
|
-
rules = {
|
|
149
|
+
rules = {
|
|
150
|
+
read: answer.toolRules && typeof answer.toolRules === "object" ? answer.toolRules : { state: "none" },
|
|
151
|
+
at: now(),
|
|
152
|
+
// Idea 11: the mission's local-tool section, when the agent is on one.
|
|
153
|
+
...(answer.mission && typeof answer.mission === "object" ? { mission: answer.mission } : {}),
|
|
154
|
+
};
|
|
150
155
|
}
|
|
151
156
|
if (["open", "stopped"].includes(answer.state) || (session !== null && answer.state === "session_stopped")) {
|
|
152
157
|
record(session, answer.state);
|
|
@@ -284,6 +289,9 @@ export async function selfAnswerState(response) {
|
|
|
284
289
|
const toolRules = body && typeof body === "object" ? body.tool_rules : undefined;
|
|
285
290
|
const answer = toolRules && typeof toolRules === "object" ? { state: "open", toolRules } : { state: "open" };
|
|
286
291
|
if (body && typeof body === "object" && Object.hasOwn(body, "injection")) answer.injection = body.injection;
|
|
292
|
+
if (body && typeof body === "object" && body.mission && typeof body.mission === "object") answer.mission = body.mission;
|
|
293
|
+
// Idea 13: the memory hold (absent when the owner has memory custody off).
|
|
294
|
+
if (body && typeof body === "object" && Object.hasOwn(body, "memory")) answer.memory = body.memory;
|
|
287
295
|
// The limits and the soft pause, for the agent's note; nothing else from the answer is kept.
|
|
288
296
|
if (body && typeof body === "object" && body.budget && typeof body.budget === "object") {
|
|
289
297
|
const kept = (v) => (v && typeof v === "object" ? v : null);
|