@agentic-kit/permissions 0.0.0-stage → 0.2.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.
Files changed (143) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +279 -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 +35 -3
  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,324 @@
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 * as path from 'node:path';
9
+ import { files, generic, leadingOptions, parse } from './args';
10
+ import { awk, chmodLike, copyLike, dd, find, grep, remove, sed, tee } from './file-commands';
11
+ import { git } from './git';
12
+ import { busyboxServer, curl, phpServer, publishes, pythonServer, remoteCopy, rubyServer, ssh, tunnel, TUNNELS, wget } from './network';
13
+ import { CLIPBOARD, clipboard, namesFromStdin, persistence, security } from './system';
14
+ import { isPathLike } from './words';
15
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'fish', 'ash']);
16
+ const AWKS = new Set(['awk', 'gawk', 'mawk', 'nawk']);
17
+ const GREPS = new Set(['grep', 'egrep', 'fgrep', 'rg', 'ag', 'ack', 'ggrep']);
18
+ const NETWORK_SHELLS = new Set(['nc', 'ncat', 'netcat', 'socat', 'telnet', 'ftp', 'tftp', 'sftp']);
19
+ const DISK_TOOLS = /^(mkfs(\..*)?|fdisk|sfdisk|gdisk|parted|wipefs|cryptsetup|newfs(_.*)?)$/;
20
+ const PERSISTENCE = new Set(['crontab', 'at', 'batch', 'launchctl', 'defaults']);
21
+ /** Commands that take no file operands. */
22
+ export const NO_OPERANDS = new Set([
23
+ 'echo',
24
+ 'printf',
25
+ 'true',
26
+ 'false',
27
+ ':',
28
+ 'exit',
29
+ 'return',
30
+ 'set',
31
+ 'unset',
32
+ 'shift',
33
+ 'wait',
34
+ 'jobs',
35
+ 'type',
36
+ 'which',
37
+ 'hash',
38
+ 'alias',
39
+ 'unalias',
40
+ 'sleep',
41
+ 'date',
42
+ 'pwd',
43
+ 'whoami',
44
+ 'clear',
45
+ 'kill',
46
+ 'trap',
47
+ 'read',
48
+ 'let'
49
+ ]);
50
+ /**
51
+ * Readers whose every operand is a file, with the options that take a value.
52
+ * An operand built from a variable is then a path, not a word: it asks in
53
+ * every mode, as it may name any file.
54
+ */
55
+ const READERS = new Map([
56
+ ...['cat', 'less', 'more', 'bat', 'wc', 'nl', 'strings', 'file', 'stat', 'cmp', 'diff'].map((n) => [n, new Set()]),
57
+ ['head', new Set(['-n', '-c'])],
58
+ ['tail', new Set(['-n', '-c', '-b'])],
59
+ ['sort', new Set(['-k', '-t', '-o', '-S', '-T'])],
60
+ ['uniq', new Set(['-f', '-s'])],
61
+ ['base64', new Set(['-b', '-i', '-o', '-w'])],
62
+ ['xxd', new Set(['-c', '-g', '-l', '-s', '-o'])],
63
+ ['od', new Set(['-A', '-j', '-N', '-t'])],
64
+ ['hexdump', new Set(['-e', '-f', '-n', '-s'])]
65
+ ]);
66
+ /** The test commands: `[` and `[[` are names here, not globs. */
67
+ export const TESTS = new Set(['test', '[', '[[']);
68
+ /** `[[`'s arithmetic comparisons evaluate their operands as expressions. */
69
+ const ARITHMETIC_TESTS = new Set(['-eq', '-ne', '-lt', '-le', '-gt', '-ge']);
70
+ /**
71
+ * A test reads the files it names. `-v NAME` (and, in `[[`, an arithmetic
72
+ * comparison) evaluates array subscripts, which can run a substitution even
73
+ * from a quoted word.
74
+ */
75
+ function test(name, ctx, rest) {
76
+ const close = name === '[' ? ']' : name === '[[' ? ']]' : null;
77
+ const operands = close && rest[rest.length - 1]?.text === close ? rest.slice(0, -1) : rest;
78
+ const evaluates = operands.some((a) => a.text === '-v' || (name === '[[' && ARITHMETIC_TESTS.has(a.text)));
79
+ if (evaluates)
80
+ ctx.analyzer.dynamic(`it runs ${name} with an operator that evaluates expressions`);
81
+ generic(ctx, operands);
82
+ }
83
+ /** Shell options that take a value; the `*file` ones name a script the shell loads. */
84
+ const SHELL_VALUE_OPTIONS = new Set(['-o', '-O', '--rcfile', '--init-file', '--command', '--init-command']);
85
+ const SHELL_LOADS = new Set(['--rcfile', '--init-file']);
86
+ /** `-c` takes its string from the first operand; fish's long forms carry it. */
87
+ const SHELL_INLINE = new Set(['--command', '--init-command']);
88
+ /** A word in a shell's option list that is not a plain letter cluster (`-ex`, `+o`). */
89
+ const isOddShellOption = (text) => /^[-+][^-]/.test(text) && !/^[-+][a-zA-Z]+$/.test(text);
90
+ function shell(name, ctx, rest) {
91
+ const { analyzer } = ctx;
92
+ // `+x`, `+o name`: the same options, turned off.
93
+ const words = rest.map((a) => (/^\+[a-zA-Z]/.test(a.text) ? { ...a, text: `-${a.text.slice(1)}` } : a));
94
+ const { options, next } = leadingOptions(words, SHELL_VALUE_OPTIONS);
95
+ const odd = rest.slice(0, next).find((a) => isOddShellOption(a.text));
96
+ if (odd)
97
+ analyzer.dynamic(`it passes ${name} an option it cannot read: ${odd.raw}`);
98
+ for (const { key, value } of options)
99
+ if (value && SHELL_LOADS.has(key))
100
+ analyzer.operand(value);
101
+ const inline = options.find((o) => SHELL_INLINE.has(o.key));
102
+ const script = inline ? inline.value : options.some((o) => o.key === '-c') ? (rest[next] ?? null) : undefined;
103
+ if (script !== undefined) {
104
+ if (!script || script.unknown)
105
+ analyzer.dynamic(`it runs ${name} -c with a string from a variable`);
106
+ else
107
+ analyzer.nested(script.text, `it runs a shell string with ${name} -c`);
108
+ return;
109
+ }
110
+ const file = rest[next];
111
+ if (file && file.text !== '-') {
112
+ analyzer.addPath(file, 'read', true);
113
+ generic(ctx, rest.slice(next + 1));
114
+ }
115
+ else if (ctx.stdinFed) {
116
+ analyzer.dynamic(`it pipes a script into ${name}`);
117
+ }
118
+ }
119
+ const interpreter = (inline, others, extra = {}) => ({
120
+ inline: new Set(inline),
121
+ withValue: new Set([...inline, ...others, ...(extra.loads ?? [])]),
122
+ ...extra
123
+ });
124
+ const NODE = interpreter(['-e', '-p', '--eval', '--print'], ['--input-type', '--conditions', '-C'], {
125
+ loads: new Set(['-r', '--require', '--import', '--loader', '--experimental-loader'])
126
+ });
127
+ const SCRIPT_RUNNER = interpreter(['-e'], ['-l']);
128
+ /** By program name; every `python*` version is `python`. */
129
+ const INTERPRETERS = new Map([
130
+ ['python', interpreter(['-c'], ['-m', '-W', '-X', '-Q'], { module: '-m', stopAfter: new Set(['-c', '-m']), moduleServer: pythonServer })],
131
+ ['node', NODE],
132
+ ['nodejs', NODE],
133
+ ['perl', interpreter(['-e', '-E'], ['-I', '-M', '-m'])],
134
+ ['ruby', interpreter(['-e'], ['-I', '-C'], { loads: new Set(['-r']), server: rubyServer })],
135
+ ['php', interpreter(['-r', '-B', '-R', '-E'], ['-c', '-d', '-S', '-t'], { loads: new Set(['-f']), server: phpServer })],
136
+ ['lua', SCRIPT_RUNNER],
137
+ ['luajit', SCRIPT_RUNNER],
138
+ ['Rscript', SCRIPT_RUNNER],
139
+ ['osascript', SCRIPT_RUNNER]
140
+ ]);
141
+ function interpreterOf(name) {
142
+ return INTERPRETERS.get(/^python[0-9.]*$/.test(name) ? 'python' : name);
143
+ }
144
+ /** The script an interpreter runs is a read; inline code or piped code is dynamic. */
145
+ function interpret(name, spec, ctx, rest) {
146
+ const { analyzer } = ctx;
147
+ spec.server?.(ctx, rest);
148
+ const { options, next } = leadingOptions(rest, spec.withValue, spec.stopAfter);
149
+ for (const { key, value } of options) {
150
+ if (spec.inline.has(key))
151
+ return analyzer.dynamic(`it runs inline code with ${name} ${key}`);
152
+ if (value && spec.loads?.has(key))
153
+ analyzer.operand(value);
154
+ if (key === spec.module) {
155
+ if (value && !value.unknown)
156
+ spec.moduleServer?.(ctx, value.text, rest.slice(next));
157
+ return generic(ctx, rest.slice(next));
158
+ }
159
+ }
160
+ const script = rest[next];
161
+ if (script && script.text !== '-') {
162
+ analyzer.addPath(script, 'read', true);
163
+ generic(ctx, rest.slice(next + 1));
164
+ }
165
+ else if (ctx.stdinFed) {
166
+ analyzer.dynamic(`it pipes code into ${name}`);
167
+ }
168
+ }
169
+ export function runCommand(name, rest, ctx) {
170
+ const { analyzer } = ctx;
171
+ publishes(name, ctx, rest);
172
+ if (ctx.stdinFed && namesFromStdin(name, rest)) {
173
+ const words = analyzer.stdin.words;
174
+ if (words === null)
175
+ analyzer.flag('stdin-operands', `${name} takes file names from its input, which cannot be checked before it runs`);
176
+ else
177
+ for (const w of words)
178
+ analyzer.addPath(w, 'read', true);
179
+ }
180
+ if (SHELLS.has(name))
181
+ return shell(name, ctx, rest);
182
+ const spec = interpreterOf(name);
183
+ if (spec)
184
+ return interpret(name, spec, ctx, rest);
185
+ if (AWKS.has(name))
186
+ return awk(name, ctx, rest);
187
+ if (GREPS.has(name))
188
+ return grep(ctx, rest);
189
+ if (NETWORK_SHELLS.has(name)) {
190
+ analyzer.flag('upload', `it uploads data: ${name} opens a raw network connection`);
191
+ return generic(ctx, rest.filter((a) => isPathLike(a.text)));
192
+ }
193
+ if (TUNNELS.has(name))
194
+ return tunnel(name, ctx, rest);
195
+ if (PERSISTENCE.has(name))
196
+ return persistence(name, ctx, rest);
197
+ if (CLIPBOARD.has(name))
198
+ return clipboard(name, ctx, rest);
199
+ if (DISK_TOOLS.test(name)) {
200
+ analyzer.flag('destructive', `it runs ${name}, which formats or partitions a disk`);
201
+ return;
202
+ }
203
+ if (TESTS.has(name))
204
+ return test(name, ctx, rest);
205
+ const readerValues = READERS.get(name);
206
+ if (readerValues) {
207
+ for (const v of parse(rest, readerValues).positionals)
208
+ if (v.unknown)
209
+ analyzer.addPath(v, 'read', true);
210
+ return generic(ctx, rest);
211
+ }
212
+ if (NO_OPERANDS.has(name))
213
+ return;
214
+ switch (name) {
215
+ case 'cd':
216
+ case 'pushd': {
217
+ const target = parse(rest).positionals[0];
218
+ if (!target) {
219
+ analyzer.base = path.resolve(analyzer.ctx.homeDir);
220
+ }
221
+ else if (target.unknown || /^[-+]\d*$/.test(target.text) || analyzer.searchesCdPath(target.text)) {
222
+ // `cd -`, `pushd +1` and a `CDPATH` lookup go to a dir the text does not name.
223
+ analyzer.base = null;
224
+ }
225
+ else {
226
+ const abs = analyzer.toAbs(target.text);
227
+ analyzer.addPath(target, 'read', true);
228
+ analyzer.base = abs === null ? null : path.resolve(abs);
229
+ }
230
+ return;
231
+ }
232
+ case 'popd':
233
+ analyzer.base = null;
234
+ return;
235
+ case 'export':
236
+ case 'declare':
237
+ case 'local':
238
+ case 'readonly':
239
+ case 'typeset':
240
+ for (const arg of rest) {
241
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s.exec(arg.text);
242
+ if (m)
243
+ analyzer.assign(m[1], arg.unknown ? null : m[2]);
244
+ }
245
+ return;
246
+ case 'eval':
247
+ if (rest.some((a) => a.unknown))
248
+ analyzer.dynamic('it runs eval on a value from a variable');
249
+ else
250
+ analyzer.nested(rest.map((a) => a.text).join(' '), 'it runs a string with eval');
251
+ return;
252
+ case 'source':
253
+ case '.':
254
+ analyzer.dynamic(`it loads a script into the shell with ${name}`);
255
+ if (rest[0])
256
+ analyzer.addPath(rest[0], 'read', true);
257
+ return;
258
+ case 'deno':
259
+ if (rest[0]?.text === 'eval')
260
+ return analyzer.dynamic('it runs inline code with deno eval');
261
+ return generic(ctx, rest);
262
+ case 'bun':
263
+ if (leadingOptions(rest, NODE.inline).options.some((o) => NODE.inline.has(o.key))) {
264
+ return analyzer.dynamic('it runs inline code with bun -e');
265
+ }
266
+ return generic(ctx, rest);
267
+ case 'curl':
268
+ return curl(ctx, rest);
269
+ case 'wget':
270
+ return wget(ctx, rest);
271
+ case 'scp':
272
+ case 'rsync':
273
+ return remoteCopy(name, ctx, rest);
274
+ case 'ssh':
275
+ return ssh(ctx, rest);
276
+ case 'security':
277
+ return security(ctx, rest);
278
+ case 'busybox':
279
+ if (rest[0]?.text === 'httpd')
280
+ return busyboxServer(ctx, rest.slice(1));
281
+ if (rest[0])
282
+ return runCommand(path.basename(rest[0].text), rest.slice(1), ctx);
283
+ return;
284
+ case 'find':
285
+ return find(ctx, rest);
286
+ case 'git':
287
+ return git(ctx, rest);
288
+ case 'sed':
289
+ case 'gsed':
290
+ return sed(ctx, rest);
291
+ case 'rm':
292
+ case 'rmdir':
293
+ case 'unlink':
294
+ case 'shred':
295
+ case 'rimraf':
296
+ case 'srm':
297
+ return remove(name, ctx, rest);
298
+ case 'touch':
299
+ case 'mkdir':
300
+ case 'mkfifo':
301
+ case 'truncate':
302
+ return files(ctx, parse(rest, new Set(['-m', '--mode', '-s', '--size', '-r', '--reference', '-t', '-d'])).positionals, 'write');
303
+ case 'tee':
304
+ return tee(ctx, rest);
305
+ case 'cp':
306
+ case 'mv':
307
+ case 'ln':
308
+ case 'install':
309
+ return copyLike(name, ctx, rest);
310
+ case 'chmod':
311
+ case 'chown':
312
+ case 'chgrp':
313
+ return chmodLike(name, ctx, rest);
314
+ case 'dd':
315
+ return dd(ctx, rest);
316
+ case 'diskutil':
317
+ if (rest.some((a) => /^(erase|zero|partition|secureErase|reformat)/i.test(a.text))) {
318
+ analyzer.flag('destructive', 'it runs diskutil to erase or partition a disk');
319
+ }
320
+ return;
321
+ default:
322
+ return generic(ctx, rest);
323
+ }
324
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Commands that read, write, copy and delete files: which operands they touch
3
+ * with which access, which forms destroy data, and where a copy puts a file's
4
+ * contents.
5
+ */
6
+ import type { Arg } from './analyze';
7
+ import { type CommandContext } from './args';
8
+ /** `tee file…`: stdin lands in each file. */
9
+ export declare function tee(ctx: CommandContext, rest: readonly Arg[]): void;
10
+ /** The dirs `find` searches (`.` when none is given), and the index of its first expression word. */
11
+ export declare function findRoots(rest: readonly Arg[]): {
12
+ roots: Arg[];
13
+ next: number;
14
+ };
15
+ export declare function find(ctx: CommandContext, rest: readonly Arg[]): void;
16
+ export declare function sed(ctx: CommandContext, rest: readonly Arg[]): void;
17
+ export declare function grep(ctx: CommandContext, rest: readonly Arg[]): void;
18
+ export declare function awk(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
19
+ export declare function remove(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
20
+ export declare function copyLike(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
21
+ export declare function chmodLike(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
22
+ export declare function dd(ctx: CommandContext, rest: readonly Arg[]): void;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Commands that read, write, copy and delete files: which operands they touch
3
+ * with which access, which forms destroy data, and where a copy puts a file's
4
+ * contents.
5
+ */
6
+ import * as path from 'node:path';
7
+ import { files, has, literalArg, parse, valuesOf } from './args';
8
+ /**
9
+ * Record that the contents of `sources` (or of `stdin`) land in `dest`: a dir
10
+ * when `dir`, where each file keeps its name.
11
+ */
12
+ function copies(ctx, what, sources, dest, dir, stdin = []) {
13
+ const { analyzer } = ctx;
14
+ const to = dest.unknown ? null : analyzer.toAbs(dest.text);
15
+ if (to === null)
16
+ return;
17
+ const from = [...stdin];
18
+ for (const s of sources) {
19
+ const abs = s.unknown ? null : analyzer.toAbs(s.text);
20
+ if (abs !== null)
21
+ from.push({ raw: s.raw, abs });
22
+ }
23
+ if (from.length > 0)
24
+ analyzer.tracker.flows.push({ sources: from, to: { kind: 'file', raw: dest.raw, abs: to, dir }, what });
25
+ }
26
+ /** `tee file…`: stdin lands in each file. */
27
+ export function tee(ctx, rest) {
28
+ const ops = parse(rest).positionals;
29
+ files(ctx, ops, 'write');
30
+ for (const op of ops)
31
+ copies(ctx, 'tee', [], op, false, ctx.analyzer.stdin.sources);
32
+ }
33
+ /** Options that come before `find`'s roots. */
34
+ const FIND_LEADING = new Set(['-H', '-L', '-P', '-E', '-X', '-s', '-x', '-d', '-O0', '-O1', '-O2', '-O3']);
35
+ /** The dirs `find` searches (`.` when none is given), and the index of its first expression word. */
36
+ export function findRoots(rest) {
37
+ let k = 0;
38
+ while (k < rest.length && FIND_LEADING.has(rest[k].text))
39
+ k++;
40
+ const roots = [];
41
+ while (k < rest.length && !/^[-(!)]/.test(rest[k].text))
42
+ roots.push(rest[k++]);
43
+ return { roots: roots.length > 0 ? roots : [literalArg('.')], next: k };
44
+ }
45
+ export function find(ctx, rest) {
46
+ const { analyzer } = ctx;
47
+ const { roots, next } = findRoots(rest);
48
+ for (const r of roots)
49
+ analyzer.addPath(r, 'read', true);
50
+ for (let k = next; k < rest.length; k++) {
51
+ const t = rest[k].text;
52
+ if (t === '-delete') {
53
+ for (const r of roots)
54
+ analyzer.destroy(r, 'find -delete');
55
+ }
56
+ else if (/^-(fprint0?|fprintf|fls)$/.test(t) && rest[k + 1]) {
57
+ analyzer.addPath(rest[++k], 'write', true);
58
+ }
59
+ else if (/^-(exec|execdir|ok|okdir)$/.test(t)) {
60
+ const end = rest.findIndex((a, j) => j > k && (a.text === ';' || a.text === '+'));
61
+ const sub = rest.slice(k + 1, end < 0 ? rest.length : end);
62
+ k = end < 0 ? rest.length : end;
63
+ if (sub.length === 0)
64
+ continue;
65
+ // `{}` stands for each match: a path inside each root.
66
+ for (const r of roots) {
67
+ const replaced = sub.map((a) => (a.text.includes('{}') ? { ...a, text: a.text.split('{}').join(`${r.text}/{}`) } : a));
68
+ analyzer.runArgs(replaced, false);
69
+ }
70
+ }
71
+ }
72
+ }
73
+ export function sed(ctx, rest) {
74
+ const p = parse(rest, new Set(['-e', '-f', '--expression', '--file', '-l']));
75
+ const inPlace = has(p, '-i', '--in-place') || [...p.flags].some((f) => f.startsWith('-i'));
76
+ let ops = p.positionals;
77
+ // BSD `sed -i '' …`: the empty word is the backup suffix.
78
+ if (inPlace && ops[0]?.text === '')
79
+ ops = ops.slice(1);
80
+ for (const f of valuesOf(p, '-f', '--file'))
81
+ ctx.analyzer.addPath(f, 'read', true);
82
+ if (valuesOf(p, '-e', '--expression', '-f', '--file').length === 0)
83
+ ops = ops.slice(1);
84
+ files(ctx, ops, inPlace ? 'write' : 'read');
85
+ }
86
+ export function grep(ctx, rest) {
87
+ const p = parse(rest, new Set([
88
+ '-e',
89
+ '-f',
90
+ '-m',
91
+ '-A',
92
+ '-B',
93
+ '-C',
94
+ '-g',
95
+ '-t',
96
+ '-T',
97
+ '-d',
98
+ '-D',
99
+ '--regexp',
100
+ '--file',
101
+ '--max-count',
102
+ '--glob',
103
+ '--type',
104
+ '--type-not',
105
+ '--include',
106
+ '--exclude',
107
+ '--exclude-dir',
108
+ '--context',
109
+ '--after-context',
110
+ '--before-context'
111
+ ]));
112
+ for (const f of valuesOf(p, '-f', '--file'))
113
+ ctx.analyzer.addPath(f, 'read', true);
114
+ const ops = valuesOf(p, '-e', '--regexp', '-f', '--file').length ? p.positionals : p.positionals.slice(1);
115
+ for (const op of ops)
116
+ ctx.analyzer.operand(op);
117
+ }
118
+ export function awk(name, ctx, rest) {
119
+ const p = parse(rest, new Set(['-f', '-v', '-F', '-i', '--file', '--include']));
120
+ let ops = p.positionals;
121
+ const progFiles = valuesOf(p, '-f', '--file');
122
+ for (const f of progFiles)
123
+ ctx.analyzer.addPath(f, 'read', true);
124
+ if (progFiles.length === 0) {
125
+ const program = ops[0];
126
+ ops = ops.slice(1);
127
+ if (program && (program.unknown || /\bsystem\s*\(|\|/.test(program.text))) {
128
+ ctx.analyzer.dynamic(`its ${name} program runs commands`);
129
+ }
130
+ }
131
+ const inPlace = valuesOf(p, '-i', '--include').some((v) => v.text === 'inplace');
132
+ for (const op of ops) {
133
+ if (/^[A-Za-z_]\w*=/.test(op.text))
134
+ continue;
135
+ if (inPlace)
136
+ ctx.analyzer.addPath(op, 'write', true);
137
+ else
138
+ ctx.analyzer.operand(op);
139
+ }
140
+ }
141
+ export function remove(name, ctx, rest) {
142
+ const { analyzer } = ctx;
143
+ const p = parse(rest);
144
+ if (has(p, '--no-preserve-root'))
145
+ analyzer.flag('destructive', `it runs ${name} --no-preserve-root`);
146
+ const forceful = name === 'rimraf' ||
147
+ name === 'shred' ||
148
+ has(p, '-r', '-R', '-f', '--recursive', '--force');
149
+ for (const op of p.positionals) {
150
+ analyzer.addPath(op, 'write', true);
151
+ if (forceful)
152
+ analyzer.destroy(op, `${name} ${[...p.flags].join(' ')}`.trim(), true);
153
+ }
154
+ if (ctx.xargs && (name === 'rm' || name === 'rimraf' || name === 'shred' || name === 'unlink')) {
155
+ analyzer.destroy(null, `xargs ${name}`);
156
+ }
157
+ }
158
+ export function copyLike(name, ctx, rest) {
159
+ const { analyzer } = ctx;
160
+ const p = parse(rest, new Set(['-t', '--target-directory', '-S', '--suffix', '-m', '--mode', '-o', '--owner', '-g', '--group']));
161
+ const targetDir = valuesOf(p, '-t', '--target-directory')[0];
162
+ const ops = p.positionals;
163
+ const sourceAccess = name === 'mv' ? 'write' : 'read';
164
+ if (name === 'install' && has(p, '-d'))
165
+ return files(ctx, ops, 'write');
166
+ if (targetDir) {
167
+ analyzer.addPath(targetDir, 'write', true);
168
+ if (name !== 'ln')
169
+ copies(ctx, name, ops, targetDir, true);
170
+ return files(ctx, ops, sourceAccess);
171
+ }
172
+ if (ops.length === 1 && name === 'ln') {
173
+ analyzer.addPath(ops[0], 'read', true);
174
+ analyzer.addPath({ ...ops[0], text: path.basename(ops[0].text) }, 'write', true);
175
+ return;
176
+ }
177
+ if (ops.length === 0)
178
+ return;
179
+ const dest = ops[ops.length - 1];
180
+ files(ctx, ops.slice(0, -1), sourceAccess);
181
+ analyzer.addPath(dest, 'write', true);
182
+ if (name !== 'ln')
183
+ copies(ctx, name, ops.slice(0, -1), dest, ops.length > 2 || dest.text.endsWith('/'));
184
+ }
185
+ export function chmodLike(name, ctx, rest) {
186
+ let recursive = false;
187
+ let reference = false;
188
+ const operands = [];
189
+ for (const arg of rest) {
190
+ const t = arg.text;
191
+ if (/^-[RvcfhHLP]+$/.test(t) || t === '--recursive' || t.startsWith('--')) {
192
+ if (/^-[a-zA-Z]*R/.test(t) || t === '--recursive')
193
+ recursive = true;
194
+ if (t.startsWith('--reference'))
195
+ reference = true;
196
+ continue;
197
+ }
198
+ operands.push(arg);
199
+ }
200
+ // The first operand is the mode or owner (`755`, `+x`, `-w`, `user:group`).
201
+ for (const op of reference ? operands : operands.slice(1)) {
202
+ ctx.analyzer.addPath(op, 'write', true);
203
+ if (recursive)
204
+ ctx.analyzer.destroy(op, `${name} -R`);
205
+ }
206
+ }
207
+ export function dd(ctx, rest) {
208
+ const input = rest.find((a) => a.text.startsWith('if='));
209
+ const output = rest.find((a) => a.text.startsWith('of='));
210
+ if (output) {
211
+ const dest = { ...output, text: output.text.slice(3) };
212
+ if (input)
213
+ copies(ctx, 'dd', [{ ...input, text: input.text.slice(3) }], dest, false);
214
+ else
215
+ copies(ctx, 'dd', [], dest, false, ctx.analyzer.stdin.sources);
216
+ }
217
+ for (const arg of rest) {
218
+ const m = /^(if|of)=(.*)$/.exec(arg.text);
219
+ if (!m)
220
+ continue;
221
+ const target = { ...arg, text: m[2] };
222
+ if (m[1] === 'if') {
223
+ ctx.analyzer.addPath(target, 'read', true);
224
+ }
225
+ else {
226
+ if (m[2].startsWith('/dev/') && !/^\/dev\/(null|stdout|stderr)$/.test(m[2])) {
227
+ ctx.analyzer.flag('destructive', `dd writes raw blocks to ${m[2]}`);
228
+ }
229
+ ctx.analyzer.addPath(target, 'write', true);
230
+ ctx.analyzer.destroy(target, 'dd of=');
231
+ }
232
+ }
233
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Where file contents go inside one command line: down pipes, into
3
+ * redirections and copies, onto the clipboard, and through programs that
4
+ * change them. The analyzer only records the flows; the classifier decides
5
+ * which sources are secret files, since that needs the real paths.
6
+ */
7
+ import type { Analyzer, Arg, Run } from './analyze';
8
+ import type { SimpleCommand } from './tokenize';
9
+ export interface Source {
10
+ raw: string;
11
+ abs: string;
12
+ }
13
+ export type FlowSink =
14
+ /** A copy into a file, or into a dir when `dir` (the file keeps its name). */
15
+ {
16
+ kind: 'file';
17
+ raw: string;
18
+ abs: string;
19
+ dir: boolean;
20
+ } | {
21
+ kind: 'clipboard';
22
+ }
23
+ /** A program whose output is not the text it read (`base64`, `sed`, `node`). */
24
+ | {
25
+ kind: 'transform';
26
+ };
27
+ export interface ContentFlow {
28
+ sources: Source[];
29
+ to: FlowSink;
30
+ /** The program, for the reason: `cp`, `base64`, `>`. */
31
+ what: string;
32
+ }
33
+ /** What one command reads on stdin. */
34
+ export interface Stdin {
35
+ /** Files whose contents arrive on stdin. */
36
+ sources: Source[];
37
+ /** The words on stdin when they are known (`echo a b |`, `<<< a`); `null` when they are not. */
38
+ words: Arg[] | null;
39
+ /**
40
+ * When stdin is a file listing (`find src |`, `git ls-files |`): the roots
41
+ * every listed name lies under. `null` when it is anything else.
42
+ */
43
+ listedUnder: Arg[] | null;
44
+ }
45
+ /** The program prints what it read as is, or prints nothing of it. */
46
+ export declare function keepsContent(name: string, rest: readonly Arg[]): boolean;
47
+ /** Follows contents from command to command within one analyzed string. */
48
+ export declare class FlowTracker {
49
+ private readonly analyzer;
50
+ readonly flows: ContentFlow[];
51
+ /** The files whose contents each command's stdout carries. */
52
+ private readonly outputs;
53
+ /** The words each `echo` or `printf` printed. */
54
+ private readonly printed;
55
+ /** The roots each file-listing command printed names under. */
56
+ private readonly listed;
57
+ /** Every source seen so far: what a `( … ) |` group may print. */
58
+ private readonly all;
59
+ constructor(analyzer: Analyzer);
60
+ /** What arrives on the command's stdin: from `<`, a here-string, a heredoc, or a pipe. */
61
+ stdinOf(cmd: SimpleCommand): Stdin;
62
+ /**
63
+ * After a command ran: remember what its stdout carries, and record a
64
+ * transform and its stdout redirections as flows.
65
+ */
66
+ record(cmd: SimpleCommand, run: Run | null, sources: Source[], redirects: Source[]): void;
67
+ }