@agent-corpus/policy-manager 0.9.0 → 0.11.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 (47) hide show
  1. package/README.md +126 -29
  2. package/dist/adapters.d.ts +3 -1
  3. package/dist/adapters.js +37 -18
  4. package/dist/classifier.d.ts +98 -0
  5. package/dist/classifier.js +343 -0
  6. package/dist/cli.js +66 -7
  7. package/dist/config.d.ts +2 -0
  8. package/dist/config.js +6 -2
  9. package/dist/evidence.d.ts +1 -0
  10. package/dist/evidence.js +60 -0
  11. package/dist/flow.d.ts +4 -0
  12. package/dist/flow.js +91 -18
  13. package/dist/gitalias.d.ts +13 -0
  14. package/dist/gitalias.js +33 -0
  15. package/dist/grants.d.ts +9 -9
  16. package/dist/grants.js +46 -30
  17. package/dist/hard.d.ts +63 -0
  18. package/dist/hard.js +1637 -0
  19. package/dist/helpers.d.ts +59 -0
  20. package/dist/helpers.js +304 -0
  21. package/dist/merged.d.ts +6 -0
  22. package/dist/merged.js +23 -0
  23. package/dist/nativerules.d.ts +44 -0
  24. package/dist/nativerules.js +653 -0
  25. package/dist/permissive.js +179 -7
  26. package/dist/policy.d.ts +12 -0
  27. package/dist/policy.js +228 -45
  28. package/dist/profile.d.ts +7 -0
  29. package/dist/profile.js +32 -1
  30. package/dist/prompt.d.ts +32 -0
  31. package/dist/prompt.js +334 -0
  32. package/dist/reads.d.ts +46 -0
  33. package/dist/reads.js +812 -0
  34. package/dist/replay.d.ts +42 -0
  35. package/dist/replay.js +174 -1
  36. package/dist/service.d.ts +12 -1
  37. package/dist/service.js +23 -6
  38. package/dist/session.d.ts +76 -13
  39. package/dist/session.js +373 -116
  40. package/dist/shell.d.ts +2 -0
  41. package/dist/shell.js +1 -1
  42. package/dist/shellscan.d.ts +58 -0
  43. package/dist/shellscan.js +395 -0
  44. package/dist/statepaths.d.ts +41 -0
  45. package/dist/statepaths.js +706 -0
  46. package/dist/types.d.ts +11 -1
  47. package/package.json +1 -1
