@jalaxy33/pi-permission 0.4.0 → 0.5.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 CHANGED
@@ -6,7 +6,7 @@ Three gates, checked in order:
6
6
 
7
7
  1. **Path rules** — file tools and bash paths are matched by operation: `read`, `write`, `delete`. A match can deny, ask, or allow.
8
8
  2. **Outside the workspace** — a write or delete outside the session `cwd` asks first, unless the path is on the allow list.
9
- 3. **Commands** — each command in a bash string is matched against command rules. Text inside heredocs, quotes and comments is never matched.
9
+ 3. **Commands** — each command in a bash string is matched against command rules. Text inside heredocs, quotes and comments is never matched, and a command the splitter cannot resolve (an unterminated quote, `$(` or heredoc) asks instead of guessed at.
10
10
 
11
11
  When nothing matches, `defaultPermission` decides: `allow` (default), `ask`, or `deny`.
12
12
 
@@ -29,7 +29,7 @@ Then run `/reload`.
29
29
  | Key | Action |
30
30
  |---|---|
31
31
  | `y` / `Enter` | allow once |
32
- | `a` | allow this rule with these flags, this rule and operation, or this directory, for the rest of the session |
32
+ | `a` | allow this rule with these flags, this rule and operation, or this exact path, for the rest of the session |
33
33
  | `n` / `Esc` / `Ctrl+C` | deny; the turn continues |
34
34
  | `s` | deny and stop the turn |
35
35
  | `j` / `k` / `↑` / `↓` · `o` | scroll · expand the command view |
