@agent-corpus/policy-manager 0.2.1 → 0.3.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/dist/evidence.js CHANGED
@@ -24,10 +24,12 @@ export function inside(root, path) {
24
24
  const rel = relative(root, path);
25
25
  return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
26
26
  }
27
+ const CREDENTIAL_CONFIG_DIRS = /(?:^|[\\/])\.config[\\/](?:gh|gcloud|op|hub)(?:[\\/]|$)/i;
27
28
  export function sensitive(path) {
28
- return path
29
- .split(/[\\/]/)
30
- .some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.kube|\.npmrc|\.netrc|credentials?|secrets?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part));
29
+ return (CREDENTIAL_CONFIG_DIRS.test(path) ||
30
+ path
31
+ .split(/[\\/]/)
32
+ .some((part) => /^(?:\.git|\.env(?:\..*)?|\.ssh|\.aws|\.azure|\.gcloud|\.docker|\.gnupg|\.password-store|\.git-credentials|\.vault-token|\.pgpass|\.my\.cnf|\.pypirc|\.npmrc|\.netrc|\.kube|credentials?|secrets?|id_rsa|id_ed25519|id_ecdsa|kubeconfig|terraform\.tfstate(?:\..*)?|.*\.(?:pem|key|pfx|p12))$/i.test(part)));
31
33
  }
32
34
  export function protectedPath(path) {
33
35
  return path
package/dist/merged.js CHANGED
@@ -62,7 +62,7 @@ export function mergedEvidence(cwd, ref) {
62
62
  },
63
63
  }).trim();
64
64
  const cherry = git(cwd, ["cherry", into, synthetic]);
