-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecurity-guard.ts
More file actions
483 lines (418 loc) · 13.7 KB
/
Copy pathsecurity-guard.ts
File metadata and controls
483 lines (418 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/**
* Security Guard Extension
*
* Protects against destructive operations, sensitive file writes, and reads
* through a configurable TOML-like configuration file.
*
* Configuration: ~/.pi/agent/security-guard.toml
* An example config is written to ~/.pi/agent/security-guard.toml.example
* on first load if it doesn't already exist.
*/
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
const DEBUG = false; // Set to true for verbose logging
type Action = "prompt" | "block" | "allow";
interface SecurityRule {
pattern: string;
action: Action;
}
interface SecurityRules {
operations: SecurityRule[];
writes: SecurityRule[];
reads: SecurityRule[];
}
const DEFAULT_RULES: SecurityRules = {
operations: [
{ pattern: "rm -rf", action: "prompt" },
{ pattern: "sudo", action: "prompt" },
],
writes: [
{ pattern: ".env", action: "block" },
{ pattern: "~/.ssh", action: "block" },
],
reads: [
{ pattern: "~/.ssh", action: "block" },
{ pattern: "~/.aws/credentials", action: "prompt" },
],
};
function getConfigPath(): string {
const piDir =
process.env.PI_CODING_AGENT_DIR ||
path.join(os.homedir(), ".pi", "agent");
return path.join(piDir, "security-guard.toml");
}
function parseConfigFile(filePath: string): SecurityRules | null {
try {
if (!fs.existsSync(filePath)) {
return null;
}
const content = fs.readFileSync(filePath, "utf-8");
const lines = content.split("\n");
const rules: SecurityRules = {
operations: [],
writes: [],
reads: [],
};
let currentSection: "operations" | "writes" | "reads" | null = null;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Skip empty lines and comments
if (line === "" || line.startsWith("#")) {
continue;
}
// Check for section headers
if (line === "[operations]") {
currentSection = "operations";
continue;
} else if (line === "[writes]") {
currentSection = "writes";
continue;
} else if (line === "[reads]") {
currentSection = "reads";
continue;
}
// Parse rule line: pattern = action
// Split on last '=' to handle patterns containing '=' characters
if (currentSection) {
const lastEqualIndex = line.lastIndexOf("=");
if (lastEqualIndex > 0) {
const pattern = line.substring(0, lastEqualIndex).trim();
const action = line.substring(lastEqualIndex + 1).trim() as Action;
if (action !== "prompt" && action !== "block" && action !== "allow") {
console.warn(
`[security-guard] Invalid action "${action}" on line ${i + 1}, skipping`
);
continue;
}
rules[currentSection].push({ pattern, action });
} else {
console.warn(
`[security-guard] Could not parse line ${i + 1}: ${line}`
);
}
}
}
return rules;
} catch (error) {
console.error("[security-guard] Error reading config file:", error);
return null;
}
}
function loadRules(): SecurityRules {
const configPath = getConfigPath();
const parsed = parseConfigFile(configPath);
if (parsed) {
// Merge with defaults for any missing sections
return {
operations:
parsed.operations.length > 0
? parsed.operations
: DEFAULT_RULES.operations,
writes:
parsed.writes.length > 0 ? parsed.writes : DEFAULT_RULES.writes,
reads: parsed.reads.length > 0 ? parsed.reads : DEFAULT_RULES.reads,
};
}
return DEFAULT_RULES;
}
function expandTilde(pattern: string): string {
if (pattern.startsWith("~/")) {
return path.join(os.homedir(), pattern.slice(2));
}
return pattern;
}
function matchesPattern(text: string, rule: SecurityRule): boolean {
if (text.includes(rule.pattern)) {
return true;
}
// If pattern starts with ~, also check expanded version
if (rule.pattern.startsWith("~")) {
const expanded = expandTilde(rule.pattern);
if (text.includes(expanded)) {
return true;
}
}
return false;
}
/**
* Highlights the matched pattern so it's easy to spot (e.g. a nested "rm -rf")
* in a long command. Checks both the literal pattern and, for ~ paths, the
* expanded home path.
*
* If a `colorize` function is provided (e.g. ctx.ui.theme.fg bound to a color),
* the *entire command segment* containing the match is colored — not just the
* trigger pattern — so the command and its arguments stand out. Segments are
* split on shell separators (&&, ||, |, ;, newline) so neighboring commands
* stay uncolored. The whole colored segment is wrapped in »« markers so the
* command and its arguments are clearly delimited even without color. Each
* colored span is inline (no newlines), so per-line SGR resets in the TUI
* won't bleed across lines.
*/
function highlightMatch(
text: string,
rule: SecurityRule,
colorize?: (s: string) => string
): string {
const needles = [rule.pattern];
if (rule.pattern.startsWith("~")) {
needles.push(expandTilde(rule.pattern));
}
// Highlight the longest matching needle present in the text.
const needle = needles
.filter((n) => n.length > 0 && text.includes(n))
.sort((a, b) => b.length - a.length)[0];
if (!needle) {
return text;
}
const mark = (s: string) => s.split(needle).join(`»${needle}«`);
// Without color, just mark the trigger pattern.
if (!colorize) {
return mark(text);
}
// With color, split into command segments (keeping separators) and color
// any whole segment that contains the trigger, wrapping the command and its
// arguments in »« markers (placed inside any surrounding whitespace).
const separators = new Set(["&&", "||", "|", ";", "\n"]);
const parts = text.split(/(&&|\|\||;|\||\n)/);
return parts
.map((part) => {
if (separators.has(part) || !part.includes(needle)) {
return part;
}
const m = part.match(/^(\s*)([\s\S]*?)(\s*)$/);
const [, lead, core, trail] = m ?? ["", "", part, ""];
return `${lead}${colorize(`»${core}«`)}${trail}`;
})
.join("");
}
function findMatchingRule(
text: string,
rules: SecurityRule[]
): SecurityRule | null {
// Collect all matching rules and return the most specific one
// (longest pattern). This allows narrow "allow" exceptions to
// override broader "block" rules, e.g.:
// > /dev/ = block
// > /dev/null = allow
let best: SecurityRule | null = null;
for (const rule of rules) {
if (matchesPattern(text, rule)) {
if (best === null || rule.pattern.length > best.pattern.length) {
best = rule;
}
}
}
return best;
}
function ensureExampleConfig() {
const piDir =
process.env.PI_CODING_AGENT_DIR ||
path.join(os.homedir(), ".pi", "agent");
const examplePath = path.join(piDir, "security-guard.toml.example");
if (!fs.existsSync(examplePath)) {
const exampleContent = `# Security Guard Configuration
#
# This extension protects against destructive operations, sensitive file writes,
# and sensitive file reads. Each rule has a pattern and an action.
#
# Actions:
# prompt - Ask for user confirmation before allowing the operation
# block - Immediately block the operation without prompting
# allow - Explicitly allow (use to create exceptions to broader rules)
#
# Patterns use simple substring matching. For paths starting with ~/, both the
# literal pattern and the expanded home directory path are checked.
#
# Copy this file to security-guard.toml and customize for your needs.
[operations]
# Bash commands to guard against
rm -rf = prompt
sudo = prompt
dd if= = block
mkfs = block
> /dev/ = block
> /dev/null = allow
[writes]
# File paths to protect from write/edit operations
.env = block
~/.ssh = block
~/.aws = block
/etc/ = block
~/.bash_history = prompt
[reads]
# File paths to protect from read operations
~/.ssh = block
~/.aws/credentials = prompt
~/.gnupg = block
`;
try {
fs.writeFileSync(examplePath, exampleContent, "utf-8");
} catch (error) {
console.error(
"[security-guard] Failed to create example config:",
error
);
}
}
}
export default function (pi: ExtensionAPI) {
ensureExampleConfig();
// Rules are loaded on initialization. When /reload is called,
// pi re-initializes this extension, which loads fresh rules.
const rules = loadRules();
pi.on("session_start", async (_event, ctx) => {
const configPath = getConfigPath();
const configExists = fs.existsSync(configPath);
if (configExists) {
const opCount = rules.operations.length;
const writeCount = rules.writes.length;
const readCount = rules.reads.length;
ctx.ui.notify(
`Security guard loaded: ${opCount} operations, ${writeCount} writes, ${readCount} reads`,
"info"
);
} else {
ctx.ui.notify(
"Security guard using defaults (no config file found)",
"info"
);
}
});
pi.on("tool_call", async (event, ctx) => {
// Handle bash commands
if (event.toolName === "bash") {
const command = event.input.command as string;
const matchedRule = findMatchingRule(command, rules.operations);
if (matchedRule) {
if (DEBUG) {
console.log(
`[security-guard] Matched bash command: "${command}" -> ${matchedRule.action}`
);
}
if (matchedRule.action === "allow") {
return undefined;
}
if (matchedRule.action === "block") {
if (ctx.hasUI) {
ctx.ui.notify(
`Blocked: bash command contains "${matchedRule.pattern}"`,
"warning"
);
}
return {
block: true,
reason: `Blocked by security-guard: pattern "${matchedRule.pattern}"`,
};
}
if (matchedRule.action === "prompt") {
if (!ctx.hasUI) {
return {
block: true,
reason:
"Security check required but no UI available for confirmation",
};
}
const choice = await ctx.ui.select(
`⚠️ Security check: Command contains "${matchedRule.pattern}"\n\nCommand: ${highlightMatch(command, matchedRule, (s) => ctx.ui.theme.fg("error", s))}\n\nAllow?`,
["Allow", "Deny"]
);
if (choice !== "Allow") {
ctx.ui.notify(`Denied: bash command "${command}"`, "warning");
return { block: true, reason: "Denied by user" };
}
}
}
}
// Handle write and edit operations
if (event.toolName === "write" || event.toolName === "edit") {
const filePath = event.input.path as string;
const matchedRule = findMatchingRule(filePath, rules.writes);
if (matchedRule) {
if (DEBUG) {
console.log(
`[security-guard] Matched write path: "${filePath}" -> ${matchedRule.action}`
);
}
if (matchedRule.action === "allow") {
return undefined;
}
if (matchedRule.action === "block") {
if (ctx.hasUI) {
ctx.ui.notify(
`Blocked: write to "${filePath}" (pattern: ${matchedRule.pattern})`,
"warning"
);
}
return {
block: true,
reason: `Blocked by security-guard: pattern "${matchedRule.pattern}"`,
};
}
if (matchedRule.action === "prompt") {
if (!ctx.hasUI) {
return {
block: true,
reason:
"Security check required but no UI available for confirmation",
};
}
const choice = await ctx.ui.select(
`⚠️ Security check: Writing to file matching "${matchedRule.pattern}"\n\nPath: ${highlightMatch(filePath, matchedRule, (s) => ctx.ui.theme.fg("error", s))}\n\nAllow?`,
["Allow", "Deny"]
);
if (choice !== "Allow") {
ctx.ui.notify(`Denied: write to "${filePath}"`, "warning");
return { block: true, reason: "Denied by user" };
}
}
}
}
// Handle read operations
if (event.toolName === "read") {
const filePath = event.input.path as string;
const matchedRule = findMatchingRule(filePath, rules.reads);
if (matchedRule) {
if (DEBUG) {
console.log(
`[security-guard] Matched read path: "${filePath}" -> ${matchedRule.action}`
);
}
if (matchedRule.action === "allow") {
return undefined;
}
if (matchedRule.action === "block") {
if (ctx.hasUI) {
ctx.ui.notify(
`Blocked: read from "${filePath}" (pattern: ${matchedRule.pattern})`,
"warning"
);
}
return {
block: true,
reason: `Blocked by security-guard: pattern "${matchedRule.pattern}"`,
};
}
if (matchedRule.action === "prompt") {
if (!ctx.hasUI) {
return {
block: true,
reason:
"Security check required but no UI available for confirmation",
};
}
const choice = await ctx.ui.select(
`⚠️ Security check: Reading file matching "${matchedRule.pattern}"\n\nPath: ${highlightMatch(filePath, matchedRule, (s) => ctx.ui.theme.fg("error", s))}\n\nAllow?`,
["Allow", "Deny"]
);
if (choice !== "Allow") {
ctx.ui.notify(`Denied: read from "${filePath}"`, "warning");
return { block: true, reason: "Denied by user" };
}
}
}
}
return undefined;
});
}