@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,203 @@
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 { literalArg } from './args';
8
+ import { findRoots } from './file-commands';
9
+ /** Readers whose output is the file's text unchanged, so redaction still matches it. */
10
+ const VERBATIM = new Set([
11
+ 'cat',
12
+ 'head',
13
+ 'tail',
14
+ 'less',
15
+ 'more',
16
+ 'bat',
17
+ 'grep',
18
+ 'egrep',
19
+ 'fgrep',
20
+ 'ggrep',
21
+ 'rg',
22
+ 'ag',
23
+ 'ack',
24
+ 'wc',
25
+ 'diff',
26
+ 'tee',
27
+ 'sort',
28
+ 'uniq',
29
+ 'nl'
30
+ ]);
31
+ /**
32
+ * Commands that do not print what they read (`ls`, `test`, `rm`), or whose
33
+ * output another signal already covers (copies, the clipboard, `source`).
34
+ */
35
+ const NO_CONTENT = new Set([
36
+ 'ls',
37
+ 'stat',
38
+ 'du',
39
+ 'file',
40
+ 'test',
41
+ '[',
42
+ '[[',
43
+ 'touch',
44
+ 'cd',
45
+ 'pushd',
46
+ 'realpath',
47
+ 'readlink',
48
+ 'basename',
49
+ 'dirname',
50
+ 'rm',
51
+ 'rmdir',
52
+ 'unlink',
53
+ 'shred',
54
+ 'srm',
55
+ 'rimraf',
56
+ 'chmod',
57
+ 'chown',
58
+ 'chgrp',
59
+ 'mkdir',
60
+ 'find',
61
+ 'git',
62
+ 'source',
63
+ '.',
64
+ 'cp',
65
+ 'mv',
66
+ 'install',
67
+ 'ln',
68
+ 'dd',
69
+ 'pbcopy',
70
+ 'xclip',
71
+ 'xsel',
72
+ 'wl-copy'
73
+ ]);
74
+ /** `head -c`, `grep -o`, `rg -r`: a verbatim reader that cuts values apart. */
75
+ function trims(name, rest) {
76
+ const flags = rest.map((a) => a.text).filter((t) => t.startsWith('-'));
77
+ if (name === 'head' || name === 'tail')
78
+ return flags.some((t) => /^(-c|--bytes)/.test(t));
79
+ if (name === 'rg' && flags.some((t) => /^(-r|--replace)/.test(t)))
80
+ return true;
81
+ return flags.some((t) => t === '--only-matching' || /^-[a-zA-Z]*o[a-zA-Z]*$/.test(t));
82
+ }
83
+ /** The program prints what it read as is, or prints nothing of it. */
84
+ export function keepsContent(name, rest) {
85
+ if (NO_CONTENT.has(name))
86
+ return true;
87
+ return VERBATIM.has(name) && !trims(name, rest);
88
+ }
89
+ /** Split words the way `xargs` does (on whitespace). `null` when one is not known. */
90
+ function splitWords(args) {
91
+ if (args.some((a) => a.unknown))
92
+ return null;
93
+ return args.flatMap((a) => a.text
94
+ .split(/\s+/)
95
+ .filter(Boolean)
96
+ .map((text) => literalArg(text, a.raw)));
97
+ }
98
+ /** The words `echo` or `printf` prints; `null` when one is not known. */
99
+ function printedWords(name, rest) {
100
+ if (name === 'printf')
101
+ return rest[0]?.text === '-v' ? [] : splitWords(rest);
102
+ let k = 0;
103
+ while (k < rest.length && /^-[neE]+$/.test(rest[k].text))
104
+ k++;
105
+ return splitWords(rest.slice(k));
106
+ }
107
+ /**
108
+ * The roots a file-listing command prints names under: `find`, `ls`, and
109
+ * `git ls-files`. `null` for any other command, an unknown root, or a `find`
110
+ * that follows symlinks (`-L`), whose names can leave its roots.
111
+ */
112
+ function listedRoots(name, rest) {
113
+ if (rest.some((a) => a.unknown))
114
+ return null;
115
+ if (name === 'find') {
116
+ if (rest.some((a) => a.text === '-L' || a.text === '-follow'))
117
+ return null;
118
+ return findRoots(rest).roots;
119
+ }
120
+ if (name === 'ls') {
121
+ const roots = rest.filter((a) => !a.text.startsWith('-'));
122
+ return roots.length > 0 ? roots : [literalArg('.')];
123
+ }
124
+ if (name === 'git' && rest[0]?.text === 'ls-files')
125
+ return [literalArg('.')];
126
+ return null;
127
+ }
128
+ const GROUP_END = new Set(['}', 'done', 'fi', 'esac']);
129
+ /** Follows contents from command to command within one analyzed string. */
130
+ export class FlowTracker {
131
+ analyzer;
132
+ flows = [];
133
+ /** The files whose contents each command's stdout carries. */
134
+ outputs = new Map();
135
+ /** The words each `echo` or `printf` printed. */
136
+ printed = new Map();
137
+ /** The roots each file-listing command printed names under. */
138
+ listed = new Map();
139
+ /** Every source seen so far: what a `( … ) |` group may print. */
140
+ all = [];
141
+ constructor(analyzer) {
142
+ this.analyzer = analyzer;
143
+ }
144
+ /** What arrives on the command's stdin: from `<`, a here-string, a heredoc, or a pipe. */
145
+ stdinOf(cmd) {
146
+ const { analyzer } = this;
147
+ const sources = [];
148
+ let words = [];
149
+ let listedUnder = null;
150
+ for (const r of cmd.redirects) {
151
+ if (r.op !== '<' || !r.target)
152
+ continue;
153
+ words = null;
154
+ for (const t of analyzer.resolveWord(r.target)) {
155
+ const abs = t.unknown ? null : analyzer.toAbs(t.text);
156
+ if (abs)
157
+ sources.push({ raw: t.raw, abs });
158
+ }
159
+ }
160
+ if (cmd.heredocs.length > 0)
161
+ words = null;
162
+ for (const w of cmd.hereStrings) {
163
+ const said = splitWords(analyzer.resolveWord(w));
164
+ words = words && said ? [...words, ...said] : null;
165
+ }
166
+ if (cmd.pipedIn) {
167
+ const up = cmd.upstream;
168
+ if (!up || up === 'group' || up.words.every((w) => GROUP_END.has(w.raw))) {
169
+ sources.push(...this.all);
170
+ words = null;
171
+ }
172
+ else {
173
+ sources.push(...(this.outputs.get(up) ?? []));
174
+ const said = this.printed.get(up);
175
+ words = words && said ? [...words, ...said] : null;
176
+ const onlyPipe = cmd.redirects.every((r) => r.op !== '<') && cmd.hereStrings.length === 0 && cmd.heredocs.length === 0;
177
+ listedUnder = onlyPipe ? (this.listed.get(up) ?? null) : null;
178
+ }
179
+ }
180
+ return { sources, words, listedUnder };
181
+ }
182
+ /**
183
+ * After a command ran: remember what its stdout carries, and record a
184
+ * transform and its stdout redirections as flows.
185
+ */
186
+ record(cmd, run, sources, redirects) {
187
+ this.outputs.set(cmd, sources);
188
+ this.all.push(...sources);
189
+ if (!run)
190
+ return;
191
+ if (run.name === 'echo' || run.name === 'printf')
192
+ this.printed.set(cmd, printedWords(run.name, run.rest));
193
+ const roots = listedRoots(run.name, run.rest);
194
+ if (roots)
195
+ this.listed.set(cmd, roots);
196
+ if (sources.length === 0)
197
+ return;
198
+ if (!keepsContent(run.name, run.rest))
199
+ this.flows.push({ sources, to: { kind: 'transform' }, what: run.name });
200
+ for (const r of redirects)
201
+ this.flows.push({ sources, to: { kind: 'file', ...r, dir: false }, what: '>' });
202
+ }
203
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * git: options that make it run programs, pushes that rewrite or leave for an
3
+ * unknown remote, config writes, and force-adding a secret file.
4
+ */
5
+ import type { Arg } from './analyze';
6
+ import { type CommandContext } from './args';
7
+ export declare function git(ctx: CommandContext, rest: readonly Arg[]): void;
@@ -0,0 +1,127 @@
1
+ /**
2
+ * git: options that make it run programs, pushes that rewrite or leave for an
3
+ * unknown remote, config writes, and force-adding a secret file.
4
+ */
5
+ import * as path from 'node:path';
6
+ import { isSecretFile } from '../secret-files';
7
+ import { generic, has, parse, valuesOf } from './args';
8
+ import { isRemoteSpec, isUrl } from './words';
9
+ /** `git -c` keys that make git run a program. */
10
+ const GIT_EXEC_CONFIG = /^(alias\.|core\.(sshcommand|pager|editor|fsmonitor|hookspath|askpass|gitproxy)|diff\.|credential\.|sequence\.editor|gpg\.|filter\.|uploadpack\.|protocol\.|include\.|includeif\.|remote\..*\.(uploadpack|receivepack))/i;
11
+ /** `git -c remote.<name>.url=…`: the remote points somewhere else for this run. */
12
+ const GIT_REMOTE_URL_CONFIG = /^remote\.(.+)\.(url|pushurl)=/i;
13
+ /**
14
+ * `git push`: destructive when it rewrites or deletes refs, and an upload when
15
+ * it goes to a URL or to a remote this command added or repointed.
16
+ */
17
+ function push(ctx, p) {
18
+ const { analyzer } = ctx;
19
+ const force = has(p, '-f', '--force', '--force-if-includes', '--mirror', '-d', '--delete', '--prune') ||
20
+ [...p.flags].some((f) => f.startsWith('--force-with-lease')) ||
21
+ p.positionals.some((a) => a.text.startsWith('+') || a.text.startsWith(':'));
22
+ if (force)
23
+ analyzer.flag('destructive', 'it force-pushes or deletes refs on the remote');
24
+ const remote = valuesOf(p, '--repo')[0] ?? p.positionals[0];
25
+ if (!remote) {
26
+ if (analyzer.gitRemotes.size > 0)
27
+ analyzer.flag('upload', 'it uploads data: git push goes to a remote this command changed');
28
+ return;
29
+ }
30
+ if (remote.unknown || isUrl(remote.text) || isRemoteSpec(remote.text)) {
31
+ analyzer.flag('upload', `it uploads data: git push sends commits to ${remote.raw}`);
32
+ }
33
+ else if (analyzer.gitRemotes.has(remote.text)) {
34
+ analyzer.flag('upload', `it uploads data: git push goes to ${remote.raw}, a remote this command set`);
35
+ }
36
+ }
37
+ /** `git remote add|set-url NAME URL`: remember the name, so a later push is an upload. */
38
+ function remote(ctx, args) {
39
+ const p = parse(args, new Set(['-t', '-m']));
40
+ const [action, name] = p.positionals;
41
+ if ((action?.text === 'add' || action?.text === 'set-url') && name)
42
+ ctx.analyzer.gitRemotes.add(name.text);
43
+ }
44
+ /** `git add -f .env`: stages a file `.gitignore` keeps out, so its values would be committed. */
45
+ function add(ctx, args) {
46
+ const p = parse(args, new Set(['--chmod', '--pathspec-from-file']));
47
+ if (has(p, '-f', '--force')) {
48
+ for (const op of p.positionals) {
49
+ if (op.unknown || !isSecretFile(op.text))
50
+ continue;
51
+ ctx.analyzer.flag('secret-file', `git add -f stages the secret file ${op.raw}, which .gitignore keeps out of the repo`);
52
+ ctx.analyzer.flag('secret-into-plain-file', `git add -f puts ${op.raw} into the repo, where its values are committed in the clear`);
53
+ }
54
+ }
55
+ generic(ctx, p.positionals.filter((a) => !isUrl(a.text)));
56
+ }
57
+ export function git(ctx, rest) {
58
+ const { analyzer } = ctx;
59
+ let k = 0;
60
+ let base = analyzer.base;
61
+ for (; k < rest.length; k++) {
62
+ const t = rest[k].text;
63
+ if (t === '-C') {
64
+ const dir = rest[++k];
65
+ base = dir && !dir.unknown && base !== null ? path.resolve(base, dir.text) : null;
66
+ if (dir)
67
+ analyzer.addPath(dir, 'read', true);
68
+ }
69
+ else if (t === '-c') {
70
+ const kv = rest[++k];
71
+ if (kv && GIT_EXEC_CONFIG.test(kv.text))
72
+ analyzer.dynamic(`git -c ${kv.text} makes git run a program`);
73
+ const repointed = kv ? GIT_REMOTE_URL_CONFIG.exec(kv.text) : null;
74
+ if (repointed)
75
+ analyzer.gitRemotes.add(repointed[1]);
76
+ }
77
+ else if (/^--(git-dir|work-tree)=/.test(t)) {
78
+ analyzer.addPath({ ...rest[k], text: t.slice(t.indexOf('=') + 1) }, 'read', true);
79
+ }
80
+ else if (t.startsWith('--exec-path')) {
81
+ analyzer.dynamic('git --exec-path changes which programs git runs');
82
+ }
83
+ else if (!t.startsWith('-')) {
84
+ break;
85
+ }
86
+ }
87
+ const sub = rest[k]?.text;
88
+ const args = rest.slice(k + 1);
89
+ const saved = analyzer.base;
90
+ analyzer.base = base;
91
+ try {
92
+ if (sub === 'remote')
93
+ return remote(ctx, args);
94
+ if (sub === 'add')
95
+ return add(ctx, args);
96
+ if (sub === 'push')
97
+ return push(ctx, parse(args, new Set(['--repo', '-o', '--push-option', '--receive-pack', '--exec'])));
98
+ const p = parse(args, new Set(['-m', '-F', '-C', '-c', '--file', '-f', '-o', '--message', '--format']));
99
+ const here = { text: '.', raw: rest[k]?.raw ?? '.', unknown: base === null, glob: false };
100
+ if (sub === 'reset' && has(p, '--hard'))
101
+ analyzer.destroy(here, 'git reset --hard');
102
+ if (sub === 'clean' && has(p, '-f', '--force'))
103
+ analyzer.destroy(here, 'git clean -f');
104
+ if (sub === 'config') {
105
+ const reads = has(p, '--get', '--get-all', '--get-regexp', '--get-urlmatch', '--list', '-l', '--show-origin');
106
+ const edits = has(p, '--add', '--unset', '--unset-all', '--replace-all', '--rename-section', '--remove-section', '-e', '--edit');
107
+ if (!reads && (edits || p.positionals.length >= 2)) {
108
+ const file = valuesOf(p, '--file', '-f')[0];
109
+ if (file)
110
+ analyzer.addPath(file, 'write', true);
111
+ else if (has(p, '--global'))
112
+ analyzer.addPath({ ...here, text: `${analyzer.ctx.homeDir}/.gitconfig` }, 'write', true);
113
+ else if (has(p, '--system'))
114
+ analyzer.addPath({ ...here, text: '/etc/gitconfig' }, 'write', true);
115
+ else
116
+ analyzer.addPath({ ...here, text: '.git/config', raw: '.git/config' }, 'write', true);
117
+ }
118
+ return;
119
+ }
120
+ for (const f of valuesOf(p, '-F', '--file'))
121
+ analyzer.addPath(f, 'read', true);
122
+ generic(ctx, p.positionals.filter((a) => !isUrl(a.text)));
123
+ }
124
+ finally {
125
+ analyzer.base = saved;
126
+ }
127
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Commands that talk to other machines: uploads (`curl -d @file`, `scp` to a
3
+ * host, publishing a package), servers and tunnels that expose the project to
4
+ * the network, and raw network tools.
5
+ */
6
+ import type { Arg } from './analyze';
7
+ import { type CommandContext } from './args';
8
+ export declare function curl(ctx: CommandContext, rest: readonly Arg[]): void;
9
+ export declare function wget(ctx: CommandContext, rest: readonly Arg[]): void;
10
+ export declare function remoteCopy(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
11
+ export declare function ssh(ctx: CommandContext, rest: readonly Arg[]): void;
12
+ /** Tunnels that put a local port on the internet. */
13
+ export declare const TUNNELS: Set<string>;
14
+ export declare function tunnel(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
15
+ /** `python -m http.server` binds every interface unless `--bind` says otherwise. */
16
+ export declare function pythonServer(ctx: CommandContext, module: string, args: readonly Arg[]): void;
17
+ /** `php -S host:port`. */
18
+ export declare function phpServer(ctx: CommandContext, rest: readonly Arg[]): void;
19
+ /** `ruby -run -e httpd`. */
20
+ export declare function rubyServer(ctx: CommandContext, rest: readonly Arg[]): void;
21
+ /** `busybox httpd -p [ip:]port`. */
22
+ export declare function busyboxServer(ctx: CommandContext, rest: readonly Arg[]): void;
23
+ /** `npm publish`, `docker push`, …: an upload. */
24
+ export declare function publishes(name: string, ctx: CommandContext, rest: readonly Arg[]): void;
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Commands that talk to other machines: uploads (`curl -d @file`, `scp` to a
3
+ * host, publishing a package), servers and tunnels that expose the project to
4
+ * the network, and raw network tools.
5
+ */
6
+ import { generic, has, parse, valuesOf } from './args';
7
+ import { isLoopbackHost, isPathLike, isRemoteSpec, isUrl } from './words';
8
+ const CURL_WITH_VALUE = new Set([
9
+ '-d',
10
+ '-F',
11
+ '-T',
12
+ '-H',
13
+ '-o',
14
+ '-u',
15
+ '-X',
16
+ '-A',
17
+ '-e',
18
+ '-b',
19
+ '-c',
20
+ '-K',
21
+ '-E',
22
+ '-x',
23
+ '-w',
24
+ '-m',
25
+ '-y',
26
+ '-Y',
27
+ '-z',
28
+ '-C',
29
+ '-r',
30
+ '-Q',
31
+ '-D',
32
+ '-U',
33
+ '-t',
34
+ '--data',
35
+ '--data-binary',
36
+ '--data-raw',
37
+ '--data-ascii',
38
+ '--data-urlencode',
39
+ '--json',
40
+ '--form',
41
+ '--form-string',
42
+ '--upload-file',
43
+ '--header',
44
+ '--output',
45
+ '--config',
46
+ '--url',
47
+ '--user',
48
+ '--request',
49
+ '--cookie',
50
+ '--cookie-jar',
51
+ '--proxy',
52
+ '--cert',
53
+ '--key',
54
+ '--cacert',
55
+ '--dump-header',
56
+ '--write-out',
57
+ '--max-time',
58
+ '--connect-timeout',
59
+ '--retry',
60
+ '--referer',
61
+ '--user-agent',
62
+ '--range',
63
+ '--resolve',
64
+ '--output-dir'
65
+ ]);
66
+ function isLocalUrl(url) {
67
+ const m = /^(?:[a-z][a-z0-9+.-]*:\/\/)?(?:[^@/]*@)?(\[[^\]]*\]|[^:/?#]*)/i.exec(url);
68
+ return isLoopbackHost(m?.[1] ?? '');
69
+ }
70
+ export function curl(ctx, rest) {
71
+ const { analyzer } = ctx;
72
+ const p = parse(rest, CURL_WITH_VALUE);
73
+ const say = (detail) => analyzer.flag('upload', `it uploads data: ${detail}`);
74
+ let dataForms = false;
75
+ for (const key of ['-d', '--data', '--data-binary', '--data-raw', '--data-ascii', '--json']) {
76
+ for (const v of p.values.get(key) ?? []) {
77
+ dataForms = true;
78
+ if (v.unknown)
79
+ say(`curl ${key} with a value from a variable or substitution`);
80
+ if (v.text.startsWith('@')) {
81
+ say(`curl ${key} ${v.text} sends a file's contents`);
82
+ if (v.text !== '@-')
83
+ analyzer.addPath({ ...v, text: v.text.slice(1) }, 'read', true);
84
+ }
85
+ }
86
+ }
87
+ for (const v of p.values.get('--data-urlencode') ?? []) {
88
+ dataForms = true;
89
+ const at = v.text.indexOf('@');
90
+ if (at >= 0) {
91
+ say(`curl --data-urlencode ${v.text} sends a file's contents`);
92
+ const file = v.text.slice(at + 1);
93
+ if (file !== '-')
94
+ analyzer.addPath({ ...v, text: file }, 'read', true);
95
+ }
96
+ }
97
+ for (const v of valuesOf(p, '-F', '--form')) {
98
+ dataForms = true;
99
+ const m = /=([@<])([^;]*)/.exec(v.text);
100
+ if (m) {
101
+ say(`curl -F ${v.text} sends a file`);
102
+ if (m[2] !== '-')
103
+ analyzer.addPath({ ...v, text: m[2] }, 'read', true);
104
+ }
105
+ }
106
+ for (const v of valuesOf(p, '-T', '--upload-file')) {
107
+ dataForms = true;
108
+ say(`curl -T ${v.text} uploads a file`);
109
+ if (v.text !== '-' && v.text !== '.')
110
+ analyzer.addPath(v, 'read', true);
111
+ }
112
+ for (const v of valuesOf(p, '-H', '--header')) {
113
+ if (v.text.startsWith('@')) {
114
+ say(`curl -H ${v.text} sends headers from a file`);
115
+ analyzer.addPath({ ...v, text: v.text.slice(1) }, 'read', true);
116
+ }
117
+ }
118
+ for (const v of valuesOf(p, '-K', '--config')) {
119
+ analyzer.dynamic(`curl ${v.text === '-' ? 'reads its options from stdin' : `reads its options from ${v.raw}`}`);
120
+ if (v.text !== '-')
121
+ analyzer.addPath(v, 'read', true);
122
+ }
123
+ for (const v of valuesOf(p, '-o', '--output', '-c', '--cookie-jar', '-D', '--dump-header')) {
124
+ if (v.text !== '-')
125
+ analyzer.addPath(v, 'write', true);
126
+ }
127
+ for (const v of valuesOf(p, '--output-dir'))
128
+ analyzer.addPath(v, 'write', true);
129
+ for (const v of valuesOf(p, '-E', '--cert', '--key', '--cacert', '-b', '--cookie')) {
130
+ if (isPathLike(v.text))
131
+ analyzer.addPath(v, 'read', true);
132
+ }
133
+ const urls = [...p.positionals, ...valuesOf(p, '--url')];
134
+ for (const u of p.positionals)
135
+ if (!isUrl(u.text) && isPathLike(u.text) && !/^[\w.-]+:\d/.test(u.text))
136
+ analyzer.operand(u);
137
+ const remote = urls.length === 0 || urls.some((u) => u.unknown || !isLocalUrl(u.text));
138
+ if (ctx.stdinFed && dataForms)
139
+ say('curl sends data it reads from stdin');
140
+ else if (ctx.stdinFed && remote)
141
+ say('curl gets piped input and talks to a remote host');
142
+ }
143
+ export function wget(ctx, rest) {
144
+ const { analyzer } = ctx;
145
+ const p = parse(rest, new Set(['-O', '-o', '-a', '-P', '-i', '--post-file', '--body-file', '--post-data', '--body-data', '--output-document', '--input-file']));
146
+ for (const v of valuesOf(p, '--post-file', '--body-file')) {
147
+ analyzer.flag('upload', `it uploads data: wget sends ${v.raw}`);
148
+ analyzer.addPath(v, 'read', true);
149
+ }
150
+ // Like curl -d: a body built from a variable may carry anything.
151
+ for (const key of ['--post-data', '--body-data']) {
152
+ for (const v of p.values.get(key) ?? []) {
153
+ if (v.unknown)
154
+ analyzer.flag('upload', `it uploads data: wget ${key} with a value from a variable or substitution`);
155
+ }
156
+ }
157
+ for (const v of valuesOf(p, '-O', '--output-document', '-o', '-a', '-P')) {
158
+ if (v.text !== '-')
159
+ analyzer.addPath(v, 'write', true);
160
+ }
161
+ for (const v of valuesOf(p, '-i', '--input-file'))
162
+ if (v.text !== '-')
163
+ analyzer.addPath(v, 'read', true);
164
+ const remote = p.positionals.length === 0 || p.positionals.some((u) => u.unknown || !isLocalUrl(u.text));
165
+ if (ctx.stdinFed && remote)
166
+ analyzer.flag('upload', 'it uploads data: wget gets piped input and talks to a remote host');
167
+ }
168
+ export function remoteCopy(name, ctx, rest) {
169
+ const { analyzer } = ctx;
170
+ const withValue = name === 'scp'
171
+ ? new Set(['-i', '-F', '-P', '-o', '-c', '-l', '-S', '-J'])
172
+ : new Set(['-e', '--rsh', '--exclude', '--include', '--exclude-from', '--include-from', '--files-from', '-f', '--filter']);
173
+ const p = parse(rest, withValue);
174
+ for (const v of valuesOf(p, '-i', '-F', '--exclude-from', '--include-from', '--files-from')) {
175
+ if (v.text === '-')
176
+ analyzer.flag('stdin-operands', `${name} takes file names from its input, which cannot be checked before it runs`);
177
+ else
178
+ analyzer.addPath(v, 'read', true);
179
+ }
180
+ const ops = p.positionals;
181
+ if (ops.length === 0)
182
+ return;
183
+ const dest = ops[ops.length - 1];
184
+ const sources = ops.slice(0, -1);
185
+ if (isRemoteSpec(dest.text) || dest.unknown) {
186
+ analyzer.flag('upload', `it uploads data: ${name} copies to the remote ${dest.raw}`);
187
+ }
188
+ else {
189
+ analyzer.addPath(dest, 'write', true);
190
+ }
191
+ for (const s of sources)
192
+ if (!isRemoteSpec(s.text))
193
+ analyzer.addPath(s, 'read', true);
194
+ }
195
+ export function ssh(ctx, rest) {
196
+ const { analyzer } = ctx;
197
+ const p = parse(rest, new Set(['-i', '-F', '-o', '-p', '-l', '-J', '-L', '-R', '-D', '-E', '-S', '-W', '-b', '-c', '-e', '-m', '-O', '-Q', '-w']));
198
+ for (const v of valuesOf(p, '-i', '-F'))
199
+ analyzer.addPath(v, 'read', true);
200
+ if (has(p, '-R'))
201
+ expose(ctx, 'ssh -R forwards a port from a remote host to this machine');
202
+ if (ctx.stdinFed)
203
+ analyzer.flag('upload', 'it uploads data: ssh gets piped input');
204
+ }
205
+ function expose(ctx, what) {
206
+ ctx.analyzer.flag('network-exposure', `it exposes this machine to the network: ${what}`);
207
+ }
208
+ /** Tunnels that put a local port on the internet. */
209
+ export const TUNNELS = new Set(['ngrok', 'cloudflared', 'localtunnel', 'lt']);
210
+ export function tunnel(name, ctx, rest) {
211
+ expose(ctx, `${name} opens a public tunnel to a local port`);
212
+ generic(ctx, rest.filter((a) => isPathLike(a.text)));
213
+ }
214
+ /** The value of one option, as `-b X`, `-bX`, `--bind X` or `--bind=X`. */
215
+ function optionValue(rest, short, long) {
216
+ for (let k = 0; k < rest.length; k++) {
217
+ const t = rest[k].text;
218
+ if (t === short || t === long)
219
+ return rest[k + 1]?.text ?? '';
220
+ if (long && t.startsWith(`${long}=`))
221
+ return t.slice(long.length + 1);
222
+ if (short && t.startsWith(short) && t.length > short.length && !t.startsWith('--'))
223
+ return t.slice(short.length);
224
+ }
225
+ return undefined;
226
+ }
227
+ /** The host of `host:port`, `[::1]:port` or a bare host. */
228
+ function hostOf(address) {
229
+ const v6 = /^\[([^\]]*)\]/.exec(address);
230
+ if (v6)
231
+ return v6[1];
232
+ const colon = address.lastIndexOf(':');
233
+ return colon > 0 && address.indexOf(':') === colon ? address.slice(0, colon) : address;
234
+ }
235
+ /** A dev server that serves files on an address: asks unless it is loopback only. */
236
+ function serves(ctx, what, address) {
237
+ if (address !== undefined && address !== '' && isLoopbackHost(hostOf(address)))
238
+ return;
239
+ expose(ctx, `${what} serves files on ${address ? hostOf(address) : 'every network interface'}`);
240
+ }
241
+ /** `python -m http.server` binds every interface unless `--bind` says otherwise. */
242
+ export function pythonServer(ctx, module, args) {
243
+ if (module === 'SimpleHTTPServer')
244
+ serves(ctx, 'python -m SimpleHTTPServer', undefined);
245
+ else if (module === 'http.server')
246
+ serves(ctx, 'python -m http.server', optionValue(args, '-b', '--bind'));
247
+ }
248
+ /** `php -S host:port`. */
249
+ export function phpServer(ctx, rest) {
250
+ const address = optionValue(rest, '-S', null);
251
+ if (address !== undefined)
252
+ serves(ctx, 'php -S', address);
253
+ }
254
+ /** `ruby -run -e httpd`. */
255
+ export function rubyServer(ctx, rest) {
256
+ const un = rest.some((a, k) => a.text === '-run' || (a.text === '-r' && rest[k + 1]?.text === 'un'));
257
+ if (un && rest.some((a) => a.text === 'httpd'))
258
+ serves(ctx, 'ruby -run -e httpd', optionValue(rest, null, '--bind-address'));
259
+ }
260
+ /** `busybox httpd -p [ip:]port`. */
261
+ export function busyboxServer(ctx, rest) {
262
+ const port = optionValue(rest, '-p', null);
263
+ serves(ctx, 'busybox httpd', port !== undefined && port.includes(':') ? port : undefined);
264
+ }
265
+ /** Commands that send a package or an image to a registry, by program, and the subcommand that does. */
266
+ const PUBLISH = new Map([
267
+ ['npm', 'publish'],
268
+ ['pnpm', 'publish'],
269
+ ['yarn', 'publish'],
270
+ ['bun', 'publish'],
271
+ ['gem', 'push'],
272
+ ['twine', 'upload'],
273
+ ['cargo', 'publish'],
274
+ ['docker', 'push'],
275
+ ['podman', 'push']
276
+ ]);
277
+ /** `npm publish`, `docker push`, …: an upload. */
278
+ export function publishes(name, ctx, rest) {
279
+ const sub = PUBLISH.get(name);
280
+ if (sub && rest.some((a) => a.text === sub))
281
+ ctx.analyzer.flag('upload', `it uploads data: ${name} ${sub} sends it to a registry`);
282
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Quoting and bracket matching for the lexer: where a quote, a substitution or
3
+ * a `${…}` ends, and how `$'…'` decodes. Every helper throws `LexError` on
4
+ * input that does not close, and the lexer turns that into `shell-dynamic`.
5
+ */
6
+ export declare class LexError extends Error {
7
+ }
8
+ /** Find the `)` that closes a `(` at `open`, skipping quotes and nested parens. */
9
+ export declare function matchParen(s: string, open: number): number;
10
+ export declare function matchBacktick(s: string, open: number): number;
11
+ export declare function matchBrace(s: string, open: number): number;
12
+ /** Decode a `$'…'` body (ANSI-C quoting), so `$'\x72m'` reads as `rm`. */
13
+ export declare function decodeAnsiC(body: string): string;
14
+ export declare function findAnsiClose(s: string, from: number): number;
15
+ export declare function unescapeBackticks(inner: string): string;
16
+ export declare function stripQuotes(text: string): string;