@jalaxy33/pi-permission 0.0.0-stage → 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/src/ops.ts ADDED
@@ -0,0 +1,252 @@
1
+ /** Maps a parsed bash command to the paths it touches and the operation on each. */
2
+
3
+ import { existsSync } from "node:fs";
4
+ import * as fs from "node:fs";
5
+ import { basename, isAbsolute, resolve } from "node:path";
6
+ import { parseArgs, type Args } from "./argv";
7
+ import { expandTilde } from "./paths";
8
+ import { type SimpleCommand, tokenize } from "./tokenize";
9
+ import { unlayer } from "./unlayer";
10
+ import type { PathOp } from "./types";
11
+
12
+ const READ = new Set([
13
+ "cat",
14
+ "bat",
15
+ "head",
16
+ "tail",
17
+ "less",
18
+ "more",
19
+ "grep",
20
+ "egrep",
21
+ "rg",
22
+ "ag",
23
+ "awk",
24
+ "strings",
25
+ "xxd",
26
+ "od",
27
+ "hexdump",
28
+ "file",
29
+ "wc",
30
+ "diff",
31
+ "cmp",
32
+ "md5sum",
33
+ "sha1sum",
34
+ "sha256sum",
35
+ "sha512sum",
36
+ "openssl",
37
+ "gpg",
38
+ "jq",
39
+ "yq",
40
+ "column",
41
+ "sort",
42
+ "uniq",
43
+ "cut",
44
+ "envsubst",
45
+ ]);
46
+
47
+ const WRITE = new Set([
48
+ "tee",
49
+ "truncate",
50
+ "touch",
51
+ "install",
52
+ "ln",
53
+ "chmod",
54
+ "chown",
55
+ "chgrp",
56
+ "setfacl",
57
+ "patch",
58
+ ]);
59
+
60
+ const DELETE = new Set(["rm", "unlink", "shred", "rmdir"]);
61
+
62
+ /** First operand is the source (read), the rest are written. */
63
+ const COPY = new Set(["cp", "mv", "rsync", "scp", "dd"]);
64
+
65
+ const EXTENSION = /\.[A-Za-z0-9_]+$/;
66
+ export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
67
+ const MAX_GLOB_MATCHES = 50;
68
+ export const MAX_NESTING = 3;
69
+
70
+ /** Conservative heuristic: anything that looks like a filesystem path. */
71
+ export function looksLikePath(value: string, cwd: string): boolean {
72
+ if (!value || value.startsWith("-")) return false;
73
+ if (value.includes("$") || value.includes("*") || value.includes("?")) return false;
74
+ if (value.includes("/") || value.startsWith(".") || value.startsWith("~")) return true;
75
+ if (EXTENSION.test(value)) return true;
76
+ const abs = isAbsolute(value) ? value : resolve(cwd, expandTilde(value));
77
+ return existsSync(abs);
78
+ }
79
+
80
+ function hasGlobChars(value: string): boolean {
81
+ return value.includes("*") || value.includes("?") || value.includes("[");
82
+ }
83
+
84
+ /** Expands a shell glob so `cat .env*` cannot slip past the rules. */
85
+ function expandGlob(value: string, cwd: string): string[] {
86
+ const fn = (fs as { globSync?: (pattern: string, options?: { cwd?: string }) => string[] }).globSync;
87
+ if (typeof fn !== "function") return [];
88
+ try {
89
+ return fn(expandTilde(value), { cwd }).slice(0, MAX_GLOB_MATCHES);
90
+ } catch {
91
+ return [];
92
+ }
93
+ }
94
+
95
+ /**
96
+ * `$VAR` operands cannot be resolved: keep the literal basename for matching, so
97
+ * `cat "$HOME/.ssh/id_rsa"` still reaches the rule for `id_rsa`.
98
+ */
99
+ function unresolvedBasename(value: string): string | undefined {
100
+ const cut = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
101
+ const suffix = cut === -1 ? value : value.slice(cut + 1);
102
+ if (!suffix || suffix.startsWith("$")) return undefined;
103
+ return suffix;
104
+ }
105
+
106
+ function flagValueOf(token: string): string | undefined {
107
+ const eq = token.indexOf("=");
108
+ return token.startsWith("-") && eq > 0 ? token.slice(eq + 1) : undefined;
109
+ }
110
+
111
+ function cwdAfterArgs(args: Args, cwd: string): string {
112
+ if (args.program !== "cd" && args.program !== "pushd") return cwd;
113
+ const target = args.positional[0];
114
+ if (!target || target === "-") return cwd;
115
+ const expanded = expandTilde(target);
116
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
117
+ }
118
+
119
+ /** cwd for the next command in the chain (`cd dir`, `pushd dir`). */
120
+ export function cwdAfter(simple: SimpleCommand, cwd: string): string {
121
+ const args = parseArgs(simple.argv);
122
+ return args ? cwdAfterArgs(args, cwd) : cwd;
123
+ }
124
+
125
+ export interface PathTarget {
126
+ path: string;
127
+ op: PathOp;
128
+ /** Set when only the literal basename is known (e.g. `${HOME}/.env`). */
129
+ basenameOnly?: boolean;
130
+ }
131
+
132
+ export function extractTargets(simple: SimpleCommand, cwd: string): PathTarget[] {
133
+ const args = parseArgs(simple.argv);
134
+ return args ? targetsOf(args, simple, cwd) : [];
135
+ }
136
+
137
+ function targetsOf(args: Args, simple: SimpleCommand, cwd: string): PathTarget[] {
138
+ const targets: PathTarget[] = [];
139
+ const add = (value: string | undefined, op: PathOp) => {
140
+ if (!value) return;
141
+
142
+ if (hasGlobChars(value)) {
143
+ for (const match of expandGlob(value, cwd)) targets.push({ path: match, op });
144
+ return;
145
+ }
146
+
147
+ if (value.includes("$")) {
148
+ const basename = unresolvedBasename(value);
149
+ if (basename) targets.push({ path: basename, op, basenameOnly: true });
150
+ return;
151
+ }
152
+
153
+ if (!looksLikePath(value, cwd)) return;
154
+ targets.push({ path: value, op });
155
+ };
156
+
157
+ // Redirections: `> file` writes, `>> file` writes, `< file` reads.
158
+ for (const redirect of simple.redirects) {
159
+ add(redirect.target, redirect.op === "<" ? "read" : "write");
160
+ }
161
+
162
+ if (args.program === "cd" || args.program === "pushd") return targets;
163
+
164
+ // The `-c` script is walked by collectTargets; its text is not an operand.
165
+ if (SHELLS.has(args.program)) {
166
+ const script = scriptAfterC(simple.argv);
167
+ for (const operand of args.positional) if (operand !== script) add(operand, "read");
168
+ return targets;
169
+ }
170
+
171
+ if (DELETE.has(args.program)) {
172
+ for (const operand of args.positional) add(operand, "delete");
173
+ return targets;
174
+ }
175
+
176
+ if (COPY.has(args.program)) {
177
+ if (args.program === "dd") {
178
+ for (const operand of args.positional) add(operand, "write");
179
+ return targets;
180
+ }
181
+ const operands = args.positional;
182
+ // A move deletes its source; a copy only reads it.
183
+ const sourceOp: PathOp = args.program === "mv" ? "delete" : "read";
184
+ operands.forEach((operand, index) => {
185
+ add(operand, index === operands.length - 1 ? "write" : sourceOp);
186
+ });
187
+ return targets;
188
+ }
189
+
190
+ if (args.program === "sed") {
191
+ const inPlace = args.flags.has("-i") || args.flags.has("--in-place");
192
+ for (const operand of args.positional.slice(1)) add(operand, inPlace ? "write" : "read");
193
+ return targets;
194
+ }
195
+
196
+ if (WRITE.has(args.program)) {
197
+ for (const operand of args.positional) add(operand, "write");
198
+ return targets;
199
+ }
200
+
201
+ if (READ.has(args.program)) {
202
+ for (const operand of args.positional) add(operand, "read");
203
+ return targets;
204
+ }
205
+
206
+ // Unknown program: treat path-looking operands and `--flag=value` paths as reads.
207
+ for (const operand of args.positional) add(operand, "read");
208
+ for (const token of simple.argv) add(flagValueOf(token), "read");
209
+
210
+ return targets;
211
+ }
212
+
213
+ /**
214
+ * Script text of `sh -c "..."`, so nested commands are checked too.
215
+ * Reads the token after `-c`, not the first positional: `bash -o pipefail -c '...'`.
216
+ */
217
+ export function scriptAfterC(argv: string[]): string | undefined {
218
+ const args = parseArgs(argv);
219
+ if (!args || !SHELLS.has(args.program)) return undefined;
220
+ const index = argv.findIndex(
221
+ (token, position) => position > 0 && /^-[A-Za-z0-9]*c[A-Za-z0-9]*$/.test(token),
222
+ );
223
+ return index > 0 ? argv[index + 1] : undefined;
224
+ }
225
+
226
+ /** A path from a `cd`-relative command is pinned to the directory that command runs in. */
227
+ function pin(target: PathTarget, current: string, cwd: string): PathTarget {
228
+ if (current === cwd || target.basenameOnly || isAbsolute(target.path)) return target;
229
+ return { ...target, path: resolve(current, target.path) };
230
+ }
231
+
232
+ /** All path targets of a command string, including `cd` tracking and `sh -c`. */
233
+ export function collectTargets(command: string, cwd: string, depth = 0): PathTarget[] {
234
+ const targets: PathTarget[] = [];
235
+ let current = cwd;
236
+
237
+ for (const simple of tokenize(command)) {
238
+ const argv = unlayer(simple.argv);
239
+ if (!argv) continue;
240
+ const args = parseArgs(argv);
241
+ if (!args) continue;
242
+ const peeled = { ...simple, argv };
243
+ for (const target of targetsOf(args, peeled, current)) targets.push(pin(target, current, cwd));
244
+ const script = scriptAfterC(argv);
245
+ if (script && depth < MAX_NESTING) {
246
+ for (const target of collectTargets(script, current, depth + 1)) targets.push(pin(target, current, cwd));
247
+ }
248
+ current = cwdAfterArgs(args, current);
249
+ }
250
+
251
+ return targets;
252
+ }
package/src/outside.ts ADDED
@@ -0,0 +1,87 @@
1
+ /** Gate for paths outside the session working directory. */
2
+
3
+ import { realpathSync } from "node:fs";
4
+ import { isAbsolute, sep } from "node:path";
5
+ import { expandTilde, globToRegExp, resolveCandidate } from "./paths";
6
+ import type { OutsideCwdConfig, PathOp } from "./types";
7
+
8
+ export type OutsideMode = "allow" | "ask" | "block";
9
+
10
+ interface CompiledPattern {
11
+ kind: "abs" | "rel";
12
+ re: RegExp;
13
+ }
14
+
15
+ export interface OutsideRule {
16
+ mode: OutsideMode;
17
+ allow: CompiledPattern[];
18
+ }
19
+
20
+ export const DEFAULT_ALLOW_PATHS = [
21
+ "/tmp/**",
22
+ "/dev/**",
23
+ "~/.pi/agent/**",
24
+ "~/.cache/**",
25
+ "~/.bun/**",
26
+ "~/.npm/**",
27
+ "~/.local/share/**",
28
+ ];
29
+
30
+ export function compileOutside(config?: OutsideCwdConfig): OutsideRule {
31
+ const patterns = [...DEFAULT_ALLOW_PATHS, ...(config?.allowPaths ?? [])];
32
+ return {
33
+ mode: config?.mode ?? "ask",
34
+ allow: patterns.map((pattern) => ({
35
+ kind: pattern.startsWith("~") || isAbsolute(pattern) ? "abs" : "rel",
36
+ re: globToRegExp(expandTilde(pattern)),
37
+ })),
38
+ };
39
+ }
40
+
41
+ function insideCwd(abs: string, cwd: string): boolean {
42
+ return abs === cwd || abs.startsWith(cwd.endsWith(sep) ? cwd : `${cwd}${sep}`);
43
+ }
44
+
45
+ /** The workspace as the filesystem sees it, so a symlinked cwd is not "outside". */
46
+ function realCwdOf(cwd: string): string | undefined {
47
+ try {
48
+ return realpathSync(cwd);
49
+ } catch {
50
+ return undefined;
51
+ }
52
+ }
53
+
54
+ export interface OutsideHit {
55
+ path: string;
56
+ mode: OutsideMode;
57
+ }
58
+
59
+ /**
60
+ * Returns a hit when the path is outside the workspace and not explicitly allowed.
61
+ * Reads are not gated here; path rules cover files that must never be read.
62
+ */
63
+ export function checkOutside(
64
+ rule: OutsideRule,
65
+ rawPath: string,
66
+ cwd: string,
67
+ op: PathOp,
68
+ ): OutsideHit | undefined {
69
+ if (rule.mode === "allow" || op === "read") return undefined;
70
+
71
+ const candidate = resolveCandidate(rawPath, cwd);
72
+ const realCwd = realCwdOf(cwd);
73
+ const inside = (path: string | undefined) =>
74
+ typeof path === "string" &&
75
+ (insideCwd(path, cwd) || (realCwd !== undefined && insideCwd(path, realCwd)));
76
+ // Where the write lands is the real path; a symlink to outside is outside.
77
+ const outside = !inside(candidate.real ?? candidate.abs);
78
+ if (!outside) return undefined;
79
+
80
+ // Match the allow list against where the write lands, so a symlink out of /tmp stays gated.
81
+ const allowed = rule.allow.some((pattern) => {
82
+ const target = pattern.kind === "abs" ? candidate.real ?? candidate.abs : candidate.relReal ?? candidate.rel;
83
+ return pattern.re.test(target);
84
+ });
85
+
86
+ return allowed ? undefined : { path: candidate.abs, mode: rule.mode };
87
+ }
package/src/paths.ts ADDED
@@ -0,0 +1,212 @@
1
+ /** File path rules: glob matching against resolved absolute paths. */
2
+
3
+ import { existsSync, lstatSync, readlinkSync, realpathSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from "node:path";
6
+ import type { CompiledPathRule, PathAction, PathOp, PathRule } from "./types";
7
+
8
+ const ALL_OPS: PathOp[] = ["read", "write", "delete"];
9
+
10
+ export function expandTilde(path: string): string {
11
+ if (path === "~") return homedir();
12
+ if (path.startsWith("~/") || path.startsWith("~\\")) return resolve(homedir(), path.slice(2));
13
+ return path;
14
+ }
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
+
25
+ export function globToRegExp(glob: string): RegExp {
26
+ let out = "";
27
+ for (let i = 0; i < glob.length; i++) {
28
+ const ch = glob[i] as string;
29
+ if (ch === "*") {
30
+ if (glob[i + 1] === "*") {
31
+ out += ".*";
32
+ i += 1;
33
+ } else {
34
+ out += "[^/]*";
35
+ }
36
+ continue;
37
+ }
38
+ if (ch === "?") {
39
+ out += "[^/]";
40
+ continue;
41
+ }
42
+ out += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
43
+ }
44
+ return new RegExp(`^${out}$`);
45
+ }
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
+
52
+ function kindOf(pattern: string): "base" | "abs" | "rel" {
53
+ // `**` is the project tree, not "any basename": a whitelist needs one pattern.
54
+ if (pattern === "**") return "rel";
55
+ if (!pattern.includes("/")) return "base";
56
+ if (pattern.startsWith("~") || isAbsolute(pattern) || hasWindowsRoot(pattern)) return "abs";
57
+ return "rel";
58
+ }
59
+
60
+ function compilePattern(pattern: string): CompiledPathRule["compiled"][number] {
61
+ const normalized = normalizeSeparators(expandTilde(pattern));
62
+ return { value: pattern, kind: kindOf(normalized), re: globToRegExp(normalized) };
63
+ }
64
+
65
+ export function compilePathRules(rules: PathRule[]): { rules: CompiledPathRule[]; warnings: string[] } {
66
+ const warnings: string[] = [];
67
+ const compiled: CompiledPathRule[] = [];
68
+
69
+ for (const rule of rules) {
70
+ if (!rule || typeof rule.id !== "string" || !rule.id.trim()) {
71
+ warnings.push(`ignore path rule without id: ${JSON.stringify(rule)}`);
72
+ continue;
73
+ }
74
+ if (!Array.isArray(rule.patterns) || rule.patterns.length === 0) {
75
+ warnings.push(`path rule ${rule.id}: no patterns, ignored`);
76
+ continue;
77
+ }
78
+ compiled.push({
79
+ ...rule,
80
+ compiled: rule.patterns.map(compilePattern),
81
+ compiledExcept: (rule.except ?? []).map(compilePattern),
82
+ });
83
+ }
84
+
85
+ return { rules: compiled, warnings };
86
+ }
87
+
88
+ interface Candidate {
89
+ abs: string;
90
+ real?: string;
91
+ rel: string;
92
+ relReal?: string;
93
+ base: string;
94
+ baseReal?: string;
95
+ exists: boolean;
96
+ }
97
+
98
+ /**
99
+ * Real path of a target that may not exist yet: symlinked ancestors are resolved,
100
+ * and so is a symlink whose own target is missing, since a write follows it there.
101
+ * The missing tail is appended unchanged.
102
+ */
103
+ function realPathOf(abs: string, seen = new Set<string>()): string | undefined {
104
+ let current = abs;
105
+ const tail: string[] = [];
106
+ for (;;) {
107
+ try {
108
+ const real = realpathSync(current);
109
+ return tail.length > 0 ? join(real, ...tail.reverse()) : real;
110
+ } catch {
111
+ if (!seen.has(current) && seen.size < 16) {
112
+ try {
113
+ if (lstatSync(current).isSymbolicLink()) {
114
+ seen.add(current);
115
+ const target = realPathOf(resolve(dirname(current), readlinkSync(current)), seen);
116
+ if (target) return tail.length > 0 ? join(target, ...tail.reverse()) : target;
117
+ }
118
+ } catch {
119
+ // Unreadable link: fall through to the parent.
120
+ }
121
+ }
122
+ const parent = dirname(current);
123
+ if (parent === current) return undefined;
124
+ tail.push(basename(current));
125
+ current = parent;
126
+ }
127
+ }
128
+ }
129
+
130
+ export function resolveCandidate(rawPath: string, cwd: string): Candidate {
131
+ const expanded = expandTilde(rawPath);
132
+ const abs = normalize(isAbsolute(expanded) ? expanded : resolve(cwd, expanded));
133
+ const exists = existsSync(abs);
134
+ const real = realPathOf(abs);
135
+ return {
136
+ abs,
137
+ real,
138
+ rel: relative(cwd, abs),
139
+ relReal: real ? relative(cwd, real) : undefined,
140
+ base: basename(abs),
141
+ baseReal: real ? basename(real) : undefined,
142
+ exists,
143
+ };
144
+ }
145
+
146
+ function patternMatches(
147
+ pattern: { value: string; kind: "base" | "abs" | "rel"; re: RegExp },
148
+ candidate: Candidate,
149
+ ): boolean {
150
+ if (pattern.kind === "rel") {
151
+ // A relative pattern describes paths under the project, never `../outside`.
152
+ // Both the written path and the real path must stay inside, so a symlink in
153
+ // the workspace cannot make an allow rule cover an outside file.
154
+ const inside = (value: string) => value !== ".." && !value.startsWith(`..${sep}`);
155
+ if (!inside(candidate.rel)) return false;
156
+ if (candidate.relReal !== undefined && !inside(candidate.relReal)) return false;
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));
160
+ }
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));
164
+ }
165
+
166
+ export interface PathHit {
167
+ rule: string;
168
+ reason: string;
169
+ path: string;
170
+ action: PathAction;
171
+ }
172
+
173
+ /** All matching rules for the operation, in rule order. */
174
+ export function matchPath(
175
+ rules: CompiledPathRule[],
176
+ rawPath: string,
177
+ cwd: string,
178
+ op: PathOp,
179
+ options: { basenameOnly?: boolean } = {},
180
+ ): PathHit[] {
181
+ const candidate = resolveCandidate(rawPath, cwd);
182
+ const testable = (pattern: CompiledPathRule["compiled"][number]) =>
183
+ !options.basenameOnly || pattern.kind === "base";
184
+
185
+ const hits: PathHit[] = [];
186
+ for (const rule of rules) {
187
+ const ops = rule.ops ?? ALL_OPS;
188
+ if (!ops.includes(op)) continue;
189
+ if (rule.onlyIfExists && !candidate.exists && !options.basenameOnly) continue;
190
+ if (rule.compiledExcept.some((pattern) => testable(pattern) && patternMatches(pattern, candidate))) continue;
191
+ if (!rule.compiled.some((pattern) => testable(pattern) && patternMatches(pattern, candidate))) continue;
192
+ hits.push({
193
+ rule: rule.id,
194
+ path: candidate.abs,
195
+ action: rule.action ?? "deny",
196
+ reason: rule.message ?? `pi-permission: ${rule.id} protects ${candidate.abs}`,
197
+ });
198
+ }
199
+
200
+ return hits;
201
+ }
202
+
203
+ /** First matching rule, for callers that only need one. */
204
+ export function checkPath(
205
+ rules: CompiledPathRule[],
206
+ rawPath: string,
207
+ cwd: string,
208
+ op: PathOp,
209
+ options: { basenameOnly?: boolean } = {},
210
+ ): PathHit | undefined {
211
+ return matchPath(rules, rawPath, cwd, op, options)[0];
212
+ }
@@ -0,0 +1,83 @@
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"], numericFlag: true },
28
+ nohup: {},
29
+ setsid: { flags: ["-f", "-c", "-w"] },
30
+ timeout: { valueFlags: ["-k", "-s"], positional: 1 },
31
+ stdbuf: { valueFlags: ["-i", "-o", "-e"] },
32
+ command: { flags: ["-p"] },
33
+ env: { assignmentsOnly: true },
34
+ };
35
+
36
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
37
+ const NUMERIC_FLAG = /^-\d+$/;
38
+ const MAX_DEPTH = 2;
39
+
40
+ function stripOne(tokens: string[], spec: PrefixSpec): string[] | undefined {
41
+ let positional = spec.positional ?? 0;
42
+
43
+ for (let i = 0; i < tokens.length; i += 1) {
44
+ const token = tokens[i] as string;
45
+ if (token === "--") continue;
46
+
47
+ if (token.startsWith("-") && token !== "-") {
48
+ if (spec.assignmentsOnly === true) return undefined;
49
+ const valueFlag = spec.valueFlags?.find((flag) => token === flag || token.startsWith(flag));
50
+ if (valueFlag !== undefined) {
51
+ // `-o0` carries its value; `-o 0` takes the next word.
52
+ if (token === valueFlag) {
53
+ if (i + 1 >= tokens.length) return undefined;
54
+ i += 1;
55
+ }
56
+ continue;
57
+ }
58
+ if (spec.flags?.includes(token) === true) continue;
59
+ if (spec.numericFlag === true && NUMERIC_FLAG.test(token)) continue;
60
+ return undefined;
61
+ }
62
+
63
+ if (spec.assignmentsOnly === true && ASSIGNMENT.test(token)) continue;
64
+ if (positional > 0) {
65
+ positional -= 1;
66
+ continue;
67
+ }
68
+ return tokens.slice(i);
69
+ }
70
+
71
+ return undefined;
72
+ }
73
+
74
+ /** Peels recognized wrapper programs; anything unrecognized is returned as is. */
75
+ export function stripPrefixes(argv: string[], depth = 0): string[] {
76
+ if (depth >= MAX_DEPTH || argv.length === 0) return argv;
77
+ const first = argv[0] as string;
78
+ const spec = SPECS[normalizeProgram(first)];
79
+ if (!spec) return argv;
80
+ const inner = stripOne(argv.slice(1), spec);
81
+ if (!inner || inner.length === 0) return argv;
82
+ return stripPrefixes(inner, depth + 1);
83
+ }
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
+ }