passcontrol 1.7.1 → 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.
@@ -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
+ }
@@ -96,7 +96,7 @@ const NOT_IN_A_HOSTNAME = /[\s/\\@?#]/;
96
96
  * `api.anthropic.com`, so a string comparison that treats them as different
97
97
  * hosts is a one-character bypass of the provider refusal below.
98
98
  */
99
- function normalizeHostname(value) {
99
+ export function normalizeHostname(value) {
100
100
  let host = String(value ?? "").trim().toLowerCase();
101
101
  if (host.startsWith("[") && host.endsWith("]")) host = host.slice(1, -1);
102
102
  if (host.endsWith(".")) host = host.slice(0, -1);