@jalaxy33/pi-permission 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/ops.ts CHANGED
@@ -6,6 +6,7 @@ import { basename, isAbsolute, resolve } from "node:path";
6
6
  import { parseArgs, type Args } from "./argv";
7
7
  import { expandTilde } from "./paths";
8
8
  import { type SimpleCommand, tokenize } from "./tokenize";
9
+ import { unlayer } from "./unlayer";
9
10
  import type { PathOp } from "./types";
10
11
 
11
12
  const READ = new Set([
@@ -62,7 +63,7 @@ const DELETE = new Set(["rm", "unlink", "shred", "rmdir"]);
62
63
  const COPY = new Set(["cp", "mv", "rsync", "scp", "dd"]);
63
64
 
64
65
  const EXTENSION = /\.[A-Za-z0-9_]+$/;
65
- const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
66
+ export const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
66
67
  const MAX_GLOB_MATCHES = 50;
67
68
  export const MAX_NESTING = 3;
68
69
 
@@ -91,11 +92,15 @@ function expandGlob(value: string, cwd: string): string[] {
91
92
  }
92
93
  }
93
94
 
94
- /** `$VAR` operands cannot be resolved: keep the literal basename for matching. */
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
+ */
95
99
  function unresolvedBasename(value: string): string | undefined {
96
- const suffix = basename(value);
100
+ const cut = Math.max(value.lastIndexOf("/"), value.lastIndexOf("\\"));
101
+ const suffix = cut === -1 ? value : value.slice(cut + 1);
97
102
  if (!suffix || suffix.startsWith("$")) return undefined;
98
- return EXTENSION.test(suffix) ? suffix : undefined;
103
+ return suffix;
99
104
  }
100
105
 
101
106
  function flagValueOf(token: string): string | undefined {
@@ -230,10 +235,13 @@ export function collectTargets(command: string, cwd: string, depth = 0): PathTar
230
235
  let current = cwd;
231
236
 
232
237
  for (const simple of tokenize(command)) {
233
- const args = parseArgs(simple.argv);
238
+ const argv = unlayer(simple.argv);
239
+ if (!argv) continue;
240
+ const args = parseArgs(argv);
234
241
  if (!args) continue;
235
- for (const target of targetsOf(args, simple, current)) targets.push(pin(target, current, cwd));
236
- const script = scriptAfterC(simple.argv);
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);
237
245
  if (script && depth < MAX_NESTING) {
238
246
  for (const target of collectTargets(script, current, depth + 1)) targets.push(pin(target, current, cwd));
239
247
  }
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,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
+ }
package/src/rulesets.ts CHANGED
@@ -27,10 +27,17 @@ 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 {
@@ -42,12 +49,15 @@ export function readJson(
42
49
  const parsed: unknown = JSON.parse(raw);
43
50
  if (!isObject(parsed)) {
44
51
  warnings.push(`${path}: expected a JSON object`);
52
+ failures?.push({ path, reason: "expected a JSON object" });
45
53
  return undefined;
46
54
  }
47
55
  checkFields(parsed, path, warnings, kind);
48
56
  return parsed as ConfigFile;
49
57
  } catch (error) {
50
- warnings.push(`${path}: invalid JSON (${(error as Error).message})`);
58
+ const reason = `invalid JSON (${(error as Error).message})`;
59
+ warnings.push(`${path}: ${reason}`);
60
+ failures?.push({ path, reason });
51
61
  return undefined;
52
62
  }
53
63
  }
package/src/scripts.ts ADDED
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Programs that run source code, and how to name that code in a session grant.
3
+ *
4
+ * A shell script can be read and judged like the command line it is. Every
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.
7
+ */
8
+
9
+ import { createHash } from "node:crypto";
10
+ import { normalizeProgram } from "./program";
11
+
12
+ /** Programs whose first non-flag argument is source code. */
13
+ const INTERPRETERS =
14
+ /^(python[0-9.]*|pypy[0-9.]*|node|nodejs|bun|deno|perl|ruby|php|lua|rscript|osascript|pwsh|powershell|groovy|tclsh|wish)$/;
15
+
16
+ export function isCodeRunner(program: string): boolean {
17
+ return INTERPRETERS.test(normalizeProgram(program).toLowerCase());
18
+ }
19
+
20
+ const SCRIPT_NAME = /\.(sh|bash|zsh|ksh|dash|fish|py|pyw|js|mjs|cjs|ts|pl|rb|php|lua|ps1|tcl)$/i;
21
+
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
+ );
27
+ }
28
+
29
+ export function scriptHash(text: string): string {
30
+ return createHash("sha1").update(text).digest("hex").slice(0, 16);
31
+ }