@alexwkleung/reika 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,8 +9,8 @@ import { execFileSync } from 'node:child_process';
9
9
  import { existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
- import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
13
- import { stripHeredocs } from './_heredoc.js';
12
+ import { WORD_RE, maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
13
+ import { scanHeredocs, stripHeredocs } from './_heredoc.js';
14
14
  import { maskMarkdownData } from './_markdown.js';
15
15
  // Workflow-policy commands: not destructive (a commit is local and reversible, a push is
16
16
  // recoverable), but they record or publish work, and the user generally wants to stay in the
@@ -141,23 +141,101 @@ const PACKAGE_PATTERNS = [
141
141
  // detectDangerousPatterns. Matching is per shell segment, because the verb position is what
142
142
  // makes this precise: `grep -rn install src/` passes `install` as an *argument*, and the
143
143
  // read-only leads below never install anything, so they are skipped outright.
144
+ //
145
+ // Position is read TWO ways, but only one of them reads every segment (#752, narrowed by #757). On
146
+ // whitespace, `GENERIC_PACKAGE_RE` counted `CFLAGS="-O2`, `-g` and `-Wall"` in `make CFLAGS="-O2 -g
147
+ // -Wall" install` as three leading tokens, so the verb landed past the budget and the install ran
148
+ // unprompted; `genericVerbWord` reads the same shape off the shell's own words, where that value is
149
+ // ONE token. The whitespace reading exists for exactly one case: `words()` DROPS a quote it cannot
150
+ // close and so SPLITS an unterminated run (`FOO="a b` reads as `FOO=`, `a`, `b`), and the extra words
151
+ // can push the verb past the budget — an under-report. Unioned with the word reading on every segment
152
+ // it was also a false-positive machine, because the other half of the same weakness is that it cuts a
153
+ // CLOSED quoted argument at the spaces inside it: `cp -r "build install" dist` is one quoted argument
154
+ // to `cp`, which `words()` reads correctly and this reading re-accepted as a verb (#757). So it is
155
+ // consulted only where `words()` actually dropped a quote — the whole difference it was paying for —
156
+ // and nowhere else. The trade: an install carried in a CLOSED quoted value, `A="make install" bash -c
157
+ // "$A"`, is now read only off words, which sees one assignment word and reports nothing. That shape
158
+ // is indistinguishable from the false positive by any test cheaper than expanding the value, which is
159
+ // `bash`'s job and not this file's. A quote-aware token PATTERN stays the rejected option: an anchored
160
+ // reader that also tolerates an unterminated quote has two viable ends per token and re-explores every
161
+ // earlier one (`GENERIC_PACKAGE_RE` ends in `install`, so a `""` run backtracks catastrophically).
162
+ // `words()` is a lexer, so it costs one linear scan.
144
163
  const GENERIC_PACKAGE_RE = /^(?:\S+\s+){1,3}?(?:-{1,2}[\w-]+\s+)*(un)?install(?![\w./-])/;
164
+ // Where `words()` first read this segment differently from the shell, or -1. A quote it cannot close
165
+ // is dropped, not failed, so the only characters a word list cannot consume are the quotes
166
+ // themselves. The position matters, not just the fact: a dropped quote only explains a verb the
167
+ // whitespace reading finds AFTER it, and an apostrophe in a trailing comment (`mv "old install" new
168
+ // # it's fine`) must not license a verb read out of the closed quote before it.
169
+ function firstDroppedQuote(segment) {
170
+ let at = 0;
171
+ for (const m of segment.matchAll(WORD_RE)) {
172
+ const gap = segment.slice(at, m.index).search(/["']/);
173
+ if (gap >= 0)
174
+ return at + gap;
175
+ at = m.index + m[0].length;
176
+ }
177
+ const gap = segment.slice(at).search(/["']/);
178
+ return gap >= 0 ? at + gap : -1;
179
+ }
180
+ // A flag token: the gap between the leading words and the verb.
181
+ const GENERIC_FLAG_RE = /^-{1,2}[\w-]+$/;
182
+ // A `VAR=value` operand (`make DESTDIR=/x install`) sits in the same gap: a make line carries
183
+ // several, and counted as leading words they pushed the verb past the budget.
184
+ const GENERIC_ASSIGN_RE = /^[A-Za-z_]\w*=/;
185
+ function genericVerbWord(list) {
186
+ // 1–3 leading words, then any run of flags and assignments, then the verb.
187
+ for (let i = 1; i <= 3 && i < list.length; i++) {
188
+ let j = i;
189
+ while (j < list.length && (GENERIC_FLAG_RE.test(list[j]) || GENERIC_ASSIGN_RE.test(list[j]))) {
190
+ j++;
191
+ }
192
+ if (j >= list.length)
193
+ break;
194
+ if (list[j] === 'uninstall')
195
+ return 'uninstall';
196
+ if (list[j] === 'install')
197
+ return 'install';
198
+ }
199
+ return undefined;
200
+ }
145
201
  const READ_ONLY_LEAD_RE = /^(?:e?grep|fgrep|rg|ag|ack|find|man|which|type|whereis|cat|bat|less|more|head|tail|awk|sed|echo|printf|ls|wc|git)\b/;
146
202
  // Tools whose own patterns already describe what they do. Without this, `helm uninstall app`
147
203
  // falls through to the generic label and reads as "removes third-party code" — it removes a
148
204
  // release from a cluster, and a misleading label is its own bug: the warning text is what the
149
205
  // user reads to decide.
150
206
  const SELF_COVERED_LEAD_RE = /^(?:helm|kubectl|oc|docker|podman|terraform|tofu|pulumi)\b/;
151
- function genericPackageLabel(command) {
152
- for (const segment of command.split(/[;&|]+/)) {
153
- const seg = segment.trim();
154
- if (!seg || READ_ONLY_LEAD_RE.test(seg) || SELF_COVERED_LEAD_RE.test(seg))
207
+ // Reads `verbSegments`' segments, so the two per-segment readers agree on what a segment is (#749).
208
+ //
209
+ // The lead is tested after the verb prefix is stripped, not on the raw segment (#757): what a
210
+ // segment runs is the command behind its assignments and wrappers, and `LANG=C grep -rn install src`
211
+ // runs `grep` — an argument, not a verb — while the raw test saw `LANG=C`, missed the read-only lead,
212
+ // and asked `grep`'s own word list for an install it never had. `stripVerbPrefix` is `verbLabels`'
213
+ // strip, so both per-segment readers agree on which command a segment runs. It skips a wrapper's
214
+ // options too (`sudo -u me grep …`), and strips `command -v x` to nothing, since that runs nothing.
215
+ //
216
+ // The VERB is still read off the raw segment as well as the stripped one: the strip brings a deep
217
+ // verb inside the budget (`env A=1 sudo time conda install numpy`) and can also move one out of it
218
+ // (`sudo install -m 644 x /etc/x` has its verb at word 1, and word 0 is past this reader by design).
219
+ // Both readings, unioned — the same rule that keeps a label at least as wide as it was.
220
+ function genericPackageLabel(segments) {
221
+ for (const segment of segments.map(s => s.trim())) {
222
+ if (!segment)
223
+ continue;
224
+ const stripped = stripVerbPrefix(segment);
225
+ if (!stripped || READ_ONLY_LEAD_RE.test(stripped) || SELF_COVERED_LEAD_RE.test(stripped)) {
155
226
  continue;
156
- const m = GENERIC_PACKAGE_RE.exec(seg);
157
- if (m) {
158
- return m[1]
159
- ? 'Uninstall command (removes third-party code)'
160
- : 'Install command (fetches and runs third-party code)';
227
+ }
228
+ for (const seg of stripped === segment ? [segment] : [segment, stripped]) {
229
+ const word = genericVerbWord(words(seg));
230
+ // The whitespace reading only where `words()` split a quote it could not close, and only for a
231
+ // verb that quote comes before — see above.
232
+ const dropped = firstDroppedQuote(seg);
233
+ const ws = dropped >= 0 ? GENERIC_PACKAGE_RE.exec(seg) : null;
234
+ const m = ws && dropped < ws[0].length ? ws : undefined;
235
+ if (word === 'uninstall' || m?.[1])
236
+ return 'Uninstall command (removes third-party code)';
237
+ if (word === 'install' || m)
238
+ return 'Install command (fetches and runs third-party code)';
161
239
  }
162
240
  }
163
241
  return undefined;
@@ -579,41 +657,300 @@ const VERB_PATTERNS = [
579
657
  ];
580
658
  // Leading tokens that don't change what a segment actually runs: env assignments, privilege and
581
659
  // timing wrappers, and the shell keywords a segment can open with (`if curl … ; then`).
582
- const VERB_PREFIX_RE = /^(?:(?:[A-Za-z_]\w*=\S*|sudo|command|nohup|exec|env|time|if|then|else|elif|do|while|until|!)\s+)+/;
660
+ //
661
+ // The quoted reading (`stripVerbPrefix`) walks the segment one shell word at a time, so an
662
+ // assignment's value is whatever the shell reads as one word: `"a b"`, `pre"a b"`, `"a b"c`, `$'a b'`,
663
+ // `a\ b`. `[A-Za-z_]\w*=\S*` stops at the space inside `"a b"` and leaves `b" curl …` standing, so
664
+ // the `^`-anchored verbs never see `curl` and the fetch runs unprompted (#752); a regex alternative
665
+ // that read only a value made of exactly one quoted run was the first cut, and missed the rest. A
666
+ // quote the walk cannot close takes the rest of its non-space run, the old reading, so an assignment
667
+ // is never left unmatchable. A lexer rather than a quote-aware pattern because a pattern that also
668
+ // tolerates an unclosed quote gives each token two viable ends, and anything anchored after it
669
+ // re-explores every earlier token's choice.
670
+ //
671
+ // `VERB_PREFIX_WS_RE` is the old strip, and it stays because the fragment IT leaves behind is
672
+ // sometimes the verb: `A="x pkill node" bash -c "$A"` reads as a `pkill` only through the blind
673
+ // reading, and the value is exactly what that `bash -c` runs. So `verbLabels` reads a segment both
674
+ // ways and reports the union — quoting can add a label, and cannot cost one. Both readings strip the
675
+ // same words, from one list, or the union would disagree about a wrapper only one of them knows.
676
+ const VERB_PREFIX_WORDS = [
677
+ 'sudo',
678
+ 'command',
679
+ 'nohup',
680
+ 'exec',
681
+ 'env',
682
+ 'time',
683
+ 'if',
684
+ 'then',
685
+ 'else',
686
+ 'elif',
687
+ 'do',
688
+ 'while',
689
+ 'until',
690
+ '!',
691
+ ];
692
+ const VERB_PREFIX_WORD_SET = new Set(VERB_PREFIX_WORDS);
693
+ const VERB_PREFIX_WS_RE = new RegExp(String.raw `^(?:(?:[A-Za-z_]\w*=\S*|${VERB_PREFIX_WORDS.join('|')})\s+)+`);
694
+ const SHELL_WORD_RE = /(?:"(?:[^"\\]|\\[\s\S])*"|\$'(?:[^'\\]|\\[\s\S])*'|'[^']*'|\\[\s\S]|[^\s"'\\])+/y;
695
+ const NON_SPACE_RUN_RE = /\S*/y;
696
+ const WORD_GAP_RE = /\s+/y;
697
+ const ENV_ASSIGN_WORD_RE = /^[A-Za-z_]\w*=/;
698
+ // A wrapper's own options sit between it and the command it runs (`sudo -u me grep …`, `env -i …`,
699
+ // `time -p …`); left in place, the option became the lead and the command behind it read as an
700
+ // argument (#757 review). These are the options that consume the next word as their value.
701
+ const WRAPPER_VALUE_OPTIONS = {
702
+ sudo: new Set(['-u', '-g', '-U', '-C', '-D', '-h', '-p', '-r', '-t', '-T', '-R']),
703
+ env: new Set(['-u', '-C']),
704
+ exec: new Set(['-a']),
705
+ time: new Set(['-o', '-f']),
706
+ };
707
+ const WRAPPER_WORDS = new Set(['sudo', 'command', 'nohup', 'exec', 'env', 'time']);
708
+ // `command -v x` looks `x` up and runs nothing, so it has no verb at all.
709
+ const COMMAND_LOOKUP_RE = /^-[a-zA-Z]*[vV]/;
710
+ function stripVerbPrefix(segment) {
711
+ let at = 0;
712
+ let wrapper;
713
+ let takesValue = false;
714
+ for (;;) {
715
+ SHELL_WORD_RE.lastIndex = at;
716
+ let end = SHELL_WORD_RE.exec(segment) ? SHELL_WORD_RE.lastIndex : at;
717
+ if (end < segment.length && /["'\\]/.test(segment[end])) {
718
+ NON_SPACE_RUN_RE.lastIndex = end;
719
+ NON_SPACE_RUN_RE.exec(segment);
720
+ end = NON_SPACE_RUN_RE.lastIndex;
721
+ }
722
+ const word = segment.slice(at, end);
723
+ if (wrapper === 'command' && COMMAND_LOOKUP_RE.test(word))
724
+ return '';
725
+ const isOption = wrapper !== undefined && (takesValue || word.startsWith('-'));
726
+ WORD_GAP_RE.lastIndex = end;
727
+ const gap = WORD_GAP_RE.exec(segment);
728
+ if (!gap || !(isOption || VERB_PREFIX_WORD_SET.has(word) || ENV_ASSIGN_WORD_RE.test(word))) {
729
+ return segment.slice(at);
730
+ }
731
+ if (takesValue) {
732
+ takesValue = false;
733
+ }
734
+ else if (isOption) {
735
+ // `--` ends the wrapper's options: the next word is the command, even one spelled `-x`.
736
+ if (word === '--')
737
+ wrapper = undefined;
738
+ else
739
+ takesValue = WRAPPER_VALUE_OPTIONS[wrapper]?.has(word) ?? false;
740
+ }
741
+ else if (WRAPPER_WORDS.has(word)) {
742
+ wrapper = word;
743
+ }
744
+ else if (!ENV_ASSIGN_WORD_RE.test(word)) {
745
+ wrapper = undefined;
746
+ }
747
+ at = WORD_GAP_RE.lastIndex;
748
+ }
749
+ }
583
750
  // Segments split on the operators AND on command substitution, so `$(curl …)` and `` `pkill …` ``
584
- // are seen as the commands they are rather than as arguments of whatever encloses them.
585
- // A separator inside quotes is data — `grep "a\|gh pr\|b"` is one grep, not a `gh pr` — except a
586
- // substitution, which runs inside double quotes too.
751
+ // are seen as the commands they are rather than as arguments of whatever encloses them. Matched
752
+ // against `maskShellData`, where a separator inside quotes is data — `grep "a\|gh pr\|b"` is one
753
+ // grep, not a `gh pr` — but a `$(…)` inside `"…"` is commands, and one inside `'…'` is neither.
587
754
  const VERB_SEPARATOR_RE = /[\n;&|(){}]+|\$\(|`/g;
588
- function verbSegments(command) {
755
+ // The shells that read a heredoc body as a program of their own. Everything else — `python3 -`,
756
+ // `node -`, `cat > run.py`, `gh --body-file -` — reads a body as a script in another language or as
757
+ // text, where a `; curl y` inside a string literal is a string and not a second command. Naming a
758
+ // shell here is the direction that KEEPS a body in the scan, so the set errs long: a wrong name
759
+ // costs an over-reported label, not a hidden command.
760
+ const SHELL_READERS = new Set([
761
+ 'sh',
762
+ 'bash',
763
+ 'rbash',
764
+ 'dash',
765
+ 'ash',
766
+ 'ksh',
767
+ 'mksh',
768
+ 'pdksh',
769
+ 'oksh',
770
+ 'zsh',
771
+ 'yash',
772
+ 'csh',
773
+ 'tcsh',
774
+ 'fish',
775
+ 'xonsh',
776
+ 'elvish',
777
+ 'busybox',
778
+ 'su',
779
+ ]);
780
+ // A version suffix still names the shell: `ksh93`, `bash5`, `zsh-5.9`.
781
+ function namesShell(word) {
782
+ const name = word.slice(word.lastIndexOf('/') + 1);
783
+ return SHELL_READERS.has(name) || SHELL_READERS.has(name.replace(/-?\d[\d.]*$/, ''));
784
+ }
785
+ // `.`/`source` read a file as shell, and stdin is a file: `. /dev/stdin <<'EOF'` runs the body.
786
+ const SOURCE_STDIN_RE = /(?:^|[\s;&|(])(?:\.|source)\s+\/(?:dev\/stdin|dev\/fd\/0|proc\/self\/fd\/0)(?=\s|$)/m;
787
+ // Whether a shell is named anywhere in the command outside its heredoc bodies. Any one then keeps
788
+ // every body in the scan, because the reader is not only the operator's own pipeline: a body
789
+ // written to a file is run by a shell on a later line (`cat > s.sh <<'EOF'` … `sh s.sh`), a shell
790
+ // on an earlier line reaches it through a `\` continuation or an open `bash -c "$(`, and a pipe
791
+ // carries on past a comment (`| # note`). Over-reports a command that merely names a shell.
792
+ function shellOutsideBodies(command, heredocs) {
793
+ let outside = command;
794
+ for (const h of heredocs) {
795
+ outside =
796
+ outside.slice(0, h.bodyStart) + ' '.repeat(h.end - h.bodyStart) + outside.slice(h.end);
797
+ }
798
+ return SOURCE_STDIN_RE.test(outside) || words(outside).some(namesShell);
799
+ }
800
+ // Whether a pipeline stage could be the shell that runs the body. ANY word naming a shell counts,
801
+ // not just the command word, because the shell can sit behind a wrapper's flags — `sudo -u me bash`,
802
+ // `env -i sh` — where the first word is the wrapper or one of its operands, and because a shell in
803
+ // the stage is the one reading the body either way. Coarse on purpose: `cat <<'EOF' | grep -n sh`
804
+ // then keeps the body in the scan and over-reports, which is the direction this can afford. A stage
805
+ // with no words at all is one the caller cannot read (`cat <<'EOF' |` with the pipeline continuing on
806
+ // the next line) and is answered the same way.
807
+ //
808
+ // The lookup is lexical, so it misses any name that only BECOMES a shell after quote removal or
809
+ // expansion — `s\h`, `$SHELL`, a backtick — and each miss HIDES a body a shell runs. One character
810
+ // of them is visible without guessing: they all carry a `\`, a `$` or a backtick, which no literal
811
+ // shell name does. A stage carrying one is answered as a shell too; over-report is the affordable
812
+ // error, a hidden `pkill node` is not.
813
+ function readsAsShell(stage) {
814
+ const ws = words(stage);
815
+ return ws.length === 0 || /[$`\\]/.test(stage) || ws.some(namesShell);
816
+ }
817
+ // The pipeline stages of one physical line, split on `|` as the quote mask sees it: a `|` inside a
818
+ // quoted string is a data character, not a stage boundary.
819
+ function lineStages(command, view, lineStart, lineEnd) {
820
+ const stages = [];
821
+ let start = lineStart;
822
+ for (let i = lineStart; i < lineEnd; i++) {
823
+ if (view[i] !== '|')
824
+ continue;
825
+ stages.push({ start, end: i });
826
+ start = i + 1;
827
+ }
828
+ stages.push({ start, end: lineEnd });
829
+ return stages;
830
+ }
831
+ // The verb question's two accounts of one command: `maskQuoted`'s, plus the heredoc bodies nothing
832
+ // runs (#699). A body is the verb scan's blind spot in both directions. The shell pastes it whole,
833
+ // so none of its separators are the shell's — but the walk that builds the quote mask deliberately
834
+ // records no quote spans inside one, because the shell doesn't quote-parse a body either. So before
835
+ // this, a `;` inside a string literal in a body split a segment and made the next word a verb:
836
+ // `python3 - <<'EOF'` / `print("x; curl y")` / `EOF` read as a `curl`, which for a script that runs
837
+ // no shell is exactly the reflexive-approval prompt the gate exists to avoid. Approving it also runs
838
+ // the script UNSANDBOXED (a flagged command a human cleared is `decideSandbox`'s unbounded case),
839
+ // where without the label it would have run sandboxed and unprompted.
840
+ //
841
+ // `pasted` comes back as its own list rather than as more blanking in `syntax`, and that is not
842
+ // cosmetic: `verbSegments` finds its separators in that mask, and a body's OPENING newline cannot be
843
+ // blanked without changing the command's line structure. A region is therefore reported as the
844
+ // half-open span `[bodyStart - 1, bodyEnd)` — the body plus the newline that opened
845
+ // it, terminator line excluded — and a caller asks whether a separator RUN ends in one. Not where
846
+ // it STARTS: `cat <<'EOF';` glues the body's opening newline onto the `;` before it, so a
847
+ // start-position test lets the body's first line through as a segment — while a run starting inside
848
+ // the body (a separator-char delimiter like `cat <<';'`) can cross `bodyEnd` and swallow the
849
+ // newline that restores `keep`, hiding the command after the body. The END of the run is what says
850
+ // "inside": it is the separator the run stands for.
851
+ //
852
+ // Three things keep a body out of `pasted`, and they are all the over-reporting side:
853
+ //
854
+ // - an UNQUOTED delimiter (`<<EOF`, `<<\EOF`): the shell expands `$(…)` and backticks in the body,
855
+ // so a substitution there runs — the same body `expandingHeredocBodies` reports. Only a body
856
+ // the shell pastes literally is data here.
857
+ // - a shell as the reader: `sh -s <<'EOF'`, one behind a wrapper's flags (`env -i sh <<'EOF'`) or
858
+ // further down the pipeline (`cat <<'EOF' | sh`, `cat <<'EOF' | sudo /bin/bash -s`), where the
859
+ // body arrives on the shell's stdin as commands. Such a body stays in the scan, because nothing
860
+ // here quote-parses it and so a bare `pkill node` line in one cannot be told from a string.
861
+ // - a reader that cannot be read: a stage with no words at all, and a line that ends in `\`, are
862
+ // both pipelines this does not see the end of.
863
+ //
864
+ // A command the lexer cannot read exactly pastes nothing, exactly as `maskQuoted` blanks nothing:
865
+ // the labels then over-report, never hide.
866
+ function verbData(command) {
867
+ const syntax = maskShellData(command);
589
868
  const masked = maskQuoted(command);
869
+ const scan = scanHeredocs(command);
870
+ if (scan.uncertain || shellOutsideBodies(command, scan.heredocs))
871
+ return { syntax, pasted: [] };
872
+ const pasted = [];
873
+ for (const h of scan.heredocs) {
874
+ if (!h.literal)
875
+ continue;
876
+ // An EMPTY body still reports its opening newline: the line that would close it is the
877
+ // terminator, and a terminator that reads as a verb (`cat <<'curl'` / `curl`) is not a command.
878
+ // The span degenerates to that one newline, which is all the caller needs.
879
+ // The verb question runs per line, and the reader and every stage the body could reach are both
880
+ // on the operator's own line: the body starts after the newline that ends it.
881
+ const lineStart = command.lastIndexOf('\n', h.opAt - 1) + 1;
882
+ const nl = command.indexOf('\n', h.opAt);
883
+ // A backslash before the newline continues the line, so the pipeline the operator sits in may
884
+ // reach further than this reads (and the shell puts the body after the NEXT newline, which is
885
+ // not where the lexer looked). Nothing is pasted then: the body stays in the scan.
886
+ let trailing = 0;
887
+ while (nl > lineStart && command[nl - 1 - trailing] === '\\')
888
+ trailing++;
889
+ if (trailing % 2 === 1)
890
+ continue;
891
+ const stages = lineStages(command, masked, lineStart, nl === -1 ? command.length : nl);
892
+ // The stage the operator sits in is the reader's; the ones after it are where a pipe could hand
893
+ // the body on to a shell. Earlier stages cannot read it, so `sh setup.sh | cat <<'EOF'` pastes.
894
+ const readers = stages
895
+ .slice(stages.findIndex(s => h.opAt < s.end))
896
+ .map(s => command.slice(s.start, s.end));
897
+ if (readers.some(readsAsShell))
898
+ continue;
899
+ pasted.push([h.bodyStart - 1, h.bodyEnd]);
900
+ }
901
+ return { syntax, pasted };
902
+ }
903
+ // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
904
+ // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
905
+ function verbSegments(command, pasteBodies) {
906
+ const { syntax, pasted: found } = verbData(command);
907
+ const pasted = pasteBodies ? found : [];
908
+ // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
909
+ // backslash before a newline is not one, and the mask is what tells them apart.
910
+ const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
590
911
  const segments = [];
591
912
  let start = 0;
592
913
  let keep = true;
593
914
  VERB_SEPARATOR_RE.lastIndex = 0;
594
- for (let m = VERB_SEPARATOR_RE.exec(command); m; m = VERB_SEPARATOR_RE.exec(command)) {
915
+ for (let m = VERB_SEPARATOR_RE.exec(syntax); m; m = VERB_SEPARATOR_RE.exec(syntax)) {
595
916
  if (keep)
596
- segments.push(command.slice(start, m.index));
917
+ segments.push(text.slice(start, m.index));
597
918
  start = m.index + m[0].length;
598
- keep = m[0] === '$(' || m[0] === '`' || masked[m.index] === command[m.index];
919
+ // A separator inside a pasted body ends nothing the shell runs, so the text it closes is not a
920
+ // segment of its own — and `keep` goes false, which is what holds the body's own lines out of
921
+ // the next segment. It is read off `pasted` rather than off a blanked `masked`, because the
922
+ // opening separator of a body IS that body's newline and stays one in the mask. The test is
923
+ // where the run ENDS: `cat <<'EOF';` glues the body's opening newline onto the `;` before it
924
+ // (a start-position test would let the body's first line through), and a run starting inside
925
+ // the body can cross `bodyEnd` and swallow the newline that restores `keep` (hiding the command
926
+ // after the body) — an END past the region means the run ends in real syntax, and its text is
927
+ // the shell's again. A `$(…)` inside a pasted body is a string in that script.
928
+ keep = !pasted.some(([from, to]) => m.index + m[0].length > from && m.index + m[0].length <= to);
599
929
  }
600
930
  if (keep)
601
- segments.push(command.slice(start));
931
+ segments.push(text.slice(start));
602
932
  return segments;
603
933
  }
604
- function verbLabels(command) {
934
+ function verbLabels(segments) {
605
935
  const hits = [];
606
- for (const segment of verbSegments(command)) {
607
- const seg = segment.trim().replace(VERB_PREFIX_RE, '');
608
- if (!seg)
609
- continue;
610
- for (const { re, label } of VERB_PATTERNS) {
611
- if (re.test(seg) && !hits.includes(label))
612
- hits.push(label);
936
+ for (const segment of segments) {
937
+ const trimmed = segment.trim();
938
+ // Both prefix readings, unioned — see `VERB_PREFIX_WS_RE` above. They agree on any segment
939
+ // without a quoted value holding a space, which is nearly all of them, so the second pass only
940
+ // runs when they differ.
941
+ const quoted = stripVerbPrefix(trimmed);
942
+ const spaced = trimmed.replace(VERB_PREFIX_WS_RE, '');
943
+ for (const seg of spaced === quoted ? [quoted] : [quoted, spaced]) {
944
+ if (!seg)
945
+ continue;
946
+ for (const { re, label } of VERB_PATTERNS) {
947
+ if (re.test(seg) && !hits.includes(label))
948
+ hits.push(label);
949
+ }
950
+ const cluster = clusterLabel(seg) ?? ghLabel(seg) ?? hfLabel(seg);
951
+ if (cluster && !hits.includes(cluster))
952
+ hits.push(cluster);
613
953
  }
614
- const cluster = clusterLabel(seg) ?? ghLabel(seg) ?? hfLabel(seg);
615
- if (cluster && !hits.includes(cluster))
616
- hits.push(cluster);
617
954
  }
618
955
  return hits;
619
956
  }
@@ -832,6 +1169,11 @@ function readWord(rest) {
832
1169
  const SHELL_C_RE = /\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[\w-]+\s+)*-c(?![\w-])/g;
833
1170
  const INTERPRETER_C_RE = /\b(python[\d.]*|ruby|perl|node|deno|php)\s+(?:-[\w-]+\s+)*(-[ce])(?![\w-])/g;
834
1171
  const CONTAINER_EXEC_RE = /\b(kubectl|oc|docker|podman)\s+(?:exec|run)\b[^\n]*?\s--(?=\s)/g;
1172
+ // The assignment arm keeps its bare `\S*` where the verb reader went to a lexer (#752), and the
1173
+ // trailing `ssh` is why: a quoted value has two viable ends (up to the space, or at the closing
1174
+ // `"`) and an `ssh` that fails to appear makes the engine re-explore every earlier token's choice.
1175
+ // What a miss costs here is the `via ssh:` detail only: `stripVerbPrefix` still puts `ssh` itself
1176
+ // in verb position, so the remote command prompts as remote host access.
835
1177
  const SSH_LEAD_RE = /(?:^|[\n;&|`(])\s*(?:(?:[A-Za-z_]\w*=\S*|sudo|command|nohup|env|time)\s+)*ssh(?![\w./-])/g;
836
1178
  const MAX_NESTED_BODIES = 8;
837
1179
  function nestedBodies(command) {
@@ -888,13 +1230,13 @@ function* segmentsWithDir(command, cwd) {
888
1230
  const stripped = stripHeredocs(command);
889
1231
  let dir = cwd;
890
1232
  for (const raw of splitSegments(stripped, maskQuoted(stripped))) {
891
- const words = (raw.trim().match(WORD_RE) ?? []).map(w => w.replace(/['"]/g, ''));
892
- if (words[0] === 'cd') {
893
- if (words[1])
894
- dir = resolve(dir, expandHome(words[1]));
1233
+ const ws = words(raw.trim());
1234
+ if (ws[0] === 'cd') {
1235
+ if (ws[1])
1236
+ dir = resolve(dir, expandHome(ws[1]));
895
1237
  continue;
896
1238
  }
897
- yield { dir, words };
1239
+ yield { dir, words: ws };
898
1240
  }
899
1241
  }
900
1242
  function expandHome(path) {
@@ -1013,8 +1355,11 @@ function detectAtDepth(rawCommand, depth, cwd) {
1013
1355
  if (re.test(command) && !hits.includes(label))
1014
1356
  hits.push(label);
1015
1357
  }
1358
+ // A shell's `-c` program pastes nothing: a heredoc there can be a `$(cat <<'EOF' …)` whose
1359
+ // output IS the program, and the shell that runs it was named one level up, out of sight here.
1360
+ const segments = verbSegments(command, depth === 0);
1016
1361
  for (const label of [
1017
- ...verbLabels(command),
1362
+ ...verbLabels(segments),
1018
1363
  remoteExecLabel(command, cwd),
1019
1364
  checkoutPathLabel(command, cwd),
1020
1365
  ]) {
@@ -1025,7 +1370,7 @@ function detectAtDepth(rawCommand, depth, cwd) {
1025
1370
  // reports one precise label instead of two overlapping ones. Every install/uninstall label
1026
1371
  // above contains the word, which is what makes this cheap test sufficient.
1027
1372
  if (!hits.some(h => /install/i.test(h))) {
1028
- const generic = genericPackageLabel(command);
1373
+ const generic = genericPackageLabel(segments);
1029
1374
  if (generic)
1030
1375
  hits.push(generic);
1031
1376
  }
@@ -39,6 +39,8 @@ const WORD_END_RE = /[\s;&|<>()]/;
39
39
  export function scanHeredocs(command) {
40
40
  const heredocs = [];
41
41
  const quotes = [];
42
+ const substitutions = [];
43
+ const escapes = [];
42
44
  let unclosedQuote = false;
43
45
  let ambiguousQuote = false;
44
46
  let uncertain = false;
@@ -46,6 +48,11 @@ export function scanHeredocs(command) {
46
48
  let pending = [];
47
49
  const n = command.length;
48
50
  let i = 0;
51
+ const closeSubstitution = (end) => {
52
+ const f = stack.pop();
53
+ if (f?.subAt !== undefined)
54
+ substitutions.push({ start: f.subAt, end });
55
+ };
49
56
  const innermostCloser = () => {
50
57
  for (let k = stack.length - 1; k >= 0; k--) {
51
58
  if (stack[k].kind === 'sub')
@@ -69,12 +76,12 @@ export function scanHeredocs(command) {
69
76
  i++;
70
77
  }
71
78
  else if (ch === '`') {
72
- stack.push({ kind: 'tick', parens: 0 });
79
+ stack.push({ kind: 'tick', parens: 0, subAt: i });
73
80
  i++;
74
81
  }
75
82
  else if (ch === '$' && command[i + 1] === '(') {
76
83
  const arith = command[i + 2] === '(';
77
- stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
84
+ stack.push({ kind: arith ? 'arith' : 'sub', parens: 0, subAt: arith ? undefined : i });
78
85
  i += arith ? 3 : 2;
79
86
  }
80
87
  else
@@ -108,6 +115,7 @@ export function scanHeredocs(command) {
108
115
  }
109
116
  // A command context: the top level, a `$(…)`, a backtick or a process substitution.
110
117
  if (ch === '\\') {
118
+ escapes.push(i);
111
119
  i += 2;
112
120
  continue;
113
121
  }
@@ -150,15 +158,15 @@ export function scanHeredocs(command) {
150
158
  }
151
159
  if (ch === '`') {
152
160
  if (frame.kind === 'tick')
153
- stack.pop();
161
+ closeSubstitution(i + 1);
154
162
  else
155
- stack.push({ kind: 'tick', parens: 0 });
163
+ stack.push({ kind: 'tick', parens: 0, subAt: i });
156
164
  i++;
157
165
  continue;
158
166
  }
159
167
  if (ch === '$' && command[i + 1] === '(') {
160
168
  const arith = command[i + 2] === '(';
161
- stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
169
+ stack.push({ kind: arith ? 'arith' : 'sub', parens: 0, subAt: arith ? undefined : i });
162
170
  i += arith ? 3 : 2;
163
171
  continue;
164
172
  }
@@ -182,13 +190,13 @@ export function scanHeredocs(command) {
182
190
  if (frame.parens > 0)
183
191
  frame.parens--;
184
192
  else if (frame.kind === 'sub')
185
- stack.pop();
193
+ closeSubstitution(i + 1);
186
194
  i++;
187
195
  continue;
188
196
  }
189
197
  if ((ch === '<' || ch === '>') && command[i + 1] === '(') {
190
198
  // Process substitution runs a command of its own, with its own heredocs.
191
- stack.push({ kind: 'sub', parens: 0 });
199
+ stack.push({ kind: 'sub', parens: 0, subAt: i });
192
200
  i += 2;
193
201
  continue;
194
202
  }
@@ -261,7 +269,11 @@ export function scanHeredocs(command) {
261
269
  // the `)` ever arrives, so the spans read there are good either way.
262
270
  if (stack.some(f => f.kind === 'dq'))
263
271
  unclosedQuote = true;
264
- return { heredocs, quotes, unclosedQuote, ambiguousQuote, uncertain };
272
+ for (const f of stack) {
273
+ if (f.subAt !== undefined)
274
+ substitutions.push({ start: f.subAt, end: n });
275
+ }
276
+ return { heredocs, quotes, substitutions, escapes, unclosedQuote, ambiguousQuote, uncertain };
265
277
  }
266
278
  function pendingFields(p) {
267
279
  return {
@@ -366,6 +378,8 @@ export function scanQuotes(command) {
366
378
  const scan = scanHeredocs(command);
367
379
  return {
368
380
  spans: scan.quotes,
381
+ substitutions: scan.substitutions,
382
+ escapes: scan.escapes,
369
383
  uncertain: scan.unclosedQuote || scan.ambiguousQuote,
370
384
  heredocOperator: heredocOperatorIn(scan),
371
385
  };