pi-keeper 0.1.0 → 0.1.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/CHANGELOG.md +78 -0
- package/extensions/ask-mailbox.ts +22 -4
- package/extensions/ask-server.ts +15 -6
- package/extensions/child-cwd.ts +4 -2
- package/extensions/config.ts +24 -12
- package/extensions/index.ts +254 -68
- package/extensions/modes.ts +59 -7
- package/extensions/options.ts +9 -0
- package/extensions/preview.ts +5 -3
- package/extensions/project-rules.ts +81 -12
- package/extensions/remote-relay.ts +10 -5
- package/extensions/rulebook.ts +61 -1
- package/extensions/rules-view.ts +35 -16
- package/extensions/rules.ts +189 -22
- package/extensions/session-grant-store.ts +18 -0
- package/extensions/session-grants.ts +9 -3
- package/extensions/settings-panel.ts +80 -22
- package/extensions/telemetry.ts +99 -2
- package/extensions/ui-relay.ts +6 -1
- package/extensions/utils.ts +1108 -105
- package/package.json +5 -2
- package/prompt-templates/new-rule.md +30 -0
package/extensions/utils.ts
CHANGED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
|
|
24
24
|
import { spawnSync } from "node:child_process";
|
|
25
25
|
import { chmodSync, existsSync, lstatSync, mkdtempSync, readdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
|
|
26
|
-
import { homedir, tmpdir } from "node:os";
|
|
26
|
+
import { homedir, tmpdir, userInfo } from "node:os";
|
|
27
27
|
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
28
28
|
|
|
29
29
|
import {
|
|
@@ -55,12 +55,15 @@ import {
|
|
|
55
55
|
REMOVAL_SUBCOMMANDS,
|
|
56
56
|
RTK_RUNNERS,
|
|
57
57
|
RUNNER_SUBCOMMANDS,
|
|
58
|
+
RUNNER_VALUE_OPTIONS,
|
|
58
59
|
SAFE_ENV_PREFIXES,
|
|
59
60
|
SAFE_ENV_VARS,
|
|
60
61
|
SAFETY_OFF_FLAGS,
|
|
61
62
|
SECRET_FILE_PATTERNS,
|
|
62
63
|
SECRET_HOME_PATHS,
|
|
63
64
|
SHELLS,
|
|
65
|
+
SHELL_RESERVED_WORDS,
|
|
66
|
+
NEVER_RULE_ROOTS,
|
|
64
67
|
WRAPPERS,
|
|
65
68
|
WRITE_FLAGS,
|
|
66
69
|
PROGRAM_FLAGS,
|
|
@@ -134,6 +137,11 @@ export function tokenize(command: string, scratch?: string): Segment[] | null {
|
|
|
134
137
|
}
|
|
135
138
|
if (inDouble) {
|
|
136
139
|
if (ch === "\\") {
|
|
140
|
+
// backslash-newline is a line continuation: bash removes both
|
|
141
|
+
if (command[i + 1] === "\n") {
|
|
142
|
+
i += 2;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
137
145
|
word += command[i + 1] ?? "";
|
|
138
146
|
i += 2;
|
|
139
147
|
continue;
|
|
@@ -145,6 +153,11 @@ export function tokenize(command: string, scratch?: string): Segment[] | null {
|
|
|
145
153
|
}
|
|
146
154
|
|
|
147
155
|
if (ch === "\\") {
|
|
156
|
+
// line continuation: the word goes on after the newline, and nothing starts
|
|
157
|
+
if (command[i + 1] === "\n") {
|
|
158
|
+
i += 2;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
148
161
|
word += command[i + 1] ?? "";
|
|
149
162
|
wordStarted = true;
|
|
150
163
|
i += 2;
|
|
@@ -221,6 +234,15 @@ export function tokenize(command: string, scratch?: string): Segment[] | null {
|
|
|
221
234
|
while (i < command.length && command[i] !== "\n") i++;
|
|
222
235
|
continue;
|
|
223
236
|
}
|
|
237
|
+
// $"…" quotes like "…". $'…' quotes like '…' unless it holds a backslash (its escapes are not read, so the `$` stays)
|
|
238
|
+
if (ch === "$") {
|
|
239
|
+
const close = command.indexOf("'", i + 2);
|
|
240
|
+
const plainAnsi = command[i + 1] === "'" && close !== -1 && !command.slice(i + 2, close).includes("\\");
|
|
241
|
+
if (command[i + 1] === '"' || plainAnsi) {
|
|
242
|
+
i++;
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
224
246
|
// globs, brace expansion and unquoted $ expansion can turn one word
|
|
225
247
|
// into several (or into flags: `{-delete,}`, `x${IFS}-delete`)
|
|
226
248
|
if (ch === "*" || ch === "?" || ch === "[" || ch === "$") wordGlob = true;
|
|
@@ -294,16 +316,70 @@ function isBraceExpansion(command: string, start: number): boolean {
|
|
|
294
316
|
* surrounding quotes trimmed. Only used to FIND deny/ask commands.
|
|
295
317
|
*/
|
|
296
318
|
function looseUnits(command: string): string[][] {
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
319
|
+
// read the raw text and the continuation-joined copy: `su\<newline>do` is `sudo` to bash
|
|
320
|
+
const joined = joinContinuations(command);
|
|
321
|
+
const texts = joined === command ? [command] : [command, joined];
|
|
322
|
+
return texts.flatMap((text) =>
|
|
323
|
+
text
|
|
324
|
+
.split(/\$\(|[`;&|\n(){}]/)
|
|
325
|
+
.map((chunk) =>
|
|
326
|
+
chunk
|
|
327
|
+
// redirect operators split words; their targets stay (`x>>.git/y`)
|
|
328
|
+
.split(/\s+|[0-9]*[<>]+&?/)
|
|
329
|
+
.map((w) => w.replace(/^['"]+|['"]+$/g, ""))
|
|
330
|
+
.filter((w) => w !== ""),
|
|
331
|
+
)
|
|
332
|
+
.filter((unit) => unit.length > 0),
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Copy of text with bash line continuations removed: a backslash-newline
|
|
338
|
+
* outside single quotes, unless the backslash is itself escaped (`\\` then a
|
|
339
|
+
* real newline keeps both the backslash and the newline).
|
|
340
|
+
*/
|
|
341
|
+
function joinContinuations(text: string): string {
|
|
342
|
+
let out = "";
|
|
343
|
+
let quote: string | undefined;
|
|
344
|
+
let comment = false;
|
|
345
|
+
let wordStart = true;
|
|
346
|
+
for (let i = 0; i < text.length; i++) {
|
|
347
|
+
const ch = text[i] ?? "";
|
|
348
|
+
if (comment) {
|
|
349
|
+
// a comment does not continue: its backslashes and newline are kept
|
|
350
|
+
if (ch === "\n") {
|
|
351
|
+
comment = false;
|
|
352
|
+
wordStart = true;
|
|
353
|
+
}
|
|
354
|
+
out += ch;
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
if (quote === "'") {
|
|
358
|
+
if (ch === "'") quote = undefined;
|
|
359
|
+
out += ch;
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
if (ch === "\\") {
|
|
363
|
+
if (text[i + 1] === "\n") {
|
|
364
|
+
i++;
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
out += ch + (text[i + 1] ?? "");
|
|
368
|
+
i++;
|
|
369
|
+
wordStart = false;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (quote === '"') {
|
|
373
|
+
if (ch === '"') quote = undefined;
|
|
374
|
+
} else if (ch === "'" || ch === '"') {
|
|
375
|
+
quote = ch;
|
|
376
|
+
wordStart = false;
|
|
377
|
+
} else if (ch === "#" && wordStart) {
|
|
378
|
+
comment = true;
|
|
379
|
+
} else wordStart = " \t\n;&|()<>".includes(ch);
|
|
380
|
+
out += ch;
|
|
381
|
+
}
|
|
382
|
+
return out;
|
|
307
383
|
}
|
|
308
384
|
|
|
309
385
|
/** Heredoc body or here-string, and the root of the command reading it. */
|
|
@@ -325,6 +401,61 @@ const HERESTRING = /<<<\s*('[^']*'|"(?:[^"\\]|\\.)*"|(?:\$\([^)]*\)|[^\s;&|)])+)
|
|
|
325
401
|
const HEREDOC = /<<(-?)[ \t]*((?:\\|['"])?[A-Za-z_][^\s;&|<>()]*)/;
|
|
326
402
|
const PIPE_TO_SHELL = /\|&?\s*(\S*\/)?(ba|z|da|k|fi)?sh\b/;
|
|
327
403
|
|
|
404
|
+
/**
|
|
405
|
+
* True when the line text[from, end) ends in a backslash that bash reads as a
|
|
406
|
+
* continuation: unescaped, outside single quotes, outside a `#` comment, and
|
|
407
|
+
* not inside an unterminated quote. Scans from `from` so quotes and comments
|
|
408
|
+
* begun earlier on the logical line count.
|
|
409
|
+
*/
|
|
410
|
+
function continuesAt(text: string, from: number, end: number): boolean {
|
|
411
|
+
let quote: string | undefined;
|
|
412
|
+
let comment = false;
|
|
413
|
+
let wordStart = true;
|
|
414
|
+
for (let i = from; i < end; i++) {
|
|
415
|
+
const ch = text[i] ?? "";
|
|
416
|
+
if (comment) {
|
|
417
|
+
if (ch === "\n") {
|
|
418
|
+
comment = false;
|
|
419
|
+
wordStart = true;
|
|
420
|
+
}
|
|
421
|
+
continue;
|
|
422
|
+
}
|
|
423
|
+
if (quote === "'") {
|
|
424
|
+
if (ch === "'") quote = undefined;
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
if (ch === "\\") {
|
|
428
|
+
if (i + 1 === end) return quote === undefined;
|
|
429
|
+
i++;
|
|
430
|
+
wordStart = false;
|
|
431
|
+
continue;
|
|
432
|
+
}
|
|
433
|
+
if (quote === '"') {
|
|
434
|
+
if (ch === '"') quote = undefined;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (ch === "'" || ch === '"') {
|
|
438
|
+
quote = ch;
|
|
439
|
+
wordStart = false;
|
|
440
|
+
continue;
|
|
441
|
+
}
|
|
442
|
+
if (ch === "#" && wordStart) {
|
|
443
|
+
comment = true;
|
|
444
|
+
continue;
|
|
445
|
+
}
|
|
446
|
+
wordStart = " \t\n;&|()<>".includes(ch);
|
|
447
|
+
}
|
|
448
|
+
return false;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** End of the logical line that starts at `from`: the first newline that no backslash continues, or -1. */
|
|
452
|
+
function logicalLineEnd(text: string, from: number): number {
|
|
453
|
+
for (let end = text.indexOf("\n", from); end !== -1; end = text.indexOf("\n", end + 1)) {
|
|
454
|
+
if (!continuesAt(text, from, end)) return end;
|
|
455
|
+
}
|
|
456
|
+
return -1;
|
|
457
|
+
}
|
|
458
|
+
|
|
328
459
|
/** Rest of the line from `index`, without the following heredoc body. */
|
|
329
460
|
function restOfLine(text: string, index: number): string {
|
|
330
461
|
const end = text.indexOf("\n", index);
|
|
@@ -359,20 +490,22 @@ function extractStdinFeeds(command: string): { text: string; feeds: StdinFeed[]
|
|
|
359
490
|
for (let m = HEREDOC.exec(text); m !== null; m = HEREDOC.exec(text)) {
|
|
360
491
|
const consumer = consumerAt(text, m.index);
|
|
361
492
|
const opEnd = m.index + m[0].length;
|
|
362
|
-
|
|
493
|
+
// the body starts after the logical line, which a backslash continues; the operator is read joined (`<<EOF\<newline>| sh`)
|
|
494
|
+
const lineEnd = logicalLineEnd(text, m.index);
|
|
363
495
|
if (lineEnd === -1) {
|
|
364
496
|
text = text.slice(0, m.index) + text.slice(opEnd);
|
|
365
497
|
continue;
|
|
366
498
|
}
|
|
367
|
-
const
|
|
368
|
-
const
|
|
499
|
+
const op = HEREDOC.exec(joinContinuations(text.slice(m.index, lineEnd))) ?? m;
|
|
500
|
+
const stripTabs = op[1] === "-";
|
|
501
|
+
const delimiter = op[2].replace(/['"\\]/g, "");
|
|
369
502
|
const lines = text.slice(lineEnd + 1).split("\n");
|
|
370
503
|
const end = lines.findIndex((l) => (stripTabs ? l.replace(/^\t+/, "") : l) === delimiter);
|
|
371
504
|
feeds.push({
|
|
372
505
|
consumer,
|
|
373
|
-
pipedToShell: PIPE_TO_SHELL.test(
|
|
506
|
+
pipedToShell: PIPE_TO_SHELL.test(joinContinuations(text.slice(opEnd, lineEnd))),
|
|
374
507
|
script: lines.slice(0, end === -1 ? lines.length : end).join("\n"),
|
|
375
|
-
expands: !/['"\\]/.test(
|
|
508
|
+
expands: !/['"\\]/.test(op[2]),
|
|
376
509
|
});
|
|
377
510
|
const after = end === -1 ? "" : lines.slice(end + 1).join("\n");
|
|
378
511
|
text = text.slice(0, m.index) + text.slice(opEnd, lineEnd + 1) + after;
|
|
@@ -624,7 +757,8 @@ export function maskScratchHeredocs(command: string, scratch: string | undefined
|
|
|
624
757
|
const opEnd = at + m[0].length;
|
|
625
758
|
const lineStart = text.lastIndexOf("\n", at - 1) + 1;
|
|
626
759
|
const lineEnd = text.indexOf("\n", opEnd);
|
|
627
|
-
|
|
760
|
+
// a continued operator line is left to the normal checks
|
|
761
|
+
if (lineEnd === -1 || continuesAt(text, at, lineEnd)) continue;
|
|
628
762
|
const consumer = looseUnits(text.slice(lineStart, at)).at(-1)?.[0];
|
|
629
763
|
const rest = restOfLine(text, opEnd);
|
|
630
764
|
if (consumer === undefined || basename(consumer) !== "cat" || PIPE_TO_SHELL.test(rest) || !/>/.test(text.slice(lineStart, at) + rest)) continue;
|
|
@@ -808,6 +942,7 @@ function awkProgramProblem(program: string): string | undefined {
|
|
|
808
942
|
if (/\bgetline\b/.test(program)) return "`awk` program reads from a command or a file (`getline`)";
|
|
809
943
|
if (/@(?:include|load)\b/.test(program)) return "`awk` program loads another program (`@include`/`@load`)";
|
|
810
944
|
const code = awkCode(program);
|
|
945
|
+
if (code === undefined) return "`awk` program has a `/` after `+` or `-` that could be a regex or a division";
|
|
811
946
|
// a single `|` pipes into a command; `||` is a comparison
|
|
812
947
|
if (/(^|[^|])\|([^|]|$)/.test(code)) return "`awk` program pipes into a command";
|
|
813
948
|
if (/\bprintf?\b[^;{}]*>>?/.test(code)) return "`awk` program writes to a file";
|
|
@@ -820,7 +955,7 @@ function awkProgramProblem(program: string): string | undefined {
|
|
|
820
955
|
* word, a number or `)` it is a division and stays, so nothing can hide in
|
|
821
956
|
* what this function removes.
|
|
822
957
|
*/
|
|
823
|
-
function awkCode(program: string): string {
|
|
958
|
+
function awkCode(program: string): string | undefined {
|
|
824
959
|
let out = "";
|
|
825
960
|
let prev = "";
|
|
826
961
|
let i = 0;
|
|
@@ -838,7 +973,10 @@ function awkCode(program: string): string {
|
|
|
838
973
|
prev = '"';
|
|
839
974
|
continue;
|
|
840
975
|
}
|
|
841
|
-
|
|
976
|
+
// `x++ / 2` and `x-- / 2`: postfix increment or decrement, a division
|
|
977
|
+
if (ch === "/" && awkRegexStartsAfter(prev) && !/(\+\+|--)$/.test(out.trimEnd())) {
|
|
978
|
+
// after a single `+` or `-` the slash may start a regex or divide: not read-only
|
|
979
|
+
if (/[+-]$/.test(out.trimEnd())) return undefined;
|
|
842
980
|
let j = i + 1;
|
|
843
981
|
let closed = false;
|
|
844
982
|
while (j < program.length && program[j] !== "\n") {
|
|
@@ -1122,7 +1260,20 @@ const GIT_REPO_FLAGS = new Set(["-C", "--git-dir", "--work-tree"]);
|
|
|
1122
1260
|
* Why a git invocation isn't read-only, or undefined when it is (also used
|
|
1123
1261
|
* for `rtk git ...`; `label` names the command in the reason).
|
|
1124
1262
|
*/
|
|
1125
|
-
|
|
1263
|
+
/** Git forms that run a program named in their arguments (`rebase --exec`, `submodule foreach`, `bisect run`, `difftool -x`). */
|
|
1264
|
+
function gitProgramForm(sub: string, rest: string[]): string | undefined {
|
|
1265
|
+
const longName = (a: string): string => (a.startsWith("--") ? a.split("=")[0] : "");
|
|
1266
|
+
// getopt-style: any unambiguous abbreviation of the long option (at least `min` characters) counts
|
|
1267
|
+
const isLong = (a: string, full: string, min: number): boolean => longName(a).length >= min && full.startsWith(longName(a));
|
|
1268
|
+
const firstWord = rest.find((a) => !a.startsWith("-"));
|
|
1269
|
+
if (sub === "rebase" && rest.some((a) => /^-[a-zA-Z]*x/.test(a) || isLong(a, "--exec", 4))) return "`git rebase --exec` runs a command";
|
|
1270
|
+
if (sub === "submodule" && firstWord === "foreach") return "`git submodule foreach` runs a command in each submodule";
|
|
1271
|
+
if (sub === "bisect" && firstWord === "run") return "`git bisect run` runs a command";
|
|
1272
|
+
if (sub === "difftool" && rest.some((a) => a === "-x" || isLong(a, "--extcmd", 5))) return "`git difftool -x` runs a command";
|
|
1273
|
+
return undefined;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
function gitBlocker(args: string[], cwd: string | undefined, label = "git", gitRepos?: readonly string[]): Blocker | undefined {
|
|
1126
1277
|
const outputs = optionValues(args, "", ["--output"], "", false, 4);
|
|
1127
1278
|
if (outputs === null || outputs.length > 0) {
|
|
1128
1279
|
const words = outputs ?? [];
|
|
@@ -1146,7 +1297,7 @@ function gitBlocker(args: string[], cwd: string | undefined, label = "git"): Blo
|
|
|
1146
1297
|
if (GIT_REPO_FLAGS.has(flag)) {
|
|
1147
1298
|
const dir = inline ?? args[i + 1];
|
|
1148
1299
|
// the target must be inside the cwd and in the cwd's own repo (a nested repo's hooks and fsmonitor would run)
|
|
1149
|
-
if (cwd === undefined || dir === undefined ||
|
|
1300
|
+
if (cwd === undefined || dir === undefined || foreignGitDir(resolvePath(dir, cwd), cwd, gitRepos)) {
|
|
1150
1301
|
return execBlock(`\`${label} ${flag}\` points git outside the working directory (that repo's config and hooks would run)`);
|
|
1151
1302
|
}
|
|
1152
1303
|
if (inline === undefined) i++;
|
|
@@ -1163,6 +1314,8 @@ function gitBlocker(args: string[], cwd: string | undefined, label = "git"): Blo
|
|
|
1163
1314
|
const opensPager = sub === "grep" && rest.some((a) => /^-O/.test(a) || a.startsWith("--open-files-in-pager"));
|
|
1164
1315
|
return opensPager ? execBlock(`\`${label} grep -O\` opens matches in another program`) : undefined;
|
|
1165
1316
|
}
|
|
1317
|
+
const program = gitProgramForm(sub, rest);
|
|
1318
|
+
if (program !== undefined) return execBlock(program);
|
|
1166
1319
|
const withArgs = plain(`\`${[label, sub, rest[0]].filter((w) => w !== undefined).join(" ")}\` can change the repository`);
|
|
1167
1320
|
switch (sub) {
|
|
1168
1321
|
case "branch":
|
|
@@ -1256,7 +1409,7 @@ function globReachesOutside(word: string, cwd: string | undefined): boolean {
|
|
|
1256
1409
|
const RTK_NATIVE: Record<string, string> = { find: "find", rg: "rg", grep: "rg", tree: "tree" };
|
|
1257
1410
|
|
|
1258
1411
|
/** Why an rtk invocation isn't read-only, or undefined when it is. */
|
|
1259
|
-
function rtkBlocker(args: string[], globs: boolean[], cwd: string | undefined): Blocker | undefined {
|
|
1412
|
+
function rtkBlocker(args: string[], globs: boolean[], cwd: string | undefined, gitRepos?: readonly string[]): Blocker | undefined {
|
|
1260
1413
|
let i = 0;
|
|
1261
1414
|
// only display-only global flags are known; any other changes what rtk does
|
|
1262
1415
|
while (i < args.length && args[i].startsWith("-")) {
|
|
@@ -1267,7 +1420,7 @@ function rtkBlocker(args: string[], globs: boolean[], cwd: string | undefined):
|
|
|
1267
1420
|
if (sub === undefined) return plain("`rtk` without a subcommand");
|
|
1268
1421
|
const rest = args.slice(i + 1);
|
|
1269
1422
|
const restGlobs = globs.slice(i + 1);
|
|
1270
|
-
if (sub === "git") return gitBlocker(rest, cwd, "rtk git");
|
|
1423
|
+
if (sub === "git") return gitBlocker(rest, cwd, "rtk git", gitRepos);
|
|
1271
1424
|
const native = RTK_NATIVE[sub];
|
|
1272
1425
|
if (native !== undefined) {
|
|
1273
1426
|
const glob = rest.find((word, k) => restGlobs[k] && globMayBecomeFlag(word));
|
|
@@ -1404,7 +1557,7 @@ const SHELL_SYNTAX_WORDS = new Set(["for", "while", "until", "if", "then", "else
|
|
|
1404
1557
|
* single source of truth for read-only detection: isReadOnlySegment and
|
|
1405
1558
|
* the dialog's "Why" line both come from here.
|
|
1406
1559
|
*/
|
|
1407
|
-
function segmentBlocker(segment: Segment, cwd: string | undefined, scratch?: string, viaXargs = false, dir?: string, fetchHosts?: readonly string[]): Blocker | undefined {
|
|
1560
|
+
function segmentBlocker(segment: Segment, cwd: string | undefined, scratch?: string, viaXargs = false, dir?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): Blocker | undefined {
|
|
1408
1561
|
const stripped = stripPrefixes(segment.argv, segment.globs, true);
|
|
1409
1562
|
if (stripped === null) {
|
|
1410
1563
|
const name = segment.argv.map((w) => ASSIGNMENT.exec(w)?.[1]).find((n) => n !== undefined && !isSafeEnvVar(n));
|
|
@@ -1415,7 +1568,7 @@ function segmentBlocker(segment: Segment, cwd: string | undefined, scratch?: str
|
|
|
1415
1568
|
// a 1:1 rtk proxy is analysed as the real command (`rtk npm test` → `npm test`)
|
|
1416
1569
|
const canon = canonicalize(stripped.argv);
|
|
1417
1570
|
if (canon.length !== stripped.argv.length) {
|
|
1418
|
-
return segmentBlocker({ argv: canon, globs: stripped.globs.slice(stripped.argv.length - canon.length) }, cwd, scratch, viaXargs, dir, fetchHosts);
|
|
1571
|
+
return segmentBlocker({ argv: canon, globs: stripped.globs.slice(stripped.argv.length - canon.length) }, cwd, scratch, viaXargs, dir, fetchHosts, gitRepos);
|
|
1419
1572
|
}
|
|
1420
1573
|
const [root, ...args] = stripped.argv;
|
|
1421
1574
|
const argGlobs = stripped.globs.slice(1);
|
|
@@ -1459,9 +1612,9 @@ function segmentBlocker(segment: Segment, cwd: string | undefined, scratch?: str
|
|
|
1459
1612
|
|
|
1460
1613
|
switch (root) {
|
|
1461
1614
|
case "git":
|
|
1462
|
-
return gitBlocker(args, cwd);
|
|
1615
|
+
return gitBlocker(args, cwd, "git", gitRepos);
|
|
1463
1616
|
case "rtk":
|
|
1464
|
-
return rtkBlocker(args, argGlobs, cwd);
|
|
1617
|
+
return rtkBlocker(args, argGlobs, cwd, gitRepos);
|
|
1465
1618
|
case "node":
|
|
1466
1619
|
return args.length > 0 && args.every((a) => a === "--version" || a === "-v") ? undefined : plain("`node` runs code (only `node --version` is read-only)");
|
|
1467
1620
|
case "npm":
|
|
@@ -1471,7 +1624,8 @@ function segmentBlocker(segment: Segment, cwd: string | undefined, scratch?: str
|
|
|
1471
1624
|
? undefined
|
|
1472
1625
|
: plain(`\`${[root, args[0]].filter(Boolean).join(" ")}\` isn't a read-only ${root} command`);
|
|
1473
1626
|
case "cd":
|
|
1474
|
-
|
|
1627
|
+
// a cd into a git repo the user granted (see inGrantedRepo) is no blocker, so git there can be judged
|
|
1628
|
+
return cwd !== undefined && args.length === 1 && (isInside(resolvePath(args[0], cwd), resolve(cwd)) || cdIntoScratch(args[0], dir ?? cwd, scratch) || inGrantedRepo(resolvePath(args[0], dir ?? cwd), gitRepos))
|
|
1475
1629
|
? undefined
|
|
1476
1630
|
: plain("`cd` leaves the working directory");
|
|
1477
1631
|
case "uniq":
|
|
@@ -1990,12 +2144,15 @@ const HARMLESS_DEVICES = new Set(["/dev/null", "/dev/stdout", "/dev/stderr"]);
|
|
|
1990
2144
|
* leading `~` resolves to home and is judged like any path.
|
|
1991
2145
|
*/
|
|
1992
2146
|
function targetProblem(target: Target, cwd: string | undefined, dir: string | null | undefined, scratch: string | undefined): TargetProblem | undefined {
|
|
1993
|
-
const word = target.word;
|
|
1994
2147
|
if (target.remote === true) return "outside";
|
|
1995
|
-
if (HARMLESS_DEVICES.has(word)) return undefined;
|
|
2148
|
+
if (HARMLESS_DEVICES.has(target.word)) return undefined;
|
|
2149
|
+
if (otherUserTilde(target.word)) return "outside";
|
|
1996
2150
|
if (cwd === undefined) return "unchecked";
|
|
1997
2151
|
const where = dir === undefined ? cwd : (dir ?? undefined);
|
|
1998
|
-
|
|
2152
|
+
// `~` and `~<current user>` are the home dir and `~+` the directory the command runs in: judged as the paths they stand for
|
|
2153
|
+
if (target.word.startsWith("~+") && where === undefined) return "unchecked";
|
|
2154
|
+
const word = expandHome(target.word, homedir(), where);
|
|
2155
|
+
if (target.glob || word === "" || /[$`]/.test(word)) return "unchecked";
|
|
1999
2156
|
if (where === undefined && !/^[/~]/.test(word)) return "unchecked";
|
|
2000
2157
|
const resolved = resolvePath(word, where ?? "/");
|
|
2001
2158
|
const inScratch = scratch !== undefined && isInsideScratch(resolved, scratch);
|
|
@@ -2063,14 +2220,14 @@ function segmentDirs(segments: readonly Segment[], cwd: string | undefined): (st
|
|
|
2063
2220
|
* "plain" (just not on the list), "write" or "exec". undefined when the
|
|
2064
2221
|
* command can't be parsed. For tests and diagnostics.
|
|
2065
2222
|
*/
|
|
2066
|
-
export function commandEffects(command: string, cwd?: string, scratch?: string, fetchHosts?: readonly string[]): Array<"read-only" | "plain" | "write" | "exec"> | undefined {
|
|
2223
|
+
export function commandEffects(command: string, cwd?: string, scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): Array<"read-only" | "plain" | "write" | "exec"> | undefined {
|
|
2067
2224
|
const tokens = tokenize(maskForAnalysis(command.trim(), scratch), scratch);
|
|
2068
|
-
return tokens?.map((segment) => segmentBlocker(segment, cwd, scratch, false, undefined, fetchHosts)).map((b) => (b === undefined ? "read-only" : (b.effect ?? "plain")));
|
|
2225
|
+
return tokens?.map((segment) => segmentBlocker(segment, cwd, scratch, false, undefined, fetchHosts, gitRepos)).map((b) => (b === undefined ? "read-only" : (b.effect ?? "plain")));
|
|
2069
2226
|
}
|
|
2070
2227
|
|
|
2071
2228
|
/** True when one simple command is read-only. */
|
|
2072
|
-
function isReadOnlySegment(segment: Segment, cwd: string | undefined, scratch?: string, fetchHosts?: readonly string[]): boolean {
|
|
2073
|
-
return segmentBlocker(segment, cwd, scratch, false, undefined, fetchHosts) === undefined;
|
|
2229
|
+
function isReadOnlySegment(segment: Segment, cwd: string | undefined, scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): boolean {
|
|
2230
|
+
return segmentBlocker(segment, cwd, scratch, false, undefined, fetchHosts, gitRepos) === undefined;
|
|
2074
2231
|
}
|
|
2075
2232
|
|
|
2076
2233
|
function rootOf(segment: Segment): string | undefined {
|
|
@@ -2133,6 +2290,7 @@ function classifySegments(
|
|
|
2133
2290
|
covered: readonly CoverSource[],
|
|
2134
2291
|
scratch: string | undefined,
|
|
2135
2292
|
fetchHosts?: readonly string[],
|
|
2293
|
+
gitRepos?: readonly string[],
|
|
2136
2294
|
): { problem?: string; items: ClassifiedSegment[]; changesDirWithGit: boolean } {
|
|
2137
2295
|
const none = { items: [], changesDirWithGit: false };
|
|
2138
2296
|
const original = command.trim();
|
|
@@ -2143,20 +2301,27 @@ function classifySegments(
|
|
|
2143
2301
|
if (segments === null) return { ...none, problem: unparseableReason(trimmed) };
|
|
2144
2302
|
if (segments.length === 0) return { ...none, problem: "has no command (only a comment)" };
|
|
2145
2303
|
// coverage is judged on the git -C normalized form, like isCoveredByPrefixes
|
|
2146
|
-
const normalized = normalizeGitSegments(segments, cwd);
|
|
2304
|
+
const normalized = normalizeGitSegments(segments, cwd, gitRepos);
|
|
2147
2305
|
const dirs = segmentDirs(segments, cwd);
|
|
2148
2306
|
const items = segments.map((segment, k): ClassifiedSegment => {
|
|
2149
|
-
const blocker = segmentBlocker(segment, cwd, scratch, false, dirs[k] ?? undefined, fetchHosts);
|
|
2307
|
+
const blocker = segmentBlocker(segment, cwd, scratch, false, dirs[k] ?? undefined, fetchHosts, gitRepos);
|
|
2150
2308
|
if (blocker === undefined) return { segment };
|
|
2151
|
-
const source = covered.find((c) => isCoveredSegment(normalized[k], c.prefixes, cwd, c.exact, scratch, dirs[k]));
|
|
2309
|
+
const source = covered.find((c) => isCoveredSegment(normalized[k], c.prefixes, cwd, c.exact, scratch, dirs[k], gitRepos));
|
|
2152
2310
|
return { segment, blocker, reason: reasonOf(blocker, cwd, dirs[k], scratch), coveredBy: source?.label };
|
|
2153
2311
|
});
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2312
|
+
return { items, changesDirWithGit: gitInOtherRepoAfterCd(segments, normalized, cwd, gitRepos) };
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
/**
|
|
2316
|
+
* True when a `cd`/`pushd`/`popd` is in the command and git then runs in
|
|
2317
|
+
* another repository (see gitRunsInOtherRepo): the case CD_GIT_REASON names.
|
|
2318
|
+
* git after a cd into a nested repo, outside the cwd, or an unresolvable dir;
|
|
2319
|
+
* a subdirectory of the same repo uses the same config and hooks (-C left
|
|
2320
|
+
* after normalization is gitBlocker's reason, not this one).
|
|
2321
|
+
*/
|
|
2322
|
+
function gitInOtherRepoAfterCd(segments: readonly Segment[], normalized: Segment[], cwd: string | undefined, gitRepos?: readonly string[]): boolean {
|
|
2157
2323
|
const changesDir = segments.some((s) => DIR_CHANGERS.has(basename(rootOf(s) ?? "")));
|
|
2158
|
-
|
|
2159
|
-
return { items, changesDirWithGit };
|
|
2324
|
+
return cwd !== undefined && changesDir && gitRunsInOtherRepo(normalized, cwd, false, gitRepos);
|
|
2160
2325
|
}
|
|
2161
2326
|
|
|
2162
2327
|
const CD_GIT_REASON = "`cd` into another repository or outside the working directory combined with git (that repo's config and hooks would run)";
|
|
@@ -2166,8 +2331,8 @@ const CD_GIT_REASON = "`cd` into another repository or outside the working direc
|
|
|
2166
2331
|
* don't (read-only, or covered by one of `covered`). An unparseable command
|
|
2167
2332
|
* is one `needs` entry with an empty segment.
|
|
2168
2333
|
*/
|
|
2169
|
-
export function approvalBreakdown(command: string, cwd?: string, covered: readonly CoverSource[] = [], scratch?: string, fetchHosts?: readonly string[]): ApprovalBreakdown {
|
|
2170
|
-
const { problem, items, changesDirWithGit } = classifySegments(command, cwd, covered, scratch, fetchHosts);
|
|
2334
|
+
export function approvalBreakdown(command: string, cwd?: string, covered: readonly CoverSource[] = [], scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): ApprovalBreakdown {
|
|
2335
|
+
const { problem, items, changesDirWithGit } = classifySegments(command, cwd, covered, scratch, fetchHosts, gitRepos);
|
|
2171
2336
|
if (problem !== undefined) return { needs: [{ segment: "", reason: problem }], ok: [] };
|
|
2172
2337
|
const needs: ApprovalBreakdown["needs"] = [];
|
|
2173
2338
|
const ok: string[] = [];
|
|
@@ -2211,9 +2376,9 @@ export function formatBreakdown(breakdown: ApprovalBreakdown): string[] {
|
|
|
2211
2376
|
* `cd` that changes directory combined with git is not read-only (git
|
|
2212
2377
|
* would run that directory's hooks/config).
|
|
2213
2378
|
*/
|
|
2214
|
-
export function readOnlyBlockers(command: string, cwd?: string, limit = 3, covered: readonly (readonly string[])[] = [], scratch?: string, fetchHosts?: readonly string[]): string[] {
|
|
2379
|
+
export function readOnlyBlockers(command: string, cwd?: string, limit = 3, covered: readonly (readonly string[])[] = [], scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): string[] {
|
|
2215
2380
|
const sources = covered.length === 0 ? [] : [{ label: "covered", prefixes: covered, exact: [] }];
|
|
2216
|
-
const { problem, items, changesDirWithGit } = classifySegments(command, cwd, sources, scratch, fetchHosts);
|
|
2381
|
+
const { problem, items, changesDirWithGit } = classifySegments(command, cwd, sources, scratch, fetchHosts, gitRepos);
|
|
2217
2382
|
if (problem !== undefined) return [problem];
|
|
2218
2383
|
const reasons = new Set<string>();
|
|
2219
2384
|
for (const { blocker, reason, coveredBy } of items) if (blocker !== undefined && coveredBy === undefined) reasons.add(reason ?? blocker.reason);
|
|
@@ -2222,8 +2387,8 @@ export function readOnlyBlockers(command: string, cwd?: string, limit = 3, cover
|
|
|
2222
2387
|
}
|
|
2223
2388
|
|
|
2224
2389
|
/** True when the command is read-only (see readOnlyBlockers). */
|
|
2225
|
-
export function isReadOnlyCommand(command: string, cwd?: string, scratch?: string, fetchHosts?: readonly string[]): boolean {
|
|
2226
|
-
return readOnlyBlockers(command, cwd, 1, [], scratch, fetchHosts).length === 0;
|
|
2390
|
+
export function isReadOnlyCommand(command: string, cwd?: string, scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): boolean {
|
|
2391
|
+
return readOnlyBlockers(command, cwd, 1, [], scratch, fetchHosts, gitRepos).length === 0;
|
|
2227
2392
|
}
|
|
2228
2393
|
|
|
2229
2394
|
// ---------------------------------------------------------------------------
|
|
@@ -2235,7 +2400,7 @@ export function isReadOnlyCommand(command: string, cwd?: string, scratch?: strin
|
|
|
2235
2400
|
* commands inside `sh -c '<script>'` and `eval ...`. Falls back to a loose
|
|
2236
2401
|
* split when the tokenizer rejects the command.
|
|
2237
2402
|
*/
|
|
2238
|
-
function scanUnits(command: string, depth = 0): string[][] {
|
|
2403
|
+
function scanUnits(command: string, depth = 0, remote = true): string[][] {
|
|
2239
2404
|
const segments = command.length <= MAX_COMMAND_LENGTH ? tokenize(command) : null;
|
|
2240
2405
|
const units: string[][] = [];
|
|
2241
2406
|
let raw: string[][];
|
|
@@ -2245,11 +2410,15 @@ function scanUnits(command: string, depth = 0): string[][] {
|
|
|
2245
2410
|
// heredoc/here-string text is data, except when a shell reads it or bash expands substitutions in it
|
|
2246
2411
|
const { text, feeds } = extractStdinFeeds(command);
|
|
2247
2412
|
raw = looseUnits(text);
|
|
2248
|
-
if (depth < 4) for (const script of feedScripts(feeds)) units.push(...scanUnits(script, depth + 1));
|
|
2413
|
+
if (depth < 4) for (const script of feedScripts(feeds)) units.push(...scanUnits(script, depth + 1, remote));
|
|
2249
2414
|
}
|
|
2250
2415
|
for (const argv of raw) {
|
|
2251
2416
|
const unit = stripPrefixes(argv, argv.map(() => false), false)?.argv ?? argv;
|
|
2252
|
-
if (unit.length === 0)
|
|
2417
|
+
if (unit.length === 0) {
|
|
2418
|
+
// a bare `env` (options and NAME=value words only) prints the environment: keep it as a unit
|
|
2419
|
+
if (basename(argv[0] ?? "") === "env") units.push(argv);
|
|
2420
|
+
continue;
|
|
2421
|
+
}
|
|
2253
2422
|
units.push(unit);
|
|
2254
2423
|
if (depth >= 4) continue;
|
|
2255
2424
|
const [root, ...args] = unit;
|
|
@@ -2262,10 +2431,12 @@ function scanUnits(command: string, depth = 0): string[][] {
|
|
|
2262
2431
|
s++;
|
|
2263
2432
|
}
|
|
2264
2433
|
const script = c === -1 ? undefined : args[s];
|
|
2265
|
-
if (script !== undefined) units.push(...scanUnits(script, depth + 1));
|
|
2434
|
+
if (script !== undefined) units.push(...scanUnits(script, depth + 1, remote));
|
|
2266
2435
|
}
|
|
2267
|
-
if (root === "eval") units.push(...scanUnits(args.join(" "), depth + 1));
|
|
2436
|
+
if (root === "eval") units.push(...scanUnits(args.join(" "), depth + 1, remote));
|
|
2268
2437
|
if (root === "rtk") units.push(...rtkInnerUnits(args, depth));
|
|
2438
|
+
// the command a runner or launcher runs (`exec make deploy`, `ionice sudo id`): scanned like any command
|
|
2439
|
+
for (const inner of runnerInner(unit, remote)) units.push(...scanUnits(inner.map(shellWord).join(" "), depth + 1, remote));
|
|
2269
2440
|
}
|
|
2270
2441
|
return units;
|
|
2271
2442
|
}
|
|
@@ -2311,6 +2482,97 @@ function innerCommands(unit: string[]): string[][] {
|
|
|
2311
2482
|
return positions.map((j) => args.slice(j)).filter((inner) => inner[0] !== root);
|
|
2312
2483
|
}
|
|
2313
2484
|
|
|
2485
|
+
/** A command that runs another command given in its arguments: never a rememberable prefix, and never covers what it launches. */
|
|
2486
|
+
function isRunnerName(name: string): boolean {
|
|
2487
|
+
return COMMAND_RUNNERS.has(name) || Object.hasOwn(RUNNER_VALUE_OPTIONS, name) || name === "builtin";
|
|
2488
|
+
}
|
|
2489
|
+
|
|
2490
|
+
/** A word as one single-quoted shell word, so re-tokenizing the joined words gives the same argv. */
|
|
2491
|
+
const shellWord = (word: string): string => `'${word.replace(/'/g, "'\\''")}'`;
|
|
2492
|
+
|
|
2493
|
+
/**
|
|
2494
|
+
* The commands a unit runs as its arguments: `script -c 'cmd'` runs `sh -c 'cmd'`;
|
|
2495
|
+
* a launcher in RUNNER_VALUE_OPTIONS (`ionice -c 2 cmd`, `ssh -p 22 host cmd`,
|
|
2496
|
+
* `busybox sh -c …`) runs the command from each word that is not one of its value
|
|
2497
|
+
* options; the other runners go through innerCommands.
|
|
2498
|
+
*/
|
|
2499
|
+
function runnerInner(unit: string[], remote = true): string[][] {
|
|
2500
|
+
const [root, ...args] = unit;
|
|
2501
|
+
const name = basename(root ?? "");
|
|
2502
|
+
if (name === "script") {
|
|
2503
|
+
const c = args.findIndex((a) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(a));
|
|
2504
|
+
return c === -1 || args[c + 1] === undefined ? [] : [["sh", "-c", args[c + 1]]];
|
|
2505
|
+
}
|
|
2506
|
+
// ssh runs its -o ProxyCommand / LocalCommand locally; the words after the host run on the remote side
|
|
2507
|
+
if (name === "ssh") return [...sshLocalCommands(args), ...(remote ? valueShapedInner(args, RUNNER_VALUE_OPTIONS.ssh) : [])];
|
|
2508
|
+
if (name === "tmux") return tmuxInner(args);
|
|
2509
|
+
if (name === "screen") return screenInner(args);
|
|
2510
|
+
if (!Object.hasOwn(RUNNER_VALUE_OPTIONS, name)) return innerCommands(unit);
|
|
2511
|
+
return valueShapedInner(args, RUNNER_VALUE_OPTIONS[name]);
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
/** The command from each word that is not one of the launcher's value options (`ionice -c 2 cmd`). */
|
|
2515
|
+
function valueShapedInner(args: string[], values: readonly string[]): string[][] {
|
|
2516
|
+
const inner: string[][] = [];
|
|
2517
|
+
for (let j = 0; j < args.length; j++) {
|
|
2518
|
+
if (args[j].startsWith("-")) {
|
|
2519
|
+
if (values.includes(args[j])) j++;
|
|
2520
|
+
continue;
|
|
2521
|
+
}
|
|
2522
|
+
inner.push(args.slice(j));
|
|
2523
|
+
}
|
|
2524
|
+
return inner;
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2527
|
+
/** `ssh -o ProxyCommand=CMD` and `-o LocalCommand=CMD`: a local shell command. */
|
|
2528
|
+
function sshLocalCommands(args: string[]): string[][] {
|
|
2529
|
+
const out: string[][] = [];
|
|
2530
|
+
for (let j = 0; j < args.length; j++) {
|
|
2531
|
+
let option: string | undefined;
|
|
2532
|
+
if (args[j] === "-o") option = args[++j];
|
|
2533
|
+
else if (/^-o./.test(args[j])) option = args[j].slice(2);
|
|
2534
|
+
const m = option === undefined ? null : /^(ProxyCommand|LocalCommand)\s*=?\s*(.+)$/i.exec(option);
|
|
2535
|
+
if (m !== null) out.push(["sh", "-c", m[2]]);
|
|
2536
|
+
}
|
|
2537
|
+
return out;
|
|
2538
|
+
}
|
|
2539
|
+
|
|
2540
|
+
/** tmux options that take a value (the union over the commands below). */
|
|
2541
|
+
const TMUX_VALUE_OPTIONS = ["-c", "-e", "-F", "-f", "-l", "-n", "-L", "-p", "-S", "-s", "-t", "-x", "-y"];
|
|
2542
|
+
/** tmux commands whose trailing words are a shell command (`new -d 'cmd'`, `run-shell cmd`). */
|
|
2543
|
+
const TMUX_COMMAND_SUBCOMMANDS = new Set(["new", "new-session", "new-window", "split-window", "respawn-pane", "run-shell", "run"]);
|
|
2544
|
+
|
|
2545
|
+
/** Index of the first word after the options (a value option takes the next word too). */
|
|
2546
|
+
function skipOptionWords(words: readonly string[], values: readonly string[]): number {
|
|
2547
|
+
let k = 0;
|
|
2548
|
+
while (k < words.length && words[k].startsWith("-")) k += values.includes(words[k]) ? 2 : 1;
|
|
2549
|
+
return k;
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
/** tmux: the trailing command of new/split/respawn/run-shell, and the keys of send-keys (typed into a shell). */
|
|
2553
|
+
function tmuxInner(args: string[]): string[][] {
|
|
2554
|
+
const s = skipOptionWords(args, TMUX_VALUE_OPTIONS);
|
|
2555
|
+
const sub = args[s];
|
|
2556
|
+
const rest = args.slice(s + 1);
|
|
2557
|
+
if (sub === "send-keys" || sub === "send") {
|
|
2558
|
+
const keys = rest.slice(skipOptionWords(rest, TMUX_VALUE_OPTIONS)).filter((w) => w !== "Enter");
|
|
2559
|
+
return keys.length > 0 ? [["sh", "-c", keys.join(" ")]] : [];
|
|
2560
|
+
}
|
|
2561
|
+
if (!TMUX_COMMAND_SUBCOMMANDS.has(sub ?? "")) return [];
|
|
2562
|
+
const k = skipOptionWords(rest, TMUX_VALUE_OPTIONS);
|
|
2563
|
+
return k < rest.length ? [["sh", "-c", rest.slice(k).join(" ")]] : [];
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
/** screen: the command after its options (`-dmS name cmd`; the -S, -c and -T values are skipped). */
|
|
2567
|
+
function screenInner(args: string[]): string[][] {
|
|
2568
|
+
let k = 0;
|
|
2569
|
+
while (k < args.length && args[k].startsWith("-")) {
|
|
2570
|
+
if (/^-[A-Za-z]+$/.test(args[k]) && /[ScT]/.test(args[k].slice(1))) k++;
|
|
2571
|
+
k++;
|
|
2572
|
+
}
|
|
2573
|
+
return k < args.length ? [args.slice(k)] : [];
|
|
2574
|
+
}
|
|
2575
|
+
|
|
2314
2576
|
function isPrivilegedUnit(unit: string[], depth = 0): boolean {
|
|
2315
2577
|
const root = basename(unit[0] ?? "");
|
|
2316
2578
|
if (PRIVILEGE_COMMANDS.has(root)) return true;
|
|
@@ -2318,7 +2580,8 @@ function isPrivilegedUnit(unit: string[], depth = 0): boolean {
|
|
|
2318
2580
|
const inner = rtkInnerUnits(unit.slice(1), depth).map((u) => stripPrefixes(u, u.map(() => false), false)?.argv ?? u);
|
|
2319
2581
|
if (inner.some((u) => isPrivilegedUnit(u, depth + 1))) return true;
|
|
2320
2582
|
}
|
|
2321
|
-
|
|
2583
|
+
// a remote command (after the ssh host) runs under the remote account, not locally: only local commands count here
|
|
2584
|
+
return depth < 4 && runnerInner(unit, false).some((inner) => isPrivilegedUnit(inner, depth + 1));
|
|
2322
2585
|
}
|
|
2323
2586
|
|
|
2324
2587
|
/**
|
|
@@ -2327,7 +2590,7 @@ function isPrivilegedUnit(unit: string[], depth = 0): boolean {
|
|
|
2327
2590
|
* command names one (`x=sudo; $x ls`).
|
|
2328
2591
|
*/
|
|
2329
2592
|
export function isPrivilegedCommand(command: string): boolean {
|
|
2330
|
-
const units = scanUnits(command);
|
|
2593
|
+
const units = scanUnits(command, 0, false);
|
|
2331
2594
|
if (units.some(isPrivilegedUnit)) return true;
|
|
2332
2595
|
if (!units.some((unit) => (unit[0] ?? "").startsWith("$"))) return false;
|
|
2333
2596
|
return looseUnits(command)
|
|
@@ -2354,6 +2617,8 @@ export interface PathContext {
|
|
|
2354
2617
|
skillDirs?: readonly string[];
|
|
2355
2618
|
/** Hosts the user allowed fetching from (session and project grants); no host is allowed by default. */
|
|
2356
2619
|
fetchHosts?: readonly string[];
|
|
2620
|
+
/** Realpaths of git repository roots the user allowed git to run in from another directory (session grants, see gitRepoRootOf). */
|
|
2621
|
+
gitRepos?: readonly string[];
|
|
2357
2622
|
}
|
|
2358
2623
|
|
|
2359
2624
|
/**
|
|
@@ -2377,7 +2642,7 @@ function isDangerousUnit(unit: string[], ctx: PathContext, cwd: string | undefin
|
|
|
2377
2642
|
const inner = rtkInnerUnits(args, depth).map((u) => stripPrefixes(u, u.map(() => false), false)?.argv ?? u);
|
|
2378
2643
|
if (inner.some((u) => isDangerousUnit(u, ctx, cwd, depth + 1))) return true;
|
|
2379
2644
|
}
|
|
2380
|
-
if (depth < 3) return
|
|
2645
|
+
if (depth < 3) return runnerInner(unit).some((inner) => isDangerousUnit(inner, ctx, cwd, depth + 1));
|
|
2381
2646
|
return false;
|
|
2382
2647
|
}
|
|
2383
2648
|
|
|
@@ -2468,7 +2733,8 @@ export function isDangerousCommand(command: string, ctx: PathContext): boolean {
|
|
|
2468
2733
|
// heredoc/here-string text is data, except when a shell reads it or bash expands substitutions in it
|
|
2469
2734
|
const { text, feeds } = extractStdinFeeds(command);
|
|
2470
2735
|
if (feedScripts(feeds).some((script) => isDangerousCommand(script, ctx))) return true;
|
|
2471
|
-
|
|
2736
|
+
const joined = joinContinuations(text);
|
|
2737
|
+
if (DANGEROUS_RAW_PATTERNS.some((pattern) => pattern.test(text) || pattern.test(joined))) return true;
|
|
2472
2738
|
const units = scanUnits(command);
|
|
2473
2739
|
// units run in order: a `cd` changes where later relative paths point
|
|
2474
2740
|
let cwd: string | undefined = ctx.cwd;
|
|
@@ -2489,7 +2755,87 @@ export function isDangerousCommand(command: string, ctx: PathContext): boolean {
|
|
|
2489
2755
|
* directly or through a glob that can match a .env file (`.en*`, `.e[n]v`).
|
|
2490
2756
|
*/
|
|
2491
2757
|
export function isSecretCommand(command: string, ctx?: SecretContext): boolean {
|
|
2492
|
-
|
|
2758
|
+
const quoted = quotedLiteralWords(command);
|
|
2759
|
+
return (
|
|
2760
|
+
scanUnits(command).some((unit) => {
|
|
2761
|
+
const gitObject = isGitObjectRead(unit);
|
|
2762
|
+
const root = basename(unit[0] ?? "");
|
|
2763
|
+
return unit.some((word, k) => {
|
|
2764
|
+
// `ls -I PATTERN` (and --hide, --ignore) names a filter, not a file: the word after it is not checked
|
|
2765
|
+
if ((root === "ls" || root === "tree") && k > 0 && LISTING_FILTER_OPTIONS.has(unit[k - 1] ?? "")) return false;
|
|
2766
|
+
return secretCandidates(word, gitObject, root).some((w) => {
|
|
2767
|
+
// a glob under ~ or $HOME is judged on the directory it names, like the same path without a glob
|
|
2768
|
+
const expanded = expandHome(w, homedir(), ctx?.cwd);
|
|
2769
|
+
const capped = !quoted.has(w);
|
|
2770
|
+
return isSecretFile(w, ctx) || globMatchesSecretFile(expanded, capped) || globMatchesSecretOnDisk(expanded, ctx, capped);
|
|
2771
|
+
});
|
|
2772
|
+
});
|
|
2773
|
+
}) || printsSecretVariable(command) || dumpsEnvironment(command)
|
|
2774
|
+
);
|
|
2775
|
+
}
|
|
2776
|
+
|
|
2777
|
+
/**
|
|
2778
|
+
* Words the command passes quoted, with no unquoted glob, brace or `$` in them (`'a*b'`): the shell does not
|
|
2779
|
+
* expand them, so the star cap does not apply. Only top-level words are read; a word also seen unquoted counts
|
|
2780
|
+
* as unquoted, and a command the tokenizer rejects has none (every word is capped).
|
|
2781
|
+
*/
|
|
2782
|
+
function quotedLiteralWords(command: string): Set<string> {
|
|
2783
|
+
const quoted = new Set<string>();
|
|
2784
|
+
const unquoted = new Set<string>();
|
|
2785
|
+
const segments = command.length <= MAX_COMMAND_LENGTH ? tokenize(command) : null;
|
|
2786
|
+
for (const segment of segments ?? []) {
|
|
2787
|
+
segment.argv.forEach((word, i) => (segment.globs[i] === true ? unquoted : quoted).add(word));
|
|
2788
|
+
}
|
|
2789
|
+
for (const word of unquoted) quoted.delete(word);
|
|
2790
|
+
return quoted;
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
/** Options of a listing command whose next word is a filter pattern, not a file. */
|
|
2794
|
+
const LISTING_FILTER_OPTIONS = new Set(["-I", "--hide", "--ignore"]);
|
|
2795
|
+
|
|
2796
|
+
/** Long options whose value is a filter pattern, not a file read (`--exclude-from` and `--ignore-file` do read their file). */
|
|
2797
|
+
const FILTER_LONG_OPTIONS = new Set(["exclude", "exclude-dir", "ignore", "ignore-dir", "hide"]);
|
|
2798
|
+
|
|
2799
|
+
/** Global git options that take a value as the next word (`git -c k=v show`). */
|
|
2800
|
+
const GIT_VALUE_GLOBALS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env"]);
|
|
2801
|
+
|
|
2802
|
+
/**
|
|
2803
|
+
* The texts of one word that may name a file: the word itself, the value after `--flag=` (`--file=.env`),
|
|
2804
|
+
* the value after a short flag letter (`-f.env`) and every suffix of a clustered short-flag word from its
|
|
2805
|
+
* second letter (`-nf.env` names `f.env` and `.env`; `ls -aI.env` stops at its `I`), and, for `git show` and
|
|
2806
|
+
* `git cat-file`, the part after the last `:` (`HEAD:.env`, `:.env`).
|
|
2807
|
+
*/
|
|
2808
|
+
function secretCandidates(word: string, gitObject: boolean, root: string): string[] {
|
|
2809
|
+
const out = [word];
|
|
2810
|
+
const long = /^--([^=]*)=(.*)$/.exec(word);
|
|
2811
|
+
const short = long === null ? /^-([A-Za-z])(.+)$/.exec(word) : null;
|
|
2812
|
+
const value = long?.[2] ?? short?.[2];
|
|
2813
|
+
if (value !== undefined && !isFilterOption(long?.[1], short?.[1], value, root)) out.push(value);
|
|
2814
|
+
if (long === null && /^-[A-Za-z]{2}/.test(word)) {
|
|
2815
|
+
const listing = root === "ls" || root === "tree";
|
|
2816
|
+
const filter = listing ? word.indexOf("I") : -1;
|
|
2817
|
+
const end = filter > 0 ? filter : word.length;
|
|
2818
|
+
for (let k = 2; k < end; k++) out.push(word.slice(k));
|
|
2819
|
+
}
|
|
2820
|
+
if (gitObject && word.includes(":")) out.push(word.slice(word.lastIndexOf(":") + 1));
|
|
2821
|
+
return out;
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
/**
|
|
2825
|
+
* An option whose value is a filter, not a file it reads: the long options in FILTER_LONG_OPTIONS,
|
|
2826
|
+
* `-g`/`--glob`/`--iglob` with a `!` (ripgrep's negated glob), and `-I` of ls and tree.
|
|
2827
|
+
*/
|
|
2828
|
+
function isFilterOption(longName: string | undefined, shortLetter: string | undefined, value: string, root: string): boolean {
|
|
2829
|
+
if (longName !== undefined) return FILTER_LONG_OPTIONS.has(longName) || (/^i?glob$/.test(longName) && value.startsWith("!"));
|
|
2830
|
+
if (shortLetter === "g") return value.startsWith("!");
|
|
2831
|
+
return shortLetter === "I" && (root === "ls" || root === "tree");
|
|
2832
|
+
}
|
|
2833
|
+
|
|
2834
|
+
/** True for `git show` and `git cat-file`, which read the object a `<rev>:<path>` word names. */
|
|
2835
|
+
function isGitObjectRead(unit: string[]): boolean {
|
|
2836
|
+
if (basename(unit[0] ?? "") !== "git") return false;
|
|
2837
|
+
const sub = unit.slice(1).find((a, k, all) => !a.startsWith("-") && !(k > 0 && GIT_VALUE_GLOBALS.has(all[k - 1] ?? "")));
|
|
2838
|
+
return sub === "show" || sub === "cat-file";
|
|
2493
2839
|
}
|
|
2494
2840
|
|
|
2495
2841
|
/**
|
|
@@ -2526,10 +2872,35 @@ function maskLiteralDollars(command: string): string {
|
|
|
2526
2872
|
}
|
|
2527
2873
|
|
|
2528
2874
|
/** True when echo or printf is given a credential-named variable (`$NAME`, `${NAME}`) that the shell expands. */
|
|
2875
|
+
/** Names echo/printf must not print: credential words, passwords (`PGPASSWORD`), and PWD except the directory variables themselves. */
|
|
2876
|
+
function isSecretPrintName(name: string): boolean {
|
|
2877
|
+
if (SECRET_PRINT_NAME.test(name) || /PASS(WORD|WD)/i.test(name)) return true;
|
|
2878
|
+
const upper = name.toUpperCase();
|
|
2879
|
+
return upper.includes("PWD") && upper !== "PWD" && upper !== "OLDPWD";
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
/** `jq` with the `env` or `$ENV` builtin, or awk reading ENVIRON: each prints every variable, credentials included. */
|
|
2883
|
+
function dumpsEnvironment(command: string): boolean {
|
|
2884
|
+
return scanUnits(command).some(([root = "", ...args]) => {
|
|
2885
|
+
const name = basename(root);
|
|
2886
|
+
if (name === "jq") return args.some((a) => !a.startsWith("-") && /(^|[^.\w$])env\b|\$ENV\b/.test(a));
|
|
2887
|
+
if (AWK_COMMANDS.has(name)) return args.some((a) => /\bENVIRON\b/.test(a));
|
|
2888
|
+
// `env` with no command after its options and NAME=value words prints the environment
|
|
2889
|
+
if (name === "env") return args.every((a) => a.startsWith("-") || ASSIGNMENT.test(a));
|
|
2890
|
+
if (name === "printenv") return args.every((a) => a.startsWith("-")) || args.some((a) => !a.startsWith("-") && isSecretPrintName(a));
|
|
2891
|
+
// bare set, export -p / export, declare and typeset with -p or -x (no name): the variables and their values
|
|
2892
|
+
if (name === "set") return args.length === 0;
|
|
2893
|
+
if (name === "export") return args.every((a) => a === "-p");
|
|
2894
|
+
if (name === "declare" || name === "typeset") return args.every((a) => a.startsWith("-") && /[px]/.test(a));
|
|
2895
|
+
if (name === "compgen") return args.some((a) => a === "-e" || a === "-v");
|
|
2896
|
+
return false;
|
|
2897
|
+
});
|
|
2898
|
+
}
|
|
2899
|
+
|
|
2529
2900
|
function printsSecretVariable(command: string): boolean {
|
|
2530
2901
|
return scanUnits(maskLiteralDollars(command)).some(([root = "", ...args]) => {
|
|
2531
2902
|
if (!["echo", "printf"].includes(basename(root))) return false;
|
|
2532
|
-
return args.some((arg) => [...arg.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)].some((m) =>
|
|
2903
|
+
return args.some((arg) => [...arg.matchAll(/\$\{?([A-Za-z_][A-Za-z0-9_]*)/g)].some((m) => isSecretPrintName(m[1] ?? "")));
|
|
2533
2904
|
});
|
|
2534
2905
|
}
|
|
2535
2906
|
|
|
@@ -2551,12 +2922,16 @@ const NON_READING_COMMANDS = new Set(["echo", "printf", "which", "type", "comman
|
|
|
2551
2922
|
*/
|
|
2552
2923
|
export function outsideCwdReadPaths(command: string, ctx: PathContext): string[] {
|
|
2553
2924
|
const found = new Set<string>();
|
|
2925
|
+
const quoted = quotedLiteralWords(command);
|
|
2554
2926
|
// units run in order: a `cd` changes which directory later relative words name
|
|
2555
2927
|
let cwd: string | undefined = ctx.cwd;
|
|
2556
2928
|
for (const [root, ...args] of scanUnits(command)) {
|
|
2557
2929
|
if (root === undefined) continue;
|
|
2558
2930
|
const name = basename(root);
|
|
2559
2931
|
if (DIR_CHANGERS.has(name)) {
|
|
2932
|
+
// `cd ~root` or `cd ~-` enters another account's directory: an outside read whatever follows
|
|
2933
|
+
const target = args.find((a) => !a.startsWith("-") || a === "-");
|
|
2934
|
+
if (target !== undefined && otherUserTilde(target)) found.add(target);
|
|
2560
2935
|
cwd = changedDir(name, args, cwd);
|
|
2561
2936
|
continue;
|
|
2562
2937
|
}
|
|
@@ -2564,16 +2939,25 @@ export function outsideCwdReadPaths(command: string, ctx: PathContext): string[]
|
|
|
2564
2939
|
// the command runs outside the cwd (after a `cd`): the directory it reads in
|
|
2565
2940
|
if (cwd !== undefined && !isSamePath(cwd, ctx.cwd, ctx.cwd) && isOutsideCwdRead(cwd, ctx)) found.add(cwd);
|
|
2566
2941
|
for (const arg of args) {
|
|
2942
|
+
const raw = arg.startsWith("-") ? arg.slice(arg.indexOf("=") + 1) : arg;
|
|
2943
|
+
// another account's home is outside whether or not the path exists here
|
|
2944
|
+
if (otherUserTilde(raw)) {
|
|
2945
|
+
found.add(raw);
|
|
2946
|
+
continue;
|
|
2947
|
+
}
|
|
2567
2948
|
// $HOME is expanded first, so `$HOME/x` is judged like `~/x`; a `..` segment can climb out of the cwd anywhere in the word
|
|
2568
|
-
const value = expandHome(
|
|
2569
|
-
|
|
2949
|
+
const value = expandHome(raw, homedir(), cwd);
|
|
2950
|
+
// a glob is outside when the directory above its first glob character is (`/etc/pass*`); its matches are not walked
|
|
2951
|
+
const dir = /[*?[{]/.test(value) ? globDirectory(value) : undefined;
|
|
2952
|
+
if (dir !== undefined && cwd !== undefined && isOutsideCwdRead(resolvePath(dir, cwd), ctx)) found.add(value);
|
|
2953
|
+
else if (/^(\/|~|\.\.)|(^|\/)\.\.(\/|$)/.test(value) && isOutsideCwdRead(value, ctx)) found.add(value);
|
|
2570
2954
|
// a path or glob inside the project can still be, or match, a link that leads out of it
|
|
2571
2955
|
// (a path that is itself outside is the case above, or the `cd` directory already reported)
|
|
2572
2956
|
else if (cwd !== undefined && !arg.startsWith("-") && isInside(resolve(cwd), resolve(ctx.cwd))) {
|
|
2573
2957
|
const here: string = cwd;
|
|
2574
2958
|
const leadsOut = (path: string): boolean => isInside(resolvePath(path, here), resolve(ctx.cwd)) && isOutsideCwdRead(resolvePath(path, here), ctx);
|
|
2575
2959
|
if (/[*?[{]/.test(arg)) {
|
|
2576
|
-
const matches = expandGlob(arg, cwd);
|
|
2960
|
+
const matches = expandGlob(arg, cwd, !quoted.has(arg));
|
|
2577
2961
|
if (matches === null) found.add(arg);
|
|
2578
2962
|
else for (const match of matches) if (leadsOut(match)) found.add(match);
|
|
2579
2963
|
} else if (lstatOk(resolvePath(arg, cwd)) && leadsOut(arg)) found.add(arg);
|
|
@@ -2583,6 +2967,14 @@ export function outsideCwdReadPaths(command: string, ctx: PathContext): string[]
|
|
|
2583
2967
|
return [...found];
|
|
2584
2968
|
}
|
|
2585
2969
|
|
|
2970
|
+
/** The directory above a glob word's first glob character (`/etc` for `/etc/pass*`, `.` for `*.py`). */
|
|
2971
|
+
function globDirectory(word: string): string | undefined {
|
|
2972
|
+
const glob = word.search(/[*?[{]/);
|
|
2973
|
+
if (glob === -1) return undefined;
|
|
2974
|
+
const slash = word.lastIndexOf("/", glob);
|
|
2975
|
+
return slash === -1 ? "." : slash === 0 ? "/" : word.slice(0, slash);
|
|
2976
|
+
}
|
|
2977
|
+
|
|
2586
2978
|
/**
|
|
2587
2979
|
* True when `resolved` lies in the OS temp dir, judged by realpath, so a link
|
|
2588
2980
|
* in the temp dir to a file elsewhere is not in it (and a link from elsewhere
|
|
@@ -2750,20 +3142,46 @@ export function bashWritesInsideArtifactDirs(command: string, ctx: PathContext):
|
|
|
2750
3142
|
export function outsideCwdBashWrites(command: string, ctx: PathContext): string[] {
|
|
2751
3143
|
const trimmed = command.trim();
|
|
2752
3144
|
if (trimmed === "" || trimmed.length > MAX_COMMAND_LENGTH) return [];
|
|
2753
|
-
const
|
|
2754
|
-
|
|
3145
|
+
const { text, inner } = unsubstituted(maskForAnalysis(trimmed, ctx.scratchDir));
|
|
3146
|
+
// a substitution runs its own commands: judged like a line of their own
|
|
3147
|
+
const found: string[] = inner.flatMap((script) => outsideCwdBashWrites(script, ctx));
|
|
3148
|
+
found.push(...redirectOutsideTargets(text, ctx));
|
|
3149
|
+
const tokens = tokenize(text, ctx.scratchDir);
|
|
3150
|
+
if (tokens === null) return found;
|
|
2755
3151
|
const dirs = segmentDirs(tokens, ctx.cwd);
|
|
2756
|
-
|
|
2757
|
-
|
|
3152
|
+
// a command a launcher runs (`env cp a /etc/x`, `ionice cp a /etc/x`) is judged the same way
|
|
3153
|
+
const judge = (segment: Segment, dir: string | null | undefined, depth: number): void => {
|
|
2758
3154
|
const blocker = segmentBlocker(segment, ctx.cwd, ctx.scratchDir);
|
|
2759
|
-
if (blocker?.effect
|
|
2760
|
-
|
|
2761
|
-
|
|
3155
|
+
if (blocker?.effect === "write" && Array.isArray(blocker.targets)) {
|
|
3156
|
+
for (const target of blocker.targets) {
|
|
3157
|
+
if (targetProblem(target, ctx.cwd, dir, ctx.scratchDir) === "outside") found.push(target.word);
|
|
3158
|
+
}
|
|
2762
3159
|
}
|
|
2763
|
-
|
|
3160
|
+
if (depth < 4) for (const argv of runnerInner(segment.argv)) judge({ argv, globs: argv.map(() => false) }, dir, depth + 1);
|
|
3161
|
+
};
|
|
3162
|
+
for (const [k, segment] of tokens.entries()) judge(segment, dirs[k], 0);
|
|
2764
3163
|
return found;
|
|
2765
3164
|
}
|
|
2766
3165
|
|
|
3166
|
+
/**
|
|
3167
|
+
* The line with each `$(…)` and backquoted substitution replaced by the word `X`, and each here-string or
|
|
3168
|
+
* heredoc operator dropped, so the writes around them can be read. The substitutions' own text is returned.
|
|
3169
|
+
*/
|
|
3170
|
+
function unsubstituted(command: string): { text: string; inner: string[] } {
|
|
3171
|
+
const inner: string[] = [];
|
|
3172
|
+
let text = command;
|
|
3173
|
+
for (let pass = 0; pass < 8; pass++) {
|
|
3174
|
+
const next = text.replace(/\$\(\([^]*?\)\)|\$\(([^()]*)\)|`([^`]*)`/g, (_m, a: string | undefined, b: string | undefined) => {
|
|
3175
|
+
if (a !== undefined || b !== undefined) inner.push(a ?? b ?? "");
|
|
3176
|
+
return "X";
|
|
3177
|
+
});
|
|
3178
|
+
if (next === text) break;
|
|
3179
|
+
text = next;
|
|
3180
|
+
}
|
|
3181
|
+
text = text.replace(/<<<\s*("[^"]*"|'[^']*'|\S+)/g, " ").replace(/<<-?\s*(["']?)([A-Za-z_][A-Za-z0-9_]*)\1/g, " ");
|
|
3182
|
+
return { text, inner };
|
|
3183
|
+
}
|
|
3184
|
+
|
|
2767
3185
|
/**
|
|
2768
3186
|
* Every simple command of `command` with the directory it runs in (the
|
|
2769
3187
|
* session cwd, moved by earlier `cd`/`pushd`; undefined after one that can't
|
|
@@ -2985,6 +3403,13 @@ export interface SearchHit {
|
|
|
2985
3403
|
why: "secret" | "unchecked" | "limit";
|
|
2986
3404
|
}
|
|
2987
3405
|
|
|
3406
|
+
/** Most `*` a glob word may have: more is not expanded or matched (its nested `.*` backtracks for too long). */
|
|
3407
|
+
const GLOB_STAR_LIMIT = 8;
|
|
3408
|
+
|
|
3409
|
+
function starCount(word: string): number {
|
|
3410
|
+
return word.split("*").length - 1;
|
|
3411
|
+
}
|
|
3412
|
+
|
|
2988
3413
|
/** A glob pattern matched against a file name; null patterns match everything (fail closed). */
|
|
2989
3414
|
function globMatches(glob: string, name: string): boolean {
|
|
2990
3415
|
return globToRegExp(glob)?.test(name) ?? true;
|
|
@@ -3110,6 +3535,7 @@ export function secretSearchHits(command: string, ctx: PathContext): SearchHit[]
|
|
|
3110
3535
|
const rel = relative(ctx.cwd, path);
|
|
3111
3536
|
return rel !== "" && !rel.startsWith("..") && !rel.startsWith(sep) ? rel : path;
|
|
3112
3537
|
};
|
|
3538
|
+
const searches: Array<{ roots: Array<string | undefined>; scan: SearchScan; pipe?: boolean }> = [];
|
|
3113
3539
|
for (const { unit, dir } of unitsWithDirs(command, ctx)) {
|
|
3114
3540
|
const viaRtk = basename(unit[0] ?? "") === "rtk";
|
|
3115
3541
|
let name = basename(unit[0] ?? "");
|
|
@@ -3131,16 +3557,24 @@ export function secretSearchHits(command: string, ctx: PathContext): SearchHit[]
|
|
|
3131
3557
|
return expandSearchRoot(word, dir ?? "/");
|
|
3132
3558
|
});
|
|
3133
3559
|
const triggers = kind === "grep" ? scan.recursive : kind === "rtkgrep" ? scan.recursive || scan.unrestricted : scan.unrestricted;
|
|
3134
|
-
if (
|
|
3560
|
+
if (triggers) searches.push({ roots, scan });
|
|
3561
|
+
}
|
|
3562
|
+
searches.push(...pipedListSearches(command, ctx));
|
|
3563
|
+
for (const { roots, scan, pipe } of searches) {
|
|
3135
3564
|
for (const root of roots) {
|
|
3136
3565
|
if (root === undefined) {
|
|
3137
3566
|
hits.push({ path: "(search path)", why: "unchecked" });
|
|
3138
3567
|
continue;
|
|
3139
3568
|
}
|
|
3140
|
-
const { secrets, limit } = secretFilesUnder(root, ctx, scan);
|
|
3141
3569
|
// a committed fixture under a directory this session may read is repository content, not the user's credential
|
|
3142
3570
|
const real = realpathLoose(resolve(root));
|
|
3143
3571
|
const readable = isInside(real, resolve(ctx.cwd)) || (ctx.outsideReadDirs ?? []).some((dir) => isInside(real, dir));
|
|
3572
|
+
// a file list of a directory outside the project is not walked: it is an outside read
|
|
3573
|
+
if (pipe === true && !readable) {
|
|
3574
|
+
hits.push({ path: shown(root), why: "unchecked" });
|
|
3575
|
+
continue;
|
|
3576
|
+
}
|
|
3577
|
+
const { secrets, limit } = secretFilesUnder(root, ctx, scan);
|
|
3144
3578
|
for (const secret of uncommittedSecrets(secrets, readable)) hits.push({ path: shown(secret), why: "secret" });
|
|
3145
3579
|
if (limit && secrets.length === 0) hits.push({ path: shown(root), why: "limit" });
|
|
3146
3580
|
}
|
|
@@ -3148,6 +3582,460 @@ export function secretSearchHits(command: string, ctx: PathContext): SearchHit[]
|
|
|
3148
3582
|
return hits;
|
|
3149
3583
|
}
|
|
3150
3584
|
|
|
3585
|
+
/** A token of a shell line: a word (quotes removed), an operator, or the target word of a redirection. */
|
|
3586
|
+
type LineToken = { word: string } | { op: string } | { redirect: string };
|
|
3587
|
+
|
|
3588
|
+
/**
|
|
3589
|
+
* The tokens of a shell line as bash reads them for these checks: quotes removed, operators split out, a
|
|
3590
|
+
* newline as `;`, and each redirection as a `redirect` token holding its target (`2>&1` and `>&2` have none).
|
|
3591
|
+
* Null where the line is not read with confidence: a substitution, a process substitution, a heredoc, an
|
|
3592
|
+
* unterminated quote, a redirection with no target.
|
|
3593
|
+
*/
|
|
3594
|
+
function lexLine(command: string): LineToken[] | null {
|
|
3595
|
+
if (/\$\(|`|<\(|>\(|<</.test(command)) return null;
|
|
3596
|
+
const out: LineToken[] = [];
|
|
3597
|
+
let word = "";
|
|
3598
|
+
let started = false;
|
|
3599
|
+
let bare = true;
|
|
3600
|
+
let pendingRedirect = false;
|
|
3601
|
+
let pendingWrite = false;
|
|
3602
|
+
let failed = false;
|
|
3603
|
+
const flush = (): void => {
|
|
3604
|
+
if (!started) return;
|
|
3605
|
+
if (pendingRedirect) {
|
|
3606
|
+
if (pendingWrite) out.push({ redirect: word });
|
|
3607
|
+
} else out.push(bare && (word === "{" || word === "}") ? { op: word } : { word });
|
|
3608
|
+
pendingRedirect = false;
|
|
3609
|
+
pendingWrite = false;
|
|
3610
|
+
word = "";
|
|
3611
|
+
started = false;
|
|
3612
|
+
bare = true;
|
|
3613
|
+
};
|
|
3614
|
+
const operator = (text: string): void => {
|
|
3615
|
+
flush();
|
|
3616
|
+
if (pendingRedirect) failed = true;
|
|
3617
|
+
out.push({ op: text });
|
|
3618
|
+
};
|
|
3619
|
+
let i = 0;
|
|
3620
|
+
while (i < command.length && !failed) {
|
|
3621
|
+
const ch = command[i] ?? "";
|
|
3622
|
+
if (ch === " " || ch === "\t") {
|
|
3623
|
+
flush();
|
|
3624
|
+
i++;
|
|
3625
|
+
continue;
|
|
3626
|
+
}
|
|
3627
|
+
if (ch === "\n") {
|
|
3628
|
+
operator(";");
|
|
3629
|
+
i++;
|
|
3630
|
+
continue;
|
|
3631
|
+
}
|
|
3632
|
+
if (ch === "#" && !started) {
|
|
3633
|
+
while (i < command.length && command[i] !== "\n") i++;
|
|
3634
|
+
continue;
|
|
3635
|
+
}
|
|
3636
|
+
if (ch === "'") {
|
|
3637
|
+
const end = command.indexOf("'", i + 1);
|
|
3638
|
+
if (end === -1) return null;
|
|
3639
|
+
word += command.slice(i + 1, end);
|
|
3640
|
+
started = true;
|
|
3641
|
+
bare = false;
|
|
3642
|
+
i = end + 1;
|
|
3643
|
+
continue;
|
|
3644
|
+
}
|
|
3645
|
+
if (ch === '"') {
|
|
3646
|
+
let j = i + 1;
|
|
3647
|
+
while (j < command.length && command[j] !== '"') {
|
|
3648
|
+
const c = command[j] ?? "";
|
|
3649
|
+
if (c === "\\" && "$`\"\\\n".includes(command[j + 1] ?? "\u0000")) {
|
|
3650
|
+
if (command[j + 1] !== "\n") word += command[j + 1];
|
|
3651
|
+
j += 2;
|
|
3652
|
+
continue;
|
|
3653
|
+
}
|
|
3654
|
+
word += c;
|
|
3655
|
+
j++;
|
|
3656
|
+
}
|
|
3657
|
+
if (j >= command.length) return null;
|
|
3658
|
+
started = true;
|
|
3659
|
+
bare = false;
|
|
3660
|
+
i = j + 1;
|
|
3661
|
+
continue;
|
|
3662
|
+
}
|
|
3663
|
+
if (ch === "\\") {
|
|
3664
|
+
if (i + 1 >= command.length) return null;
|
|
3665
|
+
if (command[i + 1] !== "\n") {
|
|
3666
|
+
word += command[i + 1];
|
|
3667
|
+
started = true;
|
|
3668
|
+
bare = false;
|
|
3669
|
+
}
|
|
3670
|
+
i += 2;
|
|
3671
|
+
continue;
|
|
3672
|
+
}
|
|
3673
|
+
if (ch === ">" || ch === "<" || (ch === "&" && command[i + 1] === ">")) {
|
|
3674
|
+
// a number right before the operator, with no space, is the fd it redirects (`2>`)
|
|
3675
|
+
if (started && bare && !pendingRedirect && /^\d+$/.test(word)) {
|
|
3676
|
+
word = "";
|
|
3677
|
+
started = false;
|
|
3678
|
+
} else flush();
|
|
3679
|
+
if (pendingRedirect) {
|
|
3680
|
+
failed = true;
|
|
3681
|
+
break;
|
|
3682
|
+
}
|
|
3683
|
+
let j = i + (ch === "&" ? 2 : 1);
|
|
3684
|
+
if (ch === "<" && command[j] === "<") return null;
|
|
3685
|
+
if (command[j] === ">" || command[j] === "|") j++;
|
|
3686
|
+
if (command[j] === "&") {
|
|
3687
|
+
// a duplication or close (`>&2`, `2>&-`) writes no file; `>&file` does
|
|
3688
|
+
if (/[0-9-]/.test(command[j + 1] ?? "")) {
|
|
3689
|
+
j++;
|
|
3690
|
+
while (/[0-9]/.test(command[j] ?? "")) j++;
|
|
3691
|
+
if (command[j] === "-") j++;
|
|
3692
|
+
i = j;
|
|
3693
|
+
continue;
|
|
3694
|
+
}
|
|
3695
|
+
j++;
|
|
3696
|
+
}
|
|
3697
|
+
pendingRedirect = true;
|
|
3698
|
+
pendingWrite = ch !== "<" || command[i + 1] === ">";
|
|
3699
|
+
i = j;
|
|
3700
|
+
continue;
|
|
3701
|
+
}
|
|
3702
|
+
if (ch === "|") {
|
|
3703
|
+
const double = command[i + 1] === "|";
|
|
3704
|
+
operator(double ? "||" : "|");
|
|
3705
|
+
i += double || command[i + 1] === "&" ? 2 : 1;
|
|
3706
|
+
continue;
|
|
3707
|
+
}
|
|
3708
|
+
if (ch === "&") {
|
|
3709
|
+
if (command[i + 1] === "&") {
|
|
3710
|
+
operator("&&");
|
|
3711
|
+
i += 2;
|
|
3712
|
+
} else {
|
|
3713
|
+
operator("&");
|
|
3714
|
+
i++;
|
|
3715
|
+
}
|
|
3716
|
+
continue;
|
|
3717
|
+
}
|
|
3718
|
+
if (ch === ";") {
|
|
3719
|
+
const double = command[i + 1] === ";";
|
|
3720
|
+
operator(double ? ";;" : ";");
|
|
3721
|
+
i += double ? 2 : 1;
|
|
3722
|
+
continue;
|
|
3723
|
+
}
|
|
3724
|
+
if (ch === "(" || ch === ")") {
|
|
3725
|
+
operator(ch);
|
|
3726
|
+
i++;
|
|
3727
|
+
continue;
|
|
3728
|
+
}
|
|
3729
|
+
word += ch;
|
|
3730
|
+
started = true;
|
|
3731
|
+
i++;
|
|
3732
|
+
}
|
|
3733
|
+
if (failed) return null;
|
|
3734
|
+
flush();
|
|
3735
|
+
return pendingRedirect ? null : out;
|
|
3736
|
+
}
|
|
3737
|
+
|
|
3738
|
+
/** A simple command of a line, and the indexes of the commands whose output it reads through a pipe. */
|
|
3739
|
+
interface LineCommand {
|
|
3740
|
+
argv: string[];
|
|
3741
|
+
feeders: number[];
|
|
3742
|
+
}
|
|
3743
|
+
|
|
3744
|
+
/**
|
|
3745
|
+
* The simple commands of a line, in order. A command after `|` is fed by the command before it, or, when that
|
|
3746
|
+
* is a group `( … )` or `{ … }`, by every command of the group. Redirect targets are not words.
|
|
3747
|
+
*/
|
|
3748
|
+
function lineCommands(tokens: LineToken[]): LineCommand[] {
|
|
3749
|
+
const cmds: LineCommand[] = [];
|
|
3750
|
+
const groups: number[] = [];
|
|
3751
|
+
let argv: string[] = [];
|
|
3752
|
+
let feeders: number[] = [];
|
|
3753
|
+
let last: number[] = [];
|
|
3754
|
+
const finish = (): void => {
|
|
3755
|
+
if (argv.length === 0) return;
|
|
3756
|
+
cmds.push({ argv, feeders });
|
|
3757
|
+
last = [cmds.length - 1];
|
|
3758
|
+
argv = [];
|
|
3759
|
+
};
|
|
3760
|
+
for (const token of tokens) {
|
|
3761
|
+
if ("redirect" in token) continue;
|
|
3762
|
+
if ("word" in token) {
|
|
3763
|
+
argv.push(token.word);
|
|
3764
|
+
continue;
|
|
3765
|
+
}
|
|
3766
|
+
switch (token.op) {
|
|
3767
|
+
case "|":
|
|
3768
|
+
finish();
|
|
3769
|
+
feeders = last;
|
|
3770
|
+
break;
|
|
3771
|
+
case "(":
|
|
3772
|
+
case "{":
|
|
3773
|
+
finish();
|
|
3774
|
+
groups.push(cmds.length);
|
|
3775
|
+
break;
|
|
3776
|
+
case ")":
|
|
3777
|
+
case "}": {
|
|
3778
|
+
finish();
|
|
3779
|
+
const start = groups.pop() ?? 0;
|
|
3780
|
+
last = Array.from({ length: cmds.length - start }, (_, k) => start + k);
|
|
3781
|
+
break;
|
|
3782
|
+
}
|
|
3783
|
+
default:
|
|
3784
|
+
finish();
|
|
3785
|
+
feeders = [];
|
|
3786
|
+
}
|
|
3787
|
+
}
|
|
3788
|
+
finish();
|
|
3789
|
+
return cmds;
|
|
3790
|
+
}
|
|
3791
|
+
|
|
3792
|
+
/** Commands that print their input's lines unchanged or filtered: a file list piped through them keeps its names. */
|
|
3793
|
+
const PASS_THROUGH = new Set(["sort", "uniq", "head", "tail", "grep", "egrep", "fgrep", "sed", "tr", "cut", "tee", "awk", "cat", "rev", "shuf"]);
|
|
3794
|
+
|
|
3795
|
+
/** Commands that print no file's text when given files (a count, a size, a type, a digest, or they change the file). */
|
|
3796
|
+
const NON_READING = new Set(["echo", "printf", "wc", "ls", "stat", "file", "du", "basename", "dirname", "realpath", "readlink", "md5sum", "sha1sum", "sha256sum", "sha512sum", "touch", "mkdir", "rmdir", "rm", "chmod"]);
|
|
3797
|
+
|
|
3798
|
+
/** Launchers stripped before a command is judged: the wrappers, and the runners of RUNNER_VALUE_OPTIONS (not ssh: its first operand is a host). */
|
|
3799
|
+
const PIPE_WRAPPERS = new Set(["nice", "time", "nohup", "command", "env", "stdbuf", "timeout", "setsid", "chronic", ...Object.keys(RUNNER_VALUE_OPTIONS).filter((name) => name !== "ssh")]);
|
|
3800
|
+
|
|
3801
|
+
/** Options of the wrappers above that take a separate value (`nice -n 5`, `timeout -s KILL 5`). */
|
|
3802
|
+
const LAUNCHER_VALUES: Record<string, string[]> = {
|
|
3803
|
+
nice: ["-n", "--adjustment"],
|
|
3804
|
+
timeout: ["-s", "-k", "--signal", "--kill-after"],
|
|
3805
|
+
env: ["-u", "--unset", "-C", "--chdir"],
|
|
3806
|
+
stdbuf: ["-i", "-o", "-e"],
|
|
3807
|
+
time: ["-f", "-o"],
|
|
3808
|
+
};
|
|
3809
|
+
|
|
3810
|
+
/** The command a launcher runs: its options (with their values), `NAME=value` words (env), and the positional word of timeout, chrt and taskset are dropped. */
|
|
3811
|
+
function stripPipeWrappers(argv: string[]): string[] {
|
|
3812
|
+
let k = 0;
|
|
3813
|
+
while (k < argv.length && PIPE_WRAPPERS.has(basename(argv[k] ?? ""))) {
|
|
3814
|
+
const name = basename(argv[k] ?? "");
|
|
3815
|
+
const values = [...(LAUNCHER_VALUES[name] ?? []), ...(RUNNER_VALUE_OPTIONS[name] ?? [])];
|
|
3816
|
+
k++;
|
|
3817
|
+
let cpuGiven = false;
|
|
3818
|
+
while (k < argv.length) {
|
|
3819
|
+
const word = argv[k] ?? "";
|
|
3820
|
+
if (word.startsWith("-")) {
|
|
3821
|
+
k++;
|
|
3822
|
+
if (word === "-c" || word === "--cpu-list") cpuGiven = true;
|
|
3823
|
+
if (values.includes(word)) k++;
|
|
3824
|
+
continue;
|
|
3825
|
+
}
|
|
3826
|
+
if (name === "env" && /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) {
|
|
3827
|
+
k++;
|
|
3828
|
+
continue;
|
|
3829
|
+
}
|
|
3830
|
+
break;
|
|
3831
|
+
}
|
|
3832
|
+
// the positional word before the command: timeout's duration, chrt's priority, taskset's mask (not with -c)
|
|
3833
|
+
const positional = name === "timeout" || name === "chrt" || (name === "taskset" && !cpuGiven);
|
|
3834
|
+
if (positional && k < argv.length) k++;
|
|
3835
|
+
}
|
|
3836
|
+
return argv.slice(k);
|
|
3837
|
+
}
|
|
3838
|
+
|
|
3839
|
+
/** True when a command named as the first word reads the files it is given (not in NON_READING; nothing named is the default `echo`). */
|
|
3840
|
+
function isReadingCommand(root: string | undefined): boolean {
|
|
3841
|
+
return root !== undefined && !NON_READING.has(basename(root));
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3844
|
+
/** Short xargs options that take a value (`-I {}`, `-n 1`); `-i`, `-e`, `-l` take an attached value only. */
|
|
3845
|
+
const XARGS_VALUE_SHORT = "ILnPsEadj";
|
|
3846
|
+
const XARGS_LONG_VALUE = new Set(["max-args", "max-procs", "max-chars", "delimiter", "arg-file", "process-slot-var", "jobs"]);
|
|
3847
|
+
|
|
3848
|
+
/** The command xargs runs: its first word after xargs' own options (none: the default `echo`). */
|
|
3849
|
+
function xargsCommand(args: string[]): string[] {
|
|
3850
|
+
for (let k = 0; k < args.length; k++) {
|
|
3851
|
+
const a = args[k] ?? "";
|
|
3852
|
+
if (a === "--") return args.slice(k + 1);
|
|
3853
|
+
if (a.startsWith("--")) {
|
|
3854
|
+
if (!a.includes("=") && XARGS_LONG_VALUE.has(a.slice(2))) k++;
|
|
3855
|
+
continue;
|
|
3856
|
+
}
|
|
3857
|
+
if (a.startsWith("-") && a.length > 1) {
|
|
3858
|
+
for (let c = 1; c < a.length; c++) {
|
|
3859
|
+
if (!XARGS_VALUE_SHORT.includes(a[c] ?? "")) continue;
|
|
3860
|
+
if (c === a.length - 1) k++;
|
|
3861
|
+
break;
|
|
3862
|
+
}
|
|
3863
|
+
continue;
|
|
3864
|
+
}
|
|
3865
|
+
return args.slice(k);
|
|
3866
|
+
}
|
|
3867
|
+
return [];
|
|
3868
|
+
}
|
|
3869
|
+
|
|
3870
|
+
/** Short ls options that take a value (`-I PATTERN`, `-w N`, `-T N`), and the long ones. */
|
|
3871
|
+
const LS_VALUE_SHORT = "IwT";
|
|
3872
|
+
const LS_LONG_VALUE = new Set(["hide", "ignore", "width", "tabsize", "block-size", "format", "sort", "time-style", "time"]);
|
|
3873
|
+
|
|
3874
|
+
/** The directories an ls lists: its operands (not option values); `.` when none. */
|
|
3875
|
+
function lsOperands(args: string[]): string[] {
|
|
3876
|
+
const out: string[] = [];
|
|
3877
|
+
let options = true;
|
|
3878
|
+
for (let k = 0; k < args.length; k++) {
|
|
3879
|
+
const a = args[k] ?? "";
|
|
3880
|
+
if (options && a === "--") {
|
|
3881
|
+
options = false;
|
|
3882
|
+
continue;
|
|
3883
|
+
}
|
|
3884
|
+
if (options && a.startsWith("--")) {
|
|
3885
|
+
if (!a.includes("=") && LS_LONG_VALUE.has(a.slice(2))) k++;
|
|
3886
|
+
continue;
|
|
3887
|
+
}
|
|
3888
|
+
if (options && a.startsWith("-") && a.length > 1) {
|
|
3889
|
+
for (let c = 1; c < a.length; c++) {
|
|
3890
|
+
if (!LS_VALUE_SHORT.includes(a[c] ?? "")) continue;
|
|
3891
|
+
if (c === a.length - 1) k++;
|
|
3892
|
+
break;
|
|
3893
|
+
}
|
|
3894
|
+
continue;
|
|
3895
|
+
}
|
|
3896
|
+
out.push(a);
|
|
3897
|
+
}
|
|
3898
|
+
return out.length > 0 ? out : ["."];
|
|
3899
|
+
}
|
|
3900
|
+
|
|
3901
|
+
/** The roots a find walks: the paths before its expression (after -H/-L/-P), `.` when none. */
|
|
3902
|
+
function findRoots(args: string[]): string[] {
|
|
3903
|
+
let k = 0;
|
|
3904
|
+
while (k < args.length && (args[k] === "-H" || args[k] === "-L" || args[k] === "-P")) k++;
|
|
3905
|
+
const roots: string[] = [];
|
|
3906
|
+
for (; k < args.length && !/^[-(!]/.test(args[k] ?? ""); k++) roots.push(args[k] ?? "");
|
|
3907
|
+
return roots.length > 0 ? roots : ["."];
|
|
3908
|
+
}
|
|
3909
|
+
|
|
3910
|
+
/** find's expression words that can keep names other than the `-name` glob: a negation, an alternative, a group, a prune. */
|
|
3911
|
+
const FIND_COMPLEX = new Set(["!", "-not", "-o", "-or", "(", "-prune"]);
|
|
3912
|
+
const FIND_EXEC = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
3913
|
+
|
|
3914
|
+
/**
|
|
3915
|
+
* The walk of a find: every file under its roots, or, when its expression is a plain `-name G` / `-iname G`,
|
|
3916
|
+
* only the files whose name G matches (the same test as a recursive search's include).
|
|
3917
|
+
*/
|
|
3918
|
+
function findScan(args: string[]): SearchScan {
|
|
3919
|
+
const scan = treeScan();
|
|
3920
|
+
if (args.some((a) => FIND_COMPLEX.has(a))) return scan;
|
|
3921
|
+
const at = args.findIndex((a) => a === "-name" || a === "-iname");
|
|
3922
|
+
const glob = at === -1 ? undefined : args[at + 1];
|
|
3923
|
+
if (glob !== undefined) scan.includes = [args[at] === "-iname" ? caseless(glob) : glob];
|
|
3924
|
+
return scan;
|
|
3925
|
+
}
|
|
3926
|
+
|
|
3927
|
+
/** True for `git ls-files` that lists untracked files: `--others`, or a short cluster holding `o` (`-o`, `-io`). */
|
|
3928
|
+
function gitUntracked(args: string[]): boolean {
|
|
3929
|
+
return args.some((a) => a === "--others" || (/^-[A-Za-z]+$/.test(a) && a.includes("o")));
|
|
3930
|
+
}
|
|
3931
|
+
|
|
3932
|
+
/** A walk of every file under the roots, with no include filter. */
|
|
3933
|
+
function treeScan(): SearchScan {
|
|
3934
|
+
return { recursive: true, unrestricted: false, roots: [], includes: [], excludes: [], excludeDirs: [] };
|
|
3935
|
+
}
|
|
3936
|
+
|
|
3937
|
+
/** A search over `roots` from a file list: `pipe` is set, so a root outside the project is not walked. */
|
|
3938
|
+
interface ListSearch {
|
|
3939
|
+
roots: Array<string | undefined>;
|
|
3940
|
+
scan: SearchScan;
|
|
3941
|
+
pipe: boolean;
|
|
3942
|
+
}
|
|
3943
|
+
|
|
3944
|
+
/**
|
|
3945
|
+
* The searches a file list makes, when a reader gets the names: `ls`, `find` or `git ls-files` (untracked)
|
|
3946
|
+
* whose output reaches `xargs <reader>` through pass-through filters, groups and wrappers; and a `find` whose
|
|
3947
|
+
* `-exec` / `-ok` runs a reader. Every reader but the NON_READING ones counts. The tree a list walks is
|
|
3948
|
+
* searched the way a recursive search is. A `cd` in the command, or a path that can't be resolved, is
|
|
3949
|
+
* unchecked. Tracked files (`git ls-files`) are content, and a list the lexer can't read is unchecked.
|
|
3950
|
+
*/
|
|
3951
|
+
function pipedListSearches(command: string, ctx: PathContext): ListSearch[] {
|
|
3952
|
+
const tokens = lexLine(command);
|
|
3953
|
+
if (tokens === null) {
|
|
3954
|
+
const mayList = /\b(xargs|find|ls|git)\b/.test(command) && /\b(xargs|-exec|-execdir|-ok|-okdir)\b/.test(command);
|
|
3955
|
+
return mayList ? [{ roots: [undefined], scan: treeScan(), pipe: true }] : [];
|
|
3956
|
+
}
|
|
3957
|
+
const cmds = lineCommands(tokens);
|
|
3958
|
+
const changesDir = scanUnits(command).some((unit) => DIR_CHANGERS.has(basename(unit[0] ?? "")));
|
|
3959
|
+
const rootsOf = (words: string[]): Array<string | undefined> =>
|
|
3960
|
+
words.flatMap((word) => (changesDir || /[$`]/.test(word) ? [undefined] : expandSearchRoot(word, ctx.cwd)));
|
|
3961
|
+
// the search a list-making command is, or undefined for any other command
|
|
3962
|
+
const listOf = (argv: string[]): ListSearch | undefined => {
|
|
3963
|
+
const [name = "", ...args] = argv;
|
|
3964
|
+
const base = basename(name);
|
|
3965
|
+
if (base === "ls") return { roots: rootsOf(lsOperands(args)), scan: treeScan(), pipe: true };
|
|
3966
|
+
if (base === "find") return { roots: rootsOf(findRoots(args)), scan: findScan(args), pipe: true };
|
|
3967
|
+
if (base === "git") {
|
|
3968
|
+
const at = args.indexOf("ls-files");
|
|
3969
|
+
if (at === -1 || !gitUntracked(args.slice(at + 1))) return undefined;
|
|
3970
|
+
// `git -C <dir> ls-files` names another repository than the cwd's: not judged
|
|
3971
|
+
return { roots: at === 0 ? rootsOf(["."]) : [undefined], scan: treeScan(), pipe: true };
|
|
3972
|
+
}
|
|
3973
|
+
return undefined;
|
|
3974
|
+
};
|
|
3975
|
+
// the lists that reach a command through its pipe, walking back through pass-through filters
|
|
3976
|
+
const feeding = (indexes: number[], depth: number): ListSearch[] =>
|
|
3977
|
+
indexes.flatMap((idx) => {
|
|
3978
|
+
const cmd = cmds[idx];
|
|
3979
|
+
if (cmd === undefined) return [];
|
|
3980
|
+
const argv = stripPipeWrappers(cmd.argv);
|
|
3981
|
+
const found = listOf(argv);
|
|
3982
|
+
if (found !== undefined) return [found];
|
|
3983
|
+
if (!PASS_THROUGH.has(basename(argv[0] ?? ""))) return [];
|
|
3984
|
+
// a chain this deep is not followed: its list is unchecked
|
|
3985
|
+
return depth < 16 ? feeding(cmd.feeders, depth + 1) : [{ roots: [undefined], scan: treeScan(), pipe: true }];
|
|
3986
|
+
});
|
|
3987
|
+
const out: ListSearch[] = [];
|
|
3988
|
+
for (const cmd of cmds) {
|
|
3989
|
+
const argv = stripPipeWrappers(cmd.argv);
|
|
3990
|
+
const root = basename(argv[0] ?? "");
|
|
3991
|
+
if (root === "find" && argv.slice(1).some((a, k, all) => FIND_EXEC.has(a) && isReadingCommand(all[k + 1]))) {
|
|
3992
|
+
const found = listOf(argv);
|
|
3993
|
+
if (found !== undefined) out.push(found);
|
|
3994
|
+
}
|
|
3995
|
+
if ((root === "xargs" || root === "parallel") && isReadingCommand(stripPipeWrappers(xargsCommand(argv.slice(1)))[0])) out.push(...feeding(cmd.feeders, 0));
|
|
3996
|
+
}
|
|
3997
|
+
return out;
|
|
3998
|
+
}
|
|
3999
|
+
|
|
4000
|
+
/**
|
|
4001
|
+
* Literal redirection targets that are outside the project (`> f`, `>> f`, `&> f`, `>| f`, `2> f`), judged from
|
|
4002
|
+
* the cwd and every directory a unit runs in (a `cd` moves them). /dev/null, fd duplications and unresolvable
|
|
4003
|
+
* targets are not outside.
|
|
4004
|
+
*/
|
|
4005
|
+
function redirectOutsideTargets(command: string, ctx: PathContext): string[] {
|
|
4006
|
+
const tokens = lexLine(command);
|
|
4007
|
+
const targets = tokens === null ? redirectTextTargets(command) : tokens.flatMap((token) => ("redirect" in token ? [token.redirect] : []));
|
|
4008
|
+
if (targets.length === 0) return [];
|
|
4009
|
+
const dirs = [...new Set<string | null | undefined>([ctx.cwd, ...unitsWithDirs(command, ctx).map((unit) => unit.dir ?? null)])];
|
|
4010
|
+
const judged = new Map<string, boolean>();
|
|
4011
|
+
const outside = (target: string): boolean => {
|
|
4012
|
+
const known = judged.get(target);
|
|
4013
|
+
if (known !== undefined) return known;
|
|
4014
|
+
const result = dirs.some((dir) => targetProblem({ word: target, glob: false }, ctx.cwd, dir, ctx.scratchDir) === "outside");
|
|
4015
|
+
judged.set(target, result);
|
|
4016
|
+
return result;
|
|
4017
|
+
};
|
|
4018
|
+
return targets.filter((target) => target !== "/dev/null" && outside(target));
|
|
4019
|
+
}
|
|
4020
|
+
|
|
4021
|
+
/**
|
|
4022
|
+
* The `>`-class redirect targets of a line the lexer can't read, found in the text: `>`, `>>`, `&>`, `>|`, `N>`,
|
|
4023
|
+
* with the quotes removed from the target. Input (`<`) is not one. A quoted `>` counts too (fails closed).
|
|
4024
|
+
*/
|
|
4025
|
+
function redirectTextTargets(command: string): string[] {
|
|
4026
|
+
const targets: string[] = [];
|
|
4027
|
+
for (const match of command.matchAll(/(?:^|[\s;&|(])(?:\d*|&)>>?\|?\s*([^\s;&|<>()]+)/g)) {
|
|
4028
|
+
const target = (match[1] ?? "").replace(/['"]/g, "");
|
|
4029
|
+
if (target !== "") targets.push(target);
|
|
4030
|
+
}
|
|
4031
|
+
return targets;
|
|
4032
|
+
}
|
|
4033
|
+
|
|
4034
|
+
/** A glob that matches the same names ignoring case: each letter becomes both cases (a glob with its own brackets is kept). */
|
|
4035
|
+
function caseless(glob: string): string {
|
|
4036
|
+
return glob.includes("[") ? glob : glob.replace(/[A-Za-z]/g, (c) => `[${c.toLowerCase()}${c.toUpperCase()}]`);
|
|
4037
|
+
}
|
|
4038
|
+
|
|
3151
4039
|
// ---------------------------------------------------------------------------
|
|
3152
4040
|
// Uploads of secret files
|
|
3153
4041
|
// ---------------------------------------------------------------------------
|
|
@@ -3230,11 +4118,13 @@ export function secretUploads(command: string, ctx: PathContext): string[] {
|
|
|
3230
4118
|
const SECRET_FILE_SAMPLES = [".env", ".env.local", ".env.development", ".env.production", ".env.test"];
|
|
3231
4119
|
|
|
3232
4120
|
/** A glob whose basename can match a .env file. Leading `*`/`?`/`[` never match dotfiles. */
|
|
3233
|
-
function globMatchesSecretFile(word: string): boolean {
|
|
4121
|
+
function globMatchesSecretFile(word: string, capped = true): boolean {
|
|
4122
|
+
// too many stars to check: it may match anything, a secret included
|
|
4123
|
+
if (capped && starCount(word) > GLOB_STAR_LIMIT) return true;
|
|
3234
4124
|
const name = basename(word);
|
|
3235
4125
|
if (!name.startsWith(".") || !/[*?[]/.test(name)) return false;
|
|
3236
|
-
const pattern = globToRegExp(name);
|
|
3237
|
-
return pattern
|
|
4126
|
+
const pattern = globToRegExp(name, capped);
|
|
4127
|
+
return pattern === null || SECRET_FILE_SAMPLES.some((sample) => pattern.test(sample));
|
|
3238
4128
|
}
|
|
3239
4129
|
|
|
3240
4130
|
/** Most files a glob operand may match before it is no longer checked one by one. */
|
|
@@ -3275,7 +4165,8 @@ function braceAlternatives(word: string, depth = 0): string[] | null {
|
|
|
3275
4165
|
* Null when more than GLOB_EXPANSION_LIMIT names would be read, so the caller
|
|
3276
4166
|
* can fail closed.
|
|
3277
4167
|
*/
|
|
3278
|
-
function expandGlob(word: string, cwd: string): string[] | null {
|
|
4168
|
+
function expandGlob(word: string, cwd: string, capped = true): string[] | null {
|
|
4169
|
+
if (capped && starCount(word) > GLOB_STAR_LIMIT) return null;
|
|
3279
4170
|
const alternatives = braceAlternatives(word);
|
|
3280
4171
|
if (alternatives === null) return null;
|
|
3281
4172
|
const found: string[] = [];
|
|
@@ -3288,7 +4179,7 @@ function expandGlob(word: string, cwd: string): string[] | null {
|
|
|
3288
4179
|
if (!/[*?[]/.test(segment)) {
|
|
3289
4180
|
for (const base of paths) next.push(joined(base, segment));
|
|
3290
4181
|
} else {
|
|
3291
|
-
const pattern = globToRegExp(segment);
|
|
4182
|
+
const pattern = globToRegExp(segment, capped);
|
|
3292
4183
|
if (pattern === null) return null;
|
|
3293
4184
|
for (const base of paths) {
|
|
3294
4185
|
let names: string[];
|
|
@@ -3324,17 +4215,21 @@ function lstatOk(path: string): boolean {
|
|
|
3324
4215
|
* by looking at the directory: `conf/*` holding an `id_rsa` is a secret read
|
|
3325
4216
|
* that no pattern on the word can show. Unreadable by the limit counts as one.
|
|
3326
4217
|
*/
|
|
3327
|
-
function globMatchesSecretOnDisk(word: string, ctx: SecretContext | undefined): boolean {
|
|
4218
|
+
function globMatchesSecretOnDisk(word: string, ctx: SecretContext | undefined, capped = true): boolean {
|
|
3328
4219
|
if (ctx?.cwd === undefined || !/[*?[{]/.test(word) || word.startsWith("-")) return false;
|
|
3329
|
-
const matches = expandGlob(word, ctx.cwd);
|
|
4220
|
+
const matches = expandGlob(word, ctx.cwd, capped);
|
|
3330
4221
|
return matches === null || matches.some((match) => isSecretFile(match, ctx));
|
|
3331
4222
|
}
|
|
3332
4223
|
|
|
3333
|
-
function globToRegExp(glob: string): RegExp | null {
|
|
4224
|
+
function globToRegExp(glob: string, capped = true): RegExp | null {
|
|
4225
|
+
if (capped && starCount(glob) > GLOB_STAR_LIMIT) return null;
|
|
3334
4226
|
let source = "";
|
|
3335
4227
|
for (let i = 0; i < glob.length; i++) {
|
|
3336
4228
|
const ch = glob[i];
|
|
3337
|
-
|
|
4229
|
+
// a run of stars is one `.*`: each extra one only adds backtracking
|
|
4230
|
+
if (ch === "*") {
|
|
4231
|
+
if (glob[i - 1] !== "*") source += ".*";
|
|
4232
|
+
}
|
|
3338
4233
|
else if (ch === "?") source += ".";
|
|
3339
4234
|
else if (ch === "[" && glob.indexOf("]", i + 2) !== -1) {
|
|
3340
4235
|
const end = glob.indexOf("]", i + 2);
|
|
@@ -3370,11 +4265,13 @@ export function deriveCommandPrefixes(command: string, ctx: PathContext): string
|
|
|
3370
4265
|
if (trimmed.length > MAX_COMMAND_LENGTH) return undefined;
|
|
3371
4266
|
const tokens = tokenize(maskForAnalysis(trimmed, ctx.scratchDir), ctx.scratchDir);
|
|
3372
4267
|
if (tokens === null) return undefined;
|
|
3373
|
-
const segments = normalizeGitSegments(tokens, ctx.cwd);
|
|
4268
|
+
const segments = normalizeGitSegments(tokens, ctx.cwd, ctx.gitRepos);
|
|
4269
|
+
// a remembered `cd` never lifts a git run in another repo: only a repo grant does (CD_GIT_REASON)
|
|
4270
|
+
if (gitInOtherRepoAfterCd(tokens, segments, ctx.cwd, ctx.gitRepos)) return undefined;
|
|
3374
4271
|
const dirs = segmentDirs(tokens, ctx.cwd);
|
|
3375
4272
|
const prefixes: string[][] = [];
|
|
3376
4273
|
for (const [k, segment] of segments.entries()) {
|
|
3377
|
-
const blocker = segmentBlocker(segment, ctx.cwd, ctx.scratchDir);
|
|
4274
|
+
const blocker = segmentBlocker(segment, ctx.cwd, ctx.scratchDir, false, undefined, undefined, ctx.gitRepos);
|
|
3378
4275
|
if (blocker === undefined) continue;
|
|
3379
4276
|
// exec can't be covered; a write is offered only when this call's targets stay in the project
|
|
3380
4277
|
if (blocker.effect === "exec" || writeProblem(blocker, ctx.cwd, dirs[k], ctx.scratchDir) !== undefined) return undefined;
|
|
@@ -3399,7 +4296,7 @@ const INSIDE_ONLY = " (inside the project only)";
|
|
|
3399
4296
|
export function scopeSuffix(command: string, ctx: PathContext): string {
|
|
3400
4297
|
const tokens = tokenize(maskForAnalysis(command.trim(), ctx.scratchDir), ctx.scratchDir);
|
|
3401
4298
|
if (tokens === null) return "";
|
|
3402
|
-
return normalizeGitSegments(tokens, ctx.cwd).some((segment) => segmentBlocker(segment, ctx.cwd, ctx.scratchDir)?.effect === "write") ? INSIDE_ONLY : "";
|
|
4299
|
+
return normalizeGitSegments(tokens, ctx.cwd, ctx.gitRepos).some((segment) => segmentBlocker(segment, ctx.cwd, ctx.scratchDir, false, undefined, undefined, ctx.gitRepos)?.effect === "write") ? INSIDE_ONLY : "";
|
|
3403
4300
|
}
|
|
3404
4301
|
|
|
3405
4302
|
/** One choice of the "different command pattern" picker. */
|
|
@@ -3433,9 +4330,9 @@ export function patternLadder(command: string, ctx: PathContext): PatternChoice[
|
|
|
3433
4330
|
const tokens = tokenize(maskForAnalysis(trimmed, ctx.scratchDir), ctx.scratchDir);
|
|
3434
4331
|
if (tokens === null) return undefined;
|
|
3435
4332
|
const dirs = segmentDirs(tokens, ctx.cwd);
|
|
3436
|
-
const needing = normalizeGitSegments(tokens, ctx.cwd).flatMap((segment, k) => (isReadOnlySegment(segment, ctx.cwd, ctx.scratchDir) ? [] : [{ segment, dir: dirs[k] }]));
|
|
4333
|
+
const needing = normalizeGitSegments(tokens, ctx.cwd, ctx.gitRepos).flatMap((segment, k) => (isReadOnlySegment(segment, ctx.cwd, ctx.scratchDir, undefined, ctx.gitRepos) ? [] : [{ segment, dir: dirs[k] }]));
|
|
3437
4334
|
if (needing.length !== 1) return undefined;
|
|
3438
|
-
const blocker = segmentBlocker(needing[0].segment, ctx.cwd, ctx.scratchDir);
|
|
4335
|
+
const blocker = segmentBlocker(needing[0].segment, ctx.cwd, ctx.scratchDir, false, undefined, undefined, ctx.gitRepos);
|
|
3439
4336
|
const stripped = stripPrefixes(needing[0].segment.argv, needing[0].segment.globs, true);
|
|
3440
4337
|
if (stripped === null || blocker?.effect === "exec" || (blocker !== undefined && writeProblem(blocker, ctx.cwd, needing[0].dir, ctx.scratchDir) !== undefined)) return undefined;
|
|
3441
4338
|
const suffix = blocker?.effect === "write" ? INSIDE_ONLY : "";
|
|
@@ -3471,9 +4368,9 @@ export function exactRuleTokens(command: string, ctx: PathContext): string[] | u
|
|
|
3471
4368
|
const tokens = tokenize(maskForAnalysis(trimmed, ctx.scratchDir), ctx.scratchDir);
|
|
3472
4369
|
if (tokens === null) return undefined;
|
|
3473
4370
|
const dirs = segmentDirs(tokens, ctx.cwd);
|
|
3474
|
-
const needing = normalizeGitSegments(tokens, ctx.cwd).flatMap((segment, k) => (isReadOnlySegment(segment, ctx.cwd, ctx.scratchDir) ? [] : [{ segment, dir: dirs[k] }]));
|
|
4371
|
+
const needing = normalizeGitSegments(tokens, ctx.cwd, ctx.gitRepos).flatMap((segment, k) => (isReadOnlySegment(segment, ctx.cwd, ctx.scratchDir, undefined, ctx.gitRepos) ? [] : [{ segment, dir: dirs[k] }]));
|
|
3475
4372
|
if (needing.length !== 1) return undefined;
|
|
3476
|
-
const blocker = segmentBlocker(needing[0].segment, ctx.cwd, ctx.scratchDir);
|
|
4373
|
+
const blocker = segmentBlocker(needing[0].segment, ctx.cwd, ctx.scratchDir, false, undefined, undefined, ctx.gitRepos);
|
|
3477
4374
|
const stripped = stripPrefixes(needing[0].segment.argv, needing[0].segment.globs, true);
|
|
3478
4375
|
// removals never get a rule (privilege and the file-format checks are parseRule's call)
|
|
3479
4376
|
if (stripped === null || isRemoval(stripped.argv) || blocker?.effect === "exec" || (blocker !== undefined && writeProblem(blocker, ctx.cwd, needing[0].dir, ctx.scratchDir) !== undefined)) return undefined;
|
|
@@ -3511,11 +4408,12 @@ export function planCommandPrefixes(commands: readonly string[], ctx: PathContex
|
|
|
3511
4408
|
* would be broader than the table intends).
|
|
3512
4409
|
*/
|
|
3513
4410
|
function prefixFor(command: string[]): string[] | undefined {
|
|
4411
|
+
if (NEVER_RULE_ROOTS.has(command[0] ?? "")) return undefined;
|
|
3514
4412
|
const argv = canonicalize(command);
|
|
3515
4413
|
const [root, ...args] = argv;
|
|
3516
4414
|
if (root === undefined || isRemoval(argv)) return undefined;
|
|
3517
4415
|
const name = basename(root);
|
|
3518
|
-
if (INTERPRETERS.has(name) ||
|
|
4416
|
+
if (INTERPRETERS.has(name) || isRunnerName(name) || PRIVILEGE_COMMANDS.has(name)) return undefined;
|
|
3519
4417
|
|
|
3520
4418
|
if (name === "rtk") {
|
|
3521
4419
|
// not a 1:1 proxy: remember the rtk form (`rtk test cargo test`, `rtk read`)
|
|
@@ -3573,11 +4471,12 @@ function isRemoval(command: string[]): boolean {
|
|
|
3573
4471
|
* (`npm run` would allow every script).
|
|
3574
4472
|
*/
|
|
3575
4473
|
export function isRememberablePrefix(typed: readonly string[]): boolean {
|
|
4474
|
+
if (NEVER_RULE_ROOTS.has(typed[0] ?? "")) return false;
|
|
3576
4475
|
const tokens = canonicalize(typed);
|
|
3577
4476
|
const [root, ...args] = tokens;
|
|
3578
4477
|
if (root === undefined || isRemoval([...tokens])) return false;
|
|
3579
4478
|
const name = basename(root);
|
|
3580
|
-
if (INTERPRETERS.has(name) ||
|
|
4479
|
+
if (INTERPRETERS.has(name) || isRunnerName(name) || PRIVILEGE_COMMANDS.has(name)) return false;
|
|
3581
4480
|
if (name === "rtk") {
|
|
3582
4481
|
const sub = args[0];
|
|
3583
4482
|
if (sub === undefined || sub.startsWith("-") || sub === "run") return false;
|
|
@@ -3597,6 +4496,7 @@ export function isRememberablePrefix(typed: readonly string[]): boolean {
|
|
|
3597
4496
|
* runners (`npm run build`) are fine: only that command runs unasked.
|
|
3598
4497
|
*/
|
|
3599
4498
|
export function isRememberableExact(typed: readonly string[]): boolean {
|
|
4499
|
+
if (NEVER_RULE_ROOTS.has(typed[0] ?? "")) return false;
|
|
3600
4500
|
const tokens = canonicalize(typed);
|
|
3601
4501
|
const [root, ...args] = tokens;
|
|
3602
4502
|
if (root === undefined || isRemoval([...tokens])) return false;
|
|
@@ -3616,16 +4516,16 @@ export function isRememberableExact(typed: readonly string[]): boolean {
|
|
|
3616
4516
|
* `npm test && rm x` is not covered by `npm test`, and removals are never
|
|
3617
4517
|
* covered, even by a prefix the user typed (`git` does not cover `git rm`).
|
|
3618
4518
|
*/
|
|
3619
|
-
export function isCoveredByPrefixes(command: string, prefixes: readonly (readonly string[])[], cwd: string, exact: readonly (readonly string[])[] = [], scratch?: string, fetchHosts?: readonly string[]): boolean {
|
|
4519
|
+
export function isCoveredByPrefixes(command: string, prefixes: readonly (readonly string[])[], cwd: string, exact: readonly (readonly string[])[] = [], scratch?: string, fetchHosts?: readonly string[], gitRepos?: readonly string[]): boolean {
|
|
3620
4520
|
if (prefixes.length === 0 && exact.length === 0) return false;
|
|
3621
4521
|
const trimmed = command.trim();
|
|
3622
4522
|
if (trimmed === "" || trimmed.length > MAX_COMMAND_LENGTH) return false;
|
|
3623
4523
|
const tokens = tokenize(maskForAnalysis(trimmed, scratch), scratch);
|
|
3624
4524
|
if (tokens === null || tokens.length === 0) return false;
|
|
3625
|
-
const segments = normalizeGitSegments(tokens, cwd);
|
|
4525
|
+
const segments = normalizeGitSegments(tokens, cwd, gitRepos);
|
|
3626
4526
|
const dirs = segmentDirs(tokens, cwd);
|
|
3627
|
-
if (!segments.every((segment, k) => isReadOnlySegment(segment, cwd, scratch, fetchHosts) || isCoveredSegment(segment, prefixes, cwd, exact, scratch, dirs[k]))) return false;
|
|
3628
|
-
return !gitRunsInOtherRepo(segments, cwd);
|
|
4527
|
+
if (!segments.every((segment, k) => isReadOnlySegment(segment, cwd, scratch, fetchHosts, gitRepos) || isCoveredSegment(segment, prefixes, cwd, exact, scratch, dirs[k], gitRepos))) return false;
|
|
4528
|
+
return !gitRunsInOtherRepo(segments, cwd, true, gitRepos);
|
|
3629
4529
|
}
|
|
3630
4530
|
|
|
3631
4531
|
/**
|
|
@@ -3634,7 +4534,7 @@ export function isCoveredByPrefixes(command: string, prefixes: readonly (readonl
|
|
|
3634
4534
|
* repo: that repo's hooks and config (fsmonitor) would run. A `cd` into a
|
|
3635
4535
|
* plain subdirectory of the same repo is fine.
|
|
3636
4536
|
*/
|
|
3637
|
-
function gitRunsInOtherRepo(segments: Segment[], cwd: string, checkRepoFlags = true): boolean {
|
|
4537
|
+
function gitRunsInOtherRepo(segments: Segment[], cwd: string, checkRepoFlags = true, gitRepos?: readonly string[]): boolean {
|
|
3638
4538
|
let dir: string | undefined = cwd;
|
|
3639
4539
|
for (const segment of segments) {
|
|
3640
4540
|
const stripped = stripPrefixes(segment.argv, segment.globs, true);
|
|
@@ -3647,12 +4547,83 @@ function gitRunsInOtherRepo(segments: Segment[], cwd: string, checkRepoFlags = t
|
|
|
3647
4547
|
// -C / --git-dir / --work-tree left after normalization point at another repo
|
|
3648
4548
|
const flags = args.slice(0, Math.max(0, args.findIndex((x) => !x.startsWith("-"))));
|
|
3649
4549
|
if (checkRepoFlags && flags.some((f) => f === "-C" || /^--(git-dir|work-tree)(=|$)/.test(f))) return true;
|
|
3650
|
-
if (dir === undefined || (dir !== cwd &&
|
|
4550
|
+
if (dir === undefined || (dir !== cwd && foreignGitDir(dir, cwd, gitRepos))) return true;
|
|
3651
4551
|
}
|
|
3652
4552
|
}
|
|
3653
4553
|
return false;
|
|
3654
4554
|
}
|
|
3655
4555
|
|
|
4556
|
+
/**
|
|
4557
|
+
* True when git run in `dir` would use another repository than the one at
|
|
4558
|
+
* `cwd` (crossesRepoBoundary) and that repository is not granted for the
|
|
4559
|
+
* session (gitRepos, realpaths of repo roots from gitRepoRootOf).
|
|
4560
|
+
*/
|
|
4561
|
+
function foreignGitDir(dir: string, cwd: string, gitRepos?: readonly string[]): boolean {
|
|
4562
|
+
return crossesRepoBoundary(dir, cwd) && !inGrantedRepo(dir, gitRepos);
|
|
4563
|
+
}
|
|
4564
|
+
|
|
4565
|
+
/** True when `dir` belongs to a git repo the user granted for the session (its repo root is in gitRepos). */
|
|
4566
|
+
function inGrantedRepo(dir: string, gitRepos?: readonly string[]): boolean {
|
|
4567
|
+
if (gitRepos === undefined || gitRepos.length === 0) return false;
|
|
4568
|
+
const root = gitRepoRootOf(dir);
|
|
4569
|
+
return root !== undefined && gitRepos.includes(root);
|
|
4570
|
+
}
|
|
4571
|
+
|
|
4572
|
+
/**
|
|
4573
|
+
* The git repository a run in `dir` belongs to: the realpath of `dir`, or of
|
|
4574
|
+
* its nearest ancestor holding `.git`. Undefined when `dir` can't be resolved,
|
|
4575
|
+
* no ancestor holds `.git`, or that root is too broad to grant: "/", the home
|
|
4576
|
+
* dir or one of its ancestors (the same bar as readGrantDir).
|
|
4577
|
+
*/
|
|
4578
|
+
export function gitRepoRootOf(dir: string): string | undefined {
|
|
4579
|
+
let current: string;
|
|
4580
|
+
try {
|
|
4581
|
+
current = realpathSync(dir);
|
|
4582
|
+
} catch {
|
|
4583
|
+
return undefined;
|
|
4584
|
+
}
|
|
4585
|
+
while (!existsSync(join(current, ".git"))) {
|
|
4586
|
+
const parent = dirname(current);
|
|
4587
|
+
if (parent === current) return undefined;
|
|
4588
|
+
current = parent;
|
|
4589
|
+
}
|
|
4590
|
+
const home = realpathLoose(homedir());
|
|
4591
|
+
if (current === dirname(current) || isInside(home, current)) return undefined;
|
|
4592
|
+
return current;
|
|
4593
|
+
}
|
|
4594
|
+
|
|
4595
|
+
/**
|
|
4596
|
+
* The repo roots a "Yes, and allow git in <repo>/ this session" grant needs
|
|
4597
|
+
* for `command` to stop asking about its cd into another repository (the
|
|
4598
|
+
* CD_GIT_REASON case), one per directory git would run in. undefined when
|
|
4599
|
+
* there is no such run, or one can't be granted: its directory is unknown or
|
|
4600
|
+
* gitRepoRootOf finds no root to grant. Then no grant is offered.
|
|
4601
|
+
*/
|
|
4602
|
+
export function gitGrantRoots(command: string, cwd: string, scratch?: string, gitRepos?: readonly string[]): string[] | undefined {
|
|
4603
|
+
const trimmed = command.trim();
|
|
4604
|
+
if (trimmed === "" || trimmed.length > MAX_COMMAND_LENGTH) return undefined;
|
|
4605
|
+
const segments = tokenize(maskForAnalysis(trimmed, scratch), scratch);
|
|
4606
|
+
if (segments === null) return undefined;
|
|
4607
|
+
const normalized = normalizeGitSegments(segments, cwd, gitRepos);
|
|
4608
|
+
if (!gitInOtherRepoAfterCd(segments, normalized, cwd, gitRepos)) return undefined;
|
|
4609
|
+
const roots: string[] = [];
|
|
4610
|
+
let dir: string | undefined = cwd;
|
|
4611
|
+
for (const segment of normalized) {
|
|
4612
|
+
const [root, ...args] = canonicalize(stripPrefixes(segment.argv, segment.globs, true)?.argv ?? []);
|
|
4613
|
+
if (root === undefined) continue;
|
|
4614
|
+
const name = basename(root);
|
|
4615
|
+
if (DIR_CHANGERS.has(name)) {
|
|
4616
|
+
dir = changedDir(name, args, dir);
|
|
4617
|
+
} else if (name === "git" && (dir === undefined || (dir !== cwd && foreignGitDir(dir, cwd, gitRepos)))) {
|
|
4618
|
+
if (dir === undefined) return undefined;
|
|
4619
|
+
const repo = gitRepoRootOf(dir);
|
|
4620
|
+
if (repo === undefined) return undefined;
|
|
4621
|
+
if (!roots.includes(repo)) roots.push(repo);
|
|
4622
|
+
}
|
|
4623
|
+
}
|
|
4624
|
+
return roots.length > 0 ? roots : undefined;
|
|
4625
|
+
}
|
|
4626
|
+
|
|
3656
4627
|
/**
|
|
3657
4628
|
* True when running git in `dir` would use a different repo than the one at
|
|
3658
4629
|
* `cwd`: `dir` is outside `cwd`, or it or an ancestor strictly below `cwd`
|
|
@@ -3692,7 +4663,7 @@ const GIT_HARMLESS_FLAGS = new Set(["--no-pager", "--no-optional-locks"]);
|
|
|
3692
4663
|
* directory is inside the cwd and not in a nested repo. Never for `-c`,
|
|
3693
4664
|
* `--git-dir`, `--work-tree`, `--exec-path`, `--namespace`, `--config-env`.
|
|
3694
4665
|
*/
|
|
3695
|
-
function gitSubcommandStart(argv: readonly string[], globs: readonly boolean[], dir: string | undefined, cwd: string | undefined): number | undefined {
|
|
4666
|
+
function gitSubcommandStart(argv: readonly string[], globs: readonly boolean[], dir: string | undefined, cwd: string | undefined, gitRepos?: readonly string[]): number | undefined {
|
|
3696
4667
|
if (basename(argv[0] ?? "") !== "git") return undefined;
|
|
3697
4668
|
let i = 1;
|
|
3698
4669
|
let target = dir;
|
|
@@ -3707,7 +4678,7 @@ function gitSubcommandStart(argv: readonly string[], globs: readonly boolean[],
|
|
|
3707
4678
|
} else return undefined;
|
|
3708
4679
|
}
|
|
3709
4680
|
if (i === 1 || i >= argv.length) return undefined; // nothing to normalize, or no subcommand left
|
|
3710
|
-
if (target !== dir && (cwd === undefined ||
|
|
4681
|
+
if (target !== dir && (cwd === undefined || foreignGitDir(target ?? "", cwd, gitRepos))) return undefined;
|
|
3711
4682
|
return i;
|
|
3712
4683
|
}
|
|
3713
4684
|
|
|
@@ -3716,7 +4687,7 @@ function gitSubcommandStart(argv: readonly string[], globs: readonly boolean[],
|
|
|
3716
4687
|
* where gitSubcommandStart allows it, tracking `cd` like gitRunsInOtherRepo,
|
|
3717
4688
|
* so prefixes and coverage treat them as the plain command.
|
|
3718
4689
|
*/
|
|
3719
|
-
function normalizeGitSegments(segments: Segment[], cwd: string | undefined): Segment[] {
|
|
4690
|
+
function normalizeGitSegments(segments: Segment[], cwd: string | undefined, gitRepos?: readonly string[]): Segment[] {
|
|
3720
4691
|
let dir: string | undefined = cwd;
|
|
3721
4692
|
return segments.map((segment) => {
|
|
3722
4693
|
const stripped = stripPrefixes(segment.argv, segment.globs, true);
|
|
@@ -3725,7 +4696,7 @@ function normalizeGitSegments(segments: Segment[], cwd: string | undefined): Seg
|
|
|
3725
4696
|
const globs = stripped.globs.slice(stripped.argv.length - argv.length);
|
|
3726
4697
|
const name = basename(argv[0] ?? "");
|
|
3727
4698
|
if (DIR_CHANGERS.has(name)) dir = changedDir(name, argv.slice(1), dir);
|
|
3728
|
-
const start = gitSubcommandStart(argv, globs, dir, cwd);
|
|
4699
|
+
const start = gitSubcommandStart(argv, globs, dir, cwd, gitRepos);
|
|
3729
4700
|
return start === undefined ? segment : { argv: [argv[0], ...argv.slice(start)], globs: [globs[0], ...globs.slice(start)] };
|
|
3730
4701
|
});
|
|
3731
4702
|
}
|
|
@@ -3738,10 +4709,12 @@ function normalizeGitSegments(segments: Segment[], cwd: string | undefined): Seg
|
|
|
3738
4709
|
* target stays in the project (targetProblem), by exact rules too. `dir`:
|
|
3739
4710
|
* where the segment runs (default the cwd; null = unknown).
|
|
3740
4711
|
*/
|
|
3741
|
-
function isCoveredSegment(segment: Segment, prefixes: readonly (readonly string[])[], cwd: string | undefined, exact: readonly (readonly string[])[] = [], scratch?: string, dir?: string | null): boolean {
|
|
4712
|
+
function isCoveredSegment(segment: Segment, prefixes: readonly (readonly string[])[], cwd: string | undefined, exact: readonly (readonly string[])[] = [], scratch?: string, dir?: string | null, gitRepos?: readonly string[]): boolean {
|
|
3742
4713
|
const stripped = stripPrefixes(segment.argv, segment.globs, true);
|
|
3743
4714
|
if (stripped === null || isRemoval(stripped.argv)) return false;
|
|
3744
|
-
|
|
4715
|
+
// a keyword that starts the unit (`do`, `for`, `then`) is never the command a rule names
|
|
4716
|
+
if (SHELL_RESERVED_WORDS.has(stripped.argv[0] ?? "")) return false;
|
|
4717
|
+
const blocker = segmentBlocker(segment, cwd, scratch, false, undefined, undefined, gitRepos);
|
|
3745
4718
|
if (blocker?.effect === "exec" || (blocker !== undefined && writeProblem(blocker, cwd, dir, scratch) !== undefined)) return false;
|
|
3746
4719
|
// compare canonical forms: `git add` covers `rtk git add` and vice versa
|
|
3747
4720
|
const argv = canonicalize(stripped.argv);
|
|
@@ -3751,7 +4724,8 @@ function isCoveredSegment(segment: Segment, prefixes: readonly (readonly string[
|
|
|
3751
4724
|
})) return true;
|
|
3752
4725
|
return prefixes.some((raw) => {
|
|
3753
4726
|
const p = canonicalize(raw);
|
|
3754
|
-
|
|
4727
|
+
// a prefix headed by a runner (`exec`, `ionice`) would cover whatever it launches: it never covers
|
|
4728
|
+
return !isRunnerName(basename(p[0] ?? "")) && p.length <= argv.length && p.every((t, k) => argv[k] === t);
|
|
3755
4729
|
});
|
|
3756
4730
|
}
|
|
3757
4731
|
|
|
@@ -3763,7 +4737,9 @@ function isCoveredSegment(segment: Segment, prefixes: readonly (readonly string[
|
|
|
3763
4737
|
* Expands a leading `~`, `$HOME` or `${HOME}` (each followed by `/` or the end)
|
|
3764
4738
|
* to the home dir, so `$HOME/.aws/credentials` is judged like `~/.aws/credentials`.
|
|
3765
4739
|
* With `pwd`, a leading `$PWD` or `${PWD}` expands to it the same way (the
|
|
3766
|
-
* command's cwd); `${PWD:-x}`
|
|
4740
|
+
* command's cwd); `${PWD:-x}` is left as it is. `~<this user>` is the home
|
|
4741
|
+
* dir and `~+` the cwd; any other `~name` and `~-` become an absolute path
|
|
4742
|
+
* that is never inside a project, so they are judged as outside.
|
|
3767
4743
|
*/
|
|
3768
4744
|
export function expandHome(path: string, home = homedir(), pwd?: string): string {
|
|
3769
4745
|
const prefix = /^(?:~|\$\{HOME\}|\$HOME)(?=\/|$)/.exec(path);
|
|
@@ -3772,9 +4748,34 @@ export function expandHome(path: string, home = homedir(), pwd?: string): string
|
|
|
3772
4748
|
const dir = /^(?:\$\{PWD\}|\$PWD)(?=\/|$)/.exec(path);
|
|
3773
4749
|
if (dir !== null) return pwd + path.slice(dir[0].length);
|
|
3774
4750
|
}
|
|
4751
|
+
// `~<current user>` is the home dir and `~+` the cwd; any other `~name` or `~-` is another account's
|
|
4752
|
+
// directory, so it becomes an absolute path (never inside a project) and is judged as outside
|
|
4753
|
+
const tilde = /^~([^/]*)(?=\/|$)/.exec(path);
|
|
4754
|
+
if (tilde !== null) {
|
|
4755
|
+
const name = tilde[1] ?? "";
|
|
4756
|
+
if (name === currentUser()) return home + path.slice(tilde[0].length);
|
|
4757
|
+
if (name === "+" && pwd !== undefined) return pwd + path.slice(tilde[0].length);
|
|
4758
|
+
return `/${path}`;
|
|
4759
|
+
}
|
|
3775
4760
|
return path;
|
|
3776
4761
|
}
|
|
3777
4762
|
|
|
4763
|
+
/** The current account's name, or undefined when the system has no account entry for it. */
|
|
4764
|
+
function currentUser(): string | undefined {
|
|
4765
|
+
try {
|
|
4766
|
+
return userInfo().username;
|
|
4767
|
+
} catch {
|
|
4768
|
+
return undefined;
|
|
4769
|
+
}
|
|
4770
|
+
}
|
|
4771
|
+
|
|
4772
|
+
/** True for `~name` or `~-` naming an account other than the current one (the shell looks it up, so it is never the project). */
|
|
4773
|
+
function otherUserTilde(word: string): boolean {
|
|
4774
|
+
const tilde = /^~([^/]*)(?=\/|$)/.exec(word);
|
|
4775
|
+
const name = tilde?.[1] ?? "";
|
|
4776
|
+
return tilde !== null && name !== "" && name !== "+" && name !== currentUser();
|
|
4777
|
+
}
|
|
4778
|
+
|
|
3778
4779
|
function resolvePath(path: string, cwd: string): string {
|
|
3779
4780
|
return resolve(cwd, expandHome(path, homedir(), cwd));
|
|
3780
4781
|
}
|
|
@@ -3968,6 +4969,8 @@ export function isSecretFile(path: string, ctx?: SecretContext): boolean {
|
|
|
3968
4969
|
|
|
3969
4970
|
/** The name and location checks of isSecretFile, on the path as given. */
|
|
3970
4971
|
function isSecretPath(path: string, ctx?: SecretContext): boolean {
|
|
4972
|
+
// a process's environment (`/proc/self/environ`, `/proc/$$/environ`, `/proc/*/environ`) holds credentials
|
|
4973
|
+
if (/^\/proc\/[^/]+\/environ$/.test(path)) return true;
|
|
3971
4974
|
const name = basename(path);
|
|
3972
4975
|
if (/^\.env(\..+)?$/.test(name)) return !/\.(example|sample|template|dist)$/.test(name);
|
|
3973
4976
|
if (name.endsWith(".pub")) return false;
|