@jackice/pi-approval-gate 0.1.6 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ - Configurable policy in `settings.json` under `approvalGate`: `mode`, `patterns` (ordered `match`/`approval` glob rules), `extraDangerous`, and `redirects`. Read on every command, so edits apply without a restart or a new release.
6
+ - **Default behavior change:** `mode` defaults to `yolo`, which follows OMP's `bash.patterns` semantics — only the critical patterns and your own `prompt`/`deny` rules prompt. The previous full analysis (`rm -rf <dir>`, `git push`, `gh pr merge`, `npm publish`, interpreters, unparseable commands) moved to `mode: "strict"`. Critical patterns also prompt in `yolo` (OMP's `resolveApproval` auto-approves them there).
7
+ - Adds OMP's `CRITICAL_BASH_PATTERNS` (20 patterns) as the critical set; it matches the raw command line and does not depend on the tokenizer.
8
+ - `patterns` follow OMP's `bash.patterns`: the first matching rule wins, `allow` only vouches for a single simple command, and `deny`/`prompt` also match every shell segment, including segments built from expansions (`cd /tmp && rm -rf "$dir"`). Put narrow `deny` rules before broader `allow` rules.
9
+ - The spawn-time binding check now uses the same policy as the approval decision; previously a permitted command could fail with `approval binding mismatch`.
10
+ - Writes to `/dev/null` (`>/dev/null`, `2>/dev/null`, `&>/dev/null`, `>>/dev/null`) no longer force approval in `strict` mode. `yolo` does not tokenize, so redirection alone never prompts there.
11
+
3
12
  ## 0.1.6
4
13
 
5
14
  - Use a full-width rounded approval dialog with a warning heading and a highlighted selection.
package/README.md CHANGED
@@ -5,7 +5,7 @@ An approval extension for Pi's supported Bash execution paths. It binds user app
5
5
  - Verified with Pi `1.6.0` and `@jackice/pi-ui` `0.4.2`. The native selection list is the default approval UI.
6
6
  - Commands that require approval are denied when no supported interactive UI is available, in subagents, or on timeout, abort, reload, or shutdown.
7
7
  - Registers a replacement `bash` tool through Pi's extension API. No Pi source changes are required.
8
- - Commands the policy cannot parse require approval.
8
+ - Only critical patterns prompt by default (`approvalGate.mode: "yolo"`, matching OMP). Unparseable commands no longer require approval; set `mode: "strict"` to restore the old full-analysis behavior.
9
9
  - Honors `shellCommandPrefix` and `shellPath` settings and shows the final command before execution.
10
10
  - Known limit: Pi `1.6.0` has no synchronous pre-spawn hook, so a cancellation in the gap between authorization and `spawn()` can still start the command. See the [review notes](docs/security-review.md). This is not a sandbox.
11
11
 
@@ -44,6 +44,50 @@ The native-list view is the default. Both views start on **Allow once** and requ
44
44
 
45
45
  It is off by default. The guard is separate from approval: it runs first for both the tool and `user_bash`, and a returned message stops the command.
46
46
 
47
+ ### Configurable policy
48
+
49
+ `approvalGate` sets the default posture and extends the built-in policy without a new release. It is read on every command, so edits apply to the next command with no restart. Unreadable entries are ignored and reported once at session start.
50
+
51
+ ```json
52
+ {
53
+ "approvalGate": {
54
+ "mode": "yolo",
55
+ "redirects": ["/dev/null"],
56
+ "extraDangerous": ["kubectl", "terraform"],
57
+ "patterns": [
58
+ { "match": "git *", "approval": "allow" },
59
+ { "match": "curl *", "approval": "prompt" },
60
+ { "match": "deploy *", "approval": "deny" }
61
+ ]
62
+ }
63
+ }
64
+ ```
65
+
66
+ | Field | Default | Meaning |
67
+ | --- | --- | --- |
68
+ | `mode` | `"yolo"` | Default posture. See the table below. |
69
+ | `redirects` | `["/dev/null"]` | Redirection targets dropped before tokenizing. |
70
+ | `extraDangerous` | `[]` | Command names that always prompt; matched at command position, including through wrappers and `sh -c`. |
71
+ | `patterns` | `[]` | Ordered glob rules (`*` only); the first matching rule wins. |
72
+
73
+ Modes:
74
+
75
+ | Mode | Prompts for | Notes |
76
+ | --- | --- | --- |
77
+ | `yolo` (default) | Critical patterns only | OMP's `yolo` also auto-approves critical commands (its bare critical override is ignored outside non-yolo modes). This extension deliberately keeps the critical floor, so `rm -rf /` still prompts. Full-analysis checks such as `rm -rf build`, `git push`, `gh pr merge`, `npm publish`, and unparseable commands (loops, `"$var"`) do not prompt. |
78
+ | `strict` | The full built-in analysis plus critical patterns | Dangerous commands, remote writes, interpreters, `rm`/`sudo`, unparseable commands. This was the pre-0.1.7 behavior. |
79
+ | `always-ask` | Every command | Only `deny` and `allow` rules can change the outcome. |
80
+
81
+ `yolo` relies on the same critical set as OMP's `CRITICAL_BASH_PATTERNS`, matched against the raw command line: recursive `rm` on `/`, `sudo rm`, `chmod`/`chown -R` on `/`, fork bombs, writes to `/dev/sd*`, `mkfs`, `dd`/`shred` on devices, `cryptsetup`, writes to `/etc/passwd|shadow|sudoers`, `curl|sh`, process substitution from `curl`, `eval "$(curl ...)"`, `kill -9 1`, `shutdown`/`reboot`/`init 0`, and `nc -e`.
82
+
83
+ `approval` values (all modes):
84
+
85
+ - `deny` rejects the command without a dialog; the model sees `Blocked by bash pattern: <match>`.
86
+ - `prompt` shows the approval dialog.
87
+ - `allow` skips the dialog, but only for a command the tokenizer can read as a single simple command. Any `;`, `&&`, `||`, `|`, `&`, `<`, `>`, `$(`, backtick, or `-c`/`--eval` option disables the rule, so `match: "git *"` never approves `git status && rm -rf build`.
88
+
89
+ Rule evaluation follows OMP's `bash.patterns`: the first matching rule wins, so put a narrow `deny` before a broader `allow` (`git push *` deny must precede `git *` allow). Order of checks: the matched rule's `deny`, then the mode's checks (critical patterns run first), then its `allow`, then its `prompt`, then the mode default. `deny` and `prompt` match the whole command and every shell segment, including segments built from expansions (`cd /tmp && rm -rf "$dir"`). A configured `allow` cannot approve `rm -rf /` in any mode.
90
+
47
91
  ## Verification
