@operad-io/access-match 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/package.json +21 -4
- package/src/command.ts +301 -0
- package/src/index.ts +663 -0
- package/src/readonly.ts +66 -0
- package/src/summary.ts +196 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Yinghai Zhao
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,13 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @operad-io/access-match
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Access profiles matched against agent tool calls.** Says whether one tool call of an agent may run under an access profile's `denyPaths`, `denyCommands` and `askCommands`. The harnesses call it before a tool runs.
|
|
4
|
+
|
|
5
|
+
This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
|
|
6
|
+
|
|
7
|
+
## Documentation
|
|
8
|
+
|
|
9
|
+
- User guide: [docs/user/access.md](https://github.com/operad-io/operad/blob/main/docs/user/access.md)
|
|
10
|
+
- Website: <https://operad.io>
|
|
11
|
+
- Developer reference: `REFERENCE.md` in this directory
|
|
12
|
+
|
|
13
|
+
MIT licensed.
|
package/package.json
CHANGED
|
@@ -1,6 +1,23 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@operad-io/access-match",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"exports": {
|
|
6
|
+
".": "./src/index.ts"
|
|
7
|
+
},
|
|
8
|
+
"dependencies": {
|
|
9
|
+
"@operad-io/engine": "0.1.0"
|
|
10
|
+
},
|
|
11
|
+
"description": "operad: access profiles matched against agent tool calls",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/operad-io/operad.git",
|
|
15
|
+
"directory": "packages/access-match"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"files": [
|
|
19
|
+
"src",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
]
|
|
23
|
+
}
|
package/src/command.ts
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Splits a `bash` command into parts and matches the parts against
|
|
3
|
+
* `denyCommands` rules. The tables are in `../README.md`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** One command between operators; `sep` is the operator before it ("" for the first). */
|
|
7
|
+
export interface Part {
|
|
8
|
+
readonly sep: string;
|
|
9
|
+
readonly words: readonly string[];
|
|
10
|
+
readonly text: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface Scan {
|
|
14
|
+
readonly parts: readonly Part[];
|
|
15
|
+
/** The first command or process substitution seen outside single quotes. */
|
|
16
|
+
readonly substitution: string | undefined;
|
|
17
|
+
/** An extended glob (`@(a|b)`, `!(a)`, `+(a)`) was seen outside quotes; the shell may expand it to any path. */
|
|
18
|
+
readonly extglob: boolean;
|
|
19
|
+
/** A `$'…'` word with escapes was seen; its characters are not decoded. */
|
|
20
|
+
readonly ansiC: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const WHITESPACE = new Set([" ", "\t", "\r"]);
|
|
24
|
+
|
|
25
|
+
export function scan(command: string): Scan {
|
|
26
|
+
const parts: Part[] = [];
|
|
27
|
+
let substitution: string | undefined;
|
|
28
|
+
let extglob = false;
|
|
29
|
+
let ansiC = false;
|
|
30
|
+
let words: string[] = [];
|
|
31
|
+
let word: string | undefined;
|
|
32
|
+
let sep = "";
|
|
33
|
+
let start = 0;
|
|
34
|
+
|
|
35
|
+
const endWord = (): void => {
|
|
36
|
+
if (word !== undefined) words.push(word);
|
|
37
|
+
word = undefined;
|
|
38
|
+
};
|
|
39
|
+
const endPart = (end: number, next: string, nextStart: number): void => {
|
|
40
|
+
endWord();
|
|
41
|
+
if (words.length > 0) parts.push({ sep, words, text: command.slice(start, end).trim() });
|
|
42
|
+
words = [];
|
|
43
|
+
sep = next;
|
|
44
|
+
start = nextStart;
|
|
45
|
+
};
|
|
46
|
+
const note = (form: string): void => {
|
|
47
|
+
substitution ??= form;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
let i = 0;
|
|
51
|
+
while (i < command.length) {
|
|
52
|
+
const ch = command.charAt(i);
|
|
53
|
+
const next = command.charAt(i + 1);
|
|
54
|
+
if (ch === "$" && next === "'") {
|
|
55
|
+
let end = i + 2;
|
|
56
|
+
while (end < command.length && command.charAt(end) !== "'") end += command.charAt(end) === "\\" ? 2 : 1;
|
|
57
|
+
const content = command.slice(i + 2, end);
|
|
58
|
+
if (content.includes("\\")) ansiC = true;
|
|
59
|
+
word = (word ?? "") + content;
|
|
60
|
+
i = end + 1;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (ch === "'") {
|
|
64
|
+
const close = command.indexOf("'", i + 1);
|
|
65
|
+
const end = close === -1 ? command.length : close;
|
|
66
|
+
word = (word ?? "") + command.slice(i + 1, end);
|
|
67
|
+
i = end + 1;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
if (ch === '"') {
|
|
71
|
+
word ??= "";
|
|
72
|
+
i += 1;
|
|
73
|
+
while (i < command.length && command.charAt(i) !== '"') {
|
|
74
|
+
const inner = command.charAt(i);
|
|
75
|
+
if (inner === "\\" && i + 1 < command.length) {
|
|
76
|
+
const escaped = command.charAt(i + 1);
|
|
77
|
+
word += '"\\`$'.includes(escaped) ? escaped : `\\${escaped}`;
|
|
78
|
+
i += 2;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (inner === "`") note("`");
|
|
82
|
+
if (inner === "$" && command.charAt(i + 1) === "(") note("$(");
|
|
83
|
+
word += inner;
|
|
84
|
+
i += 1;
|
|
85
|
+
}
|
|
86
|
+
i += 1;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (ch === "\\") {
|
|
90
|
+
if (next === "\n") {
|
|
91
|
+
i += 2;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (i + 1 < command.length) word = (word ?? "") + next;
|
|
95
|
+
i += 2;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (ch === "`") {
|
|
99
|
+
note("`");
|
|
100
|
+
word = (word ?? "") + ch;
|
|
101
|
+
i += 1;
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (ch === "$" && next === "(") {
|
|
105
|
+
note("$(");
|
|
106
|
+
word = (word ?? "") + ch;
|
|
107
|
+
i += 1;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if ((ch === "<" || ch === ">") && next === "(") {
|
|
111
|
+
note(`${ch}(`);
|
|
112
|
+
word = (word ?? "") + ch;
|
|
113
|
+
i += 1;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (ch === "(" && word !== undefined && "@!+?*".includes(word.slice(-1)) && word.length > 0) {
|
|
117
|
+
let depth = 0;
|
|
118
|
+
let end = i;
|
|
119
|
+
for (; end < command.length; end += 1) {
|
|
120
|
+
const c = command.charAt(end);
|
|
121
|
+
if (c === "(") depth += 1;
|
|
122
|
+
if (c === ")" && --depth === 0) break;
|
|
123
|
+
}
|
|
124
|
+
extglob = true;
|
|
125
|
+
word += command.slice(i, end + 1);
|
|
126
|
+
i = end + 1;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (WHITESPACE.has(ch)) {
|
|
130
|
+
endWord();
|
|
131
|
+
i += 1;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (ch === "&" && (command.charAt(i - 1) === ">" || command.charAt(i - 1) === "<" || next === ">")) {
|
|
135
|
+
word = (word ?? "") + ch; // 2>&1 and &> are redirections, not operators
|
|
136
|
+
i += 1;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (ch === "&" && next === "&") {
|
|
140
|
+
endPart(i, "&&", i + 2);
|
|
141
|
+
i += 2;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (ch === "|" && (next === "|" || next === "&")) {
|
|
145
|
+
endPart(i, `|${next}`, i + 2);
|
|
146
|
+
i += 2;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (ch === "|" || ch === ";" || ch === "&" || ch === "\n" || ch === "(" || ch === ")") {
|
|
150
|
+
endPart(i, ch === "\n" ? ";" : ch, i + 1);
|
|
151
|
+
i += 1;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
word = (word ?? "") + ch;
|
|
155
|
+
i += 1;
|
|
156
|
+
}
|
|
157
|
+
endPart(command.length, "", command.length);
|
|
158
|
+
return { parts, substitution, extglob, ansiC };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const WRAPPERS = new Set(["env", "command", "exec", "nohup", "time", "builtin", "sudo", "doas"]);
|
|
162
|
+
const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
163
|
+
|
|
164
|
+
export function baseName(word: string): string {
|
|
165
|
+
const slash = word.lastIndexOf("/");
|
|
166
|
+
return slash === -1 ? word : word.slice(slash + 1);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function skipAssignments(words: readonly string[]): readonly string[] {
|
|
170
|
+
let index = 0;
|
|
171
|
+
while (index < words.length && ASSIGNMENT.test(words.at(index) ?? "")) index += 1;
|
|
172
|
+
return words.slice(index);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** The part's words as the part itself, then after each wrapper in front. */
|
|
176
|
+
export function levels(words: readonly string[]): ReadonlyArray<readonly string[]> {
|
|
177
|
+
const result: Array<readonly string[]> = [];
|
|
178
|
+
let current = skipAssignments(words);
|
|
179
|
+
while (current.length > 0) {
|
|
180
|
+
result.push(current);
|
|
181
|
+
if (!WRAPPERS.has(baseName(current.at(0) ?? ""))) break;
|
|
182
|
+
let rest = current.slice(1);
|
|
183
|
+
for (;;) {
|
|
184
|
+
const first = rest.at(0);
|
|
185
|
+
if (first === undefined || !(first.startsWith("-") || ASSIGNMENT.test(first))) break;
|
|
186
|
+
rest = rest.slice(1);
|
|
187
|
+
}
|
|
188
|
+
current = rest;
|
|
189
|
+
}
|
|
190
|
+
return result;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const CLUSTER = /^-[A-Za-z0-9]+$/;
|
|
194
|
+
|
|
195
|
+
function letters(args: readonly string[]): Set<string> {
|
|
196
|
+
const found = new Set<string>();
|
|
197
|
+
for (const arg of args) {
|
|
198
|
+
if (CLUSTER.test(arg)) for (const letter of arg.slice(1)) found.add(letter);
|
|
199
|
+
}
|
|
200
|
+
return found;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const SHELLS = new Set(["bash", "sh", "zsh", "dash", "ksh"]);
|
|
204
|
+
const INLINE_E = new Set(["node", "bun", "osascript"]);
|
|
205
|
+
const FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
206
|
+
|
|
207
|
+
/** The inline-code form a part runs at one wrapper level, or undefined. */
|
|
208
|
+
function inlineForm(words: readonly string[]): string | undefined {
|
|
209
|
+
const name = baseName(words.at(0) ?? "");
|
|
210
|
+
const args = words.slice(1);
|
|
211
|
+
if (SHELLS.has(name) && letters(args).has("c")) return `${name} -c`;
|
|
212
|
+
if (/^python[0-9.]*$/.test(name) && letters(args).has("c")) return `${name} -c`;
|
|
213
|
+
if (INLINE_E.has(name) && letters(args).has("e")) return `${name} -e`;
|
|
214
|
+
if (name === "find") {
|
|
215
|
+
const hit = args.find((arg) => FIND_EXEC.has(arg));
|
|
216
|
+
if (hit !== undefined) return `find ${hit}`;
|
|
217
|
+
}
|
|
218
|
+
if (name === "xargs" || name === "eval") return name;
|
|
219
|
+
return undefined;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function inlineFormOf(part: Part): string | undefined {
|
|
223
|
+
for (const level of levels(part.words)) {
|
|
224
|
+
const form = inlineForm(level);
|
|
225
|
+
if (form !== undefined) return form;
|
|
226
|
+
}
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function glob(pattern: string): RegExp {
|
|
231
|
+
const source = pattern
|
|
232
|
+
.split("*")
|
|
233
|
+
.map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
234
|
+
.join(".*");
|
|
235
|
+
return new RegExp(`^${source}$`);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
interface Segment {
|
|
239
|
+
readonly command: RegExp;
|
|
240
|
+
readonly conditions: readonly string[];
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export interface Rule {
|
|
244
|
+
readonly text: string;
|
|
245
|
+
readonly segments: readonly Segment[];
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
export function parseRule(text: string): Rule | undefined {
|
|
249
|
+
const segments: Segment[] = [];
|
|
250
|
+
for (const piece of text.split("|")) {
|
|
251
|
+
const words = piece.split(/\s+/).filter((w) => w.length > 0 && w !== "…" && w !== "...");
|
|
252
|
+
const first = words.at(0);
|
|
253
|
+
if (first === undefined) return undefined;
|
|
254
|
+
segments.push({ command: glob(first), conditions: words.slice(1) });
|
|
255
|
+
}
|
|
256
|
+
return { text, segments };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function trimSlash(arg: string): string {
|
|
260
|
+
return arg.length > 1 ? arg.replace(/\/+$/, "") || "/" : arg;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function segmentMatches(segment: Segment, words: readonly string[]): boolean {
|
|
264
|
+
if (!segment.command.test(baseName(words.at(0) ?? ""))) return false;
|
|
265
|
+
const args = words.slice(1);
|
|
266
|
+
const found = letters(args);
|
|
267
|
+
return segment.conditions.every((condition) => {
|
|
268
|
+
if (CLUSTER.test(condition)) return [...condition.slice(1)].every((letter) => found.has(letter));
|
|
269
|
+
const pattern = glob(condition);
|
|
270
|
+
return args.some((arg) => pattern.test(arg) || pattern.test(trimSlash(arg)));
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function partMatches(segment: Segment, part: Part): boolean {
|
|
275
|
+
return levels(part.words).some((level) => segmentMatches(segment, level));
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Whether the rule matches the parts starting at `from`. */
|
|
279
|
+
function matchesAt(rule: Rule, parts: readonly Part[], from: number): boolean {
|
|
280
|
+
return rule.segments.every((segment, offset) => {
|
|
281
|
+
const part = parts[from + offset];
|
|
282
|
+
if (part === undefined) return false;
|
|
283
|
+
if (offset > 0 && part.sep !== "|" && part.sep !== "|&") return false;
|
|
284
|
+
return partMatches(segment, part);
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** The text of the matched parts for the first rule that matches, or undefined. */
|
|
289
|
+
export function findDenied(
|
|
290
|
+
rules: readonly Rule[],
|
|
291
|
+
parts: readonly Part[],
|
|
292
|
+
): { readonly text: string; readonly rule: string } | undefined {
|
|
293
|
+
for (let from = 0; from < parts.length; from += 1) {
|
|
294
|
+
for (const rule of rules) {
|
|
295
|
+
if (!matchesAt(rule, parts, from)) continue;
|
|
296
|
+
const matched = parts.slice(from, from + rule.segments.length);
|
|
297
|
+
return { text: matched.map((p) => p.text).join(" | "), rule: rule.text };
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return undefined;
|
|
301
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
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
|
+
* (ADR 0025 D3 and D7).
|
|
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 (the MCP-tool rule in
|
|
64
|
+
* `docs/backlog/operad-sandbox.md`, not in an ADR yet).
|
|
65
|
+
*/
|
|
66
|
+
readonly allowMcp?: readonly string[] | undefined;
|
|
67
|
+
/** Permissions not yet used; the caller uses one up before it lets a call through. */
|
|
68
|
+
readonly grants?: readonly AccessGrant[] | undefined;
|
|
69
|
+
/**
|
|
70
|
+
* Calls a person answered `allow_always` for: they run without asking, and
|
|
71
|
+
* only after every deny passed. The harness leaves them out in a background
|
|
72
|
+
* run (`docs/backlog/operad-sandbox.md` for the background run; ADR 0025 D7
|
|
73
|
+
* for the user layer).
|
|
74
|
+
*/
|
|
75
|
+
readonly alwaysAllow?: readonly AlwaysAllowEntry[] | undefined;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface ToolCall {
|
|
79
|
+
readonly tool: string;
|
|
80
|
+
readonly input: Readonly<Record<string, unknown>>;
|
|
81
|
+
readonly cwd: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* What the profile says about one call. The precedence is fixed: a deny wins
|
|
86
|
+
* over an ask, and an ask wins over an allow. So a call that matches
|
|
87
|
+
* `denyCommands` or `denyPaths` anywhere is refused whatever `askCommands` or
|
|
88
|
+
* `askPaths` say; a call that matches only those asks; every other call is
|
|
89
|
+
* allowed. A caller that does not know `ask` reads it as a refusal
|
|
90
|
+
* (`allow: false`), never as a pass.
|
|
91
|
+
*/
|
|
92
|
+
export type Verdict =
|
|
93
|
+
| { readonly allow: true; readonly ask?: undefined }
|
|
94
|
+
| {
|
|
95
|
+
readonly allow: false;
|
|
96
|
+
readonly ask?: undefined;
|
|
97
|
+
readonly reason: string;
|
|
98
|
+
/** The profile rule that refused, as the profile wrote it; never part of the call. */
|
|
99
|
+
readonly rule?: string;
|
|
100
|
+
}
|
|
101
|
+
| {
|
|
102
|
+
readonly allow: false;
|
|
103
|
+
readonly ask: true;
|
|
104
|
+
readonly reason: string;
|
|
105
|
+
/** The `askCommands` or `askPaths` rule that matched, or `inline code` when the command hides what it runs. */
|
|
106
|
+
readonly rule: string;
|
|
107
|
+
/**
|
|
108
|
+
* What a person is asked about: the whole command of a `bash` call, or the
|
|
109
|
+
* path as the call wrote it with the `tool` that writes it.
|
|
110
|
+
*/
|
|
111
|
+
readonly kind: "command" | "path";
|
|
112
|
+
readonly value: string;
|
|
113
|
+
readonly tool?: string;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
export interface MatchOptions {
|
|
117
|
+
/** What `~` means; defaults to the user's home directory. */
|
|
118
|
+
readonly home?: string | undefined;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type ProfileRead =
|
|
122
|
+
| { readonly ok: true; readonly profile: AccessProfile }
|
|
123
|
+
| { readonly ok: false; readonly message: string };
|
|
124
|
+
|
|
125
|
+
/** Reads the fields the matcher uses from an untrusted object. */
|
|
126
|
+
export function readProfile(value: unknown): ProfileRead {
|
|
127
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
128
|
+
return { ok: false, message: "the access profile must be an object" };
|
|
129
|
+
}
|
|
130
|
+
const found: { denyPaths?: string[]; denyCommands?: string[]; askCommands?: string[]; askPaths?: string[]; readPaths?: string[]; allowMcp?: string[]; readOnly?: boolean; grants?: AccessGrant[]; alwaysAllow?: AlwaysAllowEntry[] } = {};
|
|
131
|
+
const readOnly: unknown = Reflect.get(value, "readOnly");
|
|
132
|
+
if (readOnly !== undefined) {
|
|
133
|
+
if (typeof readOnly !== "boolean") return { ok: false, message: "readOnly must be true or false" };
|
|
134
|
+
found.readOnly = readOnly;
|
|
135
|
+
}
|
|
136
|
+
for (const field of ["denyPaths", "denyCommands", "askCommands", "askPaths", "readPaths", "allowMcp"] as const) {
|
|
137
|
+
const entry: unknown = Reflect.get(value, field);
|
|
138
|
+
if (entry === undefined) continue;
|
|
139
|
+
if (!Array.isArray(entry) || !entry.every((item): item is string => typeof item === "string")) {
|
|
140
|
+
return { ok: false, message: `${field} must be an array of strings` };
|
|
141
|
+
}
|
|
142
|
+
found[field] = entry;
|
|
143
|
+
}
|
|
144
|
+
const alwaysAllow: unknown = Reflect.get(value, "alwaysAllow");
|
|
145
|
+
if (alwaysAllow !== undefined) {
|
|
146
|
+
if (!Array.isArray(alwaysAllow)) return { ok: false, message: "alwaysAllow must be an array" };
|
|
147
|
+
const read: AlwaysAllowEntry[] = [];
|
|
148
|
+
for (const entry of alwaysAllow) {
|
|
149
|
+
if (typeof entry !== "object" || entry === null) {
|
|
150
|
+
return { ok: false, message: "each alwaysAllow entry must be an object" };
|
|
151
|
+
}
|
|
152
|
+
const kind: unknown = Reflect.get(entry, "kind");
|
|
153
|
+
const text: unknown = Reflect.get(entry, "value");
|
|
154
|
+
const cwd: unknown = Reflect.get(entry, "cwd");
|
|
155
|
+
const tool: unknown = Reflect.get(entry, "tool");
|
|
156
|
+
if ((kind !== "command" && kind !== "path") || typeof text !== "string" || text.length === 0) {
|
|
157
|
+
return { ok: false, message: "each alwaysAllow entry needs a kind (command or path) and a value" };
|
|
158
|
+
}
|
|
159
|
+
if (typeof cwd !== "string" || cwd.length === 0) {
|
|
160
|
+
return { ok: false, message: "each alwaysAllow entry needs the working directory it was allowed in" };
|
|
161
|
+
}
|
|
162
|
+
if (kind === "path" && (typeof tool !== "string" || tool.length === 0)) {
|
|
163
|
+
return { ok: false, message: "an alwaysAllow path entry needs the tool it was allowed for" };
|
|
164
|
+
}
|
|
165
|
+
read.push({
|
|
166
|
+
kind,
|
|
167
|
+
value: text,
|
|
168
|
+
cwd,
|
|
169
|
+
...(kind === "path" ? { tool: tool as string } : {}),
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
found.alwaysAllow = read;
|
|
173
|
+
}
|
|
174
|
+
const grants: unknown = Reflect.get(value, "grants");
|
|
175
|
+
if (grants !== undefined) {
|
|
176
|
+
if (!Array.isArray(grants)) return { ok: false, message: "grants must be an array" };
|
|
177
|
+
const read: AccessGrant[] = [];
|
|
178
|
+
for (const grant of grants) {
|
|
179
|
+
if (typeof grant !== "object" || grant === null) {
|
|
180
|
+
return { ok: false, message: "each grant must be an object" };
|
|
181
|
+
}
|
|
182
|
+
const waitId: unknown = Reflect.get(grant, "waitId");
|
|
183
|
+
const kind: unknown = Reflect.get(grant, "kind");
|
|
184
|
+
const text: unknown = Reflect.get(grant, "value");
|
|
185
|
+
if (
|
|
186
|
+
typeof waitId !== "string" ||
|
|
187
|
+
(kind !== "command" && kind !== "path") ||
|
|
188
|
+
typeof text !== "string"
|
|
189
|
+
) {
|
|
190
|
+
return { ok: false, message: "each grant needs a waitId, a kind (command or path) and a value" };
|
|
191
|
+
}
|
|
192
|
+
const tool: unknown = Reflect.get(grant, "tool");
|
|
193
|
+
if (tool !== undefined && typeof tool !== "string") {
|
|
194
|
+
return { ok: false, message: "a grant's tool must be a string" };
|
|
195
|
+
}
|
|
196
|
+
read.push({ waitId, kind, value: text, ...(tool === undefined ? {} : { tool }) });
|
|
197
|
+
}
|
|
198
|
+
found.grants = read;
|
|
199
|
+
}
|
|
200
|
+
return { ok: true, profile: found };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const ALLOW: Verdict = { allow: true };
|
|
204
|
+
|
|
205
|
+
function normalise(path: string, cwd: string, home: string): string {
|
|
206
|
+
let expanded = path;
|
|
207
|
+
if (path === "~") expanded = home;
|
|
208
|
+
else if (path.startsWith("~/")) expanded = `${home}${path.slice(1)}`;
|
|
209
|
+
return posix.resolve(cwd, expanded);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function isUnder(path: string, entry: string): boolean {
|
|
213
|
+
return path === entry || path.startsWith(entry === "/" ? "/" : `${entry}/`);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Whether a person allowed this exact call always; never a deny, and never another cwd. */
|
|
217
|
+
function alwaysAllowed(profile: AccessProfile, call: ToolCall): boolean {
|
|
218
|
+
for (const entry of profile.alwaysAllow ?? []) {
|
|
219
|
+
if (entry.cwd !== call.cwd) continue;
|
|
220
|
+
if (entry.kind === "command") {
|
|
221
|
+
if (call.tool === "bash" && call.input["command"] === entry.value) return true;
|
|
222
|
+
if (call.tool === MCP_TOOL) {
|
|
223
|
+
const server: unknown = call.input["server"];
|
|
224
|
+
const tool: unknown = call.input["tool"];
|
|
225
|
+
if (typeof server === "string" && typeof tool === "string" && mcpCallValue(server, tool) === entry.value) {
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
if (call.tool !== entry.tool) continue;
|
|
232
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
233
|
+
if (typeof path === "string" && path === entry.value) return true;
|
|
234
|
+
}
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
interface Denied {
|
|
239
|
+
readonly entries: ReadonlyArray<{ readonly written: string; readonly path: string }>;
|
|
240
|
+
readonly cwd: string;
|
|
241
|
+
readonly home: string;
|
|
242
|
+
/** Normalised directories this call may read through a deny (`readPaths`). */
|
|
243
|
+
readonly readable: readonly string[];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function checkPath(denied: Denied, path: string, cwd: string = denied.cwd, written: string = path): Verdict {
|
|
247
|
+
const normal = normalise(path, cwd, denied.home);
|
|
248
|
+
if (denied.readable.some((entry) => isUnder(normal, entry))) return ALLOW;
|
|
249
|
+
for (const entry of denied.entries) {
|
|
250
|
+
if (isUnder(normal, entry.path)) {
|
|
251
|
+
return { allow: false, reason: `path "${written}" is under denyPaths entry "${entry.written}"`, rule: entry.written };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return ALLOW;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const PATH_TOOLS = new Set(["read", "write", "edit", "grep", "find", "ls"]);
|
|
258
|
+
const REDIRECT = /^(?:\d*|&)(?:>>|>|<)&?/;
|
|
259
|
+
|
|
260
|
+
function pathLike(word: string): boolean {
|
|
261
|
+
return word.includes("/") || word.startsWith("~") || word.startsWith(".");
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** The readings of one word that may be a path: itself, minus a redirect, after `=`. */
|
|
265
|
+
function readings(word: string, home: string): string[] {
|
|
266
|
+
const unredirected = word.replace(REDIRECT, "");
|
|
267
|
+
const found = [word, unredirected];
|
|
268
|
+
const equals = unredirected.indexOf("=");
|
|
269
|
+
if (equals !== -1) found.push(unredirected.slice(equals + 1));
|
|
270
|
+
return found.filter(
|
|
271
|
+
(reading, index) => reading.length > 0 && found.indexOf(reading) === index && pathLike(expandWord(reading, home).text),
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
interface Expanded {
|
|
276
|
+
readonly text: string;
|
|
277
|
+
/** Still holds an expansion the matcher cannot resolve. */
|
|
278
|
+
readonly unresolved: boolean;
|
|
279
|
+
/** A simple glob character (`*`, `?`, `[`) in any component. */
|
|
280
|
+
readonly glob: boolean;
|
|
281
|
+
/** A simple glob character in a component before the last. */
|
|
282
|
+
readonly dirGlob: boolean;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const GLOB_META = /[*?[{]|[@!+]\(/;
|
|
286
|
+
|
|
287
|
+
/** Expands `~`, `$HOME` and `${HOME}` to `home`; reports what else a shell would still expand. */
|
|
288
|
+
function expandWord(word: string, home: string): Expanded {
|
|
289
|
+
let text = word;
|
|
290
|
+
if (text === "~") text = home;
|
|
291
|
+
else if (text.startsWith("~/")) text = `${home}${text.slice(1)}`;
|
|
292
|
+
text = text.replace(/\$\{HOME\}|\$HOME(?![A-Za-z0-9_])/g, () => home);
|
|
293
|
+
const tilde = text.startsWith("~");
|
|
294
|
+
const meta = text.search(GLOB_META);
|
|
295
|
+
// A `..` after a glob can climb out of whatever the glob matched, so the literal prefix says nothing.
|
|
296
|
+
const climbs = meta !== -1 && /(^|\/)\.\.(\/|$)/.test(text.slice(meta));
|
|
297
|
+
const unresolved = tilde || climbs || /\$[A-Za-z0-9_{(@*#?$!-]|`/.test(text);
|
|
298
|
+
return { text, unresolved, glob: meta !== -1, dirGlob: meta !== -1 };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* A glob word is judged by the literal text before its first metacharacter,
|
|
303
|
+
* not by evaluating the pattern: refused when a denied entry starts with that
|
|
304
|
+
* prefix or the prefix starts with a denied entry.
|
|
305
|
+
*/
|
|
306
|
+
function checkGlob(denied: Denied, text: string, cwd: string, written: string): Verdict {
|
|
307
|
+
const prefix = text.slice(0, text.search(GLOB_META));
|
|
308
|
+
const absolute = posix.normalize(prefix.startsWith("/") ? prefix : `${cwd}/${prefix}`);
|
|
309
|
+
if (denied.readable.some((entry) => isUnder(absolute, entry))) return ALLOW;
|
|
310
|
+
for (const entry of denied.entries) {
|
|
311
|
+
if (entry.path.startsWith(absolute) || absolute.startsWith(entry.path)) {
|
|
312
|
+
return { allow: false, reason: `path "${written}" can match a path under denyPaths entry "${entry.written}"`, rule: entry.written };
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
return ALLOW;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
const CD_GLOB = /[*?[\]{]|[@!+]\(/;
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Words that can change the shell's directory in a way the matcher does not
|
|
322
|
+
* model: compound commands, function and script runners, wrappers and the
|
|
323
|
+
* directory stack. A part that starts with one makes the directory unknown.
|
|
324
|
+
*/
|
|
325
|
+
const UNMODELLED = new Set([
|
|
326
|
+
"{", "}", "if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "select",
|
|
327
|
+
"function", "time", "coproc", "!", "[[", "eval", "source", ".", "exec", "builtin", "command", "env", "pushd", "popd", "trap",
|
|
328
|
+
]);
|
|
329
|
+
|
|
330
|
+
const ASSIGNMENT_WORD = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
331
|
+
|
|
332
|
+
interface BashWord {
|
|
333
|
+
readonly word: string;
|
|
334
|
+
readonly next: string | undefined;
|
|
335
|
+
/** Position in its part; 0 is the command name. */
|
|
336
|
+
readonly index: number;
|
|
337
|
+
/** The directory relative paths of this word mean; undefined once the directory is unknown. */
|
|
338
|
+
readonly dir: string | undefined;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The words of a command with the directory each is read in, and whether a
|
|
343
|
+
* `cd` target could not be resolved. Only a plain top-level `cd <path>` in a
|
|
344
|
+
* chain is modelled; anything else that can change the directory makes it
|
|
345
|
+
* unknown for the rest of the command (`README.md`).
|
|
346
|
+
*/
|
|
347
|
+
function bashWords(parts: readonly Part[], cwd: string, home: string): { words: BashWord[]; unresolvedCd: boolean } {
|
|
348
|
+
const words: BashWord[] = [];
|
|
349
|
+
let dir: string | undefined = cwd;
|
|
350
|
+
let unresolvedCd = false;
|
|
351
|
+
parts.forEach((part, at) => {
|
|
352
|
+
const here = dir;
|
|
353
|
+
part.words.forEach((word, index) => words.push({ word, next: part.words.at(index + 1), index, dir: here }));
|
|
354
|
+
if (dir === undefined) return;
|
|
355
|
+
if (part.sep === "(" || part.sep === ")") {
|
|
356
|
+
dir = undefined;
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
let start = 0;
|
|
360
|
+
while (start < part.words.length && ASSIGNMENT_WORD.test(part.words.at(start) ?? "")) start += 1;
|
|
361
|
+
if (part.words.some((word) => word.startsWith("CDPATH=") || word === "CDPATH")) {
|
|
362
|
+
dir = undefined;
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const name = part.words.at(start) ?? "";
|
|
366
|
+
if (UNMODELLED.has(name)) {
|
|
367
|
+
dir = undefined;
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if (name !== "cd") return;
|
|
371
|
+
// A cd in a pipeline or in the background runs in a subshell.
|
|
372
|
+
const after = parts.at(at + 1)?.sep;
|
|
373
|
+
if (part.sep === "|" || part.sep === "|&" || part.sep === "&" || after === "|" || after === "|&" || after === "&") {
|
|
374
|
+
dir = undefined;
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const operands = part.words.slice(start + 1).filter((word) => word !== "--" && !/^-[LPe@]+$/.test(word));
|
|
378
|
+
const target = operands.at(0);
|
|
379
|
+
if (target === undefined || target === "-") {
|
|
380
|
+
dir = undefined;
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const expanded = expandWord(target, home);
|
|
384
|
+
if (expanded.unresolved || CD_GLOB.test(expanded.text)) {
|
|
385
|
+
unresolvedCd = true;
|
|
386
|
+
dir = undefined;
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
dir = posix.resolve(dir, expanded.text);
|
|
390
|
+
});
|
|
391
|
+
return { words, unresolvedCd };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function checkBash(profile: AccessProfile, command: string, denied: Denied | undefined): Verdict {
|
|
395
|
+
const rules = (profile.denyCommands ?? [])
|
|
396
|
+
.map((text) => parseRule(text))
|
|
397
|
+
.filter((rule): rule is Rule => rule !== undefined);
|
|
398
|
+
const { parts, substitution, extglob, ansiC } = scan(command);
|
|
399
|
+
|
|
400
|
+
if ((profile.denyCommands ?? []).length > 0) {
|
|
401
|
+
if (substitution !== undefined) {
|
|
402
|
+
return {
|
|
403
|
+
allow: false,
|
|
404
|
+
reason: `command "${command}" runs inline code (${substitution}); it is refused while denyCommands is set`,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
for (const part of parts) {
|
|
408
|
+
const form = inlineFormOf(part);
|
|
409
|
+
if (form !== undefined) {
|
|
410
|
+
return {
|
|
411
|
+
allow: false,
|
|
412
|
+
reason: `part "${part.text}" runs inline code (${form}); it is refused while denyCommands is set`,
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
const hit = findDenied(rules, parts);
|
|
417
|
+
if (hit !== undefined) {
|
|
418
|
+
return { allow: false, reason: `part "${hit.text}" is refused by denyCommands rule "${hit.rule}"`, rule: hit.rule };
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
if (denied !== undefined) {
|
|
423
|
+
const { words, unresolvedCd } = bashWords(parts, denied.cwd, denied.home);
|
|
424
|
+
let unresolved = unresolvedCd ? "a cd target" : substitution === undefined ? undefined : `a command substitution (${substitution})`;
|
|
425
|
+
if (extglob) unresolved ??= "an extended glob";
|
|
426
|
+
if (ansiC) unresolved ??= "a $'…' word with escapes";
|
|
427
|
+
for (const { word, index, dir } of words) {
|
|
428
|
+
if (dir === undefined && (index > 0 ? !word.startsWith("-") : word.includes("/")) && !expandWord(word, denied.home).text.startsWith("/")) {
|
|
429
|
+
unresolved ??= `"${word}" after a directory change it cannot follow`;
|
|
430
|
+
}
|
|
431
|
+
for (const reading of readings(word, denied.home)) {
|
|
432
|
+
const expanded = expandWord(reading, denied.home);
|
|
433
|
+
if (expanded.unresolved) {
|
|
434
|
+
unresolved ??= `"${reading}"`;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
const verdict = expanded.glob
|
|
438
|
+
? checkGlob(denied, expanded.text, dir ?? denied.cwd, reading)
|
|
439
|
+
: checkPath(denied, expanded.text, dir ?? denied.cwd, reading);
|
|
440
|
+
if (!verdict.allow) return verdict;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// A deny wins over this ask: it is only reached when no path was denied.
|
|
444
|
+
if (unresolved !== undefined) {
|
|
445
|
+
return {
|
|
446
|
+
allow: false,
|
|
447
|
+
ask: true,
|
|
448
|
+
reason: `command "${command}" uses ${unresolved}, which holds a shell expansion that cannot be matched against denyPaths; it asks`,
|
|
449
|
+
rule: "inline code",
|
|
450
|
+
kind: "command",
|
|
451
|
+
value: command,
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return ALLOW;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
interface AskedPaths {
|
|
459
|
+
readonly entries: ReadonlyArray<{ readonly written: string; readonly pattern: RegExp }>;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** The `askPaths` entries as patterns over normalised paths; `*` stays within a segment. */
|
|
463
|
+
function askedPaths(profile: AccessProfile, cwd: string, home: string): AskedPaths | undefined {
|
|
464
|
+
const entries = (profile.askPaths ?? [])
|
|
465
|
+
.filter((written) => written.length > 0)
|
|
466
|
+
.map((written) => {
|
|
467
|
+
const source = normalise(written, cwd, home)
|
|
468
|
+
.split("*")
|
|
469
|
+
.map((piece) => piece.replace(/[.+?^${}()|[\]\\]/g, "\\$&"))
|
|
470
|
+
.join("[^/]*");
|
|
471
|
+
return { written, pattern: new RegExp(`^${source}(?:/.*)?$`) };
|
|
472
|
+
});
|
|
473
|
+
return entries.length > 0 ? { entries } : undefined;
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
function askedRule(asked: AskedPaths, normal: string): string | undefined {
|
|
477
|
+
return asked.entries.find((entry) => entry.pattern.test(normal))?.written;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** The path a word or the word after it redirects output to, if it does. */
|
|
481
|
+
function redirectTarget(word: string, next: string | undefined): string | undefined {
|
|
482
|
+
const match = /^(?:\d*|&)>>?(.*)$/.exec(word);
|
|
483
|
+
if (match === null) return undefined;
|
|
484
|
+
const glued = match[1] ?? "";
|
|
485
|
+
const target = glued.length > 0 ? glued : next;
|
|
486
|
+
return target !== undefined && target.length > 0 && !target.startsWith("&") ? target : undefined;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* The ask verdict of a command, when no deny applied. A command that hides what
|
|
491
|
+
* it runs (inline code) cannot be matched, so it asks while `askCommands` is
|
|
492
|
+
* set (ADR 0025 D3).
|
|
493
|
+
*/
|
|
494
|
+
function askBash(profile: AccessProfile, command: string, asked: AskedPaths | undefined, cwd: string, home: string): Verdict {
|
|
495
|
+
const texts = profile.askCommands ?? [];
|
|
496
|
+
let found: { readonly target: string; readonly rule: string } | undefined;
|
|
497
|
+
if (texts.length === 0 && asked === undefined) return ALLOW;
|
|
498
|
+
const rules = texts.map((text) => parseRule(text)).filter((rule): rule is Rule => rule !== undefined);
|
|
499
|
+
const { parts, substitution } = scan(command);
|
|
500
|
+
const ask = (reason: string, rule: string): Verdict => ({ allow: false, ask: true, reason, rule, kind: "command", value: command });
|
|
501
|
+
if (asked !== undefined) {
|
|
502
|
+
// Only a redirect writes by itself: a word after `>` or `>>`, or glued to it.
|
|
503
|
+
const walked = bashWords(parts, cwd, home);
|
|
504
|
+
let unresolved: string | undefined;
|
|
505
|
+
let redirects = false;
|
|
506
|
+
for (const { word, next, dir } of walked.words) {
|
|
507
|
+
const target = redirectTarget(word, next);
|
|
508
|
+
if (target === undefined) continue;
|
|
509
|
+
redirects = true;
|
|
510
|
+
const expanded = expandWord(target, home);
|
|
511
|
+
if (expanded.unresolved || expanded.dirGlob) {
|
|
512
|
+
unresolved ??= `"${target}"`;
|
|
513
|
+
continue;
|
|
514
|
+
}
|
|
515
|
+
if (dir === undefined && !expanded.text.startsWith("/")) {
|
|
516
|
+
unresolved ??= `"${target}"`;
|
|
517
|
+
continue;
|
|
518
|
+
}
|
|
519
|
+
const hit = askedRule(asked, normalise(expanded.text, dir ?? cwd, home));
|
|
520
|
+
if (hit !== undefined && found === undefined) found = { target, rule: hit };
|
|
521
|
+
}
|
|
522
|
+
if (found !== undefined) return ask(`command "${command}" writes "${found.target}", which is under askPaths entry "${found.rule}"`, found.rule);
|
|
523
|
+
if (redirects && walked.unresolvedCd) unresolved ??= "a cd target";
|
|
524
|
+
if (redirects && substitution !== undefined) unresolved ??= `a command substitution (${substitution})`;
|
|
525
|
+
if (unresolved !== undefined) {
|
|
526
|
+
return ask(`command "${command}" writes to ${unresolved}, which holds a shell expansion that cannot be matched against askPaths; it asks`, "inline code");
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
if (texts.length === 0) return ALLOW;
|
|
530
|
+
if (substitution !== undefined) {
|
|
531
|
+
return ask(`command "${command}" runs inline code (${substitution}); it asks while askCommands is set`, "inline code");
|
|
532
|
+
}
|
|
533
|
+
for (const part of parts) {
|
|
534
|
+
const form = inlineFormOf(part);
|
|
535
|
+
if (form !== undefined) {
|
|
536
|
+
return ask(`part "${part.text}" runs inline code (${form}); it asks while askCommands is set`, "inline code");
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
const hit = findDenied(rules, parts);
|
|
540
|
+
if (hit !== undefined) return ask(`part "${hit.text}" matches askCommands rule "${hit.rule}"`, hit.rule);
|
|
541
|
+
return ALLOW;
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/** The tool name of a call to an MCP server's tool; its input has `server` and `tool`. */
|
|
545
|
+
export const MCP_TOOL = "mcp";
|
|
546
|
+
|
|
547
|
+
/** The words a person is asked about, and a one-time permission covers, for an MCP tool. */
|
|
548
|
+
export function mcpCallValue(server: string, tool: string): string {
|
|
549
|
+
return `mcp ${server}.${tool}`;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function matchMcp(profile: AccessProfile, call: ToolCall): Verdict {
|
|
553
|
+
// Only the field's presence puts MCP tools under the profile.
|
|
554
|
+
if (profile.allowMcp === undefined) return ALLOW;
|
|
555
|
+
const server: unknown = call.input["server"];
|
|
556
|
+
const tool: unknown = call.input["tool"];
|
|
557
|
+
if (typeof server !== "string" || typeof tool !== "string") {
|
|
558
|
+
return { allow: false, reason: "an MCP call that names no server and tool cannot be checked" };
|
|
559
|
+
}
|
|
560
|
+
const allowed = profile.allowMcp;
|
|
561
|
+
if (allowed.includes(`${server}.${tool}`) || allowed.includes(`${server}.*`)) return ALLOW;
|
|
562
|
+
return {
|
|
563
|
+
allow: false,
|
|
564
|
+
ask: true,
|
|
565
|
+
reason: `MCP tool "${server}.${tool}" is not on the allowed list; a tool nobody listed counts as a write and asks`,
|
|
566
|
+
rule: "unknown MCP tool",
|
|
567
|
+
kind: "command",
|
|
568
|
+
value: mcpCallValue(server, tool),
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Whether one tool call may run under the profile. Pure and lexical. Deny wins
|
|
574
|
+
* over ask and ask over allow: the deny rules and paths are checked first, and
|
|
575
|
+
* `askCommands` only when nothing denied the call.
|
|
576
|
+
*/
|
|
577
|
+
export function match(given: AccessProfile, call: ToolCall, options: MatchOptions = {}): Verdict {
|
|
578
|
+
const home = options.home ?? homedir();
|
|
579
|
+
// A read-only working directory is a directory whose writes ask.
|
|
580
|
+
// A directory that may be read is one whose writes ask.
|
|
581
|
+
const readPaths = (given.readPaths ?? []).filter((written) => written.length > 0);
|
|
582
|
+
const asking = [...(given.readOnly === true ? [call.cwd] : []), ...readPaths];
|
|
583
|
+
const profile: AccessProfile =
|
|
584
|
+
asking.length > 0 ? { ...given, askPaths: [...(given.askPaths ?? []), ...asking] } : given;
|
|
585
|
+
const entries = (profile.denyPaths ?? [])
|
|
586
|
+
.filter((written) => written.length > 0)
|
|
587
|
+
.map((written) => ({ written, path: normalise(written, call.cwd, home) }));
|
|
588
|
+
// Only a call that reads may go through a deny by way of `readPaths`.
|
|
589
|
+
const reads =
|
|
590
|
+
call.tool === "bash"
|
|
591
|
+
? typeof call.input["command"] === "string" && isReadOnlyCommand(call.input["command"])
|
|
592
|
+
: call.tool === "read" || call.tool === "grep" || call.tool === "find" || call.tool === "ls";
|
|
593
|
+
const readable = reads ? readPaths.map((written) => normalise(written, call.cwd, home)) : [];
|
|
594
|
+
const denied: Denied | undefined = entries.length > 0 ? { entries, cwd: call.cwd, home, readable } : undefined;
|
|
595
|
+
|
|
596
|
+
if (call.tool === "bash") {
|
|
597
|
+
const command: unknown = call.input["command"];
|
|
598
|
+
if (typeof command !== "string") return ALLOW;
|
|
599
|
+
const verdict = checkBash(profile, command, denied);
|
|
600
|
+
// A deny stays a deny; only an ask can be lifted by an always-allowed entry.
|
|
601
|
+
if (!verdict.allow && verdict.ask !== true) return verdict;
|
|
602
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
603
|
+
if (!verdict.allow) return verdict;
|
|
604
|
+
const asked = askBash(profile, command, askedPaths(profile, call.cwd, home), call.cwd, home);
|
|
605
|
+
if (!asked.allow) return asked;
|
|
606
|
+
// A read-only directory runs only commands known to read.
|
|
607
|
+
if (given.readOnly === true && !isReadOnlyCommand(command)) {
|
|
608
|
+
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 };
|
|
609
|
+
}
|
|
610
|
+
return asked;
|
|
611
|
+
}
|
|
612
|
+
if (call.tool === MCP_TOOL) {
|
|
613
|
+
// An allow_always answer to an unlisted tool is its exact command entry.
|
|
614
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
615
|
+
return matchMcp(profile, call);
|
|
616
|
+
}
|
|
617
|
+
if (PATH_TOOLS.has(call.tool)) {
|
|
618
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
619
|
+
if (typeof path === "string" && path.length > 0) {
|
|
620
|
+
if (denied !== undefined) {
|
|
621
|
+
const verdict = checkPath(denied, path);
|
|
622
|
+
if (!verdict.allow) return verdict;
|
|
623
|
+
}
|
|
624
|
+
// An always-allowed entry lifts the ask, never a deny.
|
|
625
|
+
if (alwaysAllowed(profile, call)) return ALLOW;
|
|
626
|
+
// Ask comes after deny: a write to a path that is asked about asks.
|
|
627
|
+
const asked = call.tool === "write" || call.tool === "edit" ? askedPaths(profile, call.cwd, home) : undefined;
|
|
628
|
+
const hit = asked === undefined ? undefined : askedRule(asked, normalise(path, call.cwd, home));
|
|
629
|
+
if (hit !== undefined) {
|
|
630
|
+
return { allow: false, ask: true, reason: `path "${path}" is under askPaths entry "${hit}"`, rule: hit, kind: "path", value: path, tool: call.tool };
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return ALLOW;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/**
|
|
638
|
+
* The unused grant that covers this exact call, if any. A command grant covers
|
|
639
|
+
* a bash call whose command equals the value character for character; a path
|
|
640
|
+
* grant covers a path tool call whose path names the same file. The caller must
|
|
641
|
+
* use the grant up before it lets the call run, and match as usual afterwards.
|
|
642
|
+
*/
|
|
643
|
+
export function findGrant(profile: AccessProfile, call: ToolCall, options: MatchOptions = {}): AccessGrant | undefined {
|
|
644
|
+
const home = options.home ?? homedir();
|
|
645
|
+
for (const grant of profile.grants ?? []) {
|
|
646
|
+
if (grant.kind === "command") {
|
|
647
|
+
if (call.tool === "bash" && call.input["command"] === grant.value) return grant;
|
|
648
|
+
if (call.tool === MCP_TOOL && mcpCallValue(String(call.input["server"]), String(call.input["tool"])) === grant.value) return grant;
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
// A path grant covers the tool the person approved and no other.
|
|
652
|
+
if (!PATH_TOOLS.has(call.tool) || grant.tool !== call.tool) continue;
|
|
653
|
+
const path: unknown = call.input["path"] ?? call.input["file_path"];
|
|
654
|
+
if (
|
|
655
|
+
typeof path === "string" &&
|
|
656
|
+
path.length > 0 &&
|
|
657
|
+
normalise(path, call.cwd, home) === normalise(grant.value, call.cwd, home)
|
|
658
|
+
) {
|
|
659
|
+
return grant;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return undefined;
|
|
663
|
+
}
|
package/src/readonly.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The commands a read-only working directory lets run. Anything not recognised
|
|
3
|
+
* here is not read-only: the allowlist is the rule, so a new way to write a file
|
|
4
|
+
* never needs a new pattern. A command is read-only only when every part of it
|
|
5
|
+
* (split at `|`, `;`, `&&`, `||`, `&`, newlines) is, and it has no output
|
|
6
|
+
* redirection, no substitution and no inline code.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { scan, baseName } from "./command.ts";
|
|
10
|
+
|
|
11
|
+
/** Programs that only read, whatever their arguments (the ones with a writing option are checked below). */
|
|
12
|
+
const PLAIN = new Set(["ls", "cat", "head", "tail", "wc", "grep", "rg", "pwd", "stat", "file", "du", "tree", "which", "true"]);
|
|
13
|
+
|
|
14
|
+
/** Options of an otherwise reading program that write or run something. */
|
|
15
|
+
const WRITING_OPTIONS: Readonly<Record<string, RegExp>> = {
|
|
16
|
+
tree: /^-[a-zA-Z]*o|^--output/,
|
|
17
|
+
rg: /^--pre(=|$)|^--hostname-bin|^--search-zip$|^-z$/,
|
|
18
|
+
grep: /^--output/,
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const GIT_READ = new Set(["status", "log", "diff", "show", "blame", "rev-parse", "ls-files", "ls-tree", "shortlog", "describe", "cat-file", "grep"]);
|
|
22
|
+
const GIT_WRITING_OPTION = /^--output|^--ext-diff|^--textconv|^-o$|^--open-files-in-pager|^-O/;
|
|
23
|
+
const FIND_WRITING = new Set(["-exec", "-execdir", "-ok", "-okdir", "-delete", "-fprint", "-fprint0", "-fprintf", "-fls"]);
|
|
24
|
+
const SED_SCRIPT = /^\d*(?:,(?:\d+|\$))?p$/;
|
|
25
|
+
|
|
26
|
+
function gitIsReadOnly(words: readonly string[]): boolean {
|
|
27
|
+
const sub = words[1];
|
|
28
|
+
if (sub === undefined || sub.startsWith("-")) return false;
|
|
29
|
+
const rest = words.slice(2);
|
|
30
|
+
if (sub === "branch") return rest.every((word) => ["--list", "-a", "-r", "-v", "-vv", "--show-current"].includes(word));
|
|
31
|
+
if (!GIT_READ.has(sub)) return false;
|
|
32
|
+
return !rest.some((word) => GIT_WRITING_OPTION.test(word));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function partIsReadOnly(words: readonly string[]): boolean {
|
|
36
|
+
const first = words[0];
|
|
37
|
+
if (first === undefined) return true;
|
|
38
|
+
const program = baseName(first);
|
|
39
|
+
const args = words.slice(1);
|
|
40
|
+
if (words.some((word) => word.includes(">"))) return false;
|
|
41
|
+
if (PLAIN.has(program)) return !args.some((word) => WRITING_OPTIONS[program]?.test(word) === true);
|
|
42
|
+
switch (program) {
|
|
43
|
+
case "git":
|
|
44
|
+
return gitIsReadOnly(words);
|
|
45
|
+
case "find":
|
|
46
|
+
return !args.some((word) => FIND_WRITING.has(word));
|
|
47
|
+
case "sed": {
|
|
48
|
+
if (args[0] !== "-n") return false;
|
|
49
|
+
const script = args[1];
|
|
50
|
+
return args.length >= 2 && script !== undefined && SED_SCRIPT.test(script) && !args.slice(2).some((word) => word.startsWith("-"));
|
|
51
|
+
}
|
|
52
|
+
case "bun":
|
|
53
|
+
return args[0] === "test";
|
|
54
|
+
case "bunx":
|
|
55
|
+
return args[0] === "tsc" && args.includes("--noEmit") && !args.includes("-b") && !args.includes("--build");
|
|
56
|
+
default:
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Whether a shell command only reads. */
|
|
62
|
+
export function isReadOnlyCommand(command: string): boolean {
|
|
63
|
+
const { parts, substitution } = scan(command);
|
|
64
|
+
if (substitution !== undefined) return false;
|
|
65
|
+
return parts.every((part) => partIsReadOnly(part.words));
|
|
66
|
+
}
|
package/src/summary.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a log line says about a tool call: a short summary of what ran, and the
|
|
3
|
+
* first line of an error. Never file contents, tool output or environment
|
|
4
|
+
* values.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { match, type AccessProfile } from "./index.ts";
|
|
8
|
+
import { isRecord, oneLine } from "@operad-io/engine";
|
|
9
|
+
|
|
10
|
+
/** A command is cut at this many characters. */
|
|
11
|
+
export const COMMAND_SUMMARY_CHARS = 500;
|
|
12
|
+
/** Any other summary, and an error line, is cut at this many. */
|
|
13
|
+
export const SUMMARY_CHARS = 300;
|
|
14
|
+
|
|
15
|
+
/** What a summary says of a command the reader could not read. */
|
|
16
|
+
export const COMMAND_NOT_SHOWN = "<command not shown: could not read it safely>";
|
|
17
|
+
|
|
18
|
+
/** What a log says of a refused call: the real reason names paths and commands the profile may mark secret. */
|
|
19
|
+
export const REFUSED_IN_LOG = "refused by the access profile";
|
|
20
|
+
|
|
21
|
+
/** What stands where a secret value was. */
|
|
22
|
+
const MASK = "***";
|
|
23
|
+
|
|
24
|
+
/** An environment variable whose name matches this holds a secret. */
|
|
25
|
+
const SECRET_NAME = /(KEY|TOKEN|SECRET|PASS|PASSWORD|AUTH|CREDENTIAL)/i;
|
|
26
|
+
const SECRET_MIN_CHARS = 6;
|
|
27
|
+
|
|
28
|
+
/** What the summary of a call may know besides the call. */
|
|
29
|
+
export interface SummaryOptions {
|
|
30
|
+
/** Secret values of the operad secret store; each is masked wherever it appears. */
|
|
31
|
+
readonly secrets?: readonly string[] | undefined;
|
|
32
|
+
/** The environment whose secret-named values are masked; defaults to this process's. */
|
|
33
|
+
readonly env?: Readonly<Record<string, string | undefined>> | undefined;
|
|
34
|
+
/** A command keeps its line breaks (still cut at 500 characters), for a log that shows its first line. */
|
|
35
|
+
readonly keepLines?: boolean | undefined;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Keys that hold the main argument of a tool, in the order they are tried. */
|
|
39
|
+
const MAIN_KEYS = ["file_path", "path", "notebook_path", "pattern", "query", "url", "command", "description"] as const;
|
|
40
|
+
|
|
41
|
+
/** Starts of the shell constructs the reader does not understand. */
|
|
42
|
+
const NOT_UNDERSTOOD = ["$(", "`", "<(", ">(", "<<", "$[", "$(("];
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The one shell-word reader: the words of a command with their spans. It
|
|
46
|
+
* handles single quotes, double quotes and backslashes; undefined when a quote
|
|
47
|
+
* or a trailing backslash is left open.
|
|
48
|
+
*/
|
|
49
|
+
function readWords(command: string): { start: number; end: number }[] | undefined {
|
|
50
|
+
const words: { start: number; end: number }[] = [];
|
|
51
|
+
let i = 0;
|
|
52
|
+
while (i < command.length) {
|
|
53
|
+
if (/\s/.test(command.charAt(i))) {
|
|
54
|
+
i++;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const start = i;
|
|
58
|
+
while (i < command.length && !/\s/.test(command.charAt(i))) {
|
|
59
|
+
const c = command.charAt(i);
|
|
60
|
+
if (c === "\\") {
|
|
61
|
+
if (i + 1 >= command.length) return undefined;
|
|
62
|
+
i += 2;
|
|
63
|
+
} else if (c === "'") {
|
|
64
|
+
const close = command.indexOf("'", i + 1);
|
|
65
|
+
if (close < 0) return undefined;
|
|
66
|
+
i = close + 1;
|
|
67
|
+
} else if (c === '"') {
|
|
68
|
+
i++;
|
|
69
|
+
while (i < command.length && command.charAt(i) !== '"') i += command.charAt(i) === "\\" ? 2 : 1;
|
|
70
|
+
if (i >= command.length) return undefined;
|
|
71
|
+
i++;
|
|
72
|
+
} else {
|
|
73
|
+
i++;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
words.push({ start, end: i });
|
|
77
|
+
}
|
|
78
|
+
return words;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* A command with the values of its leading assignments (`NAME=value` before the
|
|
83
|
+
* command word) shown as `***`; the placeholder text when it cannot be read.
|
|
84
|
+
*/
|
|
85
|
+
function withoutAssignmentValues(command: string): string {
|
|
86
|
+
const words = readWords(command);
|
|
87
|
+
if (words === undefined) return COMMAND_NOT_SHOWN;
|
|
88
|
+
let out = "";
|
|
89
|
+
let at = 0;
|
|
90
|
+
for (const word of words) {
|
|
91
|
+
const text = command.slice(word.start, word.end);
|
|
92
|
+
const name = /^[A-Za-z_][A-Za-z0-9_]*=/.exec(text);
|
|
93
|
+
if (name === null) break;
|
|
94
|
+
if (NOT_UNDERSTOOD.some((mark) => text.includes(mark))) return COMMAND_NOT_SHOWN;
|
|
95
|
+
out += command.slice(at, word.start) + name[0] + MASK;
|
|
96
|
+
at = word.end;
|
|
97
|
+
}
|
|
98
|
+
return out + command.slice(at);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The values in a secret store, so a log can mask them. A store that cannot be read has none. */
|
|
102
|
+
export async function secretValuesOf(store: {
|
|
103
|
+
names(): Promise<readonly string[]>;
|
|
104
|
+
get(name: string): Promise<{ reveal(): string } | undefined>;
|
|
105
|
+
}): Promise<string[]> {
|
|
106
|
+
try {
|
|
107
|
+
const values: string[] = [];
|
|
108
|
+
for (const name of await store.names()) {
|
|
109
|
+
const secret = await store.get(name);
|
|
110
|
+
if (secret !== undefined) values.push(secret.reveal());
|
|
111
|
+
}
|
|
112
|
+
return values;
|
|
113
|
+
} catch {
|
|
114
|
+
return [];
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Replaces every known secret value in the text. */
|
|
119
|
+
function withoutSecretValues(text: string, options: SummaryOptions): string {
|
|
120
|
+
const env = options.env ?? process.env;
|
|
121
|
+
const values = new Set<string>();
|
|
122
|
+
for (const value of options.secrets ?? []) if (value.length > 0) values.add(value);
|
|
123
|
+
for (const [name, value] of Object.entries(env)) {
|
|
124
|
+
if (value !== undefined && value.length >= SECRET_MIN_CHARS && SECRET_NAME.test(name)) values.add(value);
|
|
125
|
+
}
|
|
126
|
+
let out = text;
|
|
127
|
+
for (const value of [...values].sort((x, y) => y.length - x.length)) out = out.split(value).join(MASK);
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** The lines of a command, each with its spaces collapsed, blank lines kept so a count of them is true, cut at the limit. */
|
|
132
|
+
function linesOf(text: string, limit: number): string {
|
|
133
|
+
const flat = text
|
|
134
|
+
.split(/\r?\n/)
|
|
135
|
+
.map((line) => line.replace(/[ \t]+/g, " ").trim())
|
|
136
|
+
.join("\n");
|
|
137
|
+
return flat.length <= limit ? flat : `${flat.slice(0, limit - 1)}…`;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The summary of one tool call, or undefined when the tool has no main
|
|
142
|
+
* argument. `bash` shows its command (500 characters, one line), the file tools
|
|
143
|
+
* their path, others the first of pattern, query, url or description. A call the
|
|
144
|
+
* access profile denies shows only that it was denied: never its arguments.
|
|
145
|
+
*/
|
|
146
|
+
export function summarizeCall(
|
|
147
|
+
profile: AccessProfile,
|
|
148
|
+
toolName: string,
|
|
149
|
+
input: unknown,
|
|
150
|
+
cwd: string,
|
|
151
|
+
options: SummaryOptions = {},
|
|
152
|
+
): string | undefined {
|
|
153
|
+
if (!isRecord(input)) return undefined;
|
|
154
|
+
const tool = toolName.toLowerCase();
|
|
155
|
+
const verdict = match(profile, { tool, input, cwd });
|
|
156
|
+
// A call that asks a person is shown as itself: the person sees what runs.
|
|
157
|
+
if (!verdict.allow && verdict.ask !== true) {
|
|
158
|
+
return `${toolName} denied by the access profile${verdict.rule === undefined ? "" : ` (rule: ${oneLine(verdict.rule, SUMMARY_CHARS)})`}`;
|
|
159
|
+
}
|
|
160
|
+
let text: string | undefined;
|
|
161
|
+
let limit = SUMMARY_CHARS;
|
|
162
|
+
if (tool === "bash") {
|
|
163
|
+
const command = input["command"];
|
|
164
|
+
if (typeof command === "string") {
|
|
165
|
+
text = withoutAssignmentValues(command);
|
|
166
|
+
limit = COMMAND_SUMMARY_CHARS;
|
|
167
|
+
}
|
|
168
|
+
} else {
|
|
169
|
+
for (const key of MAIN_KEYS) {
|
|
170
|
+
const value = input[key];
|
|
171
|
+
if (typeof value === "string" && value.trim().length > 0) {
|
|
172
|
+
text = value;
|
|
173
|
+
break;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (text === undefined || text.trim().length === 0) return undefined;
|
|
178
|
+
const masked = withoutSecretValues(text, options);
|
|
179
|
+
return options.keepLines === true && tool === "bash" ? linesOf(masked, limit) : oneLine(masked, limit);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** The first non-empty line of an error text, cut; undefined when there is none. */
|
|
183
|
+
export function firstErrorLine(error: unknown, options: SummaryOptions = {}): string | undefined {
|
|
184
|
+
if (typeof error !== "string") return undefined;
|
|
185
|
+
const masked = withoutSecretValues(error, options);
|
|
186
|
+
for (const line of masked.split("\n")) {
|
|
187
|
+
if (line.trim().length > 0) return oneLine(line, SUMMARY_CHARS);
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** An assistant message as one paragraph of at most 300 characters; undefined when empty. */
|
|
193
|
+
export function messageSummary(text: string): string | undefined {
|
|
194
|
+
const flat = oneLine(text, SUMMARY_CHARS);
|
|
195
|
+
return flat.length === 0 ? undefined : flat;
|
|
196
|
+
}
|