@jalaxy33/pi-permission 0.4.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/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 { isSyntaxCheck, MAX_NESTING, scriptAfterC, SHELLS } from "./ops";
4
+ import { flagCarriesCode, 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,9 +12,139 @@ function verdict(action: Action, matched: boolean): Verdict {
10
12
  return { action, reasons: [], grants: [], terminate: false, matched };
11
13
  }
12
14
 
13
- /** A session grant covers one rule with the same flags, not every command it matches. */
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, subject = ""): Verdict {
21
+ const result = verdict("ask", true);
22
+ result.reasons = [`gate cannot inspect this command: ${what}`];
23
+ const scope = subject === "" ? "" : `:${scriptHash(subject)}`;
24
+ result.grants = [`unreadable:${what}${scope}`];
25
+ return result;
26
+ }
27
+
28
+ /** A `-c` script that reads a variable runs code this gate never sees. */
29
+ function hasRuntimeExpansion(script: string): boolean {
30
+ return /\$(?!\()/.test(script);
31
+ }
32
+
33
+ /** A program name built from a substitution, escape or glob is not a name. */
34
+ function unreadableProgram(meta: WordMeta | undefined, argv: string[]): Verdict | undefined {
35
+ if (!meta) return undefined;
36
+ if (meta.expansion || meta.escape || meta.glob) {
37
+ return unreadable("program name is not a literal", argv.slice(0, 2).join(" "));
38
+ }
39
+ return undefined;
40
+ }
41
+
42
+ /** Source code the gate can see but not read. */
43
+ function unreadableScript(program: string, why: string, grant?: string): Verdict {
44
+ const result = verdict("ask", true);
45
+ result.reasons = [`${why}. The gate cannot read the ${program} script`];
46
+ if (grant !== undefined) result.grants = [grant];
47
+ return result;
48
+ }
49
+
50
+ /** The script a command runs, when it comes from somewhere other than `-c`. */
51
+ export function decideInput(
52
+ simple: SimpleCommand,
53
+ argv: string[],
54
+ rules: GateRules,
55
+ fallback: Action,
56
+ depth: number,
57
+ options: DecideOptions,
58
+ ): Verdict | undefined {
59
+ const args = parseArgs(argv);
60
+ if (!args) return undefined;
61
+ const shell = SHELLS.has(args.program);
62
+ if (!shell && !isCodeRunner(args.program)) 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
+ }
84
+
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
+ }
94
+ }
95
+
96
+ const operand = scriptOperand(args.program, argv);
97
+ if (operand !== undefined) {
98
+ const text = options.readScript?.(operand);
99
+ if (text === undefined) {
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
+ );
113
+ }
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) {
121
+ return unreadableScript(
122
+ args.program,
123
+ "its script is written inline, in a language the gate does not parse",
124
+ `opaque:${args.program}:heredoc`,
125
+ );
126
+ }
127
+
128
+ if (stdinFed) return unreadableScript(args.program, "its script arrives on stdin, which the command text does not contain");
129
+ return undefined;
130
+ }
131
+
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
+ */
14
137
  function grantKey(rule: CompiledRule, args: Args): string {
15
- 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}`;
16
148
  }
17
149
 
18
150
  /** `-rf` and `-fr` are the same flags; keep only the letters for grant keys. */
@@ -60,6 +192,12 @@ function decideOne(argv: string[], rules: GateRules, fallback: Action): Verdict
60
192
  return result;
61
193
  }
62
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
+
63
201
  function mergeInto(target: Verdict, source: Verdict): void {
64
202
  for (const reason of source.reasons) {
65
203
  if (!target.reasons.includes(reason)) target.reasons.push(reason);
@@ -76,14 +214,43 @@ function mergeInto(target: Verdict, source: Verdict): void {
76
214
  * Strictest verdict across every simple command, including `sh -c` scripts.
77
215
  * `fallback` is `defaultPermission.commands`: what an unmatched program does.
78
216
  */
79
- export function decide(command: string, rules: GateRules, fallback: Action = "allow", depth = 0): Verdict {
217
+ export interface DecideOptions {
218
+ /** Reads a script file named by a command. Undefined when it cannot be read. */
219
+ readScript?: (path: string) => string | undefined;
220
+ }
221
+
222
+ export function decide(
223
+ command: string,
224
+ rules: GateRules,
225
+ fallback: Action = "allow",
226
+ depth = 0,
227
+ options: DecideOptions = {},
228
+ ): Verdict {
80
229
  const merged: Verdict = { action: "allow", reasons: [], grants: [], terminate: false, matched: false };
81
230
 
82
- for (const simple of tokenize(command)) {
83
- mergeInto(merged, decideOne(simple.argv, rules, fallback));
231
+ const split = tokenizeDetailed(command);
232
+ for (const hazard of split.hazards) mergeInto(merged, unreadable(hazard, command));
233
+
234
+ for (const simple of split.commands) {
235
+ const argv = unlayer(simple.argv);
236
+ if (!argv) continue;
237
+ // `FOO=1 "$CMD" x` puts the program one word later than the segment start.
238
+ const wordIndex = programWordIndex(argv);
239
+ const meta = wordIndex === -1 ? undefined : simple.words[simple.argv.length - argv.length + wordIndex];
240
+ mergeInto(merged, unreadableProgram(meta, argv) ?? verdict("allow", false));
241
+ mergeInto(merged, decideOne(argv, rules, fallback));
242
+
243
+ const input = decideInput(simple, argv, rules, fallback, depth, options);
244
+ if (input) mergeInto(merged, input);
84
245
 
85
- const script = scriptAfterC(simple.argv);
86
- if (script && depth < MAX_NESTING) mergeInto(merged, decide(script, rules, fallback, depth + 1));
246
+ const script = scriptAfterC(argv);
247
+ if (!script) continue;
248
+ if (depth >= MAX_NESTING) {
249
+ mergeInto(merged, unreadable("nested script"));
250
+ continue;
251
+ }
252
+ mergeInto(merged, decide(script, rules, fallback, depth + 1, options));
253
+ if (hasRuntimeExpansion(script)) mergeInto(merged, unreadable("script expansion"));
87
254
  }
88
255
 
89
256
  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 =
@@ -66,7 +74,7 @@ function toolTargets(
66
74
  if (!GATED_TOOLS.has(toolName)) return undefined;
67
75
  const command = input.command;
68
76
  if (typeof command !== "string" || command.trim() === "") return undefined;
69
- return { paths: collectTargets(command, cwd), label: command, text: command };
77
+ return { paths: collectTargets(command, cwd, { readScript: (path) => readScript(path, cwd) }), label: command, text: command };
70
78
  }
71
79
 
72
80
  /** A grant covers one rule and one operation: allowing a read leaves writes asking. */
@@ -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
 
package/src/ops.ts CHANGED
@@ -5,7 +5,11 @@ 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";
12
+ import { unlayer } from "./unlayer";
9
13
  import type { PathOp } from "./types";
10
14
 
11
15
  const READ = new Set([
@@ -62,7 +66,6 @@ const DELETE = new Set(["rm", "unlink", "shred", "rmdir"]);
62
66
  const COPY = new Set(["cp", "mv", "rsync", "scp", "dd"]);
63
67
 
64
68
  const EXTENSION = /\.[A-Za-z0-9_]+$/;
65
- const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
66
69
  const MAX_GLOB_MATCHES = 50;
67
70
  export const MAX_NESTING = 3;
68
71
 
@@ -91,11 +94,15 @@ function expandGlob(value: string, cwd: string): string[] {
91
94
  }
92
95
  }
93
96
 
94
- /** `$VAR` operands cannot be resolved: keep the literal basename for matching. */
97
+ /**
98
+ * `$VAR` operands cannot be resolved: keep the literal basename for matching, so
99
+ * `cat "$HOME/.ssh/id_rsa"` still reaches the rule for `id_rsa`.
100
+ */
95
101
  function unresolvedBasename(value: string): string | undefined {
96
- const suffix = basename(value);
102
+ const cut = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
103
+ const suffix = cut === -1 ? value : value.slice(cut + 1);
97
104
  if (!suffix || suffix.startsWith("$")) return undefined;
98
- return EXTENSION.test(suffix) ? suffix : undefined;
105
+ return suffix;
99
106
  }
100
107
 
101
108
  function flagValueOf(token: string): string | undefined {
@@ -208,6 +215,7 @@ function targetsOf(args: Args, simple: SimpleCommand, cwd: string): PathTarget[]
208
215
  /**
209
216
  * Script text of `sh -c "..."`, so nested commands are checked too.
210
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.
211
219
  */
212
220
  export function scriptAfterC(argv: string[]): string | undefined {
213
221
  const args = parseArgs(argv);
@@ -215,7 +223,18 @@ export function scriptAfterC(argv: string[]): string | undefined {
215
223
  const index = argv.findIndex(
216
224
  (token, position) => position > 0 && /^-[A-Za-z0-9]*c[A-Za-z0-9]*$/.test(token),
217
225
  );
218
- 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");
219
238
  }
220
239
 
221
240
  /** A path from a `cd`-relative command is pinned to the directory that command runs in. */
@@ -224,18 +243,36 @@ function pin(target: PathTarget, current: string, cwd: string): PathTarget {
224
243
  return { ...target, path: resolve(current, target.path) };
225
244
  }
226
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
+
227
251
  /** All path targets of a command string, including `cd` tracking and `sh -c`. */
228
- export function collectTargets(command: string, cwd: string, depth = 0): PathTarget[] {
252
+ export function collectTargets(command: string, cwd: string, options: TargetOptions = {}, depth = 0): PathTarget[] {
229
253
  const targets: PathTarget[] = [];
230
254
  let current = cwd;
231
255
 
232
256
  for (const simple of tokenize(command)) {
233
- const args = parseArgs(simple.argv);
257
+ const argv = unlayer(simple.argv);
258
+ if (!argv) continue;
259
+ const args = parseArgs(argv);
234
260
  if (!args) continue;
235
- for (const target of targetsOf(args, simple, current)) targets.push(pin(target, current, cwd));
236
- const script = scriptAfterC(simple.argv);
261
+ const peeled = { ...simple, argv };
262
+ for (const target of targetsOf(args, peeled, current)) targets.push(pin(target, current, cwd));
263
+ const script = scriptAfterC(argv);
237
264
  if (script && depth < MAX_NESTING) {
238
- 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
+ }
239
276
  }
240
277
  current = cwdAfterArgs(args, current);
241
278
  }
package/src/paths.ts CHANGED
@@ -9,10 +9,19 @@ const ALL_OPS: PathOp[] = ["read", "write", "delete"];
9
9
 
10
10
  export function expandTilde(path: string): string {
11
11
  if (path === "~") return homedir();
12
- if (path.startsWith("~/")) return resolve(homedir(), path.slice(2));
12
+ if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(homedir(), path.slice(2));
13
13
  return path;
14
14
  }
15
15
 
16
+ /**
17
+ * Glob matching works on one separator. A pattern written with `/` has to match
18
+ * the `\` that `node:path` produces on Windows, so both sides go through here
19
+ * before they meet a RegExp.
20
+ */
21
+ export function normalizeSeparators(value: string): string {
22
+ return value.replace(/\\/g, "/");
23
+ }
24
+
16
25
  export function globToRegExp(glob: string): RegExp {
17
26
  let out = "";
18
27
  for (let i = 0; i < glob.length; i++) {
@@ -35,16 +44,22 @@ export function globToRegExp(glob: string): RegExp {
35
44
  return new RegExp(`^${out}$`);
36
45
  }
37
46
 
47
+ /** Windows drive (`C:/x`), UNC (`//server/share`) or MSYS (`/c/x`) root. */
48
+ function hasWindowsRoot(pattern: string): boolean {
49
+ return /^[A-Za-z]:\//.test(pattern) || pattern.startsWith("//");
50
+ }
51
+
38
52
  function kindOf(pattern: string): "base" | "abs" | "rel" {
39
53
  // `**` is the project tree, not "any basename": a whitelist needs one pattern.
40
54
  if (pattern === "**") return "rel";
41
55
  if (!pattern.includes("/")) return "base";
42
- if (pattern.startsWith("~") || isAbsolute(pattern)) return "abs";
56
+ if (pattern.startsWith("~") || isAbsolute(pattern) || hasWindowsRoot(pattern)) return "abs";
43
57
  return "rel";
44
58
  }
