reasonally 0.2.0 → 0.4.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.
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Which shell commands only look (Plan mode runs them without asking). Pure and deliberately
3
+ * strict: anything we can't read with certainty asks, as every command does today.
4
+ *
5
+ * A command qualifies when it's one line in a POSIX shell, made only of allowlisted programs
6
+ * joined by `|`, `&&`, `||` or `;`, with no expansion, substitution or redirection of any kind.
7
+ * The words that could name files come back so the caller can resolve them (symlinks followed)
8
+ * and check that each one stays inside the project and isn't a secret.
9
+ */
10
+ /** Shells whose quoting rules this file understands. */
11
+ const POSIX_SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh"]);
12
+ const MAX_LENGTH = 500;
13
+ const MAX_WORDS = 64;
14
+ /**
15
+ * Characters that mean expansion, substitution, redirection, globbing or more when unquoted
16
+ * (`$`, backticks, `(`, `)`, `{`, `}`, `<`, `>`, `*`, `?`, `[`, `]`, `\`, `!`, `#`).
17
+ */
18
+ const UNQUOTED_SPECIAL = new Set([..."$`(){}<>*?[]\\!#"]);
19
+ /**
20
+ * Special only where a word starts (`~` is the home folder, `=cmd` a program's path in zsh,
21
+ * `^x` a negated glob in zsh), or for `~`, right after `=` or `:`. Mid-word they're plain text,
22
+ * as in `HEAD~1` or `HEAD^`.
23
+ */
24
+ const WORD_START_SPECIAL = new Set([..."~=^"]);
25
+ /** Inside double quotes these still expand. */
26
+ const DOUBLE_QUOTED_SPECIAL = new Set([..."$`\\!"]);
27
+ /** Splits a command into segments of words, or null when it uses anything we don't accept. */
28
+ export function splitCommand(command) {
29
+ if (!command.trim() || command.length > MAX_LENGTH || /[\r\n\0]/.test(command))
30
+ return null;
31
+ const segments = [];
32
+ let words = [];
33
+ let word = "";
34
+ let inWord = false;
35
+ const endWord = () => {
36
+ if (inWord)
37
+ words.push(word);
38
+ word = "";
39
+ inWord = false;
40
+ };
41
+ const endSegment = () => {
42
+ endWord();
43
+ if (!words.length)
44
+ return false;
45
+ segments.push(words);
46
+ words = [];
47
+ return true;
48
+ };
49
+ for (let i = 0; i < command.length; i++) {
50
+ const c = command[i];
51
+ if (c === "'") {
52
+ const end = command.indexOf("'", i + 1);
53
+ if (end === -1)
54
+ return null;
55
+ word += command.slice(i + 1, end);
56
+ inWord = true;
57
+ i = end;
58
+ }
59
+ else if (c === '"') {
60
+ let j = i + 1;
61
+ for (; j < command.length && command[j] !== '"'; j++) {
62
+ if (DOUBLE_QUOTED_SPECIAL.has(command[j]))
63
+ return null;
64
+ }
65
+ if (j >= command.length)
66
+ return null;
67
+ word += command.slice(i + 1, j);
68
+ inWord = true;
69
+ i = j;
70
+ }
71
+ else if (c === " " || c === "\t") {
72
+ endWord();
73
+ }
74
+ else if (c === ";") {
75
+ if (!endSegment())
76
+ return null;
77
+ }
78
+ else if (c === "|") {
79
+ if (command[i + 1] === "&")
80
+ return null;
81
+ if (command[i + 1] === "|")
82
+ i++;
83
+ if (!endSegment())
84
+ return null;
85
+ }
86
+ else if (c === "&") {
87
+ if (command[i + 1] !== "&")
88
+ return null;
89
+ i++;
90
+ if (!endSegment())
91
+ return null;
92
+ }
93
+ else if (UNQUOTED_SPECIAL.has(c)) {
94
+ return null;
95
+ }
96
+ else {
97
+ if (WORD_START_SPECIAL.has(c)) {
98
+ const prev = word.at(-1);
99
+ if (!inWord || (c === "~" && (prev === "=" || prev === ":")))
100
+ return null;
101
+ }
102
+ word += c;
103
+ inWord = true;
104
+ }
105
+ }
106
+ if (!endSegment())
107
+ return null;
108
+ return segments;
109
+ }
110
+ const isFlag = (w) => w.startsWith("-") && w !== "-";
111
+ /** `-abc` (not `--abc`): its letters, for programs whose short flags can be grouped. */
112
+ const shortLetters = (w) => (w.startsWith("-") && !w.startsWith("--") ? w.slice(1) : "");
113
+ const longName = (w) => (w.startsWith("--") ? w.slice(2).split("=")[0] : null);
114
+ /** Refuses a flag when its long name is listed, or a short group has a listed letter. */
115
+ function flagsAllowed(args, longs, letters = "") {
116
+ for (const arg of args) {
117
+ if (!isFlag(arg))
118
+ continue;
119
+ const name = longName(arg);
120
+ if (name !== null) {
121
+ if (longs.some((l) => (l.endsWith("*") ? name.startsWith(l.slice(0, -1)) : name === l))) {
122
+ return false;
123
+ }
124
+ }
125
+ else if ([...shortLetters(arg)].some((ch) => letters.includes(ch))) {
126
+ return false;
127
+ }
128
+ }
129
+ return true;
130
+ }
131
+ const any = { allowed: () => true };
132
+ const PROGRAMS = {
133
+ ls: any,
134
+ pwd: any,
135
+ echo: any,
136
+ cat: any,
137
+ head: any,
138
+ basename: any,
139
+ dirname: any,
140
+ realpath: any,
141
+ which: any,
142
+ cmp: any,
143
+ stat: any,
144
+ tail: { allowed: (a) => flagsAllowed(a, ["follow*", "retry", "pid*"], "fF") },
145
+ wc: { allowed: (a) => flagsAllowed(a, ["files0-from*"]) },
146
+ du: { allowed: (a) => flagsAllowed(a, ["files0-from*"]) },
147
+ tree: { allowed: (a) => flagsAllowed(a, ["fromfile", "output*"], "oR") },
148
+ diff: {
149
+ allowed: (a) => flagsAllowed(a, ["recursive", "from-file*", "to-file*", "output*"], "r"),
150
+ },
151
+ grep: {
152
+ pattern: true,
153
+ allowed: (a) => flagsAllowed(a, ["recursive", "dereference-recursive", "directories*", "devices*", "file"], "rRdDf"),
154
+ },
155
+ rg: {
156
+ pattern: true,
157
+ allowed: (a) => flagsAllowed(a, ["pre", "pre-glob", "search-zip", "hidden", "unrestricted", "no-ignore*", "follow", "file"], "zuL.f"),
158
+ },
159
+ find: {
160
+ allowed: (a) => !a.some((w) => [
161
+ "-exec",
162
+ "-execdir",
163
+ "-ok",
164
+ "-okdir",
165
+ "-delete",
166
+ "-fprint",
167
+ "-fprint0",
168
+ "-fprintf",
169
+ "-fls",
170
+ "-L",
171
+ "-H",
172
+ "-follow",
173
+ ].includes(w)),
174
+ },
175
+ };
176
+ /** git subcommands that only read, and any extra rule for their arguments. */
177
+ const GIT_READS = {
178
+ status: () => true,
179
+ log: () => true,
180
+ show: () => true,
181
+ diff: () => true,
182
+ blame: () => true,
183
+ "ls-files": () => true,
184
+ "ls-tree": () => true,
185
+ "rev-parse": () => true,
186
+ describe: () => true,
187
+ shortlog: () => true,
188
+ grep: (a) => flagsAllowed(a, ["open-files-in-pager*"], "O"),
189
+ // Only the forms that list: any other word would create, rename or delete.
190
+ branch: (a) => listingOnly(a, ["-l", "--list"]),
191
+ tag: (a) => listingOnly(a, ["-l", "--list"]),
192
+ remote: (a) => a.every((w) => w === "-v" || w === "--verbose"),
193
+ stash: (a) => a[0] === "list" || a[0] === "show",
194
+ };
195
+ const BRANCH_TAG_FLAGS = new Set([
196
+ "-a",
197
+ "--all",
198
+ "-r",
199
+ "--remotes",
200
+ "-v",
201
+ "-vv",
202
+ "--verbose",
203
+ "-l",
204
+ "--list",
205
+ "--show-current",
206
+ "--merged",
207
+ "--no-merged",
208
+ "--contains",
209
+ "--no-contains",
210
+ "--points-at",
211
+ "--no-color",
212
+ "--color",
213
+ "--sort",
214
+ "--format",
215
+ "--column",
216
+ "--no-column",
217
+ "-n",
218
+ ]);
219
+ /** Only listing flags; plain words (patterns, commits) only after a flag that lists. */
220
+ function listingOnly(args, listFlags) {
221
+ const listing = args.some((a) => listFlags.includes(a));
222
+ let afterValueFlag = false;
223
+ for (const arg of args) {
224
+ if (isFlag(arg)) {
225
+ const name = arg.split("=")[0];
226
+ if (!BRANCH_TAG_FLAGS.has(name) && !/^-n\d+$/.test(arg))
227
+ return false;
228
+ afterValueFlag =
229
+ !arg.includes("=") &&
230
+ ["--merged", "--no-merged", "--contains", "--no-contains", "--points-at"].includes(name);
231
+ }
232
+ else {
233
+ if (!listing && !afterValueFlag)
234
+ return false;
235
+ afterValueFlag = false;
236
+ }
237
+ }
238
+ return true;
239
+ }
240
+ /** Flags no read-only git command needs, and that write files or run programs. */
241
+ const GIT_FORBIDDEN = ["output*", "ext-diff", "exec*", "upload-pack*", "receive-pack*"];
242
+ /** The words of one segment that could name files, or null when it might change something. */
243
+ function segmentPaths(words) {
244
+ const [program, ...rest] = words;
245
+ if (program.includes("/") || program.includes("="))
246
+ return null;
247
+ let args = rest;
248
+ let rule;
249
+ if (program === "git") {
250
+ const [sub, ...gitArgs] = rest;
251
+ // Global options (-c, -C, --git-dir, -p…) come before the subcommand: none are accepted.
252
+ if (!sub || isFlag(sub))
253
+ return null;
254
+ const check = GIT_READS[sub];
255
+ if (!check || !check(gitArgs) || !flagsAllowed(gitArgs, GIT_FORBIDDEN))
256
+ return null;
257
+ args = gitArgs;
258
+ rule = { allowed: () => true, pattern: sub === "grep" };
259
+ }
260
+ else {
261
+ rule = PROGRAMS[program];
262
+ if (!rule || !rule.allowed(args))
263
+ return null;
264
+ }
265
+ const paths = [];
266
+ // A pattern given by flag (or a listing with none) means every plain word is a file.
267
+ const noPatternWord = args.some((a) => ["-e", "-f", "--regexp", "--file", "--files", "--type-list"].includes(a.split("=")[0]));
268
+ let skipPattern = Boolean(rule.pattern) && !noPatternWord;
269
+ let afterE = false;
270
+ for (const arg of args) {
271
+ if (afterE) {
272
+ // The word after -e is a pattern, not a file.
273
+ afterE = false;
274
+ continue;
275
+ }
276
+ if (arg === "-e" || arg === "--regexp") {
277
+ afterE = true;
278
+ continue;
279
+ }
280
+ if (isFlag(arg)) {
281
+ // A value given with `=` might name a file (`--exclude-from=…`): check it too.
282
+ const eq = arg.indexOf("=");
283
+ if (eq !== -1 && eq < arg.length - 1)
284
+ paths.push(arg.slice(eq + 1));
285
+ continue;
286
+ }
287
+ if (skipPattern) {
288
+ skipPattern = false;
289
+ continue;
290
+ }
291
+ paths.push(arg);
292
+ }
293
+ return paths;
294
+ }
295
+ /**
296
+ * The words that could name files when `command` only looks, else null. `shell` is the name of
297
+ * the shell commands run in (`zsh`, `bash`…); any other shell's rules aren't ours to guess.
298
+ */
299
+ export function readOnlyWords(command, shell) {
300
+ if (!POSIX_SHELLS.has(shell))
301
+ return null;
302
+ const segments = splitCommand(command);
303
+ if (!segments)
304
+ return null;
305
+ if (segments.reduce((n, s) => n + s.length, 0) > MAX_WORDS)
306
+ return null;
307
+ const paths = [];
308
+ for (const segment of segments) {
309
+ const found = segmentPaths(segment);
310
+ if (!found)
311
+ return null;
312
+ paths.push(...found);
313
+ }
314
+ return paths;
315
+ }