@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.
@@ -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
+ }