@@ -0,0 +1,706 @@
1
+ import { readdirSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, dirname } from "node:path";
4
+ import { canonical, resolveWord, tempRoots } from "./evidence.js";
5
+ /**
6
+ * Whether a write, move or delete target could reach the policy service's own state: the
7
+ * `acp-<uid>-*` session directories in the temp directory (audit logs, token, socket, grants,
8
+ * cache). Targets are matched as the shell would expand them, against the real directories and a
9
+ * sample one, so a glob (`acp-*`, `a*p-501*`, `[a]cp-*`), an unknown expansion (read as `*`) or a
10
+ * directory above the state (`rm -rf $TMPDIR`) counts, not only the literal name.
11
+ */
12
+ const slashes = (path) => path.replace(/\\/g, "/");
13
+ const WINDOWS = process.platform === "win32";
14
+ const STATE_DIR = /^acp-(?:\d+|user)-/i;
15
+ /** Files a session directory holds, by name; a sample stands for the rotated logs. */
16
+ const STATE_FILES = ["audit.jsonl", "audit.00000001.jsonl", "token", "service.sock", "grants.json"];
17
+ /**
18
+ * Longest word or pattern matched here. Anything longer fails closed (counts as reaching the
19
+ * state), so no input can make matching slow.
20
+ */
21
+ export const MAX_TARGET = 4096;
22
+ /** `text` without trailing `/` (a loop, linear on any input). */
23
+ function stripSlashes(text) {
24
+ let end = text.length;
25
+ while (end > 0 && text[end - 1] === "/")
26
+ end--;
27
+ return text.slice(0, end);
28
+ }
29
+ /** `path` without a trailing separator (the root stays `/`). */
30
+ function trim(path) {
31
+ const trimmed = stripSlashes(path);
32
+ return trimmed === "" ? "/" : trimmed;
33
+ }
34
+ /**
35
+ * Whether `pattern` has a brace expansion: a `{...}` with no nested braces and a `,` or `..`
36
+ * inside. One pass, linear.
37
+ */
38
+ function hasBrace(pattern) {
39
+ let open = -1;
40
+ let separated = false;
41
+ for (let i = 0; i < pattern.length; i++) {
42
+ const c = pattern[i];
43
+ if (c === "\\")
44
+ i++;
45
+ else if (c === "{") {
46
+ open = i;
47
+ separated = false;
48
+ }
49
+ else if (open >= 0 && (c === "," || (c === "." && pattern[i + 1] === ".")))
50
+ separated = true;
51
+ else if (c === "}") {
52
+ if (open >= 0 && separated)
53
+ return true;
54
+ open = -1;
55
+ }
56
+ }
57
+ return false;
58
+ }
59
+ let cache;
60
+ /**
61
+ * The state directories: every `acp-<uid>-*` directory in each temp root, plus a sample one in the
62
+ * temp directory the service uses, so a pattern that would match a later session's directory
63
+ * counts too. Each is listed under both the temp directory as the system gives it (on macOS the
64
+ * logical `/var/folders/...`, where the service creates them) and its real path
65
+ * (`/private/var/folders/...`), so a pattern written against either form matches.
66
+ */
67
+ export function stateDirs() {
68
+ const temp = `${process.env.TMPDIR}|${process.env.TMP}|${process.env.TEMP}`;
69
+ if (cache && cache.temp === temp && Date.now() - cache.at < 2000)
70
+ return cache.dirs;
71
+ const uid = String(process.getuid?.() ?? "user");
72
+ const sample = `acp-${uid}-0123456789abcdef01234567`;
73
+ const logical = trim(slashes(tmpdir()));
74
+ let real = logical;
75
+ try {
76
+ real = trim(slashes(canonical(tmpdir())));
77
+ }
78
+ catch {
79
+ /* judged as given */
80
+ }
81
+ const dirs = new Set([`${logical}/${sample}`, `${real}/${sample}`]);
82
+ for (const root of tempRoots()) {
83
+ const base = trim(slashes(root));
84
+ let names;
85
+ try {
86
+ names = readdirSync(root);
87
+ }
88
+ catch {
89
+ continue; // unreadable: the samples still count
90
+ }
91
+ for (const name of names) {
92
+ if (!STATE_DIR.test(name))
93
+ continue;
94
+ dirs.add(`${base}/${name}`);
95
+ // The same directory under the other form of the temp directory.
96
+ if (base === real && logical !== real)
97
+ dirs.add(`${logical}/${name}`);
98
+ if (base === logical && logical !== real)
99
+ dirs.add(`${real}/${name}`);
100
+ }
101
+ }
102
+ cache = { at: Date.now(), temp, dirs: [...dirs] };
103
+ return cache.dirs;
104
+ }
105
+ const fold = (path) => (WINDOWS ? path.toLowerCase() : path);
106
+ let lists;
107
+ /**
108
+ * The state directories and the directories above them, folded for comparison, with a cache of
109
+ * real paths. Rebuilt whenever `stateDirs` is (every 2 seconds at most), so a long-running service
110
+ * never judges with stale filesystem facts for longer than that.
111
+ */
112
+ function stateLists() {
113
+ const from = stateDirs();
114
+ if (lists?.from !== from)
115
+ lists = {
116
+ from,
117
+ dirs: from.map(fold),
118
+ above: stateAncestors().map(fold),
119
+ real: new Map(),
120
+ names: new Map(),
121
+ dirSet: new Set(from.map(fold)),
122
+ aboveSet: new Set(stateAncestors().map(fold)),
123
+ };
124
+ return lists;
125
+ }
126
+ /**
127
+ * The real path of `path` as `/` text, or undefined: its directory's real path (memoized for the
128
+ * current state lists, so words in one directory cost one lookup) and its own name. A symlink as
129
+ * the last name is not followed: making one that points at the state names the state, which the
130
+ * rule already catches.
131
+ */
132
+ function realOf(path) {
133
+ const parent = dirname(path);
134
+ if (parent === path)
135
+ return trim(path);
136
+ const base = realDir(parent);
137
+ return base === undefined ? undefined : `${base === "/" ? "" : base}/${basename(path)}`;
138
+ }
139
+ function realDir(dir) {
140
+ const cache = stateLists().real;
141
+ const known = cache.get(dir);
142
+ if (known !== undefined)
143
+ return known ?? undefined;
144
+ let real = null;
145
+ try {
146
+ real = trim(slashes(canonical(dir)));
147
+ }
148
+ catch {
149
+ /* judged as written */
150
+ }
151
+ if (cache.size < 10_000)
152
+ cache.set(dir, real);
153
+ return real ?? undefined;
154
+ }
155
+ /** Every directory a state directory lies in, from the filesystem root down. */
156
+ function stateAncestors() {
157
+ const found = new Set();
158
+ for (const dir of stateDirs()) {
159
+ const parts = dir.split("/");
160
+ for (let i = 1; i < parts.length; i++)
161
+ found.add(trim(parts.slice(0, i).join("/") || "/"));
162
+ }
163
+ return [...found];
164
+ }
165
+ /**
166
+ * A shell glob as tokens: `*`, `?`, `[...]` with `!`/`^` negation and ranges, and `\` escapes.
167
+ * Undefined for a brace expansion (`{a,b}`, `{1..3}`), which callers treat as matching.
168
+ */
169
+ const tokenCache = new Map();
170
+ /** `tokenize`, memoized (a script names the same patterns many times). */
171
+ function tokenize(pattern) {
172
+ if (tokenCache.has(pattern))
173
+ return tokenCache.get(pattern);
174
+ const tokens = tokenizeOnce(pattern);
175
+ if (tokenCache.size > 4096)
176
+ tokenCache.clear();
177
+ tokenCache.set(pattern, tokens);
178
+ return tokens;
179
+ }
180
+ function tokenizeOnce(pattern) {
181
+ if (pattern.length > MAX_TARGET || hasBrace(pattern))
182
+ return undefined;
183
+ const out = [];
184
+ for (let i = 0; i < pattern.length; i++) {
185
+ const c = pattern[i];
186
+ if (c === "\\" && i + 1 < pattern.length)
187
+ out.push({ kind: "char", c: pattern[++i] });
188
+ else if (c === "*") {
189
+ if (out[out.length - 1]?.kind !== "star")
190
+ out.push({ kind: "star" });
191
+ }
192
+ else if (c === "?")
193
+ out.push({ kind: "one" });
194
+ else if (c === "[") {
195
+ let j = i + 1;
196
+ const negate = pattern[j] === "!" || pattern[j] === "^";
197
+ if (negate)
198
+ j++;
199
+ const items = [];
200
+ let first = true;
201
+ while (j < pattern.length && (pattern[j] !== "]" || first)) {
202
+ const lo = pattern[j];
203
+ if (pattern[j + 1] === "-" && pattern[j + 2] !== undefined && pattern[j + 2] !== "]") {
204
+ items.push([lo, pattern[j + 2]]);
205
+ j += 3;
206
+ }
207
+ else {
208
+ items.push([lo, lo]);
209
+ j++;
210
+ }
211
+ first = false;
212
+ }
213
+ if (j >= pattern.length)
214
+ out.push({ kind: "char", c });
215
+ else {
216
+ out.push({ kind: "set", negate, items });
217
+ i = j;
218
+ }
219
+ }
220
+ else
221
+ out.push({ kind: "char", c });
222
+ }
223
+ return out;
224
+ }
225
+ /** Whether a shell glob matches `text`. `*` matches any run, `/` included (as `find -path` does). */
226
+ export function globMatch(pattern, text, fold = WINDOWS) {
227
+ const p = fold ? pattern.toLowerCase() : pattern;
228
+ const t = fold ? text.toLowerCase() : text;
229
+ const tokens = tokenize(p);
230
+ if (!tokens)
231
+ return true;
232
+ const one = (token, c) => token.kind === "one" ||
233
+ (token.kind === "char" && token.c === c) ||
234
+ (token.kind === "set" && token.items.some(([lo, hi]) => c >= lo && c <= hi) !== token.negate);
235
+ let k = 0, i = 0, star = -1, mark = 0;
236
+ while (i < t.length) {
237
+ const token = tokens[k];
238
+ if (token && token.kind !== "star" && one(token, t[i])) {
239
+ k++;
240
+ i++;
241
+ }
242
+ else if (token?.kind === "star") {
243
+ star = k++;
244
+ mark = i;
245
+ }
246
+ else if (star >= 0) {
247
+ k = star + 1;
248
+ i = ++mark;
249
+ }
250
+ else
251
+ return false;
252
+ }
253
+ while (tokens[k]?.kind === "star")
254
+ k++;
255
+ return k === tokens.length;
256
+ }
257
+ export const hasGlob = (text) => /[*?[]/.test(text) || tokenize(text) === undefined;
258
+ /**
259
+ * Whether path `pattern` names `target`, segment by segment, or (with `inside`) anything within
260
+ * it. A `**` segment matches any number of segments; a pattern this cannot follow matches.
261
+ */
262
+ function pathMatch(pattern, target, inside) {
263
+ const ps = trim(pattern).split("/");
264
+ const ts = trim(target).split("/");
265
+ // Memoized on (pattern segment, target segment), so any number of `**` stays polynomial.
266
+ const seen = new Set();
267
+ const go = (a, b) => {
268
+ if (b === ts.length)
269
+ return a === ps.length || (inside && a > 0) || ps[a] === "**";
270
+ if (a === ps.length)
271
+ return false;
272
+ const key = a * (ts.length + 1) + b;
273
+ if (seen.has(key))
274
+ return false;
275
+ seen.add(key);
276
+ if (ps[a] === "**")
277
+ return go(a + 1, b) || go(a, b + 1);
278
+ return globMatch(ps[a], ts[b]) && go(a + 1, b + 1);
279
+ };
280
+ return go(0, 0);
281
+ }
282
+ /** A shell word's text with the temp variables filled in and any other expansion read as `*`. */
283
+ export function stateText(text, literal) {
284
+ if (literal)
285
+ return text;
286
+ if (text.length > MAX_TARGET)
287
+ return "*";
288
+ const temp = slashes(tmpdir());
289
+ // One pass: `$NAME`, `${...}`, `$(...)` and backticks; the temp variables become the temp
290
+ // directory and anything else `*`. An unclosed one runs to the end.
291
+ let out = "";
292
+ for (let i = 0; i < text.length; i++) {
293
+ const c = text[i];
294
+ if (c === "`") {
295
+ const end = text.indexOf("`", i + 1);
296
+ out += "*";
297
+ i = end < 0 ? text.length : end;
298
+ }
299
+ else if (c !== "$")
300
+ out += c;
301
+ else if (text[i + 1] === "{" || text[i + 1] === "(") {
302
+ const close = text[i + 1] === "{" ? "}" : ")";
303
+ const end = text.indexOf(close, i + 2);
304
+ const name = end < 0 ? "" : text.slice(i + 2, end);
305
+ out += /^(?:TMPDIR|TMP|TEMP)$/.test(name) && close === "}" ? temp : "*";
306
+ i = end < 0 ? text.length : end;
307
+ }
308
+ else {
309
+ let j = i + 1;
310
+ while (j < text.length && /\w/.test(text[j]))
311
+ j++;
312
+ const name = text.slice(i + 1, j);
313
+ out += /^(?:TMPDIR|TMP|TEMP)$/.test(name) ? temp : "*";
314
+ i = j > i + 1 ? j - 1 : i + (/[@*#?$!-]/.test(text[i + 1] ?? "") ? 1 : 0);
315
+ }
316
+ }
317
+ return out;
318
+ }
319
+ /**
320
+ * Whether a target word (as `stateText` gives it) could name the policy service's state from any
321
+ * of `cwds`: a state directory, a file in one, anything inside one, or, for a delete or move
322
+ * (`removes`), a directory the state lies in (`rm -rf $TMPDIR`, `rm -rf /tmp/*`).
323
+ */
324
+ export function namesState(text, cwds, removes) {
325
+ if (!text)
326
+ return false;
327
+ if (text.length > MAX_TARGET)
328
+ return true;
329
+ // An option or a number names no file.
330
+ if (/^-[^=]*$|^\d+$/.test(text))
331
+ return false;
332
+ // The same word in the same directories is asked many times: memoized with the state lists.
333
+ const list = [...cwds];
334
+ const memo = stateLists().names;
335
+ const key = `${removes ? 1 : 0}\0${text}\0${list.join("\0")}`;
336
+ const known = memo.get(key);
337
+ if (known !== undefined)
338
+ return known;
339
+ const answer = namesStateOnce(text, list, removes);
340
+ if (memo.size < 20_000)
341
+ memo.set(key, answer);
342
+ return answer;
343
+ }
344
+ function namesStateOnce(text, cwds, removes) {
345
+ const { dirs, above: ancestors } = stateLists();
346
+ const above = removes ? ancestors : [];
347
+ const forms = new Set();
348
+ for (const cwd of cwds) {
349
+ let path;
350
+ try {
351
+ path = slashes(resolveWord(cwd, text));
352
+ }
353
+ catch {
354
+ continue;
355
+ }
356
+ forms.add(trim(path));
357
+ const real = realOf(path);
358
+ if (real !== undefined)
359
+ forms.add(real);
360
+ }
361
+ for (const raw of forms) {
362
+ const form = fold(raw);
363
+ if (!hasGlob(form)) {
364
+ // A literal path: a state directory, anything in one, or (for a delete) a directory above.
365
+ // Set lookups on each prefix: linear in the path, whatever the number of state directories.
366
+ const { dirSet, aboveSet } = stateLists();
367
+ for (let at = form.indexOf("/", 1);; at = form.indexOf("/", at + 1)) {
368
+ if (dirSet.has(at < 0 ? form : form.slice(0, at)))
369
+ return true;
370
+ if (at < 0)
371
+ break;
372
+ }
373
+ if (removes && aboveSet.has(form))
374
+ return true;
375
+ continue;
376
+ }
377
+ // A glob: only directories its literal start leads to can match.
378
+ const lead = form.slice(0, form.search(/[*?[{]/));
379
+ const base = lead.slice(0, lead.lastIndexOf("/") + 1);
380
+ const near = (dir) => dir.startsWith(base) || `${dir}/`.startsWith(base);
381
+ if (dirs.some((dir) => near(dir) && pathMatch(form, dir, true)))
382
+ return true;
383
+ if (above.some((dir) => near(dir) && pathMatch(form, dir, false)))
384
+ return true;
385
+ }
386
+ return false;
387
+ }
388
+ /**
389
+ * Whether `find` with an action that deletes or runs something could reach the state: a start
390
+ * directory in or above a state directory, and a `-name`/`-iname` pattern that can match a name on
391
+ * the way down, a `-path`/`-ipath` pattern that can match the path find prints, a `-regex`
392
+ * (not followed: fails closed), or no such filter at all.
393
+ */
394
+ export function findReachesState(args, cwds) {
395
+ const start = args.findIndex((arg) => /^[-!(]/.test(arg));
396
+ const roots = args.slice(0, start < 0 ? args.length : start);
397
+ const names = [];
398
+ const paths = [];
399
+ let regex = false;
400
+ for (let i = 0; i < args.length; i++) {
401
+ const arg = args[i];
402
+ const value = args[i + 1] ?? "";
403
+ if (arg === "-name" || arg === "-iname")
404
+ names.push([value, arg === "-iname"]);
405
+ else if (arg === "-path" || arg === "-ipath" || arg === "-wholename" || arg === "-iwholename")
406
+ paths.push([value, arg.startsWith("-i")]);
407
+ else if (arg === "-regex" || arg === "-iregex")
408
+ regex = true;
409
+ }
410
+ const targets = stateDirs().flatMap((dir) => [
411
+ dir,
412
+ ...STATE_FILES.map((file) => `${dir}/${file}`),
413
+ ]);
414
+ for (const rootText of roots.length ? roots : ["."]) {
415
+ for (const cwd of cwds) {
416
+ let root;
417
+ try {
418
+ root = trim(slashes(canonical(resolveWord(cwd, rootText))));
419
+ }
420
+ catch {
421
+ try {
422
+ root = trim(slashes(resolveWord(cwd, rootText)));
423
+ }
424
+ catch {
425
+ return true;
426
+ }
427
+ }
428
+ if (hasGlob(rootText)) {
429
+ if (namesState(rootText, [cwd], true))
430
+ return true;
431
+ continue;
432
+ }
433
+ const prefix = root === "/" ? "/" : `${root}/`;
434
+ for (const target of targets) {
435
+ if (target !== root && !target.startsWith(prefix))
436
+ continue;
437
+ // Inside a state directory, every entry is state.
438
+ if (target !== root &&
439
+ stateDirs().some((dir) => root.startsWith(`${dir}/`) || root === dir))
440
+ return true;
441
+ if (regex || (!names.length && !paths.length))
442
+ return true;
443
+ const rel = target === root ? "" : target.slice(prefix.length);
444
+ const steps = rel.split("/").filter(Boolean);
445
+ if (names.some(([pattern, fold]) => steps.some((step) => globMatch(pattern, step, fold))))
446
+ return true;
447
+ const printed = `${stripSlashes(rootText)}/${rel}`;
448
+ if (paths.some(([pattern, fold]) => globMatch(pattern, printed, fold)))
449
+ return true;
450
+ }
451
+ }
452
+ }
453
+ return false;
454
+ }
455
+ /** The temp directory computed at run time (case matters: `/tmp` in a path is not `TMP`). */
456
+ const TEMP_LOOKUP = /\$\{?(?:TMPDIR|TMP|TEMP)\b|environ\b[^\n]{0,40}\b(?:TMPDIR|TMP|TEMP)\b|process\.env\.(?:TMPDIR|TMP|TEMP)\b|ENV\[\s*["'](?:TMPDIR|TMP|TEMP)|getenv\(\s*["'](?:TMPDIR|TMP|TEMP)|gettempdir|tempfile\.tempdir|os\.tmpdir|tmpdir\(\)|Dir\.tmpdir|sys_get_temp_dir|GetTempPath/;
457
+ /** Longest inline code judged; longer code fails closed. */
458
+ const MAX_CODE = 100_000;
459
+ /** File calls that take two paths (source and destination); every other one takes one. */
460
+ const TWO_PATHS = new Set([
461
+ ...["rename", "renames", "replace", "move", "copy", "copyfile", "copy2", "copytree", "mv"],
462
+ ...["cp", "renameSync", "copyFileSync", "cpSync", "copyFile", "symlink", "link", "symlinkSync"],
463
+ ...["linkSync", "cp_r", "ln_s", "ln_sf"],
464
+ ]);
465
+ /** Names specific enough to count with no receiver (and Perl and PHP builtins, which have none). */
466
+ const BARE_CALLS = /^(?:rmtree|rmSync|unlinkSync|rmdirSync|renameSync|copyFileSync|cpSync|writeFileSync|appendFileSync|truncateSync|chmodSync|chownSync|symlinkSync|linkSync|file_put_contents|remove_tree|rimraf|unlink|rmdir|rename|chmod|chown|chdir|truncate|symlink|link|copy|fopen)$/;
467
+ /** Receivers whose file calls count (`os.remove`, `shutil.rmtree`, `fs.rmSync`, `FileUtils.rm_rf`). */
468
+ const RECEIVERS = /^(?:os|shutil|fs|fsp|promises|File|FileUtils|Dir|IO|Pathname)$/;
469
+ const FILE_CALL = /(?:\b([A-Za-z_]\w*)\s*\.\s*)?\b(remove|unlink|rmtree|rmdir|removedirs|rmSync|unlinkSync|rmdirSync|rm_rf|rm_r|rm_f|rm|remove_tree|rimraf|delete|rename|renames|replace|move|copy|copyfile|copy2|copytree|renameSync|copyFileSync|cpSync|copyFile|mv|cp|cp_r|writeFileSync|appendFileSync|writeFile|appendFile|write|binwrite|write_text|write_bytes|file_put_contents|truncate|truncateSync|chmod|chmodSync|chown|chownSync|chdir|touch|symlink|symlinkSync|link|linkSync|ln_s|ln_sf|open|fopen|glob)\b(\s*\(|[ \t]+(?=[$'"\w]))/g;
470
+ /**
471
+ * Method names that are file calls on any receiver: in the APIs that have them they mean nothing
472
+ * else (`require('fs').rmSync(x)`, `fsp.rm(x)`, `x.rmtree()`).
473
+ */
474
+ const FILE_METHODS = /^(?:rmSync|rm|unlinkSync|unlink|rmdirSync|rmdir|rmtree|removedirs|renameSync|renames|writeFileSync|appendFileSync|writeFile|appendFile|truncateSync|chmodSync|chownSync|copyFileSync|copyFile|cpSync|symlinkSync|linkSync|rm_rf|rm_r|rm_f|cp_r|ln_s|ln_sf|file_put_contents|copytree|copyfile|copy2|chdir|write_text|write_bytes)$/;
475
+ /** A call chain that starts by loading a module: `require('fs').`, `__import__('os').`. */
476
+ const LOADED = /\b(?:require|__import__|import_module)\s*\([^()]*\)(?:\s*\.\s*\w+)*\s*\.\s*$/;
477
+ /** Names bound to a module: `import os as o`, `const f = require('fs')`, `m = __import__('os')`. */
478
+ function moduleAliases(code) {
479
+ const found = new Set();
480
+ for (const match of code.matchAll(/\bimport\s+[\w.]+\s+as\s+(\w+)/g))
481
+ found.add(match[1]);
482
+ for (const match of code.matchAll(/\b\$?(\w+)\s*=\s*(?:require|__import__|importlib\s*\.\s*import_module|import_module)\s*\(/g))
483
+ found.add(match[1]);
484
+ return found;
485
+ }
486
+ /** Methods that act on the path object they are called on (`Path('/x').unlink()`, `p.write_text(...)`). */
487
+ const PATH_METHODS = /^(?:unlink|rmdir|write_text|write_bytes|rename|replace|touch|chmod|symlink_to)$/;
488
+ /**
489
+ * The value of a plain string literal (`'x'`, `"x"`, `r'x'`), or undefined for anything else:
490
+ * an f-string, a template or interpolating string, concatenation, a call, a variable.
491
+ */
492
+ function plainLiteral(text) {
493
+ const arg = text.trim();
494
+ const prefix = /^[rRbBuU]{0,2}/.exec(arg)?.[0] ?? "";
495
+ const quote = arg[prefix.length];
496
+ if ((quote !== "'" && quote !== '"') || arg.length < prefix.length + 2)
497
+ return undefined;
498
+ if (arg[arg.length - 1] !== quote)
499
+ return undefined;
500
+ const inner = arg.slice(prefix.length + 1, -1);
501
+ if (inner.includes(quote) || inner.includes("\\"))
502
+ return undefined;
503
+ if (quote === '"' && /\$|#\{/.test(inner))
504
+ return undefined;
505
+ return inner;
506
+ }
507
+ /**
508
+ * The arguments of a call from `start` (just after its `(`, or after the name for a call without
509
+ * parentheses), split at top-level commas. Undefined when they cannot be read within the limit.
510
+ */
511
+ function callArgs(code, start, parens) {
512
+ const args = [];
513
+ let depth = 0;
514
+ let quote = "";
515
+ let from = start;
516
+ const end = Math.min(code.length, start + MAX_TARGET);
517
+ for (let i = start; i < end; i++) {
518
+ const c = code[i];
519
+ if (quote) {
520
+ if (c === "\\")
521
+ i++;
522
+ else if (c === quote)
523
+ quote = "";
524
+ continue;
525
+ }
526
+ if (c === "'" || c === '"' || c === "`")
527
+ quote = c;
528
+ else if ("([{".includes(c))
529
+ depth++;
530
+ else if (")]}".includes(c) || (!parens && (c === ";" || c === "\n") && depth === 0)) {
531
+ if (depth === 0) {
532
+ args.push(code.slice(from, i));
533
+ return args;
534
+ }
535
+ depth--;
536
+ }
537
+ else if (c === "," && depth === 0) {
538
+ args.push(code.slice(from, i));
539
+ from = i + 1;
540
+ }
541
+ }
542
+ if (!parens && end === code.length) {
543
+ args.push(code.slice(from, end));
544
+ return args;
545
+ }
546
+ return undefined;
547
+ }
548
+ /** Variables assigned exactly once, to a plain string literal: `p = '/x'`, `const p = "/x"`. */
549
+ function literalVariables(code) {
550
+ const found = new Map();
551
+ for (const line of code.split(/[\n;]/)) {
552
+ const match = /^\s*(?:(?:const|let|var|my|our)\s+)?\$?([A-Za-z_]\w*)\s*=(?!=)(.*)$/.exec(line);
553
+ if (!match)
554
+ continue;
555
+ const [, name = "", value = ""] = match;
556
+ found.set(name, found.has(name) ? undefined : plainLiteral(value));
557
+ }
558
+ return found;
559
+ }
560
+ /**
561
+ * Whether a file call in the code deletes, moves, copies, writes or enters a path that could be
562
+ * the state, or one this cannot read as a plain string literal (concatenation, `chr()`, `os.sep`,
563
+ * `join`, an f-string, a variable not assigned a literal once, a `listdir`/`walk` result): the
564
+ * state lies in the temp directory, so a computed path fails closed.
565
+ */
566
+ function callsReachState(code, cwds) {
567
+ const vars = literalVariables(code);
568
+ const aliases = moduleAliases(code);
569
+ const value = (arg) => {
570
+ const name = /^\s*\$?([A-Za-z_]\w*)\s*$/.exec(arg)?.[1];
571
+ if (name)
572
+ return vars.get(name);
573
+ const path = /^\s*(?:pathlib\s*\.\s*)?Path\s*\((.*)\)\s*$/.exec(arg)?.[1];
574
+ if (path !== undefined)
575
+ return value(path);
576
+ return plainLiteral(arg);
577
+ };
578
+ const reaches = (arg) => {
579
+ if (arg === undefined)
580
+ return true;
581
+ const path = value(arg);
582
+ return path === undefined || namesState(path, cwds, true);
583
+ };
584
+ for (const match of code.matchAll(FILE_CALL)) {
585
+ const [whole, receiver, name = "", opener = ""] = match;
586
+ const at = (match.index ?? 0) + whole.length;
587
+ const parens = opener.includes("(");
588
+ // Without parentheses only Ruby's `FileUtils.rm_rf dir`, `File.delete f` and Perl's
589
+ // `unlink $f`/`unlink glob(...)` forms count, so prose in a string or comment does not.
590
+ if (!parens &&
591
+ !(receiver && RECEIVERS.test(receiver)) &&
592
+ !(/^(?:unlink|rmdir)$/.test(name) && /^[$'"]|^glob\b/.test(code.slice(at))))
593
+ continue;
594
+ const index = match.index ?? 0;
595
+ const before = code.slice(Math.max(0, index - MAX_TARGET), index);
596
+ // A method on an expression: `Path('/x').unlink()`, `require('fs').rmSync(x)`.
597
+ const dotted = !receiver && /\.\s*$/.test(before.slice(-8));
598
+ // The path object a method is called on, when it is `Path(<literal>)`.
599
+ const pathObject = () => /Path\s*\(([^()]*)\)\s*\.?\s*$/.exec(before.replace(/\s*\.\s*$/, ""))?.[1];
600
+ // A module, an alias of one, or a chain that starts by loading one: any name is a file call.
601
+ const moduleCall = (receiver !== undefined && (RECEIVERS.test(receiver) || aliases.has(receiver))) ||
602
+ (dotted && LOADED.test(before.slice(-200)));
603
+ if (dotted && !moduleCall && !FILE_METHODS.test(name)) {
604
+ if (!PATH_METHODS.test(name))
605
+ continue;
606
+ // `.replace(...)`/`.rename(...)` on anything but a `Path(...)` is a string or table method.
607
+ const object = pathObject();
608
+ if (object === undefined && /^(?:replace|rename)$/.test(name))
609
+ continue;
610
+ if (reaches(object))
611
+ return true;
612
+ continue;
613
+ }
614
+ if (name === "glob" || name === "open" || name === "fopen" || name === "write") {
615
+ // A glob only finds names; `open`/`fopen`/`File.write` write only in a write mode.
616
+ if (name === "glob")
617
+ continue;
618
+ const args = callArgs(code, at, parens);
619
+ if (!args)
620
+ return true;
621
+ if (name === "write") {
622
+ if (receiver !== "File" && receiver !== "IO")
623
+ continue;
624
+ }
625
+ else {
626
+ const mode = args[1];
627
+ if (mode === undefined)
628
+ continue;
629
+ const literal = plainLiteral(mode);
630
+ if (literal !== undefined && !/[wax+]/.test(literal))
631
+ continue;
632
+ }
633
+ if (reaches(args[0]))
634
+ return true;
635
+ continue;
636
+ }
637
+ const fileCall = moduleCall ||
638
+ ((receiver !== undefined || dotted) && FILE_METHODS.test(name)) ||
639
+ (receiver === undefined && !dotted && BARE_CALLS.test(name));
640
+ if (!fileCall) {
641
+ // A method on a path object: `p.write_text(...)`. On a plain variable, `replace` and
642
+ // `rename` are string methods far more often than path ones.
643
+ if (!receiver || !PATH_METHODS.test(name) || /^(?:replace|rename)$/.test(name))
644
+ continue;
645
+ if (reaches(pathObject() ?? receiver))
646
+ return true;
647
+ continue;
648
+ }
649
+ // A path object's own method (`p.unlink()`, `Path(x).write_text(s)`) acts on the object.
650
+ if (!moduleCall && (receiver !== undefined || dotted) && PATH_METHODS.test(name)) {
651
+ if (reaches(pathObject() ?? receiver))
652
+ return true;
653
+ continue;
654
+ }
655
+ const args = callArgs(code, at, parens);
656
+ if (!args)
657
+ return true;
658
+ const count = TWO_PATHS.has(name) ? 2 : 1;
659
+ for (let i = 0; i < count; i++)
660
+ if (reaches(args[i]))
661
+ return true;
662
+ }
663
+ return false;
664
+ }
665
+ /**
666
+ * Whether inline interpreter code could change the state. It names `acp`; or it deletes, moves or
667
+ * writes files and either computes the temp directory at run time (an environment variable or an
668
+ * API: the result is the directory the state lies in), or names a path that could reach the state
669
+ * the way a shell target does: a state directory, a directory above one (the temp root itself), a
670
+ * glob matching one, or a path built at run time (`f'/tmp/{x}'`, `'/tmp/' + x`, `"$TMPDIR/$x"`,
671
+ * read as a glob). A literal path into another directory in temp (`/tmp/pm-x/notes.md`) is not.
672
+ */
673
+ export function codeTouchesState(code, cwds) {
674
+ if (code.length > MAX_CODE)
675
+ return true;
676
+ if (/\bacp/i.test(code))
677
+ return true;
678
+ const roots = [...cwds];
679
+ if (callsReachState(code, roots.length ? roots : ["/"]))
680
+ return true;
681
+ // Dynamic import or attribute indirection hides which call runs (`__import__`, `getattr`,
682
+ // `require(x)`, `eval`, `Function`): with a temp lookup or a path built at run time, fail closed.
683
+ if (/__import__\s*\(|\bimportlib\b|\bgetattr\s*\(|\brequire\s*\(\s*[^'"\s)]|\beval\s*\(|\bexec\s*\(|\bFunction\s*\(|\bsend\s*\(|\bcall_user_func/.test(code) &&
684
+ (TEMP_LOOKUP.test(code) ||
685
+ /['"]\s*\+|\+\s*['"]|\bos\.sep\b|\bchr\s*\(|\.join\s*\(|\bf['"]|`[^`]*\$\{/.test(code) ||
686
+ /['"]\/(?:tmp|var|private)\b/.test(code)))
687
+ return true;
688
+ const changes = /unlink|remove|rmtree|rmdir|\brm\b|rmSync|rename|truncate|writeFile|open\s*\(|shutil|glob|listdir|walk|readdir|system|exec|spawn|subprocess/i.test(code);
689
+ if (!changes)
690
+ return false;
691
+ // The temp directory computed at run time (case matters: `/tmp` in a path is not `TMP`).
692
+ if (TEMP_LOOKUP.test(code))
693
+ return true;
694
+ const list = [...cwds];
695
+ for (const match of code.matchAll(/(?:~\/|\/)[\w.*?[\]{}$%-][^\s'"`,;)(]*/g)) {
696
+ // Parts filled in at run time are any name: `{x}`, `%s`, `$x`; a path that ends where code
697
+ // goes on (`'/tmp/' + x`) keeps its trailing `/` and is read as the directory.
698
+ if (match[0].length > MAX_TARGET)
699
+ return true;
700
+ const path = match[0].replace(/\{[^}/]*\}|%[sd]|\$\{?\w*\}?/g, "*");
701
+ if (namesState(path, list.length ? list : ["/"], true))
702
+ return true;
703
+ }
704
+ return false;
705
+ }
706
+ //# sourceMappingURL=statepaths.js.map