pi-guard 1.0.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/README.md ADDED
@@ -0,0 +1,193 @@
1
+ # pi-guard
2
+
3
+ General-purpose permission system for pi tools. Handles permissions for bash and file tools (read/edit/write) with extensible matchers for custom tools.
4
+
5
+ ## Overview
6
+
7
+ pi-guard intercepts tool calls and checks them against permission rules before execution. Tools have **matchers** that define how to extract and match input, and **rules** that define what's allowed.
8
+
9
+ Built-in matchers for `bash`, `read`, `edit`, and `write`. Other tools can be guarded by configuring matchers in settings.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install pi-guard
15
+ ```
16
+
17
+ Add to your `~/.pi/agent/extensions/pi-guard.ts`:
18
+
19
+ ```typescript
20
+ import guard from "pi-guard";
21
+ export default [guard];
22
+ ```
23
+
24
+ ## Configuration
25
+
26
+ Configure in `~/.pi/agent/settings.json`:
27
+
28
+ ```json
29
+ {
30
+ "guard": {
31
+ "enabled": true,
32
+ "matchers": {
33
+ "webfetch": { "param": "url", "type": "glob" },
34
+ "spawn": { "param": "agent", "type": "exact" }
35
+ },
36
+ "rules": {
37
+ "*": "ask",
38
+ "bash": {
39
+ "*": "ask",
40
+ "git *": "allow",
41
+ "rm *": "deny"
42
+ },
43
+ "read": {
44
+ "*": "allow",
45
+ "*.env": "deny",
46
+ "*.pem": "deny"
47
+ },
48
+ "edit": { "*": "ask" },
49
+ "write": { "*": "ask" },
50
+ "webfetch": {
51
+ "*": "ask",
52
+ "https://github.com/*": "allow"
53
+ },
54
+ "spawn": {
55
+ "build": "allow",
56
+ "test": "allow",
57
+ "*": "deny"
58
+ }
59
+ }
60
+ }
61
+ }
62
+ ```
63
+
64
+ ### Shorthand
65
+
66
+ Disable all checks:
67
+ ```json
68
+ { "guard": { "enabled": false } }
69
+ ```
70
+
71
+ Whole-tool action (no pattern matching needed):
72
+ ```json
73
+ { "guard": { "rules": { "bash": "allow" } } }
74
+ ```
75
+
76
+ ### Environment Variable
77
+
78
+ Set `PI_GUARD` to inject rules from outside (e.g., by pi-spawn or CI/CD):
79
+
80
+ ```bash
81
+ PI_GUARD='{"*":"deny","bash":{"git diff":"allow"}}'
82
+ ```
83
+
84
+ ## Matchers
85
+
86
+ Matchers define how to extract and match input from a tool call:
87
+
88
+ ```typescript
89
+ interface Matcher {
90
+ param: string; // Tool parameter to extract
91
+ type: "bash" | "glob" | "exact"; // How to match
92
+ }
93
+ ```
94
+
95
+ | Type | Description | Use case |
96
+ |------|-------------|----------|
97
+ | `bash` | Parse command, extract all commands, subsequence match | Bash commands |
98
+ | `glob` | `*` and `**` matching (paths, URLs) | File paths, URLs |
99
+ | `exact` | String equality | Enum values, agent names |
100
+
101
+ Tools without a matcher get simple allow/ask/deny for the whole tool.
102
+
103
+ ## Matching Algorithms
104
+
105
+ ### Bash (type: "bash")
106
+
107
+ 1. Parse command with unbash AST parser
108
+ 2. Extract all commands from the AST
109
+ 3. For each command, check rules using subsequence matching
110
+ 4. Tokens in rule must appear in order, extra arguments allowed
111
+
112
+ Example: `"git log"` matches `git log`, `git log --oneline`, `git log --oneline -10`
113
+
114
+ ### Glob (type: "glob")
115
+
116
+ Standard glob matching:
117
+ - `*` matches anything except `/`
118
+ - `**` matches anything including `/`
119
+ - `?` matches single character
120
+ - `~` expands to home directory
121
+
122
+ ### Exact (type: "exact")
123
+
124
+ Simple string equality. Rule `"build"` only matches input `build`.
125
+
126
+ ## Rule Precedence
127
+
128
+ ```
129
+ DEFAULT_CONFIG → user config → project config → PI_GUARD → session rules
130
+ ```
131
+
132
+ **Last match wins** within a tool's rules. Put catch-all `"*"` first, specific rules after:
133
+
134
+ ```json
135
+ "bash": {
136
+ "*": "ask",
137
+ "git *": "allow"
138
+ }
139
+ ```
140
+
141
+ ## Actions
142
+
143
+ Each permission rule resolves to one of:
144
+ - `"allow"` — run without approval
145
+ - `"ask"` — prompt for approval (or block in non-interactive mode)
146
+ - `"deny"` — block the action
147
+
148
+ ## Commands
149
+
150
+ ### `/guard`
151
+
152
+ Manage pi-guard security settings.
153
+
154
+ ```
155
+ /guard toggle # Enable/disable guard
156
+ /guard list # Show current rules
157
+ ```
158
+
159
+ ## Default Rules
160
+
161
+ ```typescript
162
+ {
163
+ bash: {
164
+ "*": "ask",
165
+ cat: "allow",
166
+ cd: "allow",
167
+ echo: "allow",
168
+ find: "allow",
169
+ grep: "allow",
170
+ head: "allow",
171
+ ls: "allow",
172
+ pwd: "allow",
173
+ rg: "allow",
174
+ "git blame": "allow",
175
+ "git branch --show-current": "allow",
176
+ "git diff": "allow",
177
+ "git log": "allow",
178
+ "git show": "allow",
179
+ "git status": "allow",
180
+ },
181
+ read: {
182
+ "*": "allow",
183
+ "*.env": "deny",
184
+ "*.pem": "deny",
185
+ },
186
+ edit: { "*": "ask" },
187
+ write: { "*": "ask" },
188
+ }
189
+ ```
190
+
191
+ ## License
192
+
193
+ MIT
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "pi-guard",
3
+ "version": "1.0.0",
4
+ "description": "General-purpose permission system for pi tools, handling permissions for bash and file tools with extensible matchers for custom tools.",
5
+ "keywords": [
6
+ "pi-package",
7
+ "security",
8
+ "permissions",
9
+ "bash",
10
+ "file",
11
+ "guard"
12
+ ],
13
+ "author": "Jason Diamond <jason@diamond.name>",
14
+ "license": "MIT",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/jdiamond/pi-guard.git"
18
+ },
19
+ "homepage": "https://github.com/jdiamond/pi-guard#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/jdiamond/pi-guard/issues"
22
+ },
23
+ "files": [
24
+ "src",
25
+ "README.md"
26
+ ],
27
+ "type": "module",
28
+ "scripts": {
29
+ "test": "npm run check && node --test test/**/*.ts",
30
+ "check": "tsc --noEmit"
31
+ },
32
+ "pi": {
33
+ "extensions": [
34
+ "./src/index.ts"
35
+ ]
36
+ },
37
+ "dependencies": {
38
+ "minimatch": "^10.2.4",
39
+ "unbash": "jdiamond/unbash#combined-fixes"
40
+ },
41
+ "peerDependencies": {
42
+ "@mariozechner/pi-coding-agent": "*"
43
+ },
44
+ "devDependencies": {
45
+ "@mariozechner/pi-coding-agent": "*",
46
+ "@types/minimatch": "^5.1.2",
47
+ "@types/node": "^25",
48
+ "typescript": "^5.8"
49
+ }
50
+ }
package/src/config.ts ADDED
@@ -0,0 +1,310 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as os from "node:os";
4
+ import type { GuardConfig, Matchers, Action, ToolRules, Rules } from "./types.ts";
5
+
6
+ const AGENT_DIR = path.join(os.homedir(), ".pi", "agent");
7
+ const SETTINGS_PATH = path.join(AGENT_DIR, "settings.json");
8
+
9
+ /** Built-in matchers for core tools. */
10
+ export const DEFAULT_MATCHERS: Matchers = {
11
+ bash: { param: "command", type: "bash" },
12
+ read: { param: "path", type: "glob" },
13
+ edit: { param: "path", type: "glob" },
14
+ write: { param: "path", type: "glob" },
15
+ };
16
+
17
+ /** Default rules - permissive for reading, restrictive for writing. */
18
+ export const DEFAULT_RULES: Record<string, ToolRules> = {
19
+ bash: {
20
+ "*": "ask",
21
+ cat: "allow",
22
+ cd: "allow",
23
+ echo: "allow",
24
+ find: "allow",
25
+ grep: "allow",
26
+ head: "allow",
27
+ ls: "allow",
28
+ pwd: "allow",
29
+ rg: "allow",
30
+ "git blame": "allow",
31
+ "git branch --show-current": "allow",
32
+ "git diff": "allow",
33
+ "git log": "allow",
34
+ "git show": "allow",
35
+ "git status": "allow",
36
+ },
37
+ read: {
38
+ "*": "allow",
39
+ "*.env": "deny",
40
+ "*.pem": "deny",
41
+ },
42
+ edit: {
43
+ "*": "ask",
44
+ },
45
+ write: {
46
+ "*": "ask",
47
+ },
48
+ };
49
+
50
+ const DEFAULT_CONFIG: GuardConfig = {
51
+ enabled: true,
52
+ matchers: DEFAULT_MATCHERS,
53
+ rules: DEFAULT_RULES,
54
+ };
55
+
56
+ const SAFE_FALLBACK_CONFIG: GuardConfig = {
57
+ enabled: true,
58
+ rules: {},
59
+ };
60
+
61
+ interface LoadedConfigResult {
62
+ config: GuardConfig;
63
+ warning?: string;
64
+ }
65
+
66
+ export function buildEffectiveRules(
67
+ userRules: Rules,
68
+ projectRules: Rules,
69
+ sessionRules: Rules,
70
+ envRules: Rules | undefined,
71
+ ): Rules {
72
+ // Handle the case where rules is a single action (applies to all tools)
73
+ if (typeof userRules === "string" || typeof projectRules === "string" || typeof sessionRules === "string" || typeof envRules === "string") {
74
+ // If any layer is a single action, that wins
75
+ if (typeof envRules === "string") return envRules;
76
+ if (typeof sessionRules === "string") return sessionRules;
77
+ if (typeof projectRules === "string") return projectRules;
78
+ if (typeof userRules === "string") return userRules;
79
+ }
80
+
81
+ // Merge object-based rules
82
+ const merged: Record<string, ToolRules> = { ...DEFAULT_RULES };
83
+
84
+ for (const layer of [userRules, projectRules, sessionRules, envRules]) {
85
+ if (!layer || typeof layer === "string") continue;
86
+ for (const [tool, rules] of Object.entries(layer)) {
87
+ if (typeof rules === "string") {
88
+ merged[tool] = rules;
89
+ } else {
90
+ merged[tool] = { ...merged[tool] as Record<string, Action>, ...rules };
91
+ }
92
+ }
93
+ }
94
+
95
+ return merged;
96
+ }
97
+
98
+ /** Load project-level guard config from .pi/settings.json in the given directory. */
99
+ function loadProjectConfig(cwd: string): LoadedConfigResult | null {
100
+ const projectSettingsPath = path.join(cwd, ".pi", "settings.json");
101
+ if (!fs.existsSync(projectSettingsPath)) {
102
+ return null;
103
+ }
104
+ try {
105
+ const data = fs.readFileSync(projectSettingsPath, "utf-8");
106
+ const parsed = JSON.parse(data);
107
+ const result = getGuardConfigFromSettings(parsed);
108
+ return result;
109
+ } catch {
110
+ return {
111
+ config: { ...SAFE_FALLBACK_CONFIG },
112
+ warning: "Failed to parse project .pi/settings.json; using safe fallback.",
113
+ };
114
+ }
115
+ }
116
+
117
+ export function validateToolRules(input: unknown): { rules: Record<string, Action>; warnings: string[] } {
118
+ const warnings: string[] = [];
119
+ const rules: Record<string, Action> = {};
120
+
121
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
122
+ return { rules, warnings: ['rules must be an object mapping patterns to "allow", "ask", or "deny"'] };
123
+ }
124
+
125
+ for (const [key, value] of Object.entries(input as Record<string, unknown>)) {
126
+ if (typeof key === "string" && key.trim().length > 0 && (value === "allow" || value === "ask" || value === "deny")) {
127
+ rules[key] = value;
128
+ } else {
129
+ warnings.push(`Invalid rule: "${key}" -> "${value}"`);
130
+ }
131
+ }
132
+
133
+ return { rules, warnings };
134
+ }
135
+
136
+ export function validateLoadedGuardConfig(input: unknown): LoadedConfigResult {
137
+ if (!input || typeof input !== "object") {
138
+ return {
139
+ config: { ...SAFE_FALLBACK_CONFIG },
140
+ warning: "Invalid guard config shape; using safe fallback (enabled=true, rules={}).",
141
+ };
142
+ }
143
+
144
+ const cfg = input as Record<string, unknown>;
145
+ const warnings: string[] = [];
146
+
147
+ let enabled = SAFE_FALLBACK_CONFIG.enabled;
148
+ if (typeof cfg.enabled === "boolean") {
149
+ enabled = cfg.enabled;
150
+ } else if (cfg.enabled !== undefined) {
151
+ warnings.push("enabled must be a boolean");
152
+ }
153
+
154
+ let matchers: Matchers | undefined = DEFAULT_MATCHERS;
155
+ if (cfg.matchers !== undefined) {
156
+ if (cfg.matchers && typeof cfg.matchers === "object" && !Array.isArray(cfg.matchers)) {
157
+ const validMatchers: Matchers = {};
158
+ for (const [tool, matcher] of Object.entries(cfg.matchers as Record<string, unknown>)) {
159
+ if (
160
+ matcher &&
161
+ typeof matcher === "object" &&
162
+ typeof (matcher as Record<string, unknown>).param === "string" &&
163
+ ["bash", "glob", "exact"].includes((matcher as Record<string, unknown>).type as string)
164
+ ) {
165
+ validMatchers[tool] = {
166
+ param: (matcher as Record<string, unknown>).param as string,
167
+ type: (matcher as Record<string, unknown>).type as "bash" | "glob" | "exact",
168
+ };
169
+ } else {
170
+ warnings.push(`Invalid matcher for tool "${tool}"`);
171
+ }
172
+ }
173
+ matchers = validMatchers;
174
+ } else {
175
+ warnings.push("matchers must be an object mapping tool names to matcher configs");
176
+ }
177
+ }
178
+
179
+ let rules: Rules = {};
180
+ if (cfg.rules !== undefined) {
181
+ if (typeof cfg.rules === "string" && (cfg.rules === "allow" || cfg.rules === "ask" || cfg.rules === "deny")) {
182
+ rules = cfg.rules;
183
+ } else if (cfg.rules && typeof cfg.rules === "object" && !Array.isArray(cfg.rules)) {
184
+ const validRules: Record<string, ToolRules> = {};
185
+ for (const [tool, toolRules] of Object.entries(cfg.rules as Record<string, unknown>)) {
186
+ if (typeof toolRules === "string" && (toolRules === "allow" || toolRules === "ask" || toolRules === "deny")) {
187
+ validRules[tool] = toolRules;
188
+ } else if (toolRules && typeof toolRules === "object" && !Array.isArray(toolRules)) {
189
+ const { rules: validated, warnings: toolWarnings } = validateToolRules(toolRules);
190
+ validRules[tool] = validated;
191
+ warnings.push(...toolWarnings.map(w => `Tool "${tool}": ${w}`));
192
+ } else {
193
+ warnings.push(`Invalid rules for tool "${tool}"`);
194
+ }
195
+ }
196
+ rules = validRules;
197
+ } else {
198
+ warnings.push('rules must be a single action ("allow"/"ask"/"deny") or an object mapping tool names to rules');
199
+ }
200
+ }
201
+
202
+ if (warnings.length > 0) {
203
+ return {
204
+ config: { enabled, matchers, rules },
205
+ warning: `Invalid guard config fields (${warnings.join("; ")}); using safe values for invalid fields.`,
206
+ };
207
+ }
208
+
209
+ return { config: { enabled, matchers, rules } };
210
+ }
211
+
212
+ export function getGuardConfigFromSettings(input: unknown): LoadedConfigResult {
213
+ if (!input || typeof input !== "object") {
214
+ return { config: DEFAULT_CONFIG };
215
+ }
216
+
217
+ const settings = input as Record<string, unknown>;
218
+
219
+ if (!Object.hasOwn(settings, "guard")) {
220
+ return { config: DEFAULT_CONFIG };
221
+ }
222
+
223
+ return validateLoadedGuardConfig(settings.guard);
224
+ }
225
+
226
+ /** Load environment rules from PI_GUARD env var. */
227
+ function loadEnvRules(): Rules | undefined {
228
+ const env = process.env.PI_GUARD;
229
+ if (!env) return undefined;
230
+
231
+ try {
232
+ const parsed = JSON.parse(env);
233
+ if (typeof parsed === "string" && (parsed === "allow" || parsed === "ask" || parsed === "deny")) {
234
+ return parsed;
235
+ }
236
+ if (typeof parsed === "object" && parsed !== null) {
237
+ // Validate it's a valid rules object
238
+ const result = validateLoadedGuardConfig({ rules: parsed });
239
+ if (result.config.rules) {
240
+ return result.config.rules;
241
+ }
242
+ }
243
+ } catch {
244
+ // Silently ignore invalid env var
245
+ }
246
+
247
+ return undefined;
248
+ }
249
+
250
+ export function loadConfig(): LoadedConfigResult {
251
+ const envRules = loadEnvRules();
252
+
253
+ if (fs.existsSync(SETTINGS_PATH)) {
254
+ try {
255
+ const data = fs.readFileSync(SETTINGS_PATH, "utf-8");
256
+ const parsed = JSON.parse(data);
257
+ const result = getGuardConfigFromSettings(parsed);
258
+
259
+ // Merge env rules if present
260
+ if (envRules) {
261
+ result.config = {
262
+ ...result.config,
263
+ rules: buildEffectiveRules(
264
+ result.config.rules,
265
+ {},
266
+ {},
267
+ envRules,
268
+ ),
269
+ };
270
+ }
271
+
272
+ return result;
273
+ } catch {
274
+ return {
275
+ config: { ...SAFE_FALLBACK_CONFIG, rules: envRules ?? SAFE_FALLBACK_CONFIG.rules },
276
+ warning: "Failed to parse settings.json; using safe fallback (enabled=true, rules={}).",
277
+ };
278
+ }
279
+ }
280
+
281
+ return {
282
+ config: {
283
+ ...DEFAULT_CONFIG,
284
+ rules: envRules ? buildEffectiveRules(DEFAULT_CONFIG.rules, {}, {}, envRules) : DEFAULT_CONFIG.rules,
285
+ },
286
+ };
287
+ }
288
+
289
+ export function saveConfig(config: GuardConfig) {
290
+ try {
291
+ fs.mkdirSync(AGENT_DIR, { recursive: true });
292
+
293
+ let settings: Record<string, unknown> = {};
294
+ if (fs.existsSync(SETTINGS_PATH)) {
295
+ settings = JSON.parse(fs.readFileSync(SETTINGS_PATH, "utf-8"));
296
+ }
297
+
298
+ settings.guard = {
299
+ enabled: config.enabled,
300
+ ...(config.matchers && Object.keys(config.matchers).length > 0 && { matchers: config.matchers }),
301
+ rules: config.rules,
302
+ };
303
+
304
+ fs.writeFileSync(SETTINGS_PATH, JSON.stringify(settings, null, 2), "utf-8");
305
+ } catch (e) {
306
+ console.error("Failed to save guard config to settings.json", e);
307
+ }
308
+ }
309
+
310
+ export { loadProjectConfig, DEFAULT_CONFIG };