passport-bridge 0.26.0 → 0.27.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 (42) hide show
  1. package/README.md +2 -2
  2. package/dist/blindKind.d.ts +15 -0
  3. package/dist/blindKind.js +5 -0
  4. package/dist/cliChanges.d.ts +12 -4
  5. package/dist/cliChanges.js +26 -15
  6. package/dist/cliGuardState.js +2 -2
  7. package/dist/cliHookBlind.d.ts +15 -0
  8. package/dist/cliHookBlind.js +65 -0
  9. package/dist/cliHookLocal.d.ts +7 -16
  10. package/dist/cliHookLocal.js +75 -97
  11. package/dist/cliHookLocalCode.js +7 -1
  12. package/dist/cliHookLocalFs.d.ts +15 -0
  13. package/dist/cliHookLocalFs.js +77 -0
  14. package/dist/cliHookScripts.d.ts +2 -1
  15. package/dist/cliOutput.js +2 -2
  16. package/dist/cliProjectSummary.d.ts +1 -1
  17. package/dist/cliProjectSummary.js +19 -8
  18. package/dist/cliScriptRead.d.ts +5 -4
  19. package/dist/cliScriptRead.js +3 -2
  20. package/dist/cliSeen.d.ts +24 -15
  21. package/dist/cliSeen.js +34 -16
  22. package/dist/cliSessions.js +20 -6
  23. package/dist/cliSessionsJson.d.ts +48 -0
  24. package/dist/cliSessionsJson.js +40 -10
  25. package/dist/cliSessionsRender.d.ts +4 -0
  26. package/dist/cliSessionsRender.js +42 -8
  27. package/dist/inlineCode.d.ts +35 -0
  28. package/dist/inlineCode.js +201 -0
  29. package/dist/inlineScan.d.ts +23 -0
  30. package/dist/inlineScan.js +389 -0
  31. package/dist/localCommands.d.ts +10 -3
  32. package/dist/localCommands.js +59 -37
  33. package/dist/localFiles.d.ts +38 -2
  34. package/dist/localFiles.js +453 -33
  35. package/dist/localGit.js +53 -17
  36. package/dist/localShared.d.ts +3 -0
  37. package/dist/pluginPin.d.ts +1 -1
  38. package/dist/pluginPin.js +1 -1
  39. package/dist/version.d.ts +1 -1
  40. package/dist/version.js +1 -1
  41. package/npm-shrinkwrap.json +2 -2
  42. package/package.json +1 -1