48
92
 
49
93
  Verified with Pi `1.6.0` in a real TUI, using a test provider and a disposable fixture:
package/index.ts CHANGED
@@ -15,7 +15,8 @@ import { createApprovalPrompt } from "./src/dialog.ts";
15
15
  import { createBashSpawnHook } from "./src/bash-hook.ts";
16
16
  import { verifyFinalBinding } from "./src/binding.ts";
17
17
  import { ApprovalGate, type ApprovalAuthorization, type ApprovalRequest } from "./src/gate.ts";
18
- import { dangerReason } from "./src/policy.ts";
18
+ import { parsePolicyConfig } from "./src/policy-config.ts";
19
+ import { evaluatePolicy } from "./src/policy-rules.ts";
19
20
  import { uvGuard } from "./src/uv-guard.ts";
20
21
 
21
22
  const DEFAULT_TIMEOUT_MS = 120_000;
@@ -56,6 +57,9 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
56
57
  return settings?.approvalGate?.guard === "uv" ? uvGuard : undefined;
57
58
  };
58
59
 
60
+ /** Also resolved per call, so a settings.json edit applies to the next command. */
61
+ const policyConfig = () => parsePolicyConfig(approvalGateSettings(pi)).config;
62
+
59
63
  const timeoutMs = () =>
60
64
  numberFlag(pi, "approval-timeout-ms", "PI_APPROVAL_TIMEOUT_MS", DEFAULT_TIMEOUT_MS);
61
65
  const gate = new ApprovalGate({ timeoutMs, maxPending: MAX_PENDING });
@@ -63,7 +67,7 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
63
67
  let shadowed = false;
64
68
 
65
69
  const template = createBashToolDefinition(process.cwd(), {
66
- spawnHook: (context) => verifyFinalBinding(undefined, undefined, context),
70
+ spawnHook: (context) => verifyFinalBinding(undefined, undefined, context, undefined, policyConfig()),
67
71
  });
68
72
  pi.registerTool({
69
73
  ...template,
@@ -82,10 +86,21 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
82
86
  details: undefined,
83
87
  };
84
88
  }
85
- const reason = dangerReason(finalCommand);
89
+ const config = policyConfig();
90
+ const verdict = evaluatePolicy(finalCommand, config);
91
+ if (verdict.decision === "deny") {
92
+ return {
93
+ content: [{
94
+ type: "text",
95
+ text: `${verdict.reason}; command was not executed.`,
96
+ }],
97
+ isError: true,
98
+ details: undefined,
99
+ };
100
+ }
86
101
  let authorization: ApprovalAuthorization | undefined;
87
102
  let approvalRequest: ApprovalRequest | undefined;
88
- if (reason !== undefined) {
103
+ if (verdict.decision === "prompt") {
89
104
  const approved = await gate.request(
90
105
  {
91
106
  sessionId: ctx.sessionManager.getSessionId(),
@@ -93,7 +108,7 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
93
108
  toolName: "bash",
94
109
  command: finalCommand,
95
110
  cwd,
96
- reason,
111
+ reason: verdict.reason ?? "policy",
97
112
  risk: "high",
98
113
  },
99
114
  {
@@ -125,6 +140,7 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
125
140
  authorization,
126
141
  request: approvalRequest,
127
142
  signal,
143
+ config,
128
144
  }));
129
145
  try {
130
146
  return await createBashToolDefinition(cwd, options).execute(
@@ -149,6 +165,13 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
149
165
  "error",
150
166
  );
151
167
  }
168
+ const { dropped } = parsePolicyConfig(approvalGateSettings(pi));
169
+ if (dropped > 0 && ctx.hasUI) {
170
+ ctx.ui.notify(
171
+ `approval gate: ignored ${dropped} invalid approvalGate setting(s)`,
172
+ "warning",
173
+ );
174
+ }
152
175
  });
153
176
 
154
177
  pi.on("tool_call", (event) => {
@@ -168,10 +191,21 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
168
191
  result: { output: blocked, exitCode: 1, cancelled: true, truncated: false },
169
192
  };
170
193
  }
