kovence-cli 0.0.0-stage → 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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/SECURITY.md +13 -0
- package/nd.js +700 -0
- package/package.json +55 -5
- package/providers.js +530 -0
- package/src/agent/history.js +157 -0
- package/src/agent/project_context.js +136 -0
- package/src/agent/resilience.js +100 -0
- package/src/agent/turn.js +782 -0
- package/src/cli/args.js +171 -0
- package/src/cli/sinks.js +326 -0
- package/src/commands/handlers.js +1280 -0
- package/src/config/memory.js +175 -0
- package/src/config/model_registry.js +123 -0
- package/src/config/paths.js +268 -0
- package/src/config/providers.js +209 -0
- package/src/config/sessions.js +201 -0
- package/src/permissions/engine.js +846 -0
- package/src/permissions/store.js +113 -0
- package/src/settings/schema.js +340 -0
- package/src/settings/store.js +136 -0
- package/src/tools/checkpoints.js +108 -0
- package/src/tools/download.js +513 -0
- package/src/tools/exec.js +155 -0
- package/src/tools/fs_walk.js +165 -0
- package/src/tools/net.js +467 -0
- package/src/tools/patch_git.js +205 -0
- package/src/tools/sudo.js +212 -0
- package/src/tools/tasks.js +127 -0
- package/src/tui/settings_panel.js +223 -0
- package/src/tui/text_width.js +218 -0
- package/src/tui/themes.js +143 -0
- package/store.js +107 -0
- package/tools.js +1267 -0
- package/tui.js +1634 -0
- package/ui.js +394 -0
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const os = require("node:os");
|
|
5
|
+
const path = require("node:path");
|
|
6
|
+
const { loadPermissionRules } = require("./store");
|
|
7
|
+
const { resolvePaths } = require("../config/paths");
|
|
8
|
+
|
|
9
|
+
const READ_TOOLS = new Set([
|
|
10
|
+
"list_dir",
|
|
11
|
+
"glob_files",
|
|
12
|
+
"read_file",
|
|
13
|
+
"search_files",
|
|
14
|
+
"todo_write",
|
|
15
|
+
"web_search",
|
|
16
|
+
"google_search",
|
|
17
|
+
"git_status",
|
|
18
|
+
"git_diff",
|
|
19
|
+
"git_log",
|
|
20
|
+
"ask_user",
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
const NETWORK_READ_TOOLS = new Set(["web_fetch", "web_search", "google_search"]);
|
|
24
|
+
|
|
25
|
+
const FILE_EDIT_TOOLS = new Set(["write_file", "edit_file", "multi_edit", "apply_patch", "move_file", "mkdir"]);
|
|
26
|
+
|
|
27
|
+
const FILE_PATH_TOOLS = new Set([
|
|
28
|
+
"list_dir",
|
|
29
|
+
"glob_files",
|
|
30
|
+
"read_file",
|
|
31
|
+
"search_files",
|
|
32
|
+
"write_file",
|
|
33
|
+
"edit_file",
|
|
34
|
+
"multi_edit",
|
|
35
|
+
"delete_file",
|
|
36
|
+
"download_file",
|
|
37
|
+
"apply_patch",
|
|
38
|
+
"move_file",
|
|
39
|
+
"mkdir",
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
const MEMORY_WRITE_TOOLS = new Set(["save_session_memory", "save_global_memory", "delete_global_memory"]);
|
|
43
|
+
|
|
44
|
+
const PLAN_BLOCKED_TOOLS = new Set([
|
|
45
|
+
...FILE_EDIT_TOOLS,
|
|
46
|
+
"delete_file",
|
|
47
|
+
"download_file",
|
|
48
|
+
...MEMORY_WRITE_TOOLS,
|
|
49
|
+
"undo_checkpoint",
|
|
50
|
+
]);
|
|
51
|
+
|
|
52
|
+
const READ_ONLY_BASE_COMMANDS = new Set([
|
|
53
|
+
"ls",
|
|
54
|
+
"ll",
|
|
55
|
+
"la",
|
|
56
|
+
"cat",
|
|
57
|
+
"head",
|
|
58
|
+
"tail",
|
|
59
|
+
"less",
|
|
60
|
+
"more",
|
|
61
|
+
"grep",
|
|
62
|
+
"egrep",
|
|
63
|
+
"fgrep",
|
|
64
|
+
"rg",
|
|
65
|
+
"ag",
|
|
66
|
+
"fd",
|
|
67
|
+
"tree",
|
|
68
|
+
"pwd",
|
|
69
|
+
"uname",
|
|
70
|
+
"which",
|
|
71
|
+
"type",
|
|
72
|
+
"whoami",
|
|
73
|
+
"id",
|
|
74
|
+
"date",
|
|
75
|
+
"wc",
|
|
76
|
+
"sort",
|
|
77
|
+
"uniq",
|
|
78
|
+
"cut",
|
|
79
|
+
"tr",
|
|
80
|
+
"file",
|
|
81
|
+
"stat",
|
|
82
|
+
"readlink",
|
|
83
|
+
"realpath",
|
|
84
|
+
"basename",
|
|
85
|
+
"dirname",
|
|
86
|
+
"df",
|
|
87
|
+
"du",
|
|
88
|
+
"free",
|
|
89
|
+
"uptime",
|
|
90
|
+
"ps",
|
|
91
|
+
"echo",
|
|
92
|
+
"printf",
|
|
93
|
+
"printenv",
|
|
94
|
+
]);
|
|
95
|
+
|
|
96
|
+
const READ_ONLY_GIT_SUBCOMMANDS = new Set([
|
|
97
|
+
"status",
|
|
98
|
+
"diff",
|
|
99
|
+
"log",
|
|
100
|
+
"show",
|
|
101
|
+
"branch",
|
|
102
|
+
"tag",
|
|
103
|
+
"rev-parse",
|
|
104
|
+
"ls-files",
|
|
105
|
+
"grep",
|
|
106
|
+
"blame",
|
|
107
|
+
"describe",
|
|
108
|
+
"remote",
|
|
109
|
+
]);
|
|
110
|
+
|
|
111
|
+
const TWO_WORD_PREFIX_TOOLS = new Set([
|
|
112
|
+
"git",
|
|
113
|
+
"npm",
|
|
114
|
+
"npx",
|
|
115
|
+
"yarn",
|
|
116
|
+
"pnpm",
|
|
117
|
+
"cargo",
|
|
118
|
+
"docker",
|
|
119
|
+
"kubectl",
|
|
120
|
+
"pip",
|
|
121
|
+
"pip3",
|
|
122
|
+
]);
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Resolve nearest realpath even when target file does not exist yet (catches symlink escapes).
|
|
126
|
+
*/
|
|
127
|
+
function resolveRealWithMissingLeaf(targetPath) {
|
|
128
|
+
const abs = path.resolve(targetPath);
|
|
129
|
+
const suffix = [];
|
|
130
|
+
let cursor = abs;
|
|
131
|
+
while (true) {
|
|
132
|
+
try {
|
|
133
|
+
const real = fs.realpathSync(cursor);
|
|
134
|
+
return suffix.length ? path.join(real, ...suffix.reverse()) : real;
|
|
135
|
+
} catch {
|
|
136
|
+
const parent = path.dirname(cursor);
|
|
137
|
+
if (parent === cursor) return abs;
|
|
138
|
+
suffix.push(path.basename(cursor));
|
|
139
|
+
cursor = parent;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function isWithinDir(targetPath, dirPath) {
|
|
145
|
+
const realTarget = resolveRealWithMissingLeaf(targetPath);
|
|
146
|
+
const realDir = resolveRealWithMissingLeaf(dirPath);
|
|
147
|
+
const rel = path.relative(realDir, realTarget);
|
|
148
|
+
return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function isPathInsideWorkspace(targetPath, workspaceRoot, extraDirs = []) {
|
|
152
|
+
if (!targetPath) return true;
|
|
153
|
+
const dirs = [workspaceRoot, ...(Array.isArray(extraDirs) ? extraDirs : [])].filter(Boolean);
|
|
154
|
+
return dirs.some((dir) => isWithinDir(path.resolve(workspaceRoot, targetPath), dir));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function extractToolPaths(toolName, args, workspaceRoot) {
|
|
158
|
+
const candidates = [];
|
|
159
|
+
if (args?.path) candidates.push(args.path);
|
|
160
|
+
if (args?.file) candidates.push(args.file);
|
|
161
|
+
if (args?.from) candidates.push(args.from);
|
|
162
|
+
if (args?.to) candidates.push(args.to);
|
|
163
|
+
if (args?.destination) candidates.push(args.destination);
|
|
164
|
+
return candidates
|
|
165
|
+
.map((p) => {
|
|
166
|
+
const str = String(p).trim();
|
|
167
|
+
if (!str) return null;
|
|
168
|
+
if (str.startsWith("~/")) return path.join(os.homedir(), str.slice(2));
|
|
169
|
+
return path.resolve(workspaceRoot, str);
|
|
170
|
+
})
|
|
171
|
+
.filter(Boolean);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Quote-aware shell parser splitting compound commands and flagging subshells/redirects.
|
|
176
|
+
*/
|
|
177
|
+
function parseShellCommand(command) {
|
|
178
|
+
const src = String(command || "");
|
|
179
|
+
const segments = [];
|
|
180
|
+
let curTokens = [];
|
|
181
|
+
let curToken = "";
|
|
182
|
+
let inSingle = false;
|
|
183
|
+
let inDouble = false;
|
|
184
|
+
let escaped = false;
|
|
185
|
+
let hasSubshell = false;
|
|
186
|
+
let hasRedirect = false;
|
|
187
|
+
|
|
188
|
+
const pushToken = () => {
|
|
189
|
+
if (curToken.length > 0) {
|
|
190
|
+
curTokens.push(curToken);
|
|
191
|
+
curToken = "";
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
const pushSegment = () => {
|
|
195
|
+
pushToken();
|
|
196
|
+
if (curTokens.length > 0) {
|
|
197
|
+
segments.push(curTokens);
|
|
198
|
+
curTokens = [];
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
for (let i = 0; i < src.length; i++) {
|
|
203
|
+
const ch = src[i];
|
|
204
|
+
const next = src[i + 1] || "";
|
|
205
|
+
|
|
206
|
+
if (escaped) {
|
|
207
|
+
curToken += ch;
|
|
208
|
+
escaped = false;
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
if (inSingle) {
|
|
212
|
+
if (ch === "'") inSingle = false;
|
|
213
|
+
else curToken += ch;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (ch === "\\") {
|
|
217
|
+
escaped = true;
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (inDouble) {
|
|
221
|
+
if (ch === '"') {
|
|
222
|
+
inDouble = false;
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
if ((ch === "$" && next === "(") || ch === "`") {
|
|
226
|
+
hasSubshell = true;
|
|
227
|
+
}
|
|
228
|
+
curToken += ch;
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (ch === "'") {
|
|
233
|
+
inSingle = true;
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
if (ch === '"') {
|
|
237
|
+
inDouble = true;
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if ((ch === "$" && next === "(") || ch === "`" || ch === "(" || ch === ")") {
|
|
241
|
+
hasSubshell = true;
|
|
242
|
+
curToken += ch;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
if ((ch === "<" || ch === ">") && next === "(") {
|
|
246
|
+
hasSubshell = true;
|
|
247
|
+
}
|
|
248
|
+
if (ch === ">" || (ch === "&" && next === ">") || (/\d/.test(ch) && next === ">" && curToken === "")) {
|
|
249
|
+
hasRedirect = true;
|
|
250
|
+
pushToken();
|
|
251
|
+
if (next === ">") i++;
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if ((ch === "&" && next === "&") || (ch === "|" && next === "|")) {
|
|
255
|
+
pushSegment();
|
|
256
|
+
i++;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (ch === ";" || ch === "|" || ch === "\n" || ch === "&") {
|
|
260
|
+
pushSegment();
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (/\s/.test(ch)) {
|
|
264
|
+
pushToken();
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
curToken += ch;
|
|
268
|
+
}
|
|
269
|
+
pushSegment();
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
segments,
|
|
273
|
+
hasSubshell,
|
|
274
|
+
hasRedirect,
|
|
275
|
+
raw: src,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Strip leading VAR=val env assignments or sudo wrapper from a segment's token list.
|
|
281
|
+
*/
|
|
282
|
+
function stripSegmentLead(tokens) {
|
|
283
|
+
let i = 0;
|
|
284
|
+
let usesSudo = false;
|
|
285
|
+
while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i])) {
|
|
286
|
+
i++;
|
|
287
|
+
}
|
|
288
|
+
if (tokens[i] === "sudo") {
|
|
289
|
+
usesSudo = true;
|
|
290
|
+
i++;
|
|
291
|
+
while (i < tokens.length && tokens[i].startsWith("-")) {
|
|
292
|
+
if (tokens[i] === "-u" || tokens[i] === "-g" || tokens[i] === "-p") i += 2;
|
|
293
|
+
else i++;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { cmdTokens: tokens.slice(i), usesSudo };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function getSegmentPrefix(tokens) {
|
|
300
|
+
const { cmdTokens } = stripSegmentLead(tokens);
|
|
301
|
+
if (cmdTokens.length === 0) return "";
|
|
302
|
+
const head = path.basename(cmdTokens[0]);
|
|
303
|
+
if (TWO_WORD_PREFIX_TOOLS.has(head) && cmdTokens[1] && !cmdTokens[1].startsWith("-")) {
|
|
304
|
+
return `${head} ${cmdTokens[1]}`;
|
|
305
|
+
}
|
|
306
|
+
return head;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Verify a shell command is strictly read-only for Plan Mode.
|
|
311
|
+
*/
|
|
312
|
+
function isReadOnlyShellCommand(command) {
|
|
313
|
+
const parsed = parseShellCommand(command);
|
|
314
|
+
if (parsed.segments.length === 0) return false;
|
|
315
|
+
if (parsed.hasSubshell || parsed.hasRedirect) return false;
|
|
316
|
+
|
|
317
|
+
for (const seg of parsed.segments) {
|
|
318
|
+
const { cmdTokens, usesSudo } = stripSegmentLead(seg);
|
|
319
|
+
if (usesSudo || cmdTokens.length === 0) return false;
|
|
320
|
+
const bin = path.basename(cmdTokens[0]);
|
|
321
|
+
const rest = cmdTokens.slice(1);
|
|
322
|
+
|
|
323
|
+
if (bin === "git") {
|
|
324
|
+
const sub = rest.find((t) => !t.startsWith("-"));
|
|
325
|
+
if (!sub || !READ_ONLY_GIT_SUBCOMMANDS.has(sub)) return false;
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (bin === "find") {
|
|
329
|
+
if (rest.some((t) => /^-(delete|exec|execdir|ok|okdir|fls|fprint)/i.test(t))) return false;
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (bin === "sed") {
|
|
333
|
+
if (rest.some((t) => t === "-i" || t.startsWith("-i"))) return false;
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
if (bin === "node") {
|
|
337
|
+
if (rest.length === 1 && (rest[0] === "-v" || rest[0] === "--version")) continue;
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
if (bin === "npm") {
|
|
341
|
+
const sub = rest.find((t) => !t.startsWith("-"));
|
|
342
|
+
if (sub === "ls" || sub === "list" || sub === "view" || rest.includes("--version") || rest.includes("-v")) {
|
|
343
|
+
continue;
|
|
344
|
+
}
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
if (!READ_ONLY_BASE_COMMANDS.has(bin)) return false;
|
|
348
|
+
}
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function normalizeHomePath(p) {
|
|
353
|
+
const s = String(p || "").trim();
|
|
354
|
+
if (s.startsWith("~/")) return path.join(os.homedir(), s.slice(2));
|
|
355
|
+
return path.resolve(s);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
function isProtectedConfigPath(filePath) {
|
|
359
|
+
const home = os.homedir();
|
|
360
|
+
const resolved = resolveRealWithMissingLeaf(normalizeHomePath(filePath));
|
|
361
|
+
const criticalFiles = [".bashrc", ".zshrc", ".profile", ".bash_profile", ".zprofile", ".bash_login"].map((f) =>
|
|
362
|
+
path.join(home, f)
|
|
363
|
+
);
|
|
364
|
+
if (criticalFiles.some((f) => resolved === f)) return "Shell startup config (~/.bashrc / ~/.zshrc / ~/.profile)";
|
|
365
|
+
if (isWithinDir(resolved, path.join(home, ".ssh"))) return "SSH directory (~/.ssh)";
|
|
366
|
+
if (["/etc/passwd", "/etc/shadow", "/etc/sudoers"].includes(resolved) || resolved.startsWith("/etc/sudoers.d/")) {
|
|
367
|
+
return `Critical system file (${resolved})`;
|
|
368
|
+
}
|
|
369
|
+
return null;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function isSecretFilePath(filePath) {
|
|
373
|
+
const resolved = resolveRealWithMissingLeaf(normalizeHomePath(filePath));
|
|
374
|
+
const base = path.basename(resolved).toLowerCase();
|
|
375
|
+
const home = os.homedir();
|
|
376
|
+
|
|
377
|
+
if (/^\.env(\..+)?$/.test(base) && !/^\.env\.(example|sample|template)$/.test(base)) {
|
|
378
|
+
return `Environment secret file (${base})`;
|
|
379
|
+
}
|
|
380
|
+
if (/\.(pem|key|p12|pfx)$/i.test(base) || ["id_rsa", "id_ed25519", "id_ecdsa", "id_dsa"].includes(base)) {
|
|
381
|
+
return `Private key / certificate file (${base})`;
|
|
382
|
+
}
|
|
383
|
+
const sensitiveHomePaths = [
|
|
384
|
+
path.join(home, ".ssh"),
|
|
385
|
+
path.join(home, ".aws", "credentials"),
|
|
386
|
+
path.join(home, ".aws", "config"),
|
|
387
|
+
path.join(home, ".npmrc"),
|
|
388
|
+
path.join(home, ".netrc"),
|
|
389
|
+
path.join(home, ".pypirc"),
|
|
390
|
+
path.join(home, ".docker", "config.json"),
|
|
391
|
+
path.join(home, ".gnupg"),
|
|
392
|
+
];
|
|
393
|
+
for (const sPath of sensitiveHomePaths) {
|
|
394
|
+
if (resolved === sPath || isWithinDir(resolved, sPath)) {
|
|
395
|
+
return `Sensitive credential store (${sPath})`;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* Hard denylist that ALWAYS prompts user confirmation regardless of mode or saved rules.
|
|
403
|
+
* In `auto` mode, only catastrophic system/data-destruction patterns remain on the hard denylist;
|
|
404
|
+
* normal package operations and workspace file inspections are allowed seamlessly.
|
|
405
|
+
*/
|
|
406
|
+
function checkHardDenylist(toolName, args, workspaceRoot, isAutoMode = false) {
|
|
407
|
+
if (FILE_PATH_TOOLS.has(toolName)) {
|
|
408
|
+
const paths = extractToolPaths(toolName, args, workspaceRoot);
|
|
409
|
+
for (const p of paths) {
|
|
410
|
+
if (!isAutoMode) {
|
|
411
|
+
const secretReason = isSecretFilePath(p);
|
|
412
|
+
if (secretReason) return secretReason;
|
|
413
|
+
}
|
|
414
|
+
if (
|
|
415
|
+
toolName !== "read_file" &&
|
|
416
|
+
toolName !== "list_dir" &&
|
|
417
|
+
toolName !== "glob_files" &&
|
|
418
|
+
toolName !== "search_files"
|
|
419
|
+
) {
|
|
420
|
+
const protReason = isProtectedConfigPath(p);
|
|
421
|
+
if (protReason) return protReason;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (toolName !== "run_command") return null;
|
|
427
|
+
const cmd = String(args?.command || "");
|
|
428
|
+
const parsed = parseShellCommand(cmd);
|
|
429
|
+
|
|
430
|
+
// Pipe remote script into shell (curl|sh, wget|bash, etc.)
|
|
431
|
+
if (/\b(curl|wget)\b[\s\S]*\|\s*(sudo\s+)?(sh|bash|zsh|dash|ksh|python|python3)\b/i.test(cmd)) {
|
|
432
|
+
return "Piping remote download directly into a shell/interpreter";
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// Critical shell/ssh/secret targets via shell command
|
|
436
|
+
if (
|
|
437
|
+
/(>>?\s*|tee\s+)(~\/|\$HOME\/)?(\.ssh\/|\.bashrc|\.zshrc|\.profile|\.bash_profile|\/etc\/(passwd|shadow|sudoers))/i.test(
|
|
438
|
+
cmd
|
|
439
|
+
)
|
|
440
|
+
) {
|
|
441
|
+
return "Modifying sensitive ~/.ssh, shell rc, or /etc auth files";
|
|
442
|
+
}
|
|
443
|
+
if (
|
|
444
|
+
!isAutoMode &&
|
|
445
|
+
/(?:^|\s|\/)(\.env(?!\.(?:example|sample|template))|id_rsa|id_ed25519|\.aws\/credentials|\.npmrc|\.netrc)(?:\s|$)/i.test(
|
|
446
|
+
cmd
|
|
447
|
+
)
|
|
448
|
+
) {
|
|
449
|
+
return "Accessing sensitive secret or credential files";
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
for (const seg of parsed.segments) {
|
|
453
|
+
const { cmdTokens, usesSudo } = stripSegmentLead(seg);
|
|
454
|
+
if (cmdTokens.length === 0) continue;
|
|
455
|
+
const bin = path.basename(cmdTokens[0]);
|
|
456
|
+
const argsList = cmdTokens.slice(1);
|
|
457
|
+
|
|
458
|
+
if (bin === "dd" && argsList.some((a) => a.startsWith("of=/dev/"))) {
|
|
459
|
+
return "Raw disk write via dd";
|
|
460
|
+
}
|
|
461
|
+
if (/^mkfs(\.|$)/.test(bin) || bin === "wipefs" || bin === "fdisk" || bin === "parted") {
|
|
462
|
+
return `Filesystem/partition destructive tool (${bin})`;
|
|
463
|
+
}
|
|
464
|
+
if (bin === "chmod") {
|
|
465
|
+
const hasRec = argsList.some((a) => /^-[a-zA-Z]*R/.test(a) || a === "--recursive");
|
|
466
|
+
const has777 = argsList.some((a) => a === "777" || a === "0777" || a === "a+rwx");
|
|
467
|
+
if (hasRec && has777) return "Recursive world-writable chmod 777";
|
|
468
|
+
}
|
|
469
|
+
if (bin === "git") {
|
|
470
|
+
const isPush = argsList.includes("push");
|
|
471
|
+
const isForce = argsList.some((a) => a === "--force" || a === "-f" || a === "--force-with-lease");
|
|
472
|
+
if (isPush && isForce) return "Force pushing git history (git push --force)";
|
|
473
|
+
}
|
|
474
|
+
if (!isAutoMode && usesSudo && ["apt", "apt-get", "dpkg", "yum", "dnf", "pacman", "snap"].includes(bin)) {
|
|
475
|
+
if (
|
|
476
|
+
argsList.some((a) =>
|
|
477
|
+
["remove", "purge", "autoremove", "erase", "-r", "-P", "-R", "--remove", "--purge"].includes(a)
|
|
478
|
+
)
|
|
479
|
+
) {
|
|
480
|
+
return `Sudo package removal (${bin})`;
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
if (bin === "rm") {
|
|
484
|
+
const flags = argsList.filter((a) => a.startsWith("-")).join("");
|
|
485
|
+
const recursive = flags.includes("r") || flags.includes("R") || argsList.includes("--recursive");
|
|
486
|
+
const targets = argsList.filter((a) => !a.startsWith("-"));
|
|
487
|
+
if (recursive) {
|
|
488
|
+
for (const t of targets) {
|
|
489
|
+
if (["/", "/*", "~", "$HOME", "${HOME}", ".", "./", "..", "*"].includes(t)) {
|
|
490
|
+
return `Destructive recursive rm targeting '${t}'`;
|
|
491
|
+
}
|
|
492
|
+
const resolvedTarget = resolveRealWithMissingLeaf(
|
|
493
|
+
normalizeHomePath(path.resolve(workspaceRoot, t))
|
|
494
|
+
);
|
|
495
|
+
const resolvedRoot = resolveRealWithMissingLeaf(workspaceRoot);
|
|
496
|
+
if (resolvedTarget === "/" || resolvedTarget === os.homedir() || resolvedTarget === resolvedRoot) {
|
|
497
|
+
return `Destructive recursive rm targeting protected root '${resolvedTarget}'`;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function globToRegex(pattern) {
|
|
508
|
+
const clean = String(pattern || "").replace(/\\/g, "/");
|
|
509
|
+
let re = "^";
|
|
510
|
+
for (let i = 0; i < clean.length; i++) {
|
|
511
|
+
const ch = clean[i];
|
|
512
|
+
const next = clean[i + 1];
|
|
513
|
+
if (ch === "*" && next === "*") {
|
|
514
|
+
re += ".*";
|
|
515
|
+
i++;
|
|
516
|
+
if (clean[i + 1] === "/") i++;
|
|
517
|
+
} else if (ch === "*") {
|
|
518
|
+
re += "[^/]*";
|
|
519
|
+
} else if (ch === "?") {
|
|
520
|
+
re += "[^/]";
|
|
521
|
+
} else if (".+^${}()|[]\\".includes(ch)) {
|
|
522
|
+
re += "\\" + ch;
|
|
523
|
+
} else {
|
|
524
|
+
re += ch;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
re += "$";
|
|
528
|
+
return new RegExp(re);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function getUrlDomain(rawUrl) {
|
|
532
|
+
try {
|
|
533
|
+
return new URL(String(rawUrl || "")).hostname.toLowerCase();
|
|
534
|
+
} catch {
|
|
535
|
+
return "";
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function doesRuleMatchSegment(rule, segTokens, workspaceRoot) {
|
|
540
|
+
if (rule.tool !== "run_command") return false;
|
|
541
|
+
if (rule.scope === "tool") return true;
|
|
542
|
+
if (rule.scope === "commandPrefix") {
|
|
543
|
+
const { cmdTokens } = stripSegmentLead(segTokens);
|
|
544
|
+
if (cmdTokens.length === 0) return false;
|
|
545
|
+
const bin = path.basename(cmdTokens[0]);
|
|
546
|
+
const normalizedCmd = [bin, ...cmdTokens.slice(1)].join(" ");
|
|
547
|
+
const pat = rule.pattern.trim();
|
|
548
|
+
return normalizedCmd === pat || normalizedCmd.startsWith(pat + " ");
|
|
549
|
+
}
|
|
550
|
+
return false;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function doesRuleMatchTool(rule, toolName, args, workspaceRoot) {
|
|
554
|
+
if (rule.tool !== toolName && rule.tool !== "*") return false;
|
|
555
|
+
if (rule.scope === "tool") return true;
|
|
556
|
+
if (rule.scope === "path") {
|
|
557
|
+
const paths = extractToolPaths(toolName, args, workspaceRoot);
|
|
558
|
+
if (paths.length === 0) return false;
|
|
559
|
+
const matcher = globToRegex(rule.pattern);
|
|
560
|
+
return paths.every((absPath) => {
|
|
561
|
+
const rel = path.relative(workspaceRoot, absPath).replace(/\\/g, "/");
|
|
562
|
+
const normAbs = absPath.replace(/\\/g, "/");
|
|
563
|
+
return matcher.test(rel) || matcher.test(normAbs);
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
if (rule.scope === "domain") {
|
|
567
|
+
const domain = getUrlDomain(args?.url);
|
|
568
|
+
if (!domain) return false;
|
|
569
|
+
const pat = rule.pattern.toLowerCase();
|
|
570
|
+
if (pat.startsWith("*.")) {
|
|
571
|
+
const rootDom = pat.slice(2);
|
|
572
|
+
return domain === rootDom || domain.endsWith("." + rootDom);
|
|
573
|
+
}
|
|
574
|
+
return domain === pat;
|
|
575
|
+
}
|
|
576
|
+
return false;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
function pickHighestPrecedence(matches) {
|
|
580
|
+
if (!matches || matches.length === 0) return null;
|
|
581
|
+
const deny = matches.find((r) => r.action === "deny");
|
|
582
|
+
if (deny) return deny;
|
|
583
|
+
const ask = matches.find((r) => r.action === "ask");
|
|
584
|
+
if (ask) return ask;
|
|
585
|
+
return matches.find((r) => r.action === "allow") || null;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function matchTierRules(rules, toolName, args, workspaceRoot) {
|
|
589
|
+
if (toolName === "run_command") {
|
|
590
|
+
const parsed = parseShellCommand(args?.command || "");
|
|
591
|
+
if (parsed.segments.length === 0) return null;
|
|
592
|
+
|
|
593
|
+
// First check if ANY rule denies/asks on ANY segment
|
|
594
|
+
const segMatchesPerSeg = parsed.segments.map((seg) =>
|
|
595
|
+
rules.filter((r) => doesRuleMatchSegment(r, seg, workspaceRoot))
|
|
596
|
+
);
|
|
597
|
+
const flat = segMatchesPerSeg.flat();
|
|
598
|
+
const denyOrAsk = flat.find((r) => r.action === "deny") || flat.find((r) => r.action === "ask");
|
|
599
|
+
if (denyOrAsk) return denyOrAsk;
|
|
600
|
+
|
|
601
|
+
// To allow a compound command, never permit hidden subshells or output redirects by a simple prefix rule,
|
|
602
|
+
// and EVERY segment must be individually covered by an allow rule!
|
|
603
|
+
const allAllowed =
|
|
604
|
+
!parsed.hasSubshell &&
|
|
605
|
+
!parsed.hasRedirect &&
|
|
606
|
+
segMatchesPerSeg.every((segRules) => segRules.some((r) => r.action === "allow"));
|
|
607
|
+
if (allAllowed) {
|
|
608
|
+
return segMatchesPerSeg.map((sr) => sr.find((r) => r.action === "allow"))[0];
|
|
609
|
+
}
|
|
610
|
+
return null;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
const matches = rules.filter((r) => doesRuleMatchTool(r, toolName, args, workspaceRoot));
|
|
614
|
+
return pickHighestPrecedence(matches);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Evaluate exact tool execution decision: allow | ask | block.
|
|
619
|
+
*/
|
|
620
|
+
function evaluatePermission({
|
|
621
|
+
toolName,
|
|
622
|
+
args = {},
|
|
623
|
+
settings = {},
|
|
624
|
+
workspaceRoot = process.cwd(),
|
|
625
|
+
extraDirs = [],
|
|
626
|
+
sessionRules = [],
|
|
627
|
+
paths = resolvePaths({ cwd: workspaceRoot }),
|
|
628
|
+
}) {
|
|
629
|
+
const agentMode = settings.agentMode || "default";
|
|
630
|
+
const toolPermission = settings.toolPermission || "ask";
|
|
631
|
+
const nonWorkspaceAccess = settings.nonWorkspaceAccess || "ask";
|
|
632
|
+
const isAutoMode = agentMode === "auto" || toolPermission === "always-proceed";
|
|
633
|
+
const isAcceptEditsMode = agentMode === "accept-edits" || toolPermission === "allow-edits";
|
|
634
|
+
|
|
635
|
+
// 1. Plan mode enforcement (code-level, cannot be bypassed by auto or rules)
|
|
636
|
+
if (agentMode === "plan") {
|
|
637
|
+
if (PLAN_BLOCKED_TOOLS.has(toolName)) {
|
|
638
|
+
return {
|
|
639
|
+
decision: "block",
|
|
640
|
+
reason: "Plan mode: mutation blocked. Finish the plan and ask the user to approve.",
|
|
641
|
+
risk: "BLOCKED",
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
if (toolName === "run_command" && !isReadOnlyShellCommand(args?.command || "")) {
|
|
645
|
+
return {
|
|
646
|
+
decision: "block",
|
|
647
|
+
reason: "Plan mode: only read-only commands are allowed. Finish the plan and ask the user to approve.",
|
|
648
|
+
risk: "BLOCKED",
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// 2. Explicit deny rules always block immediately (precedence: deny > ask > allow)
|
|
654
|
+
const projectRules = loadPermissionRules("project", paths);
|
|
655
|
+
const globalRules = loadPermissionRules("global", paths);
|
|
656
|
+
const tiers = [
|
|
657
|
+
{ origin: "session", rules: Array.isArray(sessionRules) ? sessionRules : [] },
|
|
658
|
+
{ origin: "project", rules: projectRules },
|
|
659
|
+
{ origin: "global", rules: globalRules },
|
|
660
|
+
];
|
|
661
|
+
let firstTierMatch = null;
|
|
662
|
+
for (const tier of tiers) {
|
|
663
|
+
if (!tier.rules.length) continue;
|
|
664
|
+
const matched = matchTierRules(tier.rules, toolName, args, workspaceRoot);
|
|
665
|
+
if (matched) {
|
|
666
|
+
if (matched.action === "deny") {
|
|
667
|
+
return {
|
|
668
|
+
decision: "block",
|
|
669
|
+
matchedRule: { ...matched, origin: tier.origin },
|
|
670
|
+
reason: `Blocked by ${tier.origin} rule (${matched.tool}:${matched.pattern || "*"})`,
|
|
671
|
+
risk: "BLOCKED",
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
if (!firstTierMatch) {
|
|
675
|
+
firstTierMatch = { origin: tier.origin, matched };
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// 3. Catastrophic hard denylist asks even in auto mode
|
|
681
|
+
const hardReason = checkHardDenylist(toolName, args, workspaceRoot, isAutoMode);
|
|
682
|
+
if (hardReason) {
|
|
683
|
+
return {
|
|
684
|
+
decision: "ask",
|
|
685
|
+
hardDenied: true,
|
|
686
|
+
reason: `Hard denylist: ${hardReason}`,
|
|
687
|
+
risk: "CRITICAL",
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// 4. Sudo: in 'auto' mode, auto-allow (password is requested at most once per session by runWithSudo);
|
|
692
|
+
// in 'default' and 'accept-edits' modes, confirm the sudo command.
|
|
693
|
+
if (toolName === "run_command" && !isAutoMode) {
|
|
694
|
+
const parsed = parseShellCommand(args?.command || "");
|
|
695
|
+
const hasSudo = parsed.segments.some((seg) => stripSegmentLead(seg).usesSudo);
|
|
696
|
+
if (hasSudo) {
|
|
697
|
+
return {
|
|
698
|
+
decision: "ask",
|
|
699
|
+
requiresSudo: true,
|
|
700
|
+
reason: "sudo command requires confirmation",
|
|
701
|
+
risk: "HIGH",
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
// 5. Non-workspace boundary check (in 'auto' mode, allowed automatically unless explicitly set to 'deny')
|
|
707
|
+
if (FILE_PATH_TOOLS.has(toolName)) {
|
|
708
|
+
const targetPaths = extractToolPaths(toolName, args, workspaceRoot);
|
|
709
|
+
const outside = targetPaths.find((p) => !isPathInsideWorkspace(p, workspaceRoot, extraDirs));
|
|
710
|
+
if (outside) {
|
|
711
|
+
if (nonWorkspaceAccess === "deny") {
|
|
712
|
+
return {
|
|
713
|
+
decision: "block",
|
|
714
|
+
reason: `Non-workspace access denied by policy: ${outside}`,
|
|
715
|
+
risk: "HIGH",
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
if (nonWorkspaceAccess === "ask" && !isAutoMode) {
|
|
719
|
+
return {
|
|
720
|
+
decision: "ask",
|
|
721
|
+
nonWorkspace: true,
|
|
722
|
+
reason: `Path outside workspace: ${outside}`,
|
|
723
|
+
risk: "HIGH",
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// 6. Tier ask / allow rules (session -> project -> global)
|
|
730
|
+
if (firstTierMatch) {
|
|
731
|
+
const { origin, matched } = firstTierMatch;
|
|
732
|
+
if (matched.action === "ask" && !isAutoMode) {
|
|
733
|
+
return {
|
|
734
|
+
decision: "ask",
|
|
735
|
+
matchedRule: { ...matched, origin },
|
|
736
|
+
reason: `Rule requires confirmation (${matched.tool})`,
|
|
737
|
+
risk: "MEDIUM",
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
return {
|
|
741
|
+
decision: "allow",
|
|
742
|
+
matchedRule: { ...matched, origin },
|
|
743
|
+
ruleLabel: `${origin} ${matched.scope}=${matched.pattern || matched.tool}`,
|
|
744
|
+
risk: "LOW",
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// 7. Mode and preset policies
|
|
749
|
+
const isReadOnlyCmd = toolName === "run_command" && isReadOnlyShellCommand(args?.command || "");
|
|
750
|
+
const isRead = READ_TOOLS.has(toolName) || isReadOnlyCmd;
|
|
751
|
+
|
|
752
|
+
if (isAutoMode) {
|
|
753
|
+
return { decision: "allow", risk: isRead ? "LOW" : "MEDIUM" };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
if (READ_TOOLS.has(toolName) || toolName === "web_fetch" || toolName === "save_session_memory") {
|
|
757
|
+
return { decision: "allow", risk: "LOW" };
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
if (isAcceptEditsMode && (FILE_EDIT_TOOLS.has(toolName) || isReadOnlyCmd)) {
|
|
761
|
+
return { decision: "allow", risk: isReadOnlyCmd ? "LOW" : "MEDIUM" };
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
if (isReadOnlyCmd && (agentMode === "plan" || toolPermission === "allow-reads")) {
|
|
765
|
+
return { decision: "allow", risk: "LOW" };
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
return {
|
|
769
|
+
decision: "ask",
|
|
770
|
+
reason: `${toolName} requires confirmation in '${agentMode}' mode`,
|
|
771
|
+
risk: toolName === "delete_file" || toolName === "run_command" ? "HIGH" : "MEDIUM",
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/**
|
|
776
|
+
* Compute default narrowest rule suggestion for [s]/[A] approval scopes.
|
|
777
|
+
*/
|
|
778
|
+
function buildSuggestedRules(toolName, args = {}, workspaceRoot = process.cwd()) {
|
|
779
|
+
const suggestions = [];
|
|
780
|
+
if (toolName === "run_command") {
|
|
781
|
+
const parsed = parseShellCommand(args?.command || "");
|
|
782
|
+
const prefixes = Array.from(new Set(parsed.segments.map(getSegmentPrefix).filter(Boolean)));
|
|
783
|
+
if (prefixes.length === 1 && !parsed.hasSubshell && !parsed.hasRedirect) {
|
|
784
|
+
suggestions.push({
|
|
785
|
+
label: `command prefix '${prefixes[0]}'`,
|
|
786
|
+
rule: { action: "allow", tool: "run_command", scope: "commandPrefix", pattern: prefixes[0] },
|
|
787
|
+
});
|
|
788
|
+
}
|
|
789
|
+
suggestions.push({
|
|
790
|
+
label: `all run_command calls`,
|
|
791
|
+
rule: { action: "allow", tool: "run_command", scope: "tool", pattern: "" },
|
|
792
|
+
});
|
|
793
|
+
return suggestions;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
if (FILE_PATH_TOOLS.has(toolName)) {
|
|
797
|
+
const target = args?.path || args?.file || args?.destination;
|
|
798
|
+
if (target) {
|
|
799
|
+
const abs = path.resolve(workspaceRoot, String(target));
|
|
800
|
+
const relDir = path.relative(workspaceRoot, path.dirname(abs)).replace(/\\/g, "/");
|
|
801
|
+
const dirGlob =
|
|
802
|
+
relDir && !relDir.startsWith("..")
|
|
803
|
+
? `${relDir}/**`
|
|
804
|
+
: path.relative(workspaceRoot, abs).replace(/\\/g, "/") || abs;
|
|
805
|
+
suggestions.push({
|
|
806
|
+
label: `path '${dirGlob}' for ${toolName}`,
|
|
807
|
+
rule: { action: "allow", tool: toolName, scope: "path", pattern: dirGlob },
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
if (toolName === "web_fetch" || toolName === "download_file") {
|
|
813
|
+
const domain = getUrlDomain(args?.url);
|
|
814
|
+
if (domain) {
|
|
815
|
+
suggestions.push({
|
|
816
|
+
label: `domain '${domain}' for ${toolName}`,
|
|
817
|
+
rule: { action: "allow", tool: toolName, scope: "domain", pattern: domain },
|
|
818
|
+
});
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
suggestions.push({
|
|
823
|
+
label: `tool '${toolName}'`,
|
|
824
|
+
rule: { action: "allow", tool: toolName, scope: "tool", pattern: "" },
|
|
825
|
+
});
|
|
826
|
+
return suggestions;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
module.exports = {
|
|
830
|
+
READ_TOOLS,
|
|
831
|
+
NETWORK_READ_TOOLS,
|
|
832
|
+
FILE_EDIT_TOOLS,
|
|
833
|
+
FILE_PATH_TOOLS,
|
|
834
|
+
MEMORY_WRITE_TOOLS,
|
|
835
|
+
PLAN_BLOCKED_TOOLS,
|
|
836
|
+
parseShellCommand,
|
|
837
|
+
getSegmentPrefix,
|
|
838
|
+
isReadOnlyShellCommand,
|
|
839
|
+
isPathInsideWorkspace,
|
|
840
|
+
resolveRealWithMissingLeaf,
|
|
841
|
+
isProtectedConfigPath,
|
|
842
|
+
isSecretFilePath,
|
|
843
|
+
checkHardDenylist,
|
|
844
|
+
evaluatePermission,
|
|
845
|
+
buildSuggestedRules,
|
|
846
|
+
};
|