@agent-corpus/policy-manager 0.10.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.
package/dist/reads.js ADDED
@@ -0,0 +1,812 @@
1
+ import { accessSync, constants, existsSync, lstatSync, readdirSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, isAbsolute, join, relative } from "node:path";
4
+ import { canonical, git, inside, policyState, resolveWord, sensitive, tempRoots, } from "./evidence.js";
5
+ import { wildcard } from "./nativerules.js";
6
+ import { defaultProfilePath } from "./profile.js";
7
+ import { parseShell } from "./shell.js";
8
+ const GREP = {
9
+ flags: /^-[nrRiwvclLHhoEFsqxIZz]+$/,
10
+ valued: new Set(["-e", "-f", "-A", "-B", "-C", "-m"]),
11
+ files: new Set(["-f"]),
12
+ long: new Set([
13
+ ...["--include", "--exclude", "--exclude-dir", "--color", "--colour", "--line-number"],
14
+ ...["--recursive", "--ignore-case", "--files-with-matches", "--files-without-match"],
15
+ ...["--count", "--fixed-strings", "--extended-regexp", "--word-regexp", "--invert-match"],
16
+ ...["--max-count", "--context", "--before-context", "--after-context", "--no-messages"],
17
+ ...["--with-filename", "--no-filename", "--only-matching", "--quiet", "--null"],
18
+ ...["--binary-files", "--regexp", "--line-regexp"],
19
+ ]),
20
+ longFiles: new Set(["--file"]),
21
+ };
22
+ const OPTIONS = {
23
+ cat: { flags: /^-[nbsvetAETu]+$/, valued: new Set(), long: new Set(["--number"]) },
24
+ ls: {
25
+ flags: /^-[aAlhRtrSs1dFGipcunog]+$/,
26
+ valued: new Set(),
27
+ long: new Set(["--color", "--all", "--almost-all", "--human-readable", "--recursive"]),
28
+ },
29
+ head: {
30
+ flags: /^-(?:\d+|[qv]+)$/,
31
+ valued: new Set(["-n", "-c"]),
32
+ long: new Set(["--lines", "--bytes", "--quiet", "--verbose"]),
33
+ },
34
+ tail: {
35
+ flags: /^-(?:\d+|[qv]+)$/,
36
+ valued: new Set(["-n", "-c"]),
37
+ long: new Set(["--lines", "--bytes", "--quiet", "--verbose"]),
38
+ },
39
+ grep: GREP,
40
+ egrep: GREP,
41
+ fgrep: GREP,
42
+ // ripgrep skips hidden files and honors ignore files; options that change that are not listed.
43
+ rg: {
44
+ flags: /^-[niSswlcFHNoqvxI0]+$/,
45
+ valued: new Set(["-e", "-g", "-t", "-T", "-A", "-B", "-C", "-m", "-M", "-f"]),
46
+ files: new Set(["-f"]),
47
+ long: new Set([
48
+ ...["--glob", "--iglob", "--type", "--type-not", "--max-count", "--context"],
49
+ ...["--before-context", "--after-context", "--no-heading", "--heading", "--line-number"],
50
+ ...["--ignore-case", "--smart-case", "--case-sensitive", "--fixed-strings", "--files"],
51
+ ...["--files-with-matches", "--count", "--json", "--color", "--word-regexp", "--trim"],
52
+ ...["--max-columns", "--sort", "--vimgrep", "--no-messages", "--only-matching"],
53
+ ...["--regexp", "--invert-match", "--with-filename", "--no-filename", "--null"],
54
+ ]),
55
+ longFiles: new Set(["--file"]),
56
+ },
57
+ // `git grep` reads tracked content only; `--untracked` and `--no-index` are not listed.
58
+ "git-grep": {
59
+ flags: /^-[niwlLcvEFPIhHz]+$/,
60
+ valued: new Set(["-e", "-f", "-A", "-B", "-C", "-m"]),
61
+ files: new Set(["-f"]),
62
+ long: new Set([
63
+ ...["--line-number", "--ignore-case", "--word-regexp", "--files-with-matches"],
64
+ ...["--count", "--heading", "--break", "--cached", "--name-only", "--invert-match"],
65
+ ...["--extended-regexp", "--fixed-strings", "--perl-regexp", "--max-depth", "--color"],
66
+ ...["--no-color", "--full-name", "--max-count", "--context", "--and", "--or", "--not"],
67
+ ]),
68
+ },
69
+ };
70
+ /** `find` predicates that only select and print names, with whether each takes a value. */
71
+ const FIND = {
72
+ ...Object.fromEntries(["-name", "-iname", "-path", "-ipath", "-type", "-maxdepth", "-mindepth", "-newer"]
73
+ .concat(["-mtime", "-mmin", "-size", "-regex", "-iregex", "-perm", "-user", "-group"])
74
+ .map((name) => [name, true])),
75
+ ...Object.fromEntries(["-print", "-print0", "-o", "-or", "-a", "-and", "-not", "!", "(", ")", "-prune", "-empty"]
76
+ .concat(["-true", "-false", "-depth", "-xdev"])
77
+ .map((name) => [name, false])),
78
+ };
79
+ /**
80
+ * File names that hold or may hold credentials: harness settings (they can carry tokens in `env`),
81
+ * login stores, the policy profile, and the credential names `sensitive` already knows.
82
+ */
83
+ const TRACKED_SECRET = /(?:^|\/)(?:\.env(?:\.(?!example$|sample$|template$|dist$)[^/]*)?|\.git-credentials|\.netrc|\.pgpass|\.vault-token|credentials?(?:\.\w+)?|secrets?(?:\.\w+)?|id_(?:rsa|ed25519|ecdsa)|kubeconfig|terraform\.tfstate(?:\.\w+)?|[^/]*\.(?:pem|key|pfx|p12))$/i;
84
+ const SECRET_NAME = /^(?:\.?credentials?(?:\..*)?|auth\.json|\.claude\.json|settings(?:\.local)?\.json|config\.toml|config\.json|hooks\.json|permissions-config\.json|policy\.json|\.netrc|.*\.(?:sqlite3?|db|keychain(?:-db)?))$/i;
85
+ /**
86
+ * The policy service's audit logs (`audit.jsonl`, rotated `audit.N.jsonl`) in this user's own
87
+ * session directories (`<temp>/acp-<uid>-*`), and those directories themselves, which a read may
88
+ * name: they hold decisions, not secrets. The token and socket stay secret. The path must be
89
+ * absolute and directly under the real temp directory. A glob may appear only in the `acp-<uid>-`
90
+ * segment, and a glob naming the directories themselves only for `ls` and `find`, which list names.
91
+ */
92
+ export function auditLog(path, program = "", glob = false) {
93
+ const slashed = path.replace(/\\/g, "/");
94
+ const uid = String(process.getuid?.() ?? "user");
95
+ const match = new RegExp(`^(.+)/acp-${uid}-[^/]*?(/audit(?:\\.\\d+)?\\.jsonl)?/?$`).exec(slashed);
96
+ if (!match)
97
+ return false;
98
+ const [, parent = "", file] = match;
99
+ if (/[*?[\]{}]/.test(parent) || !isAbsolute(parent))
100
+ return false;
101
+ if (glob && !file && !["ls", "find"].includes(program))
102
+ return false;
103
+ try {
104
+ const real = canonical(parent);
105
+ return tempRoots().some((root) => root === real);
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ /** Whether any word the shell may expand into file names is not an audit-log pattern. */
112
+ export function unsafeGlob(argv, glob) {
113
+ return (glob ?? []).some((expands, i) => expands && !auditLog(argv[i] ?? "", argv[0], true));
114
+ }
115
+ /** Whether a path, as written or resolved, is a credential or secret-bearing file. */
116
+ export function secretPath(path) {
117
+ const slashed = path.replace(/\\/g, "/");
118
+ return (sensitive(slashed) ||
119
+ (policyState(slashed) && !auditLog(slashed)) ||
120
+ slashed === defaultProfilePath().replace(/\\/g, "/") ||
121
+ slashed.split("/").some((part) => SECRET_NAME.test(part)));
122
+ }
123
+ function inCheckout(path) {
124
+ try {
125
+ let dir = existsSync(path) && statSync(path).isDirectory() ? path : dirname(path);
126
+ while (!existsSync(dir))
127
+ dir = dirname(dir);
128
+ const top = canonical(git(dir, ["rev-parse", "--show-toplevel"]));
129
+ return inside(top, canonical(path));
130
+ }
131
+ catch {
132
+ return false;
133
+ }
134
+ }
135
+ function resolveSafe(cwd, word) {
136
+ try {
137
+ return resolveWord(cwd, word);
138
+ }
139
+ catch {
140
+ return undefined;
141
+ }
142
+ }
143
+ /**
144
+ * Claude Code's auto-memory directories (`<config>/projects/<project>/memory/`), the only part of
145
+ * the user's agent state a plain read may name. Transcripts and history next to them may not.
146
+ */
147
+ function autoMemory(path) {
148
+ try {
149
+ const config = canonical(process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"));
150
+ if (!inside(config, path))
151
+ return false;
152
+ const parts = relative(config, path).split(/[\\/]/);
153
+ return parts.length >= 3 && parts[0] === "projects" && parts[2] === "memory";
154
+ }
155
+ catch {
156
+ return false;
157
+ }
158
+ }
159
+ /**
160
+ * The one test of whether a read may name a path, shared by plain reads and read-only chain
161
+ * prefixes: no secret, and inside a Git checkout (its own `.claude`, `.agent-config`, `AGENTS.md`
162
+ * included), the system temp directory, a profile scratch root, or Claude Code's auto-memory.
163
+ * Elsewhere under the home directory (agent transcripts and history, `.config`, `.local`, shell
164
+ * history) it may not.
165
+ */
166
+ export function readable(cwd, word, roots = []) {
167
+ if (secretPath(word))
168
+ return false;
169
+ const lexical = resolveSafe(cwd, word);
170
+ if (lexical === undefined)
171
+ return false;
172
+ let real = lexical;
173
+ try {
174
+ real = canonical(lexical);
175
+ }
176
+ catch {
177
+ /* judged as written */
178
+ }
179
+ if (secretPath(lexical) || secretPath(real))
180
+ return false;
181
+ const under = (root) => {
182
+ try {
183
+ const base = canonical(root);
184
+ return real !== base ? inside(base, real) : true;
185
+ }
186
+ catch {
187
+ return false;
188
+ }
189
+ };
190
+ return inCheckout(real) || tempRoots().some(under) || roots.some(under) || autoMemory(real);
191
+ }
192
+ /**
193
+ * The directory a `cd` to `target` enters for certain, or undefined: an absolute path (or `~/...`)
194
+ * to an existing directory that can be entered now. As a script's first command such a `cd` cannot
195
+ * fail, so what follows runs only there, however it is joined.
196
+ */
197
+ export function enterable(target) {
198
+ if (!/^(?:\/|~\/|~$|[A-Za-z]:[\\/])/.test(target))
199
+ return undefined;
200
+ if (process.env.CDPATH && !/^[/~]/.test(target))
201
+ return undefined;
202
+ try {
203
+ const dir = resolveWord("/", target);
204
+ if (!statSync(dir).isDirectory())
205
+ return undefined;
206
+ accessSync(dir, constants.X_OK);
207
+ return dir;
208
+ }
209
+ catch {
210
+ return undefined;
211
+ }
212
+ }
213
+ /**
214
+ * Whether a word given to a read-only program may be read if it names a file: a word that names an
215
+ * existing path must be `readable`, one that cannot be resolved is refused, and none may name a
216
+ * secret. The value of `--opt=value` is judged the same way.
217
+ */
218
+ export function operandReadable(cwd, word, roots = []) {
219
+ const value = word.startsWith("-") ? /^-[^=]*=(.+)$/.exec(word)?.[1] : word;
220
+ if (value === undefined)
221
+ return true;
222
+ // `rev:path` names a file in Git; a Windows drive path (`C:/x`) is not one.
223
+ const revisionPath = /^[A-Za-z]:[\\/]/.test(value)
224
+ ? undefined
225
+ : /^[^:\s]*:(.+)$/.exec(value)?.[1];
226
+ if (secretPath(value) || (revisionPath && secretPath(revisionPath)))
227
+ return false;
228
+ const path = resolveSafe(cwd, value);
229
+ if (path === undefined)
230
+ return false;
231
+ return !existsSync(path) || readable(cwd, value, roots);
232
+ }
233
+ const WALK_LIMIT = 5000;
234
+ /**
235
+ * Whether a recursive search of `dir` can reach a secret file. ripgrep (`hidden: false`) skips
236
+ * hidden entries; grep reads everything except what `--exclude`/`--exclude-dir` name. Fails closed
237
+ * past WALK_LIMIT entries or on an unreadable directory.
238
+ */
239
+ function reachesSecret(dir, hidden, exclude, excludeDir) {
240
+ let seen = 0;
241
+ const stack = [dir];
242
+ while (stack.length) {
243
+ const current = stack.pop();
244
+ let names;
245
+ try {
246
+ names = readdirSync(current);
247
+ }
248
+ catch {
249
+ return true;
250
+ }
251
+ for (const name of names) {
252
+ if (++seen > WALK_LIMIT)
253
+ return true;
254
+ if (!hidden && name.startsWith("."))
255
+ continue;
256
+ const path = join(current, name);
257
+ let stat;
258
+ try {
259
+ stat = lstatSync(path);
260
+ }
261
+ catch {
262
+ return true;
263
+ }
264
+ if (stat.isSymbolicLink())
265
+ continue; // neither grep -r nor rg follows links by default
266
+ if (stat.isDirectory()) {
267
+ if (excludeDir.some((glob) => wildcard(glob, name)))
268
+ continue;
269
+ if (secretPath(path))
270
+ return true;
271
+ stack.push(path);
272
+ }
273
+ else if (!exclude.some((glob) => wildcard(glob, name)) && secretPath(path))
274
+ return true;
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+ /** The options and operands of a reading command, or undefined if any option is not listed. */
280
+ function parse(program, args) {
281
+ const parsed = {
282
+ paths: [],
283
+ recursive: program === "rg",
284
+ exclude: [],
285
+ excludeDir: [],
286
+ };
287
+ if (program === "find") {
288
+ let predicates = false;
289
+ for (let i = 0; i < args.length; i++) {
290
+ const arg = args[i];
291
+ if (arg in FIND) {
292
+ predicates = true;
293
+ // A name pattern is not read, but one that names a secret is not taken on trust.
294
+ if (FIND[arg] && secretPath(args[++i] ?? ""))
295
+ return undefined;
296
+ }
297
+ else if (arg.startsWith("-") || predicates)
298
+ return undefined;
299
+ else
300
+ parsed.paths.push(arg);
301
+ }
302
+ return parsed;
303
+ }
304
+ const options = OPTIONS[program];
305
+ if (!options)
306
+ return undefined;
307
+ // grep and rg take the pattern as the first operand unless -e/-f gave one.
308
+ const given = args.some((arg) => arg === "--files" ||
309
+ /^-[ef]/.test(arg) ||
310
+ /^--(?:regexp|file)(?:=|$)/.test(arg) ||
311
+ /^-[^-]*[ef]$/.test(arg));
312
+ let pattern = ["grep", "egrep", "fgrep", "rg", "git-grep"].includes(program) && !given;
313
+ let operandsOnly = false;
314
+ for (let i = 0; i < args.length; i++) {
315
+ const arg = args[i];
316
+ if (operandsOnly || arg === "-" || !arg.startsWith("-")) {
317
+ // A pattern is not read, but one that names a secret path is not taken on trust either.
318
+ if (pattern) {
319
+ if (secretPath(arg))
320
+ return undefined;
321
+ pattern = false;
322
+ }
323
+ else
324
+ parsed.paths.push(arg);
325
+ continue;
326
+ }
327
+ if (arg === "--") {
328
+ operandsOnly = true;
329
+ continue;
330
+ }
331
+ if (arg.startsWith("--")) {
332
+ const [name = "", ...rest] = arg.split("=");
333
+ const value = rest.join("=");
334
+ if (options.longFiles?.has(name)) {
335
+ parsed.paths.push(value || (args[++i] ?? ""));
336
+ pattern = false;
337
+ continue;
338
+ }
339
+ if (!options.long.has(name))
340
+ return undefined;
341
+ if (name === "--recursive")
342
+ parsed.recursive = true;
343
+ if (name === "--regexp")
344
+ pattern = false;
345
+ if (name === "--exclude" && value)
346
+ parsed.exclude.push(value);
347
+ if (name === "--exclude-dir" && value)
348
+ parsed.excludeDir.push(value);
349
+ continue;
350
+ }
351
+ const short = arg.slice(0, 2);
352
+ if (options.valued.has(short)) {
353
+ const value = arg.length > 2 ? arg.slice(2) : args[++i];
354
+ if (value === undefined)
355
+ return undefined;
356
+ if (short === "-e" || short === "-f")
357
+ pattern = false;
358
+ if (options.files?.has(short))
359
+ parsed.paths.push(value);
360
+ continue;
361
+ }
362
+ if (!options.flags.test(arg))
363
+ return undefined;
364
+ if (program !== "ls" && /[rR]/.test(arg.slice(1)) && program !== "git-grep")
365
+ parsed.recursive = true;
366
+ }
367
+ return parsed;
368
+ }
369
+ /** Whether a request is a plain read of non-secret paths in a checkout or protected directory. */
370
+ export function plainRead(request, roots = []) {
371
+ const input = request.input;
372
+ if (input.env !== undefined || input.shell !== undefined || input.stdin !== undefined)
373
+ return false;
374
+ if (["Read", "view", "read_file"].includes(request.tool)) {
375
+ const file = input.file_path ?? input.path;
376
+ return typeof file === "string" && readable(request.cwd, file, roots);
377
+ }
378
+ const command = input.command ?? input.cmd;
379
+ if (!["Bash", "bash", "exec_command", "shell"].includes(request.tool))
380
+ return false;
381
+ if (typeof command !== "string" || command.length > 4000)
382
+ return false;
383
+ const pipelines = parseShell(command);
384
+ if (!pipelines)
385
+ return false;
386
+ let checked = 0;
387
+ // A `cd <dir>` may lead or join the reads; a later word is judged in every directory it could
388
+ // run in, since `cd x || cat y` reads from the old one.
389
+ const cwds = new Set([request.cwd]);
390
+ for (const pipeline of pipelines)
391
+ for (const cmd of pipeline) {
392
+ if (cmd.env.length || cmd.subs.length || cmd.stdin !== undefined)
393
+ return false;
394
+ const program = cmd.argv[0] ?? "";
395
+ const gitGrep = program === "git" && cmd.argv[1] === "grep";
396
+ // `git grep` pathspecs (`'**/*.md'`, `':(glob)src/**'`) are Git's, not files to expand.
397
+ if (cmd.loose?.some(Boolean) || (!gitGrep && unsafeGlob(cmd.argv, cmd.glob)))
398
+ return false;
399
+ if (program === "cd" && pipeline.length === 1) {
400
+ const target = cmd.argv[1];
401
+ if (cmd.argv.length !== 2 || !target || target.startsWith("-") || cmd.redirects.length)
402
+ return false;
403
+ // As the script's first command, a `cd` that cannot fail leaves only its target.
404
+ // After `||` the next command runs exactly when it fails, so `||` anywhere keeps the old one.
405
+ const sure = pipeline === pipelines[0] && !command.includes("||") ? enterable(target) : undefined;
406
+ if (sure) {
407
+ cwds.clear();
408
+ cwds.add(sure);
409
+ continue;
410
+ }
411
+ for (const dir of [...cwds]) {
412
+ const next = resolveSafe(dir, target);
413
+ if (next === undefined || !existsSync(next))
414
+ return false;
415
+ cwds.add(next);
416
+ }
417
+ if (cwds.size > 4)
418
+ return false;
419
+ continue;
420
+ }
421
+ if (!(program in OPTIONS) && program !== "find" && !gitGrep) {
422
+ // A read-only filter or git read (`git show rev:path | sed -n 1,9p | sort | uniq -c`):
423
+ // only allow-listed options; a word that names an existing file must be a readable,
424
+ // non-secret path, and no word (a script, a pattern, `rev:path`) may name a secret.
425
+ if (!readOnly(cmd.argv))
426
+ return false;
427
+ for (const word of cmd.argv.slice(1))
428
+ for (const cwd of cwds)
429
+ if (++checked > 64 || !operandReadable(cwd, word, roots))
430
+ return false;
431
+ for (const redirect of cmd.redirects) {
432
+ if (redirect.op === ">&" && redirect.target === "1" && redirect.fd === "2")
433
+ continue;
434
+ if (redirect.op === ">" && redirect.fd === "2" && redirect.target === "/dev/null")
435
+ continue;
436
+ if (redirect.op === "<" && readable(request.cwd, redirect.target, roots))
437
+ continue;
438
+ return false;
439
+ }
440
+ for (const cwd of cwds)
441
+ if (!readable(cwd, ".", roots))
442
+ return false;
443
+ continue;
444
+ }
445
+ const parsed = parse(gitGrep ? "git-grep" : program, cmd.argv.slice(gitGrep ? 2 : 1));
446
+ if (!parsed)
447
+ return false;
448
+ for (const redirect of cmd.redirects) {
449
+ if (redirect.op === ">&" && redirect.target === "1" && redirect.fd === "2")
450
+ continue;
451
+ if (redirect.op === ">" && redirect.fd === "2" && redirect.target === "/dev/null")
452
+ continue;
453
+ if (redirect.op === "<") {
454
+ parsed.paths.push(redirect.target);
455
+ continue;
456
+ }
457
+ return false;
458
+ }
459
+ for (const cwd of cwds) {
460
+ // A reader with no path searches or lists the directory it runs in.
461
+ if (!readable(cwd, ".", roots))
462
+ return false;
463
+ if (gitGrep) {
464
+ // Git reads tracked files only: none of them may be a secret.
465
+ if (parsed.paths.some((word) => secretPath(word)))
466
+ return false;
467
+ try {
468
+ const tracked = git(cwd, ["ls-files", "-z"]).split("\0");
469
+ // Tracked files that would hold a credential (a committed `.npmrc` or `.env.example`
470
+ // is configuration already in history; a committed `.env`, key or state file is not).
471
+ if (tracked.some((file) => TRACKED_SECRET.test(file)))
472
+ return false;
473
+ }
474
+ catch {
475
+ return false;
476
+ }
477
+ continue;
478
+ }
479
+ const targets = parsed.paths.length ? parsed.paths : ["."];
480
+ for (const word of parsed.paths)
481
+ if (++checked > 32 || !readable(cwd, word, roots))
482
+ return false;
483
+ if (parsed.recursive)
484
+ for (const word of targets) {
485
+ const path = resolveSafe(cwd, word);
486
+ if (path === undefined)
487
+ return false;
488
+ let directory = false;
489
+ try {
490
+ directory = statSync(path).isDirectory();
491
+ }
492
+ catch {
493
+ return false;
494
+ }
495
+ if (directory &&
496
+ reachesSecret(path, program !== "rg", parsed.exclude, parsed.excludeDir))
497
+ return false;
498
+ if (!directory && secretPath(basename(path)))
499
+ return false;
500
+ }
501
+ }
502
+ }
503
+ return true;
504
+ }
505
+ const READ_ONLY = {
506
+ pwd: { flags: /^-[LP]$/ },
507
+ true: {},
508
+ echo: { flags: /^-[neE]+$/, operands: true },
509
+ printf: { operands: true },
510
+ stat: { flags: /^-[LtFlsx]+$/, valued: ["-f", "-c"], operands: true },
511
+ file: { flags: /^-[bLhiz]+$/, operands: true },
512
+ which: { flags: /^-a$/, operands: true },
513
+ basename: { flags: /^-[az]$/, valued: ["-s"], operands: true },
514
+ dirname: { operands: true },
515
+ realpath: { flags: /^-[esmqz]+$/, operands: true },
516
+ date: { flags: /^(?:-[uRI]|-I\w+|\+.*)$/, operands: false },
517
+ wc: { flags: /^-[lwcmL]+$/, operands: true },
518
+ cut: { valued: ["-d", "-f", "-c", "-b"], flags: /^-(?:[dfcb].+|s|n)$/, operands: true },
519
+ tr: { flags: /^-[dsc]+$/, operands: true },
520
+ nl: { flags: /^-[bnv]\w*$/, operands: true },
521
+ column: { flags: /^-[tx]+$/, valued: ["-s"], operands: true },
522
+ jq: { flags: /^-[rcesnjaS]+$/, valued: ["--arg", "--argjson"], operands: true },
523
+ diff: {
524
+ flags: /^(?:-[uqNwBbiyU0-9]+|--brief|--unified(?:=\d+)?|--color(?:=\w+)?)$/,
525
+ operands: true,
526
+ },
527
+ cmp: { flags: /^-[bls]+$/, operands: true },
528
+ comm: { flags: /^-[123]+$/, operands: true },
529
+ sort: { flags: /^-[nrufbdhVMs]+$/, valued: ["-k", "-t"], operands: true },
530
+ // uniq writes its second operand: standard input only.
531
+ uniq: { flags: /^-[cdui]+$/, valued: ["-f", "-s"], operands: false },
532
+ find: {
533
+ flags: /^(?:-(?:name|iname|path|ipath|type|maxdepth|mindepth|newer|mtime|mmin|size|regex|iregex|perm|user|group|print|print0|o|or|a|and|not|prune|empty|true|false|depth|xdev)|!|\(|\))$/,
534
+ operands: true,
535
+ },
536
+ };
537
+ const GIT_READ_ONLY = {
538
+ status: {
539
+ flags: /^(?:-[sbz]+|--short|--branch|--porcelain(?:=v[12])?|-u\w*|--untracked-files(?:=\w+)?|--ignored)$/,
540
+ operands: true,
541
+ },
542
+ log: {
543
+ flags: /^(?:-\d+|-[pz]|--oneline|--graph|--decorate(?:=\w+)?|--stat|--shortstat|--name-only|--name-status|--no-merges|--merges|--first-parent|--reverse|--all|--abbrev-commit|--no-color|--color(?:=\w+)?|--(?:format|pretty|since|until|after|before|author|grep|date|max-count|skip)=.*|--)$/,
544
+ valued: ["-n"],
545
+ operands: true,
546
+ },
547
+ diff: {
548
+ flags: /^(?:--stat(?:=\d+)?|--shortstat|--numstat|--name-only|--name-status|--cached|--staged|-U\d+|--unified=\d+|--no-color|--color(?:=\w+)?|-w|--ignore-space-change|--ignore-all-space|--exit-code|--quiet|-M|-R|--)$/,
549
+ operands: true,
550
+ },
551
+ show: {
552
+ flags: /^(?:--stat|--name-only|--name-status|--oneline|-s|--no-patch|--no-color|--color(?:=\w+)?|-U\d+|--(?:format|pretty)=.*|--)$/,
553
+ operands: true,
554
+ },
555
+ "rev-parse": {
556
+ flags: /^(?:--abbrev-ref|--short(?:=\d+)?|--verify|--quiet|-q|--show-toplevel|--git-dir|--git-common-dir|--absolute-git-dir|--path-format=\w+|--symbolic-full-name|--is-inside-work-tree)$/,
557
+ operands: true,
558
+ },
559
+ "ls-files": {
560
+ flags: /^(?:-[zcmdoti]+|--others|--cached|--modified|--deleted|--exclude-standard|--)$/,
561
+ operands: true,
562
+ },
563
+ "for-each-ref": {
564
+ flags: /^(?:--(?:format|count|sort|contains|merged|no-merged|points-at)(?:=.*)?)$/,
565
+ operands: true,
566
+ },
567
+ "merge-base": { flags: /^(?:--is-ancestor|--all|--fork-point)$/, operands: true },
568
+ "cat-file": { flags: /^-[tspe]$/, operands: true },
569
+ describe: { flags: /^(?:--tags|--always|--long|--abbrev=\d+|--exact-match)$/, operands: true },
570
+ "rev-list": {
571
+ flags: /^(?:--count|--all|--max-count=\d+|--left-right|--not|--first-parent|--no-merges|-n\d*)$/,
572
+ operands: true,
573
+ },
574
+ shortlog: { flags: /^-[sne]+$|^--(?:summary|numbered|email)$/, operands: true },
575
+ blame: {
576
+ flags: /^(?:-[wsef]+|-L.+|--porcelain|--line-porcelain)$/,
577
+ valued: ["-L"],
578
+ operands: true,
579
+ },
580
+ // A refspec with a destination (`+pull/1/head:refs/heads/x`) can overwrite a local branch.
581
+ fetch: {
582
+ flags: /^(?:-q|--quiet|--tags|--no-tags)$/,
583
+ operands: true,
584
+ // Only from `origin`: a fetch from another repository changes the refs the engine trusts.
585
+ check: (operands) => (operands[0] === undefined || operands[0] === "origin") &&
586
+ operands.every((operand) => !operand.includes(":")),
587
+ },
588
+ };
589
+ function allowed(spec, args) {
590
+ const operands = [];
591
+ for (let i = 0; i < args.length; i++) {
592
+ const arg = args[i];
593
+ if (arg.startsWith("-") && arg !== "-") {
594
+ if (spec.valued?.includes(arg)) {
595
+ if (args[++i] === undefined)
596
+ return false;
597
+ continue;
598
+ }
599
+ if (!spec.flags?.test(arg))
600
+ return false;
601
+ continue;
602
+ }
603
+ if (arg === "!" || arg === "(" || arg === ")") {
604
+ if (!spec.flags?.test(arg))
605
+ return false;
606
+ continue;
607
+ }
608
+ // `find -name x`: the value of a find predicate.
609
+ operands.push(arg);
610
+ }
611
+ if (operands.length && !spec.operands)
612
+ return false;
613
+ return spec.check ? spec.check(operands) : true;
614
+ }
615
+ export function readOnly(argv) {
616
+ const [program = "", ...args] = argv;
617
+ if (program === "git") {
618
+ let index = 0;
619
+ while (args[index] === "-C" || args[index] === "--no-pager")
620
+ index += args[index] === "-C" ? 2 : 1;
621
+ if (args[index] === "grep")
622
+ return true; // the full plain-read check follows
623
+ const spec = GIT_READ_ONLY[args[index] ?? ""];
624
+ return !!spec && allowed(spec, args.slice(index + 1));
625
+ }
626
+ // The readers (cat, ls, grep, rg, head, tail, git grep) get the full plain-read check instead.
627
+ if (["cat", "ls", "grep", "egrep", "fgrep", "rg", "head", "tail"].includes(program))
628
+ return true;
629
+ if (program === "sed")
630
+ return sedReadOnly(args);
631
+ if (["awk", "gawk", "mawk", "nawk"].includes(program))
632
+ return awkReadOnly(args);
633
+ const spec = READ_ONLY[program];
634
+ return !!spec && allowed(spec, args);
635
+ }
636
+ /**
637
+ * sed that only prints: no `-i`, no script file, and every script free of the commands that write
638
+ * a file or run one (`w`, `W`, `r`, `R`, `e`, an `s///` with the `w` or `e` flag). An unknown
639
+ * command is not read-only.
640
+ */
641
+ function sedReadOnly(args) {
642
+ const scripts = [];
643
+ let given = false;
644
+ const operands = [];
645
+ for (let i = 0; i < args.length; i++) {
646
+ const arg = args[i];
647
+ if (arg === "-e" || arg === "--expression") {
648
+ const value = args[++i];
649
+ if (value === undefined)
650
+ return false;
651
+ scripts.push(value);
652
+ given = true;
653
+ }
654
+ else if (arg.startsWith("--expression=")) {
655
+ scripts.push(arg.slice(13));
656
+ given = true;
657
+ }
658
+ else if (/^-e./.test(arg)) {
659
+ scripts.push(arg.slice(2));
660
+ given = true;
661
+ }
662
+ else if (/^-[nErsuz]+$/.test(arg) ||
663
+ /^--(?:quiet|silent|regexp-extended|separate|null-data)$/.test(arg))
664
+ continue;
665
+ else if (arg.startsWith("-"))
666
+ return false;
667
+ else
668
+ operands.push(arg);
669
+ }
670
+ if (!given) {
671
+ const script = operands.shift();
672
+ if (script === undefined)
673
+ return false;
674
+ scripts.push(script);
675
+ }
676
+ return scripts.every(sedScriptReadOnly);
677
+ }
678
+ /**
679
+ * awk that only reads and prints to standard output: no script file, and a program without
680
+ * `system`, `getline`, a pipe or a `>` (a redirection, or a comparison it cannot tell apart).
681
+ */
682
+ function awkReadOnly(args) {
683
+ const operands = [];
684
+ for (let i = 0; i < args.length; i++) {
685
+ const arg = args[i];
686
+ if (arg === "-F" || arg === "-v") {
687
+ if (args[++i] === undefined)
688
+ return false;
689
+ }
690
+ else if (/^-[Fv]./.test(arg))
691
+ continue;
692
+ else if (arg.startsWith("-"))
693
+ return false;
694
+ else
695
+ operands.push(arg);
696
+ }
697
+ const program = operands[0];
698
+ return program !== undefined && !/system|getline|\||>|close\s*\(|fflush|print\s*>/.test(program);
699
+ }
700
+ /** Whether a sed script only prints: no file it reads or writes and no command it runs. */
701
+ function sedScriptReadOnly(script) {
702
+ const scanned = sedScript(script);
703
+ return !!scanned && !scanned.runs && !scanned.files.length;
704
+ }
705
+ /**
706
+ * The files a sed script reads or writes (`r`, `R`, `w`, `W`, an `s///w` flag) and whether it runs
707
+ * a command (`e`, an `s///e` flag), read the way sed parses it: text in `s` and `y` patterns and
708
+ * replacements, and after `a`, `i` and `c`, is data. Undefined when the script cannot be read.
709
+ */
710
+ export function sedScript(script) {
711
+ const files = [];
712
+ let runs = false;
713
+ let i = 0;
714
+ const n = script.length;
715
+ /** Reads up to an unescaped `delimiter`, past it. */
716
+ const until = (delimiter) => {
717
+ while (i < n) {
718
+ const c = script[i++];
719
+ if (c === "\\")
720
+ i++;
721
+ else if (c === delimiter)
722
+ return true;
723
+ }
724
+ return false;
725
+ };
726
+ /** The rest of the line: a file name. */
727
+ const restOfLine = () => {
728
+ const start = i;
729
+ while (i < n && script[i] !== "\n")
730
+ i++;
731
+ return script.slice(start, i).trim();
732
+ };
733
+ while (i < n) {
734
+ while (i < n && /[\s;]/.test(script[i]))
735
+ i++;
736
+ if (i >= n)
737
+ break;
738
+ // Addresses: line numbers, `$`, `/re/`, `\cREc`, ranges, steps and negation.
739
+ for (;;) {
740
+ const c = script[i];
741
+ if (c !== undefined && /[\d$,!~+]/.test(c))
742
+ i++;
743
+ else if (c === "/") {
744
+ i++;
745
+ if (!until("/"))
746
+ return undefined;
747
+ }
748
+ else if (c === "\\" && script[i + 1] !== undefined) {
749
+ const delimiter = script[i + 1];
750
+ i += 2;
751
+ if (!until(delimiter))
752
+ return undefined;
753
+ }
754
+ else
755
+ break;
756
+ }
757
+ while (i < n && /[ \t]/.test(script[i]))
758
+ i++;
759
+ const command = script[i++];
760
+ if (command === undefined)
761
+ break;
762
+ if (command === "{" || command === "}")
763
+ continue;
764
+ if (command === "s" || command === "y") {
765
+ const delimiter = script[i++];
766
+ if (delimiter === undefined || delimiter === "\\" || delimiter === "\n")
767
+ return undefined;
768
+ if (!until(delimiter) || !until(delimiter))
769
+ return undefined;
770
+ if (command === "s") {
771
+ while (i < n && /[gpIiMm0-9eE]/.test(script[i])) {
772
+ if (/[eE]/.test(script[i]))
773
+ runs = true;
774
+ i++;
775
+ }
776
+ if (script[i] === "w" || script[i] === "W") {
777
+ i++;
778
+ files.push(restOfLine());
779
+ }
780
+ }
781
+ continue;
782
+ }
783
+ if ("aic".includes(command)) {
784
+ // Text to print: to the end of the line, and on past every line that ends in a backslash.
785
+ while (i < n && !(script[i] === "\n" && script[i - 1] !== "\\"))
786
+ i++;
787
+ continue;
788
+ }
789
+ if ("rRwW".includes(command)) {
790
+ files.push(restOfLine());
791
+ continue;
792
+ }
793
+ if (command === "e") {
794
+ runs = true;
795
+ restOfLine();
796
+ continue;
797
+ }
798
+ if (":btT".includes(command)) {
799
+ while (i < n && !/[;\n]/.test(script[i]))
800
+ i++;
801
+ continue;
802
+ }
803
+ if ("pPdDnNgGhHxlq=QzF".includes(command)) {
804
+ while (i < n && /\d/.test(script[i]))
805
+ i++;
806
+ continue;
807
+ }
808
+ return undefined;
809
+ }
810
+ return { files, runs };
811
+ }
812
+ //# sourceMappingURL=reads.js.map