@peer2peer/codex-bridge 0.1.1 → 0.1.3
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 +3 -3
- package/dist/bridge.d.ts +9 -0
- package/dist/bridge.js +33 -2
- package/dist/hook.js +3 -1
- package/dist/index.js +1 -1
- package/dist/install.js +8 -3
- package/dist/lib.d.ts +91 -6
- package/dist/lib.js +685 -46
- package/dist/p2p.d.ts +3 -1
- package/dist/p2p.js +7 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.js +12 -6
- 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;
|
|
@@ -284,7 +305,7 @@ const MAX_FILE_CHARS = 200;
|
|
|
284
305
|
const isWindowsPath = (p) => /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
|
|
285
306
|
/** The last segment of a path, whichever separator it uses. */
|
|
286
307
|
export function pathBasename(path) {
|
|
287
|
-
const trimmed = path
|
|
308
|
+
const trimmed = trimChars(path, "\\/");
|
|
288
309
|
return trimmed.split(/[\\/]/).pop() || undefined;
|
|
289
310
|
}
|
|
290
311
|
/** A relative path as the relay takes it (core isSafeRelativePath, plus the mod's own rules). */
|
|
@@ -333,12 +354,11 @@ export function stripPaths(line) {
|
|
|
333
354
|
}
|
|
334
355
|
/** A summary as one shareable line (no absolute paths, at most 200 characters), or undefined. */
|
|
335
356
|
export function cleanSummary(text) {
|
|
336
|
-
const
|
|
357
|
+
const folded = String(text)
|
|
337
358
|
.replace(/\s+/g, " ")
|
|
338
359
|
.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "")
|
|
339
|
-
.trim()
|
|
340
|
-
.replace(/^["'`]+|["'`]+$/g, "")
|
|
341
360
|
.trim();
|
|
361
|
+
const line = trimChars(folded, "\"'`", true).trim();
|
|
342
362
|
if (line === "" || /^(none|n\/a|unknown)\.?$/i.test(line))
|
|
343
363
|
return undefined;
|
|
344
364
|
const scrubbed = stripPaths(line);
|
|
@@ -417,10 +437,31 @@ export const MUTATING_TOOLS = new Set([
|
|
|
417
437
|
"p2p_link",
|
|
418
438
|
"p2p_release",
|
|
419
439
|
]);
|
|
420
|
-
|
|
421
|
-
//
|
|
422
|
-
|
|
423
|
-
|
|
440
|
+
// The three lists below are the Claude mod's (hooks/lib.ts), word for word: both are pinned to
|
|
441
|
+
// mods/claude/peer2peer/tests/guard-verbs.vectors.ts, so a verb added to one and not the other fails
|
|
442
|
+
// both suites. Anything either guard refuses, the other refuses.
|
|
443
|
+
/**
|
|
444
|
+
* `p2p` verbs that change who reaches this user, or touch its keys, refused wherever they sit after the
|
|
445
|
+
* CLI's name. `history`: the person's messages (and `history --clear` deletes them); a session's own come
|
|
446
|
+
* through p2p_history. `unblock` lifts a block the person chose. `tui` is the person's full-screen
|
|
447
|
+
* terminal UI (it accepts, declines, trusts and sends on key presses). `release`: this bridge's held
|
|
448
|
+
* messages (`codex release`), refused in any position.
|
|
449
|
+
*/
|
|
450
|
+
export const MUTATING_ONE = new Set(["join", "accept", "invite", "backup", "setup", "init", "remove", "unfriend", "block", "unblock", "petname", "link", "release", "tui", "history"]);
|
|
451
|
+
/**
|
|
452
|
+
* Pairs of words (flags between them skipped). `identity rotate|follow|dispute` move the person's
|
|
453
|
+
* identity; `trust add|remove`, `invites revoke` and `circle hold` decide who reaches them; `extensions
|
|
454
|
+
* enable|disable` decide what code p2p runs with their identity; `ix import|resolve` act on a peer's
|
|
455
|
+
* note or reference in the person's own Ix graph, `ix note|subgraph|impact` send the person's Ix data
|
|
456
|
+
* and `ix config` sets how footprints name files. `project share|private`: who sees a project's sessions.
|
|
457
|
+
*/
|
|
458
|
+
export const MUTATING_TWO = new Set([
|
|
459
|
+
"trust add",
|
|
460
|
+
"trust remove",
|
|
461
|
+
"ix import",
|
|
462
|
+
"ix resolve",
|
|
463
|
+
"extensions enable",
|
|
464
|
+
"extensions disable",
|
|
424
465
|
"held approve",
|
|
425
466
|
"held decline",
|
|
426
467
|
"relays add",
|
|
@@ -433,36 +474,525 @@ const MUTATING_TWO = new Set([
|
|
|
433
474
|
"circle transfer",
|
|
434
475
|
"circle policy",
|
|
435
476
|
"circle default",
|
|
477
|
+
"circle hold",
|
|
436
478
|
"devices revoke",
|
|
437
479
|
"session roster",
|
|
438
480
|
"identity republish",
|
|
481
|
+
"identity rotate",
|
|
482
|
+
"identity follow",
|
|
483
|
+
"identity dispute",
|
|
439
484
|
"profile set",
|
|
440
485
|
"proof add",
|
|
486
|
+
"invites revoke",
|
|
487
|
+
"codex install",
|
|
441
488
|
"codex release",
|
|
442
489
|
"codex decline",
|
|
443
|
-
"
|
|
444
|
-
|
|
490
|
+
"ix note",
|
|
491
|
+
"ix subgraph",
|
|
492
|
+
"ix impact",
|
|
493
|
+
"ix config",
|
|
445
494
|
"project share",
|
|
446
495
|
"project private",
|
|
447
496
|
]);
|
|
448
497
|
/**
|
|
449
|
-
* Verbs refused only as the subcommand itself (common words in message text): `
|
|
450
|
-
* session (its front end's job
|
|
498
|
+
* Verbs refused only as the subcommand itself (common words in message text): `status` posts a
|
|
499
|
+
* session's status (its front end's job: this bridge posts its own), `receipt` reports for a session
|
|
500
|
+
* (its front end's job), `own-agents` decides whether your agent sessions skip the hold (yours).
|
|
451
501
|
*/
|
|
452
|
-
const MUTATING_FIRST = new Set(["receipt", "own-agents"]);
|
|
453
|
-
/**
|
|
454
|
-
|
|
455
|
-
|
|
502
|
+
export const MUTATING_FIRST = new Set(["status", "receipt", "own-agents"]);
|
|
503
|
+
/** `p2p send` options that take the next word as their value, whatever it is (`--` and `--from-session=x` included). */
|
|
504
|
+
const SEND_VALUE_OPTIONS = new Set(["--to", "--project-dir"]);
|
|
505
|
+
/** Characters that can make a shell word other than what it reads as here: expansions, globs, quoting, or a redirection (`<`: shellTokens marks its target). */
|
|
506
|
+
const NOT_PLAIN = "$`{}*?[]~\\'\"<>\r";
|
|
507
|
+
/** A word written as plain text (its source, from shellTokens' `raws`): what it reads as is what the shell passes. */
|
|
508
|
+
function isPlainWord(raw) {
|
|
509
|
+
if (raw === undefined || raw === "" || raw.includes("__SUB__"))
|
|
510
|
+
return false;
|
|
511
|
+
for (const ch of raw)
|
|
512
|
+
if (NOT_PLAIN.includes(ch))
|
|
513
|
+
return false;
|
|
514
|
+
return true;
|
|
515
|
+
}
|
|
516
|
+
/**
|
|
517
|
+
* Whether a `p2p send` command line gives --from-session as the CLI's option (the mod's
|
|
518
|
+
* `sendNamesFromSession`; both are pinned to the same vectors). `args` are the words after the CLI's
|
|
519
|
+
* name and `raws` their source text. Read the way the CLI reads its argv: `--no-input` before the
|
|
520
|
+
* first `--` dropped first (cli.ts main), nothing after a `--` (text from there on, even with the
|
|
521
|
+
* `--` before `send`), and never another option's value (`--to --from-session=x` sends to
|
|
522
|
+
* "--from-session=x" from the `tui` session). The shell makes that argv, and this can't expand it:
|
|
523
|
+
* every word up to and including the deciding one must be written plain (no expansion, glob, brace,
|
|
524
|
+
* tilde, quote, escape, redirection or carriage return), or the answer is no, and the guard refuses. Linear.
|
|
525
|
+
*/
|
|
526
|
+
export function sendNamesFromSession(args, raws) {
|
|
527
|
+
const end = args.indexOf("--");
|
|
528
|
+
const words = [];
|
|
529
|
+
for (let k = 0; k < args.length; k++) {
|
|
530
|
+
const w = args[k] ?? "";
|
|
531
|
+
if (w === "--no-input" && (end < 0 || k < end) && isPlainWord(raws[k]))
|
|
532
|
+
continue;
|
|
533
|
+
words.push({ w, raw: raws[k] });
|
|
534
|
+
}
|
|
535
|
+
for (let i = 0; i < words.length; i++) {
|
|
536
|
+
const { w, raw } = words[i];
|
|
537
|
+
if (!isPlainWord(raw))
|
|
538
|
+
return false;
|
|
539
|
+
if (w === "--")
|
|
540
|
+
return false;
|
|
541
|
+
if (w === "--from-session" || w.startsWith("--from-session="))
|
|
542
|
+
return true;
|
|
543
|
+
if (SEND_VALUE_OPTIONS.has(w)) {
|
|
544
|
+
i++;
|
|
545
|
+
if (!isPlainWord(words[i]?.raw))
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return false;
|
|
550
|
+
}
|
|
551
|
+
/** The CLI's own built entry point run by path (`…/p2p/dist/bin.js`, `…/@peer2peer/cli/dist/bin.js`): the mod's `cliBinJs`. */
|
|
552
|
+
function cliBinJs(word) {
|
|
553
|
+
const w = word.replace(/\\/g, "/").toLowerCase();
|
|
554
|
+
return w.endsWith("/p2p/dist/bin.js") || w.endsWith("@peer2peer/cli/dist/bin.js");
|
|
456
555
|
}
|
|
556
|
+
/**
|
|
557
|
+
* `env`'s split string (`-S <cmd …>`, `-S<cmd …>`, `-vS <cmd …>`, `--split-string[=]<cmd …>`) among its
|
|
558
|
+
* options and assignments, from `from` (the word after `env`) up to its command: the command line it
|
|
559
|
+
* holds and the index of the first word after it, or null. The mod's `envSplitString`; both are pinned
|
|
560
|
+
* to the same vectors. Linear.
|
|
561
|
+
*/
|
|
562
|
+
export function envSplitString(words, from) {
|
|
563
|
+
for (let j = from; j < words.length; j++) {
|
|
564
|
+
const w = words[j] ?? "";
|
|
565
|
+
if (w === "--split-string")
|
|
566
|
+
return words[j + 1] === undefined ? null : { line: words[j + 1] ?? "", next: j + 2 };
|
|
567
|
+
if (w.startsWith("--split-string="))
|
|
568
|
+
return { line: w.slice("--split-string=".length), next: j + 1 };
|
|
569
|
+
if (w === "--unset" || w === "--chdir") {
|
|
570
|
+
j++;
|
|
571
|
+
continue;
|
|
572
|
+
}
|
|
573
|
+
// NAME=VALUE before the command; anything else that isn't an option is the command (or `--` ends the options).
|
|
574
|
+
if (!w.startsWith("-") || w === "-") {
|
|
575
|
+
if (w.indexOf("=") > 0)
|
|
576
|
+
continue;
|
|
577
|
+
return null;
|
|
578
|
+
}
|
|
579
|
+
// `--` ends env's options, but a `-S` read past it fails closed (`env -- -S '…'` is still read as a split string).
|
|
580
|
+
if (w === "--")
|
|
581
|
+
continue;
|
|
582
|
+
if (w.startsWith("--"))
|
|
583
|
+
continue;
|
|
584
|
+
// Short options, bundled: -S takes the rest of the word or the next one; -u and -C take a value.
|
|
585
|
+
for (let k = 1; k < w.length; k++) {
|
|
586
|
+
const o = w[k];
|
|
587
|
+
if (o === "S") {
|
|
588
|
+
if (k + 1 < w.length)
|
|
589
|
+
return { line: w.slice(k + 1), next: j + 1 };
|
|
590
|
+
return words[j + 1] === undefined ? null : { line: words[j + 1] ?? "", next: j + 2 };
|
|
591
|
+
}
|
|
592
|
+
if (o === "u" || o === "C") {
|
|
593
|
+
if (k + 1 === w.length)
|
|
594
|
+
j++;
|
|
595
|
+
break;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
return null;
|
|
600
|
+
}
|
|
601
|
+
// ---- Shared with the Codex bridge, byte for byte (the mod's hooks/lib.ts and the bridge's src/lib.ts): see indirectP2PRun.
|
|
602
|
+
/** Runners that build a command's argv from their own arguments (`parallel p2p ::: invite`): the guards never see it. */
|
|
603
|
+
const ARG_RUNNERS = new Set(['parallel', 'sem', 'parset', 'rush', 'xjobs']);
|
|
604
|
+
/** `xargs` under its names: it runs its arguments with words read from stdin. */
|
|
605
|
+
const XARGS = new Set(['xargs', 'gxargs']);
|
|
606
|
+
/** Words before a simple command's command word: keywords, and builtins and wrappers that run the next word. */
|
|
607
|
+
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']);
|
|
608
|
+
/** Those wrappers' options that take the next word as their value (`sudo -u x`, `timeout -s KILL`, `ionice -c 2`). */
|
|
609
|
+
const VALUE_OPTIONS = new Set(['-u', '-g', '-p', '-s', '-k', '-n', '-C', '-c', '-w', '-E', '--user', '--group', '--signal', '--kill-after', '--chdir', '--interval']);
|
|
610
|
+
/** Commands whose arguments are text: a quoted argument isn't read again as a script (a substitution in it still is). */
|
|
611
|
+
const TEXT_ARGS = new Set(['echo', 'printf', 'grep', 'egrep', 'fgrep', 'rg', 'ag', 'git', 'gh', 'cat', 'head', 'tail', 'wc', 'diff', 'jq', 'tee', 'less', 'more']);
|
|
612
|
+
/** Shells xargs may run with words from stdin as their script (`… | xargs -I{} sh -c '{}'`). */
|
|
613
|
+
const XARGS_SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh', 'mksh', 'fish', 'eval']);
|
|
614
|
+
/** Assignments that define a function or an alias by name (zsh's `functions`/`aliases`/`galiases`, bash's BASH_ALIASES). */
|
|
615
|
+
const NAME_STORES = ['functions[', 'aliases[', 'galiases[', 'saliases[', 'dis_functions[', 'dis_aliases[', 'BASH_ALIASES[', 'BASH_ALIASES=', 'BASH_ALIASES+=', 'BASH_CMDS[', 'BASH_CMDS=', 'BASH_CMDS+='];
|
|
616
|
+
/** How deep quoted scripts are read again; past it, a word that still names p2p is refused. */
|
|
617
|
+
const MAX_NESTING = 4;
|
|
618
|
+
const NESTED = 'a command nested too deeply to check, that names p2p';
|
|
619
|
+
/** The CLI named as a word (the guards' isCli, without configured names): `p2p`, `p2p.mjs`, `@peer2peer/cli`, `$P2P_BIN`. */
|
|
620
|
+
function cliWord(word) {
|
|
621
|
+
const base = (word.split(/[\\/]/).pop() ?? word).toLowerCase();
|
|
622
|
+
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}';
|
|
623
|
+
}
|
|
624
|
+
/** Whether a text names p2p at all (a substring: errs towards yes). */
|
|
625
|
+
function mentionsP2P(text) {
|
|
626
|
+
const lower = text.toLowerCase();
|
|
627
|
+
return lower.includes('p2p') || lower.includes('@peer2peer');
|
|
628
|
+
}
|
|
629
|
+
/** The text with every quoted span (and each escaped character) blanked, positions kept. One pass. */
|
|
630
|
+
function unquoted(text) {
|
|
631
|
+
const out = text.split('');
|
|
632
|
+
let q = '';
|
|
633
|
+
for (let i = 0; i < text.length; i++) {
|
|
634
|
+
const c = text[i];
|
|
635
|
+
if (q === "'") {
|
|
636
|
+
if (c === "'")
|
|
637
|
+
q = '';
|
|
638
|
+
else
|
|
639
|
+
out[i] = ' ';
|
|
640
|
+
continue;
|
|
641
|
+
}
|
|
642
|
+
if (q === '"' || q === '$') {
|
|
643
|
+
if (c === '\\') {
|
|
644
|
+
out[i] = ' ';
|
|
645
|
+
if (i + 1 < text.length)
|
|
646
|
+
out[++i] = ' ';
|
|
647
|
+
}
|
|
648
|
+
else if (c === (q === '$' ? "'" : '"'))
|
|
649
|
+
q = '';
|
|
650
|
+
else
|
|
651
|
+
out[i] = ' ';
|
|
652
|
+
continue;
|
|
653
|
+
}
|
|
654
|
+
if (c === '\\') {
|
|
655
|
+
out[i] = ' ';
|
|
656
|
+
if (i + 1 < text.length)
|
|
657
|
+
out[++i] = ' ';
|
|
658
|
+
}
|
|
659
|
+
else if (c === '$' && text[i + 1] === "'") {
|
|
660
|
+
q = '$';
|
|
661
|
+
i++;
|
|
662
|
+
}
|
|
663
|
+
else if (c === "'" || c === '"')
|
|
664
|
+
q = c;
|
|
665
|
+
}
|
|
666
|
+
return out.join('');
|
|
667
|
+
}
|
|
668
|
+
/** The backtick substitutions in a text, unquoted or inside double quotes (where they run; never inside single quotes). One pass. */
|
|
669
|
+
function backticks(text) {
|
|
670
|
+
const out = [];
|
|
671
|
+
let q = '';
|
|
672
|
+
for (let i = 0; i < text.length; i++) {
|
|
673
|
+
const c = text[i];
|
|
674
|
+
if (q === "'") {
|
|
675
|
+
if (c === "'")
|
|
676
|
+
q = '';
|
|
677
|
+
continue;
|
|
678
|
+
}
|
|
679
|
+
if (c === '\\') {
|
|
680
|
+
i++;
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
if (q === '$') {
|
|
684
|
+
if (c === "'")
|
|
685
|
+
q = '';
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
if (c === '`') {
|
|
689
|
+
let j = i + 1;
|
|
690
|
+
while (j < text.length && text[j] !== '`')
|
|
691
|
+
j += text[j] === '\\' ? 2 : 1;
|
|
692
|
+
out.push(text.slice(i + 1, Math.min(j, text.length)));
|
|
693
|
+
i = j;
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
if (q === '"') {
|
|
697
|
+
if (c === '"')
|
|
698
|
+
q = '';
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
if (c === '$' && text[i + 1] === "'") {
|
|
702
|
+
q = '$';
|
|
703
|
+
i++;
|
|
704
|
+
}
|
|
705
|
+
else if (c === "'" || c === '"')
|
|
706
|
+
q = c;
|
|
707
|
+
}
|
|
708
|
+
return out;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* The text with the bodies of quoted heredocs fed to a text command blanked (`cat > f <<'EOF'`: data,
|
|
712
|
+
* nothing in it runs), positions kept. Any other heredoc is left as written. `unq` is unquoted(text).
|
|
713
|
+
* One pass: each line is read once, and each line's command word once.
|
|
714
|
+
*/
|
|
715
|
+
function blankHeredocs(text, unq) {
|
|
716
|
+
const out = text.split('');
|
|
717
|
+
let lineStart = 0;
|
|
718
|
+
let lineWord = '';
|
|
719
|
+
let wordFor = -1;
|
|
720
|
+
let pos = 0;
|
|
721
|
+
let i = 0;
|
|
722
|
+
for (;;) {
|
|
723
|
+
const at = unq.indexOf('<<', i);
|
|
724
|
+
if (at < 0)
|
|
725
|
+
break;
|
|
726
|
+
while (pos < at) {
|
|
727
|
+
if (text[pos] === '\n')
|
|
728
|
+
lineStart = pos + 1;
|
|
729
|
+
pos++;
|
|
730
|
+
}
|
|
731
|
+
if (unq[at + 2] === '<') {
|
|
732
|
+
i = at + 3;
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
let j = at + 2;
|
|
736
|
+
const dash = text[j] === '-';
|
|
737
|
+
if (dash)
|
|
738
|
+
j++;
|
|
739
|
+
while (text[j] === ' ' || text[j] === '\t')
|
|
740
|
+
j++;
|
|
741
|
+
const q = text[j] === "'" || text[j] === '"' ? text[j] : '';
|
|
742
|
+
if (q)
|
|
743
|
+
j++;
|
|
744
|
+
const from = j;
|
|
745
|
+
while (j < text.length && /[\w-]/.test(text[j]))
|
|
746
|
+
j++;
|
|
747
|
+
const delim = text.slice(from, j);
|
|
748
|
+
if (q && text[j] === q)
|
|
749
|
+
j++;
|
|
750
|
+
i = Math.max(j, at + 2);
|
|
751
|
+
if (!q || delim === '')
|
|
752
|
+
continue;
|
|
753
|
+
if (wordFor !== lineStart) {
|
|
754
|
+
let s = lineStart;
|
|
755
|
+
while (text[s] === ' ' || text[s] === '\t')
|
|
756
|
+
s++;
|
|
757
|
+
let e = s;
|
|
758
|
+
while (e < text.length && !' \t\n;&|<>'.includes(text[e]))
|
|
759
|
+
e++;
|
|
760
|
+
lineWord = (text.slice(s, e).split(/[\\/]/).pop() ?? '').toLowerCase();
|
|
761
|
+
wordFor = lineStart;
|
|
762
|
+
}
|
|
763
|
+
const nl = text.indexOf('\n', j);
|
|
764
|
+
if (nl < 0)
|
|
765
|
+
break;
|
|
766
|
+
let k = nl + 1;
|
|
767
|
+
while (k <= text.length) {
|
|
768
|
+
let e = text.indexOf('\n', k);
|
|
769
|
+
if (e < 0)
|
|
770
|
+
e = text.length;
|
|
771
|
+
let s = k;
|
|
772
|
+
if (dash)
|
|
773
|
+
while (text[s] === '\t')
|
|
774
|
+
s++;
|
|
775
|
+
if (text.slice(s, e) === delim)
|
|
776
|
+
break;
|
|
777
|
+
if (TEXT_ARGS.has(lineWord))
|
|
778
|
+
for (let x = k; x < e; x++)
|
|
779
|
+
out[x] = ' ';
|
|
780
|
+
k = e + 1;
|
|
781
|
+
}
|
|
782
|
+
i = Math.max(i, k);
|
|
783
|
+
pos = Math.max(pos, Math.min(k, text.length));
|
|
784
|
+
lineStart = Math.min(k, text.length);
|
|
785
|
+
}
|
|
786
|
+
return out.join('');
|
|
787
|
+
}
|
|
788
|
+
/**
|
|
789
|
+
* A shell function defined in the text (quoted spans already blanked): `name()` or `name ( )` followed by
|
|
790
|
+
* a body, whatever it is (bash's `{ …; }` or `( … )`, zsh's simple command, after blanks, comments and
|
|
791
|
+
* newlines), or zsh's anonymous `() { … }` at a command's start. `$()`, `=()` (an empty array), `<()`
|
|
792
|
+
* and extglob's `@()` aren't. One pass: the text after each `()` is skipped once.
|
|
793
|
+
*/
|
|
794
|
+
function definesFunction(text) {
|
|
795
|
+
const blank = (c) => c === ' ' || c === '\t';
|
|
796
|
+
for (let i = 0; i < text.length; i++) {
|
|
797
|
+
if (text[i] !== '(')
|
|
798
|
+
continue;
|
|
799
|
+
let j = i + 1;
|
|
800
|
+
while (blank(text[j]))
|
|
801
|
+
j++;
|
|
802
|
+
if (text[j] !== ')')
|
|
803
|
+
continue;
|
|
804
|
+
let k = j + 1;
|
|
805
|
+
for (;;) {
|
|
806
|
+
while (blank(text[k]))
|
|
807
|
+
k++;
|
|
808
|
+
if (text[k] === '#')
|
|
809
|
+
while (k < text.length && text[k] !== '\n')
|
|
810
|
+
k++;
|
|
811
|
+
if (text[k] === '\n' || text[k] === '\r')
|
|
812
|
+
k++;
|
|
813
|
+
else
|
|
814
|
+
break;
|
|
815
|
+
}
|
|
816
|
+
const next = text[k];
|
|
817
|
+
let m = i - 1;
|
|
818
|
+
while (m >= 0 && blank(text[m]))
|
|
819
|
+
m--;
|
|
820
|
+
const before = text[m];
|
|
821
|
+
if (before === undefined || ';&|(){}\n\r'.includes(before)) {
|
|
822
|
+
if (next === '{')
|
|
823
|
+
return true;
|
|
824
|
+
}
|
|
825
|
+
else if (!'$=<>`@!?*+'.includes(before) && next !== undefined && !';|&)'.includes(next))
|
|
826
|
+
return true;
|
|
827
|
+
i = Math.max(i, k - 1);
|
|
828
|
+
}
|
|
829
|
+
return false;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* Why a command line that names p2p can't be read by its words, or null (the mod and the Codex bridge
|
|
833
|
+
* share this function, and the same vectors pin both). Not emulated, refused:
|
|
834
|
+
* - GNU `parallel` and runners like it, or `xargs`, in a simple command that names p2p or expands
|
|
835
|
+
* anything (before the CLI's name, unless the command is a text command like `grep`): they build the
|
|
836
|
+
* CLI's argv from their own arguments (`parallel p2p ::: invite`). As the command word, also when they
|
|
837
|
+
* read their arguments from stdin or a file on a line that names p2p (`echo 'p2p invite' | parallel`),
|
|
838
|
+
* or xargs runs a shell (`… | xargs -I{} sh -c '{}'`);
|
|
839
|
+
* - an alias defined in a simple command that names p2p or expands anything, `hash -p`, an assignment to
|
|
840
|
+
* zsh's `functions[…]`/`aliases[…]` or bash's BASH_ALIASES, or any shell function: each gives the CLI
|
|
841
|
+
* another name (`alias q='p2p send --to'`, `f(){ p2p "$@"; }`, `() { p2p "$@"; }`);
|
|
842
|
+
* - a command word built at run time (`$p`, `$(…)`, backticks; `$P2P_BIN` is the CLI), `eval` of text built at
|
|
843
|
+
* run time that names p2p, or a script sourced from a process substitution or a path that names p2p.
|
|
844
|
+
* A quoted word that may be a script of its own (`bash -c '…'`, `eval "…"`, `trap '…'`, `ssh host '…'`) and
|
|
845
|
+
* a backtick substitution are read again when they name p2p, up to MAX_NESTING levels (past that,
|
|
846
|
+
* refused); text after the CLI's name or a text command's (`echo`, `git commit -m`) isn't, except a
|
|
847
|
+
* substitution. The body of a quoted heredoc fed to a text command is data. One pass per level, no
|
|
848
|
+
* backtracking: linear. The caller checks that the command names p2p.
|
|
849
|
+
*/
|
|
850
|
+
export function indirectP2PRun(command, depth = 0) {
|
|
851
|
+
const unq = unquoted(command);
|
|
852
|
+
const data = command.includes('<<') ? blankHeredocs(command, unq) : command;
|
|
853
|
+
if (definesFunction(data === command ? unq : unquoted(data)))
|
|
854
|
+
return 'a shell function defined on a command that names p2p';
|
|
855
|
+
for (const inner of backticks(data)) {
|
|
856
|
+
if (!mentionsP2P(inner))
|
|
857
|
+
continue;
|
|
858
|
+
if (depth + 1 >= MAX_NESTING)
|
|
859
|
+
return NESTED;
|
|
860
|
+
const found = indirectP2PRun(inner, depth + 1);
|
|
861
|
+
if (found)
|
|
862
|
+
return found;
|
|
863
|
+
}
|
|
864
|
+
const starts = new Set();
|
|
865
|
+
const words = shellTokens(data, false, undefined, starts);
|
|
866
|
+
// Per simple command (one pass): whether a word in it names p2p, expands something, how many words it
|
|
867
|
+
// has, whether it gives arguments inline (`:::`) or from a file (`::::`, `-a`), and whether it names a shell.
|
|
868
|
+
const named = [];
|
|
869
|
+
const expands = [];
|
|
870
|
+
const count = [];
|
|
871
|
+
const inline = [];
|
|
872
|
+
const files = [];
|
|
873
|
+
const shells = [];
|
|
874
|
+
for (let i = 0, s = -1; i < words.length; i++) {
|
|
875
|
+
if (starts.has(i) || s < 0)
|
|
876
|
+
s++;
|
|
877
|
+
const w = words[i] ?? '';
|
|
878
|
+
if (mentionsP2P(w))
|
|
879
|
+
named[s] = true;
|
|
880
|
+
if (w.includes('$') || w.includes('`'))
|
|
881
|
+
expands[s] = true;
|
|
882
|
+
if (w === ':::')
|
|
883
|
+
inline[s] = true;
|
|
884
|
+
if (w === '::::' || w === '-a' || w === '--arg-file' || w.startsWith('--arg-file='))
|
|
885
|
+
files[s] = true;
|
|
886
|
+
if (XARGS_SHELLS.has((w.split(/[\\/]/).pop() ?? w).toLowerCase()))
|
|
887
|
+
shells[s] = true;
|
|
888
|
+
count[s] = (count[s] ?? 0) + 1;
|
|
889
|
+
}
|
|
890
|
+
let seg = -1;
|
|
891
|
+
let lead = true;
|
|
892
|
+
let cliSeen = false;
|
|
893
|
+
let text = false;
|
|
894
|
+
let value = false;
|
|
895
|
+
let lockFile = false;
|
|
896
|
+
for (let i = 0; i < words.length; i++) {
|
|
897
|
+
const w = words[i] ?? '';
|
|
898
|
+
if (starts.has(i) || seg < 0) {
|
|
899
|
+
seg++;
|
|
900
|
+
lead = true;
|
|
901
|
+
cliSeen = false;
|
|
902
|
+
text = false;
|
|
903
|
+
value = false;
|
|
904
|
+
lockFile = false;
|
|
905
|
+
}
|
|
906
|
+
const base = (w.split(/[\\/]/).pop() ?? w).toLowerCase();
|
|
907
|
+
const dot = base.indexOf('.');
|
|
908
|
+
const name = dot > 0 ? base.slice(0, dot) : base;
|
|
909
|
+
const marked = named[seg] === true || expands[seg] === true;
|
|
910
|
+
const runner = ARG_RUNNERS.has(name) || XARGS.has(name);
|
|
911
|
+
if (lead && value && !runner) {
|
|
912
|
+
// A wrapper's option value (`sudo -u x`, `timeout -s KILL`): the command word is still to come. A
|
|
913
|
+
// runner's name is never taken for one (`sudo -k parallel …`).
|
|
914
|
+
value = false;
|
|
915
|
+
}
|
|
916
|
+
else if (lead) {
|
|
917
|
+
value = false;
|
|
918
|
+
if (NAME_STORES.some(p => w.startsWith(p)))
|
|
919
|
+
return 'a shell alias or function defined on a command that names p2p';
|
|
920
|
+
if (w.startsWith('PROMPT_COMMAND=') && mentionsP2P(w))
|
|
921
|
+
return 'a shell hook (PROMPT_COMMAND) that names p2p';
|
|
922
|
+
if (base === 'function')
|
|
923
|
+
return 'a shell function defined on a command that names p2p';
|
|
924
|
+
if (base === 'alias' && marked)
|
|
925
|
+
return 'a shell alias defined on a command that names p2p';
|
|
926
|
+
if (base === 'hash' && marked)
|
|
927
|
+
return 'a hashed command name on a command that names p2p';
|
|
928
|
+
if (ARG_RUNNERS.has(name) && (marked || (name !== 'sem' && (!inline[seg] || files[seg]))))
|
|
929
|
+
return 'GNU parallel (or a runner like it) on a command that names p2p';
|
|
930
|
+
if (XARGS.has(name) && (marked || shells[seg]))
|
|
931
|
+
return 'xargs on a command that names p2p';
|
|
932
|
+
// eval of text built at run time that names p2p (`eval "$(printf 'f\050…')"`), or a script sourced from a
|
|
933
|
+
// process substitution or a path that names p2p (`source <(echo 'f(){ p2p …; }')`).
|
|
934
|
+
if (base === 'eval' && named[seg] && expands[seg])
|
|
935
|
+
return 'eval of text built at run time, on a command that names p2p';
|
|
936
|
+
if ((base === 'source' || base === '.') && (named[seg] || count[seg] === 1))
|
|
937
|
+
return 'a sourced script on a command that names p2p';
|
|
938
|
+
if ((w.startsWith('$') || w.startsWith('`')) && w !== '$P2P_BIN' && w !== '${P2P_BIN}')
|
|
939
|
+
return 'a command word built at run time on a command that names p2p';
|
|
940
|
+
if (base === 'flock')
|
|
941
|
+
lockFile = true;
|
|
942
|
+
// NAME=value, a keyword or wrapper, a wrapper's option (and its value) or count, or flock's lock file:
|
|
943
|
+
// the command word is still to come.
|
|
944
|
+
if (VALUE_OPTIONS.has(w))
|
|
945
|
+
value = true;
|
|
946
|
+
else if (lockFile && base !== 'flock' && !w.startsWith('-') && !runner)
|
|
947
|
+
lockFile = false;
|
|
948
|
+
else if (!(w.indexOf('=') > 0 || LEAD_WORDS.has(base) || w.startsWith('-') || (w !== '' && [...w].every(ch => ch >= '0' && ch <= '9')))) {
|
|
949
|
+
lead = false;
|
|
950
|
+
text = TEXT_ARGS.has(base);
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
else if (!text && !cliSeen && marked && runner) {
|
|
954
|
+
// Behind a wrapper the guard doesn't know (`setsid parallel p2p ::: invite`).
|
|
955
|
+
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';
|
|
956
|
+
}
|
|
957
|
+
if (cliWord(w))
|
|
958
|
+
cliSeen = true;
|
|
959
|
+
const subst = w.includes('$(') || w.includes('`');
|
|
960
|
+
if ((w.includes(' ') || w.includes('\t') || w.includes('\n')) && ((!cliSeen && !text) || subst) && mentionsP2P(w)) {
|
|
961
|
+
if (depth + 1 >= MAX_NESTING)
|
|
962
|
+
return NESTED;
|
|
963
|
+
const found = indirectP2PRun(w, depth + 1);
|
|
964
|
+
if (found)
|
|
965
|
+
return found;
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return null;
|
|
969
|
+
}
|
|
970
|
+
// ---- End of the shared block.
|
|
457
971
|
/**
|
|
458
972
|
* The mutating `p2p` verb a shell command runs, or null (the mod's
|
|
459
973
|
* `mutatingP2PVerb`, for Codex's PreToolUse hook). Defence in depth only:
|
|
460
974
|
* parsed conservatively, it may refuse a harmless command, never the reverse
|
|
461
975
|
* on purpose, but a determined command can spell things another way.
|
|
462
976
|
*/
|
|
463
|
-
|
|
464
|
-
|
|
977
|
+
/** Builtins and commands that run a string argument later or elsewhere: `trap`, `su -c`, `complete -C`, `ssh host`, `watch`. */
|
|
978
|
+
const STRING_RUNNERS = new Set(["trap", "su", "complete", "ssh", "watch"]);
|
|
979
|
+
/** 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). */
|
|
980
|
+
export const WORK_BUDGET = 64 * 16 * 1024;
|
|
981
|
+
/** mutatingP2PVerb's answer when a command that names p2p is past WORK_BUDGET: refused as one it can't check. */
|
|
982
|
+
export const TOO_COMPLEX = "a command too complex to check that names p2p";
|
|
983
|
+
export function mutatingP2PVerb(command, binNames = [], depth = 0, unread = false, deep, work = { left: WORK_BUDGET }) {
|
|
984
|
+
// Past the nesting limit nothing more is read: nestedTooDeep refuses it when it still names p2p.
|
|
985
|
+
if (depth > 3) {
|
|
986
|
+
if (deep && mentionsP2P(command))
|
|
987
|
+
deep.hit = true;
|
|
465
988
|
return null;
|
|
989
|
+
}
|
|
990
|
+
// Every pass spends the text it reads from one budget: past it, a command that names p2p is refused unread.
|
|
991
|
+
// The configured binary counts as naming p2p here too.
|
|
992
|
+
const names = (t) => mentionsP2P(t) || binNames.some((b) => b !== "" && t.includes(b));
|
|
993
|
+
work.left -= command.length + 1;
|
|
994
|
+
if (work.left < 0)
|
|
995
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
466
996
|
const segments = command.split(/\|\||&&|[|;&\n`]|\$\(|\)/);
|
|
467
997
|
const isCli = (word) => {
|
|
468
998
|
const w = word.replace(/^["']|["']$/g, "");
|
|
@@ -475,24 +1005,62 @@ export function mutatingP2PVerb(command, binNames = [], depth = 0) {
|
|
|
475
1005
|
w.startsWith("@peer2peer/cli@") ||
|
|
476
1006
|
w === "$P2P_BIN" ||
|
|
477
1007
|
w === "${P2P_BIN}" ||
|
|
1008
|
+
cliBinJs(w) ||
|
|
478
1009
|
binNames.includes(w));
|
|
479
1010
|
};
|
|
1011
|
+
// A shell's `-c` script and its positional arguments, read over the whole command (the split below doesn't
|
|
1012
|
+
// know quotes, so a `;` inside the script would cut it): the first one, once per level.
|
|
1013
|
+
const all = shellTokens(command);
|
|
1014
|
+
const sh = all.findIndex((w) => /^(sh|bash|zsh|dash|ksh|fish|pwsh|powershell|cmd)(\.exe)?$/.test((w.split(/[\\/]/).pop() ?? "").toLowerCase()));
|
|
1015
|
+
const shFlag = sh < 0 ? -1 : all.findIndex((w, j) => j > sh && /^(-c|-lc|-command|\/c|-encodedcommand)$/i.test(w));
|
|
1016
|
+
if (shFlag > 0 && all[shFlag + 1] !== undefined) {
|
|
1017
|
+
const script = shFlag + 2 < all.length ? `${all[shFlag + 1]}; ${all.slice(shFlag + 2).join(" ")}` : (all[shFlag + 1] ?? "");
|
|
1018
|
+
const found = mutatingP2PVerb(script, binNames, depth + 1, false, deep, work);
|
|
1019
|
+
if (found)
|
|
1020
|
+
return found;
|
|
1021
|
+
if (work.left < 0)
|
|
1022
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
1023
|
+
}
|
|
480
1024
|
for (const segment of segments) {
|
|
481
|
-
const
|
|
1025
|
+
const raws = [];
|
|
1026
|
+
const words = shellTokens(segment, false, undefined, undefined, raws);
|
|
1027
|
+
// At most one command line read again per simple command (its words after the runner were read in that
|
|
1028
|
+
// pass), and a shell's `-c` looked for once: so each level reads its text once, never once per runner word.
|
|
1029
|
+
let noFlag = false;
|
|
482
1030
|
for (let i = 0; i < words.length; i++) {
|
|
483
1031
|
const base = (words[i] ?? "").split(/[\\/]/).pop()?.toLowerCase() ?? "";
|
|
484
|
-
|
|
1032
|
+
let inner;
|
|
1033
|
+
let innerUnread = false;
|
|
1034
|
+
if (!noFlag && /^(sh|bash|zsh|dash|ksh|fish|pwsh|powershell|cmd)(\.exe)?$/.test(base)) {
|
|
485
1035
|
const flag = words.findIndex((w, j) => j > i && /^(-c|-lc|-command|\/c|-encodedcommand)$/i.test(w));
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
1036
|
+
if (flag < 0)
|
|
1037
|
+
noFlag = true;
|
|
1038
|
+
// The script and then its positional arguments, which it can run (`bash -c '"$@"' x eval 'p2p invite'`): one nested line.
|
|
1039
|
+
else if (words[flag + 1] !== undefined)
|
|
1040
|
+
inner = flag + 2 < words.length ? `${words[flag + 1]}; ${words.slice(flag + 2).join(" ")}` : words[flag + 1];
|
|
1041
|
+
}
|
|
1042
|
+
else if (base === "eval" || STRING_RUNNERS.has(base)) {
|
|
1043
|
+
// `eval …`, and a string that a builtin or a command runs later or elsewhere (`trap '…' EXIT`,
|
|
1044
|
+
// `su -c '…'`, `complete -C '…'`, `ssh host '…'`, `watch '…'`): read again as a command line (as the mod does).
|
|
1045
|
+
inner = words.slice(i + 1).join(" ");
|
|
490
1046
|
}
|
|
491
|
-
if (base === "
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
1047
|
+
else if (base === "env") {
|
|
1048
|
+
// `env -S "<cmd …>"` (split-string): the string is a command line of its own. Its words come from a
|
|
1049
|
+
// string read again, with no source to check, so a send there is never read as naming --from-session.
|
|
1050
|
+
const split = envSplitString(words, i + 1);
|
|
1051
|
+
if (split) {
|
|
1052
|
+
inner = [split.line, ...words.slice(split.next)].join(" ");
|
|
1053
|
+
innerUnread = true;
|
|
1054
|
+
}
|
|
495
1055
|
}
|
|
1056
|
+
if (inner === undefined)
|
|
1057
|
+
continue;
|
|
1058
|
+
const found = mutatingP2PVerb(inner, binNames, depth + 1, innerUnread, deep, work);
|
|
1059
|
+
if (found)
|
|
1060
|
+
return found;
|
|
1061
|
+
if (work.left < 0)
|
|
1062
|
+
return depth === 0 && names(command) ? TOO_COMPLEX : null;
|
|
1063
|
+
break;
|
|
496
1064
|
}
|
|
497
1065
|
const at = words.findIndex(isCli);
|
|
498
1066
|
if (at < 0)
|
|
@@ -503,6 +1071,10 @@ export function mutatingP2PVerb(command, binNames = [], depth = 0) {
|
|
|
503
1071
|
const two = `${plain[i]} ${plain[i + 1] ?? ""}`;
|
|
504
1072
|
if (MUTATING_TWO.has(two))
|
|
505
1073
|
return two;
|
|
1074
|
+
// `ix footprint` alone only computes and prints; publishing (and choosing plain names or skipping the
|
|
1075
|
+
// spacing for a publish) shares with the session's audience: the person's decision (as the mod reads it).
|
|
1076
|
+
if (two === "ix footprint" && after.some((w) => /^--(publish|names|force)(=|$)/.test(w)))
|
|
1077
|
+
return "ix footprint --publish";
|
|
506
1078
|
}
|
|
507
1079
|
if (MUTATING_FIRST.has(plain[0] ?? ""))
|
|
508
1080
|
return plain[0];
|
|
@@ -511,11 +1083,40 @@ export function mutatingP2PVerb(command, binNames = [], depth = 0) {
|
|
|
511
1083
|
return w;
|
|
512
1084
|
// `send` with no --from-session is the person's terminal path: it sends from the `tui` session and
|
|
513
1085
|
// shares that session with the recipient, a roster change only the person makes.
|
|
514
|
-
if (plain[0] === "send" && !
|
|
1086
|
+
if (plain[0] === "send" && (unread || !sendNamesFromSession(words.slice(at + 1), raws.slice(at + 1))))
|
|
515
1087
|
return "send (no --from-session)";
|
|
516
1088
|
}
|
|
517
1089
|
return null;
|
|
518
1090
|
}
|
|
1091
|
+
/**
|
|
1092
|
+
* How many times a text holds something every nested command line needs (a shell's name: `sh` is in
|
|
1093
|
+
* bash, zsh, dash, ksh, fish and pwsh; `cmd`, `eval`, `script`, `env -S`, a string runner), up to `cap`.
|
|
1094
|
+
* Over-counting only costs a pass. Quotes and backslashes are dropped first; then one indexOf pass per word.
|
|
1095
|
+
*/
|
|
1096
|
+
function nestingWords(raw, cap) {
|
|
1097
|
+
// Quotes and backslashes out first (one pass), so `e''val`, `e"v"al` and `ev\al` count as eval.
|
|
1098
|
+
let text = "";
|
|
1099
|
+
for (const ch of raw)
|
|
1100
|
+
if (ch !== "'" && ch !== '"' && ch !== '\\')
|
|
1101
|
+
text += ch;
|
|
1102
|
+
let n = 0;
|
|
1103
|
+
for (const word of ["sh", "cmd", "eval", "script", "trap", "su", "complete", "watch", "env"]) {
|
|
1104
|
+
for (let at = text.indexOf(word); at >= 0 && n < cap; at = text.indexOf(word, at + word.length))
|
|
1105
|
+
n++;
|
|
1106
|
+
if (n >= cap)
|
|
1107
|
+
break;
|
|
1108
|
+
}
|
|
1109
|
+
return n;
|
|
1110
|
+
}
|
|
1111
|
+
/** Whether mutatingP2PVerb stops at its nesting limit (shells and eval inside each other) on a command that still names p2p there. */
|
|
1112
|
+
export function nestedTooDeep(command) {
|
|
1113
|
+
// Four levels need four words that open one: without them, the second pass is skipped.
|
|
1114
|
+
if (nestingWords(command.toLowerCase(), 4) < 4)
|
|
1115
|
+
return false;
|
|
1116
|
+
const deep = { hit: false };
|
|
1117
|
+
mutatingP2PVerb(command, [], 0, false, deep);
|
|
1118
|
+
return deep.hit;
|
|
1119
|
+
}
|
|
519
1120
|
/**
|
|
520
1121
|
* Whether a shell command reaches the backup phrase file or the CLI's key
|
|
521
1122
|
* store (`.p2p` together with `backup`, or the `.p2p` folder listed, globbed
|
|
@@ -622,7 +1223,7 @@ export function turnContextOf(line) {
|
|
|
622
1223
|
/** Whether `path` is `root` or inside it (both already resolved; case-insensitive on macOS/Windows). */
|
|
623
1224
|
export function isInside(path, root, caseless = process.platform === "darwin" || process.platform === "win32") {
|
|
624
1225
|
const norm = (s) => {
|
|
625
|
-
const t = s.replace(/\\/g, "/")
|
|
1226
|
+
const t = trimChars(s.replace(/\\/g, "/"), "/") || "/";
|
|
626
1227
|
return caseless ? t.toLowerCase() : t;
|
|
627
1228
|
};
|
|
628
1229
|
const p = norm(path);
|
|
@@ -760,14 +1361,21 @@ export const LITERAL = '\uE000';
|
|
|
760
1361
|
* `starts`: the index of each word that begins a simple command (the first word, and the first
|
|
761
1362
|
* after an unquoted `;`, `|`, `&`, `(`, `)` or newline).
|
|
762
1363
|
*/
|
|
763
|
-
export function shellTokens(command, markLiteral = false, substs, starts) {
|
|
1364
|
+
export function shellTokens(command, markLiteral = false, substs, starts, raws) {
|
|
764
1365
|
const out = [];
|
|
765
1366
|
let cur = '';
|
|
766
1367
|
let has = false;
|
|
767
1368
|
let q = '';
|
|
768
1369
|
let fresh = true;
|
|
769
|
-
|
|
1370
|
+
// Where the word being read starts in `command` (raws: each word's source text, quotes and all).
|
|
1371
|
+
let start = -1;
|
|
1372
|
+
// The next word is a redirection's target (`<<< x`, `> f`): its source is marked with `<`, never argv.
|
|
1373
|
+
let redir = false;
|
|
1374
|
+
const push = (end) => {
|
|
770
1375
|
if (has) {
|
|
1376
|
+
// A carriage return next to it is a separator here but part of the word in bash: kept, so it reads as not plain.
|
|
1377
|
+
raws?.push((redir ? '<' : '') + (command[start - 1] === '\r' ? '\r' : '') + command.slice(start, end) + (command[end] === '\r' ? '\r' : ''));
|
|
1378
|
+
redir = false;
|
|
771
1379
|
if (fresh)
|
|
772
1380
|
starts?.add(out.length);
|
|
773
1381
|
fresh = false;
|
|
@@ -775,9 +1383,12 @@ export function shellTokens(command, markLiteral = false, substs, starts) {
|
|
|
775
1383
|
}
|
|
776
1384
|
cur = '';
|
|
777
1385
|
has = false;
|
|
1386
|
+
start = -1;
|
|
778
1387
|
};
|
|
779
1388
|
for (let i = 0; i < command.length; i++) {
|
|
780
1389
|
const c = command[i];
|
|
1390
|
+
if (start < 0 && !' \t\n\r;|&()<>'.includes(c))
|
|
1391
|
+
start = i;
|
|
781
1392
|
if (q === "'") {
|
|
782
1393
|
if (c === "'")
|
|
783
1394
|
q = '';
|
|
@@ -836,7 +1447,9 @@ export function shellTokens(command, markLiteral = false, substs, starts) {
|
|
|
836
1447
|
continue;
|
|
837
1448
|
}
|
|
838
1449
|
if (c === ' ' || c === '\t' || c === '\n' || c === '\r' || ';|&()<>'.includes(c)) {
|
|
839
|
-
push();
|
|
1450
|
+
push(i);
|
|
1451
|
+
if (c === '<' || c === '>')
|
|
1452
|
+
redir = true;
|
|
840
1453
|
if (c === '\n' || ';|&()'.includes(c))
|
|
841
1454
|
fresh = true;
|
|
842
1455
|
continue;
|
|
@@ -844,7 +1457,7 @@ export function shellTokens(command, markLiteral = false, substs, starts) {
|
|
|
844
1457
|
cur += c;
|
|
845
1458
|
has = true;
|
|
846
1459
|
}
|
|
847
|
-
push();
|
|
1460
|
+
push(command.length);
|
|
848
1461
|
return out;
|
|
849
1462
|
}
|
|
850
1463
|
/** The index of the `)` that closes a `$(` whose text starts at `j` (quotes and escapes skipped), or the end. Linear. */
|
|
@@ -1635,7 +2248,7 @@ export function hidesCommand(command) {
|
|
|
1635
2248
|
export const MAX_GUARDED_COMMAND = 16 * 1024;
|
|
1636
2249
|
/** Whether a command line names the p2p CLI (as a word, a path ending in it, the bundle or its variables). */
|
|
1637
2250
|
export function namesP2PCli(command) {
|
|
1638
|
-
return /(?:^|[\s;&|(/="'`])p2p(?:\.m?js|\.cjs|\.exe|\.cmd)?(?=$|[\s;&|)"'`])|@peer2peer\/cli|\$\{?P2P_(?:BIN|HOME)\b/i.test(command);
|
|
2251
|
+
return /(?:^|[\s;&|(/="'`{])p2p(?:\.m?js|\.cjs|\.exe|\.cmd)?(?=$|[\s;&|)"'`}])|@peer2peer\/cli|\$\{?P2P_(?:BIN|HOME)\b/i.test(command);
|
|
1639
2252
|
}
|
|
1640
2253
|
/**
|
|
1641
2254
|
* Why a shell command naming p2p is refused beyond its verb, or null (projects.ts): it speaks for a
|
|
@@ -1655,6 +2268,13 @@ export function boundaryRefusal(command, ownSid) {
|
|
|
1655
2268
|
return "interpreter code that runs p2p can't be checked";
|
|
1656
2269
|
if (hidden === "pty")
|
|
1657
2270
|
return "p2p under a pseudo-terminal can't be checked";
|
|
2271
|
+
// GNU parallel and its kin, xargs, an alias or function defined on the line, or a command word built at
|
|
2272
|
+
// run time (issue #69, as the mod reads them): not emulated.
|
|
2273
|
+
const indirect = indirectP2PRun(command);
|
|
2274
|
+
if (indirect)
|
|
2275
|
+
return `${indirect} can't be checked`;
|
|
2276
|
+
if (nestedTooDeep(command))
|
|
2277
|
+
return `${NESTED} can't be checked`;
|
|
1658
2278
|
const words = shellTokens(command);
|
|
1659
2279
|
for (let i = 0; i < words.length; i++) {
|
|
1660
2280
|
const m = /^--(?:from-)?session(?:=(.*))?$/s.exec(words[i] ?? "");
|
|
@@ -1688,3 +2308,22 @@ export function idleNotice(address, reason) {
|
|
|
1688
2308
|
export function pickHolder(board) {
|
|
1689
2309
|
return [...board].sort((a, b) => b.activeAt - a.activeAt || (a.sid < b.sid ? -1 : a.sid > b.sid ? 1 : 0))[0]?.sid;
|
|
1690
2310
|
}
|
|
2311
|
+
/** IxAdvice from `p2p extensions --json`'s `ix`, or undefined when absent or malformed (an older CLI). */
|
|
2312
|
+
export function parseIxAdvice(v) {
|
|
2313
|
+
if (typeof v !== "object" || v === null)
|
|
2314
|
+
return undefined;
|
|
2315
|
+
const o = v;
|
|
2316
|
+
if (typeof o.installed !== "boolean" || typeof o.declined !== "boolean" || typeof o.recommended !== "boolean" || typeof o.install !== "string")
|
|
2317
|
+
return undefined;
|
|
2318
|
+
return { installed: o.installed, declined: o.declined, recommended: o.recommended, install: o.install };
|
|
2319
|
+
}
|
|
2320
|
+
/**
|
|
2321
|
+
* The once-per-session hint to the model when Ix isn't installed and the person hasn't said no: it
|
|
2322
|
+
* may suggest Ix to its user once; installing is theirs. Undefined when there is nothing to say.
|
|
2323
|
+
*/
|
|
2324
|
+
export function ixAgentHint(ix) {
|
|
2325
|
+
if (!ix || !ix.recommended || ix.installed || ix.declined)
|
|
2326
|
+
return undefined;
|
|
2327
|
+
const cmd = inert(ix.install).slice(0, 200);
|
|
2328
|
+
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\`).`;
|
|
2329
|
+
}
|