171
- const reason = dangerReason(command);
194
+ const config = policyConfig();
195
+ const verdict = evaluatePolicy(command, config);
196
+ if (verdict.decision === "deny") {
197
+ return {
198
+ result: {
199
+ output: `${verdict.reason}; command was not executed.`,
200
+ exitCode: 1,
201
+ cancelled: true,
202
+ truncated: false,
203
+ },
204
+ };
205
+ }
172
206
  let authorization: ApprovalAuthorization | undefined;
173
207
  let request: ApprovalRequest | undefined;
174
- if (reason !== undefined) {
208
+ if (verdict.decision === "prompt") {
175
209
  const approved = await gate.request(
176
210
  {
177
211
  sessionId: ctx.sessionManager.getSessionId(),
@@ -179,7 +213,7 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
179
213
  toolName: "user_bash",
180
214
  command,
181
215
  cwd: event.cwd,
182
- reason,
216
+ reason: verdict.reason ?? "policy",
183
217
  risk: "high",
184
218
  },
185
219
  {
@@ -211,6 +245,7 @@ export default function approvalGateExtension(pi: ExtensionAPI): void {
211
245
  authorization,
212
246
  request,
213
247
  signal: options.signal,
248
+ config,
214
249
  });
215
250
  try {
216
251
  const context = spawnHook({ command, cwd, env: options.env ?? process.env });
@@ -239,6 +274,12 @@ interface ShellSettings {
239
274
  shellPath?: string;
240
275
  }
241
276
 
277
+ function approvalGateSettings(pi: ExtensionAPI): unknown {
278
+ const raw: unknown = typeof pi.getSettings === "function" ? pi.getSettings() : undefined;
279
+ if (typeof raw !== "object" || raw === null) return undefined;
280
+ return (raw as Record<string, unknown>).approvalGate;
281
+ }
282
+
242
283
  function shellSettings(pi: ExtensionAPI): ShellSettings {
243
284
  const raw: unknown = pi.getSettings();
244
285
  if (typeof raw !== "object" || raw === null) return {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jackice/pi-approval-gate",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Dangerous bash approval gate for Pi with final execution-parameter binding.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/bash-hook.ts CHANGED
@@ -2,6 +2,7 @@ import type { BashSpawnContext, BashSpawnHook } from "@earendil-works/pi-coding-
2
2
 
3
3
  import { verifyFinalBinding } from "./binding.ts";
4
4
  import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
5
+ import type { PolicyConfig } from "./policy-config.ts";
5
6
 
6
7
  export interface BashGuardOptions {
7
8
  /** Returns a message to block the command; runs before the approval is consumed. */
@@ -9,6 +10,8 @@ export interface BashGuardOptions {
9
10
  authorization?: ApprovalAuthorization | undefined;
10
11
  request?: ApprovalRequest | undefined;
11
12
  signal?: AbortSignal | undefined;
13
+ /** The same policy the verdict used; otherwise a permitted command fails binding at spawn. */
14
+ config?: PolicyConfig | undefined;
12
15
  }
13
16
 
14
17
  /**
@@ -18,6 +21,6 @@ export function createBashSpawnHook(options: BashGuardOptions): BashSpawnHook {
18
21
  return (context: BashSpawnContext): BashSpawnContext => {
19
22
  const blocked = options.guard?.(context.command);
20
23
  if (blocked !== undefined) throw new Error(blocked);
21
- return verifyFinalBinding(options.authorization, options.request, context, options.signal);
24
+ return verifyFinalBinding(options.authorization, options.request, context, options.signal, options.config);
22
25
  };
23
26
  }
package/src/binding.ts CHANGED
@@ -1,20 +1,25 @@
1
1
  import type { BashSpawnContext } from "@earendil-works/pi-coding-agent";
2
2
 
3
3
  import type { ApprovalAuthorization, ApprovalRequest } from "./gate.ts";
4
- import { isDangerousBash } from "./policy.ts";
4
+ import type { PolicyConfig } from "./policy-config.ts";
5
+ import { evaluatePolicy } from "./policy-rules.ts";
5
6
 
6
7
  /**
7
8
  * Verifies the final command and working directory right before spawn.
8
- * Dangerous commands must consume an approval bound to this exact call.
9
+ * Commands the active policy requires approval for must consume an approval bound to this
10
+ * exact call. `config` must be the same policy used to decide the verdict, otherwise the
11
+ * binding check and the dialog disagree and a permitted command fails at spawn.
9
12
  */
10
13
  export function verifyFinalBinding(
11
14
  authorization: ApprovalAuthorization | undefined,
12
15
  request: ApprovalRequest | undefined,
13
16
  context: BashSpawnContext,
14
17
  signal?: AbortSignal,
18
+ config?: PolicyConfig,
15
19
  ): BashSpawnContext {
16
20
  if (signal?.aborted) throw new Error("aborted");
17
- if (authorization !== undefined || isDangerousBash(context.command)) {
21
+ const requiresApproval = evaluatePolicy(context.command, config).decision !== "allow";
22
+ if (requiresApproval || authorization !== undefined) {
18
23
  const bound = authorization !== undefined
19
24
  && request !== undefined
20
25
  && authorization.consume({
@@ -0,0 +1,152 @@
1
+ export const DEFAULT_REDIRECT_TARGETS = ["/dev/null"];
2
+
3
+ /**
4
+ * Posture, defaulting to OMP's:
5
+ * - `yolo`: only the critical patterns apply, everything else runs.
6
+ * - `strict`: the full static analysis (dangerous commands, git push, gh merge, ...).
7
+ * - `always-ask`: every command needs approval.
8
+ */
9
+ export type PolicyMode = "yolo" | "strict" | "always-ask";
10
+
11
+ export const DEFAULT_MODE: PolicyMode = "yolo";
12
+
13
+ const MODES = new Set<string>(["yolo", "strict", "always-ask"]);
14
+
15
+ /** One bash rule: a glob over the whole command or a single segment; the first match wins. */
16
+ export interface BashPatternRule {
17
+ match: string;
18
+ approval: "allow" | "deny" | "prompt";
19
+ }
20
+
21
+ export interface PolicyConfig {
22
+ mode: PolicyMode;
23
+ /** Write redirection targets dropped before analysis. */
24
+ redirects: string[];
25
+ /** Command names added to the built-in dangerous set. */
26
+ extraDangerous: string[];
27
+ patterns: BashPatternRule[];
28
+ }
29
+
30
+ export interface PolicyConfigResult {
31
+ config: PolicyConfig;
32
+ /** Number of discarded invalid entries, reported once at session start. */
33
+ dropped: number;
34
+ }
35
+
36
+ interface ParsedList<T> {
37
+ values: T[];
38
+ dropped: number;
39
+ }
40
+
41
+ const APPROVALS = new Set(["allow", "deny", "prompt"]);
42
+
43
+ const globCache = new Map<string, RegExp>();
44
+
45
+ /** Normalizes whitespace the way OMP's `bash.patterns` does. */
46
+ export function normalizePattern(value: string): string {
47
+ return value.trim().replace(/\s+/gu, " ");
48
+ }
49
+
50
+ /** Only `*` is a wildcard; every other character is escaped literal text. */
51
+ export function compilePattern(pattern: string): RegExp {
52
+ const normalized = normalizePattern(pattern);
53
+ const cached = globCache.get(normalized);
54
+ if (cached !== undefined) return cached;
55
+ const escaped = normalized
56
+ .split("*")
57
+ .map((part) => part.replace(/[\\^$+?.()[\]{}|]/gu, "\\$&"))
58
+ .join(".*");
59
+ const compiled = new RegExp(`^${escaped}$`, "u");
60
+ globCache.set(normalized, compiled);
61
+ return compiled;
62
+ }
63
+
64
+ /** A non-array value is a configuration error: counted as dropped and replaced by the default. */
65
+ function parseField<T>(raw: unknown, parse: (value: unknown) => ParsedList<T>): ParsedList<T> {
66
+ if (raw === undefined) return { values: [], dropped: 0 };
67
+ if (!Array.isArray(raw)) return { values: [], dropped: 1 };
68
+ return parse(raw);
69
+ }
70
+
71
+ function parseRedirects(raw: unknown): ParsedList<string> {
72
+ const values: string[] = [];
73
+ let dropped = 0;
74
+ for (const item of Array.isArray(raw) ? raw : []) {
75
+ if (typeof item === "string" && item.startsWith("/") && !/[\s\0\r\n]/u.test(item)) values.push(item);
76
+ else dropped++;
77
+ }
78
+ return { values, dropped };
79
+ }
80
+
81
+ function parseExtraDangerous(raw: unknown): ParsedList<string> {
82
+ const values: string[] = [];
83
+ let dropped = 0;
84
+ for (const item of Array.isArray(raw) ? raw : []) {
85
+ if (typeof item === "string" && item.length > 0 && !/[\s/\0\r\n]/u.test(item)) values.push(item);
86
+ else dropped++;
87
+ }
88
+ return { values, dropped };
89
+ }
90
+
91
+ function parsePatterns(raw: unknown): ParsedList<BashPatternRule> {
92
+ const values: BashPatternRule[] = [];
93
+ let dropped = 0;
94
+ for (const item of Array.isArray(raw) ? raw : []) {
95
+ const rule = parsePattern(item);
96
+ if (rule === undefined) dropped++;
97
+ else values.push(rule);
98
+ }
99
+ return { values, dropped };
100
+ }
101
+
102
+ function parsePattern(item: unknown): BashPatternRule | undefined {
103
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return undefined;
104
+ const record = item as Record<string, unknown>;
105
+ if (typeof record.match !== "string") return undefined;
106
+ const match = normalizePattern(record.match);
107
+ if (match.length === 0) return undefined;
108
+ const approval = typeof record.approval === "string" ? record.approval.trim().toLowerCase() : "";
109
+ if (!APPROVALS.has(approval)) return undefined;
110
+ return { match, approval: approval as BashPatternRule["approval"] };
111
+ }
112
+
113
+ function parseMode(raw: unknown): { mode: PolicyMode; dropped: number } {
114
+ if (raw === undefined) return { mode: DEFAULT_MODE, dropped: 0 };
115
+ const normalized = typeof raw === "string" ? raw.trim().toLowerCase() : "";
116
+ if (!MODES.has(normalized)) return { mode: DEFAULT_MODE, dropped: 1 };
117
+ return { mode: normalized as PolicyMode, dropped: 0 };
118
+ }
119
+
120
+ /**
121
+ * Parses the `settings.approvalGate` section. Invalid entries are dropped and counted rather
122
+ * than thrown: a typo should cost one rule, not the whole extension.
123
+ */
124
+ export function parsePolicyConfig(raw: unknown): PolicyConfigResult {
125
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
126
+ return {
127
+ config: {
128
+ mode: DEFAULT_MODE,
129
+ redirects: [...DEFAULT_REDIRECT_TARGETS],
130
+ extraDangerous: [],
131
+ patterns: [],
132
+ },
133
+ dropped: 0,
134
+ };
135
+ }
136
+ const record = raw as Record<string, unknown>;
137
+ const mode = parseMode(record.mode);
138
+ const redirects = parseField(record.redirects, parseRedirects);
139
+ const extraDangerous = parseField(record.extraDangerous, parseExtraDangerous);
140
+ const patterns = parseField(record.patterns, parsePatterns);
141
+
142
+ return {
143
+ config: {
144
+ mode: mode.mode,
145
+ // An explicit list wins; an empty array accepts no redirection at all.
146
+ redirects: Array.isArray(record.redirects) ? redirects.values : [...DEFAULT_REDIRECT_TARGETS],
147
+ extraDangerous: extraDangerous.values,
148
+ patterns: patterns.values,
149
+ },
150
+ dropped: mode.dropped + redirects.dropped + extraDangerous.dropped + patterns.dropped,
151
+ };
152
+ }
@@ -0,0 +1,199 @@
1
+ import { criticalReason, dangerReason, extraDangerousReason } from "./policy.ts";
2
+ import {
3
+ compilePattern,
4
+ DEFAULT_MODE,
5
+ DEFAULT_REDIRECT_TARGETS,
6
+ normalizePattern,
7
+ type BashPatternRule,
8
+ type PolicyConfig,
9
+ } from "./policy-config.ts";
10
+
11
+ export type PolicyDecision = "allow" | "prompt" | "deny";
12
+
13
+ export interface PolicyVerdict {
14
+ decision: PolicyDecision;
15
+ reason?: string;
16
+ }
17
+
18
+ /**
19
+ * Characters that take a command out of "single simple command" territory. Any of them
20
+ * disables every `allow` rule; otherwise a narrow rule such as `git *` would ride along
21
+ * `git status && rm -rf build`.
22
+ */
23
+ const SHELL_CONTROL_CHARS: Record<string, true> = {
24
+ "\n": true,
25
+ "\r": true,
26
+ ";": true,
27
+ "&": true,
28
+ "|": true,
29
+ "<": true,
30
+ ">": true,
31
+ "`": true,
32
+ $: true,
33
+ "(": true,
34
+ ")": true,
35
+ };
36
+
37
+ /** Options that turn quoted or escaped arguments back into code (`sh -c`, `git -c alias.x=!...`). */
38
+ const REINTERPRET_OPTION = /(?:^|[ \t])(?:-[^-]*[ce]|--(?:command|eval))(?:[= \t]|$)/u;
39
+
40
+ /**
41
+ * Detects shell control semantics, mirroring OMP's `hasBashApprovalShellControl`: control
42
+ * characters inside quotes or after escapes are literals, but an option such as `-c`/`--eval`
43
+ * reinterprets them as code, so they count as control characters as well.
44
+ */
45
+ export function hasShellControl(command: string): boolean {
46
+ let quote: "'" | '"' | undefined;
47
+ let reinterpretable = false;
48
+ for (let index = 0; index < command.length; index++) {
49
+ const char = command[index] ?? "";
50
+ if (quote === "'") {
51
+ if (char === "'") quote = undefined;
52
+ else if (Object.hasOwn(SHELL_CONTROL_CHARS, char)) reinterpretable = true;
53
+ continue;
54
+ }
55
+ if (char === "\\") {
56
+ const escaped = command[index + 1];
57
+ if (escaped !== undefined && Object.hasOwn(SHELL_CONTROL_CHARS, escaped)) reinterpretable = true;
58
+ index++;
59
+ continue;
60
+ }
61
+ if (quote === '"') {
62
+ // `$` and backticks still expand inside double quotes.
63
+ if (char === '"') quote = undefined;
64
+ else if (char === "$" || char === "`") return true;
65
+ else if (Object.hasOwn(SHELL_CONTROL_CHARS, char)) reinterpretable = true;
66
+ continue;
67
+ }
68
+ if (char === "'" || char === '"') {
69
+ quote = char;
70
+ continue;
71
+ }
72
+ if (Object.hasOwn(SHELL_CONTROL_CHARS, char)) return true;
73
+ }
74
+ return reinterpretable && REINTERPRET_OPTION.test(command);
75
+ }
76
+
77
+ /**
78
+ * Best-effort segmenter ported from OMP's `tokenizeShellSegments`: it never fails, splitting on
79
+ * the visible shell operators instead of giving up on command substitution or heredocs. It
80
+ * complements the fail-closed tokenizer in `policy.ts`: that one feeds static analysis, this one
81
+ * lets `deny`/`prompt` rules see a dangerous segment inside a compound command.
82
+ */
83
+ export function ruleSegments(command: string): string[] {
84
+ const segments: string[][] = [];
85
+ let current: string[] = [];
86
+ let buffer = "";
87
+ let inSingle = false;
88
+ let inDouble = false;
89
+ const pushBuffer = () => {
90
+ if (buffer.length > 0) {
91
+ current.push(buffer);
92
+ buffer = "";
93
+ }
94
+ };
95
+ const pushSegment = () => {
96
+ pushBuffer();
97
+ if (current.length > 0) segments.push(current);
98
+ current = [];
99
+ };
100
+
101
+ for (let index = 0; index < command.length; index++) {
102
+ const char = command[index] ?? "";
103
+ if (inSingle) {
104
+ if (char === "'") inSingle = false;
105
+ else buffer += char;
106
+ continue;
107
+ }
108
+ if (inDouble) {
109
+ if (char === "\\" && index + 1 < command.length) {
110
+ const next = command[index + 1] ?? "";
111
+ if (next === '"' || next === "\\" || next === "$" || next === "`") {
112
+ buffer += next;
113
+ index++;
114
+ continue;
115
+ }
116
+ }
117
+ if (char === '"') inDouble = false;
118
+ else buffer += char;
119
+ continue;
120
+ }
121
+ if (char === "'") {
122
+ inSingle = true;
123
+ continue;
124
+ }
125
+ if (char === '"') {
126
+ inDouble = true;
127
+ continue;
128
+ }
129
+ if (char === "\\" && index + 1 < command.length) {
130
+ buffer += command[index + 1] ?? "";
131
+ index++;
132
+ continue;
133
+ }
134
+ if (char === " " || char === "\t") {
135
+ pushBuffer();
136
+ continue;
137
+ }
138
+ if (char === "\n" || char === ";" || char === "&" || char === "|" || char === "(" || char === ")") {
139
+ pushSegment();
140
+ continue;
141
+ }
142
+ buffer += char;
143
+ }
144
+ pushSegment();
145
+ return segments.map((tokens) => tokens.join(" ")).filter((segment) => segment.length > 0);
146
+ }
147
+
148
+ function matchesRule(command: string, rule: BashPatternRule): boolean {
149
+ const compiled = compilePattern(rule.match);
150
+ const normalized = normalizePattern(command);
151
+ if (rule.approval === "allow") {
152
+ if (hasShellControl(command)) return false;
153
+ return normalized.length > 0 && compiled.test(normalized);
154
+ }
155
+ // deny / prompt must catch a dangerous segment buried in a compound command.
156
+ if (normalized.length > 0 && compiled.test(normalized)) return true;
157
+ return ruleSegments(command).some((segment) => compiled.test(normalizePattern(segment)));
158
+ }
159
+
160
+ /**
161
+ * Single entry point for rules and modes, ordered like OMP's `BashTool.approval` plus
162
+ * `resolveApproval`: the first matching rule decides (`deny` short-circuits), then the mode,
163
+ * then `allow`, then `prompt`. Rule order is therefore policy: a narrow `deny` only wins when
164
+ * it precedes a broader `allow`, exactly as in OMP.
165
+ */
166
+ export function evaluatePolicy(command: string, config?: PolicyConfig): PolicyVerdict {
167
+ const mode = config?.mode ?? DEFAULT_MODE;
168
+ const patterns = config?.patterns ?? [];
169
+ const redirects = config?.redirects ?? DEFAULT_REDIRECT_TARGETS;
170
+ const rule = patterns.find((candidate) => matchesRule(command, candidate));
171
+
172
+ if (rule?.approval === "deny") {
173
+ return { decision: "deny", reason: `Blocked by bash pattern: ${rule.match}` };
174
+ }
175
+
176
+ const danger = modeReason(command, mode, config, redirects);
177
+ if (danger !== undefined) return { decision: "prompt", reason: danger };
178
+
179
+ // `allow` and `prompt` rules apply in every mode, matching OMP's "explicit policy beats mode".
180
+ if (rule?.approval === "allow") return { decision: "allow" };
181
+ if (rule?.approval === "prompt") {
182
+ return { decision: "prompt", reason: `Prompt required by bash pattern: ${rule.match}` };
183
+ }
184
+ if (mode === "always-ask") return { decision: "prompt", reason: "always-ask mode" };
185
+ return { decision: "allow" };
186
+ }
187
+
188
+ function modeReason(
189
+ command: string,
190
+ mode: PolicyConfig["mode"],
191
+ config: PolicyConfig | undefined,
192
+ redirects: readonly string[],
193
+ ): string | undefined {
194
+ // Critical patterns are the floor for every mode: `strict` may only be tighter, never looser.
195
+ const critical = criticalReason(command);
196
+ if (critical !== undefined) return critical;
197
+ if (mode === "strict") return dangerReason(command, config);
198
+ return extraDangerousReason(command, config?.extraDangerous, redirects);
199
+ }
package/src/policy.ts CHANGED
@@ -1,5 +1,59 @@
1
+ import { DEFAULT_REDIRECT_TARGETS, type PolicyConfig } from "./policy-config.ts";
2
+
1
3
  const MAX_COMMAND_LENGTH = 8192;
2
4
 
5
+ export type AnalysisOptions = Pick<Partial<PolicyConfig>, "redirects" | "extraDangerous">;
6
+
7
+ /**
8
+ * Critical patterns identical to OMP's `CRITICAL_BASH_PATTERNS`.
9
+ * `yolo` relies on these alone, matched against the raw command line, so no tokenizer runs.
10
+ * The list stays narrow: a miss costs data or the host, while a false positive can be undone
11
+ * with a `patterns` rule.
12
+ */
13
+ export const CRITICAL_COMMAND_PATTERNS: readonly RegExp[] = [
14
+ // Recursive destruction.
15
+ /\brm\s+-[a-z]*[rRfF][a-z]*\s+\//i,
16
+ /\bsudo\s+rm\b/i,
17
+ /\bchmod\s+-R\s+[0-7]+\s+\//i,
18
+ /\bchmod\s+-R\s+[ugoa+\-=rwxXst,]+\s+\//,
19
+ /\bchown\s+-R\s+\S+\s+\//i,
20
+
21
+ // fork bomb。
22
+ /:\(\)\s*\{\s*:\s*\|\s*:/i,
23
+
24
+ // Disk and filesystem destruction.
25
+ />\s*\/dev\/sd[a-z]/i,
26
+ /\bmkfs(\.|\b)/i,
27
+ /\bdd\s+if=.+of=\/dev\//i,
28
+ /\bshred\s+\/dev\//i,
29
+ /\bcryptsetup\b/i,
30
+
31
+ // System configuration destruction.
32
+ />\s*\/etc\/(?:passwd|shadow|sudoers)\b/i,
33
+ /\btee\s+(?:-a\s+)?\/etc\/(?:passwd|shadow|sudoers)\b/i,
34
+
35
+ // Remote fetch and execute.
36
+ /\b(?:curl|wget|fetch)\b[^|]*\|\s*(?:bash|sh|zsh|fish)\b/i,
37
+ /(?:^|[\s;&|(])(?:bash|sh|zsh|source|\.)\s+<\(\s*(?:curl|wget|fetch)\b/i,
38
+ /\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b|\beval\s+`\s*(?:curl|wget|fetch)\b/i,
39
+
40
+ // Process and host control.
41
+ /\bkill\s+-9\s+1\b/,
42
+ /(?:^|[\s;&|(])(?:shutdown|poweroff|reboot|halt)(?:\s|$|[;|&])/i,
43
+ /(?:^|[\s;&|(])init\s+0\b/i,
44
+
45
+ // Network shell exfiltration.
46
+ /\bnc\b[^|;]*\s-[a-zA-Z]*[ec][a-zA-Z]*\s/i,
47
+ ];
48
+
49
+ /** `yolo`: any critical match on the raw line requires approval. */
50
+ export function criticalReason(command: string): string | undefined {
51
+ if (command.length > MAX_COMMAND_LENGTH) return "command too long";
52
+ return CRITICAL_COMMAND_PATTERNS.some((pattern) => pattern.test(command))
53
+ ? "critical pattern detected"
54
+ : undefined;
55
+ }
56
+
3
57
  const DANGEROUS_COMMANDS = new Set([
4
58
  "rm",
5
59
  "rmdir",
@@ -32,10 +86,36 @@ function basename(value: string): string {
32
86
  }
33
87
 
34
88
  /**
35
- * Linear, quote-aware tokenizer. Shell expansion, redirection, or an unclosed quote
36
- * returns undefined so callers fail closed and treat the command as dangerous.
89
+ * Drops a write redirection to an allowed target (default `/dev/null`): it has no side effect yet
90
+ * shows up in read-only commands. Returns the index after the redirection, or undefined when the
91
+ * target is not allowed so callers fail closed.
37
92
  */
38
- function splitSegments(command: string): string[][] | undefined {
93
+ function matchRedirectTarget(
94
+ command: string,
95
+ start: number,
96
+ targets: readonly string[],
97
+ ): number | undefined {
98
+ if (command[start] !== ">") return undefined;
99
+ let targetStart = start + 1;
100
+ if (command[targetStart] === ">") targetStart++;
101
+ while (command[targetStart] === " " || command[targetStart] === "\t") targetStart++;
102
+
103
+ for (const target of targets) {
104
+ if (target.length === 0 || !command.startsWith(target, targetStart)) continue;
105
+ const end = targetStart + target.length;
106
+ const next = command[end];
107
+ if (next !== undefined && !" \t\n;&|(){}".includes(next)) continue;
108
+ return end;
109
+ }
110
+ return undefined;
111
+ }
112
+
113
+ /**
114
+ * Linear, quote-aware tokenizer. Shell expansion, redirection to a target outside
115
+ * `redirects`, or an unclosed quote returns undefined so callers fail closed and
116
+ * treat the command as dangerous.
117
+ */
118
+ function splitSegments(command: string, redirects: readonly string[]): string[][] | undefined {
39
119
  const segments: string[][] = [];
40
120
  let current: string[] = [];
41
121
  let token = "";
@@ -90,6 +170,15 @@ function splitSegments(command: string): string[][] | undefined {
90
170
  flushToken();
91
171
  continue;
92
172
  }
173
+ const redirectStart = char === ">" ? index : char === "&" && command[index + 1] === ">" ? index + 1 : -1;
174
+ if (redirectStart >= 0) {
175
+ const redirectEnd = matchRedirectTarget(command, redirectStart, redirects);
176
+ if (redirectEnd === undefined || (token !== "" && !/^\d+$/.test(token))) return undefined;
177
+ token = "";
178
+ started = false;
179
+ index = redirectEnd - 1;
180
+ continue;
181
+ }
93
182
  if (char === "\n" || char === ";" || char === "&" || char === "|") {
94
183
  flushSegment();
95
184
  const next = command[index + 1];
@@ -100,7 +189,7 @@ function splitSegments(command: string): string[][] | undefined {
100
189
  flushSegment();
101
190
  continue;
102
191
  }
103
- if (char === ">" || char === "<" || char === "$" || char === "`" || char === "\0" || char === "\r") {
192
+ if (char === "<" || char === "$" || char === "`" || char === "\0" || char === "\r") {
104
193
  return undefined;
105
194
  }
106
195
  token += char;
@@ -112,7 +201,21 @@ function splitSegments(command: string): string[][] | undefined {
112
201
  return segments;
113
202
  }
114
203
 
115
- function analyzeSegment(tokens: string[]): string | undefined {
204
+ const dangerousSets = new Map<string, ReadonlySet<string>>();
205
+
206
+ /** Union of the built-in dangerous set and `extraDangerous`, cached by configuration content. */
207
+ function dangerousSet(extra: readonly string[] | undefined): ReadonlySet<string> {
208
+ if (extra === undefined || extra.length === 0) return DANGEROUS_COMMANDS;
209
+ const key = extra.join("\0");
210
+ const cached = dangerousSets.get(key);
211
+ if (cached !== undefined) return cached;
212
+ const merged = new Set([...DANGEROUS_COMMANDS, ...extra.map((name) => name.toLowerCase())]);
213
+ dangerousSets.set(key, merged);
214
+ return merged;
215
+ }
216
+
217
+ /** Skips variable assignments, `env`, and wrapper prefixes to reach the command that actually runs. */
218
+ function resolveCommand(tokens: string[]): { command: string; args: string[] } | undefined {
116
219
  let index = 0;
117
220
 
118
221
  while (index < tokens.length) {
@@ -154,20 +257,42 @@ function analyzeSegment(tokens: string[]): string | undefined {
154
257
  }
155
258
 
156
259
  if (index >= tokens.length) return undefined;
157
- const command = basename(tokens[index] ?? "").toLowerCase();
158
- const args = tokens.slice(index + 1);
260
+ return { command: basename(tokens[index] ?? "").toLowerCase(), args: tokens.slice(index + 1) };
261
+ }
262
+
263
+ /** `yolo` extra names: only the user-supplied list, still resolved through wrappers. */
264
+ export function extraDangerousReason(
265
+ command: string,
266
+ extraDangerous: readonly string[] | undefined,
267
+ redirects?: readonly string[],
268
+ ): string | undefined {
269
+ if (extraDangerous === undefined || extraDangerous.length === 0) return undefined;
270
+ const names = new Set(extraDangerous.map((name) => name.toLowerCase()));
271
+ const segments = splitSegments(command, redirects ?? DEFAULT_REDIRECT_TARGETS);
272
+ if (segments === undefined) return undefined;
273
+ for (const segment of segments) {
274
+ const resolved = resolveCommand(segment);
275
+ if (resolved !== undefined && names.has(resolved.command)) return `dangerous command: ${resolved.command}`;
276
+ }
277
+ return undefined;
278
+ }
279
+
280
+ function analyzeSegment(tokens: string[], options: AnalysisOptions): string | undefined {
281
+ const resolved = resolveCommand(tokens);
282
+ if (resolved === undefined) return undefined;
283
+ const { command, args } = resolved;
159
284
 
160
285
  if (command === "rm" || command === "rmdir") return "recursive/forced file removal";
161
286
  if (command === "sudo") return "privilege escalation";
162
287
  if (command === "source") return "shell sourcing";
163
- if (DANGEROUS_COMMANDS.has(command)) return `dangerous command: ${command}`;
288
+ if (dangerousSet(options.extraDangerous).has(command)) return `dangerous command: ${command}`;
164
289
 
165
290
  if (SHELLS.has(command)) {
166
291
  const codeFlag = args.findIndex((arg) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(arg));
167
- if (codeFlag >= 0 && args[codeFlag + 1] !== undefined) return analyzeCommand(args[codeFlag + 1] ?? "");
292
+ if (codeFlag >= 0 && args[codeFlag + 1] !== undefined) return analyzeCommand(args[codeFlag + 1] ?? "", options);
168
293
  return `shell execution: ${command}`;
169
294
  }
170
- if (command === "eval") return analyzeCommand(args.join(" "));
295
+ if (command === "eval") return analyzeCommand(args.join(" "), options);
171
296
  if (command === "xargs") return "xargs execution";
172
297
  if (command === "find") {
173
298
  if (args.some((arg) => ["-delete", "-exec", "-execdir", "-ok", "-okdir"].includes(arg))) {
@@ -262,13 +387,13 @@ function analyzeGh(args: string[]): string | undefined {
262
387
  return undefined;
263
388
  }
264
389
 
265
- function analyzeCommand(command: string): string | undefined {
390
+ function analyzeCommand(command: string, options: AnalysisOptions = {}): string | undefined {
266
391
  if (command.length > MAX_COMMAND_LENGTH) return "command too long";
267
392
  if (/:\(\)\s*\{/.test(command)) return "fork bomb";
268
- const segments = splitSegments(command);
393
+ const segments = splitSegments(command, options.redirects ?? DEFAULT_REDIRECT_TARGETS);
269
394
  if (segments === undefined) return "unparseable command";
270
395
  for (const segment of segments) {
271
- const reason = analyzeSegment(segment);
396
+ const reason = analyzeSegment(segment, options);
272
397
  if (reason !== undefined) return reason;
273
398
  }
274
399
  return undefined;
@@ -278,10 +403,10 @@ export function hasRmInvocation(command: string): boolean {
278
403
  return analyzeCommand(command) === "recursive/forced file removal";
279
404
  }
280
405
 
281
- export function dangerReason(command: string): string | undefined {
282
- return analyzeCommand(command);
406
+ export function dangerReason(command: string, options?: AnalysisOptions): string | undefined {
407
+ return analyzeCommand(command, options);
283
408
  }
284
409
 
285
- export function isDangerousBash(command: string): boolean {
286
- return analyzeCommand(command) !== undefined;
410
+ export function isDangerousBash(command: string, options?: AnalysisOptions): boolean {
411
+ return analyzeCommand(command, options) !== undefined;
287
412
  }