@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/decide.ts ADDED
@@ -0,0 +1,200 @@
1
+ import { parseArgs, programWordIndex, type Args } from "./argv";
2
+ import { matchRule } from "./match";
3
+ import { MAX_NESTING, scriptAfterC, SHELLS } from "./ops";
4
+ import { isCodeRunner, scriptHash, scriptOperand } from "./scripts";
5
+ import { tokenizeDetailed, type SimpleCommand, type WordMeta } from "./tokenize";
6
+ import { unlayer } from "./unlayer";
7
+ import type { Action, CompiledRule, GateRules, Verdict } from "./types";
8
+
9
+ const RANK: Record<Action, number> = { allow: 0, ask: 1, deny: 2 };
10
+
11
+ function verdict(action: Action, matched: boolean): Verdict {
12
+ return { action, reasons: [], grants: [], terminate: false, matched };
13
+ }
14
+
15
+ /**
16
+ * Text the gate could not resolve, and script text that only becomes a
17
+ * command at runtime. Guessing here would turn a bypass into a silent allow,
18
+ * so it asks instead.
19
+ */
20
+ function unreadable(what: string): Verdict {
21
+ const result = verdict("ask", true);
22
+ result.reasons = [`gate cannot inspect this command: ${what}`];
23
+ result.grants = [`unreadable:${what}`];
24
+ return result;
25
+ }
26
+
27
+ /** A `-c` script that reads a variable runs code this gate never sees. */
28
+ function hasRuntimeExpansion(script: string): boolean {
29
+ return /\$(?!\()/.test(script);
30
+ }
31
+
32
+ /** A program name built from a substitution, escape or glob is not a name. */
33
+ function unreadableProgram(meta: WordMeta | undefined): Verdict | undefined {
34
+ if (!meta) return undefined;
35
+ if (meta.expansion || meta.escape || meta.glob) return unreadable("program name is not a literal");
36
+ return undefined;
37
+ }
38
+
39
+ /** Source code the gate can see but not read. */
40
+ function unreadableScript(program: string, why: string, grant?: string): Verdict {
41
+ const result = verdict("ask", true);
42
+ result.reasons = [`${why}. The gate cannot read the ${program} script`];
43
+ if (grant !== undefined) result.grants = [grant];
44
+ return result;
45
+ }
46
+
47
+ /** The script a command runs, when it comes from somewhere other than `-c`. */
48
+ export function decideInput(
49
+ simple: SimpleCommand,
50
+ argv: string[],
51
+ rules: GateRules,
52
+ fallback: Action,
53
+ depth: number,
54
+ options: DecideOptions,
55
+ ): Verdict | undefined {
56
+ const args = parseArgs(argv);
57
+ if (!args) return undefined;
58
+ const shell = SHELLS.has(args.program);
59
+ if (!shell && !isCodeRunner(args.program)) return undefined;
60
+ // `-c` names the code inline, and `-n` only parses; neither runs a file.
61
+ if (scriptAfterC(argv) !== undefined) return undefined;
62
+ if (shell && args.flags.has("-n")) return undefined;
63
+
64
+ if (shell && simple.heredoc !== undefined) {
65
+ if (depth >= MAX_NESTING) return unreadable("nested script");
66
+ return decide(simple.heredoc, rules, fallback, depth + 1, options);
67
+ }
68
+
69
+ const operand = scriptOperand(args.positional);
70
+ if (operand !== undefined) {
71
+ const text = options.readScript?.(operand);
72
+ if (text === undefined) {
73
+ return unreadableScript(args.program, `cannot read ${operand}`, `opaque:${args.program}:${operand}`);
74
+ }
75
+ if (depth >= MAX_NESTING) return unreadable("nested script");
76
+ if (shell) return decide(text, rules, fallback, depth + 1, options);
77
+ return unreadableScript(
78
+ args.program,
79
+ `${operand} is not shell code, so it is not parsed`,
80
+ `opaque:${args.program}:file:${scriptHash(text)}`,
81
+ );
82
+ }
83
+
84
+ const fromStdin =
85
+ simple.stdinPiped === true ||
86
+ simple.stdinText !== undefined ||
87
+ args.flags.has("-") ||
88
+ (shell && args.flags.has("-s")) ||
89
+ simple.redirects.some((redirect) => redirect.op === "<");
90
+ if (fromStdin) return unreadableScript(args.program, "its script arrives on stdin, which the command text does not contain");
91
+ return undefined;
92
+ }
93
+
94
+ /** A session grant covers one rule with the same flags, not every command it matches. */
95
+ function grantKey(rule: CompiledRule, args: Args): string {
96
+ return `rule:${rule.id}:${[...args.flags].filter(canonicalFlag).sort().join(",")}`;
97
+ }
98
+
99
+ /** `-rf` and `-fr` are the same flags; keep only the letters for grant keys. */
100
+ function canonicalFlag(flag: string): boolean {
101
+ return flag.startsWith("-") && !/^-[A-Za-z0-9]{2,}$/.test(flag);
102
+ }
103
+
104
+ /** Fallback grants key on the program: approving one unmatched command grants that program. */
105
+ function fallbackGrant(args: Args): string {
106
+ return `default:${args.program}:${[...args.flags].filter(canonicalFlag).sort().join(",")}`;
107
+ }
108
+
109
+ function decideOne(argv: string[], rules: GateRules, fallback: Action): Verdict {
110
+ const args = parseArgs(argv);
111
+ // A line of assignments has no program; there is nothing to ask about.
112
+ if (!args) return verdict("allow", true);
113
+
114
+ // `cd` is structural: later commands are judged in the directory it reaches,
115
+ // so it stays allowed even in a deny-by-default setup.
116
+ if (args.program === "cd" || args.program === "pushd") return verdict("allow", true);
117
+
118
+ const deny = rules.deny.filter((rule) => matchRule(rule, args));
119
+ if (deny.length > 0) {
120
+ const result = verdict("deny", true);
121
+ result.reasons = deny.map((rule) => rule.reason ?? rule.id);
122
+ result.terminate = deny.some((rule) => rule.terminate === true);
123
+ return result;
124
+ }
125
+
126
+ if (rules.allow.some((rule) => matchRule(rule, args))) return verdict("allow", true);
127
+
128
+ const ask = rules.ask.filter((rule) => matchRule(rule, args));
129
+ if (ask.length > 0) {
130
+ const result = verdict("ask", true);
131
+ result.reasons = ask.map((rule) => rule.reason ?? rule.id);
132
+ result.grants = ask.map((rule) => grantKey(rule, args));
133
+ return result;
134
+ }
135
+
136
+ if (fallback === "allow") return verdict("allow", false);
137
+
138
+ const result = verdict(fallback, false);
139
+ result.reasons = [`no command rule allows ${args.program}`];
140
+ if (fallback === "ask") result.grants = [fallbackGrant(args)];
141
+ return result;
142
+ }
143
+
144
+ function mergeInto(target: Verdict, source: Verdict): void {
145
+ for (const reason of source.reasons) {
146
+ if (!target.reasons.includes(reason)) target.reasons.push(reason);
147
+ }
148
+ for (const grant of source.grants) {
149
+ if (!target.grants.includes(grant)) target.grants.push(grant);
150
+ }
151
+ if (RANK[source.action] > RANK[target.action]) target.action = source.action;
152
+ if (source.terminate) target.terminate = true;
153
+ if (source.matched) target.matched = true;
154
+ }
155
+
156
+ /**
157
+ * Strictest verdict across every simple command, including `sh -c` scripts.
158
+ * `fallback` is `defaultPermission.commands`: what an unmatched program does.
159
+ */
160
+ export interface DecideOptions {
161
+ /** Reads a script file named by a command. Undefined when it cannot be read. */
162
+ readScript?: (path: string) => string | undefined;
163
+ }
164
+
165
+ export function decide(
166
+ command: string,
167
+ rules: GateRules,
168
+ fallback: Action = "allow",
169
+ depth = 0,
170
+ options: DecideOptions = {},
171
+ ): Verdict {
172
+ const merged: Verdict = { action: "allow", reasons: [], grants: [], terminate: false, matched: false };
173
+
174
+ const split = tokenizeDetailed(command);
175
+ for (const hazard of split.hazards) mergeInto(merged, unreadable(hazard));
176
+
177
+ for (const simple of split.commands) {
178
+ const argv = unlayer(simple.argv);
179
+ if (!argv) continue;
180
+ // `FOO=1 "$CMD" x` puts the program one word later than the segment start.
181
+ const wordIndex = programWordIndex(argv);
182
+ const meta = wordIndex === -1 ? undefined : simple.words[simple.argv.length - argv.length + wordIndex];
183
+ mergeInto(merged, unreadableProgram(meta) ?? verdict("allow", false));
184
+ mergeInto(merged, decideOne(argv, rules, fallback));
185
+
186
+ const input = decideInput(simple, argv, rules, fallback, depth, options);
187
+ if (input) mergeInto(merged, input);
188
+
189
+ const script = scriptAfterC(argv);
190
+ if (!script) continue;
191
+ if (depth >= MAX_NESTING) {
192
+ mergeInto(merged, unreadable("nested script"));
193
+ continue;
194
+ }
195
+ mergeInto(merged, decide(script, rules, fallback, depth + 1, options));
196
+ if (hasRuntimeExpansion(script)) mergeInto(merged, unreadable("script expansion"));
197
+ }
198
+
199
+ return merged;
200
+ }
package/src/gate.ts ADDED
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Decision layer: what should happen to one tool call.
3
+ * Pure: no prompting, no session state — the caller acts on the verdict.
4
+ */
5
+
6
+ import { readFileSync, statSync } from "node:fs";
7
+ import { dirname, isAbsolute, resolve } from "node:path";
8
+ import { decide } from "./decide";
9
+ import { collectTargets, type PathTarget } from "./ops";
10
+ import { checkOutside } from "./outside";
11
+ import { expandTilde, matchPath, resolveCandidate, type PathHit } from "./paths";
12
+ import type { PathOp, ResolvedConfig } from "./types";
13
+
14
+ export const GATED_TOOLS = new Set(["bash", "powershell"]);
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
+
31
+ const FILE_TOOL_OPS: Record<string, PathOp> = {
32
+ read: "read",
33
+ grep: "read",
34
+ find: "read",
35
+ ls: "read",
36
+ write: "write",
37
+ edit: "write",
38
+ };
39
+
40
+ function isDirectory(path: string): boolean {
41
+ try {
42
+ return statSync(path).isDirectory();
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
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
+ */
53
+ function outsideGrantKey(path: string): string {
54
+ return `outside:${path}`;
55
+ }
56
+
57
+ export type GateDecision =
58
+ | { kind: "allow" }
59
+ | { kind: "block"; reason: string; terminate?: boolean }
60
+ | { kind: "prompt"; title: string; reason: string; label: string; grantKeys: string[] };
61
+
62
+ function toolTargets(
63
+ toolName: string,
64
+ input: Record<string, unknown>,
65
+ cwd: string,
66
+ ): { paths: PathTarget[]; label: string; text?: string } | undefined {
67
+ const fileOp = FILE_TOOL_OPS[toolName];
68
+ if (fileOp) {
69
+ const raw = String(input.path ?? input.file_path ?? "").trim();
70
+ if (!raw) return undefined;
71
+ return { paths: [{ path: raw, op: fileOp }], label: `${toolName} ${raw}` };
72
+ }
73
+
74
+ if (!GATED_TOOLS.has(toolName)) return undefined;
75
+ const command = input.command;
76
+ if (typeof command !== "string" || command.trim() === "") return undefined;
77
+ return { paths: collectTargets(command, cwd), label: command, text: command };
78
+ }
79
+
80
+ /** A grant covers one rule and one operation: allowing a read leaves writes asking. */
81
+ function pathGrantKey(hit: PathHit, op: PathOp): string {
82
+ return `path:${hit.rule}:${op}`;
83
+ }
84
+
85
+ interface PathAsk {
86
+ op: PathOp;
87
+ path: string;
88
+ reason: string;
89
+ grantKey: string;
90
+ fromRule: boolean;
91
+ }
92
+
93
+ /** A deny rule wins over allow and ask; allow wins over ask; anything unmatched uses the default. */
94
+ function decidePaths(
95
+ config: ResolvedConfig,
96
+ targets: PathTarget[],
97
+ cwd: string,
98
+ hasGrant: (key: string) => boolean,
99
+ ): GateDecision | undefined {
100
+ const denyReasons: string[] = [];
101
+ const asks: PathAsk[] = [];
102
+
103
+ for (const target of targets) {
104
+ const hits = matchPath(config.paths, target.path, cwd, target.op, {
105
+ basenameOnly: target.basenameOnly,
106
+ });
107
+
108
+ const denied = hits.find((hit) => hit.action === "deny");
109
+ if (denied) {
110
+ denyReasons.push(denied.reason);
111
+ continue;
112
+ }
113
+ if (hits.some((hit) => hit.action === "allow")) continue;
114
+
115
+ const ruleAsks = hits.filter((hit) => hit.action === "ask");
116
+ if (ruleAsks.length > 0) {
117
+ for (const hit of ruleAsks) {
118
+ asks.push({
119
+ op: target.op,
120
+ path: hit.path,
121
+ reason: hit.reason,
122
+ grantKey: pathGrantKey(hit, target.op),
123
+ fromRule: true,
124
+ });
125
+ }
126
+ continue;
127
+ }
128
+
129
+ const fallback = config.defaultPermission.paths;
130
+ if (fallback === "allow") continue;
131
+ const path = target.basenameOnly ? target.path : resolveCandidate(target.path, cwd).abs;
132
+ const reason = `no path rule allows ${target.op} ${path}`;
133
+ if (fallback === "deny") {
134
+ denyReasons.push(`pi-permission: ${reason}`);
135
+ continue;
136
+ }
137
+ asks.push({
138
+ op: target.op,
139
+ path,
140
+ reason,
141
+ grantKey: `path:default:${target.op}:${path}`,
142
+ fromRule: false,
143
+ });
144
+ }
145
+
146
+ const denied = denyReasons[0];
147
+ if (denied) return { kind: "block", reason: denied };
148
+
149
+ const pending = asks.filter((ask) => !hasGrant(ask.grantKey));
150
+ if (pending.length === 0) return undefined;
151
+
152
+ const first = pending[0] as PathAsk;
153
+ return {
154
+ kind: "prompt",
155
+ title: pending.some((ask) => ask.fromRule) ? "Protected path" : "Unlisted path",
156
+ reason: first.reason,
157
+ label: `${first.op} ${first.path}`,
158
+ grantKeys: pending.map((ask) => ask.grantKey),
159
+ };
160
+ }
161
+
162
+ export function evaluate(
163
+ config: ResolvedConfig,
164
+ toolName: string,
165
+ input: Record<string, unknown>,
166
+ cwd: string,
167
+ hasGrant: (key: string) => boolean = () => false,
168
+ ): GateDecision {
169
+ if (config.fatal) return { kind: "block", reason: config.fatal };
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
+
186
+ const targets = toolTargets(toolName, input, cwd);
187
+
188
+ if (config.enabled.paths && targets) {
189
+ const decision = decidePaths(config, targets.paths, cwd, hasGrant);
190
+ if (decision) return decision;
191
+ }
192
+
193
+ if (targets) {
194
+ for (const target of targets.paths) {
195
+ const hit = checkOutside(config.outside, target.path, cwd, target.op);
196
+ if (!hit || hasGrant(outsideGrantKey(hit.path))) continue;
197
+ const reason = `outside workspace: ${hit.path}`;
198
+ if (hit.mode === "block") return { kind: "block", reason: `pi-permission: ${reason}` };
199
+ return {
200
+ kind: "prompt",
201
+ title: "Outside workspace",
202
+ reason,
203
+ label: targets.label,
204
+ grantKeys: [outsideGrantKey(hit.path)],
205
+ };
206
+ }
207
+ }
208
+
209
+ if (!config.enabled.commands) return { kind: "allow" };
210
+ const text = targets?.text;
211
+ if (!text) return { kind: "allow" };
212
+
213
+ const verdict = decide(text, config.commands, config.defaultPermission.commands, 0, {
214
+ readScript: (path) => readScript(path, cwd),
215
+ });
216
+ if (verdict.action === "allow") return { kind: "allow" };
217
+ if (verdict.action === "ask" && verdict.grants.length > 0 && verdict.grants.every(hasGrant)) {
218
+ return { kind: "allow" };
219
+ }
220
+
221
+ const reason = verdict.reasons.join("; ") || "matched a permission rule";
222
+ if (verdict.action === "deny") {
223
+ const hint = verdict.terminate ? "" : " Ask the user instead of retrying.";
224
+ return { kind: "block", reason: `pi-permission: ${reason}.${hint}`, terminate: verdict.terminate };
225
+ }
226
+ return {
227
+ kind: "prompt",
228
+ title: verdict.matched ? "Dangerous command" : "Unmatched command",
229
+ reason,
230
+ label: text,
231
+ grantKeys: verdict.grants,
232
+ };
233
+ }
package/src/match.ts ADDED
@@ -0,0 +1,59 @@
1
+ import type { Args } from "./argv";
2
+ import { normalizeProgram } from "./program";
3
+ import type { CompiledRule, CompileResult, Rule } from "./types";
4
+
5
+ function wildcardRegex(pattern: string): RegExp {
6
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
7
+ return new RegExp(`^${escaped}$`);
8
+ }
9
+
10
+ export function compileRules(rules: Rule[]): CompileResult {
11
+ const warnings: string[] = [];
12
+ const compiled: CompiledRule[] = [];
13
+
14
+ for (const rule of rules) {
15
+ const programOk =
16
+ typeof rule?.program === "string" ||
17
+ (Array.isArray(rule?.program) && rule.program.every((name) => typeof name === "string"));
18
+ if (!rule || !programOk) {
19
+ warnings.push(`ignore rule without program: ${JSON.stringify(rule)}`);
20
+ continue;
21
+ }
22
+ if (!rule.id) {
23
+ warnings.push(`ignore rule without id: ${rule.program}`);
24
+ continue;
25
+ }
26
+
27
+ const names = Array.isArray(rule.program) ? rule.program : [rule.program];
28
+ const entry: CompiledRule = { ...rule, programRes: names.filter((name) => name.includes("*")).map(wildcardRegex) };
29
+
30
+ if (rule.argvRegex) {
31
+ try {
32
+ entry.re = new RegExp(rule.argvRegex);
33
+ } catch (error) {
34
+ warnings.push(`rule ${rule.id}: bad argvRegex (${(error as Error).message})`);
35
+ continue;
36
+ }
37
+ }
38
+ compiled.push(entry);
39
+ }
40
+
41
+ return { rules: compiled, warnings };
42
+ }
43
+
44
+ function matchesProgram(rule: CompiledRule, program: string): boolean {
45
+ const names = Array.isArray(rule.program) ? rule.program : [rule.program];
46
+ if (names.some((name) => !name.includes("*") && normalizeProgram(name) === program)) return true;
47
+ return (rule.programRes ?? []).some((re) => re.test(program));
48
+ }
49
+
50
+ export function matchRule(rule: CompiledRule, args: Args): boolean {
51
+ if (!matchesProgram(rule, args.program)) return false;
52
+ if (rule.subcommand && !rule.subcommand.includes(args.positional[0] ?? "")) return false;
53
+ if (rule.args && !rule.args.some((wanted) => args.positional.includes(wanted))) return false;
54
+ if (rule.anyFlag && !rule.anyFlag.some((flag) => args.flags.has(flag))) return false;
55
+ if (rule.allFlags && !rule.allFlags.every((flag) => args.flags.has(flag))) return false;
56
+ if (rule.unlessFlag && rule.unlessFlag.some((flag) => args.flags.has(flag))) return false;
57
+ if (rule.re && !rule.re.test(args.joined)) return false;
58
+ return true;
59
+ }