45
59
 
46
60
  function compilePattern(pattern: string): CompiledPathRule["compiled"][number] {
47
- return { value: pattern, kind: kindOf(pattern), re: globToRegExp(expandTilde(pattern)) };
61
+ const normalized = normalizeSeparators(expandTilde(pattern));
62
+ return { value: pattern, kind: kindOf(normalized), re: globToRegExp(normalized) };
48
63
  }
49
64
 
50
65
  export function compilePathRules(rules: PathRule[]): { rules: CompiledPathRule[]; warnings: string[] } {
@@ -139,10 +154,13 @@ function patternMatches(
139
154
  const inside = (value: string) => value !== ".." && !value.startsWith(`..${sep}`);
140
155
  if (!inside(candidate.rel)) return false;
141
156
  if (candidate.relReal !== undefined && !inside(candidate.relReal)) return false;
142
- return pattern.re.test(candidate.rel) || (candidate.relReal !== undefined && pattern.re.test(candidate.relReal));
157
+ const rel = normalizeSeparators(candidate.rel);
158
+ const relReal = candidate.relReal === undefined ? undefined : normalizeSeparators(candidate.relReal);
159
+ return pattern.re.test(rel) || (relReal !== undefined && pattern.re.test(relReal));
143
160
  }
144
- const paths = pattern.kind === "base" ? [candidate.base, candidate.baseReal] : [candidate.abs, candidate.real];
145
- return paths.some((value) => typeof value === "string" && pattern.re.test(value));
161
+ const raw = pattern.kind === "base" ? [candidate.base, candidate.baseReal] : [candidate.abs, candidate.real];
162
+ const paths = raw.filter((value): value is string => typeof value === "string").map(normalizeSeparators);
163
+ return paths.some((value) => pattern.re.test(value));
146
164
  }