65
- if (cherry && cherry.split("\n").every((line) => line.startsWith("-")))
65
+ if (cherry?.split("\n").every((line) => line.startsWith("-")))
66
66
  return {
67
67
  merged: true,
68
68
  how: "patch-equivalent to a squash or rebase merge into origin default",
@@ -3,7 +3,7 @@ import { basename, join, resolve } from "node:path";
3
3
  import { branchEvidence, canonical, inside, isProtectedPath, pathEvidence, sensitive, } from "./evidence.js";
4
4
  import { mergedEvidence, remoteTipMatches } from "./merged.js";
5
5
  import { evaluateArgv, result } from "./policy.js";
6
- import { parseShell } from "./shell.js";
6
+ import { parseShell, SUBSTITUTION } from "./shell.js";
7
7
  /**
8
8
  * Permissive profile: approve everything except effects that are destructive, irreversible,
9
9
  * outward-facing, or touch credentials and protected configuration. The default for anything not
@@ -49,6 +49,22 @@ const WRITERS = new Set([
49
49
  "chown",
50
50
  ]);
51
51
  const WRAPPERS = new Set(["env", "nohup", "time", "command", "nice", "timeout", "xargs"]);
52
+ /**
53
+ * Programs whose behaviour cannot be changed by an unknown argument: they only print or compare
54
+ * strings. The output of a command substitution may be an argument of these and of nothing else,
55
+ * because for any other program it could be a flag, a path or a subcommand the checks never saw.
56
+ */
57
+ const SUBSTITUTION_OK = new Set([
58
+ "echo",
59
+ "printf",
60
+ "true",
61
+ "false",
62
+ "test",
63
+ "[",
64
+ "basename",
65
+ "dirname",
66
+ ]);
67
+ const MAX_SUBSTITUTION_DEPTH = 3;
52
68
  const BANNED_ENV = /^(?:LD_|DYLD_|GIT_|PYTHON|NODE_OPTIONS$|PATH$|HOME$|BASH_ENV$|ENV$|SHELL$|PAGER$|EDITOR$|GH_TOKEN$|GITHUB_TOKEN$)/;
53
69
  const FORCE_PUSH = ["--force", "--force-with-lease", "--force-if-includes", "--mirror", "--prune"];
54
70
  function human(request, category, reason) {
@@ -345,6 +361,9 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
345
361
  for (const [name] of command.env)
346
362
  if (BANNED_ENV.test(name))
347
363
  return human(request, "unknown", "Environment override requires human review");
364
+ for (const redirect of command.redirects)
365
+ if (redirect.target.includes(SUBSTITUTION))
366
+ return human(request, "unknown", "Command substitution in a redirection requires human review");
348
367
  for (const redirect of command.redirects) {
349
368
  // `>& word` duplicates a descriptor only when word is a number or `-`; otherwise it names a file.
350
369
  if (redirect.target === "/dev/null" ||
@@ -364,6 +383,13 @@ function simpleDecision(request, command, profile, depth, stageIndex, cwd) {
364
383
  return human(request, "unknown", "Environment override requires human review");
365
384
  const argv = unwrapped.argv;
366
385
  const program = basename(argv[0] ?? "");
386
+ // Words a wrapper consumed (env assignments, options, durations) are gone from `argv`, but an
387
+ // unquoted substitution in them can still split into extra words and pick a different program.
388
+ if (command.argv.slice(0, command.argv.length - argv.length).some((w) => w.includes(SUBSTITUTION)))
389
+ return human(request, "unknown", "Command substitution inside a wrapper command requires human review");
390
+ if (argv.some((word) => word.includes(SUBSTITUTION)) &&
391
+ (argv[0]?.includes(SUBSTITUTION) || !SUBSTITUTION_OK.has(program)))
392
+ return human(request, "unknown", "Command substitution output is only accepted as an argument to echo, printf and similar");
367
393
  const args = argv.slice(1);
368
394
  const joined = argv.join(" ");
369
395
  if (profile.humanPatterns.some((pattern) => pattern.test(joined)))
@@ -460,12 +486,24 @@ export function commandDecision(request, command, profile, depth = 0, start = [r
460
486
  let last;
461
487
  for (const pipeline of pipelines)
462
488
  for (const [index, simple] of pipeline.entries()) {
489
+ // Command substitutions run before the command, in the directories it could start from.
490
+ for (const inner of simple.subs) {
491
+ if (depth >= MAX_SUBSTITUTION_DEPTH)
492
+ return human(request, "unknown", "Command substitutions are nested too deeply");
493
+ const own = commandDecision(request, inner, profile, depth + 1, cwds);
494
+ if (own.decision !== "approve")
495
+ return own;
496
+ }
463
497
  if (basename(simple.argv[0] ?? "") === "cd") {
464
498
  const target = simple.argv.slice(1).filter((word) => word !== "--");
465
499
  // A bare `cd` and `~` or `~/x` go to the home directory; `~user` and `-` stay with a human.
466
500
  const raw = target.length === 0 ? "~" : target[0];
467
501
  const word = raw === "~" || raw?.startsWith("~/") ? join(homedir(), raw.slice(1)) : raw;
468
- if (target.length > 1 || !word || /^~|[*?[\]]/.test(word) || word.startsWith("-"))
502
+ if (target.length > 1 ||
503
+ !word ||
504
+ word.includes(SUBSTITUTION) ||
505
+ /^~|[*?[\]]/.test(word) ||
506
+ word.startsWith("-"))
469
507
  return human(request, "unknown", "Directory change requires human review");
470
508
  // The cd's own redirections, env assignments and organization patterns run first, in the
471
509
  // directories it could start from.
package/dist/shell.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ /** Stands for the unknown output of a command substitution inside a word. */
2
+ export declare const SUBSTITUTION = "\uE000";
1
3
  export interface Redirect {
2
4
  fd: string;
3
5
  op: ">" | ">>" | "<" | ">&";
@@ -7,6 +9,8 @@ export interface SimpleCommand {
7
9
  env: Array<[string, string]>;
8
10
  argv: string[];
9
11
  redirects: Redirect[];
12
+ /** Inner commands of `$(...)` and backticks in this command's words, in order. */
13
+ subs: string[];
10
14
  }
11
15
  export type Pipeline = SimpleCommand[];
12
16
  export declare function parseShell(command: string): Pipeline[] | undefined;
package/dist/shell.js CHANGED
@@ -1,15 +1,141 @@
1
1
  // Parses a bounded subset of POSIX shell: simple commands joined by `;`, newlines, `&&`, `||`
2
2
  // and `|`, with quoting, leading VAR=value assignments and file redirections. Anything whose
3
- // effects depend on expansion (`$`, backticks, subshells, braces, heredocs, background jobs,
4
- // comments, process substitution) is rejected so a caller can fall back to a human.
3
+ // effects depend on expansion is rejected so a caller can fall back to a human. Three kinds of
4
+ // expansion are understood: `$HOME`, which is substituted because its value is known before
5
+ // anything runs; command substitution (`$(...)` and backticks), whose inner command is returned in
6
+ // `subs` for the caller to judge; and parameters whose value is unknown (`$?`, `$#`, `$$`,
7
+ // `PIPESTATUS`). The output of the last two is represented in a word by SUBSTITUTION. Everything
8
+ // else (other variables, arithmetic, braces, subshells, heredocs, background jobs, comments,
9
+ // process substitution) is rejected.
10
+ import { homedir } from "node:os";
11
+ /** Stands for the unknown output of a command substitution inside a word. */
12
+ export const SUBSTITUTION = "\uE000";
5
13
  const ASSIGNMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
+ /** Index of the `)` that closes a `$(` whose body starts at `start`, honouring quotes and nesting. */
15
+ function closingParen(command, start) {
16
+ let depth = 1;
17
+ let j = start;
18
+ while (j < command.length) {
19
+ const c = command[j];
20
+ if (c === "\\")
21
+ j += 2;
22
+ else if (c === "'") {
23
+ const end = command.indexOf("'", j + 1);
24
+ if (end < 0)
25
+ return undefined;
26
+ j = end + 1;
27
+ }
28
+ else if (c === '"') {
29
+ j++;
30
+ while (j < command.length && command[j] !== '"') {
31
+ const d = command[j];
32
+ if (d === "\\")
33
+ j += 2;
34
+ else if (d === "$" && command[j + 1] === "(") {
35
+ const end = closingParen(command, j + 2);
36
+ if (end === undefined)
37
+ return undefined;
38
+ j = end + 1;
39
+ }
40
+ else if (d === "`") {
41
+ const end = closingBacktick(command, j + 1);
42
+ if (end === undefined)
43
+ return undefined;
44
+ j = end + 1;
45
+ }
46
+ else
47
+ j++;
48
+ }
49
+ if (j >= command.length)
50
+ return undefined;
51
+ j++;
52
+ }
53
+ else if (c === "`") {
54
+ const end = closingBacktick(command, j + 1);
55
+ if (end === undefined)
56
+ return undefined;
57
+ j = end + 1;
58
+ }
59
+ else {
60
+ if (c === "(")
61
+ depth++;
62
+ else if (c === ")" && --depth === 0)
63
+ return j;
64
+ j++;
65
+ }
66
+ }
67
+ return undefined;
68
+ }
69
+ function closingBacktick(command, start) {
70
+ for (let j = start; j < command.length; j++) {
71
+ if (command[j] === "\\")
72
+ j++;
73
+ else if (command[j] === "`")
74
+ return j;
75
+ }
76
+ return undefined;
77
+ }
78
+ // Only HOME has a value that is known before anything runs. The others are recognised so a
79
+ // harmless read like `echo "exit: $?"` can be judged, but their value is unknown: `$?` and friends
80
+ // change per run, and an array element such as `${PIPESTATUS[5]}` is empty when out of range.
81
+ // They are therefore represented by SUBSTITUTION, never by a made-up value.
82
+ const UNKNOWN_PARAMETER = /^(?:(?:PIPESTATUS|pipestatus)(?:\[[0-9@*]+\])?)$/;
83
+ /**
84
+ * Reads the expansion that starts at `command[at] === "$"`. Returns the text it stands for and the
85
+ * index after it, any command substitution body, or undefined for an expansion that is not
86
+ * understood.
87
+ */
88
+ function expansion(command, at) {
89
+ const rest = command.slice(at + 1);
90
+ const home = () => {
91
+ const path = homedir();
92
+ // The text is inserted as-is and never re-parsed, so a backslash (a Windows separator) is
93
+ // harmless; whitespace and glob characters would split or expand when unquoted.
94
+ return /[\s*?[\]'"$`]/.test(path) ? undefined : path;
95
+ };
96
+ if (rest[0] === "(") {
97
+ if (rest[1] === "(")
98
+ return undefined; // arithmetic expansion
99
+ const end = closingParen(command, at + 2);
100
+ if (end === undefined)
101
+ return undefined;
102
+ return { text: SUBSTITUTION, next: end + 1, inner: command.slice(at + 2, end) };
103
+ }
104
+ if (rest[0] === "{") {
105
+ const close = rest.indexOf("}");
106
+ const name = close > 0 ? rest.slice(1, close) : "";
107
+ const next = at + close + 2;
108
+ if (name === "HOME") {
109
+ const text = home();
110
+ return text === undefined ? undefined : { text, next };
111
+ }
112
+ return UNKNOWN_PARAMETER.test(name) ? { text: SUBSTITUTION, next } : undefined;
113
+ }
114
+ if (rest[0] && "?#$".includes(rest[0]))
115
+ return { text: SUBSTITUTION, next: at + 2 };
116
+ const name = /^[A-Za-z_][A-Za-z0-9_]*/.exec(rest)?.[0];
117
+ const next = at + 1 + (name?.length ?? 0);
118
+ if (name === "HOME") {
119
+ const text = home();
120
+ return text === undefined ? undefined : { text, next };
121
+ }
122
+ return name && UNKNOWN_PARAMETER.test(name) ? { text: SUBSTITUTION, next } : undefined;
123
+ }
124
+ /** Body of a backtick substitution: backslash escapes `\``, `\\` and `\$` are removed first. */
125
+ function backtickBody(raw) {
126
+ return raw.replace(/\\([`\\$])/g, "$1");
127
+ }
6
128
  export function parseShell(command) {
7
- if (!command || command.includes("\0") || command.includes("\r"))
129
+ if (!command ||
130
+ command.includes("\0") ||
131
+ command.includes("\r") ||
132
+ command.includes(SUBSTITUTION))
8
133
  return undefined;
9
134
  const pipelines = [];
10
135
  let pipeline = [];
11
136
  let words = [];
12
137
  let redirects = [];
138
+ let subs = [];
13
139
  let pendingRedirect;
14
140
  let current = "";
15
141
  let active = false;
@@ -61,9 +187,10 @@ export function parseShell(command) {
61
187
  // an assignment this parser cannot represent: reject it instead of judging it as the program.
62
188
  if (argv[0]?.includes("="))
63
189
  return false;
64
- pipeline.push({ env, argv, redirects });
190
+ pipeline.push({ env, argv, redirects, subs });
65
191
  words = [];
66
192
  redirects = [];
193
+ subs = [];
67
194
  return true;
68
195
  };
69
196
  const endPipeline = (allowEmpty) => {
@@ -93,8 +220,25 @@ export function parseShell(command) {
93
220
  current += char;
94
221
  continue;
95
222
  }
96
- if (char === "$" || char === "`")
97
- return undefined;
223
+ if (char === "$") {
224
+ const expanded = expansion(command, i);
225
+ if (!expanded)
226
+ return undefined;
227
+ current += expanded.text;
228
+ if (expanded.inner !== undefined)
229
+ subs.push(expanded.inner);
230
+ i = expanded.next - 1;
231
+ continue;
232
+ }
233
+ if (char === "`") {
234
+ const end = closingBacktick(command, i + 1);
235
+ if (end === undefined)
236
+ return undefined;
237
+ subs.push(backtickBody(command.slice(i + 1, end)));
238
+ current += SUBSTITUTION;
239
+ i = end;
240
+ continue;
241
+ }
98
242
  }
99
243
  if (char === quote)
100
244
  quote = "";
@@ -123,7 +267,32 @@ export function parseShell(command) {
123
267
  i++;
124
268
  continue;
125
269
  }
126
- if (/[`$(){}#!]/.test(char)) {
270
+ if (char === "$") {
271
+ const expanded = expansion(command, i);
272
+ if (!expanded)
273
+ return undefined;
274
+ if (eqAt < 0)
275
+ plain = false;
276
+ current += expanded.text;
277
+ active = true;
278
+ if (expanded.inner !== undefined)
279
+ subs.push(expanded.inner);
280
+ i = expanded.next - 1;
281
+ continue;
282
+ }
283
+ if (char === "`") {
284
+ const end = closingBacktick(command, i + 1);
285
+ if (end === undefined)
286
+ return undefined;
287
+ if (eqAt < 0)
288
+ plain = false;
289
+ subs.push(backtickBody(command.slice(i + 1, end)));
290
+ current += SUBSTITUTION;
291
+ active = true;
292
+ i = end;
293
+ continue;
294
+ }
295
+ if (/[(){}#!]/.test(char)) {
127
296
  // `#` only starts a comment at a word boundary, but rejecting it everywhere is simpler.
128
297
  return undefined;
129
298
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-corpus/policy-manager",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Deterministic, session-scoped permission decisions with audit logs and bounded AI classification.",
5
5
  "keywords": [
6
6
  "coding-agent",