@operad-io/access-match 0.0.0-stage → 0.0.1
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 +165 -2
- package/package.json +21 -4
- package/src/command.ts +301 -0
- package/src/index.ts +661 -0
- package/src/readonly.ts +66 -0
- package/src/summary.ts +196 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The access profile matcher. `README.md` holds the tables the tests follow.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { posix } from "node:path";
|
|
7
|
+
export { isReadOnlyCommand } from "./readonly.ts";
|
|
8
|
+
export { COMMAND_SUMMARY_CHARS, SUMMARY_CHARS, COMMAND_NOT_SHOWN, REFUSED_IN_LOG, summarizeCall, firstErrorLine, messageSummary, secretValuesOf, type SummaryOptions } from "./summary.ts";
|
|
9
|
+
import { isReadOnlyCommand } from "./readonly.ts";
|
|
10
|
+
import { findDenied, inlineFormOf, parseRule, scan, type Part, type Rule } from "./command.ts";
|
|
11
|
+
|
|
12
|
+
/** A one-time permission for the exact call a person was asked about. */
|
|
13
|
+
export interface AccessGrant {
|
|
14
|
+
readonly waitId: string;
|
|
15
|
+
readonly kind: "command" | "path";
|
|
16
|
+
readonly value: string;
|
|
17
|
+
/** The tool the person approved; a path grant covers that tool only. */
|
|
18
|
+
readonly tool?: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A call a person allowed always, from the access profile's user layer. A
|
|
23
|
+
* command entry is the exact command text and its working directory; a path
|
|
24
|
+
* entry is the tool, the path and the working directory
|
|
25
|
+
* (`operad-sandbox.md` decisions 4 and 11).
|
|
26
|
+
*/
|
|
27
|
+
export interface AlwaysAllowEntry {
|
|
28
|
+
readonly kind: "command" | "path";
|
|
29
|
+
readonly value: string;
|
|
30
|
+
readonly cwd: string;
|
|
31
|
+
/** The tool a path entry names; absent for a command entry. */
|
|
32
|
+
readonly tool?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface AccessProfile {
|
|
36
|
+
readonly denyPaths?: readonly string[] | undefined;
|
|
37
|
+
readonly denyCommands?: readonly string[] | undefined;
|
|
38
|
+
/** Command rules in the shape of `denyCommands`; a match asks a person instead of refusing. */
|
|
39
|
+
readonly askCommands?: readonly string[] | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* Paths a write asks about (`~/.zshrc`, `~/.*profile`): `*` matches within one
|
|
42
|
+
* path segment, and a path under a match counts. Judged for the `write` and
|
|
43
|
+
* `edit` tools, and for a `bash` redirect (`>`, `>>`) to such a path.
|
|
44
|
+
*/
|
|
45
|
+
readonly askPaths?: readonly string[] | undefined;
|
|
46
|
+
/**
|
|
47
|
+
* The working directory is read-only: a write there (the `write` and `edit`
|
|
48
|
+
* tools, a `bash` redirect) asks, as if the directory were in `askPaths`; a
|
|
49
|
+
* `bash` command asks unless `isReadOnlyCommand` says it only reads.
|
|
50
|
+
* Deny wins over it.
|
|
51
|
+
*/
|
|
52
|
+
readonly readOnly?: boolean | undefined;
|
|
53
|
+
/**
|
|
54
|
+
* Directories the agent may read although `denyPaths` covers them (an
|
|
55
|
+
* ancestor of one is denied): a read tool (`read`, `grep`, `find`, `ls`) or a
|
|
56
|
+
* `bash` command that only reads may touch a path under one. Writes there ask,
|
|
57
|
+
* and every other denied path stays denied.
|
|
58
|
+
*/
|
|
59
|
+
readonly readPaths?: readonly string[] | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* The MCP tools that run without asking, as `<server>.<tool>` or `<server>.*`.
|
|
62
|
+
* Having the field at all (even empty) puts MCP tools under the profile: a tool
|
|
63
|
+
* not listed counts as a write and asks (`operad-sandbox.md` decision 9).
|
|
64
|
+
*/
|
|
65
|
+
readonly allowMcp?: readonly string[] | undefined;
|
|
66
|
+
/** Permissions not yet used; the caller uses one up before it lets a call through. */
|
|
67
|
+
readonly grants?: readonly AccessGrant[] | undefined;
|
|
68
|
+
/**
|
|
69
|
+
* Calls a person answered `allow_always` for: they run without asking, and
|
|
70
|
+
* only after every deny passed. The harness leaves them out in a background
|
|
71
|
+
* run (`operad-sandbox.md` decisions 8 and 11).
|
|
72
|
+
*/
|
|
73
|
+
readonly alwaysAllow?: readonly AlwaysAllowEntry[] | undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface ToolCall {
|
|
77
|
+
readonly tool: string;
|
|
78
|
+
readonly input: Readonly<Record<string, unknown>>;
|
|
79
|
+
readonly cwd: string;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* What the profile says about one call. The precedence is fixed: a deny wins
|
|
84
|
+
* over an ask, and an ask wins over an allow. So a call that matches
|
|
85
|
+
* `denyCommands` or `denyPaths` anywhere is refused whatever `askCommands` or
|
|
86
|
+
* `askPaths` say; a call that matches only those asks; every other call is
|
|
87
|
+
* allowed. A caller that does not know `ask` reads it as a refusal
|
|
88
|
+
* (`allow: false`), never as a pass.
|
|
89
|
+
*/
|
|
90
|
+
export type Verdict =
|
|
91
|
+
| { readonly allow: true; readonly ask?: undefined }
|
|
92
|
+
| {
|
|
93
|
+
readonly allow: false;
|
|
94
|
+
readonly ask?: undefined;
|
|
95
|
+
readonly reason: string;
|
|
96
|
+
/** The profile rule that refused, as the profile wrote it; never part of the call. */
|
|
97
|
+
readonly rule?: string;
|
|
98
|
+
}
|
|
99
|
+
| {
|
|
100
|
+
readonly allow: false;
|
|
101
|
+
readonly ask: true;
|
|
102
|
+
readonly reason: string;
|
|
103
|
+
/** The `askCommands` or `askPaths` rule that matched, or `inline code` when the command hides what it runs. */
|
|
104
|
+
readonly rule: string;
|
|
105
|
+
/**
|
|
106
|
+
* What a person is asked about: the whole command of a `bash` call, or the
|
|
107
|
+
* path as the call wrote it with the `tool` that writes it.
|
|
108
|
+
*/
|
|
109
|
+
readonly kind: "command" | "path";
|
|
110
|
+
readonly value: string;
|
|
111
|
+
readonly tool?: string;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
export interface MatchOptions {
|
|
115
|
+
/** What `~` means; defaults to the user's home directory. */
|
|
116
|
+
readonly home?: string | undefined;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export type ProfileRead =
|
|
120
|
+
| { readonly ok: true; readonly profile: AccessProfile }
|
|
121
|
+
| { readonly ok: false; readonly message: string };
|
|
122
|
+
|
|
123
|
+
/** Reads the fields the matcher uses from an untrusted object. */
|
|
124
|
+
export function readProfile(value: unknown): ProfileRead {
|
|
125
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
126
|
+
return { ok: false, message: "the access profile must be an object" };
|
|
127
|
+
}
|
|
128
|
+
const found: { denyPaths?: string[]; denyCommands?: string[]; askCommands?: string[]; askPaths?: string[]; readPaths?: string[]; allowMcp?: string[]; readOnly?: boolean; grants?: AccessGrant[]; alwaysAllow?: AlwaysAllowEntry[] } = {};
|
|
129
|
+
const readOnly: unknown = Reflect.get(value, "readOnly");
|
|
130
|
+
if (readOnly !== undefined) {
|
|
131
|
+
if (typeof readOnly !== "boolean") return { ok: false, message: "readOnly must be true or false" };
|
|
132
|
+
found.readOnly = readOnly;
|
|
133
|
+
}
|
|
134
|
+
for (const field of ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "allowMcp"] as const) {
|
|
135
|
+
const entry: unknown = Reflect.get(value, field);
|
|
136
|
+
if (entry === undefined) continue;
|
|
137
|
+
if (!Array.isArray(entry) || !entry.every((item): item is string => typeof item === "string")) {
|
|
138
|
+
return { ok: false, message: `${field} must be an array of strings` };
|
|
139
|
+
}
|
|
140
|
+
found[field] = entry;
|
|
141
|
+
}
|
|
142
|
+
const alwaysAllow: unknown = Reflect.get(value, "alwaysAllow");
|
|
143
|
+
if (alwaysAllow !== undefined) {
|
|
144
|
+
if (!Array.isArray(alwaysAllow)) return { ok: false, message: "alwaysAllow must be an array" };
|
|
145
|
+
const read: AlwaysAllowEntry[] = [];
|
|
146
|
+
for (const entry of alwaysAllow) {
|
|
147
|
+
if (typeof entry !== "object" || entry === null) {
|
|
148
|
+
return { ok: false, message: "each alwaysAllow entry must be an object" };
|
|
149
|
+
}
|
|
150
|
+
const kind: unknown = Reflect.get(entry, "kind");
|
|
151
|
+
const text: unknown = Reflect.get(entry, "value");
|
|
152
|
+
const cwd: unknown = Reflect.get(entry, "cwd");
|
|
153
|
+
const tool: unknown = Reflect.get(entry, "tool");
|
|
154
|
+
if ((kind !== "command" && kind !== "path") || typeof text !== "string" || text.length === 0) {
|
|
155
|
+
return { ok: false, message: "each alwaysAllow entry needs a kind (command or path) and a value" };
|
|
156
|
+
}
|
|
157
|
+
if (typeof cwd !== "string" || cwd.length === 0) {
|
|
158
|
+
return { ok: false, message: "each alwaysAllow entry needs the working directory it was allowed in" };
|
|
159
|
+
}
|
|
160
|
+
if (kind === "path" && (typeof tool !== "string" || tool.length === 0)) {
|
|
161
|
+
return { ok: false, message: "an alwaysAllow path entry needs the tool it was allowed for" };
|
|
162
|
+
}
|
|
163
|
+
read.push({
|
|
164
|
+
kind,
|
|
165
|
+
value: text,
|
|
166
|
+
cwd,
|
|
167
|
+
...(kind === "path" ? { tool: tool as string } : {}),
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
found.alwaysAllow = read;
|
|
171
|
+
}
|
|
172
|
+
const grants: unknown = Reflect.get(value, "grants");
|
|
173
|
+
if (grants !== undefined) {
|
|
174
|
+
if (!Array.isArray(grants)) return { ok: false, message: "grants must be an array" };
|
|
175
|
+
const read: AccessGrant[] = [];
|
|
176
|
+
for (const grant of grants) {
|
|
177
|
+
if (typeof grant !== "object" || grant === null) {
|
|
178
|
+
return { ok: false, message: "each grant must be an object" };
|
|
179
|
+
}
|
|
180
|
+
const waitId: unknown = Reflect.get(grant, "waitId");
|
|
181
|
+
const kind: unknown = Reflect.get(grant, "kind");
|
|
182
|
+
const text: unknown = Reflect.get(grant, "value");
|
|
183
|
+
if (
|
|
184
|
+
typeof waitId !== "string" ||
|
|
185
|
+
(kind !== "command" && kind !== "path") ||
|
|
186
|
+
typeof text !== "string"
|
|
187
|
+
) {
|
|
188
|
+
return { ok: false, message: "each grant needs a waitId, a kind (command or path) and a value" };
|
|
189
|
+
}
|
|
190
|
+
const tool: unknown = Reflect.get(grant, "tool");
|
|
191
|
+
if (tool !== undefined && typeof tool !== "string") {
|
|
192
|
+
return { ok: false, message: "a grant's tool must be a string" };
|
|
193
|
+
}
|
|
194
|
+
read.push({ waitId, kind, value: text, ...(tool === undefined ? {} : { tool }) });
|
|
195
|
+
}
|
|
196
|
+
found.grants = read;
|
|
197
|
+
}
|
|
198
|
+
return { ok: true, profile: found };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const ALLOW: Verdict = { allow: true };
|
|
202
|
+
|
|
203
|
+
function normalise(path: string, cwd: string, home: string): string {
|
|
204
|
+
let expanded = path;
|
|
205
|
+
if (path === "~") expanded = home;
|
|
206
|
+
else if (path.startsWith("~/")) expanded = `${home}${path.slice(1)}`;
|
|
207
|
+
return posix.resolve(cwd, expanded);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function isUnder(path: string, entry: string): boolean {
|
|
211
|
+
return path === entry || path.startsWith(entry === "/" ? "/" : `${entry}/`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Whether a person allowed this exact call always; never a deny, and never another cwd. */
|
|
215
|
+
function alwaysAllowed(profile: AccessProfile, call: ToolCall): boolean {
|
|
216
|
+
for (const entry of profile.alwaysAllow ?? []) {
|
|
217
|
+
if (entry.cwd !== call.cwd) continue;
|
|
218
|
+
if (entry.kind === "command") {
|
|
219
|
+
if (call.tool === "bash" && call.input["command"] === entry.value) return true;
|
|
220
|
+
if (call.tool === MCP_TOOL) {
|
|
221
|
+
const server: unknown = call.input["server"];
|
|
222
|
+
const tool: unknown = call.input["tool"];
|
|
223
|
+
if (typeof server === "string" && typeof tool === "string" && mcpCallValue(server, tool) === entry.value) {
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
continue;
|
|
228
|
+
}
|
|
229
|
+
if (call.tool !== entry.tool) continue;
|
|
230
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
231
|
+
if (typeof path === "string" && path === entry.value) return true;
|
|
232
|
+
}
|
|
233
|
+
return false;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
interface Denied {
|
|
237
|
+
readonly entries: ReadonlyArray<{ readonly written: string; readonly path: string }>;
|
|
238
|
+
readonly cwd: string;
|
|
239
|
+
readonly home: string;
|
|
240
|
+
/** Normalised directories this call may read through a deny (`readPaths`). */
|
|
241
|
+
readonly readable: readonly string[];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function checkPath(denied: Denied, path: string, cwd: string = denied.cwd, written: string = path): Verdict {
|
|
245
|
+
const normal = normalise(path, cwd, denied.home);
|
|
246
|
+
if (denied.readable.some((entry) => isUnder(normal, entry))) return ALLOW;
|
|
247
|
+
for (const entry of denied.entries) {
|
|
248
|
+
if (isUnder(normal, entry.path)) {
|
|
249
|
+
return { allow: false, reason: `path "${written}" is under denyPaths entry "${entry.written}"`, rule: entry.written };
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
return ALLOW;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const PATH_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls"]);
|
|
256
|
+
const REDIRECT = /^(?:\d*|&)(?:>>|>|<)&?/;
|
|
257
|
+
|
|
258
|
+
function pathLike(word: string): boolean {
|
|
259
|
+
return word.includes("/") || word.startsWith("~") || word.startsWith(".");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** The readings of one word that may be a path: itself, minus a redirect, after `=`. */
|
|
263
|
+
function readings(word: string, home: string): string[] {
|
|
264
|
+
const unredirected = word.replace(REDIRECT, "");
|
|
265
|
+
const found = [word, unredirected];
|
|
266
|
+
const equals = unredirected.indexOf("=");
|
|
267
|
+
if (equals !== -1) found.push(unredirected.slice(equals + 1));
|
|
268
|
+
return found.filter(
|
|
269
|
+
(reading, index) => reading.length > 0 && found.indexOf(reading) === index && pathLike(expandWord(reading, home).text),
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
interface Expanded {
|
|
274
|
+
readonly text: string;
|
|
275
|
+
/** Still holds an expansion the matcher cannot resolve. */
|
|
276
|
+
readonly unresolved: boolean;
|
|
277
|
+
/** A simple glob character (`*`, `?`, `[`) in any component. */
|
|
278
|
+
readonly glob: boolean;
|
|
279
|
+
/** A simple glob character in a component before the last. */
|
|
280
|
+
readonly dirGlob: boolean;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const GLOB_META = /[*?[{]|[@!+]\(/;
|
|
284
|
+
|
|
285
|
+
/** Expands `~`, `$HOME` and `${HOME}` to `home`; reports what else a shell would still expand. */
|
|
286
|
+
function expandWord(word: string, home: string): Expanded {
|
|
287
|
+
let text = word;
|
|
288
|
+
if (text === "~") text = home;
|
|
289
|
+
else if (text.startsWith("~/")) text = `${home}${text.slice(1)}`;
|
|
290
|
+
text = text.replace(/\$\{HOME\}|\$HOME(?![A-Za-z0-9_])/g, () => home);
|
|
291
|
+
const tilde = text.startsWith("~");
|
|
292
|
+
const meta = text.search(GLOB_META);
|
|
293
|
+
// A `..` after a glob can climb out of whatever the glob matched, so the literal prefix says nothing.
|
|
294
|
+
const climbs = meta !== -1 && /(^|\/)\.\.(\/|$)/.test(text.slice(meta));
|
|
295
|
+
const unresolved = tilde || climbs || /\$[A-Za-z0-9_{(@*#?$!-]|`/.test(text);
|
|
296
|
+
return { text, unresolved, glob: meta !== -1, dirGlob: meta !== -1 };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* A glob word is judged by the literal text before its first metacharacter,
|
|
301
|
+
* not by evaluating the pattern: refused when a denied entry starts with that
|
|
302
|
+
* prefix or the prefix starts with a denied entry.
|
|
303
|
+
*/
|
|
304
|
+
function checkGlob(denied: Denied, text: string, cwd: string, written: string): Verdict {
|
|
305
|
+
const prefix = text.slice(0, text.search(GLOB_META));
|
|
306
|
+
const absolute = posix.normalize(prefix.startsWith("/") ? prefix : `${cwd}/${prefix}`);
|
|
307
|
+
if (denied.readable.some((entry) => isUnder(absolute, entry))) return ALLOW;
|
|
308
|
+
for (const entry of denied.entries) {
|
|
309
|
+
if (entry.path.startsWith(absolute) || absolute.startsWith(entry.path)) {
|
|
310
|
+
return { allow: false, reason: `path "${written}" can match a path under denyPaths entry "${entry.written}"`, rule: entry.written };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return ALLOW;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const CD_GLOB = /[*?[\]{]|[@!+]\(/;
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Words that can change the shell's directory in a way the matcher does not
|
|
320
|
+
* model: compound commands, function and script runners, wrappers and the
|
|
321
|
+
* directory stack. A part that starts with one makes the directory unknown.
|
|
322
|
+
*/
|
|
323
|
+
const UNMODELLED = new Set([
|
|
324
|
+
"{", "}", "if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "select",
|
|
325
|
+
"function", "time", "coproc", "!", "[[", "eval", "source", ".", "exec", "builtin", "command", "env", "pushd", "popd", "trap",
|
|
326
|
+
]);
|
|
327
|
+
|
|
328
|
+
const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
329
|
+
|
|
330
|
+
interface BashWord {
|
|
331
|
+
readonly word: string;
|
|
332
|
+
readonly next: string | undefined;
|
|
333
|
+
/** Position in its part; 0 is the command name. */
|
|
334
|
+
readonly index: number;
|
|
335
|
+
/** The directory relative paths of this word mean; undefined once the directory is unknown. */
|
|
336
|
+
readonly dir: string | undefined;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* The words of a command with the directory each is read in, and whether a
|
|
341
|
+
* `cd` target could not be resolved. Only a plain top-level `cd <path>` in a
|
|
342
|
+
* chain is modelled; anything else that can change the directory makes it
|
|
343
|
+
* unknown for the rest of the command (`README.md`).
|
|
344
|
+
*/
|
|
345
|
+
function bashWords(parts: readonly Part[], cwd: string, home: string): { words: BashWord[]; unresolvedCd: boolean } {
|
|
346
|
+
const words: BashWord[] = [];
|
|
347
|
+
let dir: string | undefined = cwd;
|
|
348
|
+
let unresolvedCd = false;
|
|
349
|
+
parts.forEach((part, at) => {
|
|
350
|
+
const here = dir;
|
|
351
|
+
part.words.forEach((word, index) => words.push({ word, next: part.words.at(index + 1), index, dir: here }));
|
|
352
|
+
if (dir === undefined) return;
|
|
353
|
+
if (part.sep === "(" || part.sep === ")") {
|
|
354
|
+
dir = undefined;
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
let start = 0;
|
|
358
|
+
while (start < part.words.length && ASSIGNMENT_WORD.test(part.words.at(start) ?? "")) start += 1;
|
|
359
|
+
if (part.words.some((word) => word.startsWith("CDPATH=") || word === "CDPATH")) {
|
|
360
|
+
dir = undefined;
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const name = part.words.at(start) ?? "";
|
|
364
|
+
if (UNMODELLED.has(name)) {
|
|
365
|
+
dir = undefined;
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (name !== "cd") return;
|
|
369
|
+
// A cd in a pipeline or in the background runs in a subshell.
|
|
370
|
+
const after = parts.at(at + 1)?.sep;
|
|
371
|
+
if (part.sep === "|" || part.sep === "|&" || part.sep === "&" || after === "|" || after === "|&" || after === "&") {
|
|
372
|
+
dir = undefined;
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
const operands = part.words.slice(start + 1).filter((word) => word !== "--" && !/^-[LPe@]+$/.test(word));
|
|
376
|
+
const target = operands.at(0);
|
|
377
|
+
if (target === undefined || target === "-") {
|
|
378
|
+
dir = undefined;
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
const expanded = expandWord(target, home);
|
|
382
|
+
if (expanded.unresolved || CD_GLOB.test(expanded.text)) {
|
|
383
|
+
unresolvedCd = true;
|
|
384
|
+
dir = undefined;
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
dir = posix.resolve(dir, expanded.text);
|
|
388
|
+
});
|
|
389
|
+
return { words, unresolvedCd };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function checkBash(profile: AccessProfile, command: string, denied: Denied | undefined): Verdict {
|
|
393
|
+
const rules = (profile.denyCommands ?? [])
|
|
394
|
+
.map((text) => parseRule(text))
|
|
395
|
+
.filter((rule): rule is Rule => rule !== undefined);
|
|
396
|
+
const { parts, substitution, extglob, ansiC } = scan(command);
|
|
397
|
+
|
|
398
|
+
if ((profile.denyCommands ?? []).length > 0) {
|
|
399
|
+
if (substitution !== undefined) {
|
|
400
|
+
return {
|
|
401
|
+
allow: false,
|
|
402
|
+
reason: `command "${command}" runs inline code (${substitution}); it is refused while denyCommands is set`,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
for (const part of parts) {
|
|
406
|
+
const form = inlineFormOf(part);
|
|
407
|
+
if (form !== undefined) {
|
|
408
|
+
return {
|
|
409
|
+
allow: false,
|
|
410
|
+
reason: `part "${part.text}" runs inline code (${form}); it is refused while denyCommands is set`,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const hit = findDenied(rules, parts);
|
|
415
|
+
if (hit !== undefined) {
|
|
416
|
+
return { allow: false, reason: `part "${hit.text}" is refused by denyCommands rule "${hit.rule}"`, rule: hit.rule };
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (denied !== undefined) {
|
|
421
|
+
const { words, unresolvedCd } = bashWords(parts, denied.cwd, denied.home);
|
|
422
|
+
let unresolved = unresolvedCd ? "a cd target" : substitution === undefined ? undefined : `a command substitution (${substitution})`;
|
|
423
|
+
if (extglob) unresolved ??= "an extended glob";
|
|
424
|
+
if (ansiC) unresolved ??= "a $'…' word with escapes";
|
|
425
|
+
for (const { word, index, dir } of words) {
|
|
426
|
+
if (dir === undefined && (index > 0 ? !word.startsWith("-") : word.includes("/")) && !expandWord(word, denied.home).text.startsWith("/")) {
|
|
427
|
+
unresolved ??= `"${word}" after a directory change it cannot follow`;
|
|
428
|
+
}
|
|
429
|
+
for (const reading of readings(word, denied.home)) {
|
|
430
|
+
const expanded = expandWord(reading, denied.home);
|
|
431
|
+
if (expanded.unresolved) {
|
|
432
|
+
unresolved ??= `"${reading}"`;
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const verdict = expanded.glob
|
|
436
|
+
? checkGlob(denied, expanded.text, dir ?? denied.cwd, reading)
|
|
437
|
+
: checkPath(denied, expanded.text, dir ?? denied.cwd, reading);
|
|
438
|
+
if (!verdict.allow) return verdict;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
// A deny wins over this ask: it is only reached when no path was denied.
|
|
442
|
+
if (unresolved !== undefined) {
|
|
443
|
+
return {
|
|
444
|
+
allow: false,
|
|
445
|
+
ask: true,
|
|
446
|
+
reason: `command "${command}" uses ${unresolved}, which holds a shell expansion that cannot be matched against denyPaths; it asks`,
|
|
447
|
+
rule: "inline code",
|
|
448
|
+
kind: "command",
|
|
449
|
+
value: command,
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return ALLOW;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
interface AskedPaths {
|
|
457
|
+
readonly entries: ReadonlyArray<{ readonly written: string; readonly pattern: RegExp }>;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** The `askPaths` entries as patterns over normalised paths; `*` stays within a segment. */
|
|
461
|
+
function askedPaths(profile: AccessProfile, cwd: string, home: string): AskedPaths | undefined {
|
|
462
|
+
const entries = (profile.askPaths ?? [])
|
|
463
|
+
.filter((written) => written.length > 0)
|
|
464
|
+
.map((written) => {
|
|
465
|
+
const source = normalise(written, cwd, home)
|
|
466
|
+
.split("*")
|
|
467
|
+
.map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
468
|
+
.join("[^/]*");
|
|
469
|
+
return { written, pattern: new RegExp(`^${source}(?:/.*)?$`) };
|
|
470
|
+
});
|
|
471
|
+
return entries.length > 0 ? { entries } : undefined;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function askedRule(asked: AskedPaths, normal: string): string | undefined {
|
|
475
|
+
return asked.entries.find((entry) => entry.pattern.test(normal))?.written;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** The path a word or the word after it redirects output to, if it does. */
|
|
479
|
+
function redirectTarget(word: string, next: string | undefined): string | undefined {
|
|
480
|
+
const match = /^(?:\d*|&)>>?(.*)$/.exec(word);
|
|
481
|
+
if (match === null) return undefined;
|
|
482
|
+
const glued = match[1] ?? "";
|
|
483
|
+
const target = glued.length > 0 ? glued : next;
|
|
484
|
+
return target !== undefined && target.length > 0 && !target.startsWith("&") ? target : undefined;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The ask verdict of a command, when no deny applied. A command that hides what
|
|
489
|
+
* it runs (inline code) cannot be matched, so it asks while `askCommands` is
|
|
490
|
+
* set (`operad-sandbox.md` decision 4).
|
|
491
|
+
*/
|
|
492
|
+
function askBash(profile: AccessProfile, command: string, asked: AskedPaths | undefined, cwd: string, home: string): Verdict {
|
|
493
|
+
const texts = profile.askCommands ?? [];
|
|
494
|
+
let found: { readonly target: string; readonly rule: string } | undefined;
|
|
495
|
+
if (texts.length === 0 && asked === undefined) return ALLOW;
|
|
496
|
+
const rules = texts.map((text) => parseRule(text)).filter((rule): rule is Rule => rule !== undefined);
|
|
497
|
+
const { parts, substitution } = scan(command);
|
|
498
|
+
const ask = (reason: string, rule: string): Verdict => ({ allow: false, ask: true, reason, rule, kind: "command", value: command });
|
|
499
|
+
if (asked !== undefined) {
|
|
500
|
+
// Only a redirect writes by itself: a word after `>` or `>>`, or glued to it.
|
|
501
|
+
const walked = bashWords(parts, cwd, home);
|
|
502
|
+
let unresolved: string | undefined;
|
|
503
|
+
let redirects = false;
|
|
504
|
+
for (const { word, next, dir } of walked.words) {
|
|
505
|
+
const target = redirectTarget(word, next);
|
|
506
|
+
if (target === undefined) continue;
|
|
507
|
+
redirects = true;
|
|
508
|
+
const expanded = expandWord(target, home);
|
|
509
|
+
if (expanded.unresolved || expanded.dirGlob) {
|
|
510
|
+
unresolved ??= `"${target}"`;
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (dir === undefined && !expanded.text.startsWith("/")) {
|
|
514
|
+
unresolved ??= `"${target}"`;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
const hit = askedRule(asked, normalise(expanded.text, dir ?? cwd, home));
|
|
518
|
+
if (hit !== undefined && found === undefined) found = { target, rule: hit };
|
|
519
|
+
}
|
|
520
|
+
if (found !== undefined) return ask(`command "${command}" writes "${found.target}", which is under askPaths entry "${found.rule}"`, found.rule);
|
|
521
|
+
if (redirects && walked.unresolvedCd) unresolved ??= "a cd target";
|
|
522
|
+
if (redirects && substitution !== undefined) unresolved ??= `a command substitution (${substitution})`;
|
|
523
|
+
if (unresolved !== undefined) {
|
|
524
|
+
return ask(`command "${command}" writes to ${unresolved}, which holds a shell expansion that cannot be matched against askPaths; it asks`, "inline code");
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
if (texts.length === 0) return ALLOW;
|
|
528
|
+
if (substitution !== undefined) {
|
|
529
|
+
return ask(`command "${command}" runs inline code (${substitution}); it asks while askCommands is set`, "inline code");
|
|
530
|
+
}
|
|
531
|
+
for (const part of parts) {
|
|
532
|
+
const form = inlineFormOf(part);
|
|
533
|
+
if (form !== undefined) {
|
|
534
|
+
return ask(`part "${part.text}" runs inline code (${form}); it asks while askCommands is set`, "inline code");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
const hit = findDenied(rules, parts);
|
|
538
|
+
if (hit !== undefined) return ask(`part "${hit.text}" matches askCommands rule "${hit.rule}"`, hit.rule);
|
|
539
|
+
return ALLOW;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** The tool name of a call to an MCP server's tool; its input has `server` and `tool`. */
|
|
543
|
+
export const MCP_TOOL = "mcp";
|
|
544
|
+
|
|
545
|
+
/** The words a person is asked about, and a one-time permission covers, for an MCP tool. */
|
|
546
|
+
export function mcpCallValue(server: string, tool: string): string {
|
|
547
|
+
return `mcp ${server}.${tool}`;
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
function matchMcp(profile: AccessProfile, call: ToolCall): Verdict {
|
|
551
|
+
// Only the field's presence puts MCP tools under the profile.
|
|
552
|
+
if (profile.allowMcp === undefined) return ALLOW;
|
|
553
|
+
const server: unknown = call.input["server"];
|
|
554
|
+
const tool: unknown = call.input["tool"];
|
|
555
|
+
if (typeof server !== "string" || typeof tool !== "string") {
|
|
556
|
+
return { allow: false, reason: "an MCP call that names no server and tool cannot be checked" };
|
|
557
|
+
}
|
|
558
|
+
const allowed = profile.allowMcp;
|
|
559
|
+
if (allowed.includes(`${server}.${tool}`) || allowed.includes(`${server}.*`)) return ALLOW;
|
|
560
|
+
return {
|
|
561
|
+
allow: false,
|
|
562
|
+
ask: true,
|
|
563
|
+
reason: `MCP tool "${server}.${tool}" is not on the allowed list; a tool nobody listed counts as a write and asks`,
|
|
564
|
+
rule: "unknown MCP tool",
|
|
565
|
+
kind: "command",
|
|
566
|
+
value: mcpCallValue(server, tool),
|
|
567
|
+
};
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* Whether one tool call may run under the profile. Pure and lexical. Deny wins
|
|
572
|
+
* over ask and ask over allow: the deny rules and paths are checked first, and
|
|
573
|
+
* `askCommands` only when nothing denied the call.
|
|
574
|
+
*/
|
|
575
|
+
export function match(given: AccessProfile, call: ToolCall, options: MatchOptions = {}): Verdict {
|
|
576
|
+
const home = options.home ?? homedir();
|
|
577
|
+
// A read-only working directory is a directory whose writes ask.
|
|
578
|
+
// A directory that may be read is one whose writes ask.
|
|
579
|
+
const readPaths = (given.readPaths ?? []).filter((written) => written.length > 0);
|
|
580
|
+
const asking = [...(given.readOnly === true ? [call.cwd] : []), ...readPaths];
|
|
581
|
+
const profile: AccessProfile =
|
|
582
|
+
asking.length > 0 ? { ...given, askPaths: [...(given.askPaths ?? []), ...asking] } : given;
|
|
583
|
+
const entries = (profile.denyPaths ?? [])
|
|
584
|
+
.filter((written) => written.length > 0)
|
|
585
|
+
.map((written) => ({ written, path: normalise(written, call.cwd, home) }));
|
|
586
|
+
// Only a call that reads may go through a deny by way of `readPaths`.
|
|
587
|
+
const reads =
|
|
588
|
+
call.tool === "bash"
|
|
589
|
+
? typeof call.input["command"] === "string" && isReadOnlyCommand(call.input["command"])
|
|
590
|
+
: call.tool === "read" || call.tool === "grep" || call.tool === "find" || call.tool === "ls";
|
|
591
|
+
const readable = reads ? readPaths.map((written) => normalise(written, call.cwd, home)) : [];
|
|
592
|
+
const denied: Denied | undefined = entries.length > 0 ? { entries, cwd: call.cwd, home, readable } : undefined;
|
|
593
|
+
|
|
594
|
+
if (call.tool === "bash") {
|
|
595
|
+
const command: unknown = call.input["command"];
|
|
596
|
+
if (typeof command !== "string") return ALLOW;
|
|
597
|
+
const verdict = checkBash(profile, command, denied);
|
|
598
|
+
// A deny stays a deny; only an ask can be lifted by an always-allowed entry.
|
|
599
|
+
if (!verdict.allow && verdict.ask !== true) return verdict;
|
|
600
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
601
|
+
if (!verdict.allow) return verdict;
|
|
602
|
+
const asked = askBash(profile, command, askedPaths(profile, call.cwd, home), call.cwd, home);
|
|
603
|
+
if (!asked.allow) return asked;
|
|
604
|
+
// A read-only directory runs only commands known to read.
|
|
605
|
+
if (given.readOnly === true && !isReadOnlyCommand(command)) {
|
|
606
|
+
return { allow: false, ask: true, reason: "the working directory is read-only and this command is not known to only read", rule: "readOnly", kind: "command", value: command };
|
|
607
|
+
}
|
|
608
|
+
return asked;
|
|
609
|
+
}
|
|
610
|
+
if (call.tool === MCP_TOOL) {
|
|
611
|
+
// An allow_always answer to an unlisted tool is its exact command entry.
|
|
612
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
613
|
+
return matchMcp(profile, call);
|
|
614
|
+
}
|
|
615
|
+
if (PATH_TOOLS.has(call.tool)) {
|
|
616
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
617
|
+
if (typeof path === "string" && path.length > 0) {
|
|
618
|
+
if (denied !== undefined) {
|
|
619
|
+
const verdict = checkPath(denied, path);
|
|
620
|
+
if (!verdict.allow) return verdict;
|
|
621
|
+
}
|
|
622
|
+
// An always-allowed entry lifts the ask, never a deny.
|
|
623
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
624
|
+
// Ask comes after deny: a write to a path that is asked about asks.
|
|
625
|
+
const asked = call.tool === "write" || call.tool === "edit" ? askedPaths(profile, call.cwd, home) : undefined;
|
|
626
|
+
const hit = asked === undefined ? undefined : askedRule(asked, normalise(path, call.cwd, home));
|
|
627
|
+
if (hit !== undefined) {
|
|
628
|
+
return { allow: false, ask: true, reason: `path "${path}" is under askPaths entry "${hit}"`, rule: hit, kind: "path", value: path, tool: call.tool };
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return ALLOW;
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/**
|
|
636
|
+
* The unused grant that covers this exact call, if any. A command grant covers
|
|
637
|
+
* a bash call whose command equals the value character for character; a path
|
|
638
|
+
* grant covers a path tool call whose path names the same file. The caller must
|
|
639
|
+
* use the grant up before it lets the call run, and match as usual afterwards.
|
|
640
|
+
*/
|
|
641
|
+
export function findGrant(profile: AccessProfile, call: ToolCall, options: MatchOptions = {}): AccessGrant | undefined {
|
|
642
|
+
const home = options.home ?? homedir();
|
|
643
|
+
for (const grant of profile.grants ?? []) {
|
|
644
|
+
if (grant.kind === "command") {
|
|
645
|
+
if (call.tool === "bash" && call.input["command"] === grant.value) return grant;
|
|
646
|
+
if (call.tool === MCP_TOOL && mcpCallValue(String(call.input["server"]), String(call.input["tool"])) === grant.value) return grant;
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
// A path grant covers the tool the person approved and no other.
|
|
650
|
+
if (!PATH_TOOLS.has(call.tool) || grant.tool !== call.tool) continue;
|
|
651
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
652
|
+
if (
|
|
653
|
+
typeof path === "string" &&
|
|
654
|
+
path.length > 0 &&
|
|
655
|
+
normalise(path, call.cwd, home) === normalise(grant.value, call.cwd, home)
|
|
656
|
+
) {
|
|
657
|
+
return grant;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return undefined;
|
|
661
|
+
}
|