@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.
@@ -0,0 +1,58 @@
1
+ /**
2
+ * A lenient shell scanner for the hard human list and for matching the user's own permission
3
+ * rules. Unlike the policy parser it never refuses a script: it removes quotes and backslashes,
4
+ * splits at operators, and opens command and process substitutions as commands of their own, so
5
+ * `'git' push --for"ce"` and `git $(echo push) --force` are seen as the words the shell would run.
6
+ * It decides nothing alone: a false match on the hard list asks rather than approves, and a user
7
+ * allow rule only matches a script the scanner read completely with literal words.
8
+ */
9
+ /** One word after quote removal. `literal` is false when it holds an expansion or substitution. */
10
+ export interface Word {
11
+ text: string;
12
+ literal: boolean;
13
+ /** The target of a redirection (`>`, `>>`, `<`, `<<<`, ...). */
14
+ redirect?: boolean;
15
+ /** The target of a redirection that writes (`>`, `>>`, `>|`, `<>`, `&>`). */
16
+ writes?: boolean;
17
+ /** The text of a here-string (`<<< text`), fed to the command's standard input. */
18
+ herestring?: boolean;
19
+ /** The first word of a command whose standard input is the previous command's output (`a | b`). */
20
+ piped?: boolean;
21
+ /** How many groups (`( )`, `{ }`, `if`, `while`, `for`, `case`...) the word is inside. */
22
+ depth?: number;
23
+ /** On a `piped` word: the group depth of the pipe, so the stage it feeds can be found. */
24
+ pipedAt?: number;
25
+ /** Holds an unquoted expansion or substitution, which can split into words and options. */
26
+ bare?: boolean;
27
+ /** The body of a here-document fed to this command's standard input (also `redirect`). */
28
+ heredoc?: boolean;
29
+ /** A here-document with a quoted delimiter (`<<'EOF'`, `<<"EOF"`, `<<\EOF`): nothing expands. */
30
+ quoted?: boolean;
31
+ }
32
+ export interface Scan {
33
+ segments: Word[][];
34
+ /** False when a quote or substitution was left open: the script could not be read fully. */
35
+ complete: boolean;
36
+ }
37
+ /**
38
+ * Scans a script. With `heredoc`, `script` is the body of a here-document with an unquoted
39
+ * delimiter, read with the shell's rules for one: everything is literal text except that a
40
+ * backslash escapes only `$`, a backtick, a backslash and a newline, and `$(...)`, backticks and
41
+ * `${...}` expand; the substitutions are read as commands.
42
+ */
43
+ export declare function scan(script: string, heredoc?: boolean): Scan;
44
+ export interface Command {
45
+ /** Assignments before the program (`GIT_DIR=x git ...`), with wrapper `env` assignments. */
46
+ assignments: Word[];
47
+ program?: Word;
48
+ args: Word[];
49
+ redirects: Word[];
50
+ }
51
+ /** The program and arguments of one segment, behind assignments, keywords and wrappers. */
52
+ export declare function command(segment: Word[]): Command;
53
+ /** The script a shell or `eval` runs, when the segment is one: `bash -c '...'`, `eval ...`. */
54
+ export declare function innerScript(cmd: Command): {
55
+ script: string;
56
+ literal: boolean;
57
+ } | undefined;
58
+ //# sourceMappingURL=shellscan.d.ts.map
@@ -0,0 +1,395 @@
1
+ /**
2
+ * A lenient shell scanner for the hard human list and for matching the user's own permission
3
+ * rules. Unlike the policy parser it never refuses a script: it removes quotes and backslashes,
4
+ * splits at operators, and opens command and process substitutions as commands of their own, so
5
+ * `'git' push --for"ce"` and `git $(echo push) --force` are seen as the words the shell would run.
6
+ * It decides nothing alone: a false match on the hard list asks rather than approves, and a user
7
+ * allow rule only matches a script the scanner read completely with literal words.
8
+ */
9
+ /**
10
+ * Scans a script. With `heredoc`, `script` is the body of a here-document with an unquoted
11
+ * delimiter, read with the shell's rules for one: everything is literal text except that a
12
+ * backslash escapes only `$`, a backtick, a backslash and a newline, and `$(...)`, backticks and
13
+ * `${...}` expand; the substitutions are read as commands.
14
+ */
15
+ export function scan(script, heredoc = false) {
16
+ const segments = [];
17
+ const stack = [];
18
+ let segment = [];
19
+ let text = "";
20
+ // A here-document body is one word of text from its first character.
21
+ let active = heredoc;
22
+ let literal = true;
23
+ let bare = false;
24
+ let redirectNext = false;
25
+ let redirectWrites = false;
26
+ let redirectHere = false;
27
+ let pipeNext = false;
28
+ /** Open groups, innermost last, and the group depth where the last pipe was. */
29
+ const groups = [];
30
+ let pipeDepth = 0;
31
+ /** The next word is a here-document delimiter (`<<` or `<<-`). */
32
+ let delimiterNext = "";
33
+ /** Here-documents whose bodies start after the next newline, with the command they feed. */
34
+ let pending = [];
35
+ /** The current word had a quote or a backslash escape in it (a quoted here-document delimiter). */
36
+ let wordQuoted = false;
37
+ let unterminated = false;
38
+ let quote = heredoc ? "h" : "";
39
+ const endWord = () => {
40
+ if (active) {
41
+ // A group keyword in command position opens or closes a group.
42
+ const command = !redirectNext &&
43
+ literal &&
44
+ segment.every((word) => word.literal && GROUP_LEAD.has(word.text));
45
+ if (command && CLOSERS[text]?.includes(groups[groups.length - 1] ?? ""))
46
+ groups.pop();
47
+ const depth = groups.length;
48
+ if (command && OPENERS.has(text))
49
+ groups.push(text);
50
+ segment.push({
51
+ text,
52
+ literal,
53
+ ...(redirectNext ? { redirect: true } : {}),
54
+ ...(redirectNext && redirectWrites ? { writes: true } : {}),
55
+ ...(redirectNext && redirectHere ? { herestring: true } : {}),
56
+ ...(pipeNext && !segment.length ? { piped: true, pipedAt: pipeDepth } : {}),
57
+ depth,
58
+ ...(bare ? { bare: true } : {}),
59
+ });
60
+ if (!redirectNext)
61
+ pipeNext = false;
62
+ redirectNext = false;
63
+ redirectWrites = false;
64
+ redirectHere = false;
65
+ if (delimiterNext) {
66
+ pending.push({
67
+ delimiter: text,
68
+ strip: delimiterNext === "<<-",
69
+ quoted: wordQuoted,
70
+ segment,
71
+ });
72
+ delimiterNext = "";
73
+ }
74
+ }
75
+ text = "";
76
+ wordQuoted = false;
77
+ active = false;
78
+ literal = true;
79
+ bare = false;
80
+ };
81
+ const endSegment = () => {
82
+ endWord();
83
+ if (segment.length)
84
+ segments.push(segment);
85
+ segment = [];
86
+ };
87
+ /** Opens a substitution: its body is read as commands, and the outer word is not literal. */
88
+ const open = (closer) => {
89
+ stack.push({
90
+ segment,
91
+ text,
92
+ active: true,
93
+ literal: false,
94
+ bare: bare || quote === "",
95
+ closer,
96
+ resume: quote === "'" ? "" : quote,
97
+ });
98
+ segment = [];
99
+ text = "";
100
+ active = false;
101
+ literal = true;
102
+ bare = false;
103
+ quote = "";
104
+ };
105
+ const close = () => {
106
+ endSegment();
107
+ const frame = stack.pop();
108
+ segment = frame.segment;
109
+ text = `${frame.text}$`;
110
+ active = frame.active;
111
+ literal = frame.literal;
112
+ bare = frame.bare;
113
+ quote = frame.resume;
114
+ };
115
+ for (let i = 0; i < script.length; i++) {
116
+ const c = script[i];
117
+ const next = script[i + 1];
118
+ if (quote === "'") {
119
+ if (c === "'")
120
+ quote = "";
121
+ else
122
+ text += c;
123
+ continue;
124
+ }
125
+ if (quote === '"' || quote === "h") {
126
+ // In a here-document a `"` is text, and a backslash escapes only `$`, a backtick, `\` and a
127
+ // newline; inside double quotes it also escapes `"`.
128
+ if (c === '"' && quote === '"')
129
+ quote = "";
130
+ else if (c === "\\" &&
131
+ next !== undefined &&
132
+ (quote === '"' ? /[$`"\\\n]/ : /[$`\\\n]/).test(next)) {
133
+ if (next === "\n")
134
+ i++;
135
+ else
136
+ text += script[++i];
137
+ active = true;
138
+ }
139
+ else if (c === "$" && next === "(") {
140
+ // The body of "$(...)" runs too; read it as commands and resume the quoted word after it.
141
+ i++;
142
+ open(")");
143
+ }
144
+ else if (c === "`")
145
+ open("`");
146
+ else {
147
+ if (c === "$")
148
+ literal = false;
149
+ text += c;
150
+ }
151
+ continue;
152
+ }
153
+ if (c === "\\") {
154
+ if (next === "\n")
155
+ i++;
156
+ else if (next !== undefined) {
157
+ text += script[++i];
158
+ wordQuoted = true;
159
+ active = true;
160
+ }
161
+ continue;
162
+ }
163
+ if (c === "'" || c === '"') {
164
+ quote = c;
165
+ wordQuoted = true;
166
+ active = true;
167
+ continue;
168
+ }
169
+ if (c === "#" && !active) {
170
+ while (i + 1 < script.length && script[i + 1] !== "\n")
171
+ i++;
172
+ continue;
173
+ }
174
+ if (c === "$" && (next === "(" || next === "{")) {
175
+ if (next === "(") {
176
+ i++;
177
+ open(")");
178
+ }
179
+ else {
180
+ literal = false;
181
+ bare = true;
182
+ active = true;
183
+ text += c;
184
+ }
185
+ continue;
186
+ }
187
+ if (c === "$") {
188
+ literal = false;
189
+ bare = true;
190
+ active = true;
191
+ text += c;
192
+ continue;
193
+ }
194
+ if (c === "`") {
195
+ if (stack.at(-1)?.closer === "`")
196
+ close();
197
+ else
198
+ open("`");
199
+ continue;
200
+ }
201
+ if (c === ")" && stack.at(-1)?.closer === ")") {
202
+ close();
203
+ continue;
204
+ }
205
+ if (c === ">" || c === "<") {
206
+ if (/^\d+$/.test(text)) {
207
+ text = "";
208
+ active = false;
209
+ }
210
+ endWord();
211
+ // `<(cmd)` and `>(cmd)` are process substitutions: their bodies are commands.
212
+ if (next === "(") {
213
+ i++;
214
+ open(")");
215
+ continue;
216
+ }
217
+ // `<<` and `<<-` start a here-document (`<<<` is a here-string, an ordinary word).
218
+ const heredoc = c === "<" && next === "<" && script[i + 2] !== "<"
219
+ ? script[i + 2] === "-"
220
+ ? "<<-"
221
+ : "<<"
222
+ : "";
223
+ const start = i;
224
+ while (/[<>|&-]/.test(script[i + 1] ?? "") && (script[i + 1] !== "-" || heredoc))
225
+ i++;
226
+ redirectNext = true;
227
+ redirectWrites = script.slice(start, i + 1).includes(">");
228
+ redirectHere = script.slice(start, i + 1) === "<<<";
229
+ if (heredoc)
230
+ delimiterNext = heredoc;
231
+ continue;
232
+ }
233
+ if (c === "&" && next === ">")
234
+ continue;
235
+ if (c === "\n" && (pending.length || delimiterNext))
236
+ endWord();
237
+ if (c === "\n" && pending.length) {
238
+ // The bodies follow, in order, each up to a line that is exactly its delimiter.
239
+ endSegment();
240
+ for (const doc of pending) {
241
+ const lines = [];
242
+ let found = false;
243
+ while (i + 1 < script.length) {
244
+ const end = script.indexOf("\n", i + 1);
245
+ const line = script.slice(i + 1, end < 0 ? script.length : end);
246
+ i = end < 0 ? script.length - 1 : end;
247
+ if ((doc.strip ? line.replace(/^\t+/, "") : line) === doc.delimiter) {
248
+ found = true;
249
+ break;
250
+ }
251
+ lines.push(line);
252
+ }
253
+ if (!found)
254
+ unterminated = true;
255
+ const body = lines.join("\n");
256
+ doc.segment.push({
257
+ text: body,
258
+ literal: true,
259
+ redirect: true,
260
+ heredoc: true,
261
+ ...(doc.quoted ? { quoted: true } : {}),
262
+ });
263
+ // With an unquoted delimiter the shell expands `$(...)`, backticks and `${...}` in the
264
+ // body, as in a double-quoted string: those substitutions run, so they are commands here.
265
+ if (!doc.quoted && /[$`]/.test(body)) {
266
+ // Read with the shell's own rules for a here-document body (see `scan`).
267
+ const inner = scan(body, true);
268
+ if (!inner.complete)
269
+ unterminated = true;
270
+ // The last segment is the body itself as one word; the others are its substitutions.
271
+ segments.push(...inner.segments.slice(0, -1));
272
+ }
273
+ }
274
+ pending = [];
275
+ continue;
276
+ }
277
+ if (/[;&|()\n]/.test(c)) {
278
+ endSegment();
279
+ // `a | b` and `a |& b`, not `a || b`; `a | (b)` pipes into the subshell's first command.
280
+ const pipe = c === "|" && next !== "|" && script[i - 1] !== "|";
281
+ if (pipe)
282
+ pipeDepth = groups.length;
283
+ pipeNext =
284
+ pipe || (c === "&" && script[i - 1] === "|" && pipeNext) || (c === "(" && pipeNext);
285
+ if (c === "(")
286
+ groups.push("(");
287
+ else if (c === ")" && groups[groups.length - 1] === "(")
288
+ groups.pop();
289
+ continue;
290
+ }
291
+ if (/\s/.test(c)) {
292
+ endWord();
293
+ continue;
294
+ }
295
+ text += c;
296
+ active = true;
297
+ }
298
+ const complete = quote === (heredoc ? "h" : "") && stack.length === 0 && !unterminated && !pending.length;
299
+ while (stack.length)
300
+ close();
301
+ endSegment();
302
+ return { segments, complete };
303
+ }
304
+ /** Programs that run the rest of their words as a command, with the options each takes a value for. */
305
+ const WRAPPERS = {
306
+ env: ["-u", "--unset", "-C", "--chdir", "-S", "--split-string"],
307
+ sudo: ["-u", "-g", "-C", "-h", "-p", "-r", "-t", "-U", "-D"],
308
+ doas: ["-u", "-C"],
309
+ command: [],
310
+ builtin: [],
311
+ exec: ["-a"],
312
+ nohup: [],
313
+ time: [],
314
+ nice: ["-n", "--adjustment"],
315
+ ionice: ["-c", "-n", "-p", "-t"],
316
+ stdbuf: ["-i", "-o", "-e"],
317
+ timeout: ["-s", "--signal", "-k", "--kill-after"],
318
+ xargs: ["-I", "-n", "-L", "-P", "-d", "-s", "-E", "-a", "--arg-file", "--delimiter"],
319
+ nocorrect: [],
320
+ noglob: [],
321
+ watch: ["-n", "--interval", "-q", "--equexit"],
322
+ };
323
+ /** Group keywords and what each closer closes. */
324
+ const OPENERS = new Set(["{", "if", "while", "until", "for", "case", "select"]);
325
+ const CLOSERS = {
326
+ "}": ["{"],
327
+ fi: ["if"],
328
+ done: ["while", "until", "for", "select"],
329
+ esac: ["case"],
330
+ };
331
+ /** Words that may come before a command in its segment (`then sh`, `do sh`, `! sh`). */
332
+ const GROUP_LEAD = new Set(["then", "do", "else", "elif", "!", "{", "if", "while", "until"]);
333
+ const KEYWORDS = new Set(["then", "do", "else", "elif", "if", "while", "until", "!", "{", "}"]);
334
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "mksh", "fish"]);
335
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/;
336
+ function basenameOf(text) {
337
+ return text.split(/[\\/]/).pop() ?? text;
338
+ }
339
+ /** The program and arguments of one segment, behind assignments, keywords and wrappers. */
340
+ export function command(segment) {
341
+ const redirects = segment.filter((word) => word.redirect);
342
+ const words = segment.filter((word) => !word.redirect);
343
+ const assignments = [];
344
+ let i = 0;
345
+ for (let depth = 0; depth < 8; depth++) {
346
+ while (i < words.length && ASSIGNMENT.test(words[i]?.text ?? ""))
347
+ assignments.push(words[i++]);
348
+ while (i < words.length && KEYWORDS.has(words[i]?.text ?? ""))
349
+ i++;
350
+ const name = basenameOf(words[i]?.text ?? "");
351
+ if (!words[i]?.literal || !(name in WRAPPERS))
352
+ break;
353
+ const valued = WRAPPERS[name];
354
+ i++;
355
+ while (i < words.length) {
356
+ const word = words[i];
357
+ if (word.text === "--") {
358
+ i++;
359
+ break;
360
+ }
361
+ if (name === "env" && ASSIGNMENT.test(word.text))
362
+ assignments.push(word);
363
+ else if (name === "timeout" && /^[0-9.]+[smhd]?$/.test(word.text)) {
364
+ i++;
365
+ break;
366
+ }
367
+ else if (!word.text.startsWith("-"))
368
+ break;
369
+ else if (valued.includes(word.text))
370
+ i++;
371
+ i++;
372
+ }
373
+ }
374
+ return { assignments, program: words[i], args: words.slice(i + 1), redirects };
375
+ }
376
+ /** The script a shell or `eval` runs, when the segment is one: `bash -c '...'`, `eval ...`. */
377
+ export function innerScript(cmd) {
378
+ const program = cmd.program;
379
+ if (!program?.literal)
380
+ return undefined;
381
+ const name = basenameOf(program.text);
382
+ if (name === "eval")
383
+ return {
384
+ script: cmd.args.map((word) => word.text).join(" "),
385
+ literal: cmd.args.every((word) => word.literal),
386
+ };
387
+ if (!SHELLS.has(name))
388
+ return undefined;
389
+ const flag = cmd.args.findIndex((word) => /^-[a-zA-Z]+$/.test(word.text) && word.text.includes("c"));
390
+ if (flag < 0)
391
+ return undefined;
392
+ const body = cmd.args.slice(flag + 1).find((word) => !word.text.startsWith("-"));
393
+ return body ? { script: body.text, literal: body.literal } : undefined;
394
+ }
395
+ //# sourceMappingURL=shellscan.js.map
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Longest word or pattern matched here. Anything longer fails closed (counts as reaching the
3
+ * state), so no input can make matching slow.
4
+ */
5
+ export declare const MAX_TARGET = 4096;
6
+ /**
7
+ * The state directories: every `acp-<uid>-*` directory in each temp root, plus a sample one in the
8
+ * temp directory the service uses, so a pattern that would match a later session's directory
9
+ * counts too. Each is listed under both the temp directory as the system gives it (on macOS the
10
+ * logical `/var/folders/...`, where the service creates them) and its real path
11
+ * (`/private/var/folders/...`), so a pattern written against either form matches.
12
+ */
13
+ export declare function stateDirs(): string[];
14
+ /** Whether a shell glob matches `text`. `*` matches any run, `/` included (as `find -path` does). */
15
+ export declare function globMatch(pattern: string, text: string, fold?: boolean): boolean;
16
+ export declare const hasGlob: (text: string) => boolean;
17
+ /** A shell word's text with the temp variables filled in and any other expansion read as `*`. */
18
+ export declare function stateText(text: string, literal: boolean): string;
19
+ /**
20
+ * Whether a target word (as `stateText` gives it) could name the policy service's state from any
21
+ * of `cwds`: a state directory, a file in one, anything inside one, or, for a delete or move
22
+ * (`removes`), a directory the state lies in (`rm -rf $TMPDIR`, `rm -rf /tmp/*`).
23
+ */
24
+ export declare function namesState(text: string, cwds: Iterable<string>, removes: boolean): boolean;
25
+ /**
26
+ * Whether `find` with an action that deletes or runs something could reach the state: a start
27
+ * directory in or above a state directory, and a `-name`/`-iname` pattern that can match a name on
28
+ * the way down, a `-path`/`-ipath` pattern that can match the path find prints, a `-regex`
29
+ * (not followed: fails closed), or no such filter at all.
30
+ */
31
+ export declare function findReachesState(args: string[], cwds: Iterable<string>): boolean;
32
+ /**
33
+ * Whether inline interpreter code could change the state. It names `acp`; or it deletes, moves or
34
+ * writes files and either computes the temp directory at run time (an environment variable or an
35
+ * API: the result is the directory the state lies in), or names a path that could reach the state
36
+ * the way a shell target does: a state directory, a directory above one (the temp root itself), a
37
+ * glob matching one, or a path built at run time (`f'/tmp/{x}'`, `'/tmp/' + x`, `"$TMPDIR/$x"`,
38
+ * read as a glob). A literal path into another directory in temp (`/tmp/pm-x/notes.md`) is not.
39
+ */
40
+ export declare function codeTouchesState(code: string, cwds: Iterable<string>): boolean;
41
+ //# sourceMappingURL=statepaths.d.ts.map