@jalaxy33/pi-permission 0.5.0 → 0.5.1

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
@@ -1,14 +1,12 @@
1
1
  # pi-permission
2
2
 
3
- A permission gate for pi. Every tool call gets one of three answers: run it, ask the user, or block it.
3
+ A permission gate for pi. Every tool call is allowed, asks, or is blocked, checked in this order:
4
4
 
5
- Three gates, checked in order:
5
+ 1. **Path rules** — file tools and bash paths, by operation: `read`, `write`, `delete`.
6
+ 2. **Outside the workspace** — writes and deletes outside the session `cwd`.
7
+ 3. **Commands** — every command in a bash string.
6
8
 
7
- 1. **Path rules** — file tools and bash paths are matched by operation: `read`, `write`, `delete`. A match can deny, ask, or allow.
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, and a command the splitter cannot resolve (an unterminated quote, `$(` or heredoc) asks instead of guessed at.
10
-
11
- When nothing matches, `defaultPermission` decides: `allow` (default), `ask`, or `deny`.
9
+ Unmatched calls fall to `defaultPermission`, `allow` by default.
12
10
 
13
11
  ## Install
14
12
 
@@ -16,8 +14,6 @@ When nothing matches, `defaultPermission` decides: `allow` (default), `ask`, or
16
14
  pi install npm:@jalaxy33/pi-permission
17
15
  ```
18
16
 
19
- From the repository:
20
-
21
17
  ```bash
22
18
  pi install git:github.com/jalaxy33/pi-permission
23
19
  ```
@@ -29,49 +25,34 @@ Then run `/reload`.
29
25
  | Key | Action |
30
26
  |---|---|
31
27
  | `y` / `Enter` | allow once |
32
- | `a` | allow this rule with these flags, this rule and operation, or this exact path, for the rest of the session |
28
+ | `a` | allow this rule with these flags, this rule and operation, or this path, for the rest of the session |
33
29
  | `n` / `Esc` / `Ctrl+C` | deny; the turn continues |
34
30
  | `s` | deny and stop the turn |
35
- | `j` / `k` / `↑` / `↓` · `o` | scroll · expand the command view |
31
+ | `j` / `k` / `↑` / `↓` · `o` | scroll · expand the command |
36
32
 
37
- Without a UI the gate fails closed: a call that would ask is blocked instead.
33
+ Without a UI, a call that would ask is blocked.
38
34
 
39
35
  ## Commands
40
36
 
41
37
  | Command | Action |
42
38
  |---|---|
43
- | `/permission` | show the active preset, selected rulesets, removals, defaults, sources and warnings |
39
+ | `/permission` | active preset, rulesets, defaults, sources, warnings |
44
40
  | `/permission:reload` | re-read the config without restarting pi |
45
41
 
46
- ## Concepts
47
-
48
- | Concept | What it is |
49
- |---|---|
50
- | **ruleset** | A leaf bundle of rules. It never includes another ruleset, so references cannot form a cycle. |
51
- | **preset** | A permission level: `minimal`, `standard`, `cautious`, `paranoid`. A flat list of rulesets. |
52
- | **config file** | Picks one preset, adds rulesets, and may override rules. |
53
-
54
- Presets and include lists are single values: the last config file that declares one replaces the value below it. Rules merge, and a config rule overrides a bundled rule with the same `id`.
55
-
56
42
  ## Configuration
57
43
 
58
44
  | File | Scope |
59
45
  |---|---|
60
46
  | `~/.pi/agent/permission.json` | all projects |
61
- | `<project>/.pi/permission.json` | one project, only after the project is trusted |
47
+ | `<project>/.pi/permission.json` | one project, after the project is trusted |
62
48
 
63
49
  ```json
64
50
  {
65
51
  "preset": { "id": "cautious", "remove": ["bulk-delete"] },
66
- "include": [
67
- "git-local",
68
- { "id": "git-remote", "remove": ["gh-delete"] }
69
- ],
52
+ "include": ["git-local", { "id": "publish", "remove": ["gh-delete"] }],
70
53
  "defaultPermission": { "commands": "allow", "paths": "allow" },
71
54
  "outsideCwd": { "mode": "ask", "allowPaths": ["~/work/shared/**"] },
72
- "rulesets": {
73
- "local": "./rules/local.json"
74
- },
55
+ "rulesets": { "local": "./rules/local.json" },
75
56
  "commands": {
76
57
  "allow": [{ "id": "git-push", "program": "git", "args": ["push"] }]
77
58
  },
@@ -81,76 +62,40 @@ Presets and include lists are single values: the last config file that declares
81
62
  }
82
63
  ```
83
64
 
84
- - `remove` on a `preset` entry drops rulesets; on an `include` entry it drops rule ids from that ruleset. It never reaches another ruleset.
85
- - A ruleset file contains only `description`, `commands` and `paths`. To replace a shipped ruleset, define it under the same name in `rulesets`; `/permission` reports the shadow.
86
- - A config rule with the same `id` as a bundled rule replaces it. Changing a `deny` rule into `ask` or `allow` is reported as a warning.
65
+ ## Presets
66
+
67
+ | Preset | Includes |
68
+ |---|---|
69
+ | `minimal` | `irreversible`, `secrets`, `dynamic-exec` |
70
+ | `standard` | `minimal` + `privilege` |
71
+ | `cautious` | `standard` + `bulk-delete`, `database`, `infra`, `git-remote`, `publish` |
72
+ | `paranoid` | `cautious` + `git-local` |
87
73
 
88
- Field-by-field reference and matching rules: [docs/configuration.md](docs/configuration.md).
74
+ The default is `standard`.
89
75
 
90
- ## Shipped rulesets
76
+ ## Rulesets
91
77
 
92
- | Ruleset | Contents |
78
+ | Ruleset | Guards |
93
79
  |---|---|
94
- | `irreversible` | git history rewrites and ref deletion (deny), `dd of=`, `mkfs*`, `wipefs`, `blkdiscard`, `fdisk` family, `shred` |
95
- | `secrets` | `.env` files and private keys (path rules, deny) |
96
- | `privilege` | `sudo`/`doas`/`pkexec`, privileged containers, recursive `chmod 777`/`chown` |
80
+ | `irreversible` | git history rewrites, `dd of=`, `mkfs*`, `wipefs`, `blkdiscard`, `fdisk`, `shred` |
81
+ | `secrets` | `.env` files and private keys |
82
+ | `privilege` | `sudo`, `doas`, `pkexec`, privileged containers, recursive `chmod 777`/`chown` |
97
83
  | `bulk-delete` | `rm -r`, `find -delete`, `xargs rm`, `truncate`, `rsync --delete`, `git clean`, stash drop, worktree remove |
98
- | `git-local` | `git add`, `commit`, `merge`, `reset --hard`, discard, branch/tag delete |
84
+ | `git-local` | `git add`, `commit`, `merge`, `reset --hard`, discard, branch and tag delete |
99
85
  | `git-remote` | `git push`; `--force-with-lease` stays allowed |
100
- | `publish` | package publishing (`npm`, `bun`, `pnpm`, `yarn`, `cargo`, `gem`), `gh delete` |
86
+ | `publish` | package publishing, `gh delete` |
101
87
  | `database` | `dropdb`, SQL `DROP`/`TRUNCATE`, Redis `FLUSH` |
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` |
104
-
105
- ## Presets
106
-
107
- | Preset | Level | Adds |
108
- |---|---|---|
109
- | `minimal` | 1 | `irreversible`, `secrets` |
110
- | `standard` | 2 | `minimal` + `privilege` |
111
- | `cautious` | 3 | `standard` + `bulk-delete`, `database`, `infra`, `git-remote`, `publish` |
112
- | `paranoid` | 4 | `cautious` + `git-local` |
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
-
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.
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.
88
+ | `infra` | terraform, kubectl delete/drain, helm uninstall, docker prune |
89
+ | `dynamic-exec` | commands whose real program cannot be read: `env -S`, `xargs`, `find -exec`, `eval`, `source`, `python -c`, `node -e`, `pwsh`, `busybox` |
140
90
 
