@hasna/hooks 0.12.10 → 0.12.14
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/README.md +69 -6
- package/bin/hooks/stop-review.js +1235 -0
- package/bin/hooks-mcp.js +298 -85
- package/bin/index.js +3309 -1086
- package/bin/native-readiness-entry.js +5 -1
- package/bin/native-safety-entry.js +27 -25
- package/bin/native-safety-worker.cjs +27 -25
- package/bin/serve.js +1362 -70
- package/dist/db/remote-storage.d.ts +7 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +1665 -257
- package/dist/lib/codex-safety-check.d.ts +1 -1
- package/dist/lib/hosted-registry.d.ts +70 -0
- package/dist/lib/legacy-registry-artifact.d.ts +23 -0
- package/dist/lib/manifest.d.ts +7 -0
- package/dist/lib/native-safety.d.ts +1 -0
- package/dist/lib/native-target.d.ts +7 -0
- package/dist/lib/opencode-stop-plugin.d.ts +55 -0
- package/dist/lib/registry-artifact.d.ts +36 -0
- package/dist/lib/registry.d.ts +4 -0
- package/dist/lib/stop-review-context.d.ts +12 -0
- package/dist/lib/store.d.ts +4 -0
- package/dist/lib/sumi-stop-plugin.d.ts +129 -0
- package/dist/lib/sync.d.ts +10 -0
- package/dist/lib/transport.d.ts +1 -1
- package/dist/native-readiness.d.ts +1 -1
- package/dist/native-readiness.js +5 -1
- package/dist/openapi.d.ts +160 -16
- package/dist/opencode-stop-plugin.js +384 -0
- package/dist/registry-auth.d.ts +5 -0
- package/dist/registry-http.d.ts +4 -0
- package/dist/sdk/generated.d.ts +32 -12
- package/dist/sdk/index.d.ts +28 -5
- package/dist/sdk/index.js +49 -24
- package/dist/sdk/registry-client.d.ts +1 -1
- package/dist/serve.d.ts +4 -4
- package/dist/storage.js +33 -2
- package/dist/sumi-stop-plugin.js +380 -0
- package/hooks/hook-stop-review/README.md +109 -0
- package/hooks/hook-stop-review/manifest.json +10 -0
- package/hooks/hook-stop-review/package.json +11 -0
- package/hooks/hook-stop-review/src/hook.ts +59 -0
- package/hooks/hook-stop-review/src/index.ts +3 -0
- package/hooks/hook-stop-review/src/jev.ts +121 -0
- package/hooks/hook-stop-review/src/native.ts +246 -0
- package/hooks/hook-stop-review/src/policy.ts +145 -0
- package/hooks/hook-stop-review/src/runtime.ts +309 -0
- package/hooks/hook-stop-review/src/types.ts +121 -0
- package/hooks/hook-trash-guard/src/hook.ts +96 -0
- package/hooks/hook-workspace-repos-guard/src/hook.ts +116 -3
- package/hooks/local-executors.ts +841 -0
- package/package.json +22 -4
- package/scripts/build-bundled-hooks.ts +40 -0
- package/scripts/validate-bundled-hooks.ts +78 -0
- package/scripts/validate-opencode-stop-plugin.ts +42 -0
- package/scripts/validate-package.ts +9 -0
- package/scripts/validate-sumi-stop-plugin.ts +47 -0
|
@@ -0,0 +1,841 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local execution hidden in a command's own options or in an interpreter's
|
|
3
|
+
* inline program, read the same way by workspace-repos-guard and trash-guard.
|
|
4
|
+
*
|
|
5
|
+
* The delete and workspace-repos guards model what a shell command deletes or
|
|
6
|
+
* writes by reading the command word and its operands. They do NOT, on their
|
|
7
|
+
* own, see a command that runs a SECOND command locally without naming it in
|
|
8
|
+
* command position:
|
|
9
|
+
*
|
|
10
|
+
* awk 'BEGIN{system("rm -rf src")}' awk runs rm through system()
|
|
11
|
+
* perl -e 'system("rm -rf src2")' perl runs rm
|
|
12
|
+
* python3 -c '...os.remove...' python runs the remove
|
|
13
|
+
* ssh -o ProxyCommand='rm -rf src' h x ssh runs ProxyCommand locally, through
|
|
14
|
+
* /bin/sh, while it connects
|
|
15
|
+
* rsync -e 'rm -rf src' … rsync runs its -e remote-shell locally
|
|
16
|
+
* git -c core.sshCommand='rm -rf src' fetch git runs the sshCommand locally
|
|
17
|
+
* sed 's/x/rm -rf src/e' f sed executes the substituted text
|
|
18
|
+
*
|
|
19
|
+
* git -c core.pager='rm -rf src' log git runs a configured command (also
|
|
20
|
+
* --config-env, GIT_CONFIG_* and the
|
|
21
|
+
* command-valued environment)
|
|
22
|
+
* bash -c "$CMD", eval "$X" a shell program the guard cannot read
|
|
23
|
+
*
|
|
24
|
+
* xargs perl -e 'system("rm -rf src")' a launcher (xargs, find -exec/-execdir/
|
|
25
|
+
* find . -exec awk '…system()…' {} + -ok/-okdir) runs an executor; see
|
|
26
|
+
* launchedCommands
|
|
27
|
+
*
|
|
28
|
+
* This module recognises those LOCAL EXECUTORS and returns the program text(s)
|
|
29
|
+
* they run locally, with the grammar each is written in, so a guard can decide
|
|
30
|
+
* whether that program is provably read-only. It reads only DECODED words (the
|
|
31
|
+
* shell's quote removal already applied); a word the shell can still expand is
|
|
32
|
+
* marked opaque by the caller, and a value we would have needed from an opaque
|
|
33
|
+
* word makes the finding `unresolved` — fail closed.
|
|
34
|
+
*
|
|
35
|
+
* It judges nothing about where the command runs: the caller scopes the
|
|
36
|
+
* refusal (workspace-repos-guard to its protected roots, trash-guard to the
|
|
37
|
+
* same handoff roots). Pure: no I/O, no imports beyond the shared delete-verb
|
|
38
|
+
* reader.
|
|
39
|
+
*/
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A delete verb named as its own word in already-decoded text. Kept here, not
|
|
43
|
+
* imported from the trash guard, so this shared module has no import cycle with
|
|
44
|
+
* either guard (both import it). It matches the trash guard's reader, applied
|
|
45
|
+
* to decoded text: a path prefix (`/bin/rm`) and surrounding punctuation count.
|
|
46
|
+
*/
|
|
47
|
+
export function mentionsDeleteVerb(text: string): boolean {
|
|
48
|
+
return /(^|[^A-Za-z0-9_.-])(rm|rmdir|unlink|shred|trash)(?![A-Za-z0-9_.-])/.test(text);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The grammar an embedded program is written in, which decides how it reads. */
|
|
52
|
+
export type ProgramKind = "c-interp" | "awk" | "shell";
|
|
53
|
+
|
|
54
|
+
export interface EmbeddedProgram {
|
|
55
|
+
text: string;
|
|
56
|
+
kind: ProgramKind;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ExecutorFinding {
|
|
60
|
+
/** The programs/option values this command runs locally. */
|
|
61
|
+
programs: EmbeddedProgram[];
|
|
62
|
+
/**
|
|
63
|
+
* True when the command is a recognised local executor but a program or
|
|
64
|
+
* option value could not be read (an opaque word, a `-f`/`-F` file we do not
|
|
65
|
+
* read). The caller fails closed: under a protected root it refuses.
|
|
66
|
+
*/
|
|
67
|
+
unresolved: boolean;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const baseName = (word: string): string => word.split("/").pop() ?? "";
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Interpreters whose inline program is given on the command line: the
|
|
74
|
+
* single-letter flags that carry it (which may be clustered, `perl -ne 'c'`),
|
|
75
|
+
* and the long options (`node --eval c`). A letter not here is an ordinary
|
|
76
|
+
* flag, skipped.
|
|
77
|
+
*/
|
|
78
|
+
const INTERP_PROGRAM_FLAGS: Record<string, { letters: Set<string>; long: Set<string> }> = {
|
|
79
|
+
perl: { letters: new Set(["e", "E"]), long: new Set() },
|
|
80
|
+
python: { letters: new Set(["c"]), long: new Set() },
|
|
81
|
+
python2: { letters: new Set(["c"]), long: new Set() },
|
|
82
|
+
python3: { letters: new Set(["c"]), long: new Set() },
|
|
83
|
+
ruby: { letters: new Set(["e"]), long: new Set() },
|
|
84
|
+
node: { letters: new Set(["e", "p"]), long: new Set(["--eval", "--print"]) },
|
|
85
|
+
nodejs: { letters: new Set(["e", "p"]), long: new Set(["--eval", "--print"]) },
|
|
86
|
+
bun: { letters: new Set(["e"]), long: new Set(["--eval"]) },
|
|
87
|
+
deno: { letters: new Set(["e"]), long: new Set(["--eval"]) },
|
|
88
|
+
php: { letters: new Set(["r"]), long: new Set() },
|
|
89
|
+
lua: { letters: new Set(["e"]), long: new Set() },
|
|
90
|
+
luajit: { letters: new Set(["e"]), long: new Set() },
|
|
91
|
+
Rscript: { letters: new Set(["e"]), long: new Set() },
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
/** `python3.11`, `perl5.38`, `ruby3.2`, `lua5.4` and the like are the same interpreter. */
|
|
95
|
+
const VERSIONED_INTERP = /^(python|perl|ruby|lua|php|node)[0-9.]+$/;
|
|
96
|
+
|
|
97
|
+
/** awk implementations: the program is the first bare operand, or every `-e` value. */
|
|
98
|
+
const AWK_NAMES = new Set(["awk", "gawk", "mawk", "nawk", "busybox-awk"]);
|
|
99
|
+
|
|
100
|
+
/** ssh-family commands whose `-o` options and config can run a local command. */
|
|
101
|
+
const SSH_NAMES = new Set(["ssh", "scp", "sftp"]);
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* ssh-family short options that take a value (ssh(1)/scp(1)/sftp(1)); the rest
|
|
105
|
+
* are flags. `-o` and `-F` are handled before this: `-o` carries the option we
|
|
106
|
+
* read, and `-F` names a config file we do not read. `-S` (scp/sftp) names the
|
|
107
|
+
* program used for the connection and runs locally, so its value is read as a
|
|
108
|
+
* command.
|
|
109
|
+
*/
|
|
110
|
+
const SSH_VALUE_OPTS = new Set("bcDEeFIiJLlmOoPpQRSWw".split(""));
|
|
111
|
+
|
|
112
|
+
/** ssh `-o` keys whose value is a command ssh runs locally (lower-cased). */
|
|
113
|
+
const SSH_LOCAL_EXEC_OPTS = new Set(["proxycommand", "localcommand", "knownhostscommand"]);
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* C-family interpreter danger tokens: a construct that runs a command, acquires
|
|
117
|
+
* a capability module, opens or mutates a file, or names a delete verb. A
|
|
118
|
+
* program with none of these is provably read-only (`print(1)`, `print if /x/`).
|
|
119
|
+
* `>`/`|` are NOT dangerous here — the shell already took the real redirections
|
|
120
|
+
* and pipes, so inside the program they are comparison/bit operators.
|
|
121
|
+
*/
|
|
122
|
+
const C_INTERP_DANGER = /(?:`|\$\()|\b(?:system|exec|execve|execvp|popen|spawn|posix_spawn|fork|subprocess|Popen|check_output|check_call|shell_exec|passthru|proc_open|pcntl_exec|qx|open|fopen|sysopen|unlink|remove|delete|rmtree|rmdir|mkdir|rename|truncate|ftruncate|chmod|chown|symlink|writeFile|createWriteStream|appendFile|child_process|FileUtils|shutil|Kernel|require|import|load|eval|os|sys|io|fs|File|IO|Dir|Path|pathlib)/;
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* awk danger: `system()` or a pipe/redirect (`| "cmd"`, `print > "file"`), a
|
|
126
|
+
* `getline` from a command or file, `close`/`fflush` on a stream, or a delete
|
|
127
|
+
* verb. `>`/`|` are awk redirection/pipe operators, so a program using them is
|
|
128
|
+
* not provably read-only (a bare comparison `$1 > 5` reads only, but is refused
|
|
129
|
+
* here under a protected root — fail closed, in class).
|
|
130
|
+
*/
|
|
131
|
+
const AWK_DANGER = /[|>]|\b(?:system|getline|close|fflush|print\w*\s*>>?)/;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Whether an embedded program is provably read-only for its grammar. A `shell`
|
|
135
|
+
* value is judged by the caller with its own command classifier (it is a shell
|
|
136
|
+
* command); only `c-interp` and `awk` are judged here.
|
|
137
|
+
*/
|
|
138
|
+
export function embeddedProgramIsReadOnly(program: EmbeddedProgram): boolean {
|
|
139
|
+
if (mentionsDeleteVerb(program.text)) return false;
|
|
140
|
+
if (program.kind === "awk") return !AWK_DANGER.test(program.text);
|
|
141
|
+
if (program.kind === "c-interp") return !C_INTERP_DANGER.test(program.text);
|
|
142
|
+
// shell: never decided here.
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Inline program(s) of a C-family interpreter, or null when it runs no inline program. */
|
|
147
|
+
function interpPrograms(name: string, words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
148
|
+
const spec = INTERP_PROGRAM_FLAGS[name] ?? (VERSIONED_INTERP.test(name) ? INTERP_PROGRAM_FLAGS[name.replace(/[0-9.]+$/, "")] : undefined);
|
|
149
|
+
if (!spec) return null;
|
|
150
|
+
const programs: EmbeddedProgram[] = [];
|
|
151
|
+
let unresolved = false;
|
|
152
|
+
const takeNext = (at: number): number => {
|
|
153
|
+
if (at + 1 >= words.length || opaque(at + 1)) { unresolved = true; return at; }
|
|
154
|
+
programs.push({ text: words[at + 1], kind: "c-interp" });
|
|
155
|
+
return at + 1;
|
|
156
|
+
};
|
|
157
|
+
for (let at = index + 1; at < words.length; at++) {
|
|
158
|
+
const word = words[at];
|
|
159
|
+
if (word === "--") break;
|
|
160
|
+
if (!word.startsWith("-") || word === "-") break;
|
|
161
|
+
if (word.startsWith("--")) {
|
|
162
|
+
// `--eval=CODE` / `--eval CODE` / `--print …`.
|
|
163
|
+
const eq = word.indexOf("=");
|
|
164
|
+
const longName = eq < 0 ? word : word.slice(0, eq);
|
|
165
|
+
if (spec.long.has(longName)) {
|
|
166
|
+
if (eq >= 0) programs.push({ text: word.slice(eq + 1), kind: "c-interp" });
|
|
167
|
+
else at = takeNext(at);
|
|
168
|
+
}
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
// A short-option cluster (`-ne`, `-Bc`, `-necode`). The program flag takes
|
|
172
|
+
// the rest of the word when it is not the last letter, else the next word.
|
|
173
|
+
const cluster = word.slice(1);
|
|
174
|
+
for (let i = 0; i < cluster.length; i++) {
|
|
175
|
+
if (!spec.letters.has(cluster[i])) continue;
|
|
176
|
+
if (i < cluster.length - 1) programs.push({ text: cluster.slice(i + 1), kind: "c-interp" });
|
|
177
|
+
else at = takeNext(at);
|
|
178
|
+
break;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (programs.length === 0 && !unresolved) return null;
|
|
182
|
+
return { programs, unresolved };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** The awk program: every `-e` value, or the first bare operand; `-f` file is unresolved. */
|
|
186
|
+
function awkProgram(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding {
|
|
187
|
+
const programs: EmbeddedProgram[] = [];
|
|
188
|
+
let unresolved = false;
|
|
189
|
+
let at = index + 1;
|
|
190
|
+
for (; at < words.length; at++) {
|
|
191
|
+
const word = words[at];
|
|
192
|
+
if (word === "--") { at++; break; }
|
|
193
|
+
if (!word.startsWith("-") || word === "-") break;
|
|
194
|
+
if (word === "-e" || word.startsWith("-e")) {
|
|
195
|
+
const attached = word === "-e" ? null : word.slice(2);
|
|
196
|
+
if (attached !== null) programs.push({ text: attached, kind: "awk" });
|
|
197
|
+
else if (at + 1 < words.length && !opaque(at + 1)) programs.push({ text: words[++at], kind: "awk" });
|
|
198
|
+
else unresolved = true;
|
|
199
|
+
} else if (word === "-f" || word.startsWith("-f")) {
|
|
200
|
+
// A program read from a file we do not read: fail closed.
|
|
201
|
+
unresolved = true;
|
|
202
|
+
if (word === "-f") at++;
|
|
203
|
+
} else if (word === "-v" || word.startsWith("-v")) {
|
|
204
|
+
if (word === "-v") at++; // `-v var=val` assignment
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (programs.length === 0 && !unresolved) {
|
|
208
|
+
// No -e/-f: the first bare operand is the program.
|
|
209
|
+
if (at < words.length) {
|
|
210
|
+
if (opaque(at)) unresolved = true;
|
|
211
|
+
else programs.push({ text: words[at], kind: "awk" });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { programs, unresolved };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Walk one `-o Key=Value`/`-oKey=Value`/`-o Key Value` of ssh and return [key, value] or null. */
|
|
218
|
+
function sshOptionValue(words: string[], at: number, opaque: (i: number) => boolean): { value: string | null; next: number } {
|
|
219
|
+
const word = words[at];
|
|
220
|
+
// `-oKey=Value` attached, or `-o` with its value in the next word.
|
|
221
|
+
let raw: string;
|
|
222
|
+
let next = at;
|
|
223
|
+
if (word === "-o") {
|
|
224
|
+
if (at + 1 >= words.length) return { value: null, next: at };
|
|
225
|
+
if (opaque(at + 1)) return { value: null, next: at + 1 };
|
|
226
|
+
raw = words[at + 1];
|
|
227
|
+
next = at + 1;
|
|
228
|
+
} else {
|
|
229
|
+
raw = word.slice(2);
|
|
230
|
+
}
|
|
231
|
+
return { value: raw, next };
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** ssh/scp/sftp local-exec option values, and `-F` config (unresolved). */
|
|
235
|
+
function sshPrograms(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding {
|
|
236
|
+
const programs: EmbeddedProgram[] = [];
|
|
237
|
+
let unresolved = false;
|
|
238
|
+
for (let at = index + 1; at < words.length; at++) {
|
|
239
|
+
const word = words[at];
|
|
240
|
+
if (word === "--") break;
|
|
241
|
+
if (!word.startsWith("-") || word === "-") break;
|
|
242
|
+
if (word.startsWith("--")) continue; // ssh takes no long options
|
|
243
|
+
// `-o…` option.
|
|
244
|
+
if (word === "-o" || word.startsWith("-o")) {
|
|
245
|
+
const { value, next } = sshOptionValue(words, at, opaque);
|
|
246
|
+
at = next;
|
|
247
|
+
if (value === null) { unresolved = true; continue; }
|
|
248
|
+
const eq = value.indexOf("=");
|
|
249
|
+
const sep = eq >= 0 ? eq : value.search(/\s/);
|
|
250
|
+
const key = (sep >= 0 ? value.slice(0, sep) : value).trim().toLowerCase();
|
|
251
|
+
const optionValue = sep >= 0 ? value.slice(sep + 1).trim() : "";
|
|
252
|
+
if (SSH_LOCAL_EXEC_OPTS.has(key)) programs.push({ text: optionValue, kind: "shell" });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
// `-F configfile`: the config can set ProxyCommand, and we do not read it.
|
|
256
|
+
if (word === "-F" || word.startsWith("-F")) {
|
|
257
|
+
unresolved = true;
|
|
258
|
+
if (word === "-F") at++;
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
// scp/sftp `-S program`: the connection program, run locally.
|
|
262
|
+
if (word === "-S" || word.startsWith("-S")) {
|
|
263
|
+
const value = word === "-S" ? (at + 1 < words.length && !opaque(at + 1) ? words[++at] : null) : word.slice(2);
|
|
264
|
+
if (value === null) unresolved = true;
|
|
265
|
+
else programs.push({ text: value, kind: "shell" });
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
// A short-option cluster: consume a value for the last value-taking option.
|
|
269
|
+
const letters = word.slice(1);
|
|
270
|
+
for (let i = 0; i < letters.length; i++) {
|
|
271
|
+
if (!SSH_VALUE_OPTS.has(letters[i])) continue;
|
|
272
|
+
// o/F/S handled above as whole words; here a cluster ends in one of them.
|
|
273
|
+
if (i < letters.length - 1) break; // value attached to the cluster
|
|
274
|
+
if (letters[i] === "o" || letters[i] === "F" || letters[i] === "S") {
|
|
275
|
+
// The value is the next word; re-read it as the respective option.
|
|
276
|
+
if (at + 1 < words.length) {
|
|
277
|
+
const vWord = words[at + 1];
|
|
278
|
+
if (letters[i] === "o") {
|
|
279
|
+
if (!opaque(at + 1)) {
|
|
280
|
+
const eq = vWord.indexOf("=");
|
|
281
|
+
const sep = eq >= 0 ? eq : vWord.search(/\s/);
|
|
282
|
+
const key = (sep >= 0 ? vWord.slice(0, sep) : vWord).trim().toLowerCase();
|
|
283
|
+
if (SSH_LOCAL_EXEC_OPTS.has(key)) programs.push({ text: sep >= 0 ? vWord.slice(sep + 1).trim() : "", kind: "shell" });
|
|
284
|
+
} else unresolved = true;
|
|
285
|
+
} else if (letters[i] === "F") unresolved = true;
|
|
286
|
+
else if (!opaque(at + 1)) programs.push({ text: vWord, kind: "shell" });
|
|
287
|
+
at++;
|
|
288
|
+
}
|
|
289
|
+
} else if (at + 1 < words.length) {
|
|
290
|
+
at++; // ordinary value-option consumes the next word
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return { programs, unresolved };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** rsync `-e`/`--rsh` remote-shell command, run locally. */
|
|
298
|
+
function rsyncPrograms(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
299
|
+
const programs: EmbeddedProgram[] = [];
|
|
300
|
+
let unresolved = false;
|
|
301
|
+
let found = false;
|
|
302
|
+
for (let at = index + 1; at < words.length; at++) {
|
|
303
|
+
const word = words[at];
|
|
304
|
+
if (word === "--") break;
|
|
305
|
+
if (word === "-e" || word === "--rsh") {
|
|
306
|
+
found = true;
|
|
307
|
+
if (at + 1 < words.length && !opaque(at + 1)) programs.push({ text: words[++at], kind: "shell" });
|
|
308
|
+
else unresolved = true;
|
|
309
|
+
} else if (word.startsWith("--rsh=")) {
|
|
310
|
+
found = true;
|
|
311
|
+
programs.push({ text: word.slice("--rsh=".length), kind: "shell" });
|
|
312
|
+
} else if (/^-[A-Za-z]*e/.test(word) && word.length > 2 && !word.startsWith("--")) {
|
|
313
|
+
// `-ae'ssh …'` short cluster ending in -e with its value attached.
|
|
314
|
+
found = true;
|
|
315
|
+
programs.push({ text: word.slice(word.indexOf("e") + 1), kind: "shell" });
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return found ? { programs, unresolved } : null;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* How one git configuration key's value is read, derived from git 2.43.0's own
|
|
323
|
+
* documentation: git-config(1), git(1) (ENVIRONMENT), gitattributes(5)
|
|
324
|
+
* (`filter.<driver>.process`), git-archive(1) (`tar.<format>.command`),
|
|
325
|
+
* git-interpret-trailers(1) (`trailer.<alias>.cmd`/`.command`) and
|
|
326
|
+
* git-submodule(1) (`submodule.<name>.update = !command`). git-send-email(1) is
|
|
327
|
+
* not installed on the station the list was derived on, so the `sendemail.*Cmd`
|
|
328
|
+
* and `sendemail.smtpServer` keys come from their names in git-config(1).
|
|
329
|
+
* - "command": the value is a command git runs (through the shell or as a
|
|
330
|
+
* program); it is judged as the shell command it is.
|
|
331
|
+
* - "unresolved": the value makes git run something the guard cannot read (an
|
|
332
|
+
* alias of git arguments, an included config file, a hooks directory, the ext
|
|
333
|
+
* transport); fail closed.
|
|
334
|
+
* - "harmless": anything else (`safe.directory`, `color.ui`, `user.name`, …).
|
|
335
|
+
* Keys are matched lower-cased; a subsection is case-sensitive in git, which
|
|
336
|
+
* only widens the match here.
|
|
337
|
+
*/
|
|
338
|
+
type GitKeyReading = { kind: "harmless" } | { kind: "command"; text: string } | { kind: "unresolved" };
|
|
339
|
+
const GIT_BOOLEAN = /^(?:true|false|yes|no|on|off|1|0|)$/i;
|
|
340
|
+
const GIT_COMMAND_KEYS: RegExp[] = [
|
|
341
|
+
/^core\.(?:pager|editor|sshcommand|askpass|alternaterefscommand)$/, /^sequence\.editor$/, /^diff\.external$/,
|
|
342
|
+
/^interactive\.difffilter$/, /^imap\.tunnel$/, /^gc\.recentobjectshook$/, /^gpg\.program$/, /^gpg\.ssh\.defaultkeycommand$/,
|
|
343
|
+
/^uploadpack\.packobjectshook$/, /^instaweb\.(?:browser|httpd)$/, /^credential\.(?:.+\.)?helper$/,
|
|
344
|
+
/^diff\..+\.(?:command|textconv)$/, /^(?:difftool|mergetool|man|browser)\..+\.(?:cmd|path)$/, /^guitool\..+\.cmd$/,
|
|
345
|
+
/^merge\..+\.driver$/, /^gpg\..+\.program$/, /^remote\..+\.(?:uploadpack|receivepack)$/, /^filter\..+\.(?:clean|smudge|process)$/,
|
|
346
|
+
/^tar\..+\.command$/, /^trailer\..+\.(?:cmd|command)$/, /^sendemail\.(?:.+\.)?(?:tocmd|cccmd|headercmd|sendmailcmd)$/,
|
|
347
|
+
];
|
|
348
|
+
export function readGitConfig(rawKey: string, value: string | undefined): GitKeyReading {
|
|
349
|
+
const key = rawKey.toLowerCase();
|
|
350
|
+
const command = (text: string | undefined): GitKeyReading => (text === undefined ? { kind: "unresolved" } : { kind: "command", text });
|
|
351
|
+
if (/^alias\./.test(key)) {
|
|
352
|
+
// `!…` is a shell command; anything else is git arguments the guard cannot read.
|
|
353
|
+
return value !== undefined && value.trimStart().startsWith("!") ? command(value.trimStart().slice(1)) : { kind: "unresolved" };
|
|
354
|
+
}
|
|
355
|
+
if (/^pager\./.test(key) || key === "core.fsmonitor") return value !== undefined && GIT_BOOLEAN.test(value) ? { kind: "harmless" } : command(value);
|
|
356
|
+
if (key === "core.gitproxy") return value !== undefined && /^none(?:\s+for\s+\S+)?$/.test(value) ? { kind: "harmless" } : command(value?.replace(/\s+for\s+\S+$/, ""));
|
|
357
|
+
if (/^submodule\..+\.update$/.test(key)) return value !== undefined && value.trimStart().startsWith("!") ? command(value.trimStart().slice(1)) : value === undefined ? { kind: "unresolved" } : { kind: "harmless" };
|
|
358
|
+
if (/^sendemail\.(?:.+\.)?smtpserver$/.test(key)) return value !== undefined && !value.startsWith("/") ? { kind: "harmless" } : command(value);
|
|
359
|
+
if (/^credential\.(?:.+\.)?helper$/.test(key)) {
|
|
360
|
+
if (value === "") return { kind: "harmless" };
|
|
361
|
+
if (value === undefined) return { kind: "unresolved" };
|
|
362
|
+
const v = value.trimStart();
|
|
363
|
+
// `!cmd` is a shell command; an absolute path runs that program; a bare
|
|
364
|
+
// name runs `git credential-<name>`.
|
|
365
|
+
return command(v.startsWith("!") ? v.slice(1) : v.startsWith("/") ? v : `git credential-${v}`);
|
|
366
|
+
}
|
|
367
|
+
if (GIT_COMMAND_KEYS.some((pattern) => pattern.test(key))) return command(value);
|
|
368
|
+
if (key === "core.hookspath") return value === "/dev/null" ? { kind: "harmless" } : { kind: "unresolved" };
|
|
369
|
+
if (key === "include.path" || /^includeif\..+\.path$/.test(key)) return { kind: "unresolved" };
|
|
370
|
+
// The ext transport runs a command named in a URL; enabling it is unreadable.
|
|
371
|
+
if (key === "protocol.allow") return value !== undefined && /^(?:never|user)$/i.test(value) ? { kind: "harmless" } : { kind: "unresolved" };
|
|
372
|
+
if (key === "protocol.ext.allow") return value !== undefined && /^never$/i.test(value) ? { kind: "harmless" } : { kind: "unresolved" };
|
|
373
|
+
return { kind: "harmless" };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** Whether some value of `key` makes git run something; a key that never does is harmless whatever its value. */
|
|
377
|
+
function gitKeyMatters(key: string): boolean {
|
|
378
|
+
return /[$\x60]/.test(key) || ["", "x", "/x", "!x"].some((value) => readGitConfig(key, value).kind !== "harmless");
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Environment variables whose value is a command git (or ssh) runs. */
|
|
382
|
+
const GIT_COMMAND_ENV = new Set(["GIT_PAGER", "GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_EXTERNAL_DIFF", "GIT_SSH", "GIT_SSH_COMMAND",
|
|
383
|
+
"GIT_ASKPASS", "SSH_ASKPASS", "GIT_PROXY_COMMAND", "PAGER", "EDITOR", "VISUAL"]);
|
|
384
|
+
/** Environment variables that make git run something the guard cannot read. `/dev/null` reads as empty config. */
|
|
385
|
+
const GIT_UNREADABLE_ENV = new Set(["GIT_EXEC_PATH", "GIT_TEMPLATE_DIR", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM"]);
|
|
386
|
+
|
|
387
|
+
/** The entries of GIT_CONFIG_PARAMETERS (`'key'='value' 'key2=value2'`, sq-quoted), or null when it does not parse. */
|
|
388
|
+
function gitConfigParameters(text: string): Array<[string, string | undefined]> | null {
|
|
389
|
+
const sq = /'((?:[^']|'\\'')*)'/y;
|
|
390
|
+
const unq = (s: string) => s.replace(/'\\''/g, "'");
|
|
391
|
+
const out: Array<[string, string | undefined]> = [];
|
|
392
|
+
let at = 0;
|
|
393
|
+
while (at < text.length) {
|
|
394
|
+
if (/\s/.test(text[at])) { at++; continue; }
|
|
395
|
+
sq.lastIndex = at;
|
|
396
|
+
const first = sq.exec(text);
|
|
397
|
+
if (!first) return null;
|
|
398
|
+
at = sq.lastIndex;
|
|
399
|
+
if (text[at] === "=") {
|
|
400
|
+
sq.lastIndex = at + 1;
|
|
401
|
+
const second = sq.exec(text);
|
|
402
|
+
if (!second) return null;
|
|
403
|
+
at = sq.lastIndex;
|
|
404
|
+
out.push([unq(first[1]), unq(second[1])]);
|
|
405
|
+
} else {
|
|
406
|
+
const entry = unq(first[1]), eq = entry.indexOf("=");
|
|
407
|
+
out.push(eq < 0 ? [entry, undefined] : [entry.slice(0, eq), entry.slice(eq + 1)]);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return out;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* git configuration given on the command line or in the environment that runs
|
|
415
|
+
* a command: `-c key=value` (and `-ckey=value`), `--config-env=key=ENV`, and
|
|
416
|
+
* prefixes on the git word (`GIT_CONFIG_PARAMETERS`, `GIT_CONFIG_COUNT` with
|
|
417
|
+
* `GIT_CONFIG_KEY_<n>`/`GIT_CONFIG_VALUE_<n>`, the command-valued variables in
|
|
418
|
+
* GIT_COMMAND_ENV, and GIT_UNREADABLE_ENV), plus `--exec-path=<dir>`. Each
|
|
419
|
+
* command value is returned as a shell program; an unreadable one makes the
|
|
420
|
+
* finding unresolved. Null when nothing of this kind is set. Whatever the
|
|
421
|
+
* subcommand: a value that cannot run for it is still refused (fail closed).
|
|
422
|
+
* Configuration persisted in a file by an earlier command is not seen here.
|
|
423
|
+
*/
|
|
424
|
+
function gitPrograms(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
425
|
+
const programs: EmbeddedProgram[] = [];
|
|
426
|
+
let unresolved = false;
|
|
427
|
+
const judge = (key: string, value: string | undefined, keyKnown = true) => {
|
|
428
|
+
if (!keyKnown || /[$\x60]/.test(key)) { unresolved = true; return; }
|
|
429
|
+
const reading = readGitConfig(key, value);
|
|
430
|
+
if (reading.kind === "unresolved") unresolved = true;
|
|
431
|
+
else if (reading.kind === "command") programs.push({ text: reading.text, kind: "shell" });
|
|
432
|
+
};
|
|
433
|
+
const fromSetting = (setting: string, valueOpaque: boolean) => {
|
|
434
|
+
const eq = setting.indexOf("=");
|
|
435
|
+
const key = eq < 0 ? setting : setting.slice(0, eq);
|
|
436
|
+
// `-c key` with no `=` is the boolean true.
|
|
437
|
+
const value = eq < 0 ? "true" : setting.slice(eq + 1);
|
|
438
|
+
if (!valueOpaque) return judge(key, value);
|
|
439
|
+
// An expanded value is unknown: a key that can run something is unresolved.
|
|
440
|
+
if (gitKeyMatters(key)) unresolved = true;
|
|
441
|
+
};
|
|
442
|
+
const VALUE_OPTIONS = new Set(["-C", "--git-dir", "--work-tree", "--namespace", "--attr-source", "--list-cmds", "--super-prefix"]);
|
|
443
|
+
for (let at = index + 1; at < words.length; at++) {
|
|
444
|
+
const word = words[at];
|
|
445
|
+
if (!word.startsWith("-") || word === "-") break; // the subcommand
|
|
446
|
+
if (word === "--") break;
|
|
447
|
+
if (word === "-c") {
|
|
448
|
+
if (at + 1 >= words.length) break;
|
|
449
|
+
fromSetting(words[at + 1], opaque(at + 1));
|
|
450
|
+
at++;
|
|
451
|
+
} else if (word.startsWith("-c") && !word.startsWith("--")) {
|
|
452
|
+
fromSetting(word.slice(2), opaque(at));
|
|
453
|
+
} else if (word === "--config-env" || word.startsWith("--config-env=")) {
|
|
454
|
+
const spec = word === "--config-env" ? words[++at] ?? "" : word.slice("--config-env=".length);
|
|
455
|
+
// The value comes from an environment variable the guard cannot read.
|
|
456
|
+
const eq = spec.indexOf("=");
|
|
457
|
+
const key = eq < 0 ? spec : spec.slice(0, eq);
|
|
458
|
+
if (opaque(at) || gitKeyMatters(key)) unresolved = true;
|
|
459
|
+
} else if (word.startsWith("--exec-path=")) {
|
|
460
|
+
unresolved = true;
|
|
461
|
+
} else if (VALUE_OPTIONS.has(word)) {
|
|
462
|
+
at++;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
// Environment prefixes on the git word (`X=… git …`, `env X=… git …`).
|
|
466
|
+
const count = new Map<string, { key?: string; value?: string; opaque?: boolean }>();
|
|
467
|
+
for (let at = 0; at < index; at++) {
|
|
468
|
+
const m = words[at].match(/^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s);
|
|
469
|
+
if (!m) continue;
|
|
470
|
+
const [, name, value] = m;
|
|
471
|
+
const valueOpaque = opaque(at);
|
|
472
|
+
if (GIT_COMMAND_ENV.has(name)) {
|
|
473
|
+
if (valueOpaque) unresolved = true; else programs.push({ text: value, kind: "shell" });
|
|
474
|
+
} else if (GIT_UNREADABLE_ENV.has(name)) {
|
|
475
|
+
if (valueOpaque || value !== "/dev/null" || name === "GIT_EXEC_PATH" || name === "GIT_TEMPLATE_DIR") unresolved = true;
|
|
476
|
+
} else if (name === "GIT_ALLOW_PROTOCOL") {
|
|
477
|
+
if (valueOpaque || value.split(":").includes("ext")) unresolved = true;
|
|
478
|
+
} else if (name === "GIT_CONFIG_PARAMETERS") {
|
|
479
|
+
const entries = valueOpaque ? null : gitConfigParameters(value);
|
|
480
|
+
if (entries === null) unresolved = true;
|
|
481
|
+
else for (const [key, v] of entries) judge(key, v ?? "true");
|
|
482
|
+
} else if (/^GIT_CONFIG_(?:KEY|VALUE)_\d+$/.test(name)) {
|
|
483
|
+
const n = name.replace(/^GIT_CONFIG_(?:KEY|VALUE)_/, "");
|
|
484
|
+
const slot = count.get(n) ?? {};
|
|
485
|
+
if (name.startsWith("GIT_CONFIG_KEY_")) slot.key = value; else slot.value = value;
|
|
486
|
+
if (valueOpaque) slot.opaque = true;
|
|
487
|
+
count.set(n, slot);
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
for (const slot of count.values()) {
|
|
491
|
+
if (slot.key === undefined) continue;
|
|
492
|
+
if (slot.opaque) fromSetting(`${slot.key}=`, true);
|
|
493
|
+
else judge(slot.key, slot.value);
|
|
494
|
+
}
|
|
495
|
+
if (programs.length === 0 && !unresolved) return null;
|
|
496
|
+
return { programs, unresolved };
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* The text a shell word stands for when it is a plain literal, or null when the
|
|
501
|
+
* shell can change it: a `$` expansion or substitution (unquoted or in double
|
|
502
|
+
* quotes), a backtick, an unquoted glob, brace or leading tilde, `$"…"`, or a
|
|
503
|
+
* `$'…'` holding an escape this reader does not decode.
|
|
504
|
+
*/
|
|
505
|
+
export function literalWord(raw: string): string | null {
|
|
506
|
+
const ANSI: Record<string, string> = { n: "\n", t: "\t", r: "\r", a: "\x07", b: "\b", e: "\x1b", E: "\x1b", f: "\f", v: "\v", "\\": "\\", "'": "'", '"': '"', "?": "?" };
|
|
507
|
+
if (/^~/.test(raw)) return null;
|
|
508
|
+
let out = "";
|
|
509
|
+
for (let i = 0; i < raw.length; i++) {
|
|
510
|
+
const ch = raw[i];
|
|
511
|
+
if (ch === "'") {
|
|
512
|
+
const end = raw.indexOf("'", i + 1);
|
|
513
|
+
if (end < 0) return null;
|
|
514
|
+
out += raw.slice(i + 1, end);
|
|
515
|
+
i = end;
|
|
516
|
+
} else if (ch === "$" && raw[i + 1] === "'") {
|
|
517
|
+
let j = i + 2;
|
|
518
|
+
for (; j < raw.length && raw[j] !== "'"; j++) {
|
|
519
|
+
if (raw[j] !== "\\") { out += raw[j]; continue; }
|
|
520
|
+
const c = raw[j + 1];
|
|
521
|
+
let m: RegExpMatchArray | null;
|
|
522
|
+
if (c !== undefined && Object.hasOwn(ANSI, c)) { out += ANSI[c]; j++; }
|
|
523
|
+
else if ((m = raw.slice(j + 1).match(/^[0-7]{1,3}/))) { out += String.fromCharCode(parseInt(m[0], 8) & 0xff); j += m[0].length; }
|
|
524
|
+
else if ((m = raw.slice(j + 1).match(/^x([0-9A-Fa-f]{1,2})/))) { out += String.fromCharCode(parseInt(m[1], 16)); j += m[0].length; }
|
|
525
|
+
else return null;
|
|
526
|
+
}
|
|
527
|
+
if (j >= raw.length) return null;
|
|
528
|
+
i = j;
|
|
529
|
+
} else if (ch === "$" || ch === "\x60") {
|
|
530
|
+
return null;
|
|
531
|
+
} else if (ch === '"') {
|
|
532
|
+
let j = i + 1;
|
|
533
|
+
for (; j < raw.length && raw[j] !== '"'; j++) {
|
|
534
|
+
const c = raw[j];
|
|
535
|
+
if (c === "$" || c === "\x60") return null;
|
|
536
|
+
if (c === "\\" && j + 1 < raw.length && /[$\x60"\\\n]/.test(raw[j + 1])) { out += raw[++j]; continue; }
|
|
537
|
+
out += c;
|
|
538
|
+
}
|
|
539
|
+
if (j >= raw.length) return null;
|
|
540
|
+
i = j;
|
|
541
|
+
} else if (ch === "\\") {
|
|
542
|
+
if (i + 1 >= raw.length) return null;
|
|
543
|
+
out += raw[++i];
|
|
544
|
+
} else if ("*?[{}".includes(ch)) {
|
|
545
|
+
return null;
|
|
546
|
+
} else {
|
|
547
|
+
out += ch;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return out;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* Whether a shell program's own text only holds literal words when that shell
|
|
555
|
+
* runs it: no `$` (expansion, parameter, `$'…'`) or backtick outside single
|
|
556
|
+
* quotes, no here-document (`<<`, whose body may expand), and balanced quotes.
|
|
557
|
+
*/
|
|
558
|
+
export function programIsLiteral(program: string): boolean {
|
|
559
|
+
let quote: "'" | '"' | null = null;
|
|
560
|
+
for (let i = 0; i < program.length; i++) {
|
|
561
|
+
const ch = program[i];
|
|
562
|
+
if (quote === "'") { if (ch === "'") quote = null; continue; }
|
|
563
|
+
if (ch === "\\") { i++; continue; }
|
|
564
|
+
if (ch === "$" || ch === "\x60") return false;
|
|
565
|
+
if (quote === '"') { if (ch === '"') quote = null; continue; }
|
|
566
|
+
if (ch === "'" || ch === '"') { quote = ch; continue; }
|
|
567
|
+
if (ch === "<" && program[i + 1] === "<" && program[i + 2] !== "<") return false;
|
|
568
|
+
}
|
|
569
|
+
return quote === null;
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** POSIX-family shells that run a `-c` program. */
|
|
573
|
+
const C_SHELLS = new Set(["sh", "bash", "zsh", "dash", "ksh", "ash", "mksh"]);
|
|
574
|
+
/** Long shell options that take a value. */
|
|
575
|
+
const SHELL_LONG_VALUE = new Set(["--rcfile", "--init-file"]);
|
|
576
|
+
|
|
577
|
+
export interface ShellProgram {
|
|
578
|
+
/** The program text when it is a plain literal the guard can read. */
|
|
579
|
+
program: string | null;
|
|
580
|
+
literal: boolean;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* The program of `sh|bash|zsh|dash|ksh|ash|mksh -c PROGRAM` (`-c` alone or in a
|
|
585
|
+
* cluster, `-lc`, `-ec`) or `eval WORD…`, from the RAW words of one simple
|
|
586
|
+
* command (redirections removed) with the command word at `index`. A literal
|
|
587
|
+
* program is returned for the caller to classify as it does today; a program
|
|
588
|
+
* that is not a plain literal (an expansion, a substitution, an undecodable
|
|
589
|
+
* `$'…'`, an unquoted expansion where `-c` could hide, or an eval of several
|
|
590
|
+
* words) is `literal: false` and the caller fails closed. Null when the command
|
|
591
|
+
* runs no inline program (a script file, stdin).
|
|
592
|
+
*/
|
|
593
|
+
export function shellProgram(raw: string[], index: number): ShellProgram | null {
|
|
594
|
+
if (index < 0 || index >= raw.length) return null;
|
|
595
|
+
const nameText = literalWord(raw[index]);
|
|
596
|
+
const name = baseName(nameText ?? "");
|
|
597
|
+
if (name === "eval") {
|
|
598
|
+
let at = index + 1;
|
|
599
|
+
if (literalWord(raw[at] ?? "") === "--") at++;
|
|
600
|
+
const rest = raw.slice(at);
|
|
601
|
+
if (rest.length === 0) return null;
|
|
602
|
+
if (rest.length > 1) return { program: null, literal: false };
|
|
603
|
+
const program = literalWord(rest[0]);
|
|
604
|
+
return program !== null && programIsLiteral(program) ? { program, literal: true } : { program, literal: false };
|
|
605
|
+
}
|
|
606
|
+
if (!C_SHELLS.has(name)) return null;
|
|
607
|
+
let cMode = false;
|
|
608
|
+
let at = index + 1;
|
|
609
|
+
for (; at < raw.length; at++) {
|
|
610
|
+
const text = literalWord(raw[at]);
|
|
611
|
+
if (text === null) {
|
|
612
|
+
// A quoted expansion here is the script operand (not inline); an
|
|
613
|
+
// unquoted one may split into options, `-c` among them.
|
|
614
|
+
if (cMode) break;
|
|
615
|
+
return /^"[^"]*"$/.test(raw[at]) ? null : { program: null, literal: false };
|
|
616
|
+
}
|
|
617
|
+
if (text === "--") { at++; break; }
|
|
618
|
+
if (!/^[-+]./.test(text)) break;
|
|
619
|
+
if (text.startsWith("--")) { if (SHELL_LONG_VALUE.has(text)) at++; continue; }
|
|
620
|
+
const letters = text.slice(1);
|
|
621
|
+
if (text[0] === "-" && letters.includes("c")) cMode = true;
|
|
622
|
+
if (/[oO]/.test(letters)) at++;
|
|
623
|
+
}
|
|
624
|
+
if (!cMode || at >= raw.length) return null;
|
|
625
|
+
const program = literalWord(raw[at]);
|
|
626
|
+
return program !== null && programIsLiteral(program) ? { program, literal: true } : { program, literal: false };
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* sed scripts (the `e`/`s///e` execute forms and the `w`/`W`/`s///w` file
|
|
631
|
+
* writes), without `-i`. `-i` is already a write the guards model; it is left
|
|
632
|
+
* to them. Returns the program with kind "shell" when it executes (fail closed
|
|
633
|
+
* through `unresolved` for the `e` command, whose command comes from input),
|
|
634
|
+
* and marks a write with no execute by an empty program list and `unresolved`
|
|
635
|
+
* false — the caller then treats sed as a writer, not an executor.
|
|
636
|
+
*/
|
|
637
|
+
function sedPrograms(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
638
|
+
// Collect the script text: -e values, the first bare operand, or -f (unread).
|
|
639
|
+
const scripts: string[] = [];
|
|
640
|
+
let unresolvedScript = false;
|
|
641
|
+
let hadInPlace = false;
|
|
642
|
+
let at = index + 1;
|
|
643
|
+
let sawScript = false;
|
|
644
|
+
for (; at < words.length; at++) {
|
|
645
|
+
const word = words[at];
|
|
646
|
+
if (word === "--") { at++; break; }
|
|
647
|
+
if (word === "-i" || word.startsWith("-i") || word.startsWith("--in-place")) { hadInPlace = true; continue; }
|
|
648
|
+
if (word === "-e" || word === "--expression") {
|
|
649
|
+
sawScript = true;
|
|
650
|
+
if (at + 1 < words.length && !opaque(at + 1)) scripts.push(words[++at]);
|
|
651
|
+
else unresolvedScript = true;
|
|
652
|
+
} else if (word.startsWith("-e")) { sawScript = true; scripts.push(word.slice(2)); }
|
|
653
|
+
else if (word.startsWith("--expression=")) { sawScript = true; scripts.push(word.slice("--expression=".length)); }
|
|
654
|
+
else if (word === "-f" || word === "--file") { sawScript = true; unresolvedScript = true; if (word === "-f") at++; }
|
|
655
|
+
else if (word.startsWith("-f") || word.startsWith("--file=")) { sawScript = true; unresolvedScript = true; }
|
|
656
|
+
else if (!word.startsWith("-") || word === "-") break;
|
|
657
|
+
}
|
|
658
|
+
if (hadInPlace) return null; // -i is the guards' existing write handling
|
|
659
|
+
if (!sawScript) {
|
|
660
|
+
if (at < words.length) {
|
|
661
|
+
if (opaque(at)) unresolvedScript = true;
|
|
662
|
+
else scripts.push(words[at]);
|
|
663
|
+
} else return null;
|
|
664
|
+
}
|
|
665
|
+
const text = scripts.join("\n");
|
|
666
|
+
const executes = unresolvedScript || sedScriptExecutes(text);
|
|
667
|
+
const writes = sedScriptWrites(text);
|
|
668
|
+
if (!executes && !writes) return null;
|
|
669
|
+
// An executing sed runs a command we usually cannot see (the pattern space),
|
|
670
|
+
// so it is unresolved unless the visible script already names a delete verb.
|
|
671
|
+
if (executes) return { programs: scripts.map((s) => ({ text: s, kind: "shell" as const })), unresolved: true };
|
|
672
|
+
// A writing sed (`w`/`W`/`s///w`) names its file in the script; the caller
|
|
673
|
+
// reads it as a write target. No local execution.
|
|
674
|
+
return { programs: [], unresolved: false };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** An optional sed address (line number, `$`, `/regex/`, ranges and `!`) before a command. */
|
|
678
|
+
const SED_ADDRESS = String.raw`[\s0-9$,!]*(?:\/(?:\\.|[^\/\n])*\/[\s0-9$,!]*)?`;
|
|
679
|
+
|
|
680
|
+
/** Whether a sed script executes: an `e` command, or an `s///` with the `e` flag. */
|
|
681
|
+
export function sedScriptExecutes(script: string): boolean {
|
|
682
|
+
// The `e` command: `e` optionally followed by a shell command, at the start
|
|
683
|
+
// of a command (line start, `;`, `{`) after any address. Not the `e` flag of
|
|
684
|
+
// `s`, handled next.
|
|
685
|
+
if (new RegExp(`(?:^|[;{\\n])${SED_ADDRESS}e(?:\\s|$|[^A-Za-z])`).test(script)) return true;
|
|
686
|
+
// `s<delim>…<delim>…<delim>` with a flag run containing `e`.
|
|
687
|
+
return sedSubstFlags(script).some((flags) => flags.includes("e"));
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** Whether a sed script writes a file: a `w`/`W` command, or an `s///` with the `w` flag. */
|
|
691
|
+
export function sedScriptWrites(script: string): boolean {
|
|
692
|
+
if (new RegExp(`(?:^|[;{\\n])${SED_ADDRESS}[wW]\\s+\\S`).test(script)) return true;
|
|
693
|
+
return sedSubstFlags(script).some((flags) => flags.includes("w"));
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/** The flag runs of every `s<delim>pat<delim>rep<delim>FLAGS` in a sed script (best effort). */
|
|
697
|
+
function sedSubstFlags(script: string): string[] {
|
|
698
|
+
const flags: string[] = [];
|
|
699
|
+
for (let i = 0; i < script.length; i++) {
|
|
700
|
+
if (script[i] !== "s") continue;
|
|
701
|
+
if (i > 0 && /[A-Za-z0-9_]/.test(script[i - 1])) continue;
|
|
702
|
+
const delim = script[i + 1];
|
|
703
|
+
if (!delim || /[\sA-Za-z0-9\\]/.test(delim)) continue;
|
|
704
|
+
let seen = 0;
|
|
705
|
+
let j = i + 2;
|
|
706
|
+
for (; j < script.length && seen < 2; j++) {
|
|
707
|
+
if (script[j] === "\\") { j++; continue; }
|
|
708
|
+
if (script[j] === delim) seen++;
|
|
709
|
+
}
|
|
710
|
+
if (seen < 2) continue;
|
|
711
|
+
const run = script.slice(j).match(/^[a-zA-Z0-9]*/);
|
|
712
|
+
flags.push(run ? run[0] : "");
|
|
713
|
+
i = j;
|
|
714
|
+
}
|
|
715
|
+
return flags;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** A command a launcher runs: its words are `words[start..end)` of the launcher's segment. */
|
|
719
|
+
export interface LaunchedCommand {
|
|
720
|
+
start: number;
|
|
721
|
+
end: number;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** find primaries that run a command (findutils find(1)); -exec/-execdir also end at `{} +`. */
|
|
725
|
+
const FIND_RUN_PRIMARIES = new Set(["-exec", "-execdir", "-ok", "-okdir"]);
|
|
726
|
+
const FIND_BATCH_PRIMARIES = new Set(["-exec", "-execdir"]);
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* xargs options, from GNU findutils 4.9.0 (`xargs --help`: `-E`, `-I`, `-L`,
|
|
730
|
+
* `-n`, `-P`, `-s`, `-a`, `-d` take a value; `-e`, `-i`, `-l` take one only
|
|
731
|
+
* attached) and BSD xargs(1) (`-J`, `-R`, `-S` take a value). Option parsing
|
|
732
|
+
* stops at the first operand, which is the command xargs runs.
|
|
733
|
+
*/
|
|
734
|
+
const XARGS_SHORT_FLAGS = new Set("0oprtx");
|
|
735
|
+
const XARGS_SHORT_VALUE = new Set("adEILnPsJRS");
|
|
736
|
+
const XARGS_SHORT_OPTIONAL = new Set("eil");
|
|
737
|
+
const XARGS_LONG: Record<string, "flag" | "value" | "optional"> = {
|
|
738
|
+
"--null": "flag", "--open-tty": "flag", "--interactive": "flag", "--no-run-if-empty": "flag", "--verbose": "flag",
|
|
739
|
+
"--exit": "flag", "--show-limits": "flag", "--help": "flag", "--version": "flag",
|
|
740
|
+
"--arg-file": "value", "--delimiter": "value", "--max-args": "value", "--max-procs": "value", "--max-chars": "value",
|
|
741
|
+
"--process-slot-var": "value", "--max-lines": "value",
|
|
742
|
+
"--eof": "optional", "--replace": "optional",
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
/** getopt_long's reading of a long option: an exact name, or a prefix of exactly one. */
|
|
746
|
+
function xargsLong(flag: string): "flag" | "value" | "optional" | null {
|
|
747
|
+
if (Object.hasOwn(XARGS_LONG, flag)) return XARGS_LONG[flag];
|
|
748
|
+
const matches = Object.keys(XARGS_LONG).filter((name) => name.startsWith(flag));
|
|
749
|
+
return matches.length === 1 ? XARGS_LONG[matches[0]] : null;
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* The start of the command xargs runs, reading its options from `at`. An
|
|
754
|
+
* option neither GNU nor BSD xargs knows makes the real xargs refuse to run;
|
|
755
|
+
* it is still read both as a flag and as taking the next word, so a
|
|
756
|
+
* misaligned reading cannot hide the command.
|
|
757
|
+
*/
|
|
758
|
+
function xargsCommandStarts(words: string[], at: number, skip: (at: number) => boolean, unknowns = 0): number[] {
|
|
759
|
+
while (at < words.length) {
|
|
760
|
+
if (skip(at)) { at++; continue; }
|
|
761
|
+
const word = words[at];
|
|
762
|
+
if (word === "--") { at++; break; }
|
|
763
|
+
if (!word.startsWith("-") || word === "-") break;
|
|
764
|
+
if (word.startsWith("--")) {
|
|
765
|
+
const eq = word.indexOf("=");
|
|
766
|
+
const kind = xargsLong(eq < 0 ? word : word.slice(0, eq));
|
|
767
|
+
if (kind === null) {
|
|
768
|
+
if (unknowns >= 4) return [];
|
|
769
|
+
return [...xargsCommandStarts(words, at + 1, skip, unknowns + 1), ...xargsCommandStarts(words, at + 2, skip, unknowns + 1)];
|
|
770
|
+
}
|
|
771
|
+
at += kind === "value" && eq < 0 ? 2 : 1;
|
|
772
|
+
continue;
|
|
773
|
+
}
|
|
774
|
+
let takesNext = false;
|
|
775
|
+
let unknown = false;
|
|
776
|
+
for (let i = 1; i < word.length; i++) {
|
|
777
|
+
const ch = word[i];
|
|
778
|
+
if (XARGS_SHORT_FLAGS.has(ch)) continue;
|
|
779
|
+
if (XARGS_SHORT_OPTIONAL.has(ch)) break;
|
|
780
|
+
if (XARGS_SHORT_VALUE.has(ch)) { takesNext = i === word.length - 1; break; }
|
|
781
|
+
unknown = true;
|
|
782
|
+
break;
|
|
783
|
+
}
|
|
784
|
+
if (unknown) {
|
|
785
|
+
if (unknowns >= 4) return [];
|
|
786
|
+
return [...xargsCommandStarts(words, at + 1, skip, unknowns + 1), ...xargsCommandStarts(words, at + 2, skip, unknowns + 1)];
|
|
787
|
+
}
|
|
788
|
+
at += takesNext ? 2 : 1;
|
|
789
|
+
}
|
|
790
|
+
while (at < words.length && skip(at)) at++;
|
|
791
|
+
return at < words.length ? [at] : [];
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* The commands a launcher whose command word is at `index` runs locally:
|
|
796
|
+
* find's `-exec`, `-execdir`, `-ok` and `-okdir` (the words after the primary,
|
|
797
|
+
* up to its `;`, or `{} +` for -exec/-execdir; `{}` is an operand), and the
|
|
798
|
+
* command xargs runs (the first word after xargs's own options, to the end).
|
|
799
|
+
* A guard reads each launched command as a command of its own, so a local
|
|
800
|
+
* executor hidden behind find or xargs is judged like one in command position.
|
|
801
|
+
* `skip(at)` marks words that are not arguments (redirections).
|
|
802
|
+
*/
|
|
803
|
+
export function launchedCommands(words: string[], index: number, skip: (at: number) => boolean = () => false): LaunchedCommand[] {
|
|
804
|
+
if (index < 0 || index >= words.length) return [];
|
|
805
|
+
const name = baseName(words[index]);
|
|
806
|
+
if (name === "xargs") {
|
|
807
|
+
return [...new Set(xargsCommandStarts(words, index + 1, skip))].map((start) => ({ start, end: words.length }));
|
|
808
|
+
}
|
|
809
|
+
if (name !== "find") return [];
|
|
810
|
+
const launched: LaunchedCommand[] = [];
|
|
811
|
+
for (let at = index + 1; at < words.length; at++) {
|
|
812
|
+
if (skip(at) || !FIND_RUN_PRIMARIES.has(words[at])) continue;
|
|
813
|
+
const start = at + 1;
|
|
814
|
+
let end = start;
|
|
815
|
+
for (; end < words.length; end++) {
|
|
816
|
+
if (skip(end)) continue;
|
|
817
|
+
if (words[end] === ";") break;
|
|
818
|
+
if (words[end] === "+" && end > start && words[end - 1] === "{}" && FIND_BATCH_PRIMARIES.has(words[at])) break;
|
|
819
|
+
}
|
|
820
|
+
if (start < end) launched.push({ start, end });
|
|
821
|
+
at = end;
|
|
822
|
+
}
|
|
823
|
+
return launched;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* If the simple command whose DECODED words are `words`, with its command word
|
|
828
|
+
* at `index` and `opaque(at)` true where the shell can still expand word `at`,
|
|
829
|
+
* runs a program or option value locally, return that finding. Otherwise null.
|
|
830
|
+
*/
|
|
831
|
+
export function localExecutor(words: string[], index: number, opaque: (at: number) => boolean): ExecutorFinding | null {
|
|
832
|
+
if (index < 0 || index >= words.length) return null;
|
|
833
|
+
const name = baseName(words[index]);
|
|
834
|
+
if (Object.hasOwn(INTERP_PROGRAM_FLAGS, name) || VERSIONED_INTERP.test(name)) return interpPrograms(name, words, index, opaque);
|
|
835
|
+
if (AWK_NAMES.has(name)) return awkProgram(words, index, opaque);
|
|
836
|
+
if (SSH_NAMES.has(name)) return sshPrograms(words, index, opaque);
|
|
837
|
+
if (name === "rsync") return rsyncPrograms(words, index, opaque);
|
|
838
|
+
if (name === "git") return gitPrograms(words, index, opaque);
|
|
839
|
+
if (name === "sed") return sedPrograms(words, index, opaque);
|
|
840
|
+
return null;
|
|
841
|
+
}
|