@@ -0,0 +1,389 @@
1
+ /**
2
+ * The side-effect scan behind `inlineCode.ts`: does a one-liner's code only
3
+ * read? Each scanner returns the first construct that could write, run, load,
4
+ * or reach the network (a reason that names the construct, never the code),
5
+ * or null, and collects the string literals so the caller can place paths.
6
+ *
7
+ * Python's strings and comments tokenize reliably, so names are matched with
8
+ * string contents set aside (f-string contents stay in, they hold code).
9
+ * JavaScript, Perl, and Ruby have regex literals and quote-like operators a
10
+ * small scanner can misread, which could hide a call inside what looks like
11
+ * a string, so their names are matched against the raw code. Imports are
12
+ * allow-listed; everything else is a deny list. When in doubt: blind.
13
+ */
14
+ /** Strings in the code as written, for the caller's path check (best effort, raw). */
15
+ export function quotedStrings(code) {
16
+ const out = [];
17
+ const pattern = /(['"`])((?:\\.|(?!\1)[^\\\n])*)\1/g;
18
+ for (let match = pattern.exec(code); match; match = pattern.exec(code))
19
+ out.push(match[2]);
20
+ return out;
21
+ }
22
+ // ---- Python ------------------------------------------------------------------
23
+ /** Modules a read-only one-liner may import. Anything else is blind. */
24
+ const PYTHON_MODULES = new Set(("json sys os re math cmath statistics random hashlib hmac base64 binascii zlib gzip bz2 lzma struct codecs " +
25
+ "collections itertools functools operator datetime time calendar string textwrap difflib unicodedata pprint " +
26
+ "reprlib typing dataclasses enum decimal fractions numbers copy heapq bisect array uuid glob fnmatch pathlib csv " +
27
+ "io html xml tomllib configparser shlex argparse platform locale contextlib abc inspect ast tokenize keyword " +
28
+ "zipfile tarfile email mimetypes secrets colorsys graphlib ipaddress quopri traceback warnings linecache " +
29
+ "filecmp stat queue PIL numpy yaml toml tomli dateutil pytz tabulate").split(" "));
30
+ /** `os.<name>` a read may use. */
31
+ const OS_READS = new Set(("path listdir scandir walk getcwd getcwdb environ getenv sep altsep linesep pathsep curdir pardir extsep devnull " +
32
+ "name stat lstat cpu_count getpid getppid fspath fsencode fsdecode get_terminal_size access readlink urandom " +
33
+ "uname getlogin getuid getgid geteuid getegid getgroups times strerror isatty terminal_size PathLike DirEntry " +
34
+ "stat_result R_OK W_OK X_OK F_OK").split(" "));
35
+ /** `sys.<name>` a read may use. */
36
+ const SYS_READS = new Set(("argv stdin stdout stderr exit version version_info platform maxsize byteorder getsizeof getrecursionlimit " +
37
+ "setrecursionlimit getdefaultencoding getfilesystemencoding executable implementation float_info int_info " +
38
+ "hexversion flags").split(" "));
39
+ const PYTHON_DENIED = [
40
+ [/\b(exec|eval|compile|__import__|getattr|setattr|delattr|globals|locals|vars|breakpoint|help)\s*\(/, "runs code"],
41
+ [
42
+ /\b(__builtins__|__dict__|__class__|__subclasses__|__globals__|__code__|__bases__|__mro__|__loader__)\b/,
43
+ "runs code"
44
+ ],
45
+ [/\bos\s*\.\s*environ\s*(\[[^\]]*\]\s*=(?!=)|\.\s*(update|setdefault|pop|clear)\b)/, "changes the environment"],
46
+ [
47
+ /\.\s*(write_text|write_bytes|unlink|mkdir|touch|rmdir|chmod|lchmod|symlink_to|hardlink_to|link_to|extractall|extract|save|savefig|savetxt|savez\w*|to_csv|to_json|to_excel|to_parquet|to_pickle|to_sql|to_hdf|to_feather|dump|tofile|unsafe_load)\s*\(/,
48
+ "writes a file"
49
+ ],
50
+ [/\bLoader\s*=|\ballow_pickle\b/, "runs code"],
51
+ [/\.\s*show\s*\(/, "runs a program"],
52
+ [/\benviron\s*(\[[^\]]*\]\s*=(?!=)|\.\s*(update|setdefault|pop|clear)\b)/, "changes the environment"],
53
+ [/\b(expanduser|expandvars)\b|\bPath\s*\.\s*home\b/, "reads outside the project"]
54
+ ];
55
+ /** Python with strings set aside (as `"<n>"`) and comments removed. */
56
+ function pythonTokens(source) {
57
+ let code = "";
58
+ const strings = [];
59
+ for (let at = 0; at < source.length; at++) {
60
+ const char = source[at];
61
+ if (char === "#") {
62
+ while (at < source.length && source[at] !== "\n")
63
+ at++;
64
+ code += "\n";
65
+ continue;
66
+ }
67
+ if (char !== "'" && char !== '"') {
68
+ code += char;
69
+ continue;
70
+ }
71
+ const prefix = /[rRbBuUfF]{0,2}$/.exec(code)[0];
72
+ const formatted = /f/i.test(prefix) && !/\w/.test(code[code.length - prefix.length - 1] ?? "");
73
+ const triple = source.startsWith(char.repeat(3), at);
74
+ const quote = triple ? char.repeat(3) : char;
75
+ let end = at + quote.length;
76
+ for (; end < source.length; end++) {
77
+ if (source[end] === "\\")
78
+ end++;
79
+ else if (source.startsWith(quote, end))
80
+ break;
81
+ else if (!triple && source[end] === "\n")
82
+ return null;
83
+ }
84
+ if (end >= source.length)
85
+ return null;
86
+ const text = source.slice(at + quote.length, end);
87
+ strings.push(text);
88
+ // An f-string's braces hold code: keep its text where names are matched.
89
+ code += `"${strings.length - 1}"${formatted ? ` ${text.replace(/['"]/g, " ")} ` : ""}`;
90
+ at = end + quote.length - 1;
91
+ }
92
+ return { code, strings };
93
+ }
94
+ /** The arguments of each call to `name(` in tokenized code, split at top-level commas. */
95
+ function callArguments(code, name) {
96
+ const calls = [];
97
+ for (let match = name.exec(code); match; match = name.exec(code)) {
98
+ let depth = 0;
99
+ let current = "";
100
+ const args = [];
101
+ for (let at = match.index + match[0].length; at < code.length; at++) {
102
+ const char = code[at];
103
+ if ("([{".includes(char))
104
+ depth++;
105
+ if (")]}".includes(char) && depth-- === 0)
106
+ break;
107
+ if (char === "," && depth === 0) {
108
+ args.push(current.trim());
109
+ current = "";
110
+ }
111
+ else
112
+ current += char;
113
+ }
114
+ if (current.trim())
115
+ args.push(current.trim());
116
+ calls.push(args);
117
+ }
118
+ return calls;
119
+ }
120
+ const MODE = /^[rwabxtU+]{1,4}$/;
121
+ /** `open(path, mode)` and friends: a mode that writes, or one Passport can't see. */
122
+ function pythonOpen(code, strings) {
123
+ for (const args of callArguments(code, /(?:\b|\.)(open|ZipFile|TarFile|FileIO)\s*\(/g)) {
124
+ for (const [index, arg] of args.entries()) {
125
+ const keyword = /^(\w+)\s*=\s*([\s\S]*)$/.exec(arg);
126
+ if (keyword && keyword[1] !== "mode")
127
+ continue;
128
+ const id = /^"(\d+)"$/.exec(keyword ? keyword[2] : arg)?.[1];
129
+ const text = id === undefined ? null : strings[Number(id)];
130
+ // The first argument is a path, except `Path(…).open("w")`, where it is the mode.
131
+ const mode = keyword || index > 0 ? text !== null && /^[^/.\s]{1,8}$/.test(text) : text !== null && MODE.test(text);
132
+ if (mode && /[wax+]/.test(text))
133
+ return "writes a file";
134
+ if ((keyword || index === 1) && text === null)
135
+ return "opens a file in a mode Passport can't see";
136
+ }
137
+ }
138
+ return null;
139
+ }
140
+ /** Import statements: `import a, b as c` and `from a.b import c`. */
141
+ const PYTHON_IMPORT = /(?:^|[\n;:])\s*(?:from\s+([\w.]+)\s+import\s+([^\n;]+)|import\s+([^\n;]+))/g;
142
+ export function scanPython(source, shadowed) {
143
+ const tokens = pythonTokens(source);
144
+ if (!tokens)
145
+ return { problem: "code Passport can't read", strings: [], modules: [] };
146
+ const { code, strings } = tokens;
147
+ const modules = [];
148
+ const result = (problem) => ({ problem, strings, modules });
149
+ for (const match of code.matchAll(PYTHON_IMPORT)) {
150
+ const names = match[1] ? [match[1]] : match[3].split(",").map((part) => part.trim());
151
+ for (const entry of names) {
152
+ if (/\sas\s/.test(entry) && /^(os|sys)\b/.test(entry))
153
+ return result("renames a module");
154
+ const top = entry.split(/[\s.]/)[0];
155
+ if (!PYTHON_MODULES.has(top))
156
+ return result(`imports ${/^\w+$/.test(top) ? top : "a module"}`);
157
+ if (shadowed(top))
158
+ return result(`a project file shadows ${top}`);
159
+ modules.push(top);
160
+ }
161
+ if (match[1] && /^(os|sys)$/.test(match[1])) {
162
+ const allowed = match[1] === "os" ? OS_READS : SYS_READS;
163
+ const imported = match[2].replace(/[()]/g, "").split(",");
164
+ if (imported.some((name) => !allowed.has(name.trim().split(/\s/)[0])))
165
+ return result(`uses ${match[1]} beyond reads`);
166
+ }
167
+ }
168
+ const body = code.replace(PYTHON_IMPORT, "\n");
169
+ if (/\bimport\b/.test(body))
170
+ return result("imports a module");
171
+ for (const [pattern, reason] of PYTHON_DENIED)
172
+ if (pattern.test(body))
173
+ return result(reason);
174
+ // `os` and `sys` only as `os.<read>` / `sys.<read>`.
175
+ for (const [module, allowed] of [
176
+ ["os", OS_READS],
177
+ ["sys", SYS_READS]
178
+ ]) {
179
+ for (const match of body.matchAll(new RegExp(`(\\.\\s*)?\\b${module}\\b(\\s*\\.\\s*(\\w+))?`, "g"))) {
180
+ if (match[1])
181
+ continue;
182
+ if (!match[3] || !allowed.has(match[3]))
183
+ return result(`uses ${module}${match[3] ? `.${match[3]}` : ""}`);
184
+ }
185
+ }
186
+ // pathlib's rename/replace collide with str methods: only with pathlib in use.
187
+ if (/\bPath\b|\bpathlib\b/.test(code) && /\.\s*(rename|replace)\s*\(/.test(body))
188
+ return result("writes a file");
189
+ if (strings.some((text) => text === "HOME" || text === "USERPROFILE"))
190
+ return result("reads outside the project");
191
+ return result(pythonOpen(body, strings));
192
+ }
193
+ // ---- JavaScript --------------------------------------------------------------
194
+ /** Node builtins a read may load (with or without `node:`). */
195
+ const NODE_MODULES = new Set(("fs fs/promises path path/posix path/win32 os util crypto url querystring string_decoder buffer events stream " +
196
+ "stream/promises zlib assert assert/strict readline readline/promises timers timers/promises perf_hooks process console").split(" "));
197
+ /** `fs.<name>` a read may use. */
198
+ const FS_READS = new Set(("readFileSync readFile readdirSync readdir statSync stat lstatSync lstat existsSync exists accessSync access " +
199
+ "realpathSync realpath readlinkSync readlink createReadStream constants promises opendirSync opendir openSync " +
200
+ "open closeSync close readSync read fstatSync fstat Dirent Stats watch watchFile").split(" "));
201
+ const NODE_DENIED = [
202
+ [/\bchild_process\b/, "runs a command"],
203
+ [
204
+ /\b(writeFile\w*|appendFile\w*|unlink\w*|rmSync|rmdir\w*|rename\w*|mkdir\w*|mkdtemp\w*|chmod\w*|lchmod\w*|fchmod\w*|chown\w*|lchown\w*|fchown\w*|copyFile\w*|cpSync|createWriteStream|truncate\w*|ftruncate\w*|symlink\w*|linkSync|utimes\w*|lutimes\w*|futimes\w*)\b|\b(rm|cp|link)\s*\(/,
205
+ "writes a file"
206
+ ],
207
+ [/\b(eval|Function|fetch)\s*\(|\bnew\s+Function\b/, "runs code"],
208
+ [
209
+ /\b(constructor|__proto__|prototype|globalThis|global|Reflect|Proxy|WebAssembly|Deno|Bun)\b|\bimport\s*\.\s*meta\b/,
210
+ "runs code"
211
+ ],
212
+ [/\b(WebSocket|XMLHttpRequest|EventSource|navigator)\b/, "reaches the network"],
213
+ [
214
+ /\bprocess\s*(\[|\.\s*(kill|binding|_linkedBinding|dlopen|chdir|mainModule|setuid|setgid|abort|send|emit|on)\b)/,
215
+ "controls a process"
216
+ ],
217
+ [
218
+ /\bprocess\s*\.\s*env\s*(\.\s*\w+|\[[^\]]*\])\s*(=(?!=)|\+\+|--)|delete\s+process\.env|assign\s*\(\s*process\.env/,
219
+ "changes the environment"
220
+ ],
221
+ [/\b(homedir|userInfo)\s*\(|\benv\s*\.\s*(HOME|USERPROFILE)\b/, "reads outside the project"]
222
+ ];
223
+ /** A required module: a builtin, or a JSON file by relative path (parsed, never run; the caller places it). */
224
+ function nodeModule(name) {
225
+ const bare = name.replace(/^node:/, "");
226
+ if (NODE_MODULES.has(bare) || /^\.{1,2}\/[^'"`]*\.json$/.test(name))
227
+ return null;
228
+ return `loads ${bare.startsWith(".") || bare.startsWith("/") ? "a file" : "a module"}`;
229
+ }
230
+ /** How `require("fs")` / `import … from "fs"` is bound: a name to follow, `ok` for
231
+ * read-only names or a direct read, or `bad`. */
232
+ function fsBinding(code, index, keyword, rest) {
233
+ const whole = /^\s*\(\s*['"][^'"]+['"]\s*\)\s*(;|,|\n|$)/.test(rest);
234
+ const bound = whole ? /(?:const|let|var)\s+(\w+|\{[^}]*\})\s*=\s*$/.exec(code.slice(0, index)) : null;
235
+ const imported = keyword === "import" ? /^\s+(?:\*\s+as\s+)?(\w+|\{[^}]*\})\s+from/.exec(rest) : null;
236
+ const binding = bound?.[1] ?? imported?.[1];
237
+ if (binding?.startsWith("{")) {
238
+ const names = binding
239
+ .slice(1, -1)
240
+ .split(",")
241
+ .map((part) => part.trim().split(/\s*(?::|\sas\s)\s*/)[0]);
242
+ return names.every((name) => !name || FS_READS.has(name)) ? "ok" : "bad";
243
+ }
244
+ if (binding)
245
+ return binding;
246
+ // `require("fs").readFileSync(…)`.
247
+ const member = /^\s*\(\s*['"][^'"]+['"]\s*\)\s*\.\s*(\w+)/.exec(rest)?.[1];
248
+ return member && FS_READS.has(member) ? "ok" : "bad";
249
+ }
250
+ /** Every use of a name bound to fs is `fs.<read>` (and `fs.promises.<read>`). */
251
+ function fsUsesRead(code, name) {
252
+ for (const match of code.matchAll(new RegExp(`\\b${name}\\b`, "g"))) {
253
+ const before = code.slice(0, match.index);
254
+ const after = code.slice(match.index + name.length);
255
+ // The module's own name inside require("fs") or "node:fs/promises", and the binding itself.
256
+ if (/['"`:/]$/.test(before) || /^['"`/]/.test(after))
257
+ continue;
258
+ if (/^\s*=\s*(require|await\s+import)\b/.test(after) || /(\bas|const|let|var|import)\s+$/.test(before))
259
+ continue;
260
+ const chain = /^\s*\.\s*(\w+)(?:\s*\.\s*(\w+))?/.exec(after);
261
+ if (!chain || !FS_READS.has(chain[1]))
262
+ return false;
263
+ if (chain[1] === "promises" && (!chain[2] || !FS_READS.has(chain[2])))
264
+ return false;
265
+ }
266
+ return true;
267
+ }
268
+ export function scanNode(code) {
269
+ const strings = quotedStrings(code);
270
+ const modules = [];
271
+ const result = (problem) => ({ problem, strings, modules });
272
+ for (const [pattern, reason] of NODE_DENIED)
273
+ if (pattern.test(code))
274
+ return result(reason);
275
+ // Loading code: require("x"), import("x"), import … from "x", import "x".
276
+ for (const load of code.matchAll(/\b(require|import)\b/g)) {
277
+ const rest = code.slice(load.index + load[0].length);
278
+ const call = /^\s*\(\s*(['"])([^'"`]+)\1\s*\)/.exec(rest);
279
+ const from = load[1] === "import" ? /^(?:\s+[\w*{},\s]+?\s+from)?\s*(['"])([^'"`]+)\1/.exec(rest) : null;
280
+ const target = call ?? from;
281
+ if (!target)
282
+ return result("loads code Passport can't see");
283
+ const problem = nodeModule(target[2]);
284
+ if (problem)
285
+ return result(problem);
286
+ modules.push(target[2]);
287
+ if (!/^(node:)?fs(\/promises)?$/.test(target[2]))
288
+ continue;
289
+ const binding = fsBinding(code, load.index, load[1], rest);
290
+ if (binding === "bad" || (binding !== "ok" && !fsUsesRead(code, binding)))
291
+ return result("uses fs beyond reads");
292
+ }
293
+ for (const args of callArguments(code, /\bopen(?:Sync)?\s*\(/g)) {
294
+ const flag = args[1];
295
+ if (flag === undefined)
296
+ continue;
297
+ const literal = /^(['"`])([^'"`]*)\1$/.exec(flag);
298
+ if (!literal || /[wa+]/.test(literal[2]))
299
+ return result("writes a file");
300
+ }
301
+ if (strings.some((text) => text === "HOME" || text === "USERPROFILE"))
302
+ return result("reads outside the project");
303
+ return result(null);
304
+ }
305
+ // ---- Perl and Ruby -----------------------------------------------------------
306
+ const PERL_MODULES = new Set(("strict warnings utf8 feature constant integer bigint bignum List::Util Scalar::Util Data::Dumper JSON::PP " +
307
+ "Digest::MD5 Digest::SHA MIME::Base64 File::Basename File::Spec File::Spec::Functions Time::Local Time::HiRes " +
308
+ "Encode Text::Wrap Text::Tabs Getopt::Long Getopt::Std Term::ANSIColor English Carp Cwd Math::BigInt " +
309
+ "Math::BigFloat Math::Trig Unicode::Normalize charnames").split(" "));
310
+ const PERL_DENIED = [
311
+ [/`|\b(system|exec|qx|readpipe|fork|wait|waitpid|kill|syscall|pipe|alarm)\b/, "runs a command"],
312
+ [
313
+ /\b(unlink|rename|mkdir|rmdir|chmod|chown|utime|truncate|link|symlink|sysopen|dbmopen|chdir|chroot|umask)\b/,
314
+ "writes a file"
315
+ ],
316
+ [/\b(socket|connect|bind|listen|accept|send|recv|gethostbyname)\b/, "reaches the network"],
317
+ [/\beval\b|\bdo\s+(?!\{)|\bCORE::|&\s*\{|\*\s*\{|\$\s*\{\s*["'$]/, "runs code"],
318
+ [/[/|#!}][gimosxpdualncr]*e[gimosxpdualncre]*(?=\s*(?:;|\)|\}|$))/, "runs code"],
319
+ [/(\$|%)ENV\b[^;]*?(=(?![=~])|\bdelete\b)|\bdelete\s+\$ENV/, "changes the environment"],
320
+ [
321
+ /@ARGV\s*=(?!=)|\$ARGV\s*\[[^\]]*\]\s*=(?!=)|\b(push|unshift|splice)\b[^;]*@ARGV|\$SIG\b|%SIG\b/,
322
+ "changes what it reads"
323
+ ],
324
+ [/ENV\s*\{\s*['"]?HOME\b|\bgetpw(uid|nam)\b|\bglob\s*\(\s*['"]~/, "reads outside the project"]
325
+ ];
326
+ const RUBY_MODULES = new Set("json set digest digest/md5 digest/sha1 digest/sha2 base64 time date pp stringio securerandom optparse English bigdecimal shellwords ostruct benchmark yaml psych csv".split(" "));
327
+ const RUBY_DENIED = [
328
+ [
329
+ /`|%x|\b(system|exec|spawn|fork|syscall|trap)\b|\bexit!|\b(IO\s*\.\s*(popen|sysopen)|Open3|Process|Kernel|PTY)\b/,
330
+ "runs a command"
331
+ ],
332
+ [
333
+ /\b(File|IO)\s*\.\s*(write|binwrite|delete|unlink|rename|chmod|lchmod|chown|lchown|symlink|link|truncate|utime|mkfifo|copy_stream)\b|\bFileUtils\b|\bDir\s*\.\s*(mkdir|rmdir|delete|unlink|chdir|chroot)\b/,
334
+ "writes a file"
335
+ ],
336
+ [
337
+ /\bPathname\b[\s\S]*\.\s*(write|binwrite|delete|unlink|rename|mkpath|mkdir|rmtree|rmdir|make_symlink|make_link|chmod|truncate)\b/,
338
+ "writes a file"
339
+ ],
340
+ [/\b(Net|Socket|TCPSocket|UDPSocket|TCPServer|UNIXSocket|URI\s*\.\s*open|OpenURI)\b|open-uri/, "reaches the network"],
341
+ [
342
+ /\b(eval|instance_eval|class_eval|module_eval|instance_exec|class_exec|send|__send__|public_send|method|define_method|const_get|binding|ObjectSpace|unsafe_load|Marshal|ERB)\b/,
343
+ "runs code"
344
+ ],
345
+ [/\bENV\s*(\[[^\]]*\]\s*=(?!=)|\.\s*(store|delete|update|replace|clear)\b)/, "changes the environment"],
346
+ [
347
+ /\bARGV\s*(<<|\.\s*(push|unshift|replace|insert|concat)|\[[^\]]*\]\s*=(?!=))|\bDir\s*\.\s*home\b|ENV\s*\[\s*['"]HOME/,
348
+ "reads outside the project"
349
+ ]
350
+ ];
351
+ /** `open` in Perl: only a read (`'<'` mode, no `>`, `|`, `+<`); in Ruby: a literal file, read mode. */
352
+ function scriptOpen(code, language) {
353
+ for (const match of code.matchAll(/\b(?:File\s*\.\s*(?:open|new)|open)\b/g)) {
354
+ const statement = code.slice(match.index + match[0].length).split(/[;\n]/)[0];
355
+ if (/[>|]|\+</.test(statement))
356
+ return "writes a file or runs a command";
357
+ if (language === "perl" && !/['"]<(:[\w()-]+)?['"]/.test(statement))
358
+ return "opens a file Passport can't see";
359
+ if (language === "ruby") {
360
+ const args = /^\s*\(?\s*(['"])([^'"]*)\1\s*(?:,\s*(['"])([^'"]*)\3)?/.exec(statement);
361
+ if (!args || (args[4] !== undefined && /[wa+]/.test(args[4])))
362
+ return "opens a file Passport can't see";
363
+ }
364
+ }
365
+ return null;
366
+ }
367
+ export function scanScript(code, language) {
368
+ const strings = quotedStrings(code);
369
+ const modules = [];
370
+ const result = (problem) => ({ problem, strings, modules });
371
+ for (const [pattern, reason] of language === "perl" ? PERL_DENIED : RUBY_DENIED) {
372
+ if (pattern.test(code))
373
+ return result(reason);
374
+ }
375
+ const loads = language === "perl"
376
+ ? /\b(?:use|no|require)\b\s*([^\s;()]+)/g
377
+ : /\b(?:require|require_relative|load|autoload)\b\s*\(?\s*(?:(['"])([^'"]+)\1|(\S+))/g;
378
+ for (const match of code.matchAll(loads)) {
379
+ const name = language === "perl" ? match[1] : match[2];
380
+ if (language === "perl" && /^v?\d/.test(name))
381
+ continue;
382
+ if (!name ||
383
+ !(language === "perl" ? PERL_MODULES : RUBY_MODULES).has(name) ||
384
+ match[0].startsWith("require_relative"))
385
+ return result(`loads ${name ?? "a module"}`);
386
+ modules.push(name);
387
+ }
388
+ return result(scriptOpen(code, language));
389
+ }
@@ -24,9 +24,16 @@ export type { CommandContext, LocalAction, LocalClass, LocalEnvironment, LocalOu
24
24
  export { isIrreversibleLocalVerb, writeOf } from "./localShared.js";
25
25
  export { safeSedScript } from "./localFiles.js";
26
26
  export { gitVerdict, pushPlace } from "./localGit.js";
27
- /** Environment variables a command may set and still be decided. */
28
- export declare const SAFE_ENV: Set<string>;
29
- /** Strip assignments and wrappers. `null` when an assignment isn't one Passport can see past. */
27
+ /**
28
+ * Environment variables that change what runs or how: the program found, the
29
+ * code it loads, its config, its shell, or where it writes. Setting one leaves
30
+ * the command unknown. A trailing `*` matches any suffix. Any other assignment
31
+ * (`FOO=bar cmd`, `VAR=$(…)`) is neutral; a `$(…)` value is read as nested text.
32
+ */
33
+ export declare const RUNTIME_ENV: string[];
34
+ /** Why setting `name` leaves a command unknown, or null when it is neutral. */
35
+ export declare function envReason(name: string): string | null;
36
+ /** Strip assignments and wrappers. `reason` when an assignment changes what runs (`envReason`). */
30
37
  export declare function unwrap(words: ShellWord[]): {
31
38
  words: ShellWord[];
32
39
  sudo: boolean;
@@ -20,40 +20,60 @@
20
20
  * (generated copy, `rules test`).
21
21
  */
22
22
  import { R, pythonModuleAnswer, toolAnswer } from "./localTools.js";
23
- import { copyLike, fd, find, ripgrep, rsync, sed, tar, unzip, zip } from "./localFiles.js";
23
+ import { awk, copyLike, fd, find, perlSubstitution, ripgrep, rsync, sed, tar, unzip, zip } from "./localFiles.js";
24
24
  import { git } from "./localGit.js";
25
25
  import { curl, wget } from "./localNetwork.js";
26
26
  import { DELETERS, MODE_CHANGERS, WRITERS, fromVerdict, local, operands, readOf, recursiveFlag, unknown, writeOf } from "./localShared.js";
27
27
  export { isIrreversibleLocalVerb, writeOf } from "./localShared.js";
28
28
  export { safeSedScript } from "./localFiles.js";
29
29
  export { gitVerdict, pushPlace } from "./localGit.js";
30
- /** Environment variables a command may set and still be decided. */
31
- export const SAFE_ENV = new Set([
32
- "CI",
33
- "NODE_ENV",
34
- "FORCE_COLOR",
35
- "NO_COLOR",
36
- "TERM",
37
- "COLUMNS",
38
- "LANG",
39
- "LC_ALL",
40
- "TZ",
41
- "DEBUG",
42
- "RUST_BACKTRACE",
43
- "RUST_LOG",
44
- "PYTHONUNBUFFERED",
45
- "PYTHONDONTWRITEBYTECODE",
46
- "GIT_PAGER",
47
- "PAGER",
48
- "GIT_TERMINAL_PROMPT",
49
- "VITEST",
50
- "JEST_WORKER_ID",
30
+ /**
31
+ * Environment variables that change what runs or how: the program found, the
32
+ * code it loads, its config, its shell, or where it writes. Setting one leaves
33
+ * the command unknown. A trailing `*` matches any suffix. Any other assignment
34
+ * (`FOO=bar cmd`, `VAR=$(…)`) is neutral; a `$(…)` value is read as nested text.
35
+ */
36
+ export const RUNTIME_ENV = [
37
+ "PATH",
38
+ "LD_PRELOAD",
39
+ "LD_LIBRARY_PATH",
40
+ "LD_AUDIT",
41
+ "DYLD_*",
51
42
  "NODE_OPTIONS",
52
- "CARGO_TERM_COLOR",
53
- "GOFLAGS",
54
- "HUSKY",
55
- "SKIP_ENV_VALIDATION"
56
- ]);
43
+ "NODE_PATH",
44
+ "PYTHONPATH",
45
+ "PYTHONSTARTUP",
46
+ "PERL5OPT",
47
+ "PERL5LIB",
48
+ "RUBYOPT",
49
+ "GIT_DIR",
50
+ "GIT_WORK_TREE",
51
+ "GIT_EXEC_PATH",
52
+ "GIT_SSH",
53
+ "GIT_SSH_COMMAND",
54
+ "GIT_CONFIG*",
55
+ "HOME",
56
+ "SHELL",
57
+ "ENV",
58
+ "BASH_ENV",
59
+ "ZDOTDIR",
60
+ "IFS",
61
+ "PS4",
62
+ "CDPATH",
63
+ "PROMPT_COMMAND",
64
+ "EDITOR",
65
+ "VISUAL",
66
+ "GIT_EDITOR",
67
+ "TMPDIR"
68
+ ];
69
+ const SECRET_NAME = /(_TOKEN|_SECRET|_KEY|_CREDENTIALS)$|PASSWORD/i;
70
+ /** Why setting `name` leaves a command unknown, or null when it is neutral. */
71
+ export function envReason(name) {
72
+ const runtime = RUNTIME_ENV.some((entry) => entry.endsWith("*") ? name.startsWith(entry.slice(0, -1)) : name === entry);
73
+ if (runtime)
74
+ return `sets ${name}`;
75
+ return SECRET_NAME.test(name) ? "sets a secret" : null;
76
+ }
57
77
  const ASSIGN = /^([A-Za-z_][A-Za-z0-9_]*)=/;
58
78
  /** Wrappers that run the rest of the line as the real command. */
59
79
  const WRAPPERS = {
@@ -182,15 +202,15 @@ const READERS = {
182
202
  free: { noPaths: true },
183
203
  vm_stat: { noPaths: true }
184
204
  };
185
- /** Strip assignments and wrappers. `null` when an assignment isn't one Passport can see past. */
205
+ /** Strip assignments and wrappers. `reason` when an assignment changes what runs (`envReason`). */
186
206
  export function unwrap(words) {
187
207
  let rest = [...words];
188
208
  let sudo = false;
189
209
  for (let guard = 0; guard < 8 && rest.length; guard++) {
190
210
  while (rest.length && ASSIGN.test(rest[0].text)) {
191
- const name = ASSIGN.exec(rest[0].text)[1];
192
- if (!SAFE_ENV.has(name) || rest[0].expands)
193
- return { words: [], sudo, reason: `sets ${name}` };
211
+ const reason = envReason(ASSIGN.exec(rest[0].text)[1]);
212
+ if (reason)
213
+ return { words: [], sudo, reason };
194
214
  rest = rest.slice(1);
195
215
  }
196
216
  const program = rest[0]?.text;
@@ -325,13 +345,13 @@ function processControl(program, words) {
325
345
  touches: "this computer"
326
346
  });
327
347
  }
348
+ /** `export NAME=value` follows the assignment rule; `export NAME` alone is neutral. */
328
349
  function exported(words) {
329
350
  for (const word of words) {
330
- if (word.text.startsWith("-"))
331
- continue;
332
- const name = ASSIGN.exec(word.text)?.[1] ?? word.text;
333
- if (!SAFE_ENV.has(name))
334
- return unknown(`sets ${name}`);
351
+ const name = ASSIGN.exec(word.text)?.[1];
352
+ const reason = name ? envReason(name) : null;
353
+ if (reason)
354
+ return unknown(reason);
335
355
  }
336
356
  return { kind: "neutral" };
337
357
  }
@@ -387,6 +407,7 @@ const PROGRAMS = {
387
407
  rg: (_program, rest, ctx) => ripgrep(rest, ctx),
388
408
  ...each(["fd", "fdfind"], (_program, rest, ctx) => fd(rest, ctx)),
389
409
  ...each(["sed", "gsed"], (_program, rest, ctx) => sed(rest, ctx)),
410
+ ...each(["awk", "gawk", "mawk", "nawk"], (program, rest, ctx) => awk(program, rest, ctx)),
390
411
  sort: (_program, rest, ctx) => rest.some((word) => /^(-o|--output)/.test(word.text))
391
412
  ? unknown("sort writes a file")
392
413
  : readOf("sort", "read", operands(rest, ["-k", "-t", "-S", "-T", "--parallel", "--key", "--field-separator"]), ctx),
@@ -412,7 +433,8 @@ const PROGRAMS = {
412
433
  : toolCommand(program, rest, ctx),
413
434
  ...each(["docker", "podman", "docker-compose"], (program, rest, ctx) => docker(program, rest, ctx)),
414
435
  ...each(["kill", "pkill", "killall"], (program, rest) => processControl(program, rest)),
415
- ...each(["node", "tsx", "python", "python3", "ruby", "perl"], (program, rest, ctx) => interpreter(program, rest, ctx)),
436
+ ...each(["node", "tsx", "python", "python3", "ruby"], (program, rest, ctx) => interpreter(program, rest, ctx)),
437
+ perl: (program, rest, ctx) => perlSubstitution(rest, ctx) ?? interpreter(program, rest, ctx),
416
438
  deno: (program, rest, ctx) => rest[0] && !rest[0].text.startsWith("-") ? toolCommand(program, rest, ctx) : interpreter(program, rest, ctx),
417
439
  ...each(["env", "printenv"], () => unknown("prints the environment")),
418
440
  ...each(["dd", "mkfs", "diskutil", "fdisk"], (program) => unknown(`${program} writes disks`))
@@ -9,12 +9,48 @@ export declare function copyLike(program: string, words: ShellWord[], ctx: Comma
9
9
  export declare function find(words: ShellWord[], ctx: CommandContext): LocalOutcome;
10
10
  export declare function ripgrep(words: ShellWord[], ctx: CommandContext): LocalOutcome;
11
11
  export declare function fd(words: ShellWord[], ctx: CommandContext): LocalOutcome;
12
- /** sed: a read unless it edits files in place; any script that writes or runs is no decision. */
12
+ /** sed: a read of the named files (or stdin), or a change to them in place.
13
+ * A script that writes or runs something, or comes from a file, is no decision. */
13
14
  export declare function sed(words: ShellWord[], ctx: CommandContext): LocalOutcome;
14
15
  /** BSD sed takes `-i ''` (an empty backup suffix) as its own word. */
15
16
  export declare function bsdSuffix(word: ShellWord | undefined): boolean;
16
- /** Print, delete, quit, and substitute (with print-only flags) only. */
17
+ /** True when a sed script only prints, deletes, substitutes, or edits its own buffers. */
17
18
  export declare function safeSedScript(script: string): boolean;
19
+ /**
20
+ * A small scanner over a sed script (GNU and BSD), returning why it isn't
21
+ * safe or null. Grammar, separated by `;` or newline outside brackets,
22
+ * regexes, and text:
23
+ *
24
+ * command := address? `!`* verb
25
+ * address := one (`,` (one | `+N` | `~N`))? one := N | N~M | `$` | /re/ | \%re% (flags I M)
26
+ * verb := p d D q Q n N P h H g G x z = l F { } : b t T (labels)
27
+ * | s<d>re<d>text<d>flags flags: g p i I m M digits (e and w are unknown)
28
+ * | y<d>from<d>to<d>
29
+ * | a i c text (output only, runs to the end of the line)
30
+ * unknown := r R w W e v and anything else
31
+ */
32
+ export declare function sedScriptProblem(script: string): string | null;
33
+ /**
34
+ * awk, gawk, mawk, nawk: a read of the named files (or stdin), or with gawk's
35
+ * `-i inplace` / `--in-place` a change to them. Options: `-F sep`, `-v
36
+ * name=value`, `--`; `-f file` is unknown. The first operand is the program,
37
+ * scanned with strings and regexes set aside (`awkProblem`).
38
+ */
39
+ export declare function awk(program: string, words: ShellWord[], ctx: CommandContext): LocalOutcome;
40
+ /**
41
+ * Why an awk program isn't read-only, or null. With string and regex
42
+ * contents set aside: `system(`, a pipe (`print … | "cmd"`, `"cmd" | getline`,
43
+ * `|&`), `getline <` from a file, and `>`/`>>` at the top level of a `print`
44
+ * or `printf` statement (a redirection; inside parentheses it compares).
45
+ */
46
+ export declare function awkProblem(program: string): string | null;
47
+ /**
48
+ * `perl -pi -e 's/a/b/g' files`: with flags among -p -n -i[SUFFIX] -e -E -l
49
+ * -0 -a -F -w -s -C and every script only `s///`, `tr///`, or `y///`, a change
50
+ * to the named files with -i, else a read of them. Null: any other perl, left
51
+ * to the interpreter rules and the inline-code scan.
52
+ */
53
+ export declare function perlSubstitution(words: ShellWord[], ctx: CommandContext): LocalOutcome | null;
18
54
  export declare function tar(words: ShellWord[], ctx: CommandContext): LocalOutcome;
19
55
  export declare function rsync(words: ShellWord[], ctx: CommandContext): LocalOutcome;
20
56
  /** unzip: extracts into `-d` or here; `-l`/`-t` only read. */