@agent-corpus/policy-manager 0.10.0 → 0.11.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/README.md +94 -29
- package/dist/adapters.d.ts +3 -1
- package/dist/adapters.js +37 -18
- package/dist/classifier.d.ts +98 -0
- package/dist/classifier.js +343 -0
- package/dist/cli.js +66 -7
- package/dist/config.d.ts +2 -0
- package/dist/config.js +6 -2
- package/dist/evidence.d.ts +1 -0
- package/dist/evidence.js +60 -0
- package/dist/flow.d.ts +4 -0
- package/dist/flow.js +68 -13
- package/dist/gitalias.d.ts +13 -0
- package/dist/gitalias.js +33 -0
- package/dist/grants.d.ts +9 -9
- package/dist/grants.js +46 -35
- package/dist/hard.d.ts +63 -0
- package/dist/hard.js +1637 -0
- package/dist/merged.d.ts +6 -0
- package/dist/merged.js +23 -0
- package/dist/nativerules.d.ts +44 -0
- package/dist/nativerules.js +653 -0
- package/dist/permissive.js +32 -6
- package/dist/policy.d.ts +12 -0
- package/dist/policy.js +228 -45
- package/dist/profile.d.ts +4 -0
- package/dist/profile.js +19 -1
- package/dist/prompt.d.ts +32 -0
- package/dist/prompt.js +334 -0
- package/dist/reads.d.ts +46 -0
- package/dist/reads.js +812 -0
- package/dist/replay.d.ts +42 -0
- package/dist/replay.js +174 -1
- package/dist/service.d.ts +12 -1
- package/dist/service.js +23 -6
- package/dist/session.d.ts +76 -13
- package/dist/session.js +373 -116
- package/dist/shellscan.d.ts +58 -0
- package/dist/shellscan.js +395 -0
- package/dist/statepaths.d.ts +41 -0
- package/dist/statepaths.js +706 -0
- package/dist/types.d.ts +9 -1
- package/package.json +1 -1
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { canonical, git } from "./evidence.js";
|
|
5
|
+
import { SHELL_TOOLS } from "./policy.js";
|
|
6
|
+
import { parseShell } from "./shell.js";
|
|
7
|
+
import { command as commandOf, scan } from "./shellscan.js";
|
|
8
|
+
const MAX_FILE = 1024 * 1024;
|
|
9
|
+
const cache = new Map();
|
|
10
|
+
/** A small file the user owns, read again only when it changes. Undefined when missing or unsafe. */
|
|
11
|
+
function readCached(path, parse) {
|
|
12
|
+
try {
|
|
13
|
+
const stat = statSync(path);
|
|
14
|
+
if (!stat.isFile() || stat.size > MAX_FILE)
|
|
15
|
+
return undefined;
|
|
16
|
+
const key = `${stat.mtimeMs}:${stat.size}:${stat.ino}`;
|
|
17
|
+
const hit = cache.get(path);
|
|
18
|
+
if (hit?.key === key)
|
|
19
|
+
return hit.value;
|
|
20
|
+
const value = parse(readFileSync(path, "utf8"));
|
|
21
|
+
if (cache.size > 256)
|
|
22
|
+
cache.clear();
|
|
23
|
+
cache.set(path, { key, value });
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function topLevel(cwd) {
|
|
31
|
+
try {
|
|
32
|
+
return cwd && existsSync(cwd)
|
|
33
|
+
? canonical(git(cwd, ["rev-parse", "--show-toplevel"]))
|
|
34
|
+
: undefined;
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
// ---------------------------------------------------------------------------------------------
|
|
41
|
+
// Pattern matching shared by the readers. Both matchers are iterative with no regular
|
|
42
|
+
// expressions built from user text, so a rule or a command cannot make matching super-linear.
|
|
43
|
+
/** `*` matches any run of characters, including none and spaces. O(text × pattern) worst case. */
|
|
44
|
+
export function wildcard(pattern, text) {
|
|
45
|
+
let p = 0, t = 0, star = -1, mark = 0;
|
|
46
|
+
while (t < text.length) {
|
|
47
|
+
if (p < pattern.length && pattern[p] !== "*" && pattern[p] === text[t]) {
|
|
48
|
+
p++;
|
|
49
|
+
t++;
|
|
50
|
+
}
|
|
51
|
+
else if (p < pattern.length && pattern[p] === "*") {
|
|
52
|
+
star = p++;
|
|
53
|
+
mark = t;
|
|
54
|
+
}
|
|
55
|
+
else if (star >= 0) {
|
|
56
|
+
p = star + 1;
|
|
57
|
+
t = ++mark;
|
|
58
|
+
}
|
|
59
|
+
else
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
while (pattern[p] === "*")
|
|
63
|
+
p++;
|
|
64
|
+
return p === pattern.length;
|
|
65
|
+
}
|
|
66
|
+
/** Gitignore-style path glob over `/` segments: `**` any segments, `*` and `?` within one. */
|
|
67
|
+
export function pathGlob(pattern, path) {
|
|
68
|
+
const ps = pattern.split("/").filter((part, i) => part !== "" || i === 0);
|
|
69
|
+
const ts = path.split("/").filter((part, i) => part !== "" || i === 0);
|
|
70
|
+
const segment = (p, t) => !p.includes("?")
|
|
71
|
+
? wildcard(p, t)
|
|
72
|
+
: p.length === t.length && [...p].every((c, i) => c === "?" || c === t[i]);
|
|
73
|
+
// Iterative `**` matching, the same backtracking shape as `wildcard`.
|
|
74
|
+
let p = 0, t = 0, star = -1, mark = 0;
|
|
75
|
+
while (t < ts.length) {
|
|
76
|
+
if (p < ps.length && ps[p] !== "**" && segment(ps[p], ts[t])) {
|
|
77
|
+
p++;
|
|
78
|
+
t++;
|
|
79
|
+
}
|
|
80
|
+
else if (p < ps.length && ps[p] === "**") {
|
|
81
|
+
star = p++;
|
|
82
|
+
mark = t;
|
|
83
|
+
}
|
|
84
|
+
else if (star >= 0) {
|
|
85
|
+
p = star + 1;
|
|
86
|
+
t = ++mark;
|
|
87
|
+
}
|
|
88
|
+
else
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
while (ps[p] === "**")
|
|
92
|
+
p++;
|
|
93
|
+
return p === ps.length;
|
|
94
|
+
}
|
|
95
|
+
/** Claude Code's managed settings file for this platform. */
|
|
96
|
+
function managedSettings() {
|
|
97
|
+
if (process.platform === "darwin")
|
|
98
|
+
return "/Library/Application Support/ClaudeCode/managed-settings.json";
|
|
99
|
+
if (process.platform === "win32")
|
|
100
|
+
return join(process.env.ProgramData ?? "C:\\ProgramData", "ClaudeCode", "managed-settings.json");
|
|
101
|
+
return "/etc/claude-code/managed-settings.json";
|
|
102
|
+
}
|
|
103
|
+
function claudeRules(text) {
|
|
104
|
+
const value = JSON.parse(text);
|
|
105
|
+
const list = (key) => {
|
|
106
|
+
const entries = value?.permissions?.[key];
|
|
107
|
+
return Array.isArray(entries)
|
|
108
|
+
? entries.filter((entry) => typeof entry === "string" && entry.length <= 1000)
|
|
109
|
+
: [];
|
|
110
|
+
};
|
|
111
|
+
return { allow: list("allow"), ask: list("ask"), deny: list("deny") };
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* The user settings (`CLAUDE_CONFIG_DIR`, else `~/.claude`) and the project's `.claude/settings.json`
|
|
115
|
+
* and `.claude/settings.local.json`, for the project the hook reports (`CLAUDE_PROJECT_DIR`) and
|
|
116
|
+
* the checkout the request runs in.
|
|
117
|
+
*/
|
|
118
|
+
function claudeFiles(request) {
|
|
119
|
+
const user = process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
120
|
+
const projects = new Set();
|
|
121
|
+
if (process.env.CLAUDE_PROJECT_DIR && isAbsolute(process.env.CLAUDE_PROJECT_DIR))
|
|
122
|
+
projects.add(resolve(process.env.CLAUDE_PROJECT_DIR));
|
|
123
|
+
const top = topLevel(request.cwd);
|
|
124
|
+
if (top)
|
|
125
|
+
projects.add(top);
|
|
126
|
+
else if (request.cwd && isAbsolute(request.cwd))
|
|
127
|
+
projects.add(resolve(request.cwd));
|
|
128
|
+
const files = [];
|
|
129
|
+
const add = (path, base, allows) => {
|
|
130
|
+
const rules = readCached(path, claudeRules);
|
|
131
|
+
if (rules)
|
|
132
|
+
files.push({ path, rules, base, allows });
|
|
133
|
+
};
|
|
134
|
+
const first = [...projects][0] ?? request.cwd;
|
|
135
|
+
add(managedSettings(), first, true);
|
|
136
|
+
add(join(user, "settings.json"), first, true);
|
|
137
|
+
// A checkout's settings can only make a request stricter: their deny and ask rules count, their
|
|
138
|
+
// allow rules do not (the checkout can be anyone's branch).
|
|
139
|
+
for (const project of projects) {
|
|
140
|
+
add(join(project, ".claude", "settings.json"), project, false);
|
|
141
|
+
add(join(project, ".claude", "settings.local.json"), project, false);
|
|
142
|
+
}
|
|
143
|
+
return files;
|
|
144
|
+
}
|
|
145
|
+
/** `Tool` or `Tool(content)`. */
|
|
146
|
+
function parseRule(rule) {
|
|
147
|
+
const open = rule.indexOf("(");
|
|
148
|
+
if (open < 0)
|
|
149
|
+
return /^[\w.*-]+$/.test(rule) ? { tool: rule } : undefined;
|
|
150
|
+
if (!rule.endsWith(")"))
|
|
151
|
+
return undefined;
|
|
152
|
+
return { tool: rule.slice(0, open), content: rule.slice(open + 1, -1) };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Process wrappers Claude Code strips before matching: `timeout`, `time`, `nice`, `nohup`,
|
|
156
|
+
* `stdbuf`, `command`, `builtin`, `noglob`, and bare `xargs`.
|
|
157
|
+
*/
|
|
158
|
+
function stripWrappers(words) {
|
|
159
|
+
let rest = words;
|
|
160
|
+
for (let guard = 0; guard < 8 && rest.length; guard++) {
|
|
161
|
+
const [head = "", ...tail] = rest;
|
|
162
|
+
if (["time", "nohup", "command", "builtin", "noglob"].includes(head)) {
|
|
163
|
+
rest = head === "time" && tail[0] === "-p" ? tail.slice(1) : tail;
|
|
164
|
+
}
|
|
165
|
+
else if (head === "nice") {
|
|
166
|
+
rest = tail[0] === "-n" ? tail.slice(2) : /^-\d+$/.test(tail[0] ?? "") ? tail.slice(1) : tail;
|
|
167
|
+
}
|
|
168
|
+
else if (head === "timeout") {
|
|
169
|
+
let i = 0;
|
|
170
|
+
while (tail[i]?.startsWith("-"))
|
|
171
|
+
i += ["-s", "--signal", "-k", "--kill-after"].includes(tail[i]) ? 2 : 1;
|
|
172
|
+
rest = tail.slice(i + 1);
|
|
173
|
+
}
|
|
174
|
+
else if (head === "stdbuf") {
|
|
175
|
+
let i = 0;
|
|
176
|
+
while (tail[i]?.startsWith("-"))
|
|
177
|
+
i += /^-[ioe]$/.test(tail[i]) ? 2 : 1;
|
|
178
|
+
rest = tail.slice(i);
|
|
179
|
+
}
|
|
180
|
+
else if (head === "xargs" && tail.length && !tail[0]?.startsWith("-"))
|
|
181
|
+
rest = tail;
|
|
182
|
+
else
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
return rest;
|
|
186
|
+
}
|
|
187
|
+
/** Programs that always prompt in Claude Code, whatever a prefix rule says. */
|
|
188
|
+
function alwaysPrompts(words) {
|
|
189
|
+
const [program = "", ...args] = words;
|
|
190
|
+
if (["watch", "setsid", "ionice", "flock"].includes(program))
|
|
191
|
+
return true;
|
|
192
|
+
return (program === "find" &&
|
|
193
|
+
args.some((arg) => ["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fls"].includes(arg)));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* One Bash rule against one subcommand's text. Without `*` the rule is the exact command.
|
|
197
|
+
* `cmd:*` is the same as `cmd *`; a rule whose only `*` is a trailing ` *` also matches the bare
|
|
198
|
+
* command (`Bash(ls *)` matches `ls`, not `lsof`). Otherwise `*` matches any text, spaces too.
|
|
199
|
+
*/
|
|
200
|
+
export function bashRuleMatches(content, text) {
|
|
201
|
+
let pattern = content.trim();
|
|
202
|
+
if (pattern === "" || pattern === "*")
|
|
203
|
+
return true;
|
|
204
|
+
if (pattern.endsWith(":*"))
|
|
205
|
+
pattern = `${pattern.slice(0, -2)} *`;
|
|
206
|
+
const stars = pattern.split("*").length - 1;
|
|
207
|
+
if (stars === 0)
|
|
208
|
+
return pattern === text;
|
|
209
|
+
if (stars === 1 && pattern.endsWith(" *")) {
|
|
210
|
+
const prefix = pattern.slice(0, -2);
|
|
211
|
+
return text === prefix || text.startsWith(`${prefix} `);
|
|
212
|
+
}
|
|
213
|
+
return wildcard(pattern, text);
|
|
214
|
+
}
|
|
215
|
+
function subcommands(script) {
|
|
216
|
+
const { segments, complete } = scan(script);
|
|
217
|
+
const parts = [];
|
|
218
|
+
for (const segment of segments) {
|
|
219
|
+
const cmd = commandOf(segment);
|
|
220
|
+
if (!cmd.program)
|
|
221
|
+
continue;
|
|
222
|
+
const words = [cmd.program, ...cmd.args];
|
|
223
|
+
const stripped = stripWrappers(words.map((word) => word.text));
|
|
224
|
+
const raw = segment.filter((word) => !word.redirect);
|
|
225
|
+
const written = stripWrappers(raw.map((word) => word.text));
|
|
226
|
+
const harmless = (word) => word.literal && (word.text === "/dev/null" || /^\d$/.test(word.text));
|
|
227
|
+
parts.push({
|
|
228
|
+
text: stripped.join(" "),
|
|
229
|
+
allowText: written.join(" "),
|
|
230
|
+
assigned: cmd.assignments.length > 0,
|
|
231
|
+
plain: raw.every((word) => word.literal) && cmd.redirects.every(harmless),
|
|
232
|
+
prompts: alwaysPrompts(written) || alwaysPrompts(stripped),
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
return { parts, complete };
|
|
236
|
+
}
|
|
237
|
+
const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
|
|
238
|
+
/** A Read or Edit path rule as an absolute glob, per the documented prefixes. */
|
|
239
|
+
function pathPattern(content, cwd, base) {
|
|
240
|
+
if (content.startsWith("//"))
|
|
241
|
+
return content.slice(1);
|
|
242
|
+
if (content.startsWith("~/"))
|
|
243
|
+
return join(homedir(), content.slice(2))
|
|
244
|
+
.replace(/\\/g, "/")
|
|
245
|
+
.replace(/^[A-Za-z]:(?=\/)/, "");
|
|
246
|
+
if (content.startsWith("/"))
|
|
247
|
+
return `${base.replace(/\\/g, "/")}${content}`;
|
|
248
|
+
const relative = content.startsWith("./") ? content.slice(2) : content;
|
|
249
|
+
// Gitignore style: a pattern with no `/` matches at any depth (`Read(.env)` is `Read(**/.env)`).
|
|
250
|
+
const anywhere = !relative.includes("/");
|
|
251
|
+
return `${cwd.replace(/\\/g, "/")}/${anywhere ? "**/" : ""}${relative}`;
|
|
252
|
+
}
|
|
253
|
+
function claudeRuleMatches(rule, request, base) {
|
|
254
|
+
const parsed = parseRule(rule.trim());
|
|
255
|
+
if (!parsed)
|
|
256
|
+
return false;
|
|
257
|
+
const { tool, content } = parsed;
|
|
258
|
+
if (tool.startsWith("mcp__")) {
|
|
259
|
+
if (!request.tool.startsWith("mcp__"))
|
|
260
|
+
return false;
|
|
261
|
+
if (content !== undefined)
|
|
262
|
+
return false;
|
|
263
|
+
return (request.tool === tool ||
|
|
264
|
+
request.tool.startsWith(`${tool}__`) ||
|
|
265
|
+
(tool.endsWith("*") && wildcard(tool, request.tool)));
|
|
266
|
+
}
|
|
267
|
+
if (tool === "Bash") {
|
|
268
|
+
if (!SHELL_TOOLS.has(request.tool))
|
|
269
|
+
return false;
|
|
270
|
+
const script = request.input.command;
|
|
271
|
+
if (typeof script !== "string")
|
|
272
|
+
return false;
|
|
273
|
+
if (content === undefined || content.trim() === "*")
|
|
274
|
+
return true;
|
|
275
|
+
const { parts } = subcommands(script);
|
|
276
|
+
// Deny and ask rules apply to any subcommand, past any leading assignment. (Allow rules for
|
|
277
|
+
// shell commands are matched per subcommand in `allowedScript`.)
|
|
278
|
+
return (parts.some((part) => bashRuleMatches(content, part.text) || bashRuleMatches(content, part.allowText)) || bashRuleMatches(content, script.trim()));
|
|
279
|
+
}
|
|
280
|
+
const edit = tool === "Edit" && EDIT_TOOLS.has(request.tool);
|
|
281
|
+
const read = tool === "Read" && request.tool === "Read";
|
|
282
|
+
const same = tool === request.tool && !SHELL_TOOLS.has(tool);
|
|
283
|
+
if (!edit && !read && !same)
|
|
284
|
+
return false;
|
|
285
|
+
if (content === undefined || content === "" || content === "*" || content === "**")
|
|
286
|
+
return true;
|
|
287
|
+
if (!edit && !read)
|
|
288
|
+
return false;
|
|
289
|
+
const file = request.input.file_path ?? request.input.notebook_path ?? request.input.path;
|
|
290
|
+
if (typeof file !== "string" || !request.cwd)
|
|
291
|
+
return false;
|
|
292
|
+
const windows = process.platform === "win32";
|
|
293
|
+
// Every spelling of a path: as written and resolved (Windows 8.3 short names and symlinks
|
|
294
|
+
// expanded), with `/` separators, lower-cased on Windows, and without its drive letter so that
|
|
295
|
+
// a `//abs` rule (written from the filesystem root) matches `C:/abs`.
|
|
296
|
+
const spellings = (path) => {
|
|
297
|
+
const forms = new Set([path]);
|
|
298
|
+
try {
|
|
299
|
+
forms.add(realpathSync.native(path));
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
// Missing: resolve the nearest existing ancestor and keep the rest as written.
|
|
303
|
+
let dir = dirname(path);
|
|
304
|
+
while (dir !== dirname(dir) && !existsSync(dir))
|
|
305
|
+
dir = dirname(dir);
|
|
306
|
+
try {
|
|
307
|
+
forms.add(join(realpathSync.native(dir), path.slice(dir.length)));
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
/* unresolvable: as written */
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
const out = new Set();
|
|
314
|
+
for (const form of forms) {
|
|
315
|
+
const slashed = form.replace(/\\/g, "/");
|
|
316
|
+
const cased = windows ? slashed.toLowerCase() : slashed;
|
|
317
|
+
out.add(cased);
|
|
318
|
+
if (windows)
|
|
319
|
+
out.add(cased.replace(/^[a-z]:(?=\/)/, ""));
|
|
320
|
+
}
|
|
321
|
+
return [...out];
|
|
322
|
+
};
|
|
323
|
+
const targets = spellings(resolve(request.cwd, file));
|
|
324
|
+
for (const cwd of spellings(request.cwd))
|
|
325
|
+
for (const root of spellings(base)) {
|
|
326
|
+
const pattern = pathPattern(content, cwd, root);
|
|
327
|
+
const patterns = [pattern, `${pattern}/**`].map((p) => (windows ? p.toLowerCase() : p));
|
|
328
|
+
if (targets.some((target) => patterns.some((p) => pathGlob(p, target))))
|
|
329
|
+
return true;
|
|
330
|
+
}
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
/** Allow rules covering every subcommand of a script, each part by any allow rule. */
|
|
334
|
+
function allowedScript(script, files) {
|
|
335
|
+
const { parts, complete } = subcommands(script);
|
|
336
|
+
if (!complete || !parts.length || /(?:&&|\|\||\|)\s*$/.test(script.trim()))
|
|
337
|
+
return undefined;
|
|
338
|
+
const used = [];
|
|
339
|
+
for (const part of parts) {
|
|
340
|
+
if (!part.plain || part.assigned || part.prompts)
|
|
341
|
+
return undefined;
|
|
342
|
+
let found;
|
|
343
|
+
for (const file of files) {
|
|
344
|
+
for (const rule of file.allows ? file.rules.allow : []) {
|
|
345
|
+
const parsed = parseRule(rule.trim());
|
|
346
|
+
if (parsed?.tool !== "Bash")
|
|
347
|
+
continue;
|
|
348
|
+
if (parsed.content === undefined || bashRuleMatches(parsed.content, part.allowText)) {
|
|
349
|
+
found = { verdict: "allow", rule, source: file.path };
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
if (found)
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
if (!found)
|
|
357
|
+
return undefined;
|
|
358
|
+
if (!used.some((match) => match.rule === found.rule))
|
|
359
|
+
used.push(found);
|
|
360
|
+
}
|
|
361
|
+
return {
|
|
362
|
+
verdict: "allow",
|
|
363
|
+
rule: used.map((match) => match.rule).join(", "),
|
|
364
|
+
source: [...new Set(used.map((match) => match.source))].join(", "),
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Claude Code's evaluation: deny, then ask, then allow; the first match decides. A compound
|
|
369
|
+
* command is allowed when every subcommand is covered by some allow rule.
|
|
370
|
+
*/
|
|
371
|
+
function claudeVerdict(request) {
|
|
372
|
+
const files = claudeFiles(request);
|
|
373
|
+
for (const verdict of ["deny", "ask"])
|
|
374
|
+
for (const file of files)
|
|
375
|
+
for (const rule of file.rules[verdict])
|
|
376
|
+
if (claudeRuleMatches(rule, request, file.base))
|
|
377
|
+
return { verdict, rule, source: file.path };
|
|
378
|
+
const script = request.input.command;
|
|
379
|
+
if (SHELL_TOOLS.has(request.tool) && typeof script === "string") {
|
|
380
|
+
// `Bash` or `Bash(*)` allows everything; otherwise every part needs a rule.
|
|
381
|
+
for (const file of files)
|
|
382
|
+
for (const rule of file.allows ? file.rules.allow : [])
|
|
383
|
+
if (/^Bash(?:\(\s*\*?\s*\))?$/.test(rule.trim()))
|
|
384
|
+
return { verdict: "allow", rule, source: file.path };
|
|
385
|
+
return allowedScript(script, files);
|
|
386
|
+
}
|
|
387
|
+
for (const file of files)
|
|
388
|
+
for (const rule of file.allows ? file.rules.allow : [])
|
|
389
|
+
if (claudeRuleMatches(rule, request, file.base))
|
|
390
|
+
return { verdict: "allow", rule, source: file.path };
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
/** Parses the `prefix_rule(...)` calls of a rules file. Other statements are skipped. */
|
|
394
|
+
export function parseCodexRules(text) {
|
|
395
|
+
const rules = [];
|
|
396
|
+
let i = 0;
|
|
397
|
+
const space = () => {
|
|
398
|
+
while (i < text.length) {
|
|
399
|
+
if (/\s/.test(text[i]))
|
|
400
|
+
i++;
|
|
401
|
+
else if (text[i] === "#")
|
|
402
|
+
while (i < text.length && text[i] !== "\n")
|
|
403
|
+
i++;
|
|
404
|
+
else
|
|
405
|
+
break;
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
const string = () => {
|
|
409
|
+
const quote = text[i];
|
|
410
|
+
const triple = text.startsWith(quote.repeat(3), i);
|
|
411
|
+
i += triple ? 3 : 1;
|
|
412
|
+
let out = "";
|
|
413
|
+
while (i < text.length) {
|
|
414
|
+
if (triple ? text.startsWith(quote.repeat(3), i) : text[i] === quote) {
|
|
415
|
+
i += triple ? 3 : 1;
|
|
416
|
+
return out;
|
|
417
|
+
}
|
|
418
|
+
if (text[i] === "\\" && i + 1 < text.length) {
|
|
419
|
+
const next = text[i + 1];
|
|
420
|
+
out += { n: "\n", t: "\t" }[next] ?? next;
|
|
421
|
+
i += 2;
|
|
422
|
+
}
|
|
423
|
+
else
|
|
424
|
+
out += text[i++];
|
|
425
|
+
}
|
|
426
|
+
throw new Error("Unterminated string");
|
|
427
|
+
};
|
|
428
|
+
const value = (depth = 0) => {
|
|
429
|
+
space();
|
|
430
|
+
const c = text[i];
|
|
431
|
+
if (c === '"' || c === "'")
|
|
432
|
+
return string();
|
|
433
|
+
if (c === "[" && depth < 4) {
|
|
434
|
+
i++;
|
|
435
|
+
const items = [];
|
|
436
|
+
for (;;) {
|
|
437
|
+
space();
|
|
438
|
+
if (text[i] === "]") {
|
|
439
|
+
i++;
|
|
440
|
+
return items;
|
|
441
|
+
}
|
|
442
|
+
items.push(value(depth + 1));
|
|
443
|
+
space();
|
|
444
|
+
if (text[i] === ",")
|
|
445
|
+
i++;
|
|
446
|
+
else if (text[i] !== "]")
|
|
447
|
+
throw new Error("Bad list");
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
throw new Error("Unsupported value");
|
|
451
|
+
};
|
|
452
|
+
const skipCall = () => {
|
|
453
|
+
let depth = 0;
|
|
454
|
+
while (i < text.length) {
|
|
455
|
+
const c = text[i];
|
|
456
|
+
if (c === '"' || c === "'") {
|
|
457
|
+
string();
|
|
458
|
+
continue;
|
|
459
|
+
}
|
|
460
|
+
if (c === "(")
|
|
461
|
+
depth++;
|
|
462
|
+
if (c === ")" && --depth === 0) {
|
|
463
|
+
i++;
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
i++;
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
while (i < text.length) {
|
|
470
|
+
space();
|
|
471
|
+
const start = i;
|
|
472
|
+
const name = /^[A-Za-z_]\w*/.exec(text.slice(i, i + 64))?.[0];
|
|
473
|
+
if (!name) {
|
|
474
|
+
i++;
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
i += name.length;
|
|
478
|
+
space();
|
|
479
|
+
if (text[i] !== "(")
|
|
480
|
+
continue;
|
|
481
|
+
if (name !== "prefix_rule") {
|
|
482
|
+
skipCall();
|
|
483
|
+
continue;
|
|
484
|
+
}
|
|
485
|
+
i++;
|
|
486
|
+
const args = {};
|
|
487
|
+
try {
|
|
488
|
+
for (;;) {
|
|
489
|
+
space();
|
|
490
|
+
if (text[i] === ")") {
|
|
491
|
+
i++;
|
|
492
|
+
break;
|
|
493
|
+
}
|
|
494
|
+
const key = /^[A-Za-z_]\w*/.exec(text.slice(i, i + 64))?.[0];
|
|
495
|
+
if (!key)
|
|
496
|
+
throw new Error("Expected a keyword argument");
|
|
497
|
+
i += key.length;
|
|
498
|
+
space();
|
|
499
|
+
if (text[i] !== "=")
|
|
500
|
+
throw new Error("Expected =");
|
|
501
|
+
i++;
|
|
502
|
+
args[key] = value();
|
|
503
|
+
space();
|
|
504
|
+
if (text[i] === ",")
|
|
505
|
+
i++;
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
// An unreadable rule is skipped: it can neither allow nor stop anything here.
|
|
510
|
+
i = start;
|
|
511
|
+
i += name.length;
|
|
512
|
+
skipCall();
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
const pattern = args.pattern;
|
|
516
|
+
const decision = (args.decision ?? "allow");
|
|
517
|
+
if (!Array.isArray(pattern) ||
|
|
518
|
+
!pattern.length ||
|
|
519
|
+
!["allow", "prompt", "forbidden"].includes(decision))
|
|
520
|
+
continue;
|
|
521
|
+
const elements = pattern.map((element) => typeof element === "string"
|
|
522
|
+
? [element]
|
|
523
|
+
: Array.isArray(element) && element.every((e) => typeof e === "string")
|
|
524
|
+
? element
|
|
525
|
+
: undefined);
|
|
526
|
+
if (elements.some((element) => !element?.length))
|
|
527
|
+
continue;
|
|
528
|
+
rules.push({
|
|
529
|
+
pattern: elements,
|
|
530
|
+
decision: decision,
|
|
531
|
+
text: text.slice(start, i).replace(/\s+/g, " ").slice(0, 300),
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
return rules;
|
|
535
|
+
}
|
|
536
|
+
function codexFiles(request) {
|
|
537
|
+
const home = process.env.CODEX_HOME || join(homedir(), ".codex");
|
|
538
|
+
// Allow rules count only from CODEX_HOME. A checkout's `.codex/rules` can only make a request
|
|
539
|
+
// stricter: its prompt and forbidden rules count, trusted or not, and its allow rules do not.
|
|
540
|
+
const dirs = [[join(home, "rules"), true]];
|
|
541
|
+
const top = topLevel(request.cwd);
|
|
542
|
+
if (top)
|
|
543
|
+
dirs.push([join(top, ".codex", "rules"), false]);
|
|
544
|
+
const files = [];
|
|
545
|
+
for (const [dir, allows] of dirs) {
|
|
546
|
+
let names;
|
|
547
|
+
try {
|
|
548
|
+
if (!lstatSync(dir).isDirectory())
|
|
549
|
+
continue;
|
|
550
|
+
names = readdirSync(dir)
|
|
551
|
+
.filter((name) => name.endsWith(".rules"))
|
|
552
|
+
.sort();
|
|
553
|
+
}
|
|
554
|
+
catch {
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
for (const name of names.slice(0, 64)) {
|
|
558
|
+
const path = join(dir, name);
|
|
559
|
+
const rules = readCached(path, parseCodexRules);
|
|
560
|
+
if (rules)
|
|
561
|
+
files.push({ path, rules, allows });
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return files;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* The invocations Codex evaluates for a shell script: each command of a linear chain of plain
|
|
568
|
+
* words joined by `&&`, `||`, `;` or `|`; anything else (redirects, substitutions, assignments,
|
|
569
|
+
* globs, control flow) is one `bash -lc <script>` invocation.
|
|
570
|
+
*/
|
|
571
|
+
export function codexInvocations(script) {
|
|
572
|
+
const pipelines = parseShell(script);
|
|
573
|
+
const plain = pipelines?.every((pipeline) => pipeline.every((cmd) => !cmd.env.length &&
|
|
574
|
+
!cmd.redirects.length &&
|
|
575
|
+
!cmd.subs.length &&
|
|
576
|
+
cmd.stdin === undefined &&
|
|
577
|
+
!cmd.loose?.some(Boolean) &&
|
|
578
|
+
!cmd.glob?.some(Boolean))) ?? false;
|
|
579
|
+
if (pipelines && plain)
|
|
580
|
+
return pipelines.flatMap((pipeline) => pipeline.map((cmd) => cmd.argv));
|
|
581
|
+
return [["bash", "-lc", script]];
|
|
582
|
+
}
|
|
583
|
+
const STRICTNESS = { allow: 0, prompt: 1, forbidden: 2 };
|
|
584
|
+
function codexVerdict(request) {
|
|
585
|
+
const script = request.input.command ?? request.input.cmd;
|
|
586
|
+
if (!SHELL_TOOLS.has(request.tool) || typeof script !== "string")
|
|
587
|
+
return undefined;
|
|
588
|
+
const files = codexFiles(request);
|
|
589
|
+
if (!files.length)
|
|
590
|
+
return undefined;
|
|
591
|
+
const invocations = Array.isArray(request.input.command)
|
|
592
|
+
? [request.input.command]
|
|
593
|
+
: codexInvocations(script);
|
|
594
|
+
let worst;
|
|
595
|
+
let covered = 0;
|
|
596
|
+
for (const argv of invocations) {
|
|
597
|
+
let best;
|
|
598
|
+
for (const file of files)
|
|
599
|
+
for (const rule of file.rules) {
|
|
600
|
+
if (rule.decision === "allow" && !file.allows)
|
|
601
|
+
continue;
|
|
602
|
+
if (rule.pattern.length > argv.length)
|
|
603
|
+
continue;
|
|
604
|
+
if (!rule.pattern.every((options, k) => options.includes(argv[k])))
|
|
605
|
+
continue;
|
|
606
|
+
// When several rules match, the most restrictive decision applies.
|
|
607
|
+
const level = STRICTNESS[rule.decision];
|
|
608
|
+
if (!best || level > best.level)
|
|
609
|
+
best = {
|
|
610
|
+
verdict: rule.decision === "allow" ? "allow" : rule.decision === "prompt" ? "ask" : "deny",
|
|
611
|
+
rule: rule.text,
|
|
612
|
+
source: file.path,
|
|
613
|
+
level,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
if (best) {
|
|
617
|
+
covered++;
|
|
618
|
+
if (!worst || best.level > worst.level)
|
|
619
|
+
worst = best;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
if (!worst)
|
|
623
|
+
return undefined;
|
|
624
|
+
// An allow needs every invocation allowed; a prompt or forbidden on any one applies.
|
|
625
|
+
if (worst.verdict === "allow" && covered < invocations.length)
|
|
626
|
+
return undefined;
|
|
627
|
+
const { level: _level, ...match } = worst;
|
|
628
|
+
return match;
|
|
629
|
+
}
|
|
630
|
+
// ---------------------------------------------------------------------------------------------
|
|
631
|
+
// Copilot CLI: its documented allow and deny lists are the `--allow-tool`/`--deny-tool` flags,
|
|
632
|
+
// which "apply only to the current session and aren't written to permissions-config.json";
|
|
633
|
+
// the format of the saved per-location approvals is not documented, and trusted folders gate
|
|
634
|
+
// file access, not commands. There is no documented file to read, so nothing is matched.
|
|
635
|
+
// https://docs.github.com/en/copilot/how-tos/copilot-cli/use-copilot-cli/allowing-tools
|
|
636
|
+
/** The user's own rule verdict for a request in its harness, or undefined when none applies. */
|
|
637
|
+
export function nativeRules(request) {
|
|
638
|
+
try {
|
|
639
|
+
if (request.harness === "claude")
|
|
640
|
+
return claudeVerdict(request);
|
|
641
|
+
if (request.harness === "codex")
|
|
642
|
+
return codexVerdict(request);
|
|
643
|
+
return undefined;
|
|
644
|
+
}
|
|
645
|
+
catch {
|
|
646
|
+
return undefined;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
/** For tests: forget cached rule files. */
|
|
650
|
+
export function clearNativeRuleCache() {
|
|
651
|
+
cache.clear();
|
|
652
|
+
}
|
|
653
|
+
//# sourceMappingURL=nativerules.js.map
|