@peer2peer/codex-bridge 0.1.0 → 0.1.2
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/README.md +7 -5
- package/dist/bridge.d.ts +57 -5
- package/dist/bridge.js +172 -39
- package/dist/hook.d.ts +11 -0
- package/dist/hook.js +110 -10
- package/dist/index.js +1 -1
- package/dist/install.js +8 -3
- package/dist/lib.d.ts +141 -14
- package/dist/lib.js +1391 -83
- package/dist/p2p.d.ts +46 -3
- package/dist/p2p.js +37 -3
- package/dist/server.d.ts +1 -1
- package/dist/server.js +12 -4
- package/dist/tools.d.ts +15 -0
- package/dist/tools.js +76 -6
- package/dist/trusted.d.ts +13 -0
- package/dist/trusted.js +40 -0
- package/package.json +4 -1
package/dist/lib.js
CHANGED
|
@@ -13,6 +13,31 @@ const FP = "[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}";
|
|
|
13
13
|
const USER_ID_RE = /^p2p:[a-z2-7]{20,}$/;
|
|
14
14
|
const REF_RE = /^[0-9a-f]{6}$/;
|
|
15
15
|
const LABEL_MAX = 40;
|
|
16
|
+
// ── linear scans ────────────────────────────────────────────────────────────
|
|
17
|
+
// Peer and agent text reaches these, so no backtracking regex: each is one pass.
|
|
18
|
+
/** `s` without any of `chars` at its end (and at its start when `start`). */
|
|
19
|
+
export function trimChars(s, chars, start = false) {
|
|
20
|
+
let i = 0;
|
|
21
|
+
let j = s.length;
|
|
22
|
+
if (start)
|
|
23
|
+
while (i < j && chars.includes(s.charAt(i)))
|
|
24
|
+
i++;
|
|
25
|
+
while (j > i && chars.includes(s.charAt(j - 1)))
|
|
26
|
+
j--;
|
|
27
|
+
return s.slice(i, j);
|
|
28
|
+
}
|
|
29
|
+
/** `<head> [ref]` → [head, ref], the head without trailing whitespace; null without a trailing ref. */
|
|
30
|
+
export function splitRef(s) {
|
|
31
|
+
const n = s.length;
|
|
32
|
+
if (n < 8 || s.charAt(n - 1) !== "]" || s.charAt(n - 8) !== "[")
|
|
33
|
+
return null;
|
|
34
|
+
const ref = s.slice(n - 7, n - 1);
|
|
35
|
+
if (!REF_RE.test(ref))
|
|
36
|
+
return null;
|
|
37
|
+
const head = s.slice(0, n - 8).trimEnd();
|
|
38
|
+
// As /^(.*?)\s*\[([0-9a-f]{6})\]$/ did: `.` never spans a line break.
|
|
39
|
+
return /[\n\r\u2028\u2029]/.test(head) ? null : [head, ref];
|
|
40
|
+
}
|
|
16
41
|
// ── untrusted text ──────────────────────────────────────────────────────────
|
|
17
42
|
/** Control, format (bidi overrides, zero-width, tags) and line/paragraph separator characters. */
|
|
18
43
|
const UNSAFE = /[\p{Cc}\p{Cf}\u2028\u2029]/gu;
|
|
@@ -33,19 +58,15 @@ export function inertMax(text, max) {
|
|
|
33
58
|
}
|
|
34
59
|
/** A session label as the bridge sends it: `[a-z0-9._-]`, at most 40. */
|
|
35
60
|
export function sanitizeLabel(raw) {
|
|
36
|
-
const
|
|
61
|
+
const dashed = raw
|
|
37
62
|
.toLowerCase()
|
|
38
|
-
.replace(/[^a-z0-9._-]+/g, "-")
|
|
39
|
-
|
|
40
|
-
.slice(0, LABEL_MAX);
|
|
63
|
+
.replace(/[^a-z0-9._-]+/g, "-");
|
|
64
|
+
const label = trimChars(dashed, "-", true).slice(0, LABEL_MAX);
|
|
41
65
|
return label === "" ? "session" : label;
|
|
42
66
|
}
|
|
43
67
|
/** A peer's label as it appears inside an address: inert, no spaces, slashes or brackets. */
|
|
44
68
|
export function addressLabel(label) {
|
|
45
|
-
return (inert(label)
|
|
46
|
-
.replace(/[\s[\]/"&:]+/g, "-")
|
|
47
|
-
.replace(/^-+|-+$/g, "")
|
|
48
|
-
.slice(0, 64) || "session");
|
|
69
|
+
return trimChars(inert(label).replace(/[\s[\]/"&:]+/g, "-"), "-", true).slice(0, 64) || "session";
|
|
49
70
|
}
|
|
50
71
|
/** Message text with control and format characters gone; line breaks and tabs kept. */
|
|
51
72
|
export function cleanBody(text) {
|
|
@@ -81,9 +102,9 @@ export function wrapMessage(from, text, at) {
|
|
|
81
102
|
*/
|
|
82
103
|
export function parseAddress(to) {
|
|
83
104
|
const s = to.trim();
|
|
84
|
-
const ref =
|
|
85
|
-
const head = (ref ? ref[
|
|
86
|
-
const pick = ref?.[
|
|
105
|
+
const ref = splitRef(s);
|
|
106
|
+
const head = (ref ? ref[0] : s).trim();
|
|
107
|
+
const pick = ref?.[1];
|
|
87
108
|
if (USER_ID_RE.test(head))
|
|
88
109
|
return { user: head, ...(pick ? { ref: pick } : {}) };
|
|
89
110
|
const body = head.startsWith(P2P_PREFIX) ? head.slice(P2P_PREFIX.length) : head;
|
|
@@ -124,6 +145,11 @@ export function resolveTarget(to, peers, ownSid) {
|
|
|
124
145
|
return { kind: "peer", to: `${only.own} [${only.ref}]`, peer: only };
|
|
125
146
|
if (hits.length > 1)
|
|
126
147
|
return { kind: "ambiguous", candidates: hits };
|
|
148
|
+
// A label alone names a listed session or nothing: never the user's bare address, which the CLI
|
|
149
|
+
// would send to another of their sessions (or, for this session's own label, another device of yours).
|
|
150
|
+
if (parsed.label !== undefined && parsed.ref === undefined) {
|
|
151
|
+
return { kind: "refused", code: "no-label", reason: `No session of ${inertMax(parsed.user, 80)} labelled "${inertMax(parsed.label, 40)}" is listed right now: p2p_list_peers shows the live ones.` };
|
|
152
|
+
}
|
|
127
153
|
return { kind: "cli", to: parsed.ref ? `${parsed.user} [${parsed.ref}]` : parsed.user };
|
|
128
154
|
}
|
|
129
155
|
/**
|
|
@@ -131,11 +157,30 @@ export function resolveTarget(to, peers, ownSid) {
|
|
|
131
157
|
* label and ref) when it came from one, else the user's address alone.
|
|
132
158
|
*/
|
|
133
159
|
export function eventAddress(event, peers) {
|
|
160
|
+
// One of this user's own sessions: own/sid name the session it went INTO (this one), never the sender.
|
|
161
|
+
// The sending session when the CLI knows it (this device), else no session at all.
|
|
162
|
+
if (event.from.self === true) {
|
|
163
|
+
const ref = typeof event.fromRef === "string" && REF_RE.test(event.fromRef) ? event.fromRef : undefined;
|
|
164
|
+
if (ref === undefined)
|
|
165
|
+
return `${sessionAddress({ address: event.from.address })} (another of your sessions)`;
|
|
166
|
+
const known = peers.find((p) => p.own === event.from.userId && p.ref === ref);
|
|
167
|
+
return sessionAddress({ address: event.from.address, ref, ...(known ? { label: known.label } : {}) });
|
|
168
|
+
}
|
|
134
169
|
if (event.own !== event.from.userId)
|
|
135
170
|
return sessionAddress({ address: event.from.address });
|
|
136
171
|
const known = peers.find((p) => p.own === event.own && p.sid === event.sid);
|
|
137
172
|
return sessionAddress({ address: event.from.address, ref: event.ref, ...(known ? { label: known.label } : {}) });
|
|
138
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Where a delivery notice to a received message goes: a peer's own session by its ref, else the peer;
|
|
176
|
+
* one of this user's own sessions only by the sending session's ref (this device's record), else
|
|
177
|
+
* nowhere ("": never this session's own address, never the bare address).
|
|
178
|
+
*/
|
|
179
|
+
export function replyToOf(event) {
|
|
180
|
+
if (event.from.self === true)
|
|
181
|
+
return typeof event.fromRef === "string" && REF_RE.test(event.fromRef) ? `${event.from.userId} [${event.fromRef}]` : "";
|
|
182
|
+
return event.own === event.from.userId ? `${event.from.userId} [${event.ref}]` : event.from.userId;
|
|
183
|
+
}
|
|
139
184
|
const ASKING_APPROVALS = new Set(["untrusted", "on-request", "on-failure"]);
|
|
140
185
|
const ASKING_PERMISSION_MODES = new Set(["default", "plan"]);
|
|
141
186
|
/**
|
|
@@ -232,10 +277,12 @@ export function capHeld(list) {
|
|
|
232
277
|
const kept = [];
|
|
233
278
|
for (let i = list.length - 1; i >= 0; i--) {
|
|
234
279
|
const item = list[i];
|
|
235
|
-
|
|
280
|
+
// Your own sessions each get their own bucket (`bucket`), not one shared by all of them.
|
|
281
|
+
const key = item.bucket ?? item.from.userId;
|
|
282
|
+
const n = counts.get(key) ?? 0;
|
|
236
283
|
if (n >= HELD_PER_SENDER || kept.length >= HELD_TOTAL)
|
|
237
284
|
continue;
|
|
238
|
-
counts.set(
|
|
285
|
+
counts.set(key, n + 1);
|
|
239
286
|
kept.push(item);
|
|
240
287
|
}
|
|
241
288
|
return kept.reverse();
|
|
@@ -258,7 +305,7 @@ const MAX_FILE_CHARS = 200;
|
|
|
258
305
|
const isWindowsPath = (p) => /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
|
|
259
306
|
/** The last segment of a path, whichever separator it uses. */
|
|
260
307
|
export function pathBasename(path) {
|
|
261
|
-
const trimmed = path
|
|
308
|
+
const trimmed = trimChars(path, "\\/");
|
|
262
309
|
return trimmed.split(/[\\/]/).pop() || undefined;
|
|
263
310
|
}
|
|
264
311
|
/** A relative path as the relay takes it (core isSafeRelativePath, plus the mod's own rules). */
|
|
@@ -307,12 +354,11 @@ export function stripPaths(line) {
|
|
|
307
354
|
}
|
|
308
355
|
/** A summary as one shareable line (no absolute paths, at most 200 characters), or undefined. */
|
|
309
356
|
export function cleanSummary(text) {
|
|
310
|
-
const
|
|
357
|
+
const folded = String(text)
|
|
311
358
|
.replace(/\s+/g, " ")
|
|
312
359
|
.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "")
|
|
313
|
-
.trim()
|
|
314
|
-
.replace(/^["'`]+|["'`]+$/g, "")
|
|
315
360
|
.trim();
|
|
361
|
+
const line = trimChars(folded, "\"'`", true).trim();
|
|
316
362
|
if (line === "" || /^(none|n\/a|unknown)\.?$/i.test(line))
|
|
317
363
|
return undefined;
|
|
318
364
|
const scrubbed = stripPaths(line);
|
|
@@ -392,7 +438,8 @@ export const MUTATING_TOOLS = new Set([
|
|
|
392
438
|
"p2p_release",
|
|
393
439
|
]);
|
|
394
440
|
/** `p2p` verbs that change who reaches this user, or touch its keys (the mod's guard list). */
|
|
395
|
-
|
|
441
|
+
// `history`: the person's messages (and `history --clear` deletes them); a session's own come through p2p_history.
|
|
442
|
+
const MUTATING_ONE = new Set(["join", "accept", "invite", "backup", "setup", "init", "remove", "unfriend", "block", "petname", "link", "release", "history"]);
|
|
396
443
|
const MUTATING_TWO = new Set([
|
|
397
444
|
"held approve",
|
|
398
445
|
"held decline",
|
|
@@ -418,19 +465,504 @@ const MUTATING_TWO = new Set([
|
|
|
418
465
|
"project share",
|
|
419
466
|
"project private",
|
|
420
467
|
]);
|
|
421
|
-
/**
|
|
422
|
-
|
|
423
|
-
|
|
468
|
+
/**
|
|
469
|
+
* Verbs refused only as the subcommand itself (common words in message text): `receipt` reports for a
|
|
470
|
+
* session (its front end's job), `own-agents` decides whether your agent sessions skip the hold (yours).
|
|
471
|
+
*/
|
|
472
|
+
const MUTATING_FIRST = new Set(["receipt", "own-agents"]);
|
|
473
|
+
/** `p2p send` options that take the next word as their value, whatever it is (`--` and `--from-session=x` included). */
|
|
474
|
+
const SEND_VALUE_OPTIONS = new Set(["--to", "--project-dir"]);
|
|
475
|
+
/** Characters that can make a shell word other than what it reads as here: expansions, globs, quoting, or a redirection (`<`: shellTokens marks its target). */
|
|
476
|
+
const NOT_PLAIN = "$`{}*?[]~\\'\"<>\r";
|
|
477
|
+
/** A word written as plain text (its source, from shellTokens' `raws`): what it reads as is what the shell passes. */
|
|
478
|
+
function isPlainWord(raw) {
|
|
479
|
+
if (raw === undefined || raw === "" || raw.includes("__SUB__"))
|
|
480
|
+
return false;
|
|
481
|
+
for (const ch of raw)
|
|
482
|
+
if (NOT_PLAIN.includes(ch))
|
|
483
|
+
return false;
|
|
484
|
+
return true;
|
|
485
|
+
}
|
|
486
|
+
/**
|
|
487
|
+
* Whether a `p2p send` command line gives --from-session as the CLI's option (the mod's
|
|
488
|
+
* `sendNamesFromSession`; both are pinned to the same vectors). `args` are the words after the CLI's
|
|
489
|
+
* name and `raws` their source text. Read the way the CLI reads its argv: `--no-input` before the
|
|
490
|
+
* first `--` dropped first (cli.ts main), nothing after a `--` (text from there on, even with the
|
|
491
|
+
* `--` before `send`), and never another option's value (`--to --from-session=x` sends to
|
|
492
|
+
* "--from-session=x" from the `tui` session). The shell makes that argv, and this can't expand it:
|
|
493
|
+
* every word up to and including the deciding one must be written plain (no expansion, glob, brace,
|
|
494
|
+
* tilde, quote, escape, redirection or carriage return), or the answer is no, and the guard refuses. Linear.
|
|
495
|
+
*/
|
|
496
|
+
export function sendNamesFromSession(args, raws) {
|
|
497
|
+
const end = args.indexOf("--");
|
|
498
|
+
const words = [];
|
|
499
|
+
for (let k = 0; k < args.length; k++) {
|
|
500
|
+
const w = args[k] ?? "";
|
|
501
|
+
if (w === "--no-input" && (end < 0 || k < end) && isPlainWord(raws[k]))
|
|
502
|
+
continue;
|
|
503
|
+
words.push({ w, raw: raws[k] });
|
|
504
|
+
}
|
|
505
|
+
for (let i = 0; i < words.length; i++) {
|
|
506
|
+
const { w, raw } = words[i];
|
|
507
|
+
if (!isPlainWord(raw))
|
|
508
|
+
return false;
|
|
509
|
+
if (w === "--")
|
|
510
|
+
return false;
|
|
511
|
+
if (w === "--from-session" || w.startsWith("--from-session="))
|
|
512
|
+
return true;
|
|
513
|
+
if (SEND_VALUE_OPTIONS.has(w)) {
|
|
514
|
+
i++;
|
|
515
|
+
if (!isPlainWord(words[i]?.raw))
|
|
516
|
+
return false;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
/** The CLI's own built entry point run by path (`…/p2p/dist/bin.js`, `…/@peer2peer/cli/dist/bin.js`): the mod's `cliBinJs`. */
|
|
522
|
+
function cliBinJs(word) {
|
|
523
|
+
const w = word.replace(/\\/g, "/").toLowerCase();
|
|
524
|
+
return w.endsWith("/p2p/dist/bin.js") || w.endsWith("@peer2peer/cli/dist/bin.js");
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* `env`'s split string (`-S <cmd …>`, `-S<cmd …>`, `-vS <cmd …>`, `--split-string[=]<cmd …>`) among its
|
|
528
|
+
* options and assignments, from `from` (the word after `env`) up to its command: the command line it
|
|
529
|
+
* holds and the index of the first word after it, or null. The mod's `envSplitString`; both are pinned
|
|
530
|
+
* to the same vectors. Linear.
|
|
531
|
+
*/
|
|
532
|
+
export function envSplitString(words, from) {
|
|
533
|
+
for (let j = from; j < words.length; j++) {
|
|
534
|
+
const w = words[j] ?? "";
|
|
535
|
+
if (w === "--split-string")
|
|
536
|
+
return words[j + 1] === undefined ? null : { line: words[j + 1] ?? "", next: j + 2 };
|
|
537
|
+
if (w.startsWith("--split-string="))
|
|
538
|
+
return { line: w.slice("--split-string=".length), next: j + 1 };
|
|
539
|
+
if (w === "--unset" || w === "--chdir") {
|
|
540
|
+
j++;
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
// NAME=VALUE before the command; anything else that isn't an option is the command (or `--` ends the options).
|
|
544
|
+
if (!w.startsWith("-") || w === "-") {
|
|
545
|
+
if (w.indexOf("=") > 0)
|
|
546
|
+
continue;
|
|
547
|
+
return null;
|
|
548
|
+
}
|
|
549
|
+
// `--` ends env's options, but a `-S` read past it fails closed (`env -- -S '…'` is still read as a split string).
|
|
550
|
+
if (w === "--")
|
|
551
|
+
continue;
|
|
552
|
+
if (w.startsWith("--"))
|
|
553
|
+
continue;
|
|
554
|
+
// Short options, bundled: -S takes the rest of the word or the next one; -u and -C take a value.
|
|
555
|
+
for (let k = 1; k < w.length; k++) {
|
|
556
|
+
const o = w[k];
|
|
557
|
+
if (o === "S") {
|
|
558
|
+
if (k + 1 < w.length)
|
|
559
|
+
return { line: w.slice(k + 1), next: j + 1 };
|
|
560
|
+
return words[j + 1] === undefined ? null : { line: words[j + 1] ?? "", next: j + 2 };
|
|
561
|
+
}
|
|
562
|
+
if (o === "u" || o === "C") {
|
|
563
|
+
if (k + 1 === w.length)
|
|
564
|
+
j++;
|
|
565
|
+
break;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
return null;
|
|
570
|
+
}
|
|
571
|
+
// ---- Shared with the Codex bridge, byte for byte (the mod's hooks/lib.ts and the bridge's src/lib.ts): see indirectP2PRun.
|
|
572
|
+
/** Runners that build a command's argv from their own arguments (`parallel p2p ::: invite`): the guards never see it. */
|
|
573
|
+
const ARG_RUNNERS = new Set(['parallel', 'sem', 'parset', 'rush', 'xjobs']);
|
|
574
|
+
/** `xargs` under its names: it runs its arguments with words read from stdin. */
|
|
575
|
+
const XARGS = new Set(['xargs', 'gxargs']);
|
|
576
|
+
/** Words before a simple command's command word: keywords, and builtins and wrappers that run the next word. */
|
|
577
|
+
const LEAD_WORDS = new Set(['{', '!', 'if', 'then', 'do', 'else', 'elif', 'while', 'until', 'time', 'exec', 'command', 'builtin', 'eval', 'sudo', 'doas', 'env', 'nice', 'nohup', 'timeout', 'stdbuf', 'xargs', 'gxargs', 'busybox', 'coproc', 'setsid', 'flock', 'chrt', 'taskset', 'ionice', 'caffeinate', 'unshare', 'watch']);
|
|
578
|
+
/** Those wrappers' options that take the next word as their value (`sudo -u x`, `timeout -s KILL`, `ionice -c 2`). */
|
|
579
|
+
const VALUE_OPTIONS = new Set(['-u', '-g', '-p', '-s', '-k', '-n', '-C', '-c', '-w', '-E', '--user', '--group', '--signal', '--kill-after', '--chdir', '--interval']);
|
|
580
|
+
/** Commands whose arguments are text: a quoted argument isn't read again as a script (a substitution in it still is). */
|
|
581
|
+
const TEXT_ARGS = new Set(['echo', 'printf', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'git', 'gh', 'cat', 'head', 'tail', 'wc', 'diff', 'jq', 'tee', 'less', 'more']);
|
|
582
|
+
/** Shells xargs may run with words from stdin as their script (`… | xargs -I{} sh -c '{}'`). */
|
|
583
|
+
const XARGS_SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'fish', 'eval']);
|
|
584
|
+
/** Assignments that define a function or an alias by name (zsh's `functions`/`aliases`/`galiases`, bash's BASH_ALIASES). */
|
|
585
|
+
const NAME_STORES = ['functions[', 'aliases[', 'galiases[', 'saliases[', 'dis_functions[', 'dis_aliases[', 'BASH_ALIASES[', 'BASH_ALIASES=', 'BASH_ALIASES+=', 'BASH_CMDS[', 'BASH_CMDS=', 'BASH_CMDS+='];
|
|
586
|
+
/** How deep quoted scripts are read again; past it, a word that still names p2p is refused. */
|
|
587
|
+
const MAX_NESTING = 4;
|
|
588
|
+
const NESTED = 'a command nested too deeply to check, that names p2p';
|
|
589
|
+
/** The CLI named as a word (the guards' isCli, without configured names): `p2p`, `p2p.mjs`, `@peer2peer/cli`, `$P2P_BIN`. */
|
|
590
|
+
function cliWord(word) {
|
|
591
|
+
const base = (word.split(/[\\/]/).pop() ?? word).toLowerCase();
|
|
592
|
+
return base === 'p2p' || base === 'p2p.exe' || base === 'p2p.cmd' || base === 'p2p.mjs' || base === 'p2p.cjs' || base === 'p2p.js' || word.startsWith('@peer2peer/cli') || word === '$P2P_BIN' || word === '${P2P_BIN}';
|
|
593
|
+
}
|
|
594
|
+
/** Whether a text names p2p at all (a substring: errs towards yes). */
|
|
595
|
+
function mentionsP2P(text) {
|
|
596
|
+
const lower = text.toLowerCase();
|
|
597
|
+
return lower.includes('p2p') || lower.includes('@peer2peer');
|
|
598
|
+
}
|
|
599
|
+
/** The text with every quoted span (and each escaped character) blanked, positions kept. One pass. */
|
|
600
|
+
function unquoted(text) {
|
|
601
|
+
const out = text.split('');
|
|
602
|
+
let q = '';
|
|
603
|
+
for (let i = 0; i < text.length; i++) {
|
|
604
|
+
const c = text[i];
|
|
605
|
+
if (q === "'") {
|
|
606
|
+
if (c === "'")
|
|
607
|
+
q = '';
|
|
608
|
+
else
|
|
609
|
+
out[i] = ' ';
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
if (q === '"' || q === '$') {
|
|
613
|
+
if (c === '\\') {
|
|
614
|
+
out[i] = ' ';
|
|
615
|
+
if (i + 1 < text.length)
|
|
616
|
+
out[++i] = ' ';
|
|
617
|
+
}
|
|
618
|
+
else if (c === (q === '$' ? "'" : '"'))
|
|
619
|
+
q = '';
|
|
620
|
+
else
|
|
621
|
+
out[i] = ' ';
|
|
622
|
+
continue;
|
|
623
|
+
}
|
|
624
|
+
if (c === '\\') {
|
|
625
|
+
out[i] = ' ';
|
|
626
|
+
if (i + 1 < text.length)
|
|
627
|
+
out[++i] = ' ';
|
|
628
|
+
}
|
|
629
|
+
else if (c === '$' && text[i + 1] === "'") {
|
|
630
|
+
q = '$';
|
|
631
|
+
i++;
|
|
632
|
+
}
|
|
633
|
+
else if (c === "'" || c === '"')
|
|
634
|
+
q = c;
|
|
635
|
+
}
|
|
636
|
+
return out.join('');
|
|
637
|
+
}
|
|
638
|
+
/** The backtick substitutions in a text, unquoted or inside double quotes (where they run; never inside single quotes). One pass. */
|
|
639
|
+
function backticks(text) {
|
|
640
|
+
const out = [];
|
|
641
|
+
let q = '';
|
|
642
|
+
for (let i = 0; i < text.length; i++) {
|
|
643
|
+
const c = text[i];
|
|
644
|
+
if (q === "'") {
|
|
645
|
+
if (c === "'")
|
|
646
|
+
q = '';
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
if (c === '\\') {
|
|
650
|
+
i++;
|
|
651
|
+
continue;
|
|
652
|
+
}
|
|
653
|
+
if (q === '$') {
|
|
654
|
+
if (c === "'")
|
|
655
|
+
q = '';
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (c === '`') {
|
|
659
|
+
let j = i + 1;
|
|
660
|
+
while (j < text.length && text[j] !== '`')
|
|
661
|
+
j += text[j] === '\\' ? 2 : 1;
|
|
662
|
+
out.push(text.slice(i + 1, Math.min(j, text.length)));
|
|
663
|
+
i = j;
|
|
664
|
+
continue;
|
|
665
|
+
}
|
|
666
|
+
if (q === '"') {
|
|
667
|
+
if (c === '"')
|
|
668
|
+
q = '';
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
if (c === '$' && text[i + 1] === "'") {
|
|
672
|
+
q = '$';
|
|
673
|
+
i++;
|
|
674
|
+
}
|
|
675
|
+
else if (c === "'" || c === '"')
|
|
676
|
+
q = c;
|
|
677
|
+
}
|
|
678
|
+
return out;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* The text with the bodies of quoted heredocs fed to a text command blanked (`cat > f <<'EOF'`: data,
|
|
682
|
+
* nothing in it runs), positions kept. Any other heredoc is left as written. `unq` is unquoted(text).
|
|
683
|
+
* One pass: each line is read once, and each line's command word once.
|
|
684
|
+
*/
|
|
685
|
+
function blankHeredocs(text, unq) {
|
|
686
|
+
const out = text.split('');
|
|
687
|
+
let lineStart = 0;
|
|
688
|
+
let lineWord = '';
|
|
689
|
+
let wordFor = -1;
|
|
690
|
+
let pos = 0;
|
|
691
|
+
let i = 0;
|
|
692
|
+
for (;;) {
|
|
693
|
+
const at = unq.indexOf('<<', i);
|
|
694
|
+
if (at < 0)
|
|
695
|
+
break;
|
|
696
|
+
while (pos < at) {
|
|
697
|
+
if (text[pos] === '\n')
|
|
698
|
+
lineStart = pos + 1;
|
|
699
|
+
pos++;
|
|
700
|
+
}
|
|
701
|
+
if (unq[at + 2] === '<') {
|
|
702
|
+
i = at + 3;
|
|
703
|
+
continue;
|
|
704
|
+
}
|
|
705
|
+
let j = at + 2;
|
|
706
|
+
const dash = text[j] === '-';
|
|
707
|
+
if (dash)
|
|
708
|
+
j++;
|
|
709
|
+
while (text[j] === ' ' || text[j] === '\t')
|
|
710
|
+
j++;
|
|
711
|
+
const q = text[j] === "'" || text[j] === '"' ? text[j] : '';
|
|
712
|
+
if (q)
|
|
713
|
+
j++;
|
|
714
|
+
const from = j;
|
|
715
|
+
while (j < text.length && /[\w-]/.test(text[j]))
|
|
716
|
+
j++;
|
|
717
|
+
const delim = text.slice(from, j);
|
|
718
|
+
if (q && text[j] === q)
|
|
719
|
+
j++;
|
|
720
|
+
i = Math.max(j, at + 2);
|
|
721
|
+
if (!q || delim === '')
|
|
722
|
+
continue;
|
|
723
|
+
if (wordFor !== lineStart) {
|
|
724
|
+
let s = lineStart;
|
|
725
|
+
while (text[s] === ' ' || text[s] === '\t')
|
|
726
|
+
s++;
|
|
727
|
+
let e = s;
|
|
728
|
+
while (e < text.length && !' \t\n;&|<>'.includes(text[e]))
|
|
729
|
+
e++;
|
|
730
|
+
lineWord = (text.slice(s, e).split(/[\\/]/).pop() ?? '').toLowerCase();
|
|
731
|
+
wordFor = lineStart;
|
|
732
|
+
}
|
|
733
|
+
const nl = text.indexOf('\n', j);
|
|
734
|
+
if (nl < 0)
|
|
735
|
+
break;
|
|
736
|
+
let k = nl + 1;
|
|
737
|
+
while (k <= text.length) {
|
|
738
|
+
let e = text.indexOf('\n', k);
|
|
739
|
+
if (e < 0)
|
|
740
|
+
e = text.length;
|
|
741
|
+
let s = k;
|
|
742
|
+
if (dash)
|
|
743
|
+
while (text[s] === '\t')
|
|
744
|
+
s++;
|
|
745
|
+
if (text.slice(s, e) === delim)
|
|
746
|
+
break;
|
|
747
|
+
if (TEXT_ARGS.has(lineWord))
|
|
748
|
+
for (let x = k; x < e; x++)
|
|
749
|
+
out[x] = ' ';
|
|
750
|
+
k = e + 1;
|
|
751
|
+
}
|
|
752
|
+
i = Math.max(i, k);
|
|
753
|
+
pos = Math.max(pos, Math.min(k, text.length));
|
|
754
|
+
lineStart = Math.min(k, text.length);
|
|
755
|
+
}
|
|
756
|
+
return out.join('');
|
|
424
757
|
}
|
|
758
|
+
/**
|
|
759
|
+
* A shell function defined in the text (quoted spans already blanked): `name()` or `name ( )` followed by
|
|
760
|
+
* a body, whatever it is (bash's `{ …; }` or `( … )`, zsh's simple command, after blanks, comments and
|
|
761
|
+
* newlines), or zsh's anonymous `() { … }` at a command's start. `$()`, `=()` (an empty array), `<()`
|
|
762
|
+
* and extglob's `@()` aren't. One pass: the text after each `()` is skipped once.
|
|
763
|
+
*/
|
|
764
|
+
function definesFunction(text) {
|
|
765
|
+
const blank = (c) => c === ' ' || c === '\t';
|
|
766
|
+
for (let i = 0; i < text.length; i++) {
|
|
767
|
+
if (text[i] !== '(')
|
|
768
|
+
continue;
|
|
769
|
+
let j = i + 1;
|
|
770
|
+
while (blank(text[j]))
|
|
771
|
+
j++;
|
|
772
|
+
if (text[j] !== ')')
|
|
773
|
+
continue;
|
|
774
|
+
let k = j + 1;
|
|
775
|
+
for (;;) {
|
|
776
|
+
while (blank(text[k]))
|
|
777
|
+
k++;
|
|
778
|
+
if (text[k] === '#')
|
|
779
|
+
while (k < text.length && text[k] !== '\n')
|
|
780
|
+
k++;
|
|
781
|
+
if (text[k] === '\n' || text[k] === '\r')
|
|
782
|
+
k++;
|
|
783
|
+
else
|
|
784
|
+
break;
|
|
785
|
+
}
|
|
786
|
+
const next = text[k];
|
|
787
|
+
let m = i - 1;
|
|
788
|
+
while (m >= 0 && blank(text[m]))
|
|
789
|
+
m--;
|
|
790
|
+
const before = text[m];
|
|
791
|
+
if (before === undefined || ';&|(){}\n\r'.includes(before)) {
|
|
792
|
+
if (next === '{')
|
|
793
|
+
return true;
|
|
794
|
+
}
|
|
795
|
+
else if (!'$=<>`@!?*+'.includes(before) && next !== undefined && !';|&)'.includes(next))
|
|
796
|
+
return true;
|
|
797
|
+
i = Math.max(i, k - 1);
|
|
798
|
+
}
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Why a command line that names p2p can't be read by its words, or null (the mod and the Codex bridge
|
|
803
|
+
* share this function, and the same vectors pin both). Not emulated, refused:
|
|
804
|
+
* - GNU `parallel` and runners like it, or `xargs`, in a simple command that names p2p or expands
|
|
805
|
+
* anything (before the CLI's name, unless the command is a text command like `grep`): they build the
|
|
806
|
+
* CLI's argv from their own arguments (`parallel p2p ::: invite`). As the command word, also when they
|
|
807
|
+
* read their arguments from stdin or a file on a line that names p2p (`echo 'p2p invite' | parallel`),
|
|
808
|
+
* or xargs runs a shell (`… | xargs -I{} sh -c '{}'`);
|
|
809
|
+
* - an alias defined in a simple command that names p2p or expands anything, `hash -p`, an assignment to
|
|
810
|
+
* zsh's `functions[…]`/`aliases[…]` or bash's BASH_ALIASES, or any shell function: each gives the CLI
|
|
811
|
+
* another name (`alias q='p2p send --to'`, `f(){ p2p "$@"; }`, `() { p2p "$@"; }`);
|
|
812
|
+
* - a command word built at run time (`$p`, `$(…)`, backticks; `$P2P_BIN` is the CLI), `eval` of text built at
|
|
813
|
+
* run time that names p2p, or a script sourced from a process substitution or a path that names p2p.
|
|
814
|
+
* A quoted word that may be a script of its own (`bash -c '…'`, `eval "…"`, `trap '…'`, `ssh host '…'`) and
|
|
815
|
+
* a backtick substitution are read again when they name p2p, up to MAX_NESTING levels (past that,
|
|
816
|
+
* refused); text after the CLI's name or a text command's (`echo`, `git commit -m`) isn't, except a
|
|
817
|
+
* substitution. The body of a quoted heredoc fed to a text command is data. One pass per level, no
|
|
818
|
+
* backtracking: linear. The caller checks that the command names p2p.
|
|
819
|
+
*/
|
|
820
|
+
export function indirectP2PRun(command, depth = 0) {
|
|
821
|
+
const unq = unquoted(command);
|
|
822
|
+
const data = command.includes('<<') ? blankHeredocs(command, unq) : command;
|
|
823
|
+
if (definesFunction(data === command ? unq : unquoted(data)))
|
|
824
|
+
return 'a shell function defined on a command that names p2p';
|
|
825
|
+
for (const inner of backticks(data)) {
|
|
826
|
+
if (!mentionsP2P(inner))
|
|
827
|
+
continue;
|
|
828
|
+
if (depth + 1 >= MAX_NESTING)
|
|
829
|
+
return NESTED;
|
|
830
|
+
const found = indirectP2PRun(inner, depth + 1);
|
|
831
|
+
if (found)
|
|
832
|
+
return found;
|
|
833
|
+
}
|
|
834
|
+
const starts = new Set();
|
|
835
|
+
const words = shellTokens(data, false, undefined, starts);
|
|
836
|
+
// Per simple command (one pass): whether a word in it names p2p, expands something, how many words it
|
|
837
|
+
// has, whether it gives arguments inline (`:::`) or from a file (`::::`, `-a`), and whether it names a shell.
|
|
838
|
+
const named = [];
|
|
839
|
+
const expands = [];
|
|
840
|
+
const count = [];
|
|
841
|
+
const inline = [];
|
|
842
|
+
const files = [];
|
|
843
|
+
const shells = [];
|
|
844
|
+
for (let i = 0, s = -1; i < words.length; i++) {
|
|
845
|
+
if (starts.has(i) || s < 0)
|
|
846
|
+
s++;
|
|
847
|
+
const w = words[i] ?? '';
|
|
848
|
+
if (mentionsP2P(w))
|
|
849
|
+
named[s] = true;
|
|
850
|
+
if (w.includes('$') || w.includes('`'))
|
|
851
|
+
expands[s] = true;
|
|
852
|
+
if (w === ':::')
|
|
853
|
+
inline[s] = true;
|
|
854
|
+
if (w === '::::' || w === '-a' || w === '--arg-file' || w.startsWith('--arg-file='))
|
|
855
|
+
files[s] = true;
|
|
856
|
+
if (XARGS_SHELLS.has((w.split(/[\\/]/).pop() ?? w).toLowerCase()))
|
|
857
|
+
shells[s] = true;
|
|
858
|
+
count[s] = (count[s] ?? 0) + 1;
|
|
859
|
+
}
|
|
860
|
+
let seg = -1;
|
|
861
|
+
let lead = true;
|
|
862
|
+
let cliSeen = false;
|
|
863
|
+
let text = false;
|
|
864
|
+
let value = false;
|
|
865
|
+
let lockFile = false;
|
|
866
|
+
for (let i = 0; i < words.length; i++) {
|
|
867
|
+
const w = words[i] ?? '';
|
|
868
|
+
if (starts.has(i) || seg < 0) {
|
|
869
|
+
seg++;
|
|
870
|
+
lead = true;
|
|
871
|
+
cliSeen = false;
|
|
872
|
+
text = false;
|
|
873
|
+
value = false;
|
|
874
|
+
lockFile = false;
|
|
875
|
+
}
|
|
876
|
+
const base = (w.split(/[\\/]/).pop() ?? w).toLowerCase();
|
|
877
|
+
const dot = base.indexOf('.');
|
|
878
|
+
const name = dot > 0 ? base.slice(0, dot) : base;
|
|
879
|
+
const marked = named[seg] === true || expands[seg] === true;
|
|
880
|
+
const runner = ARG_RUNNERS.has(name) || XARGS.has(name);
|
|
881
|
+
if (lead && value && !runner) {
|
|
882
|
+
// A wrapper's option value (`sudo -u x`, `timeout -s KILL`): the command word is still to come. A
|
|
883
|
+
// runner's name is never taken for one (`sudo -k parallel …`).
|
|
884
|
+
value = false;
|
|
885
|
+
}
|
|
886
|
+
else if (lead) {
|
|
887
|
+
value = false;
|
|
888
|
+
if (NAME_STORES.some(p => w.startsWith(p)))
|
|
889
|
+
return 'a shell alias or function defined on a command that names p2p';
|
|
890
|
+
if (w.startsWith('PROMPT_COMMAND=') && mentionsP2P(w))
|
|
891
|
+
return 'a shell hook (PROMPT_COMMAND) that names p2p';
|
|
892
|
+
if (base === 'function')
|
|
893
|
+
return 'a shell function defined on a command that names p2p';
|
|
894
|
+
if (base === 'alias' && marked)
|
|
895
|
+
return 'a shell alias defined on a command that names p2p';
|
|
896
|
+
if (base === 'hash' && marked)
|
|
897
|
+
return 'a hashed command name on a command that names p2p';
|
|
898
|
+
if (ARG_RUNNERS.has(name) && (marked || (name !== 'sem' && (!inline[seg] || files[seg]))))
|
|
899
|
+
return 'GNU parallel (or a runner like it) on a command that names p2p';
|
|
900
|
+
if (XARGS.has(name) && (marked || shells[seg]))
|
|
901
|
+
return 'xargs on a command that names p2p';
|
|
902
|
+
// eval of text built at run time that names p2p (`eval "$(printf 'f\050…')"`), or a script sourced from a
|
|
903
|
+
// process substitution or a path that names p2p (`source <(echo 'f(){ p2p …; }')`).
|
|
904
|
+
if (base === 'eval' && named[seg] && expands[seg])
|
|
905
|
+
return 'eval of text built at run time, on a command that names p2p';
|
|
906
|
+
if ((base === 'source' || base === '.') && (named[seg] || count[seg] === 1))
|
|
907
|
+
return 'a sourced script on a command that names p2p';
|
|
908
|
+
if ((w.startsWith('$') || w.startsWith('`')) && w !== '$P2P_BIN' && w !== '${P2P_BIN}')
|
|
909
|
+
return 'a command word built at run time on a command that names p2p';
|
|
910
|
+
if (base === 'flock')
|
|
911
|
+
lockFile = true;
|
|
912
|
+
// NAME=value, a keyword or wrapper, a wrapper's option (and its value) or count, or flock's lock file:
|
|
913
|
+
// the command word is still to come.
|
|
914
|
+
if (VALUE_OPTIONS.has(w))
|
|
915
|
+
value = true;
|
|
916
|
+
else if (lockFile && base !== 'flock' && !w.startsWith('-') && !runner)
|
|
917
|
+
lockFile = false;
|
|
918
|
+
else if (!(w.indexOf('=') > 0 || LEAD_WORDS.has(base) || w.startsWith('-') || (w !== '' && [...w].every(ch => ch >= '0' && ch <= '9')))) {
|
|
919
|
+
lead = false;
|
|
920
|
+
text = TEXT_ARGS.has(base);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
else if (!text && !cliSeen && marked && runner) {
|
|
924
|
+
// Behind a wrapper the guard doesn't know (`setsid parallel p2p ::: invite`).
|
|
925
|
+
return ARG_RUNNERS.has(name) ? 'GNU parallel (or a runner like it) on a command that names p2p' : 'xargs on a command that names p2p';
|
|
926
|
+
}
|
|
927
|
+
if (cliWord(w))
|
|
928
|
+
cliSeen = true;
|
|
929
|
+
const subst = w.includes('$(') || w.includes('`');
|
|
930
|
+
if ((w.includes(' ') || w.includes('\t') || w.includes('\n')) && ((!cliSeen && !text) || subst) && mentionsP2P(w)) {
|
|
931
|
+
if (depth + 1 >= MAX_NESTING)
|
|
932
|
+
return NESTED;
|
|
933
|
+
const found = indirectP2PRun(w, depth + 1);
|
|
934
|
+
if (found)
|
|
935
|
+
return found;
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
return null;
|
|
939
|
+
}
|
|
940
|
+
// ---- End of the shared block.
|
|
425
941
|
/**
|
|
426
942
|
* The mutating `p2p` verb a shell command runs, or null (the mod's
|
|
427
943
|
* `mutatingP2PVerb`, for Codex's PreToolUse hook). Defence in depth only:
|
|
428
944
|
* parsed conservatively, it may refuse a harmless command, never the reverse
|
|
429
945
|
* on purpose, but a determined command can spell things another way.
|
|
430
946
|
*/
|
|
431
|
-
|
|
432
|
-
|
|
947
|
+
/** Builtins and commands that run a string argument later or elsewhere: `trap`, `su -c`, `complete -C`, `ssh host`, `watch`. */
|
|
948
|
+
const STRING_RUNNERS = new Set(["trap", "su", "complete", "ssh", "watch"]);
|
|
949
|
+
/** What mutatingP2PVerb reads, in characters over all its passes, before it refuses a command that names p2p unread (64 passes over the longest command checked). */
|
|
950
|
+
export const WORK_BUDGET = 64 * 16 * 1024;
|
|
951
|
+
/** mutatingP2PVerb's answer when a command that names p2p is past WORK_BUDGET: refused as one it can't check. */
|
|
952
|
+
export const TOO_COMPLEX = "a command too complex to check that names p2p";
|
|
953
|
+
export function mutatingP2PVerb(command, binNames = [], depth = 0, unread = false, deep, work = { left: WORK_BUDGET }) {
|
|
954
|
+
// Past the nesting limit nothing more is read: nestedTooDeep refuses it when it still names p2p.
|
|
955
|
+
if (depth > 3) {
|
|
956
|
+
if (deep && mentionsP2P(command))
|
|
957
|
+
deep.hit = true;
|
|
433
958
|
return null;
|
|
959
|
+
}
|
|
960
|
+
// Every pass spends the text it reads from one budget: past it, a command that names p2p is refused unread.
|
|
961
|
+
// The configured binary counts as naming p2p here too.
|
|
962
|
+
const names = (t) => mentionsP2P(t) || binNames.some((b) => b !== "" && t.includes(b));
|
|
963
|
+
work.left -= command.length + 1;
|
|
964
|
+
if (work.left < 0)
|
|
965
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
434
966
|
const segments = command.split(/\|\||&&|[|;&\n`]|\$\(|\)/);
|
|
435
967
|
const isCli = (word) => {
|
|
436
968
|
const w = word.replace(/^["']|["']$/g, "");
|
|
@@ -443,24 +975,62 @@ export function mutatingP2PVerb(command, binNames = [], depth = 0) {
|
|
|
443
975
|
w.startsWith("@peer2peer/cli@") ||
|
|
444
976
|
w === "$P2P_BIN" ||
|
|
445
977
|
w === "${P2P_BIN}" ||
|
|
978
|
+
cliBinJs(w) ||
|
|
446
979
|
binNames.includes(w));
|
|
447
980
|
};
|
|
981
|
+
// A shell's `-c` script and its positional arguments, read over the whole command (the split below doesn't
|
|
982
|
+
// know quotes, so a `;` inside the script would cut it): the first one, once per level.
|
|
983
|
+
const all = shellTokens(command);
|
|
984
|
+
const sh = all.findIndex((w) => /^(sh|bash|zsh|dash|ksh|fish|pwsh|powershell|cmd)(\.exe)?$/.test((w.split(/[\\/]/).pop() ?? "").toLowerCase()));
|
|
985
|
+
const shFlag = sh < 0 ? -1 : all.findIndex((w, j) => j > sh && /^(-c|-lc|-command|\/c|-encodedcommand)$/i.test(w));
|
|
986
|
+
if (shFlag > 0 && all[shFlag + 1] !== undefined) {
|
|
987
|
+
const script = shFlag + 2 < all.length ? `${all[shFlag + 1]}; ${all.slice(shFlag + 2).join(" ")}` : (all[shFlag + 1] ?? "");
|
|
988
|
+
const found = mutatingP2PVerb(script, binNames, depth + 1, false, deep, work);
|
|
989
|
+
if (found)
|
|
990
|
+
return found;
|
|
991
|
+
if (work.left < 0)
|
|
992
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
993
|
+
}
|
|
448
994
|
for (const segment of segments) {
|
|
449
|
-
const
|
|
995
|
+
const raws = [];
|
|
996
|
+
const words = shellTokens(segment, false, undefined, undefined, raws);
|
|
997
|
+
// At most one command line read again per simple command (its words after the runner were read in that
|
|
998
|
+
// pass), and a shell's `-c` looked for once: so each level reads its text once, never once per runner word.
|
|
999
|
+
let noFlag = false;
|
|
450
1000
|
for (let i = 0; i < words.length; i++) {
|
|
451
1001
|
const base = (words[i] ?? "").split(/[\\/]/).pop()?.toLowerCase() ?? "";
|
|
452
|
-
|
|
1002
|
+
let inner;
|
|
1003
|
+
let innerUnread = false;
|
|
1004
|
+
if (!noFlag && /^(sh|bash|zsh|dash|ksh|fish|pwsh|powershell|cmd)(\.exe)?$/.test(base)) {
|
|
453
1005
|
const flag = words.findIndex((w, j) => j > i && /^(-c|-lc|-command|\/c|-encodedcommand)$/i.test(w));
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
1006
|
+
if (flag < 0)
|
|
1007
|
+
noFlag = true;
|
|
1008
|
+
// The script and then its positional arguments, which it can run (`bash -c '"$@"' x eval 'p2p invite'`): one nested line.
|
|
1009
|
+
else if (words[flag + 1] !== undefined)
|
|
1010
|
+
inner = flag + 2 < words.length ? `${words[flag + 1]}; ${words.slice(flag + 2).join(" ")}` : words[flag + 1];
|
|
458
1011
|
}
|
|
459
|
-
if (base === "eval") {
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
1012
|
+
else if (base === "eval" || STRING_RUNNERS.has(base)) {
|
|
1013
|
+
// `eval …`, and a string that a builtin or a command runs later or elsewhere (`trap '…' EXIT`,
|
|
1014
|
+
// `su -c '…'`, `complete -C '…'`, `ssh host '…'`, `watch '…'`): read again as a command line (as the mod does).
|
|
1015
|
+
inner = words.slice(i + 1).join(" ");
|
|
463
1016
|
}
|
|
1017
|
+
else if (base === "env") {
|
|
1018
|
+
// `env -S "<cmd …>"` (split-string): the string is a command line of its own. Its words come from a
|
|
1019
|
+
// string read again, with no source to check, so a send there is never read as naming --from-session.
|
|
1020
|
+
const split = envSplitString(words, i + 1);
|
|
1021
|
+
if (split) {
|
|
1022
|
+
inner = [split.line, ...words.slice(split.next)].join(" ");
|
|
1023
|
+
innerUnread = true;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
if (inner === undefined)
|
|
1027
|
+
continue;
|
|
1028
|
+
const found = mutatingP2PVerb(inner, binNames, depth + 1, innerUnread, deep, work);
|
|
1029
|
+
if (found)
|
|
1030
|
+
return found;
|
|
1031
|
+
if (work.left < 0)
|
|
1032
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
1033
|
+
break;
|
|
464
1034
|
}
|
|
465
1035
|
const at = words.findIndex(isCli);
|
|
466
1036
|
if (at < 0)
|
|
@@ -472,16 +1042,47 @@ export function mutatingP2PVerb(command, binNames = [], depth = 0) {
|
|
|
472
1042
|
if (MUTATING_TWO.has(two))
|
|
473
1043
|
return two;
|
|
474
1044
|
}
|
|
1045
|
+
if (MUTATING_FIRST.has(plain[0] ?? ""))
|
|
1046
|
+
return plain[0];
|
|
475
1047
|
for (const w of after)
|
|
476
1048
|
if (MUTATING_ONE.has(w))
|
|
477
1049
|
return w;
|
|
478
1050
|
// `send` with no --from-session is the person's terminal path: it sends from the `tui` session and
|
|
479
1051
|
// shares that session with the recipient, a roster change only the person makes.
|
|
480
|
-
if (plain[0] === "send" && !
|
|
1052
|
+
if (plain[0] === "send" && (unread || !sendNamesFromSession(words.slice(at + 1), raws.slice(at + 1))))
|
|
481
1053
|
return "send (no --from-session)";
|
|
482
1054
|
}
|
|
483
1055
|
return null;
|
|
484
1056
|
}
|
|
1057
|
+
/**
|
|
1058
|
+
* How many times a text holds something every nested command line needs (a shell's name: `sh` is in
|
|
1059
|
+
* bash, zsh, dash, ksh, fish and pwsh; `cmd`, `eval`, `script`, `env -S`, a string runner), up to `cap`.
|
|
1060
|
+
* Over-counting only costs a pass. Quotes and backslashes are dropped first; then one indexOf pass per word.
|
|
1061
|
+
*/
|
|
1062
|
+
function nestingWords(raw, cap) {
|
|
1063
|
+
// Quotes and backslashes out first (one pass), so `e''val`, `e"v"al` and `ev\al` count as eval.
|
|
1064
|
+
let text = "";
|
|
1065
|
+
for (const ch of raw)
|
|
1066
|
+
if (ch !== "'" && ch !== '"' && ch !== '\\')
|
|
1067
|
+
text += ch;
|
|
1068
|
+
let n = 0;
|
|
1069
|
+
for (const word of ["sh", "cmd", "eval", "script", "trap", "su", "complete", "watch", "env"]) {
|
|
1070
|
+
for (let at = text.indexOf(word); at >= 0 && n < cap; at = text.indexOf(word, at + word.length))
|
|
1071
|
+
n++;
|
|
1072
|
+
if (n >= cap)
|
|
1073
|
+
break;
|
|
1074
|
+
}
|
|
1075
|
+
return n;
|
|
1076
|
+
}
|
|
1077
|
+
/** Whether mutatingP2PVerb stops at its nesting limit (shells and eval inside each other) on a command that still names p2p there. */
|
|
1078
|
+
export function nestedTooDeep(command) {
|
|
1079
|
+
// Four levels need four words that open one: without them, the second pass is skipped.
|
|
1080
|
+
if (nestingWords(command.toLowerCase(), 4) < 4)
|
|
1081
|
+
return false;
|
|
1082
|
+
const deep = { hit: false };
|
|
1083
|
+
mutatingP2PVerb(command, [], 0, false, deep);
|
|
1084
|
+
return deep.hit;
|
|
1085
|
+
}
|
|
485
1086
|
/**
|
|
486
1087
|
* Whether a shell command reaches the backup phrase file or the CLI's key
|
|
487
1088
|
* store (`.p2p` together with `backup`, or the `.p2p` folder listed, globbed
|
|
@@ -588,7 +1189,7 @@ export function turnContextOf(line) {
|
|
|
588
1189
|
/** Whether `path` is `root` or inside it (both already resolved; case-insensitive on macOS/Windows). */
|
|
589
1190
|
export function isInside(path, root, caseless = process.platform === "darwin" || process.platform === "win32") {
|
|
590
1191
|
const norm = (s) => {
|
|
591
|
-
const t = s.replace(/\\/g, "/")
|
|
1192
|
+
const t = trimChars(s.replace(/\\/g, "/"), "/") || "/";
|
|
592
1193
|
return caseless ? t.toLowerCase() : t;
|
|
593
1194
|
};
|
|
594
1195
|
const p = norm(path);
|
|
@@ -638,6 +1239,24 @@ export function screenMessage(o) {
|
|
|
638
1239
|
// The bridge's settings or trusted files sit where a project could plant them: nothing goes out by itself.
|
|
639
1240
|
if (o.refused)
|
|
640
1241
|
return { deliver: false, reason: "auto", why: `held: ${o.refused}` };
|
|
1242
|
+
// One of your own agent sessions (a peer may have told it what to send): held like a peer's where a
|
|
1243
|
+
// peer's would be, so an injected instruction can't drive this session unattended. P2P_AUTO_DELIVER doesn't apply.
|
|
1244
|
+
if (o.ownAgent === true) {
|
|
1245
|
+
if (o.mode === "asking")
|
|
1246
|
+
return { deliver: true };
|
|
1247
|
+
if (o.mode === "auto") {
|
|
1248
|
+
return o.elsewhere
|
|
1249
|
+
? { deliver: false, reason: "auto", why: "another device of yours sent it, which can't say whether your user typed it, and this Codex session runs actions without asking (`p2p own-agents deliver --devices all-other` in your user's own terminal lets those through)" }
|
|
1250
|
+
: { deliver: false, reason: "auto", why: "an agent session of yours sent it, and this Codex session runs actions without asking you (`p2p own-agents deliver` in your own terminal skips this)" };
|
|
1251
|
+
}
|
|
1252
|
+
return {
|
|
1253
|
+
deliver: false,
|
|
1254
|
+
reason: "unknown",
|
|
1255
|
+
why: o.elsewhere
|
|
1256
|
+
? "another device of yours sent it, which can't say whether your user typed it, and this Codex session's approval mode isn't confirmed yet"
|
|
1257
|
+
: "an agent session of yours sent it, and this Codex session's approval mode isn't confirmed yet",
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
641
1260
|
if (o.fromSelf || isAutoDeliver(o.autoDeliver, o.fromUserId) || o.mode === "asking")
|
|
642
1261
|
return { deliver: true };
|
|
643
1262
|
if (o.mode === "auto")
|
|
@@ -704,21 +1323,38 @@ export const LITERAL = '\uE000';
|
|
|
704
1323
|
* parts join into one word (`''x1` and `"x"1` are `x1`), backslashes escape, `$'…'` is
|
|
705
1324
|
* ANSI-C quoted, and `;`, `|`, `&`, `(`, `)`, `<`, `>` and newlines separate words. Expansions
|
|
706
1325
|
* (`$X`, `$(…)`, backticks) stay as text. Linear in the length, with no cap on the number of words
|
|
707
|
-
* (a cap would let padding hide what follows it). Best effort: no aliases, no globbing.
|
|
1326
|
+
* (a cap would let padding hide what follows it). Best effort: no aliases, no globbing. With
|
|
1327
|
+
* `starts`: the index of each word that begins a simple command (the first word, and the first
|
|
1328
|
+
* after an unquoted `;`, `|`, `&`, `(`, `)` or newline).
|
|
708
1329
|
*/
|
|
709
|
-
export function shellTokens(command, markLiteral = false) {
|
|
1330
|
+
export function shellTokens(command, markLiteral = false, substs, starts, raws) {
|
|
710
1331
|
const out = [];
|
|
711
1332
|
let cur = '';
|
|
712
1333
|
let has = false;
|
|
713
1334
|
let q = '';
|
|
714
|
-
|
|
715
|
-
|
|
1335
|
+
let fresh = true;
|
|
1336
|
+
// Where the word being read starts in `command` (raws: each word's source text, quotes and all).
|
|
1337
|
+
let start = -1;
|
|
1338
|
+
// The next word is a redirection's target (`<<< x`, `> f`): its source is marked with `<`, never argv.
|
|
1339
|
+
let redir = false;
|
|
1340
|
+
const push = (end) => {
|
|
1341
|
+
if (has) {
|
|
1342
|
+
// A carriage return next to it is a separator here but part of the word in bash: kept, so it reads as not plain.
|
|
1343
|
+
raws?.push((redir ? '<' : '') + (command[start - 1] === '\r' ? '\r' : '') + command.slice(start, end) + (command[end] === '\r' ? '\r' : ''));
|
|
1344
|
+
redir = false;
|
|
1345
|
+
if (fresh)
|
|
1346
|
+
starts?.add(out.length);
|
|
1347
|
+
fresh = false;
|
|
716
1348
|
out.push(cur);
|
|
1349
|
+
}
|
|
717
1350
|
cur = '';
|
|
718
1351
|
has = false;
|
|
1352
|
+
start = -1;
|
|
719
1353
|
};
|
|
720
1354
|
for (let i = 0; i < command.length; i++) {
|
|
721
1355
|
const c = command[i];
|
|
1356
|
+
if (start < 0 && !' \t\n\r;|&()<>'.includes(c))
|
|
1357
|
+
start = i;
|
|
722
1358
|
if (q === "'") {
|
|
723
1359
|
if (c === "'")
|
|
724
1360
|
q = '';
|
|
@@ -736,6 +1372,17 @@ export function shellTokens(command, markLiteral = false) {
|
|
|
736
1372
|
cur += markLiteral && (c === '$' || c === '`') ? LITERAL : c;
|
|
737
1373
|
continue;
|
|
738
1374
|
}
|
|
1375
|
+
// With `substs`: a `$(…)` or backtick command stays one placeholder in its word (SUBST), its text
|
|
1376
|
+
// collected for shellPaths to read (unquoted and in double quotes, where the shell runs it).
|
|
1377
|
+
if (substs && ((c === '$' && command[i + 1] === '(') || c === '`')) {
|
|
1378
|
+
const open = c === '`' ? 1 : 2;
|
|
1379
|
+
const end = c === '`' ? closingTick(command, i + 1) : closingParen(command, i + 2);
|
|
1380
|
+
substs.push(command.slice(i + open, end));
|
|
1381
|
+
cur += SUBST;
|
|
1382
|
+
has = true;
|
|
1383
|
+
i = end;
|
|
1384
|
+
continue;
|
|
1385
|
+
}
|
|
739
1386
|
if (q === '"') {
|
|
740
1387
|
if (c === '\\' && i + 1 < command.length && '"\\$`'.includes(command[i + 1]))
|
|
741
1388
|
cur += command[++i];
|
|
@@ -766,15 +1413,53 @@ export function shellTokens(command, markLiteral = false) {
|
|
|
766
1413
|
continue;
|
|
767
1414
|
}
|
|
768
1415
|
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || ';|&()<>'.includes(c)) {
|
|
769
|
-
push();
|
|
1416
|
+
push(i);
|
|
1417
|
+
if (c === '<' || c === '>')
|
|
1418
|
+
redir = true;
|
|
1419
|
+
if (c === '\n' || ';|&()'.includes(c))
|
|
1420
|
+
fresh = true;
|
|
770
1421
|
continue;
|
|
771
1422
|
}
|
|
772
1423
|
cur += c;
|
|
773
1424
|
has = true;
|
|
774
1425
|
}
|
|
775
|
-
push();
|
|
1426
|
+
push(command.length);
|
|
776
1427
|
return out;
|
|
777
1428
|
}
|
|
1429
|
+
/** The index of the `)` that closes a `$(` whose text starts at `j` (quotes and escapes skipped), or the end. Linear. */
|
|
1430
|
+
function closingParen(s, j) {
|
|
1431
|
+
let depth = 1;
|
|
1432
|
+
for (let k = j; k < s.length; k++) {
|
|
1433
|
+
const c = s[k];
|
|
1434
|
+
if (c === '\\')
|
|
1435
|
+
k++;
|
|
1436
|
+
else if (c === "'") {
|
|
1437
|
+
const e = s.indexOf("'", k + 1);
|
|
1438
|
+
k = e < 0 ? s.length : e;
|
|
1439
|
+
}
|
|
1440
|
+
else if (c === '"') {
|
|
1441
|
+
let e = k + 1;
|
|
1442
|
+
while (e < s.length && s[e] !== '"')
|
|
1443
|
+
e += s[e] === '\\' ? 2 : 1;
|
|
1444
|
+
k = e;
|
|
1445
|
+
}
|
|
1446
|
+
else if (c === '(')
|
|
1447
|
+
depth++;
|
|
1448
|
+
else if (c === ')' && --depth === 0)
|
|
1449
|
+
return k;
|
|
1450
|
+
}
|
|
1451
|
+
return s.length;
|
|
1452
|
+
}
|
|
1453
|
+
/** The index of the backtick that closes one whose text starts at `j`, or the end. */
|
|
1454
|
+
function closingTick(s, j) {
|
|
1455
|
+
for (let k = j; k < s.length; k++) {
|
|
1456
|
+
if (s[k] === '\\')
|
|
1457
|
+
k++;
|
|
1458
|
+
else if (s[k] === '`')
|
|
1459
|
+
return k;
|
|
1460
|
+
}
|
|
1461
|
+
return s.length;
|
|
1462
|
+
}
|
|
778
1463
|
/** `p` made absolute against `cwd` (POSIX or Windows separators), `.` and `..` resolved. Linear: no regex over the input. */
|
|
779
1464
|
export function resolveLike(cwd, p) {
|
|
780
1465
|
const isSep = (c) => c === '/' || c === '\\';
|
|
@@ -825,46 +1510,558 @@ export function resolveLike(cwd, p) {
|
|
|
825
1510
|
}
|
|
826
1511
|
/** At most this many folders one command may name; past it the session is private (`over`). */
|
|
827
1512
|
export const MAX_COMMAND_PATHS = 256;
|
|
1513
|
+
/** Stands for a `$(…)` or backtick substitution in a word (shellTokens with `substs`): an expansion whose value is unknown. */
|
|
1514
|
+
const SUBST = '\uE001';
|
|
1515
|
+
/** Device files a command names by habit (`2>/dev/null`): never a folder of the session's. */
|
|
1516
|
+
const DEVICES = new Set(['/dev/null', '/dev/zero', '/dev/random', '/dev/urandom', '/dev/tty', '/dev/stdin', '/dev/stdout', '/dev/stderr', '/dev/full']);
|
|
1517
|
+
const isDevice = (p) => DEVICES.has(p) || /^\/dev\/fd\/\d+$/.test(p);
|
|
1518
|
+
/** The files Claude Code runs ahead of each Bash command (CLAUDE_ENV_FILE, its session-env and shell-snapshots folders): they can set any variable. */
|
|
1519
|
+
const ENV_FILES = /CLAUDE_ENV_FILE|session-env|shell-snapshots/i;
|
|
1520
|
+
/** Characters after which a word starts a command, for evalLike. */
|
|
1521
|
+
const EVAL_BOUNDARY = ';&|(){}`\n!\'"';
|
|
1522
|
+
/** Words after which the next word starts a command, for evalLike. */
|
|
1523
|
+
const EVAL_KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'exec', 'command', 'builtin', 'xargs']);
|
|
1524
|
+
const isSpace = (c) => c !== undefined && /\s/.test(c);
|
|
1525
|
+
const isWordChar = (c) => c !== undefined && /\w/.test(c);
|
|
1526
|
+
/**
|
|
1527
|
+
* A command that may set variables in ways no word shows: eval, source or `.` at the start, after
|
|
1528
|
+
* `;`, `&`, `|`, a bracket, a quote, a newline or `!`, or after then/do/else/elif/exec/command/
|
|
1529
|
+
* builtin/xargs, each followed by a space. One pass over the text, so it stays linear.
|
|
1530
|
+
*/
|
|
1531
|
+
function evalLike(s) {
|
|
1532
|
+
let boundary = true;
|
|
1533
|
+
for (let i = 0; i < s.length;) {
|
|
1534
|
+
const c = s[i];
|
|
1535
|
+
if (EVAL_BOUNDARY.includes(c)) {
|
|
1536
|
+
boundary = true;
|
|
1537
|
+
i++;
|
|
1538
|
+
continue;
|
|
1539
|
+
}
|
|
1540
|
+
if (isSpace(c)) {
|
|
1541
|
+
i++;
|
|
1542
|
+
continue;
|
|
1543
|
+
}
|
|
1544
|
+
if (boundary)
|
|
1545
|
+
for (const w of ['eval', 'source', '.'])
|
|
1546
|
+
if (s.startsWith(w, i) && isSpace(s[i + w.length]))
|
|
1547
|
+
return true;
|
|
1548
|
+
if (isWordChar(c)) {
|
|
1549
|
+
let j = i;
|
|
1550
|
+
while (j < s.length && isWordChar(s[j]))
|
|
1551
|
+
j++;
|
|
1552
|
+
boundary = EVAL_KEYWORDS.has(s.slice(i, j));
|
|
1553
|
+
i = j;
|
|
1554
|
+
continue;
|
|
1555
|
+
}
|
|
1556
|
+
boundary = false;
|
|
1557
|
+
i++;
|
|
1558
|
+
}
|
|
1559
|
+
return false;
|
|
1560
|
+
}
|
|
1561
|
+
/** Whether `c` holds a brace expansion with a choice: a `{`, then `,` or `..` with no brace between, then `}`. Linear. */
|
|
1562
|
+
function braceChoice(c) {
|
|
1563
|
+
let open = false;
|
|
1564
|
+
let choice = false;
|
|
1565
|
+
for (let i = 0; i < c.length; i++) {
|
|
1566
|
+
const ch = c[i];
|
|
1567
|
+
if (ch === '{') {
|
|
1568
|
+
open = true;
|
|
1569
|
+
choice = false;
|
|
1570
|
+
}
|
|
1571
|
+
else if (ch === '}') {
|
|
1572
|
+
if (open && choice)
|
|
1573
|
+
return true;
|
|
1574
|
+
open = false;
|
|
1575
|
+
}
|
|
1576
|
+
else if (open && (ch === ',' || (ch === '.' && c[i + 1] === '.')))
|
|
1577
|
+
choice = true;
|
|
1578
|
+
}
|
|
1579
|
+
return false;
|
|
1580
|
+
}
|
|
1581
|
+
/** A path component that names a repository marker or could match one (`.git`, `.p2p-private`, `.g*`, `[.]git`, `{.git,x}`). */
|
|
1582
|
+
const namesMarker = (c) => c === '.git' || c === '.p2p-private' || ((c.startsWith('.') || c.startsWith('[')) && /[*?[]/.test(c)) || braceChoice(c);
|
|
1583
|
+
/** A command word's name: its last path segment, lower-cased, `.exe` and a version (python3.12) dropped. */
|
|
1584
|
+
function commandName(w) {
|
|
1585
|
+
let base = (w.split(/[\\/]/).pop() ?? '').toLowerCase();
|
|
1586
|
+
if (base.endsWith('.exe'))
|
|
1587
|
+
base = base.slice(0, -4);
|
|
1588
|
+
let end = base.length;
|
|
1589
|
+
while (end > 0 && '0123456789.'.includes(base[end - 1]))
|
|
1590
|
+
end--;
|
|
1591
|
+
return { base, bare: base.slice(0, end) };
|
|
1592
|
+
}
|
|
1593
|
+
const CODE_SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'fish']);
|
|
1594
|
+
const SED = new Set(['sed', 'gsed']);
|
|
1595
|
+
const JQ = new Set(['jq', 'gojq']);
|
|
1596
|
+
const AWK = new Set(['awk', 'gawk', 'mawk', 'nawk']);
|
|
1597
|
+
// Shapes a program has and a path almost never does. A word in a program's place that lacks one stays a path.
|
|
1598
|
+
const sedShape = (w) => w !== undefined && /^[\s\d$,!~+;]*[sy]([^\w\s\\])(?:(?!\1)[^\\]|\\.)*\1(?:(?!\1)[^\\]|\\.)*\1/s.test(w);
|
|
1599
|
+
const jqShape = (w) => w !== undefined && (/^\s*(\.(?!\.?[\\/])|[[{("@$])/.test(w) || w.includes('|'));
|
|
1600
|
+
const awkShape = (w) => w !== undefined && (/[{}]/.test(w) || /^\s*(BEGIN|END)\b/.test(w));
|
|
1601
|
+
const codeShape = (w) => w !== undefined && (/[\s;(){}'"=]/.test(w) || sedShape(w));
|
|
1602
|
+
/** Shell words that come before a simple command's command word (`if x`, `then x`, `! x`, `{ x`). */
|
|
1603
|
+
const KEYWORDS = new Set(['if', 'then', 'do', 'else', 'elif', 'while', 'until', '!', '{', '}', 'fi', 'done', 'esac', 'time', 'coproc']);
|
|
1604
|
+
/** Commands that run the next word as the command, and their options that take a value. */
|
|
1605
|
+
const RUNNERS = {
|
|
1606
|
+
sudo: ['-u', '-g', '-p', '-C', '-D', '-h', '-r', '-t', '-T', '-U', '--user', '--group', '--prompt', '--chdir', '--close-from', '--host', '--role', '--type', '--command-timeout', '--other-user'],
|
|
1607
|
+
doas: ['-u', '-C'],
|
|
1608
|
+
env: ['-u', '--unset', '-C', '--chdir'],
|
|
1609
|
+
exec: ['-a'],
|
|
1610
|
+
time: ['-f', '-o', '--format', '--output'],
|
|
1611
|
+
nohup: [],
|
|
1612
|
+
command: [],
|
|
1613
|
+
builtin: [],
|
|
1614
|
+
nice: ['-n', '--adjustment'],
|
|
1615
|
+
timeout: ['-s', '--signal', '-k', '--kill-after'],
|
|
1616
|
+
xargs: ['-I', '-L', '-n', '-P', '-s', '-d', '-E', '-a', '--arg-file', '--delimiter', '--max-args', '--max-procs', '--max-lines', '--replace', '--eof', '--max-chars'],
|
|
1617
|
+
stdbuf: ['-i', '-o', '-e', '--input', '--output', '--error'],
|
|
1618
|
+
unbuffer: [],
|
|
1619
|
+
ionice: ['-c', '-n', '-p', '--class', '--classdata', '--pid'],
|
|
1620
|
+
caffeinate: ['-t', '-w'],
|
|
1621
|
+
noglob: [],
|
|
1622
|
+
nocorrect: [],
|
|
1623
|
+
};
|
|
828
1624
|
/**
|
|
829
|
-
* The
|
|
1625
|
+
* The simple commands of a command line, as `[first, end)` word ranges (shellTokens `starts`).
|
|
1626
|
+
*/
|
|
1627
|
+
function segmentsOf(count, starts) {
|
|
1628
|
+
const at = [...starts].filter(k => k < count).sort((x, y) => x - y);
|
|
1629
|
+
if (count > 0 && at[0] !== 0)
|
|
1630
|
+
at.unshift(0);
|
|
1631
|
+
return at.map((k, n) => [k, at[n + 1] ?? count]);
|
|
1632
|
+
}
|
|
1633
|
+
/**
|
|
1634
|
+
* The command word of the simple command `words[s..e)`: past keywords (`then`, `!`), assignments
|
|
1635
|
+
* (`X=1`) and runners with their options (`sudo -u x`, `env -i`, `timeout 5`, `xargs -0`), or -1
|
|
1636
|
+
* when there is none or it can't be told (`env -S '…'`). `dirs`: the folders a runner moves to
|
|
1637
|
+
* first (`env -C d`, `sudo -D d`).
|
|
1638
|
+
*/
|
|
1639
|
+
function commandAt(words, s, e) {
|
|
1640
|
+
const dirs = [];
|
|
1641
|
+
let i = s;
|
|
1642
|
+
for (let guard = 0; guard < 64 && i < e; guard++) {
|
|
1643
|
+
const w = words[i];
|
|
1644
|
+
if (KEYWORDS.has(w) || /^[A-Za-z_]\w*=/.test(w)) {
|
|
1645
|
+
i++;
|
|
1646
|
+
continue;
|
|
1647
|
+
}
|
|
1648
|
+
const { base } = commandName(w);
|
|
1649
|
+
const opts = Object.prototype.hasOwnProperty.call(RUNNERS, base) ? RUNNERS[base] : undefined;
|
|
1650
|
+
if (opts === undefined)
|
|
1651
|
+
break;
|
|
1652
|
+
i++;
|
|
1653
|
+
while (i < e && words[i].startsWith('-') && words[i] !== '-') {
|
|
1654
|
+
const opt = words[i];
|
|
1655
|
+
i++;
|
|
1656
|
+
if (opt === '--')
|
|
1657
|
+
break;
|
|
1658
|
+
if (base === 'env' && (opt === '-S' || opt === '--split-string' || opt.startsWith('--split-string=') || /^-[A-Za-z]*S/.test(opt)))
|
|
1659
|
+
return { at: -1, dirs };
|
|
1660
|
+
const eq = opt.indexOf('=');
|
|
1661
|
+
const name = eq > 0 ? opt.slice(0, eq) : opt;
|
|
1662
|
+
const chdir = ((base === 'env' || base === 'doas') && name === '-C') || name === '--chdir' || (base === 'sudo' && name === '-D');
|
|
1663
|
+
if (eq > 0) {
|
|
1664
|
+
if (chdir)
|
|
1665
|
+
dirs.push(opt.slice(eq + 1));
|
|
1666
|
+
}
|
|
1667
|
+
else if (opts.includes(opt)) {
|
|
1668
|
+
if (chdir && i < e)
|
|
1669
|
+
dirs.push(words[i]);
|
|
1670
|
+
i++;
|
|
1671
|
+
}
|
|
1672
|
+
else if (base === 'env' && /^-C./.test(opt))
|
|
1673
|
+
dirs.push(opt.slice(2));
|
|
1674
|
+
}
|
|
1675
|
+
if (base === 'timeout' && /^\d/.test(words[i] ?? ''))
|
|
1676
|
+
i++;
|
|
1677
|
+
}
|
|
1678
|
+
return { at: i < e ? i : -1, dirs };
|
|
1679
|
+
}
|
|
1680
|
+
/**
|
|
1681
|
+
* The words that are a program, not a path: the script of sed (`s#a/b#c/d#`), jq (`.a/b`), awk
|
|
1682
|
+
* and perl -e, and the code of `python -c`, `node -e`, `sh -c` and the like. Only for the command
|
|
1683
|
+
* word of a simple command (`segs`: commandAt), in a program's place (after the options, with
|
|
1684
|
+
* -e/-f/--from-file read as they are), within that simple command, and only with a program's
|
|
1685
|
+
* shape: anything else stays a path, since a path missed binds nothing. A word named sed or jq
|
|
1686
|
+
* anywhere else (`cat jq x/../k`) is an argument like any other. Their absolute paths are still
|
|
1687
|
+
* read (shellPaths: embedded).
|
|
1688
|
+
*/
|
|
1689
|
+
function programWords(words, segs) {
|
|
1690
|
+
const out = new Set();
|
|
1691
|
+
const mark = (j, ok) => {
|
|
1692
|
+
if (j < end && ok(words[j]))
|
|
1693
|
+
out.add(j);
|
|
1694
|
+
};
|
|
1695
|
+
let end = 0;
|
|
1696
|
+
for (const [s, e] of segs) {
|
|
1697
|
+
const i = commandAt(words, s, e).at;
|
|
1698
|
+
if (i < 0)
|
|
1699
|
+
continue;
|
|
1700
|
+
end = e;
|
|
1701
|
+
const { base, bare } = commandName(words[i]);
|
|
1702
|
+
if (SED.has(base)) {
|
|
1703
|
+
let script = false;
|
|
1704
|
+
for (let j = i + 1; j < e; j++) {
|
|
1705
|
+
const w = words[j];
|
|
1706
|
+
if (w === '--') {
|
|
1707
|
+
if (!script)
|
|
1708
|
+
mark(j + 1, sedShape);
|
|
1709
|
+
break;
|
|
1710
|
+
}
|
|
1711
|
+
if (w === '-e' || w === '--expression') {
|
|
1712
|
+
mark(j + 1, sedShape);
|
|
1713
|
+
script = true;
|
|
1714
|
+
j++;
|
|
1715
|
+
}
|
|
1716
|
+
else if (w.startsWith('--expression=')) {
|
|
1717
|
+
if (sedShape(w.slice(13)))
|
|
1718
|
+
out.add(j);
|
|
1719
|
+
script = true;
|
|
1720
|
+
}
|
|
1721
|
+
else if (w === '-f' || w === '--file') {
|
|
1722
|
+
script = true;
|
|
1723
|
+
j++;
|
|
1724
|
+
}
|
|
1725
|
+
else if (w.startsWith('--file='))
|
|
1726
|
+
script = true;
|
|
1727
|
+
else if (w === '-l' || w === '--line-length')
|
|
1728
|
+
j++;
|
|
1729
|
+
else if (/^-[A-Za-z]+$/.test(w)) {
|
|
1730
|
+
if (w.endsWith('e')) {
|
|
1731
|
+
mark(j + 1, sedShape);
|
|
1732
|
+
script = true;
|
|
1733
|
+
j++;
|
|
1734
|
+
}
|
|
1735
|
+
else if (w.endsWith('f')) {
|
|
1736
|
+
script = true;
|
|
1737
|
+
j++;
|
|
1738
|
+
}
|
|
1739
|
+
else if (w.endsWith('l'))
|
|
1740
|
+
j++;
|
|
1741
|
+
}
|
|
1742
|
+
else if (w.startsWith('-') && w.length > 1)
|
|
1743
|
+
continue;
|
|
1744
|
+
else {
|
|
1745
|
+
if (!script)
|
|
1746
|
+
mark(j, sedShape);
|
|
1747
|
+
break;
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
else if (JQ.has(base)) {
|
|
1752
|
+
let script = false;
|
|
1753
|
+
for (let j = i + 1; j < e; j++) {
|
|
1754
|
+
const w = words[j];
|
|
1755
|
+
if (w === '--') {
|
|
1756
|
+
if (!script)
|
|
1757
|
+
mark(j + 1, jqShape);
|
|
1758
|
+
break;
|
|
1759
|
+
}
|
|
1760
|
+
if (w === '-f' || w === '--from-file') {
|
|
1761
|
+
script = true;
|
|
1762
|
+
j++;
|
|
1763
|
+
}
|
|
1764
|
+
else if (w === '--arg' || w === '--argjson' || w === '--slurpfile' || w === '--rawfile')
|
|
1765
|
+
j += 2;
|
|
1766
|
+
else if (w === '--indent' || w === '-L' || w === '--library-path')
|
|
1767
|
+
j++;
|
|
1768
|
+
else if (w.startsWith('-') && w.length > 1)
|
|
1769
|
+
continue;
|
|
1770
|
+
else {
|
|
1771
|
+
if (!script)
|
|
1772
|
+
mark(j, jqShape);
|
|
1773
|
+
break;
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
else if (AWK.has(base)) {
|
|
1778
|
+
let script = false;
|
|
1779
|
+
for (let j = i + 1; j < e; j++) {
|
|
1780
|
+
const w = words[j];
|
|
1781
|
+
if (w === '--') {
|
|
1782
|
+
if (!script)
|
|
1783
|
+
mark(j + 1, awkShape);
|
|
1784
|
+
break;
|
|
1785
|
+
}
|
|
1786
|
+
if (w === '-f' || w === '-E' || w === '--file' || w === '--exec') {
|
|
1787
|
+
script = true;
|
|
1788
|
+
j++;
|
|
1789
|
+
}
|
|
1790
|
+
else if (w === '-e' || w === '--source') {
|
|
1791
|
+
mark(j + 1, awkShape);
|
|
1792
|
+
script = true;
|
|
1793
|
+
j++;
|
|
1794
|
+
}
|
|
1795
|
+
else if (w.startsWith('--source=')) {
|
|
1796
|
+
if (awkShape(w.slice(9)))
|
|
1797
|
+
out.add(j);
|
|
1798
|
+
script = true;
|
|
1799
|
+
}
|
|
1800
|
+
else if (/^-[Fvil]$/.test(w) || w === '--field-separator' || w === '--assign' || w === '--include' || w === '--load')
|
|
1801
|
+
j++;
|
|
1802
|
+
else if (w.startsWith('-') && w.length > 1) {
|
|
1803
|
+
if (/^-[A-Za-z]*f$/.test(w)) {
|
|
1804
|
+
script = true;
|
|
1805
|
+
j++;
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
else {
|
|
1809
|
+
if (!script)
|
|
1810
|
+
mark(j, awkShape);
|
|
1811
|
+
break;
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
else if (INTERPRETERS.has(base) || INTERPRETERS.has(bare) || CODE_SHELLS.has(base)) {
|
|
1816
|
+
// The word after a code flag (-c, -e, --eval; a cluster like -ne, -lc): code, when it looks like code.
|
|
1817
|
+
for (let j = i + 1; j < Math.min(e, i + 6); j++) {
|
|
1818
|
+
const w = words[j];
|
|
1819
|
+
if (CODE_FLAGS.has(w) || /^-[A-Za-z]*[ceE]$/.test(w)) {
|
|
1820
|
+
mark(j + 1, codeShape);
|
|
1821
|
+
break;
|
|
1822
|
+
}
|
|
1823
|
+
if (!w.startsWith('-'))
|
|
1824
|
+
break;
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
return out;
|
|
1829
|
+
}
|
|
1830
|
+
/**
|
|
1831
|
+
* The absolute, `~/`, `./` and `../` paths written inside a program or a quoted phrase
|
|
1832
|
+
* (`open("/x/y")`, `sed 'r /x/y'`, `sh -c 'cat ../x/y'`): each begins after a space, a quote, `(`,
|
|
1833
|
+
* `<`, `>`, `=` or `:`, never at the word's start (a sed or awk address there is a pattern). Linear.
|
|
1834
|
+
*/
|
|
1835
|
+
function embedded(t) {
|
|
1836
|
+
const out = [];
|
|
1837
|
+
const starts = ' \t\n\r"\'`(<>=:';
|
|
1838
|
+
const ends = ' \t\n\r"\'`;|&()<>,' + LITERAL + SUBST;
|
|
1839
|
+
for (let k = 1; k < t.length; k++) {
|
|
1840
|
+
const c = t[k];
|
|
1841
|
+
const tilde = c === '~' && t[k + 1] === '/';
|
|
1842
|
+
const dot = c === '.' && (t[k + 1] === '/' || (t[k + 1] === '.' && t[k + 2] === '/'));
|
|
1843
|
+
if ((c !== '/' && !tilde && !dot) || !starts.includes(t[k - 1]))
|
|
1844
|
+
continue;
|
|
1845
|
+
const first = t[tilde ? k + 2 : dot ? k + (t[k + 1] === '/' ? 2 : 3) : k + 1];
|
|
1846
|
+
if (first === undefined || !/[\w.~@%+-]/.test(first))
|
|
1847
|
+
continue;
|
|
1848
|
+
let e = k;
|
|
1849
|
+
while (e < t.length && !ends.includes(t[e]))
|
|
1850
|
+
e++;
|
|
1851
|
+
out.push(t.slice(k, e));
|
|
1852
|
+
k = e;
|
|
1853
|
+
}
|
|
1854
|
+
return out;
|
|
1855
|
+
}
|
|
1856
|
+
/** Whether `raw` uses the variable `name` other than by expanding it (`name=…`, `export name`, `read name`, `for name in`). */
|
|
1857
|
+
function mentions(raw, name) {
|
|
1858
|
+
for (let k = raw.indexOf(name); k >= 0; k = raw.indexOf(name, k + 1)) {
|
|
1859
|
+
const before = raw[k - 1];
|
|
1860
|
+
const after = raw[k + name.length];
|
|
1861
|
+
if ((before !== undefined && /\w/.test(before)) || (after !== undefined && /\w/.test(after)))
|
|
1862
|
+
continue;
|
|
1863
|
+
if (before === '$' || (before === '{' && raw[k - 2] === '$'))
|
|
1864
|
+
continue;
|
|
1865
|
+
return true;
|
|
1866
|
+
}
|
|
1867
|
+
return false;
|
|
1868
|
+
}
|
|
1869
|
+
/** Commands whose `-C <dir>` (or `--directory`) runs them in another folder. */
|
|
1870
|
+
const DIR_FLAG_COMMANDS = new Set(['git', 'make', 'gmake', 'bmake', 'tar', 'gtar', 'bsdtar', 'ninja']);
|
|
1871
|
+
/** A path with a `..` segment. */
|
|
1872
|
+
const DOTDOT = /(^|[\\/])\.\.([\\/]|$)/;
|
|
1873
|
+
/**
|
|
1874
|
+
* The paths a shell command names: absolute, `~` and relative paths (anything with a separator,
|
|
830
1875
|
* or starting with `.` or `~`), an option's value (`--file=/x`) too, each resolved (relative ones
|
|
831
|
-
* against `cwd
|
|
832
|
-
*
|
|
833
|
-
*
|
|
1876
|
+
* against `cwd` and every folder the command moves to) and the absolute paths written inside a
|
|
1877
|
+
* program or quoted phrase. A path is passed as written (`/src/secret.repo` stays itself): the CLI
|
|
1878
|
+
* maps a file to its folder.
|
|
1879
|
+
*
|
|
1880
|
+
* The folders it moves to, read per simple command: `cd`/`pushd`/`chdir` (none: `$HOME`), `git -C`,
|
|
1881
|
+
* `make -C`, `tar -C`, `env -C`, `sudo -D` and the like. Each binds, and relative paths resolve
|
|
1882
|
+
* against each one (and against the ones before it). One it can't place (`cd -`, `cd $X`, `popd`
|
|
1883
|
+
* with no `pushd`) is `unresolved`.
|
|
1884
|
+
*
|
|
1885
|
+
* Variables expand only when the front end knows their value as the shell sees it: `$HOME`,
|
|
1886
|
+
* `$PWD`, and `ctx.vars` (the mod's `$CLAUDE_JOB_DIR`), and only when the command doesn't set
|
|
1887
|
+
* them itself (`HOME=…`, `export`, `read`, `cd` for `$PWD`, eval, source). Any other expansion
|
|
1888
|
+
* (`$X/y`, `$(…)/y`, backticks) in a path's first segment can't be resolved: the session is `over`
|
|
1889
|
+
* (private), `why` `unresolved`; further in, the folder before it binds. A bare `$X` or `$(…)`
|
|
1890
|
+
* names no path. A `$(…)` or backtick command is read for its own paths.
|
|
1891
|
+
*
|
|
1892
|
+
* A program's text (programWords: only for a simple command's command word) isn't a path, unless
|
|
1893
|
+
* it has a `..` segment or a shell expansion; what it would name otherwise is `maybe`.
|
|
1894
|
+
*
|
|
1895
|
+
* Device files (`/dev/null`, `/dev/fd/1`) are skipped. A command that could delete a repository's
|
|
1896
|
+
* `.git` or `.p2p-private` without naming it (find -delete, xargs, dotglob, inline code) also
|
|
1897
|
+
* names `<folder>/.git` for each folder, so a shared folder above never covers it afterwards
|
|
1898
|
+
* (projects.ts projectOf). Past MAX_COMMAND_PATHS: `over`, `why` `folders`. URLs are not paths.
|
|
1899
|
+
* `sticky`: the command touched the files Claude Code runs before each command (pass `untrusted`
|
|
1900
|
+
* from then on).
|
|
834
1901
|
*/
|
|
835
|
-
export function shellPaths(command, cwd, home) {
|
|
1902
|
+
export function shellPaths(command, cwd, home, ctx = {}, depth = 0) {
|
|
836
1903
|
const out = new Set();
|
|
837
|
-
|
|
1904
|
+
const maybe = new Set();
|
|
1905
|
+
const why = new Set();
|
|
838
1906
|
const isSep = (c) => c === '/' || c === '\\';
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
1907
|
+
const isAbs = (t) => t.startsWith('/') || /^[A-Za-z]:[\\/]/.test(t) || t.startsWith('\\\\');
|
|
1908
|
+
const sticky = ENV_FILES.test(command);
|
|
1909
|
+
const done = () => ({ paths: [...out], over: why.size > 0, ...(why.size > 0 ? { why: [...why] } : {}), ...(sticky ? { sticky: true } : {}), ...(maybe.size > 0 ? { maybe: [...maybe] } : {}) });
|
|
1910
|
+
if (depth > 8) {
|
|
1911
|
+
why.add('unresolved');
|
|
1912
|
+
return done();
|
|
1913
|
+
}
|
|
1914
|
+
const substs = [];
|
|
1915
|
+
const starts = new Set();
|
|
1916
|
+
const words = shellTokens(command, true, substs, starts);
|
|
1917
|
+
const segs = segmentsOf(words.length, starts);
|
|
1918
|
+
const changesDir = words.some(w => w === 'cd' || w === 'pushd' || w === 'popd' || w === 'chdir');
|
|
1919
|
+
// The variables known here, as this command's shell sees them.
|
|
1920
|
+
const known = new Map();
|
|
1921
|
+
const trusted = !ctx.untrusted && !sticky && !evalLike(command);
|
|
1922
|
+
for (const [name, val] of [['HOME', home], ['PWD', cwd], ...Object.entries(ctx.vars ?? {})]) {
|
|
1923
|
+
if (!trusted || !val || !/^[A-Za-z_]\w*$/.test(name) || /[\0\n]/.test(val) || !/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(val) || mentions(command, name))
|
|
1924
|
+
continue;
|
|
1925
|
+
// After a cd, $PWD is where the command went: resolved as a relative path below (against each folder it cds to).
|
|
1926
|
+
if (name === 'PWD' && changesDir)
|
|
1927
|
+
continue;
|
|
1928
|
+
known.set(name, val);
|
|
1929
|
+
}
|
|
1930
|
+
// A word with the variables known here expanded.
|
|
1931
|
+
const expand = (word) => {
|
|
1932
|
+
let t = word;
|
|
1933
|
+
// A $PWD the command may have moved: the folder it is in, relative to each base.
|
|
1934
|
+
if (changesDir)
|
|
1935
|
+
for (const v of ['${PWD}', '$PWD'])
|
|
1936
|
+
if (t === v || t.startsWith(`${v}/`) || t.startsWith(`${v}\\`))
|
|
1937
|
+
t = `.${t.slice(v.length)}`;
|
|
1938
|
+
for (const [name, val] of known) {
|
|
1939
|
+
for (const v of [`\${${name}}`, `$${name}`]) {
|
|
1940
|
+
let k = t.indexOf(v);
|
|
1941
|
+
while (k >= 0) {
|
|
1942
|
+
const after = t[k + v.length];
|
|
1943
|
+
// `$HOMEDIR` is another variable: only the whole name.
|
|
1944
|
+
if (!v.startsWith('${') && after !== undefined && /\w/.test(after)) {
|
|
1945
|
+
k = t.indexOf(v, k + 1);
|
|
1946
|
+
continue;
|
|
1947
|
+
}
|
|
1948
|
+
t = `${t.slice(0, k)}${val}${t.slice(k + v.length)}`;
|
|
1949
|
+
k = t.indexOf(v, k + val.length);
|
|
1950
|
+
}
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
return t;
|
|
1954
|
+
};
|
|
1955
|
+
// Folders a relative path may be in: the session's, and each one the command moves to, in order
|
|
1956
|
+
// (a relative move is relative to every folder before it).
|
|
1957
|
+
const bases = [cwd];
|
|
1958
|
+
const moved = [];
|
|
1959
|
+
const moveTo = (word) => {
|
|
1960
|
+
let t = expand(word);
|
|
1961
|
+
if (/[$`]/.test(t) || t.includes(SUBST))
|
|
1962
|
+
return false;
|
|
1963
|
+
t = t.split(LITERAL).join('$');
|
|
1964
|
+
if (t === '')
|
|
1965
|
+
return true;
|
|
1966
|
+
let ps;
|
|
1967
|
+
if (t === '~' || t.startsWith('~/') || t.startsWith('~\\')) {
|
|
1968
|
+
if (!home)
|
|
1969
|
+
return false;
|
|
1970
|
+
ps = [resolveLike(home, t.slice(2) || '.')];
|
|
1971
|
+
}
|
|
1972
|
+
else if (t.startsWith('~'))
|
|
1973
|
+
return false;
|
|
1974
|
+
else if (isAbs(t))
|
|
1975
|
+
ps = [resolveLike(cwd, t)];
|
|
1976
|
+
else
|
|
1977
|
+
ps = bases.map(b => resolveLike(b, t));
|
|
1978
|
+
for (const p of ps) {
|
|
1979
|
+
if (!bases.includes(p))
|
|
1980
|
+
bases.push(p);
|
|
1981
|
+
moved.push(p);
|
|
1982
|
+
}
|
|
1983
|
+
return true;
|
|
1984
|
+
};
|
|
1985
|
+
let pushed = false;
|
|
1986
|
+
for (const [s, e] of segs) {
|
|
1987
|
+
const c = commandAt(words, s, e);
|
|
1988
|
+
const targets = [...c.dirs];
|
|
1989
|
+
let unknown = false;
|
|
1990
|
+
if (c.at >= 0) {
|
|
1991
|
+
const name = commandName(words[c.at]).base;
|
|
1992
|
+
if (name === 'cd' || name === 'pushd' || name === 'chdir') {
|
|
1993
|
+
let j = c.at + 1;
|
|
1994
|
+
while (j < e && /^-[LPe@]+$/.test(words[j]))
|
|
1995
|
+
j++;
|
|
1996
|
+
if (words[j] === '--' && j < e)
|
|
1997
|
+
j++;
|
|
1998
|
+
const target = j < e ? words[j] : undefined;
|
|
1999
|
+
if (name === 'pushd')
|
|
2000
|
+
pushed = true;
|
|
2001
|
+
// A bare pushd swaps the top two folders of a stack this front end doesn't see; cd -, pushd +1 likewise.
|
|
2002
|
+
if (target === undefined) {
|
|
2003
|
+
if (name === 'pushd')
|
|
2004
|
+
unknown = true;
|
|
2005
|
+
else
|
|
2006
|
+
targets.push('~');
|
|
853
2007
|
}
|
|
854
|
-
if (
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
2008
|
+
else if (target === '-' || /^[+-]\d+$/.test(target))
|
|
2009
|
+
unknown = true;
|
|
2010
|
+
else
|
|
2011
|
+
targets.push(target);
|
|
858
2012
|
}
|
|
2013
|
+
else if (name === 'popd') {
|
|
2014
|
+
if (!pushed)
|
|
2015
|
+
unknown = true;
|
|
2016
|
+
}
|
|
2017
|
+
else if (DIR_FLAG_COMMANDS.has(name)) {
|
|
2018
|
+
for (let j = c.at + 1; j < e; j++) {
|
|
2019
|
+
const w = words[j];
|
|
2020
|
+
// git's own -C (and --git-dir, --work-tree) come before its subcommand.
|
|
2021
|
+
if (name === 'git' && !w.startsWith('-'))
|
|
2022
|
+
break;
|
|
2023
|
+
if (w === '-C' || w === '--directory' || (name === 'git' && (w === '--git-dir' || w === '--work-tree'))) {
|
|
2024
|
+
if (j + 1 < e)
|
|
2025
|
+
targets.push(words[++j]);
|
|
2026
|
+
}
|
|
2027
|
+
else if (w.startsWith('--directory=') || (name === 'git' && (w.startsWith('--git-dir=') || w.startsWith('--work-tree='))))
|
|
2028
|
+
targets.push(w.slice(w.indexOf('=') + 1));
|
|
2029
|
+
else if (name !== 'git' && /^-C./.test(w))
|
|
2030
|
+
targets.push(w.slice(2));
|
|
2031
|
+
else if (name === 'git' && (w === '-c' || w === '--namespace' || w === '--exec-path'))
|
|
2032
|
+
j++;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
}
|
|
2036
|
+
if (unknown)
|
|
2037
|
+
why.add('unresolved');
|
|
2038
|
+
for (const t of targets)
|
|
2039
|
+
if (!moveTo(t))
|
|
2040
|
+
why.add('unresolved');
|
|
2041
|
+
if (bases.length > 32) {
|
|
2042
|
+
why.add('folders');
|
|
2043
|
+
break;
|
|
859
2044
|
}
|
|
2045
|
+
}
|
|
2046
|
+
const add = (p) => {
|
|
2047
|
+
if (isDevice(p))
|
|
2048
|
+
return true;
|
|
2049
|
+
out.add(p);
|
|
2050
|
+
return out.size <= MAX_COMMAND_PATHS;
|
|
2051
|
+
};
|
|
2052
|
+
// One path. `inner`: one written inside a program, whose own `$x` and unknowns bind nothing (never
|
|
2053
|
+
// over). `maybe`: a program's own text, kept apart (ShellPaths.maybe) for the front end to check.
|
|
2054
|
+
const take = (word, mode) => {
|
|
2055
|
+
const inner = mode !== 'path';
|
|
2056
|
+
let t = expand(word);
|
|
860
2057
|
const pathLike = t.startsWith('~') || t.startsWith('.') || t.includes('/') || t.includes('\\');
|
|
861
2058
|
if (!pathLike)
|
|
862
|
-
|
|
2059
|
+
return true;
|
|
863
2060
|
// Any other expansion: where it sits decides. In the path's first segment, the location itself
|
|
864
2061
|
// is unknown: private. Further in, the folder before it is known: that one binds.
|
|
865
2062
|
let x = -1;
|
|
866
2063
|
for (let k = 0; k < t.length; k++) {
|
|
867
|
-
if (t[k] === '$' || t[k] === '`') {
|
|
2064
|
+
if (t[k] === '$' || t[k] === '`' || t[k] === SUBST || (inner && t[k] === LITERAL)) {
|
|
868
2065
|
x = k;
|
|
869
2066
|
break;
|
|
870
2067
|
}
|
|
@@ -875,31 +2072,116 @@ export function shellPaths(command, cwd, home) {
|
|
|
875
2072
|
if (isSep(t[k]))
|
|
876
2073
|
lastSep = k;
|
|
877
2074
|
if (lastSep <= 0) {
|
|
878
|
-
|
|
879
|
-
|
|
2075
|
+
if (!inner)
|
|
2076
|
+
why.add('unresolved');
|
|
2077
|
+
return true;
|
|
880
2078
|
}
|
|
881
2079
|
t = t.slice(0, lastSep);
|
|
882
2080
|
}
|
|
883
2081
|
t = t.split(LITERAL).join('$');
|
|
884
|
-
let
|
|
2082
|
+
let ps;
|
|
885
2083
|
if (t === '~' || t.startsWith('~/') || t.startsWith('~\\')) {
|
|
886
2084
|
if (!home) {
|
|
887
|
-
|
|
888
|
-
|
|
2085
|
+
if (!inner)
|
|
2086
|
+
why.add('unresolved');
|
|
2087
|
+
return true;
|
|
889
2088
|
}
|
|
890
|
-
|
|
2089
|
+
ps = [resolveLike(home, t.slice(2) || '.')];
|
|
891
2090
|
}
|
|
2091
|
+
else if (t.startsWith('~')) {
|
|
2092
|
+
// ~user, ~+, ~-: another folder this front end doesn't know.
|
|
2093
|
+
if (!inner)
|
|
2094
|
+
why.add('unresolved');
|
|
2095
|
+
return true;
|
|
2096
|
+
}
|
|
2097
|
+
else if (isAbs(t))
|
|
2098
|
+
ps = [resolveLike(cwd, t)];
|
|
892
2099
|
else
|
|
893
|
-
|
|
894
|
-
//
|
|
895
|
-
const
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
2100
|
+
ps = [...new Set(bases.map(b => resolveLike(b, t)))];
|
|
2101
|
+
// As written: a file, a folder or a pattern (the CLI finds a file's folder, by real path, through symlinks).
|
|
2102
|
+
for (const p of ps) {
|
|
2103
|
+
if (mode === 'maybe') {
|
|
2104
|
+
if (!isDevice(p))
|
|
2105
|
+
maybe.add(p);
|
|
2106
|
+
if (maybe.size > MAX_COMMAND_PATHS)
|
|
2107
|
+
return false;
|
|
2108
|
+
}
|
|
2109
|
+
else if (!add(p))
|
|
2110
|
+
return false;
|
|
2111
|
+
}
|
|
2112
|
+
return true;
|
|
2113
|
+
};
|
|
2114
|
+
const programs = programWords(words, segs);
|
|
2115
|
+
// A command that may remove a .git or .p2p-private without naming it.
|
|
2116
|
+
let mayUnmark = /dotglob|globdots|glob_dots|GLOBIGNORE/i.test(command) || /[*?\]@!+]\(/.test(command);
|
|
2117
|
+
for (let i = 0; i < words.length && !mayUnmark; i++) {
|
|
2118
|
+
const w = words[i];
|
|
2119
|
+
const { base, bare } = commandName(w);
|
|
2120
|
+
if (!/[\\/]/.test(w) && namesMarker(w))
|
|
2121
|
+
mayUnmark = true;
|
|
2122
|
+
else if (base === 'xargs')
|
|
2123
|
+
mayUnmark = true;
|
|
2124
|
+
else if (base === 'find' || base === 'gfind' || base === 'fd' || base === 'fdfind')
|
|
2125
|
+
mayUnmark = words.some(x => /^(-delete|-exec|-execdir|-ok|-okdir|-x|-X|--exec|--exec-batch)$/.test(x));
|
|
2126
|
+
else if (base === 'rsync')
|
|
2127
|
+
mayUnmark = words.some(x => x.startsWith('--del') || x === '--remove-source-files');
|
|
2128
|
+
else if (INTERPRETERS.has(base) || INTERPRETERS.has(bare) || CODE_SHELLS.has(base))
|
|
2129
|
+
mayUnmark = words.slice(i + 1, i + 6).some(x => CODE_FLAGS.has(x) || /^-[A-Za-z]*[ceE]$/.test(x));
|
|
2130
|
+
}
|
|
2131
|
+
for (let i = 0; i < words.length; i++) {
|
|
2132
|
+
const word = words[i];
|
|
2133
|
+
// An option's value (`--file=/x`), and an assignment's (`T=/x/y`: the folder it names binds, though `$T` later can't be read).
|
|
2134
|
+
const eq = word.startsWith('-') ? word.indexOf('=') : (/^[A-Za-z_]\w*=/.exec(word)?.[0].length ?? 0) - 1;
|
|
2135
|
+
const t = eq >= 0 ? word.slice(eq + 1) : word;
|
|
2136
|
+
if (t === '' || (word.startsWith('-') && eq < 0) || t.includes('\0'))
|
|
2137
|
+
continue;
|
|
2138
|
+
const program = programs.has(i);
|
|
2139
|
+
// A program's (or a quoted phrase's) own absolute paths.
|
|
2140
|
+
if (program || /\s/.test(t))
|
|
2141
|
+
for (const e of embedded(t))
|
|
2142
|
+
if (!e.includes('://') && !take(e, 'inner'))
|
|
2143
|
+
return capped();
|
|
2144
|
+
if (t.includes('://') || t.includes('\n'))
|
|
2145
|
+
continue;
|
|
2146
|
+
// A program's own text isn't a path, unless it holds an expansion of the shell's ("$X/y" in
|
|
2147
|
+
// double quotes) or a `..` segment (`jq .git/../../k`): those are read as paths. Otherwise it
|
|
2148
|
+
// is `maybe`: bound when such a path exists.
|
|
2149
|
+
if (program && !t.startsWith('/') && !t.startsWith('~') && !/[$`]/.test(t) && !DOTDOT.test(t)) {
|
|
2150
|
+
if (!take(t, 'maybe'))
|
|
2151
|
+
return capped();
|
|
2152
|
+
continue;
|
|
2153
|
+
}
|
|
2154
|
+
if (!take(t, 'path'))
|
|
2155
|
+
return capped();
|
|
2156
|
+
}
|
|
2157
|
+
for (const p of moved)
|
|
2158
|
+
if (!add(p))
|
|
2159
|
+
return capped();
|
|
2160
|
+
for (const s of substs) {
|
|
2161
|
+
const r = shellPaths(s, cwd, home, ctx, depth + 1);
|
|
2162
|
+
for (const p of r.paths)
|
|
2163
|
+
if (!add(p))
|
|
2164
|
+
return capped();
|
|
2165
|
+
for (const p of r.maybe ?? [])
|
|
2166
|
+
maybe.add(p);
|
|
2167
|
+
for (const w of r.why ?? [])
|
|
2168
|
+
why.add(w);
|
|
2169
|
+
}
|
|
2170
|
+
if (mayUnmark) {
|
|
2171
|
+
for (const p of [...out, ...bases]) {
|
|
2172
|
+
// The folder a pattern is in (`/x/old/*`: /x/old), whose .git it may match.
|
|
2173
|
+
let q = p;
|
|
2174
|
+
for (let k = Math.max(q.lastIndexOf('/'), q.lastIndexOf('\\')); k > 0 && /[*?[\]{}]/.test(q.slice(k + 1)); k = Math.max(q.lastIndexOf('/'), q.lastIndexOf('\\')))
|
|
2175
|
+
q = q.slice(0, k);
|
|
2176
|
+
if (!add(`${q}${q.includes('\\') && !q.includes('/') ? '\\' : '/'}.git`))
|
|
2177
|
+
return capped();
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
return done();
|
|
2181
|
+
function capped() {
|
|
2182
|
+
why.add('folders');
|
|
2183
|
+
return { ...done(), paths: [...out].slice(0, MAX_COMMAND_PATHS), ...(maybe.size > 0 ? { maybe: [...maybe].slice(0, MAX_COMMAND_PATHS) } : {}) };
|
|
901
2184
|
}
|
|
902
|
-
return { paths: [...out], over };
|
|
903
2185
|
}
|
|
904
2186
|
/** Interpreters that run code given as an argument, and terminals that run a command under a pseudo-terminal. */
|
|
905
2187
|
const INTERPRETERS = new Set(['python', 'python2', 'python3', 'node', 'nodejs', 'perl', 'ruby', 'deno', 'bun', 'php', 'lua', 'osascript', 'tclsh', 'pwsh', 'powershell']);
|
|
@@ -932,7 +2214,7 @@ export function hidesCommand(command) {
|
|
|
932
2214
|
export const MAX_GUARDED_COMMAND = 16 * 1024;
|
|
933
2215
|
/** Whether a command line names the p2p CLI (as a word, a path ending in it, the bundle or its variables). */
|
|
934
2216
|
export function namesP2PCli(command) {
|
|
935
|
-
return /(?:^|[\s;&|(/="'`])p2p(?:\.m?js|\.cjs|\.exe|\.cmd)?(?=$|[\s;&|)"'`])|@peer2peer\/cli|\$\{?P2P_(?:BIN|HOME)\b/i.test(command);
|
|
2217
|
+
return /(?:^|[\s;&|(/="'`{])p2p(?:\.m?js|\.cjs|\.exe|\.cmd)?(?=$|[\s;&|)"'`}])|@peer2peer\/cli|\$\{?P2P_(?:BIN|HOME)\b/i.test(command);
|
|
936
2218
|
}
|
|
937
2219
|
/**
|
|
938
2220
|
* Why a shell command naming p2p is refused beyond its verb, or null (projects.ts): it speaks for a
|
|
@@ -952,6 +2234,13 @@ export function boundaryRefusal(command, ownSid) {
|
|
|
952
2234
|
return "interpreter code that runs p2p can't be checked";
|
|
953
2235
|
if (hidden === "pty")
|
|
954
2236
|
return "p2p under a pseudo-terminal can't be checked";
|
|
2237
|
+
// GNU parallel and its kin, xargs, an alias or function defined on the line, or a command word built at
|
|
2238
|
+
// run time (issue #69, as the mod reads them): not emulated.
|
|
2239
|
+
const indirect = indirectP2PRun(command);
|
|
2240
|
+
if (indirect)
|
|
2241
|
+
return `${indirect} can't be checked`;
|
|
2242
|
+
if (nestedTooDeep(command))
|
|
2243
|
+
return `${NESTED} can't be checked`;
|
|
955
2244
|
const words = shellTokens(command);
|
|
956
2245
|
for (let i = 0; i < words.length; i++) {
|
|
957
2246
|
const m = /^--(?:from-)?session(?:=(.*))?$/s.exec(words[i] ?? "");
|
|
@@ -985,3 +2274,22 @@ export function idleNotice(address, reason) {
|
|
|
985
2274
|
export function pickHolder(board) {
|
|
986
2275
|
return [...board].sort((a, b) => b.activeAt - a.activeAt || (a.sid < b.sid ? -1 : a.sid > b.sid ? 1 : 0))[0]?.sid;
|
|
987
2276
|
}
|
|
2277
|
+
/** IxAdvice from `p2p extensions --json`'s `ix`, or undefined when absent or malformed (an older CLI). */
|
|
2278
|
+
export function parseIxAdvice(v) {
|
|
2279
|
+
if (typeof v !== "object" || v === null)
|
|
2280
|
+
return undefined;
|
|
2281
|
+
const o = v;
|
|
2282
|
+
if (typeof o.installed !== "boolean" || typeof o.declined !== "boolean" || typeof o.recommended !== "boolean" || typeof o.install !== "string")
|
|
2283
|
+
return undefined;
|
|
2284
|
+
return { installed: o.installed, declined: o.declined, recommended: o.recommended, install: o.install };
|
|
2285
|
+
}
|
|
2286
|
+
/**
|
|
2287
|
+
* The once-per-session hint to the model when Ix isn't installed and the person hasn't said no: it
|
|
2288
|
+
* may suggest Ix to its user once; installing is theirs. Undefined when there is nothing to say.
|
|
2289
|
+
*/
|
|
2290
|
+
export function ixAgentHint(ix) {
|
|
2291
|
+
if (!ix || !ix.recommended || ix.installed || ix.declined)
|
|
2292
|
+
return undefined;
|
|
2293
|
+
const cmd = inert(ix.install).slice(0, 200);
|
|
2294
|
+
return `Peer2Peer: Ix isn't installed on this machine. It is optional: a local code graph that lets Peer2Peer flag semantic overlap with peers' sessions, show a change's blast radius, and keep local graph memory. You may suggest it to your user once, when it fits what they're doing, and ask whether they want it. Never install it yourself or run its installer: installing is your user's decision and action (they run \`${cmd}\` in their own terminal, then \`p2p setup --ix\`).`;
|
|
2295
|
+
}
|