@jalaxy33/pi-permission 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +134 -2
- package/docs/configuration.md +237 -0
- package/index.ts +97 -0
- package/package.json +54 -4
- package/rules/index.json +71 -0
- package/rules/packs/bulk-delete.json +83 -0
- package/rules/packs/database.json +30 -0
- package/rules/packs/git-local.json +81 -0
- package/rules/packs/git-remote.json +27 -0
- package/rules/packs/infra.json +45 -0
- package/rules/packs/irreversible.json +93 -0
- package/rules/packs/privilege.json +50 -0
- package/rules/packs/publish.json +33 -0
- package/rules/packs/secrets.json +43 -0
- package/schema.json +348 -0
- package/src/argv.ts +67 -0
- package/src/config.ts +201 -0
- package/src/decide.ts +90 -0
- package/src/gate.ts +208 -0
- package/src/match.ts +58 -0
- package/src/ops.ts +244 -0
- package/src/outside.ts +87 -0
- package/src/paths.ts +194 -0
- package/src/prompt.ts +275 -0
- package/src/rulesets.ts +444 -0
- package/src/tokenize.ts +222 -0
- package/src/types.ts +167 -0
- package/src/validate.ts +125 -0
package/src/gate.ts
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
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 { statSync } from "node:fs";
|
|
7
|
+
import { dirname } from "node:path";
|
|
8
|
+
import { decide } from "./decide";
|
|
9
|
+
import { collectTargets, type PathTarget } from "./ops";
|
|
10
|
+
import { checkOutside } from "./outside";
|
|
11
|
+
import { 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
|
+
const FILE_TOOL_OPS: Record<string, PathOp> = {
|
|
17
|
+
read: "read",
|
|
18
|
+
grep: "read",
|
|
19
|
+
find: "read",
|
|
20
|
+
ls: "read",
|
|
21
|
+
write: "write",
|
|
22
|
+
edit: "write",
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function isDirectory(path: string): boolean {
|
|
26
|
+
try {
|
|
27
|
+
return statSync(path).isDirectory();
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The session grant for an outside path covers its directory: a file one level up. */
|
|
34
|
+
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
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type GateDecision =
|
|
50
|
+
| { kind: "allow" }
|
|
51
|
+
| { kind: "block"; reason: string; terminate?: boolean }
|
|
52
|
+
| { kind: "prompt"; title: string; reason: string; label: string; grantKeys: string[] };
|
|
53
|
+
|
|
54
|
+
function toolTargets(
|
|
55
|
+
toolName: string,
|
|
56
|
+
input: Record<string, unknown>,
|
|
57
|
+
cwd: string,
|
|
58
|
+
): { paths: PathTarget[]; label: string; text?: string } | undefined {
|
|
59
|
+
const fileOp = FILE_TOOL_OPS[toolName];
|
|
60
|
+
if (fileOp) {
|
|
61
|
+
const raw = String(input.path ?? input.file_path ?? "").trim();
|
|
62
|
+
if (!raw) return undefined;
|
|
63
|
+
return { paths: [{ path: raw, op: fileOp }], label: `${toolName} ${raw}` };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (!GATED_TOOLS.has(toolName)) return undefined;
|
|
67
|
+
const command = input.command;
|
|
68
|
+
if (typeof command !== "string" || command.trim() === "") return undefined;
|
|
69
|
+
return { paths: collectTargets(command, cwd), label: command, text: command };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** A grant covers one rule and one operation: allowing a read leaves writes asking. */
|
|
73
|
+
function pathGrantKey(hit: PathHit, op: PathOp): string {
|
|
74
|
+
return `path:${hit.rule}:${op}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface PathAsk {
|
|
78
|
+
op: PathOp;
|
|
79
|
+
path: string;
|
|
80
|
+
reason: string;
|
|
81
|
+
grantKey: string;
|
|
82
|
+
fromRule: boolean;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** A deny rule wins over allow and ask; allow wins over ask; anything unmatched uses the default. */
|
|
86
|
+
function decidePaths(
|
|
87
|
+
config: ResolvedConfig,
|
|
88
|
+
targets: PathTarget[],
|
|
89
|
+
cwd: string,
|
|
90
|
+
hasGrant: (key: string) => boolean,
|
|
91
|
+
): GateDecision | undefined {
|
|
92
|
+
const denyReasons: string[] = [];
|
|
93
|
+
const asks: PathAsk[] = [];
|
|
94
|
+
|
|
95
|
+
for (const target of targets) {
|
|
96
|
+
const hits = matchPath(config.paths, target.path, cwd, target.op, {
|
|
97
|
+
basenameOnly: target.basenameOnly,
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
const denied = hits.find((hit) => hit.action === "deny");
|
|
101
|
+
if (denied) {
|
|
102
|
+
denyReasons.push(denied.reason);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
if (hits.some((hit) => hit.action === "allow")) continue;
|
|
106
|
+
|
|
107
|
+
const ruleAsks = hits.filter((hit) => hit.action === "ask");
|
|
108
|
+
if (ruleAsks.length > 0) {
|
|
109
|
+
for (const hit of ruleAsks) {
|
|
110
|
+
asks.push({
|
|
111
|
+
op: target.op,
|
|
112
|
+
path: hit.path,
|
|
113
|
+
reason: hit.reason,
|
|
114
|
+
grantKey: pathGrantKey(hit, target.op),
|
|
115
|
+
fromRule: true,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const fallback = config.defaultPermission.paths;
|
|
122
|
+
if (fallback === "allow") continue;
|
|
123
|
+
const path = target.basenameOnly ? target.path : resolveCandidate(target.path, cwd).abs;
|
|
124
|
+
const reason = `no path rule allows ${target.op} ${path}`;
|
|
125
|
+
if (fallback === "deny") {
|
|
126
|
+
denyReasons.push(`pi-permission: ${reason}`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
asks.push({
|
|
130
|
+
op: target.op,
|
|
131
|
+
path,
|
|
132
|
+
reason,
|
|
133
|
+
grantKey: `path:default:${target.op}:${path}`,
|
|
134
|
+
fromRule: false,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const denied = denyReasons[0];
|
|
139
|
+
if (denied) return { kind: "block", reason: denied };
|
|
140
|
+
|
|
141
|
+
const pending = asks.filter((ask) => !hasGrant(ask.grantKey));
|
|
142
|
+
if (pending.length === 0) return undefined;
|
|
143
|
+
|
|
144
|
+
const first = pending[0] as PathAsk;
|
|
145
|
+
return {
|
|
146
|
+
kind: "prompt",
|
|
147
|
+
title: pending.some((ask) => ask.fromRule) ? "Protected path" : "Unlisted path",
|
|
148
|
+
reason: first.reason,
|
|
149
|
+
label: `${first.op} ${first.path}`,
|
|
150
|
+
grantKeys: pending.map((ask) => ask.grantKey),
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function evaluate(
|
|
155
|
+
config: ResolvedConfig,
|
|
156
|
+
toolName: string,
|
|
157
|
+
input: Record<string, unknown>,
|
|
158
|
+
cwd: string,
|
|
159
|
+
hasGrant: (key: string) => boolean = () => false,
|
|
160
|
+
): GateDecision {
|
|
161
|
+
if (config.fatal) return { kind: "block", reason: config.fatal };
|
|
162
|
+
|
|
163
|
+
const targets = toolTargets(toolName, input, cwd);
|
|
164
|
+
|
|
165
|
+
if (config.enabled.paths && targets) {
|
|
166
|
+
const decision = decidePaths(config, targets.paths, cwd, hasGrant);
|
|
167
|
+
if (decision) return decision;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (targets) {
|
|
171
|
+
for (const target of targets.paths) {
|
|
172
|
+
const hit = checkOutside(config.outside, target.path, cwd, target.op);
|
|
173
|
+
if (!hit || grantedOutside(hit.path, hasGrant)) continue;
|
|
174
|
+
const reason = `outside workspace: ${hit.path}`;
|
|
175
|
+
if (hit.mode === "block") return { kind: "block", reason: `pi-permission: ${reason}` };
|
|
176
|
+
return {
|
|
177
|
+
kind: "prompt",
|
|
178
|
+
title: "Outside workspace",
|
|
179
|
+
reason,
|
|
180
|
+
label: targets.label,
|
|
181
|
+
grantKeys: [outsideGrantKey(hit.path)],
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
if (!config.enabled.commands) return { kind: "allow" };
|
|
187
|
+
const text = targets?.text;
|
|
188
|
+
if (!text) return { kind: "allow" };
|
|
189
|
+
|
|
190
|
+
const verdict = decide(text, config.commands, config.defaultPermission.commands);
|
|
191
|
+
if (verdict.action === "allow") return { kind: "allow" };
|
|
192
|
+
if (verdict.action === "ask" && verdict.grants.length > 0 && verdict.grants.every(hasGrant)) {
|
|
193
|
+
return { kind: "allow" };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const reason = verdict.reasons.join("; ") || "matched a permission rule";
|
|
197
|
+
if (verdict.action === "deny") {
|
|
198
|
+
const hint = verdict.terminate ? "" : " Ask the user instead of retrying.";
|
|
199
|
+
return { kind: "block", reason: `pi-permission: ${reason}.${hint}`, terminate: verdict.terminate };
|
|
200
|
+
}
|
|
201
|
+
return {
|
|
202
|
+
kind: "prompt",
|
|
203
|
+
title: verdict.matched ? "Dangerous command" : "Unmatched command",
|
|
204
|
+
reason,
|
|
205
|
+
label: text,
|
|
206
|
+
grantKeys: verdict.grants,
|
|
207
|
+
};
|
|
208
|
+
}
|
package/src/match.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { Args } from "./argv";
|
|
2
|
+
import type { CompiledRule, CompileResult, Rule } from "./types";
|
|
3
|
+
|
|
4
|
+
function wildcardRegex(pattern: string): RegExp {
|
|
5
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
6
|
+
return new RegExp(`^${escaped}$`);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function compileRules(rules: Rule[]): CompileResult {
|
|
10
|
+
const warnings: string[] = [];
|
|
11
|
+
const compiled: CompiledRule[] = [];
|
|
12
|
+
|
|
13
|
+
for (const rule of rules) {
|
|
14
|
+
const programOk =
|
|
15
|
+
typeof rule?.program === "string" ||
|
|
16
|
+
(Array.isArray(rule?.program) && rule.program.every((name) => typeof name === "string"));
|
|
17
|
+
if (!rule || !programOk) {
|
|
18
|
+
warnings.push(`ignore rule without program: ${JSON.stringify(rule)}`);
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (!rule.id) {
|
|
22
|
+
warnings.push(`ignore rule without id: ${rule.program}`);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const names = Array.isArray(rule.program) ? rule.program : [rule.program];
|
|
27
|
+
const entry: CompiledRule = { ...rule, programRes: names.filter((name) => name.includes("*")).map(wildcardRegex) };
|
|
28
|
+
|
|
29
|
+
if (rule.argvRegex) {
|
|
30
|
+
try {
|
|
31
|
+
entry.re = new RegExp(rule.argvRegex);
|
|
32
|
+
} catch (error) {
|
|
33
|
+
warnings.push(`rule ${rule.id}: bad argvRegex (${(error as Error).message})`);
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
compiled.push(entry);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return { rules: compiled, warnings };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function matchesProgram(rule: CompiledRule, program: string): boolean {
|
|
44
|
+
const names = Array.isArray(rule.program) ? rule.program : [rule.program];
|
|
45
|
+
if (names.some((name) => !name.includes("*") && name.replace(/^\//, "") === program)) return true;
|
|
46
|
+
return (rule.programRes ?? []).some((re) => re.test(program));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function matchRule(rule: CompiledRule, args: Args): boolean {
|
|
50
|
+
if (!matchesProgram(rule, args.program)) return false;
|
|
51
|
+
if (rule.subcommand && !rule.subcommand.includes(args.positional[0] ?? "")) return false;
|
|
52
|
+
if (rule.args && !rule.args.some((wanted) => args.positional.includes(wanted))) return false;
|
|
53
|
+
if (rule.anyFlag && !rule.anyFlag.some((flag) => args.flags.has(flag))) return false;
|
|
54
|
+
if (rule.allFlags && !rule.allFlags.every((flag) => args.flags.has(flag))) return false;
|
|
55
|
+
if (rule.unlessFlag && rule.unlessFlag.some((flag) => args.flags.has(flag))) return false;
|
|
56
|
+
if (rule.re && !rule.re.test(args.joined)) return false;
|
|
57
|
+
return true;
|
|
58
|
+
}
|
package/src/ops.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
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 type { PathOp } from "./types";
|
|
10
|
+
|
|
11
|
+
const READ = new Set([
|
|
12
|
+
"cat",
|
|
13
|
+
"bat",
|
|
14
|
+
"head",
|
|
15
|
+
"tail",
|
|
16
|
+
"less",
|
|
17
|
+
"more",
|
|
18
|
+
"grep",
|
|
19
|
+
"egrep",
|
|
20
|
+
"rg",
|
|
21
|
+
"ag",
|
|
22
|
+
"awk",
|
|
23
|
+
"strings",
|
|
24
|
+
"xxd",
|
|
25
|
+
"od",
|
|
26
|
+
"hexdump",
|
|
27
|
+
"file",
|
|
28
|
+
"wc",
|
|
29
|
+
"diff",
|
|
30
|
+
"cmp",
|
|
31
|
+
"md5sum",
|
|
32
|
+
"sha1sum",
|
|
33
|
+
"sha256sum",
|
|
34
|
+
"sha512sum",
|
|
35
|
+
"openssl",
|
|
36
|
+
"gpg",
|
|
37
|
+
"jq",
|
|
38
|
+
"yq",
|
|
39
|
+
"column",
|
|
40
|
+
"sort",
|
|
41
|
+
"uniq",
|
|
42
|
+
"cut",
|
|
43
|
+
"envsubst",
|
|
44
|
+
]);
|
|
45
|
+
|
|
46
|
+
const WRITE = new Set([
|
|
47
|
+
"tee",
|
|
48
|
+
"truncate",
|
|
49
|
+
"touch",
|
|
50
|
+
"install",
|
|
51
|
+
"ln",
|
|
52
|
+
"chmod",
|
|
53
|
+
"chown",
|
|
54
|
+
"chgrp",
|
|
55
|
+
"setfacl",
|
|
56
|
+
"patch",
|
|
57
|
+
]);
|
|
58
|
+
|
|
59
|
+
const DELETE = new Set(["rm", "unlink", "shred", "rmdir"]);
|
|
60
|
+
|
|
61
|
+
/** First operand is the source (read), the rest are written. */
|
|
62
|
+
const COPY = new Set(["cp", "mv", "rsync", "scp", "dd"]);
|
|
63
|
+
|
|
64
|
+
const EXTENSION = /\.[A-Za-z0-9_]+$/;
|
|
65
|
+
const SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "fish"]);
|
|
66
|
+
const MAX_GLOB_MATCHES = 50;
|
|
67
|
+
export const MAX_NESTING = 3;
|
|
68
|
+
|
|
69
|
+
/** Conservative heuristic: anything that looks like a filesystem path. */
|
|
70
|
+
export function looksLikePath(value: string, cwd: string): boolean {
|
|
71
|
+
if (!value || value.startsWith("-")) return false;
|
|
72
|
+
if (value.includes("$") || value.includes("*") || value.includes("?")) return false;
|
|
73
|
+
if (value.includes("/") || value.startsWith(".") || value.startsWith("~")) return true;
|
|
74
|
+
if (EXTENSION.test(value)) return true;
|
|
75
|
+
const abs = isAbsolute(value) ? value : resolve(cwd, expandTilde(value));
|
|
76
|
+
return existsSync(abs);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function hasGlobChars(value: string): boolean {
|
|
80
|
+
return value.includes("*") || value.includes("?") || value.includes("[");
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Expands a shell glob so `cat .env*` cannot slip past the rules. */
|
|
84
|
+
function expandGlob(value: string, cwd: string): string[] {
|
|
85
|
+
const fn = (fs as { globSync?: (pattern: string, options?: { cwd?: string }) => string[] }).globSync;
|
|
86
|
+
if (typeof fn !== "function") return [];
|
|
87
|
+
try {
|
|
88
|
+
return fn(expandTilde(value), { cwd }).slice(0, MAX_GLOB_MATCHES);
|
|
89
|
+
} catch {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** `$VAR` operands cannot be resolved: keep the literal basename for matching. */
|
|
95
|
+
function unresolvedBasename(value: string): string | undefined {
|
|
96
|
+
const suffix = basename(value);
|
|
97
|
+
if (!suffix || suffix.startsWith("$")) return undefined;
|
|
98
|
+
return EXTENSION.test(suffix) ? suffix : undefined;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function flagValueOf(token: string): string | undefined {
|
|
102
|
+
const eq = token.indexOf("=");
|
|
103
|
+
return token.startsWith("-") && eq > 0 ? token.slice(eq + 1) : undefined;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function cwdAfterArgs(args: Args, cwd: string): string {
|
|
107
|
+
if (args.program !== "cd" && args.program !== "pushd") return cwd;
|
|
108
|
+
const target = args.positional[0];
|
|
109
|
+
if (!target || target === "-") return cwd;
|
|
110
|
+
const expanded = expandTilde(target);
|
|
111
|
+
return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** cwd for the next command in the chain (`cd dir`, `pushd dir`). */
|
|
115
|
+
export function cwdAfter(simple: SimpleCommand, cwd: string): string {
|
|
116
|
+
const args = parseArgs(simple.argv);
|
|
117
|
+
return args ? cwdAfterArgs(args, cwd) : cwd;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface PathTarget {
|
|
121
|
+
path: string;
|
|
122
|
+
op: PathOp;
|
|
123
|
+
/** Set when only the literal basename is known (e.g. `${HOME}/.env`). */
|
|
124
|
+
basenameOnly?: boolean;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function extractTargets(simple: SimpleCommand, cwd: string): PathTarget[] {
|
|
128
|
+
const args = parseArgs(simple.argv);
|
|
129
|
+
return args ? targetsOf(args, simple, cwd) : [];
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function targetsOf(args: Args, simple: SimpleCommand, cwd: string): PathTarget[] {
|
|
133
|
+
const targets: PathTarget[] = [];
|
|
134
|
+
const add = (value: string | undefined, op: PathOp) => {
|
|
135
|
+
if (!value) return;
|
|
136
|
+
|
|
137
|
+
if (hasGlobChars(value)) {
|
|
138
|
+
for (const match of expandGlob(value, cwd)) targets.push({ path: match, op });
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (value.includes("$")) {
|
|
143
|
+
const basename = unresolvedBasename(value);
|
|
144
|
+
if (basename) targets.push({ path: basename, op, basenameOnly: true });
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!looksLikePath(value, cwd)) return;
|
|
149
|
+
targets.push({ path: value, op });
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
// Redirections: `> file` writes, `>> file` writes, `< file` reads.
|
|
153
|
+
for (const redirect of simple.redirects) {
|
|
154
|
+
add(redirect.target, redirect.op === "<" ? "read" : "write");
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (args.program === "cd" || args.program === "pushd") return targets;
|
|
158
|
+
|
|
159
|
+
// The `-c` script is walked by collectTargets; its text is not an operand.
|
|
160
|
+
if (SHELLS.has(args.program)) {
|
|
161
|
+
const script = scriptAfterC(simple.argv);
|
|
162
|
+
for (const operand of args.positional) if (operand !== script) add(operand, "read");
|
|
163
|
+
return targets;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
if (DELETE.has(args.program)) {
|
|
167
|
+
for (const operand of args.positional) add(operand, "delete");
|
|
168
|
+
return targets;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
if (COPY.has(args.program)) {
|
|
172
|
+
if (args.program === "dd") {
|
|
173
|
+
for (const operand of args.positional) add(operand, "write");
|
|
174
|
+
return targets;
|
|
175
|
+
}
|
|
176
|
+
const operands = args.positional;
|
|
177
|
+
// A move deletes its source; a copy only reads it.
|
|
178
|
+
const sourceOp: PathOp = args.program === "mv" ? "delete" : "read";
|
|
179
|
+
operands.forEach((operand, index) => {
|
|
180
|
+
add(operand, index === operands.length - 1 ? "write" : sourceOp);
|
|
181
|
+
});
|
|
182
|
+
return targets;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (args.program === "sed") {
|
|
186
|
+
const inPlace = args.flags.has("-i") || args.flags.has("--in-place");
|
|
187
|
+
for (const operand of args.positional.slice(1)) add(operand, inPlace ? "write" : "read");
|
|
188
|
+
return targets;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (WRITE.has(args.program)) {
|
|
192
|
+
for (const operand of args.positional) add(operand, "write");
|
|
193
|
+
return targets;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (READ.has(args.program)) {
|
|
197
|
+
for (const operand of args.positional) add(operand, "read");
|
|
198
|
+
return targets;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Unknown program: treat path-looking operands and `--flag=value` paths as reads.
|
|
202
|
+
for (const operand of args.positional) add(operand, "read");
|
|
203
|
+
for (const token of simple.argv) add(flagValueOf(token), "read");
|
|
204
|
+
|
|
205
|
+
return targets;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Script text of `sh -c "..."`, so nested commands are checked too.
|
|
210
|
+
* Reads the token after `-c`, not the first positional: `bash -o pipefail -c '...'`.
|
|
211
|
+
*/
|
|
212
|
+
export function scriptAfterC(argv: string[]): string | undefined {
|
|
213
|
+
const args = parseArgs(argv);
|
|
214
|
+
if (!args || !SHELLS.has(args.program)) return undefined;
|
|
215
|
+
const index = argv.findIndex(
|
|
216
|
+
(token, position) => position > 0 && /^-[A-Za-z0-9]*c[A-Za-z0-9]*$/.test(token),
|
|
217
|
+
);
|
|
218
|
+
return index > 0 ? argv[index + 1] : undefined;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** A path from a `cd`-relative command is pinned to the directory that command runs in. */
|
|
222
|
+
function pin(target: PathTarget, current: string, cwd: string): PathTarget {
|
|
223
|
+
if (current === cwd || target.basenameOnly || isAbsolute(target.path)) return target;
|
|
224
|
+
return { ...target, path: resolve(current, target.path) };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** All path targets of a command string, including `cd` tracking and `sh -c`. */
|
|
228
|
+
export function collectTargets(command: string, cwd: string, depth = 0): PathTarget[] {
|
|
229
|
+
const targets: PathTarget[] = [];
|
|
230
|
+
let current = cwd;
|
|
231
|
+
|
|
232
|
+
for (const simple of tokenize(command)) {
|
|
233
|
+
const args = parseArgs(simple.argv);
|
|
234
|
+
if (!args) continue;
|
|
235
|
+
for (const target of targetsOf(args, simple, current)) targets.push(pin(target, current, cwd));
|
|
236
|
+
const script = scriptAfterC(simple.argv);
|
|
237
|
+
if (script && depth < MAX_NESTING) {
|
|
238
|
+
for (const target of collectTargets(script, current, depth + 1)) targets.push(pin(target, current, cwd));
|
|
239
|
+
}
|
|
240
|
+
current = cwdAfterArgs(args, current);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return targets;
|
|
244
|
+
}
|
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
|
+
}
|