147
165
 
148
166
  export interface PathHit {
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Wrapper programs whose real command is visible in their own argv.
3
+ *
4
+ * Unwrapping has to know each wrapper's option table, so this stays a short
5
+ * list of programs with a closed one. A wrapper that does not match its
6
+ * expected shape is returned untouched, which keeps it visible to the rules
7
+ * that ask about it.
8
+ */
9
+
10
+ import { normalizeProgram } from "./program";
11
+
12
+ interface PrefixSpec {
13
+ /** Flags that take no value. */
14
+ flags?: string[];
15
+ /** Flags that consume the next word. */
16
+ valueFlags?: string[];
17
+ /** Words to skip before the command itself (`timeout` takes a duration). */
18
+ positional?: number;
19
+ /** Only leading `VAR=VAL` words are accepted, and no flags at all (`env`). */
20
+ assignmentsOnly?: boolean;
21
+ /** Accept the obsolete `nice -5` form. */
22
+ numericFlag?: boolean;
23
+ }
24
+
25
+ const SPECS: Record<string, PrefixSpec> = {
26
+ time: { flags: ["-p"] },
27
+ nice: { valueFlags: ["-n", "--adjustment"], numericFlag: true },
28
+ nohup: {},
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"] },
36
+ command: { flags: ["-p"] },
37
+ env: { assignmentsOnly: true },
38
+ };
39
+
40
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
41
+ const NUMERIC_FLAG = /^-\d+$/;
42
+ const MAX_DEPTH = 2;
43
+
44
+ function stripOne(tokens: string[], spec: PrefixSpec): string[] | undefined {
45
+ let positional = spec.positional ?? 0;
46
+
47
+ for (let i = 0; i < tokens.length; i += 1) {
48
+ const token = tokens[i] as string;
49
+ if (token === "--") continue;
50
+
51
+ if (token.startsWith("-") && token !== "-") {
52
+ if (spec.assignmentsOnly === true) return undefined;
53
+ const valueFlag = spec.valueFlags?.find((flag) => token === flag || token.startsWith(flag));
54
+ if (valueFlag !== undefined) {
55
+ // `-o0` carries its value; `-o 0` takes the next word.
56
+ if (token === valueFlag) {
57
+ if (i + 1 >= tokens.length) return undefined;
58
+ i += 1;
59
+ }
60
+ continue;
61
+ }
62
+ if (spec.flags?.includes(token) === true) continue;
63
+ if (spec.numericFlag === true && NUMERIC_FLAG.test(token)) continue;
64
+ return undefined;
65
+ }
66
+
67
+ if (spec.assignmentsOnly === true && ASSIGNMENT.test(token)) continue;
68
+ if (positional > 0) {
69
+ positional -= 1;
70
+ continue;
71
+ }
72
+ return tokens.slice(i);
73
+ }
74
+
75
+ return undefined;
76
+ }
77
+
78
+ /** Peels recognized wrapper programs; anything unrecognized is returned as is. */
79
+ export function stripPrefixes(argv: string[], depth = 0): string[] {
80
+ if (depth >= MAX_DEPTH || argv.length === 0) return argv;
81
+ const first = argv[0] as string;
82
+ const spec = SPECS[normalizeProgram(first)];
83
+ if (!spec) return argv;
84
+ const inner = stripOne(argv.slice(1), spec);
85
+ if (!inner || inner.length === 0) return argv;
86
+ return stripPrefixes(inner, depth + 1);
87
+ }
package/src/program.ts ADDED
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Program names as they appear on the command line, reduced to what a rule
3
+ * matches on.
4
+ *
5
+ * On Windows a shell can name the same program in several ways: `bash.exe`,
6
+ * `C:\Program Files\Git\bin\bash.exe`, `/c/Windows/System32/cmd.exe`, a UNC
7
+ * path. A rule written for `bash` has to match all of them, or a wrapper with
8
+ * a different spelling slips past every rule. Comparison stays case-sensitive
9
+ * on POSIX, where `RM` and `rm` are different programs.
10
+ */
11
+
12
+ const WINDOWS_SUFFIX = /\.(exe|com|cmd|bat|ps1)$/i;
13
+
14
+ export function normalizeProgram(token: string): string {
15
+ const parts = token.split(/[\\/]/);
16
+ const base = parts[parts.length - 1] ?? token;
17
+ const name = base.replace(WINDOWS_SUFFIX, "");
18
+ return process.platform === "win32" ? name.toLowerCase() : name;
19
+ }
package/src/rulesets.ts CHANGED
@@ -27,27 +27,42 @@ export function resolveRulePath(entry: string, baseDir: string): string {
27
27
  return isAbsolute(expanded) ? expanded : resolve(baseDir, expanded);
28
28
  }
29
29
 
30
+ /** A file that exists but cannot be used. A missing file is not one of these. */
31
+ export interface ReadFailure {
32
+ path: string;
33
+ reason: string;
34
+ }
35
+
30
36
  export function readJson(
31
37
  path: string,
32
38
  warnings: string[],
33
39
  kind: "config" | "ruleset" = "config",
40
+ failures?: ReadFailure[],
34
41
  ): ConfigFile | undefined {
35
42
  let raw: string;
36
43
  try {
37
44
  raw = readFileSync(path, "utf8");
38
- } 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 });
39
51
  return undefined;
40
52
  }
41
53
  try {
42
54
  const parsed: unknown = JSON.parse(raw);
43
55
  if (!isObject(parsed)) {
44
56
  warnings.push(`${path}: expected a JSON object`);
57
+ failures?.push({ path, reason: "expected a JSON object" });
45
58
  return undefined;
46
59
  }
47
60
  checkFields(parsed, path, warnings, kind);
48
61
  return parsed as ConfigFile;
49
62
  } catch (error) {
50
- warnings.push(`${path}: invalid JSON (${(error as Error).message})`);
63
+ const reason = `invalid JSON (${(error as Error).message})`;
64
+ warnings.push(`${path}: ${reason}`);
65
+ failures?.push({ path, reason });
51
66
  return undefined;
52
67
  }
53
68
  }