@agentic-kit/permissions 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +278 -2
  3. package/bash/analyze.d.ts +133 -0
  4. package/bash/analyze.js +442 -0
  5. package/bash/args.d.ts +45 -0
  6. package/bash/args.js +145 -0
  7. package/bash/braces.d.ts +6 -0
  8. package/bash/braces.js +72 -0
  9. package/bash/commands.d.ts +14 -0
  10. package/bash/commands.js +361 -0
  11. package/bash/file-commands.d.ts +22 -0
  12. package/bash/file-commands.js +278 -0
  13. package/bash/flows.d.ts +67 -0
  14. package/bash/flows.js +208 -0
  15. package/bash/git.d.ts +7 -0
  16. package/bash/git.js +163 -0
  17. package/bash/network.d.ts +24 -0
  18. package/bash/network.js +295 -0
  19. package/bash/quoting.d.ts +16 -0
  20. package/bash/quoting.js +164 -0
  21. package/bash/system.d.ts +16 -0
  22. package/bash/system.js +122 -0
  23. package/bash/tokenize.d.ts +67 -0
  24. package/bash/tokenize.js +440 -0
  25. package/bash/words.d.ts +9 -0
  26. package/bash/words.js +30 -0
  27. package/bash/wrappers.d.ts +32 -0
  28. package/bash/wrappers.js +237 -0
  29. package/classify.d.ts +22 -0
  30. package/classify.js +259 -0
  31. package/engine.d.ts +109 -0
  32. package/engine.js +144 -0
  33. package/env.d.ts +13 -0
  34. package/env.js +37 -0
  35. package/esm/bash/analyze.d.ts +133 -0
  36. package/esm/bash/analyze.js +405 -0
  37. package/esm/bash/args.d.ts +45 -0
  38. package/esm/bash/args.js +135 -0
  39. package/esm/bash/braces.d.ts +6 -0
  40. package/esm/bash/braces.js +69 -0
  41. package/esm/bash/commands.d.ts +14 -0
  42. package/esm/bash/commands.js +324 -0
  43. package/esm/bash/file-commands.d.ts +22 -0
  44. package/esm/bash/file-commands.js +233 -0
  45. package/esm/bash/flows.d.ts +67 -0
  46. package/esm/bash/flows.js +203 -0
  47. package/esm/bash/git.d.ts +7 -0
  48. package/esm/bash/git.js +127 -0
  49. package/esm/bash/network.d.ts +24 -0
  50. package/esm/bash/network.js +282 -0
  51. package/esm/bash/quoting.d.ts +16 -0
  52. package/esm/bash/quoting.js +153 -0
  53. package/esm/bash/system.d.ts +16 -0
  54. package/esm/bash/system.js +82 -0
  55. package/esm/bash/tokenize.d.ts +67 -0
  56. package/esm/bash/tokenize.js +437 -0
  57. package/esm/bash/words.d.ts +9 -0
  58. package/esm/bash/words.js +24 -0
  59. package/esm/bash/wrappers.d.ts +32 -0
  60. package/esm/bash/wrappers.js +200 -0
  61. package/esm/classify.d.ts +22 -0
  62. package/esm/classify.js +223 -0
  63. package/esm/engine.d.ts +109 -0
  64. package/esm/engine.js +108 -0
  65. package/esm/env.d.ts +13 -0
  66. package/esm/env.js +34 -0
  67. package/esm/findings.d.ts +7 -0
  68. package/esm/findings.js +9 -0
  69. package/esm/glob.d.ts +15 -0
  70. package/esm/glob.js +69 -0
  71. package/esm/grants.d.ts +36 -0
  72. package/esm/grants.js +99 -0
  73. package/esm/index.d.ts +19 -0
  74. package/esm/index.js +18 -0
  75. package/esm/node-fs.d.ts +6 -0
  76. package/esm/node-fs.js +34 -0
  77. package/esm/paths.d.ts +43 -0
  78. package/esm/paths.js +121 -0
  79. package/esm/policy.d.ts +21 -0
  80. package/esm/policy.js +85 -0
  81. package/esm/prompt.d.ts +14 -0
  82. package/esm/prompt.js +79 -0
  83. package/esm/roots.d.ts +75 -0
  84. package/esm/roots.js +148 -0
  85. package/esm/secret-files.d.ts +16 -0
  86. package/esm/secret-files.js +84 -0
  87. package/esm/secrets/collect.d.ts +19 -0
  88. package/esm/secrets/collect.js +60 -0
  89. package/esm/secrets/index.d.ts +5 -0
  90. package/esm/secrets/index.js +5 -0
  91. package/esm/secrets/parse.d.ts +19 -0
  92. package/esm/secrets/parse.js +140 -0
  93. package/esm/secrets/redact-result.d.ts +8 -0
  94. package/esm/secrets/redact-result.js +67 -0
  95. package/esm/secrets/rules.d.ts +34 -0
  96. package/esm/secrets/rules.js +101 -0
  97. package/esm/secrets/vault.d.ts +48 -0
  98. package/esm/secrets/vault.js +158 -0
  99. package/esm/signals.d.ts +14 -0
  100. package/esm/signals.js +26 -0
  101. package/esm/tool-input.d.ts +13 -0
  102. package/esm/tool-input.js +40 -0
  103. package/esm/types.d.ts +146 -0
  104. package/esm/types.js +20 -0
  105. package/findings.d.ts +7 -0
  106. package/findings.js +13 -0
  107. package/glob.d.ts +15 -0
  108. package/glob.js +73 -0
  109. package/grants.d.ts +36 -0
  110. package/grants.js +110 -0
  111. package/index.d.ts +19 -0
  112. package/index.js +52 -0
  113. package/node-fs.d.ts +6 -0
  114. package/node-fs.js +37 -0
  115. package/package.json +38 -4
  116. package/paths.d.ts +43 -0
  117. package/paths.js +164 -0
  118. package/policy.d.ts +21 -0
  119. package/policy.js +88 -0
  120. package/prompt.d.ts +14 -0
  121. package/prompt.js +83 -0
  122. package/roots.d.ts +75 -0
  123. package/roots.js +192 -0
  124. package/secret-files.d.ts +16 -0
  125. package/secret-files.js +124 -0
  126. package/secrets/collect.d.ts +19 -0
  127. package/secrets/collect.js +96 -0
  128. package/secrets/index.d.ts +5 -0
  129. package/secrets/index.js +21 -0
  130. package/secrets/parse.d.ts +19 -0
  131. package/secrets/parse.js +145 -0
  132. package/secrets/redact-result.d.ts +8 -0
  133. package/secrets/redact-result.js +70 -0
  134. package/secrets/rules.d.ts +34 -0
  135. package/secrets/rules.js +107 -0
  136. package/secrets/vault.d.ts +48 -0
  137. package/secrets/vault.js +163 -0
  138. package/signals.d.ts +14 -0
  139. package/signals.js +29 -0
  140. package/tool-input.d.ts +13 -0
  141. package/tool-input.js +46 -0
  142. package/types.d.ts +146 -0
  143. package/types.js +24 -0
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Static risk analysis of a bash command. It finds the paths a command touches
3
+ * and the signals that make it risky, and it fails toward asking: anything it
4
+ * cannot see through (substitution, `eval`, `sh -c`, a variable it cannot
5
+ * resolve, a lexer error) raises `shell-dynamic`.
6
+ *
7
+ * This is best effort and is not a security boundary. A program the agent
8
+ * wrote can still do anything the user can; only an OS sandbox stops that.
9
+ */
10
+ import * as path from 'node:path';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { expandBraces } from './braces';
13
+ import { runCommand, TESTS } from './commands';
14
+ import { FlowTracker } from './flows';
15
+ import { tokenize } from './tokenize';
16
+ import { isPathLike, isUrl } from './words';
17
+ import { stripWrapper, xargsOperands } from './wrappers';
18
+ export function normalizeCommand(command) {
19
+ return command.trim().replace(/\s+/g, ' ');
20
+ }
21
+ const MAX_NESTING = 4;
22
+ const MAX_COMMAND_LENGTH = 64 * 1024;
23
+ /** Device paths that are not files. */
24
+ const HARMLESS_DEVICES = new Set([
25
+ '/dev/null',
26
+ '/dev/stdin',
27
+ '/dev/stdout',
28
+ '/dev/stderr',
29
+ '/dev/tty',
30
+ '/dev/zero',
31
+ '/dev/random',
32
+ '/dev/urandom'
33
+ ]);
34
+ /** Running `/usr/bin/x` is the same as running `x`. */
35
+ const SYSTEM_BIN_DIRS = new Set(['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/opt/homebrew/bin']);
36
+ /**
37
+ * Assignments that change which program runs, what it loads (the shell's and
38
+ * every interpreter's preload and library paths), or where a path resolves.
39
+ */
40
+ const DANGEROUS_VARS = new RegExp(`^(${[
41
+ 'PATH|IFS|ENV|BASH_ENV|PROMPT_COMMAND|SHELLOPTS|BASHOPTS|PS4|CDPATH|GLOBIGNORE',
42
+ 'GIT_SSH|GIT_SSH_COMMAND|GIT_EXEC_PATH|GIT_EDITOR|GIT_PAGER|EDITOR|VISUAL|PAGER',
43
+ 'LD_PRELOAD|LD_LIBRARY_PATH|LD_AUDIT|DYLD_\\w*',
44
+ 'NODE_OPTIONS|NODE_PATH|PYTHONPATH|PYTHONSTARTUP|PYTHONHOME|PYTHONINSPECT|PERL5OPT|PERL5LIB|PERLLIB|RUBYOPT|RUBYLIB|JAVA_TOOL_OPTIONS|_JAVA_OPTIONS'
45
+ ].join('|')})$`);
46
+ const RESERVED = new Set(['!', '{', '}', 'if', 'then', 'else', 'elif', 'fi', 'do', 'done', 'while', 'until', 'esac', 'coproc']);
47
+ /** The oh-my-pi critical list (`tools/bash.ts`), matched on the raw command. */
48
+ const CRITICAL_PATTERNS = [
49
+ /\brm\s+(?:-\S+\s+)*(?:-[a-z]*[rRfF][a-z]*|--recursive|--force)\s+(?:-\S+\s+)*\//i,
50
+ /\brm\s+(?:-\S+\s+)*--no-preserve-root\b/i,
51
+ /\bsudo\s+rm\b/i,
52
+ /\bchmod\s+-R\s+[0-7]+\s+\//i,
53
+ /\bchmod\s+-R\s+[ugoa+\-=rwxXst,]+\s+\//,
54
+ /\bchown\s+-R\s+\S+\s+\//i,
55
+ /:\(\)\s*\{\s*:\s*\|\s*:/i,
56
+ />\s*\/dev\/sd[a-z]/i,
57
+ />\s*\/dev\/disk\d/i,
58
+ /\bmkfs(\.|\b)/i,
59
+ /\bdd\s+if=.+of=\/dev\//i,
60
+ /\bshred\s+\/dev\//i,
61
+ /\bcryptsetup\b/i,
62
+ />\s*\/etc\/(?:passwd|shadow|sudoers)\b/i,
63
+ /\btee\s+(?:-a\s+)?\/etc\/(?:passwd|shadow|sudoers)\b/i,
64
+ /\b(?:curl|wget|fetch)\b[^|]*\|\s*(?:sudo\s+)?(?:bash|sh|zsh|fish)\b/i,
65
+ /(?:^|[\s;&|(])(?:bash|sh|zsh|source|\.)\s+<\(\s*(?:curl|wget|fetch)\b/i,
66
+ /\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b|\beval\s+`\s*(?:curl|wget|fetch)\b/i,
67
+ /\bkill\s+-9\s+1\b/,
68
+ /(?:^|[\s;&|(])(?:shutdown|poweroff|reboot|halt)(?:\s|$|[;|&])/i,
69
+ /(?:^|[\s;&|(])init\s+0\b/i,
70
+ /\bnc\b[^|;]*\s-[a-zA-Z]*[ec][a-zA-Z]*\s/i
71
+ ];
72
+ const PLACEHOLDER_RE = /«secret:[^»]*»/;
73
+ /** Shell options that make `*` match dotfiles. */
74
+ const DOTGLOB_RE = /dotglob|glob_?dots|GLOBIGNORE/i;
75
+ /** `$NAME` and `${NAME…}` in a heredoc body. */
76
+ const BODY_VAR_RE = /\$\{?[#!]?([A-Za-z_][A-Za-z0-9_]*)/g;
77
+ function isHarmlessDevice(abs) {
78
+ return HARMLESS_DEVICES.has(abs) || abs.startsWith('/dev/fd/');
79
+ }
80
+ class Analyzer {
81
+ ctx;
82
+ findings;
83
+ paths = [];
84
+ checks = [];
85
+ tracker = new FlowTracker(this);
86
+ /** Variables expanded but never set in the command: they come from the environment. */
87
+ envRefs = new Set();
88
+ /** git remotes the command adds or points elsewhere (`git remote add`, `set-url`, `-c remote.x.url=`). */
89
+ gitRemotes = new Set();
90
+ /** What the command being analyzed reads on stdin. */
91
+ stdin = { sources: [], words: [], listedUnder: null };
92
+ /** Shell variables set earlier in the command. `null` = set to something unknown. */
93
+ vars = new Map();
94
+ /** The shell's working dir at this point. `null` after a `cd` we cannot follow. */
95
+ base;
96
+ /** How many shell strings (`sh -c`, `eval`, …) deep the analysis is. */
97
+ depth = 0;
98
+ constructor(ctx, findings) {
99
+ this.ctx = ctx;
100
+ this.findings = findings;
101
+ this.base = path.resolve(ctx.cwd);
102
+ }
103
+ flag(signal, reason) {
104
+ this.findings.flag(signal, reason);
105
+ }
106
+ dynamic(reason) {
107
+ this.flag('shell-dynamic', reason);
108
+ }
109
+ /** A path the analyzer cannot place: it asks in every mode, so no mode lets it reach a denied root. */
110
+ unresolvable(reason) {
111
+ this.flag('unresolvable-path', reason);
112
+ }
113
+ /** `cd dir` looks `dir` up in `CDPATH` when the command set it and `dir` is not `/…`, `./…` or `../…`. */
114
+ searchesCdPath(dir) {
115
+ return this.vars.has('CDPATH') && !dir.startsWith('/') && !/^\.\.?(\/|$)/.test(dir);
116
+ }
117
+ analyzeString(command) {
118
+ if (this.depth > MAX_NESTING) {
119
+ this.dynamic('the command nests shell strings too deeply to check');
120
+ return;
121
+ }
122
+ if (command.length > MAX_COMMAND_LENGTH) {
123
+ this.dynamic('the command is too long to check');
124
+ return;
125
+ }
126
+ const lexed = tokenize(command);
127
+ if (lexed.error)
128
+ this.dynamic(`the command could not be parsed (${lexed.error})`);
129
+ for (const note of lexed.dynamic)
130
+ this.dynamic(`it uses ${note}`);
131
+ for (const cmd of lexed.commands)
132
+ this.analyzeCommand(cmd);
133
+ }
134
+ /** A shell string run by `sh -c`, `eval`, `watch`, …: analyze it in its own scope. */
135
+ nested(text, why) {
136
+ this.dynamic(why);
137
+ const savedBase = this.base;
138
+ const savedVars = new Map(this.vars);
139
+ const savedStdin = this.stdin;
140
+ this.depth++;
141
+ this.analyzeString(text);
142
+ this.depth--;
143
+ this.base = savedBase;
144
+ this.vars = savedVars;
145
+ this.stdin = savedStdin;
146
+ }
147
+ /**
148
+ * `NAME=value`, inline or through `export`, `declare` or `readonly`.
149
+ * `value` is `null` when it is not known statically.
150
+ */
151
+ assign(name, value) {
152
+ if (DANGEROUS_VARS.test(name))
153
+ this.dynamic(`it sets ${name}, which changes what runs`);
154
+ this.vars.set(name, value);
155
+ }
156
+ /** A variable the command expands: an env ref unless the command set it. */
157
+ noteRef(name) {
158
+ if (!this.vars.has(name))
159
+ this.envRefs.add(name);
160
+ }
161
+ lookup(name) {
162
+ if (this.vars.has(name))
163
+ return this.vars.get(name);
164
+ if (name === 'HOME')
165
+ return path.resolve(this.ctx.homeDir);
166
+ if (name === 'PWD')
167
+ return this.base;
168
+ return null;
169
+ }
170
+ /**
171
+ * `$NAME`, or `${NAME:-fallback}`. The fallback counts only when this
172
+ * command set the variable to empty: one from outside may hold anything, and
173
+ * a fallback with its own expansion or a `~` is not known either.
174
+ */
175
+ valueOf(name, fallback) {
176
+ const value = this.lookup(name);
177
+ if (fallback === undefined || value !== '')
178
+ return value;
179
+ return /[$`~]/.test(fallback) ? null : fallback;
180
+ }
181
+ resolveWord(word) {
182
+ let text = '';
183
+ const mask = [];
184
+ let unknown = false;
185
+ const append = (value, expandable) => {
186
+ text += value;
187
+ for (let k = 0; k < value.length; k++)
188
+ mask.push(expandable);
189
+ };
190
+ for (const part of word.parts) {
191
+ if (part.kind === 'lit')
192
+ append(part.text, !part.quoted);
193
+ else if (part.kind === 'tilde')
194
+ append(path.resolve(this.ctx.homeDir), false);
195
+ else if (part.kind === 'unknown') {
196
+ unknown = true;
197
+ if (part.ref)
198
+ this.noteRef(part.ref);
199
+ }
200
+ else {
201
+ this.noteRef(part.name);
202
+ const value = this.valueOf(part.name, part.fallback);
203
+ if (value === null)
204
+ unknown = true;
205
+ else
206
+ append(value, false);
207
+ }
208
+ }
209
+ const expanded = [];
210
+ expandBraces(text, mask, expanded);
211
+ return expanded.map((e) => ({
212
+ text: e.text,
213
+ raw: word.raw,
214
+ unknown,
215
+ glob: [...e.text].some((ch, k) => e.mask[k] && (ch === '*' || ch === '?' || ch === '['))
216
+ }));
217
+ }
218
+ /** The absolute location of an argument, or `null` when it is unknown. */
219
+ toAbs(text, base = this.base) {
220
+ if (/^file:\/\//i.test(text)) {
221
+ try {
222
+ return fileURLToPath(text);
223
+ }
224
+ catch {
225
+ return null;
226
+ }
227
+ }
228
+ if (text.startsWith('/'))
229
+ return text;
230
+ if (base === null)
231
+ return null;
232
+ return `${base}/${text}`;
233
+ }
234
+ /** Record a path the command touches. `quiet`: the program loads it without printing it. */
235
+ addPath(arg, access, hard, quiet = false) {
236
+ if (arg.unknown) {
237
+ if (hard)
238
+ this.unresolvable(`the path ${arg.raw} is built from a variable or substitution`);
239
+ return;
240
+ }
241
+ if (arg.text === '')
242
+ return;
243
+ const abs = this.toAbs(arg.text);
244
+ if (abs === null) {
245
+ this.unresolvable(`${arg.raw} is used after a cd to an unknown dir`);
246
+ return;
247
+ }
248
+ if (isHarmlessDevice(abs))
249
+ return;
250
+ if (arg.glob) {
251
+ const components = arg.text.split('/');
252
+ const firstGlob = components.findIndex((c) => /[*?[]/.test(c));
253
+ if (components.slice(firstGlob).includes('..')) {
254
+ this.dynamic(`the glob ${arg.raw} climbs out with ..`);
255
+ return;
256
+ }
257
+ }
258
+ this.paths.push({ raw: arg.raw, abs, access, hard, glob: arg.glob, quiet });
259
+ }
260
+ destroy(arg, what, rootCounts = false) {
261
+ if (arg === null || arg.unknown) {
262
+ this.flag('destructive', `it runs ${what} on paths that are not known until it runs`);
263
+ return;
264
+ }
265
+ const abs = this.toAbs(arg.text);
266
+ if (abs === null)
267
+ this.flag('destructive', `it runs ${what} after a cd to an unknown dir`);
268
+ else
269
+ this.checks.push({ raw: arg.raw, abs, what, rootCounts });
270
+ }
271
+ analyzeCommand(cmd) {
272
+ const args = cmd.words.flatMap((w) => this.resolveWord(w));
273
+ const stdinFed = cmd.pipedIn || cmd.stdinDoc || cmd.redirects.some((r) => r.op === '<' && r.target);
274
+ const stdin = this.tracker.stdinOf(cmd);
275
+ this.stdin = stdin;
276
+ for (const doc of cmd.heredocs) {
277
+ if (!doc.quoted)
278
+ for (const m of doc.body.matchAll(BODY_VAR_RE))
279
+ this.noteRef(m[1]);
280
+ }
281
+ const from = this.paths.length;
282
+ const stdout = [];
283
+ for (const r of cmd.redirects) {
284
+ if (!r.target)
285
+ continue;
286
+ const access = r.op === '<' ? 'read' : 'write';
287
+ for (const target of this.resolveWord(r.target)) {
288
+ if (target.unknown) {
289
+ this.unresolvable(`it redirects to ${target.raw}, a path from a variable or substitution`);
290
+ continue;
291
+ }
292
+ this.addPath(target, access, true);
293
+ const abs = this.toAbs(target.text);
294
+ if (access === 'write' && r.fd !== 2 && abs !== null && !isHarmlessDevice(abs))
295
+ stdout.push({ raw: target.raw, abs });
296
+ }
297
+ }
298
+ const run = this.runArgs(args, stdinFed);
299
+ const reads = this.paths.slice(from).filter((p) => p.access === 'read' && !p.quiet);
300
+ const sources = [...reads.map(({ raw, abs }) => ({ raw, abs })), ...stdin.sources];
301
+ this.tracker.record(cmd, run, sources, stdout);
302
+ }
303
+ /**
304
+ * Take assignments, keywords and wrappers off, then apply the command's
305
+ * rules. Returns the program and its operands, or `null` when there is none.
306
+ * A wrapper's working dir (`env -C`) holds for this command only.
307
+ */
308
+ runArgs(args, stdinFed) {
309
+ const scope = { sudo: false, xargs: null, chdir: false };
310
+ const outer = this.base;
311
+ try {
312
+ return this.run(args, stdinFed, scope);
313
+ }
314
+ finally {
315
+ if (scope.chdir)
316
+ this.base = outer;
317
+ }
318
+ }
319
+ run(args, stdinFed, scope) {
320
+ let i = 0;
321
+ while (i < args.length) {
322
+ const arg = args[i];
323
+ const assignment = /^([A-Za-z_][A-Za-z0-9_]*)\+?=(.*)$/s.exec(arg.text);
324
+ if (assignment && /^[A-Za-z_][A-Za-z0-9_]*\+?=/.test(arg.raw)) {
325
+ this.assign(assignment[1], arg.unknown ? null : assignment[2]);
326
+ i++;
327
+ continue;
328
+ }
329
+ if (arg.raw === arg.text && RESERVED.has(arg.text)) {
330
+ i++;
331
+ continue;
332
+ }
333
+ if (arg.raw === 'function') {
334
+ this.dynamic('it defines a shell function');
335
+ return null;
336
+ }
337
+ if (arg.raw === 'for' || arg.raw === 'select') {
338
+ const inAt = args.findIndex((a, k) => k > i && a.raw === 'in');
339
+ if (inAt > 0)
340
+ for (const item of args.slice(inAt + 1))
341
+ this.operand(item);
342
+ return null;
343
+ }
344
+ if (arg.raw === 'case')
345
+ return null;
346
+ const next = stripWrapper(this, args, i, scope);
347
+ if (next === i)
348
+ break;
349
+ i = next;
350
+ }
351
+ if (i >= args.length)
352
+ return null;
353
+ const argv0 = args[i];
354
+ if (argv0.unknown) {
355
+ this.dynamic(`the command name ${argv0.raw} comes from a variable or substitution`);
356
+ return null;
357
+ }
358
+ if (argv0.glob && !TESTS.has(argv0.text)) {
359
+ this.dynamic(`the command name ${argv0.raw} is a glob`);
360
+ return null;
361
+ }
362
+ if (argv0.text.includes('/')) {
363
+ const abs = this.toAbs(argv0.text);
364
+ if (abs === null || !SYSTEM_BIN_DIRS.has(path.dirname(path.resolve(abs))))
365
+ this.addPath(argv0, 'exec', true);
366
+ }
367
+ const name = path.basename(argv0.text);
368
+ if (scope.sudo && name === 'rm')
369
+ this.flag('destructive', 'it runs rm as root');
370
+ const rest = scope.xargs ? xargsOperands(this, name, args.slice(i + 1), scope.xargs) : args.slice(i + 1);
371
+ runCommand(name, rest, { analyzer: this, stdinFed, xargs: scope.xargs !== null });
372
+ return { name, rest };
373
+ }
374
+ /** A bare operand: a hard path when it looks like one, a soft one otherwise. URLs are skipped. */
375
+ operand(arg, access = 'read') {
376
+ if (isUrl(arg.text))
377
+ return;
378
+ const hard = isPathLike(arg.text) || isPathLike(arg.raw) || /^file:\/\//i.test(arg.text);
379
+ this.addPath(arg, access, hard);
380
+ }
381
+ }
382
+ /**
383
+ * Analyze a bash command, flagging its signals into `findings`. Pure: no fs
384
+ * access; paths are canonicalized by the caller.
385
+ */
386
+ export function analyzeBash(command, ctx, findings) {
387
+ const analyzer = new Analyzer(ctx, findings);
388
+ analyzer.analyzeString(command);
389
+ for (const pattern of CRITICAL_PATTERNS) {
390
+ if (pattern.test(command)) {
391
+ analyzer.flag('destructive', 'it matches a known destructive pattern');
392
+ break;
393
+ }
394
+ }
395
+ if (PLACEHOLDER_RE.test(command)) {
396
+ analyzer.flag('placeholder-in-command', 'it contains a «secret:…» placeholder');
397
+ }
398
+ return {
399
+ paths: analyzer.paths,
400
+ destructiveChecks: analyzer.checks,
401
+ flows: analyzer.tracker.flows,
402
+ envRefs: [...analyzer.envRefs],
403
+ dotglob: DOTGLOB_RE.test(command)
404
+ };
405
+ }
@@ -0,0 +1,45 @@
1
+ /** Option parsing and the generic operand rule, shared by the command rules. */
2
+ import type { Access } from '../types';
3
+ import type { Analyzer, Arg } from './analyze';
4
+ export interface CommandContext {
5
+ analyzer: Analyzer;
6
+ /** stdin comes from a pipe, a heredoc, a here-string or a `<` redirect. */
7
+ stdinFed: boolean;
8
+ /** Run by `xargs`, so more operands arrive from stdin. */
9
+ xargs: boolean;
10
+ }
11
+ /** An argument the analyzer made up itself (`.` for a default root): fully known, no glob. */
12
+ export declare function literalArg(text: string, raw?: string): Arg;
13
+ export interface Parsed {
14
+ flags: Set<string>;
15
+ values: Map<string, Arg[]>;
16
+ positionals: Arg[];
17
+ }
18
+ /**
19
+ * Split options from operands. `withValue` lists the options that take a value
20
+ * (`-o`, `--output`); a short one may be glued (`-ofile`) or part of a cluster
21
+ * (`-sSo file`), a long one may use `=`.
22
+ */
23
+ export declare function parse(rest: readonly Arg[], withValue?: ReadonlySet<string>): Parsed;
24
+ export interface LeadingOption {
25
+ /** One option: `-c` out of a `-xc` cluster, `--eval` out of `--eval=X`. */
26
+ key: string;
27
+ /** Its value, glued (`-cX`, `--eval=X`) or the next word: only for `withValue` keys. */
28
+ value?: Arg;
29
+ }
30
+ /**
31
+ * A program's own options, up to its first operand (`node -r x main.js -e y`
32
+ * stops at `main.js`: the rest belongs to the script). Reads every spelling
33
+ * that `parse` reads. `next` is the index of the first operand; a word built
34
+ * from a variable stops the scan, because it may be either. An option in
35
+ * `stopAfter` ends the program's options (`python -c X`, `python -m X`).
36
+ */
37
+ export declare function leadingOptions(rest: readonly Arg[], withValue: ReadonlySet<string>, stopAfter?: ReadonlySet<string>): {
38
+ options: LeadingOption[];
39
+ next: number;
40
+ };
41
+ export declare const has: (p: Parsed, ...keys: string[]) => boolean;
42
+ export declare const valuesOf: (p: Parsed, ...keys: string[]) => Arg[];
43
+ /** The generic rule: operands are reads; `--opt=path` and `KEY=path` values too. */
44
+ export declare function generic(ctx: CommandContext, rest: readonly Arg[]): void;
45
+ export declare function files(ctx: CommandContext, list: readonly Arg[], access: Access): void;
@@ -0,0 +1,135 @@
1
+ /** Option parsing and the generic operand rule, shared by the command rules. */
2
+ import { isPathLike, isUrl } from './words';
3
+ /** An argument the analyzer made up itself (`.` for a default root): fully known, no glob. */
4
+ export function literalArg(text, raw = text) {
5
+ return { text, raw, unknown: false, glob: false };
6
+ }
7
+ /**
8
+ * Split options from operands. `withValue` lists the options that take a value
9
+ * (`-o`, `--output`); a short one may be glued (`-ofile`) or part of a cluster
10
+ * (`-sSo file`), a long one may use `=`.
11
+ */
12
+ export function parse(rest, withValue = new Set()) {
13
+ const flags = new Set();
14
+ const values = new Map();
15
+ const positionals = [];
16
+ const put = (key, value) => {
17
+ if (!value)
18
+ return;
19
+ values.set(key, [...(values.get(key) ?? []), value]);
20
+ };
21
+ for (let k = 0; k < rest.length; k++) {
22
+ const arg = rest[k];
23
+ const t = arg.text;
24
+ if (t === '--') {
25
+ positionals.push(...rest.slice(k + 1));
26
+ break;
27
+ }
28
+ if (t.startsWith('--')) {
29
+ const eq = t.indexOf('=');
30
+ const key = eq < 0 ? t : t.slice(0, eq);
31
+ flags.add(key);
32
+ if (eq >= 0)
33
+ put(key, { ...arg, text: t.slice(eq + 1) });
34
+ else if (withValue.has(key))
35
+ put(key, rest[++k]);
36
+ continue;
37
+ }
38
+ if (t.startsWith('-') && t.length > 1 && !arg.unknown) {
39
+ for (let c = 1; c < t.length; c++) {
40
+ const key = `-${t[c]}`;
41
+ flags.add(key);
42
+ if (withValue.has(key)) {
43
+ const glued = t.slice(c + 1);
44
+ put(key, glued ? { ...arg, text: glued } : rest[++k]);
45
+ break;
46
+ }
47
+ }
48
+ continue;
49
+ }
50
+ positionals.push(arg);
51
+ }
52
+ return { flags, values, positionals };
53
+ }
54
+ /**
55
+ * A program's own options, up to its first operand (`node -r x main.js -e y`
56
+ * stops at `main.js`: the rest belongs to the script). Reads every spelling
57
+ * that `parse` reads. `next` is the index of the first operand; a word built
58
+ * from a variable stops the scan, because it may be either. An option in
59
+ * `stopAfter` ends the program's options (`python -c X`, `python -m X`).
60
+ */
61
+ export function leadingOptions(rest, withValue, stopAfter = new Set()) {
62
+ const options = [];
63
+ let k = 0;
64
+ for (; k < rest.length; k++) {
65
+ const arg = rest[k];
66
+ const t = arg.text;
67
+ if (t === '--')
68
+ return { options, next: k + 1 };
69
+ if (arg.unknown || !t.startsWith('-') || t === '-')
70
+ break;
71
+ if (t.startsWith('--')) {
72
+ const eq = t.indexOf('=');
73
+ const key = eq < 0 ? t : t.slice(0, eq);
74
+ if (eq >= 0)
75
+ options.push({ key, value: { ...arg, text: t.slice(eq + 1) } });
76
+ else
77
+ options.push(withValue.has(key) ? { key, value: rest[++k] } : { key });
78
+ }
79
+ else {
80
+ for (let c = 1; c < t.length; c++) {
81
+ const key = `-${t[c]}`;
82
+ if (!withValue.has(key)) {
83
+ options.push({ key });
84
+ continue;
85
+ }
86
+ const glued = t.slice(c + 1);
87
+ options.push({ key, value: glued ? { ...arg, text: glued } : rest[++k] });
88
+ break;
89
+ }
90
+ }
91
+ if (stopAfter.has(options[options.length - 1]?.key ?? ''))
92
+ return { options, next: k + 1 };
93
+ }
94
+ return { options, next: k };
95
+ }
96
+ export const has = (p, ...keys) => keys.some((key) => p.flags.has(key));
97
+ export const valuesOf = (p, ...keys) => keys.flatMap((key) => p.values.get(key) ?? []);
98
+ /** Options that load an env file into the program without printing it. */
99
+ const ENV_FILE_OPTIONS = new Set(['--env-file', '--env-file-if-exists']);
100
+ /** The generic rule: operands are reads; `--opt=path` and `KEY=path` values too. */
101
+ export function generic(ctx, rest) {
102
+ const { analyzer } = ctx;
103
+ let afterDashes = false;
104
+ for (let k = 0; k < rest.length; k++) {
105
+ const arg = rest[k];
106
+ const t = arg.text;
107
+ if (t === '--') {
108
+ afterDashes = true;
109
+ continue;
110
+ }
111
+ if (!afterDashes && t.startsWith('-')) {
112
+ const eq = t.indexOf('=');
113
+ const key = eq < 0 ? t : t.slice(0, eq);
114
+ const quiet = ENV_FILE_OPTIONS.has(key);
115
+ if (eq > 0 && (quiet || isPathLike(t.slice(eq + 1)))) {
116
+ analyzer.addPath({ ...arg, text: t.slice(eq + 1) }, 'read', true, quiet);
117
+ }
118
+ else if (eq < 0 && quiet && rest[k + 1]) {
119
+ analyzer.addPath(rest[++k], 'read', true, true);
120
+ }
121
+ continue;
122
+ }
123
+ const kv = /^[A-Za-z_][\w.-]*=(.+)$/.exec(t);
124
+ if (kv && isPathLike(kv[1]) && !isUrl(kv[1])) {
125
+ analyzer.addPath({ ...arg, text: kv[1] }, 'read', true);
126
+ continue;
127
+ }
128
+ analyzer.operand(arg);
129
+ }
130
+ }
131
+ export function files(ctx, list, access) {
132
+ for (const arg of list)
133
+ if (!isUrl(arg.text))
134
+ ctx.analyzer.addPath(arg, access, true);
135
+ }
@@ -0,0 +1,6 @@
1
+ /** Brace expansion (`{a,b}`, `{1..3}`) on the unquoted parts of a word. */
2
+ /** Expand `{a,b}` and `{1..3}` in the unquoted parts of a word. */
3
+ export declare function expandBraces(text: string, mask: boolean[], out: {
4
+ text: string;
5
+ mask: boolean[];
6
+ }[]): void;
@@ -0,0 +1,69 @@
1
+ /** Brace expansion (`{a,b}`, `{1..3}`) on the unquoted parts of a word. */
2
+ const MAX_BRACE_RESULTS = 256;
3
+ /** Expand `{a,b}` and `{1..3}` in the unquoted parts of a word. */
4
+ export function expandBraces(text, mask, out) {
5
+ if (out.length >= MAX_BRACE_RESULTS)
6
+ return;
7
+ for (let open = 0; open < text.length; open++) {
8
+ if (text[open] !== '{' || !mask[open])
9
+ continue;
10
+ let depth = 0;
11
+ const commas = [];
12
+ let close = -1;
13
+ for (let j = open; j < text.length; j++) {
14
+ if (!mask[j])
15
+ continue;
16
+ if (text[j] === '{')
17
+ depth++;
18
+ else if (text[j] === '}') {
19
+ depth--;
20
+ if (depth === 0) {
21
+ close = j;
22
+ break;
23
+ }
24
+ }
25
+ else if (text[j] === ',' && depth === 1)
26
+ commas.push(j);
27
+ }
28
+ if (close < 0)
29
+ return void out.push({ text, mask });
30
+ const pre = text.slice(0, open);
31
+ const preMask = mask.slice(0, open);
32
+ const post = text.slice(close + 1);
33
+ const postMask = mask.slice(close + 1);
34
+ let alternatives = [];
35
+ if (commas.length > 0) {
36
+ const bounds = [open, ...commas, close];
37
+ for (let k = 0; k < bounds.length - 1; k++) {
38
+ alternatives.push({
39
+ text: text.slice(bounds[k] + 1, bounds[k + 1]),
40
+ mask: mask.slice(bounds[k] + 1, bounds[k + 1])
41
+ });
42
+ }
43
+ }
44
+ else {
45
+ const seq = /^(-?\d+|[A-Za-z])\.\.(-?\d+|[A-Za-z])(?:\.\.(-?\d+))?$/.exec(text.slice(open + 1, close));
46
+ if (!seq)
47
+ continue;
48
+ alternatives = sequence(seq[1], seq[2], seq[3]).map((t) => ({ text: t, mask: [...t].map(() => true) }));
49
+ }
50
+ for (const alt of alternatives) {
51
+ expandBraces(pre + alt.text + post, [...preMask, ...alt.mask, ...postMask], out);
52
+ }
53
+ return;
54
+ }
55
+ out.push({ text, mask });
56
+ }
57
+ function sequence(from, to, step) {
58
+ const numeric = /^-?\d+$/.test(from) && /^-?\d+$/.test(to);
59
+ const a = numeric ? Number(from) : from.charCodeAt(0);
60
+ const b = numeric ? Number(to) : to.charCodeAt(0);
61
+ const inc = Math.max(1, Math.abs(Number(step ?? 1)));
62
+ const out = [];
63
+ for (let v = a; a <= b ? v <= b : v >= b; v += a <= b ? inc : -inc) {
64
+ out.push(numeric ? String(v) : String.fromCharCode(v));
65
+ if (out.length >= MAX_BRACE_RESULTS)
66
+ break;
67
+ }
68
+ return out;
69
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * What known commands do with their arguments: which operands they read or
3
+ * write, and which forms run hidden code, upload data or destroy things.
4
+ * Everything not listed here gets the generic rule: every operand is a read.
5
+ * The rules for files, git, the network and the machine live in their own
6
+ * modules; this one holds the shells and interpreters and the dispatch.
7
+ */
8
+ import type { Arg } from './analyze';
9
+ import { type CommandContext } from './args';
10
+ /** Commands that take no file operands. */
11
+ export declare const NO_OPERANDS: Set<string>;
12
+ /** The test commands: `[` and `[[` are names here, not globs. */
13
+ export declare const TESTS: Set<string>;
14
+ export declare function runCommand(name: string, rest: readonly Arg[], ctx: CommandContext): void;