141
91
  ## Limits
142
92
 
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.
93
+ A guard, not a sandbox: it reads the command text, and a program's own behaviour is out of reach.
144
94
 
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.
151
- - Reads outside the workspace are not gated: a path rule is the only check on what the agent may read.
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.
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.
95
+ - Not covered: code downloaded and run later (`npx`, `at`, `cron`), remote execution (`ssh host '…'`, `docker exec`), project scripts (`make`, `npm run`), `rm` without `-r`.
96
+ - A script on stdin (`curl … | bash`) asks and cannot be granted. `python job.py` asks once per script file; a changed file asks again.
97
+ - Reads outside the workspace pass; only a path rule stops them.
98
+ - Only `bash`, `powershell` and the file tools are inspected.
154
99
 
155
100
  ## Development
156
101
 
@@ -158,8 +103,8 @@ A guard, not a sandbox. The strongest thing it can promise is that nothing the c
158
103
  bun test
159
104
  ```
160
105
 
161
- `pi-tui`, `pi-coding-agent` and `ajv` come from symlinks in `node_modules/`. The first two are peer dependencies that pi provides at runtime.
106
+ `pi-tui`, `pi-coding-agent` and `ajv` are symlinks in `node_modules/`; the first two are peer dependencies that pi provides at runtime.
162
107
 
163
108
  ## Similar extensions
164
109
 
165
- - [`@aliou/pi-guardrails`](https://pi.dev/packages/%40aliou/pi-guardrails): which inspires this plugin.
110
+ - [`@aliou/pi-guardrails`](https://pi.dev/packages/%40aliou/pi-guardrails) — the inspiration for this plugin.
@@ -33,6 +33,9 @@ A permission level. Only the shipped index defines presets; a user config select
33
33
 
34
34
  ```json
35
35
  { "preset": "cautious" }
36
+ ```
37
+
38
+ ```json
36
39
  { "preset": { "id": "cautious", "remove": ["bulk-delete"] } }
37
40
  ```
38
41
 
@@ -73,7 +76,7 @@ A file path resolves from the file that names it. Redefining a shipped ruleset i
73
76
  `include` adds rulesets to the active preset:
74
77
 
75
78
  ```json