@@ -100,6 +100,7 @@ Field-by-field reference and matching rules: [docs/configuration.md](docs/config
100
100
  | `publish` | package publishing (`npm`, `bun`, `pnpm`, `yarn`, `cargo`, `gem`), `gh delete` |
101
101
  | `database` | `dropdb`, SQL `DROP`/`TRUNCATE`, Redis `FLUSH` |
102
102
  | `infra` | terraform apply/destroy, kubectl delete/drain, helm uninstall, docker volume/prune |
103
+ | `dynamic-exec` | programs whose real command cannot be read: `env` with flags, `eval`, `source`, `exec`, `strace`, `xargs`, `busybox`, `find -exec`/`-delete`, `python -c`, `node -e`, `deno eval`, `perl -e`, `awk 'BEGIN{system(...)}'`, `pwsh` |
103
104
 
104
105
  ## Presets
105
106
 
@@ -110,17 +111,46 @@ Field-by-field reference and matching rules: [docs/configuration.md](docs/config
110
111
  | `cautious` | 3 | `standard` + `bulk-delete`, `database`, `infra`, `git-remote`, `publish` |
111
112
  | `paranoid` | 4 | `cautious` + `git-local` |
112
113
 
114
+ Every preset also includes `dynamic-exec`. It does not add risk levels, it closes a hole in reading the command: a program can hide the real command behind another one, and asking about the wrapper is the only answer that works for the ones with no closed option table.
115
+
113
116
  The shipped default is `standard`: `git add`/`commit` and `rm -rf node_modules` stay quiet, while `sudo`, `.env`, device writes and git history rewrites are still gated. Move up a level for more prompts, or list the rulesets you want.
114
117
 
118
+ Wrappers with a closed option table are peeled before matching, so the inner command decides and the prompt names it: `timeout 60 git push` asks because it is a push, `time ls` runs because it is `ls`. Peeling covers `time`, `nice`, `nohup`, `setsid`, `timeout`, `stdbuf`, `command`, and `env` in its `VAR=VAL` form. `env -S`, `xargs`, `find -exec`, `busybox`, `eval` and `source` stay whole: their command exists only at runtime.
119
+
120
+ Shell keywords are peeled the same way, so `if …; then rm -rf x; fi` and `for f in *; do rm -rf "$f"; done` are judged by the command they run.
121
+
122
+ If you do not want the remaining prompts, drop the ruleset for your config and accept that those programs run unguarded:
123
+
124
+ ```json
125
+ { "preset": { "id": "paranoid", "remove": ["dynamic-exec"] } }
126
+ ```
127
+
128
+ ## Upgrading to 0.5.0
129
+
130
+ The release is a fix for commands that slipped past the gate, and it changes what you see:
131
+
132
+ - Programs are normalized before matching: `bash.exe`, `git.exe`, `C:/bin/bash.exe` are now the programs they name.
133
+ - `if`, `for`, `then`, `do`, `!` and `{` no longer hide the command they precede.
134
+ - Wrappers with a closed option table are peeled, so `timeout 60 git push` asks because it is a push and `time ls` runs. The same wrapper approvals no longer cover other commands.
135
+ - A program name built from a substitution, escape or glob (`"$CMD"`, `\rm`, `r[m]`) asks instead of falling through.
136
+ - A program's script input is judged: `bash deploy.sh` and `bash <<EOF` are read, `python job.py` asks once per file content, and stdin (`curl … | bash`) asks without a grant.
137
+ - The `powershell` tool asks and cannot be granted, rather than being read as bash.
138
+ - A config file that is not valid JSON is fatal instead of dropping its rules.
139
+ - An outside-workspace grant names the exact path, not its directory.
140
+
115
141
  ## Limits
116
142
 
117
- A guard, not a sandbox. It sees the command text and the paths in it, so anything a program resolves on its own is out of reach.
143
+ A guard, not a sandbox. The strongest thing it can promise is that nothing the command text leaves unreadable runs silently. It cannot promise to block everything that should be blocked: a program resolves its own behaviour once it runs.
118
144
 
119
- - `python -c "open('.env')"` passes.
120
- - Shell aliases, functions and `eval` are not expanded. `sh -c '...'` is followed, but a wrapper in front of a command (`env`, `command`, `nice`, `nohup`, …) is not unwrapped.
145
+ - It only reads the command text. A program name built from a substitution, escape or glob asks instead of matching (`"$CMD"`, `\rm`, `r[m]`); a name in quotes is still a name.
146
+ - A shell script is read and judged like a command line: `bash deploy.sh`, `bash <<EOF` and `sh -c '...'` (three levels) are followed. `-n` is not followed, since it runs nothing.
147
+ - Another language is asked about, not parsed: `python job.py` asks once per file content, and `python -c`, `node -e`, `awk 'BEGIN{system(...)}'` are covered by `dynamic-exec`. Once allowed, the script can still read anything the user can, `.env` included.
148
+ - A script on stdin is not visible in the command text, so `curl … | bash`, `bash < deploy.sh`, `sh -s` and `<<<` ask and cannot be granted for the session.
149
+ - Not covered at all: downloaded code run later (`npx some-package`, `at`, `cron`), remote or nested execution (`ssh host '…'`, `docker exec`, `flock`), project-defined scripts (`make`, `npm run`, `bun run`), and `rm` without `-r`.
150
+ - Shell aliases and functions are not expanded; `shellCommandPrefix` from Pi's settings is executed but never judged, and the gate warns when it is set.
121
151
  - Reads outside the workspace are not gated: a path rule is the only check on what the agent may read.
122
152
  - Symlinks are followed: a link inside the workspace that points outside is treated as outside, and a path rule matches the file the link resolves to.
123
- - Tools other than `bash`, `powershell` and the file tools (`read`, `grep`, `find`, `ls`, `write`, `edit`) are not inspected.
153
+ - Only `bash`, `powershell` and the file tools (`read`, `grep`, `find`, `ls`, `write`, `edit`) are inspected. The `codemode` script itself is not judged — its nested tool calls are — and `models.classify` inside a script never reaches the gate.
124
154
 
125
155
  ## Development
126
156
 
@@ -115,7 +115,14 @@ Matching notes:
115
115
  - `subcommand` is the safer choice for command families: a commit message or a flag value cannot pass for the subcommand. For git, `-C`, `-c`, `--git-dir`, `--work-tree`, `--namespace`, `--exec-path` and `--super-prefix` are skipped with their value, so `git -C dir push` still matches `subcommand: ["push"]`.
116
116
  - `args` matches any positional, so for programs without a value-flag table it also matches flag values. Use it for operands, not for subcommands.
117
117
  - One string can hold several commands (`&&`, `;`, `|`, substitutions); the strictest verdict wins.
118
- - `sh -c '...'` and other shell `-c` scripts are checked like top-level commands (three levels deep).
118
+ - `sh -c '...'` and other shell `-c` scripts are checked like top-level commands, three levels deep. A deeper script, and a script that reads a variable (`sh -c "$DEPLOY"`), asks.
119
+ - `$(...)`, backticks, `<(...)` and `>(...)` are parsed as commands and checked with the same rules, including inside double quotes. Single-quoted text stays text.
120
+ - Text the splitter cannot resolve — an unterminated quote, `$(` or heredoc — asks with the reason `gate cannot inspect this command`. It is never treated as an allow.
121
+ - Wrappers with a closed option table are peeled before matching, so the inner command decides: `time`, `nice`, `nohup`, `setsid`, `timeout`, `stdbuf`, `command`, and `env` when it only carries `VAR=VAL` words. A shape the table does not cover (`env -C dir`, `env -S`, `timeout -v`, `strace -o file`) is left whole and reaches the `dynamic-exec` rules, which ask.
122
+ - Shell keywords are peeled too: `then`, `do`, `else`, `elif`, `if`, `while`, `until`, `!` and `{` precede a command; `for`, `in`, `case`, `fi`, `done`, `esac` and `}` never carry one. Word-exact and position zero only, so `cp a in` keeps its operand.
123
+ - A word containing an expansion, escape or glob cannot name a program: `"$CMD"`, `\rm` and `r[m]` ask instead of matching. A quoted name (`'git'`) is still a name.
124
+ - A program's script input is judged when the gate can see it: a shell script in a file (`bash deploy.sh`) or a heredoc body on a shell (`bash <<EOF`) is tokenized and judged like the command line; a script in another language (`python job.py`) asks once per file content, granted as `opaque:<program>:file:<hash>`; stdin (`curl … | bash`, `bash < f`, `sh -s`, `<<<`) asks and carries no grant key, because that text does not exist when the decision is made.
125
+ - `-c` names inline code and is followed instead of read; `-n` parses without running, so it is not followed.
119
126
  - Precedence inside one simple command: `deny` → `allow` → `ask` → `defaultPermission.commands`.
120
127
  - "Allow for this session" remembers the rule and the flags: after allowing `rm -r build`, `rm -r dist` runs without asking, while `rm -rf dist` asks again. Flag order does not matter. A deny rule still blocks a granted command.
121
128
 
@@ -162,7 +169,7 @@ Matching:
162
169
  - If the path exists, its real path is matched as well, so symlinks do not bypass a rule. A symlink whose target does not exist yet is followed too.
163
170
  - `*` does not cross `/`; `**` does.
164
171
 
165
- For bash commands the gate reads redirections, path arguments of known programs, path-looking arguments of unknown ones, `sed -i`, `mv` sources (as deletes), and nested `sh -c` (three levels); `cd` inside the string changes the directory for later commands. Globs are expanded before matching, so `cat .env*` is caught for files that exist; `$VAR` operands match by basename only.
172
+ For bash commands the gate reads redirections, path arguments of known programs, path-looking arguments of unknown ones, `sed -i`, `mv` sources (as deletes), and nested `sh -c` (three levels); `cd` inside the string changes the directory for later commands. Globs are expanded before matching, so `cat .env*` is caught for files that exist; `$VAR` operands match by basename only, with or without a file extension.
166
173
 
167
174
  "Allow for this session" remembers `path:<rule id>:<op>`: allowing a read leaves writes and deletes asking.
168
175
 
@@ -200,7 +207,7 @@ Built-in allow list: `/tmp/**`, `/dev/**`, `~/.pi/agent/**`, `~/.cache/**`, `~/.
200
207
 
201
208
  Only writes and deletes are checked. Reads outside the workspace are not gated, and `mode: block` does not stop them either; use a path rule for files that must never be read.
202
209
 
203
- Paths are resolved to their real location first, so a symlink inside the workspace that points outside is outside, and the allow list is matched against where the write lands rather than the link itself. A symlinked workspace stays inside. "Allow for this session" remembers the directory of the approved path, including everything below it.
210
+ Paths are resolved to their real location first, so a symlink inside the workspace that points outside is outside, and the allow list is matched against where the write lands rather than the link itself. A symlinked workspace stays inside. "Allow for this session" remembers the exact path that was approved. A directory grant belongs in `outsideCwd.allowPaths`, where it is written down and visible.
204
211
 
205
212
  ## `enabled`
206
213
 
package/index.ts CHANGED
@@ -8,6 +8,8 @@ export default async function permission(pi: ExtensionAPI) {
8
8
  const sessionGrants = new SessionGrants();
9
9
 
10
10
  const reload = (cwd: string, trusted: boolean, notify: (message: string) => void) => {
11
+ // Grants name decisions made under the old rules; they cannot outlive a reload.
12
+ sessionGrants.clear();
11
13
  config = loadConfig(cwd, trusted);
12
14
  for (const warning of config.warnings) notify(`pi-permission: ${warning}`);
13
15
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jalaxy33/pi-permission",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Permission gate for pi: command, path and workspace rules",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/rules/index.json CHANGED
@@ -10,15 +10,17 @@
10
10
  "git-remote": "./packs/git-remote.json",
11
11
  "publish": "./packs/publish.json",
12
12
  "database": "./packs/database.json",
13
- "infra": "./packs/infra.json"
13
+ "infra": "./packs/infra.json",
14
+ "dynamic-exec": "./packs/dynamic-exec.json"
14
15
  },
15
16
  "presets": {
16
17
  "minimal": {
17
18
  "level": 1,
18
- "description": "Unrecoverable damage and secrets only.",
19
+ "description": "Unrecoverable damage, secrets, and commands the gate cannot read.",
19
20
  "include": [
20
21
  "irreversible",
21
- "secrets"
22
+ "secrets",
23
+ "dynamic-exec"
22
24
  ]
23
25
  },
24
26
  "standard": {
@@ -27,7 +29,8 @@
27
29
  "include": [
28
30
  "irreversible",
29
31
  "secrets",
30
- "privilege"
32
+ "privilege",
33
+ "dynamic-exec"
31
34
  ]
32
35
  },
33
36
  "cautious": {
@@ -41,7 +44,8 @@
41
44
  "database",
42
45
  "infra",
43
46
  "git-remote",
44
- "publish"
47
+ "publish",
48
+ "dynamic-exec"
45
49
  ]
46
50
  },
47
51
  "paranoid": {
@@ -56,7 +60,8 @@
56
60
  "infra",
57
61
  "git-remote",
58
62
  "publish",
59
- "git-local"
63
+ "git-local",
64
+ "dynamic-exec"
60
65
  ]
61
66
  }
62
67
  },
@@ -0,0 +1,105 @@
1
+ {
2
+ "$schema": "../../schema.json",
3
+ "description": "Programs that run another command, or code the gate cannot read. A wrapper with a closed option table is peeled before matching, so this ruleset holds what stays whole: a command that only exists at runtime, or code in another language.",
4
+ "commands": {
5
+ "allow": [
6
+ {
7
+ "id": "env-print",
8
+ "program": "env",
9
+ "argvRegex": "^env(\\s+-[^\\s]+)*$",
10
+ "reason": "prints the environment"
11
+ },
12
+ {
13
+ "id": "command-query",
14
+ "program": "command",
15
+ "argvRegex": "^command\\s+-[vV]\\s+\\S+$",
16
+ "reason": "reports what a name resolves to"
17
+ }
18
+ ],
19
+ "ask": [
20
+ {
21
+ "id": "exec-relay",
22
+ "program": ["env", "command", "builtin", "exec", "eval", "source", "."],
23
+ "reason": "runs a command the gate cannot read"
24
+ },
25
+ {
26
+ "id": "exec-wrapper",
27
+ "program": [
28
+ "watch",
29
+ "strace",
30
+ "ltrace",
31
+ "ionice",
32
+ "chrt",
33
+ "taskset",
34
+ "unbuffer",
35
+ "script",
36
+ "expect"
37
+ ],
38
+ "reason": "wraps a command the gate cannot read"
39
+ },
40
+ {
41
+ "id": "exec-applet",
42
+ "program": "busybox",
43
+ "reason": "runs an applet the gate cannot read"
44
+ },
45
+ {
46
+ "id": "exec-runtime-args",
47
+ "program": ["xargs", "parallel"],
48
+ "reason": "builds the command's arguments at runtime"
49
+ },
50
+ {
51
+ "id": "exec-tree",
52
+ "program": ["find", "gfind"],
53
+ "anyFlag": ["-exec", "-execdir", "-ok", "-okdir", "-delete"],
54
+ "reason": "runs commands while walking the tree"
55
+ },
56
+ {
57
+ "id": "exec-shell-host",
58
+ "program": ["pwsh", "powershell", "osascript"],
59
+ "reason": "runs code the gate cannot parse"
60
+ },
61
+ {
62
+ "id": "exec-python",
63
+ "program": "python*",
64
+ "anyFlag": ["-c"],
65
+ "reason": "runs inline code"
66
+ },
67
+ {
68
+ "id": "exec-node",
69
+ "program": ["node", "nodejs"],
70
+ "anyFlag": ["-e", "--eval", "-p", "--print"],
71
+ "reason": "runs inline code"
72
+ },
73
+ {
74
+ "id": "exec-bun",
75
+ "program": "bun",
76
+ "anyFlag": ["-e", "--eval", "-p"],
77
+ "reason": "runs inline code"
78
+ },
79
+ {
80
+ "id": "exec-bun-runner",
81
+ "program": "bun",
82
+ "args": ["x"],
83
+ "reason": "runs a downloaded package"
84
+ },
85
+ {
86
+ "id": "exec-deno",
87
+ "program": "deno",
88
+ "args": ["eval"],
89
+ "reason": "runs inline code"
90
+ },
91
+ {
92
+ "id": "exec-script-lang",
93
+ "program": ["perl", "ruby", "php", "lua"],
94
+ "anyFlag": ["-e", "-r"],
95
+ "reason": "runs inline code"
96
+ },
97
+ {
98
+ "id": "exec-awk-system",
99
+ "program": ["awk", "gawk", "mawk", "nawk"],
100
+ "argvRegex": "system\\s*\\(|\\|\\s*(sh|bash|getline)",
101
+ "reason": "runs shell commands from the awk script"
102
+ }
103
+ ]
104
+ }
105
+ }
package/src/argv.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /** Turns the argv of one simple command into the pieces rules match on. */
2
2
 
3
+ import { normalizeProgram } from "./program";
4
+
3
5
  export interface Args {
4
6
  program: string;
5
7
  positional: string[];
@@ -14,11 +16,19 @@ const GLOBAL_VALUE_FLAGS: Record<string, Set<string>> = {
14
16
  git: new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--super-prefix"]),
15
17
  };
16
18
 
19
+ /** Index of the word that names the program; -1 for a line of assignments only. */
20
+ export function programWordIndex(argv: string[]): number {
21
+ for (let i = 0; i < argv.length; i++) {
22
+ if (!ASSIGNMENT.test(argv[i] as string)) return i;
23
+ }
24
+ return -1;
25
+ }
26
+
17
27
  function programOf(argv: string[]): { program: string; index: number } | undefined {
18
28
  for (let i = 0; i < argv.length; i++) {
19
29
  const token = argv[i] as string;
20
30
  if (ASSIGNMENT.test(token)) continue;
21
- return { program: token.split("/").pop() as string, index: i };
31
+ return { program: normalizeProgram(token), index: i };
22
32
  }
23
33
  return undefined;
24
34
  }
package/src/config.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
14
  readJson,
15
15
  resolveSelection,
16
16
  type LoadedRuleSet,
17
+ type ReadFailure,
17
18
  } from "./rulesets";
18
19
  import type {
19
20
  Action,
@@ -102,14 +103,16 @@ export function loadConfig(
102
103
 
103
104
  const scopePaths = [options.globalPath ?? globalConfigPath()];
104
105
  if (trusted) scopePaths.push(options.projectPath ?? projectConfigPath(cwd));
106
+ let fatal: string | undefined;
105
107
  for (const path of scopePaths) {
106
- const file = readJson(path, warnings, "config");
108
+ const failures: ReadFailure[] = [];
109
+ const file = readJson(path, warnings, "config", failures);
110
+ for (const failure of failures) fatal ??= `pi-permission: ${failure.path}: ${failure.reason}`;
107
111
  if (!file) continue;
108
112
  sources.push(path);
109
113
  scopes.push({ path, baseDir: dirname(path), file });
110
114
  }
111
115
 
112
- let fatal: string | undefined;
113
116
  const rulesets = new Map<string, LoadedRuleSet>();
114
117
  for (const scope of scopes) {
115
118
  const shape = shapeError(scope.file, scope.path);
package/src/decide.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { parseArgs, type Args } from "./argv";
1
+ import { parseArgs, programWordIndex, type Args } from "./argv";
2
2
  import { matchRule } from "./match";
3
- import { MAX_NESTING, scriptAfterC } from "./ops";
4
- import { tokenize } from "./tokenize";
3
+ import { MAX_NESTING, scriptAfterC, SHELLS } from "./ops";
4
+ import { isCodeRunner, scriptHash, scriptOperand } from "./scripts";
5
+ import { tokenizeDetailed, type SimpleCommand, type WordMeta } from "./tokenize";
6
+ import { unlayer } from "./unlayer";
5
7
  import type { Action, CompiledRule, GateRules, Verdict } from "./types";
6
8
 
7
9
  const RANK: Record<Action, number> = { allow: 0, ask: 1, deny: 2 };
@@ -10,6 +12,85 @@ function verdict(action: Action, matched: boolean): Verdict {
10
12
  return { action, reasons: [], grants: [], terminate: false, matched };
11
13
  }
12
14
 
15
+ /**
16
+ * Text the gate could not resolve, and script text that only becomes a
17
+ * command at runtime. Guessing here would turn a bypass into a silent allow,
18
+ * so it asks instead.
19
+ */
20
+ function unreadable(what: string): Verdict {
21
+ const result = verdict("ask", true);
22
+ result.reasons = [`gate cannot inspect this command: ${what}`];
23
+ result.grants = [`unreadable:${what}`];
24
+ return result;
25
+ }
26
+
27
+ /** A `-c` script that reads a variable runs code this gate never sees. */
28
+ function hasRuntimeExpansion(script: string): boolean {
29
+ return /\$(?!\()/.test(script);
30
+ }
31
+
32
+ /** A program name built from a substitution, escape or glob is not a name. */
33
+ function unreadableProgram(meta: WordMeta | undefined): Verdict | undefined {
34
+ if (!meta) return undefined;
35
+ if (meta.expansion || meta.escape || meta.glob) return unreadable("program name is not a literal");
36
+ return undefined;
37
+ }
38
+
39
+ /** Source code the gate can see but not read. */
40
+ function unreadableScript(program: string, why: string, grant?: string): Verdict {
41
+ const result = verdict("ask", true);
42
+ result.reasons = [`${why}. The gate cannot read the ${program} script`];
43
+ if (grant !== undefined) result.grants = [grant];
44
+ return result;
45
+ }
46
+
47
+ /** The script a command runs, when it comes from somewhere other than `-c`. */
48
+ export function decideInput(
49
+ simple: SimpleCommand,
50
+ argv: string[],
51
+ rules: GateRules,
52
+ fallback: Action,
53
+ depth: number,
54
+ options: DecideOptions,
55
+ ): Verdict | undefined {
56
+ const args = parseArgs(argv);
57
+ if (!args) return undefined;
58
+ const shell = SHELLS.has(args.program);
59
+ if (!shell && !isCodeRunner(args.program)) return undefined;
60
+ // `-c` names the code inline, and `-n` only parses; neither runs a file.
61
+ if (scriptAfterC(argv) !== undefined) return undefined;
62
+ if (shell && args.flags.has("-n")) return undefined;
63
+
64
+ if (shell && simple.heredoc !== undefined) {
65
+ if (depth >= MAX_NESTING) return unreadable("nested script");
66
+ return decide(simple.heredoc, rules, fallback, depth + 1, options);
67
+ }
68
+
69
+ const operand = scriptOperand(args.positional);
70
+ if (operand !== undefined) {
71
+ const text = options.readScript?.(operand);
72
+ if (text === undefined) {
73
+ return unreadableScript(args.program, `cannot read ${operand}`, `opaque:${args.program}:${operand}`);
74
+ }
75
+ if (depth >= MAX_NESTING) return unreadable("nested script");
76
+ if (shell) return decide(text, rules, fallback, depth + 1, options);
77
+ return unreadableScript(
78
+ args.program,
79
+ `${operand} is not shell code, so it is not parsed`,
80
+ `opaque:${args.program}:file:${scriptHash(text)}`,
81
+ );
82
+ }
83
+
84
+ const fromStdin =
85
+ simple.stdinPiped === true ||
86
+ simple.stdinText !== undefined ||
87
+ args.flags.has("-") ||
88
+ (shell && args.flags.has("-s")) ||
89
+ simple.redirects.some((redirect) => redirect.op === "<");
90
+ if (fromStdin) return unreadableScript(args.program, "its script arrives on stdin, which the command text does not contain");
91
+ return undefined;
92
+ }
93
+
13
94
  /** A session grant covers one rule with the same flags, not every command it matches. */
14
95
  function grantKey(rule: CompiledRule, args: Args): string {
15
96
  return `rule:${rule.id}:${[...args.flags].filter(canonicalFlag).sort().join(",")}`;
@@ -76,14 +157,43 @@ function mergeInto(target: Verdict, source: Verdict): void {
76
157
  * Strictest verdict across every simple command, including `sh -c` scripts.
77
158
  * `fallback` is `defaultPermission.commands`: what an unmatched program does.
78
159
  */
79
- export function decide(command: string, rules: GateRules, fallback: Action = "allow", depth = 0): Verdict {
80
- const merged: Verdict = { action: "allow", reasons: [], grants: [], terminate: false, matched: false };
160
+ export interface DecideOptions {
161
+ /** Reads a script file named by a command. Undefined when it cannot be read. */
162
+ readScript?: (path: string) => string | undefined;
163
+ }
81
164
 
82
- for (const simple of tokenize(command)) {
83
- mergeInto(merged, decideOne(simple.argv, rules, fallback));
165
+ export function decide(
166
+ command: string,
167
+ rules: GateRules,
168
+ fallback: Action = "allow",
169
+ depth = 0,
170
+ options: DecideOptions = {},
171
+ ): Verdict {
172
+ const merged: Verdict = { action: "allow", reasons: [], grants: [], terminate: false, matched: false };
84
173
 
85
- const script = scriptAfterC(simple.argv);
86
- if (script && depth < MAX_NESTING) mergeInto(merged, decide(script, rules, fallback, depth + 1));
174
+ const split = tokenizeDetailed(command);
175
+ for (const hazard of split.hazards) mergeInto(merged, unreadable(hazard));
176
+
177
+ for (const simple of split.commands) {
178
+ const argv = unlayer(simple.argv);
179
+ if (!argv) continue;
180
+ // `FOO=1 "$CMD" x` puts the program one word later than the segment start.
181
+ const wordIndex = programWordIndex(argv);
182
+ const meta = wordIndex === -1 ? undefined : simple.words[simple.argv.length - argv.length + wordIndex];
183
+ mergeInto(merged, unreadableProgram(meta) ?? verdict("allow", false));
184
+ mergeInto(merged, decideOne(argv, rules, fallback));
185
+
186
+ const input = decideInput(simple, argv, rules, fallback, depth, options);
187
+ if (input) mergeInto(merged, input);
188
+
189
+ const script = scriptAfterC(argv);
190
+ if (!script) continue;
191
+ if (depth >= MAX_NESTING) {
192
+ mergeInto(merged, unreadable("nested script"));
193
+ continue;
194
+ }
195
+ mergeInto(merged, decide(script, rules, fallback, depth + 1, options));
196
+ if (hasRuntimeExpansion(script)) mergeInto(merged, unreadable("script expansion"));
87
197
  }
88
198
 
89
199
  return merged;
package/src/gate.ts CHANGED
@@ -3,16 +3,31 @@
3
3
  * Pure: no prompting, no session state — the caller acts on the verdict.
4
4
  */
5
5
 
6
- import { statSync } from "node:fs";
7
- import { dirname } from "node:path";
6
+ import { readFileSync, statSync } from "node:fs";
7
+ import { dirname, isAbsolute, resolve } from "node:path";
8
8
  import { decide } from "./decide";
9
9
  import { collectTargets, type PathTarget } from "./ops";
10
10
  import { checkOutside } from "./outside";
11
- import { matchPath, resolveCandidate, type PathHit } from "./paths";
11
+ import { expandTilde, matchPath, resolveCandidate, type PathHit } from "./paths";
12
12
  import type { PathOp, ResolvedConfig } from "./types";
13
13
 
14
14
  export const GATED_TOOLS = new Set(["bash", "powershell"]);
15
15
 
16
+ /** A script larger than this is not read; it becomes an opaque ask instead. */
17
+ const MAX_SCRIPT_BYTES = 64 * 1024;
18
+
19
+ function readScript(path: string, cwd: string): string | undefined {
20
+ const expanded = expandTilde(path);
21
+ const absolute = isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
22
+ try {
23
+ const stats = statSync(absolute);
24
+ if (!stats.isFile() || stats.size > MAX_SCRIPT_BYTES) return undefined;
25
+ return readFileSync(absolute, "utf8");
26
+ } catch {
27
+ return undefined;
28
+ }
29
+ }
30
+
16
31
  const FILE_TOOL_OPS: Record<string, PathOp> = {
17
32
  read: "read",
18
33
  grep: "read",
@@ -30,20 +45,13 @@ function isDirectory(path: string): boolean {
30
45
  }
31
46
  }
32
47
 
33
- /** The session grant for an outside path covers its directory: a file one level up. */
48
+ /**
49
+ * The session grant for an outside path names that path only. Approving
50
+ * `tee /root/.bashrc` must not also approve `tee /root/.ssh/authorized_keys`;
51
+ * a directory grant belongs in `outsideCwd.allowPaths`, where it is visible.
52
+ */
34
53
  function outsideGrantKey(path: string): string {
35
- return `outside:${isDirectory(path) ? path : dirname(path)}`;
36
- }
37
-
38
- /** A granted directory also covers everything below it. */
39
- function grantedOutside(path: string, hasGrant: (key: string) => boolean): boolean {
40
- let dir = path;
41
- while (true) {
42
- if (hasGrant(`outside:${dir}`)) return true;
43
- const parent = dirname(dir);
44
- if (parent === dir) return false;
45
- dir = parent;
46
- }
54
+ return `outside:${path}`;
47
55
  }
48
56
 
49
57
  export type GateDecision =
@@ -160,6 +168,21 @@ export function evaluate(
160
168
  ): GateDecision {
161
169
  if (config.fatal) return { kind: "block", reason: config.fatal };
162
170
 
171
+ // PowerShell is a different grammar. Reading it with the bash splitter finds
172
+ // no program it knows and lets the command through, so it is not read at all.
173
+ // No grant: there is nothing to name in a decision that was never understood.
174
+ if (toolName === "powershell") {
175
+ const command = input.command;
176
+ if (typeof command !== "string" || command.trim() === "") return { kind: "allow" };
177
+ return {
178
+ kind: "prompt",
179
+ title: "Unparsed shell",
180
+ reason: "PowerShell text is not parsed; read the command and decide",
181
+ label: command,
182
+ grantKeys: [],
183
+ };
184
+ }
185
+
163
186
  const targets = toolTargets(toolName, input, cwd);
164
187
 
165
188
  if (config.enabled.paths && targets) {
@@ -170,7 +193,7 @@ export function evaluate(
170
193
  if (targets) {
171
194
  for (const target of targets.paths) {
172
195
  const hit = checkOutside(config.outside, target.path, cwd, target.op);
173
- if (!hit || grantedOutside(hit.path, hasGrant)) continue;
196
+ if (!hit || hasGrant(outsideGrantKey(hit.path))) continue;
174
197
  const reason = `outside workspace: ${hit.path}`;
175
198
  if (hit.mode === "block") return { kind: "block", reason: `pi-permission: ${reason}` };
176
199
  return {
@@ -187,7 +210,9 @@ export function evaluate(
187
210
  const text = targets?.text;
188
211
  if (!text) return { kind: "allow" };
189
212
 
190
- const verdict = decide(text, config.commands, config.defaultPermission.commands);
213
+ const verdict = decide(text, config.commands, config.defaultPermission.commands, 0, {
214
+ readScript: (path) => readScript(path, cwd),
215
+ });
191
216
  if (verdict.action === "allow") return { kind: "allow" };
192
217
  if (verdict.action === "ask" && verdict.grants.length > 0 && verdict.grants.every(hasGrant)) {
193
218
  return { kind: "allow" };
package/src/match.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Args } from "./argv";
2
+ import { normalizeProgram } from "./program";
2
3
  import type { CompiledRule, CompileResult, Rule } from "./types";
3
4
 
4
5
  function wildcardRegex(pattern: string): RegExp {
@@ -42,7 +43,7 @@ export function compileRules(rules: Rule[]): CompileResult {
42
43
 
43
44
  function matchesProgram(rule: CompiledRule, program: string): boolean {
44
45
  const names = Array.isArray(rule.program) ? rule.program : [rule.program];
45
- if (names.some((name) => !name.includes("*") && name.replace(/^\//, "") === program)) return true;
46
+ if (names.some((name) => !name.includes("*") && normalizeProgram(name) === program)) return true;
46
47
  return (rule.programRes ?? []).some((re) => re.test(program));
47
48
  }
48
49