76
- { "preset": "standard", "include": ["git-local", { "id": "git-remote", "remove": ["gh-delete"] }] }
79
+ { "preset": "standard", "include": ["git-local", { "id": "publish", "remove": ["gh-delete"] }] }
77
80
  ```
78
81
 
79
82
  `remove` lists **rule ids of that ruleset**. It cannot reach another ruleset, so equal ids in unrelated packs cannot cause a cross-pack deletion. Removing an id the ruleset does not define is a warning.
@@ -82,7 +85,7 @@ The same ruleset id cannot appear twice in one `include` list. To turn one rule
82
85
 
83
86
  ## Shipped rulesets and presets
84
87
 
85
- See [README](../README.md#shipped-rulesets) for what each pack gates and [README](../README.md#presets) for the four levels. The shipped default is `preset: "standard"`.
88
+ See [README](../README.md#rulesets) for what each pack gates and [README](../README.md#presets) for the four levels. The shipped default is `preset: "standard"`.
86
89
 
87
90
  ## Command rules
88
91
 
@@ -119,12 +122,17 @@ Matching notes:
119
122
  - `$(...)`, backticks, `<(...)` and `>(...)` are parsed as commands and checked with the same rules, including inside double quotes. Single-quoted text stays text.
120
123
  - 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
124
  - 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.
125
+ - Shell keywords are peeled too: `then`, `do`, `else`, `elif`, `if`, `while`, `until`, `!`, `{` and `coproc` 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. A `)` ends the command before it, so a subshell or a `case` arm is judged like any other command.
126
+ - Bash syntax that names the command is read the way bash reads it: `$(...)`, backticks, `<(...)` and `>(...)` are commands; `$'...'` is decoded; a backslash-newline joins lines; `2>file` is a descriptor, not an argument; `${x:-a)b}` stays one word; a lone `[` is the test builtin, not a glob.
123
127
  - 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.
128
+ - A program's script input is judged when the gate can see it. When a here-string and a heredoc are on one command, the here-string is what the program reads.
129
+ - 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, and its paths go through the path rules;
130
+ - a script in another language (`python job.py`) asks once per file content, granted as `opaque:<program>:file:<hash>`, or as `opaque:<program>:<path>` when the file cannot be read;
131
+ - inline code written in the command (`python3 - <<'PY'`) asks and is granted as `opaque:<program>:heredoc`, because the text was on screen and can be approved;
132
+ - a script that arrives on a pipe or a redirect (`curl … | bash`, `bash < f`, `sh -s`, `<<<`) asks and carries no grant key, because that text does not exist when the decision is made.
133
+ - `-c` names inline code and is followed instead of read; when that code also reads stdin (`bash -c 'sh' <<EOF`), it asks. `-n`/`--noexec` parses without running, so neither the script nor its paths are followed. A clustered option keeps working: `bash -euo pipefail -c '…'` is still followed, and `bash -euo pipefail f.sh` still reads `f.sh`.
126
134
  - Precedence inside one simple command: `deny` → `allow` → `ask` → `defaultPermission.commands`.
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.
135
+ - "Allow for this session" remembers the rule, the flags, and what the rule matched on: the subcommand (`terraform apply` does not approve `terraform destroy`), the argument, or — for a rule that matches the whole line or a flag carrying code — that exact line (`bun -e 'a'` does not approve `bun -e 'b'`). After allowing `rm -r build`, `rm -r dist` still runs without asking, while `rm -rf dist` asks again. Flag order does not matter, and a deny rule still blocks a granted command.
128
136
 
129
137
  ## Path rules
130
138
 
@@ -162,7 +170,7 @@ Matching:
162
170
  |---|---|
163
171
  | `**` | every path under the project; never `../outside` |
164
172
  | no slash (`.env`, `*.pem`) | the basename, at any depth |
165
- | starts with `~` or `/` | the absolute path |
173
+ | starts with `~`, `/`, `C:/` or `//` | the absolute path |
166
174
  | anything else (`config/*.yml`) | the path relative to the project; never `../outside` |
167
175
 
168
176
  - The target is resolved to an absolute path first: `~` expanded, `..` normalized, and a path reached through `cd` in the same command pinned to that directory.
@@ -187,7 +195,7 @@ What happens when no rule matches:
187
195
  | `ask` | prompt for the program | prompt for the path |
188
196
  | `deny` | only `allow` rules run | only `allow` path rules are reachable |
189
197
 
190
- - Config-level only; ignored in rulesets and presets.
198
+ - Config-level only: a ruleset that carries it is rejected, and a preset never has one.
191
199
  - Grants: `default:<program>:<flags>` for commands, `path:default:<op>:<absolute path>` for paths. A path fallback grant covers exactly one path.
192
200
  - The path fallback does not bypass `outsideCwd`; that gate keeps its own `mode`.
193
201
  - With `paths: "deny"`, use an allow rule for the workspace: `{ "id": "workspace", "patterns": ["**"], "action": "allow" }`.
@@ -227,7 +235,7 @@ Fatal — the config cannot be honored and every gated tool is blocked:
227
235
  - an unknown `include` or `preset` id, or two equal ids in one `include` list;
228
236
  - the same rule id defined twice inside one ruleset or one config file;
229
237
  - the same rule id in two selected rulesets;
230
- - a selected ruleset file that is missing or invalid.
238
+ - a config file that is not valid JSON or cannot be read; a selected ruleset file that is missing or invalid.
231
239
 
232
240
  Warnings:
233
241
 
@@ -236,7 +244,6 @@ Warnings:
236
244
  - a config rule that moves a bundled `deny` rule to `ask` or `allow`;
237
245
  - an unknown field name;
238
246
  - a bad `argvRegex` (the rule is dropped);
239
- - invalid JSON in a user file (that file is skipped);
240
247
  - `presets` in a user file (ignored; presets are shipped only).
241
248
 
242
249
  ## Schema
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jalaxy33/pi-permission",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "Permission gate for pi: command, path and workspace rules",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
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.",
3
+ "description": "Programs that run another command, or code the gate cannot read. A wrapper whose options the gate can peel is judged by the command inside it; a shape it cannot peel lands here and asks.",
4
4
  "commands": {
5
5
  "allow": [
6
6
  {
@@ -25,6 +25,12 @@
25
25
  {
26
26
  "id": "exec-wrapper",
27
27
  "program": [
28
+ "time",
29
+ "nice",
30
+ "nohup",
31
+ "setsid",
32
+ "timeout",
33
+ "stdbuf",
28
34
  "watch",
29
35
  "strace",
30
36
  "ltrace",
package/src/decide.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { parseArgs, programWordIndex, type Args } from "./argv";
2
2
  import { matchRule } from "./match";
3
- import { MAX_NESTING, scriptAfterC, SHELLS } from "./ops";
4
- import { isCodeRunner, scriptHash, scriptOperand } from "./scripts";
3
+ import { isSyntaxCheck, MAX_NESTING, scriptAfterC, SHELLS } from "./ops";
4
+ import { flagCarriesCode, isCodeRunner, scriptHash, scriptOperand } from "./scripts";
5
5
  import { tokenizeDetailed, type SimpleCommand, type WordMeta } from "./tokenize";
6
6
  import { unlayer } from "./unlayer";
7
7
  import type { Action, CompiledRule, GateRules, Verdict } from "./types";
@@ -17,10 +17,11 @@ function verdict(action: Action, matched: boolean): Verdict {
17
17
  * command at runtime. Guessing here would turn a bypass into a silent allow,
18
18
  * so it asks instead.
19
19
  */
20
- function unreadable(what: string): Verdict {
20
+ function unreadable(what: string, subject = ""): Verdict {
21
21
  const result = verdict("ask", true);
22
22
  result.reasons = [`gate cannot inspect this command: ${what}`];
23
- result.grants = [`unreadable:${what}`];
23
+ const scope = subject === "" ? "" : `:${scriptHash(subject)}`;
24
+ result.grants = [`unreadable:${what}${scope}`];
24
25
  return result;
25
26
  }
26
27
 
@@ -30,9 +31,11 @@ function hasRuntimeExpansion(script: string): boolean {
30
31
  }
31
32
 
32
33
  /** A program name built from a substitution, escape or glob is not a name. */
33
- function unreadableProgram(meta: WordMeta | undefined): Verdict | undefined {
34
+ function unreadableProgram(meta: WordMeta | undefined, argv: string[]): Verdict | undefined {
34
35
  if (!meta) return undefined;
35
- if (meta.expansion || meta.escape || meta.glob) return unreadable("program name is not a literal");
36
+ if (meta.expansion || meta.escape || meta.glob) {
37
+ return unreadable("program name is not a literal", argv.slice(0, 2).join(" "));
38
+ }
36
39
  return undefined;
37
40
  }
38
41
 
@@ -57,43 +60,91 @@ export function decideInput(
57
60
  if (!args) return undefined;
58
61
  const shell = SHELLS.has(args.program);
59
62
  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
+ // `-n` only parses; `-c` names code inline. An option after the script name
64
+ // belongs to the script, not to the shell.
65
+ if (isSyntaxCheck(args.program, argv)) return undefined;
66
+
67
+ // A here-string replaces stdin, so a heredoc on the same command is not what
68
+ // the program reads.
69
+ const heredocs = simple.stdinText === undefined ? (simple.heredocs ?? []) : [];
70
+ const stdinFed =
71
+ simple.stdinPiped === true ||
72
+ simple.stdinText !== undefined ||
73
+ args.flags.has("-") ||
74
+ (shell && args.flags.has("-s")) ||
75
+ simple.redirects.some((redirect) => redirect.op === "<");
76
+
77
+ if (scriptAfterC(argv) !== undefined) {
78
+ // The inline code is judged by the caller. Its stdin is not.
79
+ if (heredocs.length > 0 || stdinFed) {
80
+ return unreadableScript(args.program, "it runs inline code that reads stdin, which the command text does not contain");
81
+ }
82
+ return undefined;
83
+ }
63
84
 
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);
85
+ let merged: Verdict | undefined;
86
+ const collect = (verdict: Verdict | undefined) => {
87
+ if (!verdict) return;
88
+ merged = merged === undefined ? verdict : mergeVerdicts(merged, verdict);
89
+ };
90
+ if (shell) {
91
+ for (const body of heredocs) {
92
+ collect(depth >= MAX_NESTING ? unreadable("nested script", body) : decide(body, rules, fallback, depth + 1, options));
93
+ }
67
94
  }
68
95
 
69
- const operand = scriptOperand(args.positional);
96
+ const operand = scriptOperand(args.program, argv);
70
97
  if (operand !== undefined) {
71
98
  const text = options.readScript?.(operand);
72
99
  if (text === undefined) {
73
- return unreadableScript(args.program, `cannot read ${operand}`, `opaque:${args.program}:${operand}`);
100
+ collect(unreadableScript(args.program, `cannot read ${operand}`, `opaque:${args.program}:${operand}`));
101
+ } else if (depth >= MAX_NESTING) {
102
+ collect(unreadable("nested script", text));
103
+ } else if (shell) {
104
+ collect(decide(text, rules, fallback, depth + 1, options));
105
+ } else {
106
+ collect(
107
+ unreadableScript(
108
+ args.program,
109
+ `${operand} is not shell code, so it is not parsed`,
110
+ `opaque:${args.program}:file:${scriptHash(text)}`,
111
+ ),
112
+ );
74
113
  }
75
- if (depth >= MAX_NESTING) return unreadable("nested script");
76
- if (shell) return decide(text, rules, fallback, depth + 1, options);
114
+ }
115
+ if (merged) return merged;
116
+ if (operand !== undefined) return undefined;
117
+
118
+ // A heredoc is source code written into the command, so it can be approved:
119
+ // the text was on screen. A pipe or a redirect is not, so it cannot.
120
+ if (heredocs.length > 0) {
77
121
  return unreadableScript(
78
122
  args.program,
79
- `${operand} is not shell code, so it is not parsed`,
80
- `opaque:${args.program}:file:${scriptHash(text)}`,
123
+ "its script is written inline, in a language the gate does not parse",
124
+ `opaque:${args.program}:heredoc`,
81
125
  );
82
126
  }
83
127
 
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");
128
+ if (stdinFed) return unreadableScript(args.program, "its script arrives on stdin, which the command text does not contain");
91
129
  return undefined;
92
130
  }
93
131
 
94
- /** A session grant covers one rule with the same flags, not every command it matches. */
132
+ /**
133
+ * A session grant covers one rule with the same flags, and with the same
134
+ * subcommand or argument the rule matched on: `terraform apply` must not
135
+ * approve `terraform destroy`.
136
+ */
95
137
  function grantKey(rule: CompiledRule, args: Args): string {
96
- return `rule:${rule.id}:${[...args.flags].filter(canonicalFlag).sort().join(",")}`;
138
+ const scope: string[] = [];
139
+ if (rule.subcommand) scope.push(args.positional[0] ?? "");
140
+ if (rule.args) scope.push(rule.args.find((word) => args.positional.includes(word)) ?? "");
141
+ // A rule that matches on the whole line, or on a flag that carries code, is
142
+ // about that exact invocation: `bun -e 'a'` must not approve `bun -e 'b'`.
143
+ const carriesValue = rule.anyFlag?.some((flag) => flagCarriesCode(args.program, flag)) === true;
144
+ if (rule.argvRegex || carriesValue) scope.push(scriptHash(args.joined));
145
+ const flags = [...args.flags].filter(canonicalFlag).sort().join(",");
146
+ const scopePart = scope.length > 0 ? `:${scope.join(",")}` : "";
147
+ return `rule:${rule.id}${scopePart}:${flags}`;
97
148
  }
98
149
 
99
150
  /** `-rf` and `-fr` are the same flags; keep only the letters for grant keys. */
@@ -141,6 +192,12 @@ function decideOne(argv: string[], rules: GateRules, fallback: Action): Verdict
141
192
  return result;
142
193
  }
143
194
 
195
+ export function mergeVerdicts(left: Verdict, right: Verdict): Verdict {
196
+ const merged: Verdict = { ...left, reasons: [...left.reasons], grants: [...left.grants] };
197
+ mergeInto(merged, right);
198
+ return merged;
199
+ }
200
+
144
201
  function mergeInto(target: Verdict, source: Verdict): void {
145
202
  for (const reason of source.reasons) {
146
203
  if (!target.reasons.includes(reason)) target.reasons.push(reason);
@@ -172,7 +229,7 @@ export function decide(
172
229
  const merged: Verdict = { action: "allow", reasons: [], grants: [], terminate: false, matched: false };
173
230
 
174
231
  const split = tokenizeDetailed(command);
175
- for (const hazard of split.hazards) mergeInto(merged, unreadable(hazard));
232
+ for (const hazard of split.hazards) mergeInto(merged, unreadable(hazard, command));
176
233
 
177
234
  for (const simple of split.commands) {
178
235
  const argv = unlayer(simple.argv);
@@ -180,7 +237,7 @@ export function decide(
180
237
  // `FOO=1 "$CMD" x` puts the program one word later than the segment start.
181
238
  const wordIndex = programWordIndex(argv);
182
239
  const meta = wordIndex === -1 ? undefined : simple.words[simple.argv.length - argv.length + wordIndex];
183
- mergeInto(merged, unreadableProgram(meta) ?? verdict("allow", false));
240
+ mergeInto(merged, unreadableProgram(meta, argv) ?? verdict("allow", false));
184
241
  mergeInto(merged, decideOne(argv, rules, fallback));
185
242
 
186
243
  const input = decideInput(simple, argv, rules, fallback, depth, options);
package/src/gate.ts CHANGED
@@ -74,7 +74,7 @@ function toolTargets(
74
74
  if (!GATED_TOOLS.has(toolName)) return undefined;
75
75
  const command = input.command;
76
76
  if (typeof command !== "string" || command.trim() === "") return undefined;
77
- return { paths: collectTargets(command, cwd), label: command, text: command };
77
+ return { paths: collectTargets(command, cwd, { readScript: (path) => readScript(path, cwd) }), label: command, text: command };
78
78
  }
79
79
 
80
80
  /** A grant covers one rule and one operation: allowing a read leaves writes asking. */
package/src/ops.ts CHANGED
@@ -5,6 +5,9 @@ import * as fs from "node:fs";
5
5
  import { basename, isAbsolute, resolve } from "node:path";
6
6
  import { parseArgs, type Args } from "./argv";
7
7
  import { expandTilde } from "./paths";
8
+ import { firstOperandIndex, SHELLS, scriptOperand } from "./scripts";
9
+
10
+ export { SHELLS };
8
11
  import { type SimpleCommand, tokenize } from "./tokenize";
9
12
  import { unlayer } from "./unlayer";
10
13
  import type { PathOp } from "./types";
@@ -63,7 +66,6 @@ const DELETE = new Set(["rm", "unlink", "shred", "rmdir"]);
63
66
  const COPY = new Set(["cp", "mv", "rsync", "scp", "dd"]);
64
67
 
65
68
  const EXTENSION = /\.[A-Za-z0-9_]+$/;
66
- export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
67
69
  const MAX_GLOB_MATCHES = 50;
68
70
  export const MAX_NESTING = 3;
69
71
 
@@ -213,6 +215,7 @@ function targetsOf(args: Args, simple: SimpleCommand, cwd: string): PathTarget[]
213
215
  /**
214
216
  * Script text of `sh -c "..."`, so nested commands are checked too.
215
217
  * Reads the token after `-c`, not the first positional: `bash -o pipefail -c '...'`.
218
+ * A `-c` after the script name is the script's own argument, not a shell option.
216
219
  */
217
220
  export function scriptAfterC(argv: string[]): string | undefined {
218
221
  const args = parseArgs(argv);
@@ -220,7 +223,18 @@ export function scriptAfterC(argv: string[]): string | undefined {
220
223
  const index = argv.findIndex(
221
224
  (token, position) => position > 0 && /^-[A-Za-z0-9]*c[A-Za-z0-9]*$/.test(token),
222
225
  );
223
- return index > 0 ? argv[index + 1] : undefined;
226
+ if (index <= 0) return undefined;
227
+ const firstOperand = firstOperandIndex(args.program, argv);
228
+ if (firstOperand !== -1 && index > firstOperand) return undefined;
229
+ return argv[index + 1];
230
+ }
231
+
232
+ /** Whether a shell only parses its script (`-n`) instead of running it. */
233
+ export function isSyntaxCheck(program: string, argv: string[]): boolean {
234
+ if (!SHELLS.has(program)) return false;
235
+ const firstOperand = firstOperandIndex(program, argv);
236
+ const options = firstOperand === -1 ? argv.slice(1) : argv.slice(1, firstOperand);
237
+ return options.includes("-n") || options.includes("--noexec");
224
238
  }
225
239
 
226
240
  /** A path from a `cd`-relative command is pinned to the directory that command runs in. */
@@ -229,8 +243,13 @@ function pin(target: PathTarget, current: string, cwd: string): PathTarget {
229
243
  return { ...target, path: resolve(current, target.path) };
230
244
  }
231
245
 
246
+ export interface TargetOptions {
247
+ /** Reads a script file named by a command. Undefined when it cannot be read. */
248
+ readScript?: (path: string) => string | undefined;
249
+ }
250
+
232
251
  /** All path targets of a command string, including `cd` tracking and `sh -c`. */
233
- export function collectTargets(command: string, cwd: string, depth = 0): PathTarget[] {
252
+ export function collectTargets(command: string, cwd: string, options: TargetOptions = {}, depth = 0): PathTarget[] {
234
253
  const targets: PathTarget[] = [];
235
254
  let current = cwd;
236
255
 
@@ -243,7 +262,17 @@ export function collectTargets(command: string, cwd: string, depth = 0): PathTar
243
262
  for (const target of targetsOf(args, peeled, current)) targets.push(pin(target, current, cwd));
244
263
  const script = scriptAfterC(argv);
245
264
  if (script && depth < MAX_NESTING) {
246
- for (const target of collectTargets(script, current, depth + 1)) targets.push(pin(target, current, cwd));
265
+ for (const target of collectTargets(script, current, options, depth + 1)) targets.push(pin(target, current, cwd));
266
+ }
267
+
268
+ // A shell's script input touches paths too; read it when the gate can.
269
+ if (SHELLS.has(args.program) && !isSyntaxCheck(args.program, argv) && depth < MAX_NESTING) {
270
+ const bodies = simple.heredocs ?? [];
271
+ const operand = scriptOperand(args.program, argv);
272
+ const file = operand === undefined ? undefined : options.readScript?.(operand);
273
+ for (const text of file === undefined ? bodies : [...bodies, file]) {
274
+ for (const target of collectTargets(text, current, options, depth + 1)) targets.push(pin(target, current, cwd));
275
+ }
247
276
  }
248
277
  current = cwdAfterArgs(args, current);
249
278
  }
package/src/prefixes.ts CHANGED
@@ -24,11 +24,15 @@ interface PrefixSpec {
24
24
 
25
25
  const SPECS: Record<string, PrefixSpec> = {
26
26
  time: { flags: ["-p"] },
27
- nice: { valueFlags: ["-n"], numericFlag: true },
27
+ nice: { valueFlags: ["-n", "--adjustment"], numericFlag: true },
28
28
  nohup: {},
29
- setsid: { flags: ["-f", "-c", "-w"] },
30
- timeout: { valueFlags: ["-k", "-s"], positional: 1 },
31
- stdbuf: { valueFlags: ["-i", "-o", "-e"] },
29
+ setsid: { flags: ["-f", "-c", "-w", "--fork", "--ctty", "--wait"] },
30
+ timeout: {
31
+ flags: ["--preserve-status", "--foreground"],
32
+ valueFlags: ["-k", "-s", "--kill-after", "--signal"],
33
+ positional: 1,
34
+ },
35
+ stdbuf: { valueFlags: ["-i", "-o", "-e", "--input", "--output", "--error"] },
32
36
  command: { flags: ["-p"] },
33
37
  env: { assignmentsOnly: true },
34
38
  };
package/src/rulesets.ts CHANGED
@@ -42,7 +42,12 @@ export function readJson(
42
42
  let raw: string;
43
43
  try {
44
44
  raw = readFileSync(path, "utf8");
45
- } catch {
45
+ } catch (error) {
46
+ // A missing file is normal; one that exists and cannot be read is not.
47
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
48
+ const reason = `cannot be read (${(error as Error).message})`;
49
+ warnings.push(`${path}: ${reason}`);
50
+ failures?.push({ path, reason });
46
51
  return undefined;
47
52
  }
48
53
  try {
package/src/scripts.ts CHANGED
@@ -1,14 +1,17 @@
1
1
  /**
2
- * Programs that run source code, and how to name that code in a session grant.
2
+ * Programs that run source code, and which of their words is that code.
3
3
  *
4
4
  * A shell script can be read and judged like the command line it is. Every
5
5
  * other language is a program the gate cannot parse, so its script becomes an
6
- * opaque ask: once per file (by content), never for stdin.
6
+ * opaque ask: once per file, or once per heredoc body, never for a pipe.
7
7
  */
8
8
 
9
9
  import { createHash } from "node:crypto";
10
10
  import { normalizeProgram } from "./program";
11
11
 
12
+ /** Shells whose `-c` script and `-o` values the gate understands. */
13
+ export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
14
+
12
15
  /** Programs whose first non-flag argument is source code. */
13
16
  const INTERPRETERS =
14
17
  /^(python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|rscript|osascript|pwsh|powershell|groovy|tclsh|wish)$/;
@@ -17,13 +20,100 @@ export function isCodeRunner(program: string): boolean {
17
20
  return INTERPRETERS.test(normalizeProgram(program).toLowerCase());
18
21
  }
19
22
 
23
+ export function programFamily(program: string): string {
24
+ const name = normalizeProgram(program).toLowerCase();
25
+ if (SHELLS.has(name)) return "shell";
26
+ if (name.startsWith("python") || name.startsWith("pypy")) return "python";
27
+ if (name.startsWith("node")) return "node";
28
+ return name;
29
+ }
30
+
31
+ /**
32
+ * Options that consume the next word. `-c` is here too: its value is inline
33
+ * code, not an operand.
34
+ */
35
+ const VALUE_FLAGS: Record<string, Set<string>> = {
36
+ shell: new Set(["-o", "+o", "-O", "+O", "-c", "--init-file", "--rcfile"]),
37
+ python: new Set(["-m", "-c", "-W", "-X", "-Q", "--check-hash-based-pycs"]),
38
+ node: new Set(["-r", "--require", "--loader", "--import", "-e", "--eval", "-p", "--print", "--inspect-port"]),
39
+ bun: new Set(["-e", "--eval", "-p", "--print"]),
40
+ perl: new Set(["-I", "-M", "-e"]),
41
+ ruby: new Set(["-I", "-r", "-e"]),
42
+ };
43
+
44
+ /** Last letter of a clustered short option that still takes a value (`-euo pipefail`, `-lc '…'`). */
45
+ const CLUSTER_VALUE_LETTERS: Record<string, Set<string>> = {
46
+ shell: new Set(["o", "O", "c"]),
47
+ python: new Set(["m", "W", "X", "Q"]),
48
+ };
49
+
50
+ /** Options that name code inline or a module, so no script file is read. */
51
+ const MODULE_FLAGS: Record<string, Set<string>> = {
52
+ python: new Set(["-m", "-c"]),
53
+ node: new Set(["-e", "--eval", "-p", "--print", "--test"]),
54
+ bun: new Set(["-e", "--eval"]),
55
+ poppler: new Set(),
56
+ };
57
+
58
+ /** Subcommands that run a project task instead of a named script. */
59
+ const RUNNER_SUBCOMMANDS: Record<string, Set<string>> = {
60
+ bun: new Set(["test", "run", "x", "build", "install", "add", "remove", "pm", "create"]),
61
+ deno: new Set(["task", "test", "bench", "fmt", "lint", "check", "doc", "publish"]),
62
+ };
63
+
20
64
  const SCRIPT_NAME = /\.(sh|bash|zsh|ksh|dash|fish|py|pyw|js|mjs|cjs|ts|pl|rb|php|lua|ps1|tcl)$/i;
21
65
 
22
- /** A positional that names source code rather than a data operand. */
23
- export function scriptOperand(positional: string[]): string | undefined {
24
- return positional.find(
25
- (token) => SCRIPT_NAME.test(token) || token.startsWith("./") || token.startsWith("../") || token.startsWith("/"),
26
- );
66
+ function valueFlags(program: string): Set<string> {
67
+ return VALUE_FLAGS[programFamily(program)] ?? new Set<string>();
68
+ }
69
+
70
+ /** Whether this flag's value is code, so a rule matched on it is line-specific. */
71
+ export function flagCarriesCode(program: string, flag: string): boolean {
72
+ return valueFlags(program).has(flag);
73
+ }
74
+
75
+ /** Whether this option consumes the word after it. */
76
+ export function optionTakesValue(program: string, token: string): boolean {
77
+ if (token === "--" || !token.startsWith("-") || token === "-") return false;
78
+ const table = valueFlags(program);
79
+ if (token.includes("=")) return false;
80
+ if (table.has(token)) return true;
81
+ if (token.startsWith("--")) return false;
82
+ if (token.length === 2) return false;
83
+ const letters = CLUSTER_VALUE_LETTERS[programFamily(program)];
84
+ return letters?.has(token[token.length - 1] as string) === true;
85
+ }
86
+
87
+ /** Index of the first word that is not the program and not an option. */
88
+ export function firstOperandIndex(program: string, argv: string[]): number {
89
+ for (let i = 1; i < argv.length; i += 1) {
90
+ const token = argv[i] as string;
91
+ if (token === "--") continue;
92
+ if (optionTakesValue(program, token)) {
93
+ i += 1;
94
+ continue;
95
+ }
96
+ if (token.startsWith("-") && token !== "-") continue;
97
+ return i;
98
+ }
99
+ return -1;
100
+ }
101
+
102
+ /**
103
+ * The positional that names source code. `bash --init-file safe.sh danger.sh`
104
+ * names `danger.sh`; `bun test x.ts` and `python -m pytest x.py` name none.
105
+ */
106
+ export function scriptOperand(program: string, argv: string[]): string | undefined {
107
+ const index = firstOperandIndex(program, argv);
108
+ if (index === -1) return undefined;
109
+ const moduleFlags = MODULE_FLAGS[programFamily(program)];
110
+ if (moduleFlags && argv.slice(1, index).some((token) => moduleFlags.has(token))) return undefined;
111
+ const token = argv[index] as string;
112
+ if (RUNNER_SUBCOMMANDS[programFamily(program)]?.has(token) === true) return undefined;
113
+ if (SCRIPT_NAME.test(token) || token.startsWith("./") || token.startsWith("../") || token.startsWith("/")) {
114
+ return token;
115
+ }
116
+ return undefined;
27
117
  }
28
118
 
29
119
  export function scriptHash(text: string): string {
package/src/tokenize.ts CHANGED
@@ -32,8 +32,8 @@ export interface SimpleCommand {
32
32
  /** Parallel to `argv`. */
33
33
  words: WordMeta[];
34
34
  redirects: Redirect[];
35
- /** Body of the first heredoc this command reads (`bash <<EOF`). */
36
- heredoc?: string;
35
+ /** Bodies of the heredocs this command reads (`bash <<EOF`). */
36
+ heredocs?: string[];
37
37
  /** Text fed on stdin by a here string (`bash <<< "..."`). */
38
38
  stdinText?: string;
39
39
  /** Stdin comes from a pipe, so it is not visible in the command text. */
@@ -52,6 +52,11 @@ function isSeparator(ch: string): boolean {
52
52
  return ch === ";" || ch === "&" || ch === "|" || ch === "\n";
53
53
  }
54
54
 
55
+ /** Subshell and group operators end a command without starting a new one. */
56
+ function isGrouping(ch: string): boolean {
57
+ return ch === "(" || ch === ")";
58
+ }
59
+
55
60
  function blankMeta(): WordMeta {
56
61
  return { expansion: false, quote: false, escape: false, glob: false };
57
62
  }
@@ -71,6 +76,11 @@ function scanParen(input: string, open: number): Scanned | undefined {
71
76
  i += 2;
72
77
  continue;
73
78
  }
79
+ if (ch === "'" || ch === '"') {
80
+ const quoted = readQuoted(input, i);
81
+ i = quoted.next;
82
+ continue;
83
+ }
74
84
  if (ch === "(") depth++;
75
85
  else if (ch === ")") {
76
86
  depth--;
@@ -143,6 +153,16 @@ function readQuoted(input: string, start: number): Quoted {
143
153
  continue;
144
154
  }
145
155
  if (ch === "$" && input[i + 1] === "(") {
156
+ // `$((...))` is arithmetic: a value, not a command.
157
+ if (input[i + 2] === "(") {
158
+ const arithmetic = scanArithmetic(input, i + 1);
159
+ if (arithmetic === undefined) {
160
+ return { text, next: input.length, subs, expansion: true, unterminated: true };
161
+ }
162
+ expansion = true;
163
+ i = arithmetic;
164
+ continue;
165
+ }
146
166
  const found = scanParen(input, i + 1);
147
167
  if (!found) return { text, next: input.length, subs, expansion: true, unterminated: true };
148
168
  subs.push(found.inner);
@@ -160,6 +180,59 @@ function readQuoted(input: string, start: number): Quoted {
160
180
  return { text, next: i + 1, subs, expansion, unterminated: false };
161
181
  }
162
182
 
183
+ const ANSI_C: Record<string, string> = {
184
+ n: "\n",
185
+ t: "\t",
186
+ r: "\r",
187
+ a: "\u0007",
188
+ b: "\b",
189
+ f: "\f",
190
+ v: "\v",
191
+ e: "\u001b",
192
+ E: "\u001b",
193
+ "\\": "\\",
194
+ "'": "'",
195
+ '"': '"',
196
+ "?": "?",
197
+ };
198
+
199
+ /** Reads `$'...'` opened at the quote; the value is what bash would produce. */
200
+ function readAnsiC(input: string, open: number): { text: string; next: number } | undefined {
201
+ let text = "";
202
+ let i = open + 1;
203
+ while (i < input.length) {
204
+ const ch = input[i] as string;
205
+ if (ch === "'") return { text, next: i + 1 };
206
+ if (ch !== "\\") {
207
+ text += ch;
208
+ i++;
209
+ continue;
210
+ }
211
+ const code = input[i + 1] ?? "";
212
+ const simple = ANSI_C[code];
213
+ if (simple !== undefined) {
214
+ text += simple;
215
+ i += 2;
216
+ continue;
217
+ }
218
+ const hex = /^x([0-9A-Fa-f]{1,2})/.exec(input.slice(i + 1));
219
+ if (hex) {
220
+ text += String.fromCharCode(Number.parseInt(hex[1] as string, 16));
221
+ i += 1 + hex[0].length;
222
+ continue;
223
+ }
224
+ const octal = /^([0-7]{1,3})/.exec(input.slice(i + 1));
225
+ if (octal) {
226
+ text += String.fromCharCode(Number.parseInt(octal[1] as string, 8));
227
+ i += 1 + octal[0].length;
228
+ continue;
229
+ }
230
+ text += code;
231
+ i += 2;
232
+ }
233
+ return undefined;
234
+ }
235
+
163
236
  /**
164
237
  * Index after the closing `))` of an arithmetic expansion. `open` points at the
165
238
  * first of the two opening parentheses.
@@ -191,10 +264,12 @@ export function tokenizeDetailed(input: string): Tokenized {
191
264
  let inWord = false;
192
265
  let piped = false;
193
266
  let pendingStdin: string | undefined;
194
- let heredocs: string[] = [];
267
+ let heredocs: Array<{ delimiter: string; owner?: SimpleCommand }> = [];
195
268
 
196
269
  const flushWord = () => {
197
270
  if (inWord) {
271
+ // `[ -f x ]` starts with the test builtin, not a brace expression.
272
+ if (word === "[" || word === "[[") meta.glob = false;
198
273
  argv.push(word);
199
274
  words.push(meta);
200
275
  word = "";
@@ -203,6 +278,15 @@ export function tokenizeDetailed(input: string): Tokenized {
203
278
  }
204
279
  };
205
280
 
281
+ // `2>file` names a descriptor; that digit is not an argument.
282
+ const dropFileDescriptor = () => {
283
+ if (inWord && /^\d+$/.test(word)) {
284
+ word = "";
285
+ meta = blankMeta();
286
+ inWord = false;
287
+ }
288
+ };
289
+
206
290
  const endCommand = () => {
207
291
  flushWord();
208
292
  if (argv.length > 0) {
@@ -212,6 +296,9 @@ export function tokenizeDetailed(input: string): Tokenized {
212
296
  pendingStdin = undefined;
213
297
  commands.push(command);
214
298
  piped = false;
299
+ // A heredoc body belongs to the command that declared it, which is the
300
+ // one just pushed — not to whatever runs later on the same line.
301
+ for (const heredoc of heredocs) heredoc.owner ??= command;
215
302
  }
216
303
  argv = [];
217
304
  words = [];
@@ -262,6 +349,11 @@ export function tokenizeDetailed(input: string): Tokenized {
262
349
  const ch = input[i] as string;
263
350
 
264
351
  if (ch === "\\") {
352
+ // `\` at end of line joins the lines and contributes no character.
353
+ if (input[i + 1] === "\n") {
354
+ i += 2;
355
+ continue;
356
+ }
265
357
  word += input[i + 1] ?? "";
266
358
  meta.escape = true;
267
359
  inWord = true;
@@ -294,6 +386,20 @@ export function tokenizeDetailed(input: string): Tokenized {
294
386
  continue;
295
387
  }
296
388
 
389
+ if (ch === "$" && input[i + 1] === "'") {
390
+ const found = readAnsiC(input, i + 1);
391
+ if (!found) {
392
+ hazards.push("unterminated quote");
393
+ i = input.length;
394
+ continue;
395
+ }
396
+ word += found.text;
397
+ meta.quote = true;
398
+ inWord = true;
399
+ i = found.next;
400
+ continue;
401
+ }
402
+
297
403
  if (ch === "$" && input[i + 1] === "(") {
298
404
  // `$((...))` is arithmetic: a value, not a command.
299
405
  if (input[i + 2] === "(") {
@@ -333,9 +439,30 @@ export function tokenizeDetailed(input: string): Tokenized {
333
439
  continue;
334
440
  }
335
441
 
442
+ if (ch === "$" && input[i + 1] === "{") {
443
+ // `${x:-a)b}` is one word; `)` and `}` inside it are data.
444
+ let depth = 1;
445
+ let j = i + 2;
446
+ while (j < input.length && depth > 0) {
447
+ const inner = input[j] as string;
448
+ if (inner === "\\") {
449
+ j += 2;
450
+ continue;
451
+ }
452
+ if (inner === "{") depth++;
453
+ else if (inner === "}") depth--;
454
+ j++;
455
+ }
456
+ meta.expansion = true;
457
+ word += input.slice(i, j);
458
+ inWord = true;
459
+ i = j;
460
+ continue;
461
+ }
462
+
336
463
  if (ch === "$") {
337
- // `$VAR`, `${VAR}` and `$'...'`: the word's value is decided at runtime.
338
- if (/[A-Za-z_{@*#?$!'-]/.test(input[i + 1] ?? "")) meta.expansion = true;
464
+ // `$VAR` and `$'...'`: the word's value is decided at runtime.
465
+ if (/[A-Za-z_@*#?$!'-]/.test(input[i + 1] ?? "")) meta.expansion = true;
339
466
  word += ch;
340
467
  inWord = true;
341
468
  i++;
@@ -366,7 +493,7 @@ export function tokenizeDetailed(input: string): Tokenized {
366
493
  j++;
367
494
  }
368
495
  }
369
- if (delimiter) heredocs.push(delimiter);
496
+ if (delimiter) heredocs.push({ delimiter });
370
497
  i = j;
371
498
  continue;
372
499
  }
@@ -386,6 +513,7 @@ export function tokenizeDetailed(input: string): Tokenized {
386
513
  const append = input[i + 1] === ">";
387
514
  // `>|` overrides noclobber and is the same write.
388
515
  const clobber = input[i + 1] === "|";
516
+ dropFileDescriptor();
389
517
  flushWord();
390
518
  const redir = readRedirTarget(i + (append || clobber ? 2 : 1));
391
519
  subs.push(...redir.subs);
@@ -395,6 +523,7 @@ export function tokenizeDetailed(input: string): Tokenized {
395
523
  }
396
524
 
397
525
  if (ch === "<") {
526
+ dropFileDescriptor();
398
527
  flushWord();
399
528
  const redir = readRedirTarget(i + 1);
400
529
  subs.push(...redir.subs);
@@ -403,6 +532,12 @@ export function tokenizeDetailed(input: string): Tokenized {
403
532
  continue;
404
533
  }
405
534
 
535
+ if (isGrouping(ch)) {
536
+ endCommand();
537
+ i++;
538
+ continue;
539
+ }
540
+
406
541
  if (isSeparator(ch)) {
407
542
  const pushedTo = commands.length;
408
543
  endCommand();
@@ -413,11 +548,14 @@ export function tokenizeDetailed(input: string): Tokenized {
413
548
  }
414
549
  i++;
415
550
  if (ch === "\n") {
416
- for (const delimiter of heredocs) {
417
- const skipped = skipHeredoc(i, delimiter);
551
+ for (const heredoc of heredocs) {
552
+ const skipped = skipHeredoc(i, heredoc.delimiter);
418
553
  if (!skipped.found) hazards.push("unterminated heredoc");
419
- const owner = commands[commands.length - 1];
420
- if (owner && owner.heredoc === undefined) owner.heredoc = skipped.body;
554
+ const owner = heredoc.owner;
555
+ if (owner) {
556
+ owner.heredocs ??= [];
557
+ owner.heredocs.push(skipped.body);
558
+ }
421
559
  i = skipped.next;
422
560
  }
423
561
  heredocs = [];
package/src/unlayer.ts CHANGED
@@ -18,7 +18,7 @@ import { stripPrefixes } from "./prefixes";
18
18
  const SKIP_WORDS = new Set(["for", "in", "case", "fi", "done", "esac", "}"]);
19
19
 
20
20
  /** Keywords that precede a command; the command follows them. */
21
- const PREFIX_WORDS = new Set(["then", "do", "else", "elif", "if", "while", "until", "!", "{"]);
21
+ const PREFIX_WORDS = new Set(["then", "do", "else", "elif", "if", "while", "until", "!", "{", "coproc"]);
22
22
 
23
23
  /**
24
24
  * The innermost command of one simple command, or undefined when the segment