From 2eee66a6c177dcff302f50772fa5a9000dbd6fb5 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 23 Oct 2026 01:45:20 +0200 Subject: [PATCH 01/16] fix(hooks): split shell segments at newlines, keeping here-document bodies whole splitShellSegments() split at &&, ||, ; and & but not at a newline, so a multi-line command such as "cd app\nnpm run dev" was one segment led by cd, and the dev-server block let the dev server through. A newline now ends a segment. The body of a here-document (<, >&, 2>&1) are NOT treated as separators. + * Split a shell command into segments by operators (&&, ||, ;, &) and by + * newlines, while respecting quoting (single/double) and escaped characters. + * Redirection operators (&>, >&, 2>&1) are NOT treated as separators, and the + * body of a here-document stays in the segment of the command that reads it. */ function splitShellSegments(command) { const segments = []; let current = ''; let quote = null; + // Here-documents opened on the current line, read after its newline. + let heredocs = []; for (let i = 0; i < command.length; i++) { const ch = command[i]; @@ -42,6 +71,25 @@ function splitShellSegments(command) { const next = command[i + 1] || ''; const prev = i > 0 ? command[i - 1] : ''; + const heredoc = ch === '<' && next === '<' ? heredocAt(command, i) : null; + if (heredoc) { + heredocs.push(heredoc); + current += heredoc.text; + i += heredoc.text.length - 1; + continue; + } + + // A newline ends a command, after the bodies of the here-documents opened on its line + if (ch === '\n') { + const end = endOfHeredocBodies(command, i + 1, heredocs); + current += command.slice(i, end); + i = end - 1; + heredocs = []; + if (current.trim()) segments.push(current.trim()); + current = ''; + continue; + } + // && operator if (ch === '&' && next === '&') { if (current.trim()) segments.push(current.trim()); diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 89524b1e0..35414ad19 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -215,6 +215,20 @@ function runTests() { }) ? passed++ : failed++); } + // --- Newlines --- + + if (!isWindows) { + (test('blocks a dev server started on a later line of a multi-line command', () => { + const result = runScript('cd app\nnpm run dev'); + assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); + }) ? passed++ : failed++); + } + + (test('allows a here-document that only mentions a dev server', () => { + const result = runScript('cat < README.md\nStart it with:\nnpm run dev\nEOF'); + assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); + }) ? passed++ : failed++); + // --- Edge cases --- (test('empty/invalid input passes through (exit code 0)', () => { diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 1ec1cdb2b..964ef54e8 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -110,5 +110,31 @@ test('single command no operators', () => { assert.deepStrictEqual(splitShellSegments('npm run dev'), ['npm run dev']); }); +// Newlines and here-documents +console.log('\nNewlines and here-documents:'); +test('a newline splits into two segments', () => { + assert.deepStrictEqual(splitShellSegments('cd app\nnpm run dev'), ['cd app', 'npm run dev']); + assert.deepStrictEqual(splitShellSegments('a && b\n\nc'), ['a', 'b', 'c']); +}); +test('an escaped or quoted newline does not split', () => { + assert.deepStrictEqual(splitShellSegments('npm run \\\ndev'), ['npm run \\\ndev']); + assert.deepStrictEqual(splitShellSegments('echo "a\nb"'), ['echo "a\nb"']); +}); +test('a here-document body stays with its command', () => { + assert.deepStrictEqual( + splitShellSegments('cat < notes.md\na && b\nnpm run dev\nEOF\nls'), + ['cat < notes.md\na && b\nnpm run dev\nEOF', 'ls'] + ); + assert.deepStrictEqual( + splitShellSegments("cat <<-'END'\n\tnpm run dev\n\tEND\nls"), + ["cat <<-'END'\n\tnpm run dev\n\tEND", 'ls'] + ); + assert.deepStrictEqual(splitShellSegments('cat < { + assert.deepStrictEqual(splitShellSegments('cat <<< x && y'), ['cat <<< x', 'y']); + assert.deepStrictEqual(splitShellSegments('echo $((x << 2))\nnext'), ['echo $((x << 2))', 'next']); +}); + console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`); if (failed > 0) process.exit(1); From 8dedd4ceb3996cf58b0005494433349d9655197f Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 23 Oct 2026 02:01:04 +0200 Subject: [PATCH 02/16] fix(hooks): read << as a here-document only outside comments and arithmetic A << in a comment (echo ok # < 0 ? command[i - 1] : ''; + const spanEnd = literalSpanEnd(command, i, current === '' || /[\s;&|(]/.test(prev)); + if (spanEnd !== -1) { + current += command.slice(i, spanEnd); + i = spanEnd - 1; + continue; + } + const heredoc = ch === '<' && next === '<' ? heredocAt(command, i) : null; if (heredoc) { heredocs.push(heredoc); diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 964ef54e8..875f0262f 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -134,6 +134,19 @@ test('a here-document body stays with its command', () => { test('a here-string or a shift is not a here-document', () => { assert.deepStrictEqual(splitShellSegments('cat <<< x && y'), ['cat <<< x', 'y']); assert.deepStrictEqual(splitShellSegments('echo $((x << 2))\nnext'), ['echo $((x << 2))', 'next']); + assert.deepStrictEqual(splitShellSegments('echo $((x << n))\nnpm run dev'), ['echo $((x << n))', 'npm run dev']); + assert.deepStrictEqual(splitShellSegments('(( n << 2 )) && npm run dev'), ['(( n << 2 ))', 'npm run dev']); +}); +test('a << in a comment is not a here-document, and a comment is not split', () => { + assert.deepStrictEqual(splitShellSegments('echo ok # < { + assert.deepStrictEqual( + splitShellSegments('cat < Date: Fri, 23 Oct 2026 02:18:33 +0200 Subject: [PATCH 03/16] fix(hooks): read a here-document delimiter as a shell word and keep bodies with their command The opener pattern read only an identifier, so <]/.test(ch)) { + break; + } else { + delimiter += ch; + } + } + return delimiter && !quote ? { text: command.slice(index, i), delimiter, stripTabs } : null; } // The index after the `))` that closes the arithmetic `((` at `index`, or -1. @@ -47,6 +64,22 @@ function endOfHeredocBodies(command, start, heredocs) { return Math.min(end, command.length); } +// At the newline at `index` the command ends, after the bodies of the here-documents opened on +// its line. The bodies are data, so they go with the command that opened the first of them, even +// when an operator after it (`cat < 0 && heredocs[0].segment < segments.length) { + segments[heredocs[0].segment] += bodies.trimEnd(); + bodies = ''; + } + const rest = (current + bodies).trim(); + if (rest) segments.push(rest); + return end; +} + /** * Split a shell command into segments by operators (&&, ||, ;, &) and by * newlines, while respecting quoting (single/double) and escaped characters. @@ -101,7 +134,7 @@ function splitShellSegments(command) { const heredoc = ch === '<' && next === '<' ? heredocAt(command, i) : null; if (heredoc) { - heredocs.push(heredoc); + heredocs.push({ ...heredoc, segment: segments.length }); current += heredoc.text; i += heredoc.text.length - 1; continue; @@ -109,11 +142,8 @@ function splitShellSegments(command) { // A newline ends a command, after the bodies of the here-documents opened on its line if (ch === '\n') { - const end = endOfHeredocBodies(command, i + 1, heredocs); - current += command.slice(i, end); - i = end - 1; + i = endLine(command, i, current, heredocs, segments) - 1; heredocs = []; - if (current.trim()) segments.push(current.trim()); current = ''; continue; } diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 35414ad19..739da2ad0 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -229,6 +229,11 @@ function runTests() { assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); }) ? passed++ : failed++); + (test('allows a here-document body that follows an operator', () => { + const result = runScript('cat < { diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 875f0262f..bd4772305 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -142,6 +142,24 @@ test('a << in a comment is not a here-document, and a comment is not split', () assert.deepStrictEqual(splitShellSegments('echo hi # a && b'), ['echo hi # a && b']); assert.deepStrictEqual(splitShellSegments('echo a#b ${#x} && c'), ['echo a#b ${#x}', 'c']); }); +test('a here-document delimiter is a shell word, read without its quotes', () => { + assert.deepStrictEqual( + splitShellSegments('cat < { + assert.deepStrictEqual( + splitShellSegments('cat < { assert.deepStrictEqual( splitShellSegments('cat < Date: Fri, 23 Oct 2026 02:47:32 +0200 Subject: [PATCH 04/16] fix(hooks): leave here-document bodies out of the shell segments A body attached to the segment of its command was still searched by the dev-server check. For npm --version <]/.test(ch)) { @@ -25,7 +28,7 @@ function heredocAt(command, index) { delimiter += ch; } } - return delimiter && !quote ? { text: command.slice(index, i), delimiter, stripTabs } : null; + return (delimiter || quoted) && !quote ? { text: command.slice(index, i), delimiter, stripTabs } : null; } // The index after the `))` that closes the arithmetic `((` at `index`, or -1. @@ -64,27 +67,19 @@ function endOfHeredocBodies(command, start, heredocs) { return Math.min(end, command.length); } -// At the newline at `index` the command ends, after the bodies of the here-documents opened on -// its line. The bodies are data, so they go with the command that opened the first of them, even -// when an operator after it (`cat < 0 && heredocs[0].segment < segments.length) { - segments[heredocs[0].segment] += bodies.trimEnd(); - bodies = ''; - } - const rest = (current + bodies).trim(); - if (rest) segments.push(rest); - return end; + if (current.trim()) segments.push(current.trim()); + return endOfHeredocBodies(command, index + 1, heredocs); } /** * Split a shell command into segments by operators (&&, ||, ;, &) and by * newlines, while respecting quoting (single/double) and escaped characters. * Redirection operators (&>, >&, 2>&1) are NOT treated as separators, and the - * body of a here-document stays in the segment of the command that reads it. + * body of a here-document, which is data, is left out of the segments. */ function splitShellSegments(command) { const segments = []; @@ -134,7 +129,7 @@ function splitShellSegments(command) { const heredoc = ch === '<' && next === '<' ? heredocAt(command, i) : null; if (heredoc) { - heredocs.push({ ...heredoc, segment: segments.length }); + heredocs.push(heredoc); current += heredoc.text; i += heredoc.text.length - 1; continue; diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 739da2ad0..4db73f983 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -234,6 +234,11 @@ function runTests() { assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); }) ? passed++ : failed++); + (test('allows a here-document body fed to a package manager command', () => { + const result = runScript('npm --version < { diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index bd4772305..6c99a00ba 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -120,16 +120,10 @@ test('an escaped or quoted newline does not split', () => { assert.deepStrictEqual(splitShellSegments('npm run \\\ndev'), ['npm run \\\ndev']); assert.deepStrictEqual(splitShellSegments('echo "a\nb"'), ['echo "a\nb"']); }); -test('a here-document body stays with its command', () => { - assert.deepStrictEqual( - splitShellSegments('cat < notes.md\na && b\nnpm run dev\nEOF\nls'), - ['cat < notes.md\na && b\nnpm run dev\nEOF', 'ls'] - ); - assert.deepStrictEqual( - splitShellSegments("cat <<-'END'\n\tnpm run dev\n\tEND\nls"), - ["cat <<-'END'\n\tnpm run dev\n\tEND", 'ls'] - ); - assert.deepStrictEqual(splitShellSegments('cat < { + assert.deepStrictEqual(splitShellSegments('cat < notes.md\na && b\nnpm run dev\nEOF\nls'), ['cat < notes.md', 'ls']); + assert.deepStrictEqual(splitShellSegments("cat <<-'END'\n\tnpm run dev\n\tEND\nls"), ["cat <<-'END'", 'ls']); + assert.deepStrictEqual(splitShellSegments('cat < { assert.deepStrictEqual(splitShellSegments('cat <<< x && y'), ['cat <<< x', 'y']); @@ -143,28 +137,18 @@ test('a << in a comment is not a here-document, and a comment is not split', () assert.deepStrictEqual(splitShellSegments('echo a#b ${#x} && c'), ['echo a#b ${#x}', 'c']); }); test('a here-document delimiter is a shell word, read without its quotes', () => { - assert.deepStrictEqual( - splitShellSegments('cat < { - assert.deepStrictEqual( - splitShellSegments('cat < { + assert.deepStrictEqual(splitShellSegments('cat < { - assert.deepStrictEqual( - splitShellSegments('cat < Date: Fri, 23 Oct 2026 03:13:14 +0200 Subject: [PATCH 05/16] fix(hooks): check the commands that an expanded here-document body runs Bash expands a here-document body unless part of its delimiter is quoted, and runs the $(...) and backquoted substitutions in it, with quotes as plain text. Leaving the whole body out of the segments hid those commands, so npm --version <]/.test(ch)) { break; } else { delimiter += ch; } } - return (delimiter || quoted) && !quote ? { text: command.slice(index, i), delimiter, stripTabs } : null; + if ((!delimiter && !quoted) || quote) return null; + return { text: command.slice(index, i), delimiter, stripTabs, expands: !quoted }; +} + +// The index after the `)` that closes the `(` at `index`, or -1. Quoted parentheses and escaped +// characters do not count. +function endOfParens(command, index) { + let depth = 0; + let quote = null; + for (let i = index; i < command.length; i++) { + const ch = command[i]; + if (ch === '\\' && quote !== "'") i++; + else if (quote) quote = ch === quote ? null : quote; + else if (ch === "'" || ch === '"') quote = ch; + else if (ch === '(') depth++; + else if (ch === ')' && --depth === 0) return i + 1; + } + return -1; } // The index after the `))` that closes the arithmetic `((` at `index`, or -1. function endOfArithmetic(command, index) { - let depth = 0; - for (let i = index; i < command.length; i++) { - if (command[i] === '(') depth++; - else if (command[i] === ')' && --depth === 0) return command[i - 1] === ')' ? i + 1 : -1; + const end = endOfParens(command, index); + return end !== -1 && command[end - 2] === ')' ? end : -1; +} + +// The commands of the `$(...)` and backquoted substitutions in an expanded here-document body. +// Bash runs them while it reads the body, where quotes are plain text and a backslash escapes. +function commandSubstitutions(body) { + const commands = []; + let i = 0; + while (i < body.length) { + const backquoted = body[i] === '`'; + if (body[i] === '\\') { + i += 2; + } else if (backquoted || (body[i] === '$' && body[i + 1] === '(')) { + const end = backquoted ? body.indexOf('`', i + 1) + 1 : endOfParens(body, i + 1); + if (end <= 0) break; + commands.push(body.slice(backquoted ? i + 1 : i + 2, end - 1)); + i = end; + } else { + i++; + } } - return -1; + return commands; } // The end of a span copied as is, or -1: a comment, which runs to the end of its line, or an @@ -51,28 +87,39 @@ function literalSpanEnd(command, index, atWordStart) { return command[index] === '(' && command[index + 1] === '(' ? endOfArithmetic(command, index) : -1; } -// The end of the here-document bodies that start at `start`, one after the other. -function endOfHeredocBodies(command, start, heredocs) { +// The here-document bodies that start at `start`, one after the other: the index after them, +// and the commands that the expanded ones run through command substitution. +function readHeredocBodies(command, start, heredocs) { let end = start; - for (const { delimiter, stripTabs } of heredocs) { + const substitutions = []; + for (const { delimiter, stripTabs, expands } of heredocs) { + const bodyStart = end; + let bodyEnd = command.length; while (end < command.length) { const newline = command.indexOf('\n', end); const lineEnd = newline === -1 ? command.length : newline; // A CRLF line ends in \r, which is not part of the delimiter. const line = command.slice(end, lineEnd).replace(/\r$/, ''); + const lineStart = end; end = lineEnd + 1; - if ((stripTabs ? line.replace(/^\t+/, '') : line) === delimiter) break; + if ((stripTabs ? line.replace(/^\t+/, '') : line) === delimiter) { + bodyEnd = lineStart; + break; + } } + if (expands) substitutions.push(...commandSubstitutions(command.slice(bodyStart, bodyEnd))); } - return Math.min(end, command.length); + return { end: Math.min(end, command.length), substitutions }; } // At the newline at `index` the command ends. The bodies of the here-documents opened on its -// line follow it. They are data, not commands, so they are left out of the segments. Returns the -// index after the bodies. +// line follow it. They are data, not commands, so they are left out of the segments, except for +// the commands that an expanded body runs. Returns the index after the bodies. function endLine(command, index, current, heredocs, segments) { if (current.trim()) segments.push(current.trim()); - return endOfHeredocBodies(command, index + 1, heredocs); + const { end, substitutions } = readHeredocBodies(command, index + 1, heredocs); + for (const substitution of substitutions) segments.push(...splitShellSegments(substitution)); + return end; } /** diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 4db73f983..301f5876a 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -222,6 +222,13 @@ function runTests() { const result = runScript('cd app\nnpm run dev'); assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); }) ? passed++ : failed++); + + (test('blocks a dev server started by a substitution in a here-document body', () => { + for (const command of ["npm --version < { diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 6c99a00ba..ca330134a 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -143,6 +143,16 @@ test('a here-document delimiter is a shell word, read without its quotes', () => // An empty delimiter ends the body at the first empty line assert.deepStrictEqual(splitShellSegments("cat <<''\nnpm run dev\n\nls"), ["cat <<''", 'ls']); }); +test('an expanded here-document body exposes the commands its substitutions run', () => { + // Quotes are plain text in the body, so Bash still runs the substitution + assert.deepStrictEqual(splitShellSegments("npm --version < { assert.deepStrictEqual(splitShellSegments('cat < Date: Fri, 23 Oct 2026 03:49:21 +0200 Subject: [PATCH 06/16] fix(hooks): read an ANSI-C quoted here-document delimiter without its $ Bash reads <<$'EOF' as the delimiter EOF, but the splitter took the $ into the word and waited for a $EOF line, so the body ran on and swallowed the commands after it. A $ before a quote now only starts the quoting. --- scripts/lib/shell-split.js | 9 ++++++--- tests/hooks/pre-bash-dev-server-block.test.js | 5 +++++ tests/lib/shell-split.test.js | 1 + 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index 5d41907d0..0ea41ab3b 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -1,9 +1,9 @@ 'use strict'; // A here-document opener at `index`, but not a here-string (<<<): `<<` or `<<-`, then the -// delimiter, a shell word whose quotes are removed (`<<'EOF'`, `< { + const result = runScript("cat <<$'EOF'\ntext\nEOF\nnpm run dev"); + assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); + }) ? passed++ : failed++); + (test('blocks a dev server started by a substitution in a here-document body', () => { for (const command of ["npm --version < assert.deepStrictEqual(splitShellSegments('cat < Date: Fri, 23 Oct 2026 04:20:03 +0200 Subject: [PATCH 07/16] fix(hooks): decode the escapes of an ANSI-C quoted here-document delimiter Bash decodes $'...' quoting, so <<$'E\x4fF' ends at an EOF line. The splitter kept the escape, ended the body at a literal E\x4fF line, and exposed the rest of the body as commands. The delimiter word is now read by readWord(), which decodes $'...' as Bash does, \' included. --- scripts/lib/shell-split.js | 82 +++++++++++++------ tests/hooks/pre-bash-dev-server-block.test.js | 5 ++ tests/lib/shell-split.test.js | 3 + 3 files changed, 65 insertions(+), 25 deletions(-) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index 0ea41ab3b..b496cf5c9 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -1,5 +1,59 @@ 'use strict'; +// $'...' quoting, in which a backslash also escapes the closing quote +const ANSI_C_QUOTED_RE = /\$'((?:\\[\s\S]|[^'\\])*)'/y; +const ANSI_C_ESCAPES = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v' }; + +// The text of $'...' quoting with its escapes decoded, as Bash decodes them. +function decodeAnsiC(text) { + return text.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|c[\s\S]|[\s\S])/g, (escape, code) => { + if ('xuU'.includes(code[0]) && code.length > 1) { + const value = parseInt(code.slice(1), 16); + return value <= 0x10ffff ? String.fromCodePoint(value) : escape; + } + if (/^[0-7]/.test(code)) return String.fromCharCode(parseInt(code, 8) & 0xff); + if (code[0] === 'c' && code.length > 1) return String.fromCharCode(code.charCodeAt(1) & 0x1f); + return ANSI_C_ESCAPES[code] ?? (`\\'"?`.includes(code) ? code : escape); + }); +} + +// The shell word at `start`, up to an unquoted blank or operator character, with its quoting +// removed, and whether any part of it was quoted. Null if a quote does not close. +function readWord(command, start) { + let word = ''; + let quote = null; + let quoted = false; + let i = start; + for (; i < command.length; i++) { + const ch = command[i]; + ANSI_C_QUOTED_RE.lastIndex = i; + const ansiC = !quote && ch === '$' ? ANSI_C_QUOTED_RE.exec(command) : null; + if (quote) { + if (ch === quote) quote = null; + else word += ch; + } else if (ansiC) { + // $'...' decodes its escapes, so $'E\x4fF' is EOF + word += decodeAnsiC(ansiC[1]); + quoted = true; + i += ansiC[0].length - 1; + } else if (ch === "'" || ch === '"') { + quote = ch; + quoted = true; + } else if (ch === '$' && command[i + 1] === '"') { + // $"..." is double quoting; the $ is not part of the word + continue; + } else if (ch === '\\' && i + 1 < command.length) { + word += command[++i]; + quoted = true; + } else if (/[\s|&;()<>]/.test(ch)) { + break; + } else { + word += ch; + } + } + return quote ? null : { word, quoted, end: i }; +} + // A here-document opener at `index`, but not a here-string (<<<): `<<` or `<<-`, then the // delimiter, a shell word whose quotes are removed (`<<'EOF'`, `<]/.test(ch)) { - break; - } else { - delimiter += ch; - } - } - if ((!delimiter && !quoted) || quote) return null; - return { text: command.slice(index, i), delimiter, stripTabs, expands: !quoted }; + const word = readWord(command, i); + if (!word || (!word.word && !word.quoted)) return null; + return { text: command.slice(index, word.end), delimiter: word.word, stripTabs, expands: !word.quoted }; } // The index after the `)` that closes the `(` at `index`, or -1. Quoted parentheses and escaped diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 02ffaf9b5..d04fa8e48 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -246,6 +246,11 @@ function runTests() { assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); }) ? passed++ : failed++); + (test('allows a here-document body whose ANSI-C quoted delimiter has an escape', () => { + const result = runScript("cat <<$'E\\x4fF'\nE\\x4fF\nnpm run dev\nEOF"); + assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); + }) ? passed++ : failed++); + (test('allows a here-document body fed to a package manager command', () => { const result = runScript('npm --version < assert.deepStrictEqual(splitShellSegments('cat < Date: Fri, 23 Oct 2026 04:42:16 +0200 Subject: [PATCH 08/16] fix(hooks): decode ANSI-C byte escapes in a here-document delimiter as UTF-8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bash reads \xHH and \NNN in $'...' as bytes, so <<$'\xc3\xa9' ends at an é line. Each escape became its own character (é), which ended the body at the wrong line. The bytes of the delimiter are now collected and decoded as UTF-8. --- scripts/lib/shell-split.js | 32 +++++++++++++++++++++++--------- tests/lib/shell-split.test.js | 3 +++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index b496cf5c9..0addc1ec4 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -4,17 +4,31 @@ const ANSI_C_QUOTED_RE = /\$'((?:\\[\s\S]|[^'\\])*)'/y; const ANSI_C_ESCAPES = { a: '\x07', b: '\b', e: '\x1b', E: '\x1b', f: '\f', n: '\n', r: '\r', t: '\t', v: '\v' }; -// The text of $'...' quoting with its escapes decoded, as Bash decodes them. +// A byte escape (\xHH, \NNN), another escape, or a run of text in $'...' quoting +const ANSI_C_TOKEN_RE = /\\(x[0-9A-Fa-f]{1,2}|[0-7]{1,3})|\\(u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|c[\s\S]|[\s\S])|[^\\]+|\\/g; + +// The character that an ANSI-C escape other than a byte escape stands for, or the escape itself. +function ansiCEscape(code, escape) { + if ('uU'.includes(code[0]) && code.length > 1) { + const value = parseInt(code.slice(1), 16); + return value <= 0x10ffff ? String.fromCodePoint(value) : escape; + } + if (code[0] === 'c' && code.length > 1) return String.fromCharCode(code.charCodeAt(1) & 0x1f); + return ANSI_C_ESCAPES[code] ?? (`\\'"?`.includes(code) ? code : escape); +} + +// The text of $'...' quoting with its escapes decoded, as Bash decodes them. Hex and octal +// escapes are bytes, so $'\xc3\xa9' is the UTF-8 text é. function decodeAnsiC(text) { - return text.replace(/\\(x[0-9A-Fa-f]{1,2}|u[0-9A-Fa-f]{1,4}|U[0-9A-Fa-f]{1,8}|[0-7]{1,3}|c[\s\S]|[\s\S])/g, (escape, code) => { - if ('xuU'.includes(code[0]) && code.length > 1) { - const value = parseInt(code.slice(1), 16); - return value <= 0x10ffff ? String.fromCodePoint(value) : escape; + const bytes = []; + for (const [token, byte, code] of text.matchAll(ANSI_C_TOKEN_RE)) { + if (byte !== undefined) { + bytes.push(byte[0] === 'x' ? parseInt(byte.slice(1), 16) : parseInt(byte, 8) & 0xff); + } else { + bytes.push(...Buffer.from(code === undefined ? token : ansiCEscape(code, token), 'utf8')); } - if (/^[0-7]/.test(code)) return String.fromCharCode(parseInt(code, 8) & 0xff); - if (code[0] === 'c' && code.length > 1) return String.fromCharCode(code.charCodeAt(1) & 0x1f); - return ANSI_C_ESCAPES[code] ?? (`\\'"?`.includes(code) ? code : escape); - }); + } + return Buffer.from(bytes).toString('utf8'); } // The shell word at `start`, up to an unquoted blank or operator character, with its quoting diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index d95b5de6c..75d095cee 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -144,6 +144,9 @@ test('a here-document delimiter is a shell word, read without its quotes', () => // $'...' decodes its escapes: $'E\x4fF' is EOF, and $'it\'s' is it's assert.deepStrictEqual(splitShellSegments("cat <<$'E\\x4fF'\nE\\x4fF\nnpm run dev\nEOF\nls"), ["cat <<$'E\\x4fF'", 'ls']); assert.deepStrictEqual(splitShellSegments("cat <<$'it\\'s'\nnpm run dev\nit's\nls"), ["cat <<$'it\\'s'", 'ls']); + // Hex and octal escapes are bytes, so both of these are the UTF-8 delimiter é + assert.deepStrictEqual(splitShellSegments("cat <<$'\\xc3\\xa9'\n\u00c3\u00a9\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\xc3\\xa9'", 'ls']); + assert.deepStrictEqual(splitShellSegments("cat <<$'\\303\\251'\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\303\\251'", 'ls']); // An empty delimiter ends the body at the first empty line assert.deepStrictEqual(splitShellSegments("cat <<''\nnpm run dev\n\nls"), ["cat <<''", 'ls']); }); From 19db590a9992bf7218752c7e26372b00aabff086 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 23 Oct 2026 05:02:34 +0200 Subject: [PATCH 09/16] fix(hooks): compare ANSI-C delimiter bytes exactly and decode them without spreading Invalid UTF-8 in a $'...' delimiter became U+FFFD, which a body line could match although Bash compares raw bytes. Such a delimiter now matches no line, so its body runs to the end of the command, as in Bash. The bytes were also spread into one push() call, which threw for a delimiter of 200,000 characters. The hook then failed open. The bytes are now collected as buffers and concatenated once. --- scripts/lib/shell-split.js | 28 +++++++++++++++++++--------- tests/lib/shell-split.test.js | 5 +++++ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index 0addc1ec4..56c9a29e9 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -17,26 +17,34 @@ function ansiCEscape(code, escape) { return ANSI_C_ESCAPES[code] ?? (`\\'"?`.includes(code) ? code : escape); } -// The text of $'...' quoting with its escapes decoded, as Bash decodes them. Hex and octal -// escapes are bytes, so $'\xc3\xa9' is the UTF-8 text é. +const UTF8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }); + +// The text of $'...' quoting with its escapes decoded, as Bash decodes them, or null when the +// bytes are not UTF-8. Hex and octal escapes are bytes, so $'\xc3\xa9' is the UTF-8 text é. function decodeAnsiC(text) { - const bytes = []; + const chunks = []; for (const [token, byte, code] of text.matchAll(ANSI_C_TOKEN_RE)) { if (byte !== undefined) { - bytes.push(byte[0] === 'x' ? parseInt(byte.slice(1), 16) : parseInt(byte, 8) & 0xff); + chunks.push(Buffer.of(byte[0] === 'x' ? parseInt(byte.slice(1), 16) : parseInt(byte, 8) & 0xff)); } else { - bytes.push(...Buffer.from(code === undefined ? token : ansiCEscape(code, token), 'utf8')); + chunks.push(Buffer.from(code === undefined ? token : ansiCEscape(code, token), 'utf8')); } } - return Buffer.from(bytes).toString('utf8'); + try { + return UTF8.decode(Buffer.concat(chunks)); + } catch { + return null; + } } // The shell word at `start`, up to an unquoted blank or operator character, with its quoting -// removed, and whether any part of it was quoted. Null if a quote does not close. +// removed, and whether any part of it was quoted. Null if a quote does not close. The word is +// null when it holds bytes that are not UTF-8: no line of the command can then be equal to it. function readWord(command, start) { let word = ''; let quote = null; let quoted = false; + let utf8 = true; let i = start; for (; i < command.length; i++) { const ch = command[i]; @@ -47,7 +55,9 @@ function readWord(command, start) { else word += ch; } else if (ansiC) { // $'...' decodes its escapes, so $'E\x4fF' is EOF - word += decodeAnsiC(ansiC[1]); + const decoded = decodeAnsiC(ansiC[1]); + if (decoded === null) utf8 = false; + else word += decoded; quoted = true; i += ansiC[0].length - 1; } else if (ch === "'" || ch === '"') { @@ -65,7 +75,7 @@ function readWord(command, start) { word += ch; } } - return quote ? null : { word, quoted, end: i }; + return quote ? null : { word: utf8 ? word : null, quoted, end: i }; } // A here-document opener at `index`, but not a here-string (<<<): `<<` or `<<-`, then the diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 75d095cee..c20c1a21b 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -147,6 +147,11 @@ test('a here-document delimiter is a shell word, read without its quotes', () => // Hex and octal escapes are bytes, so both of these are the UTF-8 delimiter é assert.deepStrictEqual(splitShellSegments("cat <<$'\\xc3\\xa9'\n\u00c3\u00a9\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\xc3\\xa9'", 'ls']); assert.deepStrictEqual(splitShellSegments("cat <<$'\\303\\251'\nnpm run dev\n\u00e9\nls"), ["cat <<$'\\303\\251'", 'ls']); + // A delimiter whose bytes are not UTF-8 matches no line, so the body runs to the end + assert.deepStrictEqual(splitShellSegments("cat <<$'\\xff'\n\ufffd\nnpm run dev"), ["cat <<$'\\xff'"]); + // A long delimiter is read in one pass + const long = 'a'.repeat(200000); + assert.deepStrictEqual(splitShellSegments(`cat <<$'${long}'\ntext\n${long}\nnpm run dev`), [`cat <<$'${long}'`, 'npm run dev']); // An empty delimiter ends the body at the first empty line assert.deepStrictEqual(splitShellSegments("cat <<''\nnpm run dev\n\nls"), ["cat <<''", 'ls']); }); From 8435c911a5d435ff540436b2ef587c6d4634a957 Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 23 Oct 2026 11:51:22 +0200 Subject: [PATCH 10/16] fix(hooks): match here-document delimiters and comment starts the way bash reads them A carriage return is part of a bash word and line, so after an LF delimiter a line ending in \r no longer ends the body early and exposes the body as commands. In an expanded body, a line ending in an escaping backslash is joined with the next before it is compared, so `EO\` and `F` end an unquoted <]/.test(ch)) { + } else if (/[ \t\n|&;()<>]/.test(ch)) { break; } else { word += ch; @@ -146,6 +147,13 @@ function literalSpanEnd(command, index, atWordStart) { return command[index] === '(' && command[index + 1] === '(' ? endOfArithmetic(command, index) : -1; } +// Whether `text` ends in an odd number of backslashes, the last of which escapes what follows. +function endsInEscape(text) { + let count = 0; + while (count < text.length && text[text.length - 1 - count] === '\\') count++; + return count % 2 === 1; +} + // The here-document bodies that start at `start`, one after the other: the index after them, // and the commands that the expanded ones run through command substitution. function readHeredocBodies(command, start, heredocs) { @@ -155,12 +163,21 @@ function readHeredocBodies(command, start, heredocs) { const bodyStart = end; let bodyEnd = command.length; while (end < command.length) { - const newline = command.indexOf('\n', end); - const lineEnd = newline === -1 ? command.length : newline; - // A CRLF line ends in \r, which is not part of the delimiter. - const line = command.slice(end, lineEnd).replace(/\r$/, ''); const lineStart = end; - end = lineEnd + 1; + let line = ''; + for (;;) { + const newline = command.indexOf('\n', end); + const lineEnd = newline === -1 ? command.length : newline; + const part = command.slice(end, lineEnd); + end = lineEnd + 1; + // In an expanded body, Bash joins a line that ends in an escaping backslash with the + // next one before it compares the line with the delimiter. + if (!expands || newline === -1 || !endsInEscape(part)) { + line += part; + break; + } + line += part.slice(0, -1); + } if ((stripTabs ? line.replace(/^\t+/, '') : line) === delimiter) { bodyEnd = lineStart; break; @@ -193,6 +210,8 @@ function splitShellSegments(command) { let quote = null; // Here-documents opened on the current line, read after its newline. let heredocs = []; + // The index of the last character a backslash escaped outside quotes. + let escaped = -1; for (let i = 0; i < command.length; i++) { const ch = command[i]; @@ -213,6 +232,7 @@ function splitShellSegments(command) { if (ch === '\\' && i + 1 < command.length) { current += ch + command[i + 1]; i++; + escaped = i; continue; } @@ -226,7 +246,8 @@ function splitShellSegments(command) { const next = command[i + 1] || ''; const prev = i > 0 ? command[i - 1] : ''; - const spanEnd = literalSpanEnd(command, i, current === '' || /[\s;&|(]/.test(prev)); + const atWordStart = current === '' || (/[\s;&|(]/.test(prev) && escaped !== i - 1); + const spanEnd = literalSpanEnd(command, i, atWordStart); if (spanEnd !== -1) { current += command.slice(i, spanEnd); i = spanEnd - 1; diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index c20c1a21b..dc65d2fce 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -171,6 +171,18 @@ test('a here-document body after an operator is left out too', () => { }); test('a here-document delimiter on a CRLF line still ends the body', () => { assert.deepStrictEqual(splitShellSegments('cat < { + assert.deepStrictEqual(splitShellSegments('cat < { + assert.deepStrictEqual(splitShellSegments('echo foo\\ # && npm run dev'), ['echo foo\\ #', 'npm run dev']); + assert.deepStrictEqual(splitShellSegments('echo foo # && npm run dev'), ['echo foo # && npm run dev']); }); console.log(`\n=== Results: ${passed} passed, ${failed} failed ===`); From 159062e3397b48a090b72e972937ac0ae638342a Mon Sep 17 00:00:00 2001 From: L4XB Date: Fri, 23 Oct 2026 12:05:45 +0200 Subject: [PATCH 11/16] fix(hooks): look past a line continuation when deciding whether # starts a comment Bash removes a backslash-newline before it reads the line, so the character before the pair decides whether a following # starts a word. `echo \` then `# <= 0 && command[i] === '\\'; i--) count++; + return count % 2 === 1; +} + +// Whether the character at `index` starts a word: it is the first of the command, or it follows an +// unescaped blank or operator character. Bash removes a backslash-newline pair first, so the +// character before the pair is the one that counts. +function startsWord(command, index, current) { + if (current === '') return true; + let before = index - 1; + while (before >= 1 && command[before] === '\n' && command[before - 1] === '\\' && !isEscaped(command, before - 1)) { + before -= 2; + } + return before < 0 || (/[\s;&|(]/.test(command[before]) && !isEscaped(command, before)); +} + // The end of a span copied as is, or -1: a comment, which runs to the end of its line, or an // arithmetic expression such as $((x << n)), whose `<<` is a shift and `&&` an operator. function literalSpanEnd(command, index, atWordStart) { @@ -210,8 +229,6 @@ function splitShellSegments(command) { let quote = null; // Here-documents opened on the current line, read after its newline. let heredocs = []; - // The index of the last character a backslash escaped outside quotes. - let escaped = -1; for (let i = 0; i < command.length; i++) { const ch = command[i]; @@ -232,7 +249,6 @@ function splitShellSegments(command) { if (ch === '\\' && i + 1 < command.length) { current += ch + command[i + 1]; i++; - escaped = i; continue; } @@ -246,8 +262,7 @@ function splitShellSegments(command) { const next = command[i + 1] || ''; const prev = i > 0 ? command[i - 1] : ''; - const atWordStart = current === '' || (/[\s;&|(]/.test(prev) && escaped !== i - 1); - const spanEnd = literalSpanEnd(command, i, atWordStart); + const spanEnd = literalSpanEnd(command, i, ch === '#' && startsWord(command, i, current)); if (spanEnd !== -1) { current += command.slice(i, spanEnd); i = spanEnd - 1; diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index dc65d2fce..b92e8f5a6 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -183,6 +183,15 @@ test('an expanded here-document body joins a line that ends in an escaping backs test('a # after an escaped blank does not start a comment', () => { assert.deepStrictEqual(splitShellSegments('echo foo\\ # && npm run dev'), ['echo foo\\ #', 'npm run dev']); assert.deepStrictEqual(splitShellSegments('echo foo # && npm run dev'), ['echo foo # && npm run dev']); + // An escaped backslash leaves the blank after it unescaped + assert.deepStrictEqual(splitShellSegments('echo a\\\\ # && npm run dev'), ['echo a\\\\ # && npm run dev']); +}); +test('a # after a line continuation is read as bash reads the joined line', () => { + // Bash drops the backslash-newline, so the blank before it makes # start a comment + assert.deepStrictEqual(splitShellSegments('echo \\\n# < Date: Sun, 25 Oct 2026 19:04:25 -0400 Subject: [PATCH 12/16] fix(hooks): honor Bash quote boundaries in dev guard (cherry picked from commit f4bf43c550bd63b8619ef65d5392169f5c0d4a17) --- scripts/lib/shell-split.js | 29 ++++++++++++++----- tests/hooks/pre-bash-dev-server-block.test.js | 25 ++++++++++++++++ tests/lib/shell-split.test.js | 27 +++++++++++++++-- 3 files changed, 71 insertions(+), 10 deletions(-) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index d80aee116..8a26587c8 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -52,7 +52,10 @@ function readWord(command, start) { ANSI_C_QUOTED_RE.lastIndex = i; const ansiC = !quote && ch === '$' ? ANSI_C_QUOTED_RE.exec(command) : null; if (quote) { - if (ch === quote) quote = null; + if (quote === '"' && ch === '\\' && i + 1 < command.length && '$`"\\\n'.includes(command[i + 1])) { + const next = command[++i]; + if (next !== '\n') word += next; + } else if (ch === quote) quote = null; else word += ch; } else if (ansiC) { // $'...' decodes its escapes, so $'E\x4fF' is EOF @@ -68,8 +71,11 @@ function readWord(command, start) { // $"..." is double quoting; the $ is not part of the word continue; } else if (ch === '\\' && i + 1 < command.length) { - word += command[++i]; - quoted = true; + const next = command[++i]; + if (next !== '\n') { + word += next; + quoted = true; + } } else if (/[ \t\n|&;()<>]/.test(ch)) { break; } else { @@ -233,14 +239,17 @@ function splitShellSegments(command) { for (let i = 0; i < command.length; i++) { const ch = command[i]; - // Inside quotes: handle escapes and closing quote + // Ordinary single quotes are literal. ANSI-C $'...' quotes also allow + // backslash escapes, including an apostrophe that must not close them. + // Inside double quotes, a backslash escapes only $, `, ", \\ and newline. if (quote) { - if (ch === '\\' && i + 1 < command.length) { + if (ch === '\\' && i + 1 < command.length && + (quote === "$'" || (quote === '"' && '$`"\\\n'.includes(command[i + 1])))) { current += ch + command[i + 1]; i++; continue; } - if (ch === quote) quote = null; + if (ch === (quote === "$'" ? "'" : quote)) quote = null; current += ch; continue; } @@ -252,7 +261,13 @@ function splitShellSegments(command) { continue; } - // Opening quote + // Opening quote. Keep ANSI-C quoting distinct from literal single quotes. + if (ch === '$' && command[i + 1] === "'") { + quote = "$'"; + current += "$'"; + i++; + continue; + } if (ch === '"' || ch === "'") { quote = ch; current += ch; diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index d04fa8e48..19adefc71 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -49,6 +49,18 @@ function runTests() { assert.ok(result.stderr.includes('BLOCKED'), `Expected stderr to contain BLOCKED, got: ${result.stderr}`); }) ? passed++ : failed++); + (test('blocks dev launch after an ANSI-C escaped apostrophe', () => { + for (const command of ["export x=$'it\\'s here'; npm run dev", "export x=$'it\\'s here'\nnpm run dev"]) { + const result = runScript(command); + assert.strictEqual(result.code, 2, `Expected exit code 2 for ${command}, got ${result.code}`); + } + }) ? passed++ : failed++); + + (test('allows a dev command mentioned inside an ANSI-C quoted string', () => { + const result = runScript("echo $'x\\' && npm run dev'"); + assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); + }) ? passed++ : failed++); + (test('blocks pnpm dev (exit code 2)', () => { const result = runScript('pnpm dev'); assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); @@ -218,6 +230,13 @@ function runTests() { // --- Newlines --- if (!isWindows) { + (test('blocks a dev server after a single-quoted backslash and a separator', () => { + for (const command of ["echo 'x\\'; npm run dev", "echo 'x\\'\nnpm run dev"]) { + const result = runScript(command); + assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`); + } + }) ? passed++ : failed++); + (test('blocks a dev server started on a later line of a multi-line command', () => { const result = runScript('cd app\nnpm run dev'); assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); @@ -228,6 +247,12 @@ function runTests() { assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); }) ? passed++ : failed++); + (test('blocks a dev server after a here-document with an escaped quote in its delimiter', () => { + const command = 'cat < { for (const command of ["npm --version < { const segs = splitShellSegments('echo "hello \\"world\\"" && echo bye'); assert.strictEqual(segs.length, 2); }); -test('escaped single quote inside single quotes', () => { - const segs = splitShellSegments("echo 'hello \\'world\\'' && echo bye"); - assert.strictEqual(segs.length, 2); +test('a backslash inside single quotes cannot escape the closing quote', () => { + assert.deepStrictEqual(splitShellSegments("echo 'x\\'; npm run dev"), ["echo 'x\\'", 'npm run dev']); + assert.deepStrictEqual(splitShellSegments("echo 'x\\'\nnpm run dev"), ["echo 'x\\'", 'npm run dev']); +}); +test('ANSI-C quotes keep escaped apostrophes and shell operators as data', () => { + const actualLaunch = "export x=$'it\\'s here'; npm run dev"; + const literalInstruction = "echo $'x\\' && npm run dev'"; + assert.deepStrictEqual(splitShellSegments(actualLaunch), ["export x=$'it\\'s here'", 'npm run dev']); + assert.deepStrictEqual(splitShellSegments("export x=$'it\\'s here'\nnpm run dev"), ["export x=$'it\\'s here'", 'npm run dev']); + assert.deepStrictEqual(splitShellSegments(literalInstruction), [literalInstruction]); + if (process.platform !== 'win32') { + const syntax = spawnSync('/bin/bash', ['-n', '-c', actualLaunch], { encoding: 'utf8' }); + assert.strictEqual(syntax.status, 0, syntax.stderr); + const value = spawnSync('/bin/bash', ['-c', "export x=$'it\\'s here'; printf '%s' \"$x\""], { encoding: 'utf8' }); + assert.strictEqual(value.status, 0, value.stderr); + assert.strictEqual(value.stdout, "it's here"); + const text = spawnSync('/bin/bash', ['-c', literalInstruction], { encoding: 'utf8' }); + assert.strictEqual(text.status, 0, text.stderr); + assert.strictEqual(text.stdout, "x' && npm run dev\n"); + } }); // Escaped operators outside quotes @@ -144,6 +162,9 @@ test('a here-document delimiter is a shell word, read without its quotes', () => // $'...' decodes its escapes: $'E\x4fF' is EOF, and $'it\'s' is it's assert.deepStrictEqual(splitShellSegments("cat <<$'E\\x4fF'\nE\\x4fF\nnpm run dev\nEOF\nls"), ["cat <<$'E\\x4fF'", 'ls']); assert.deepStrictEqual(splitShellSegments("cat <<$'it\\'s'\nnpm run dev\nit's\nls"), ["cat <<$'it\\'s'", 'ls']); + // Bash keeps a double-quoted delimiter open across an escaped quote. + assert.deepStrictEqual(splitShellSegments('cat < Date: Thu, 5 Nov 2026 10:27:19 +0100 Subject: [PATCH 13/16] fix(hooks): read $$ as the process ID before looking for $'...' In `echo $$'\'; npm run dev`, Bash reads `$$` as the process-ID parameter and the quote after it as an ordinary single quote, so it runs `npm run dev`. The splitter took the second `$` as the start of ANSI-C quoting, which hid the semicolon, and a here-document delimiter such as `$$'EOF'` was read as `$EOF`, so the body never ended. Consume the `$$` pair first in both places. --- scripts/lib/shell-split.js | 13 ++++++++++++ tests/hooks/pre-bash-dev-server-block.test.js | 12 +++++++++++ tests/lib/shell-split.test.js | 20 +++++++++++++++++++ 3 files changed, 45 insertions(+) diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index 8a26587c8..c1c26c919 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -49,6 +49,12 @@ function readWord(command, start) { let i = start; for (; i < command.length; i++) { const ch = command[i]; + // $$ is the process-ID parameter, so a quote right after it is not $'...' + if (!quote && ch === '$' && command[i + 1] === '$') { + word += '$$'; + i++; + continue; + } ANSI_C_QUOTED_RE.lastIndex = i; const ansiC = !quote && ch === '$' ? ANSI_C_QUOTED_RE.exec(command) : null; if (quote) { @@ -261,6 +267,13 @@ function splitShellSegments(command) { continue; } + // $$ is the process-ID parameter, so a quote right after it is not $'...' + if (ch === '$' && command[i + 1] === '$') { + current += '$$'; + i++; + continue; + } + // Opening quote. Keep ANSI-C quoting distinct from literal single quotes. if (ch === '$' && command[i + 1] === "'") { quote = "$'"; diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 19adefc71..d6f97b132 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -56,6 +56,18 @@ function runTests() { } }) ? passed++ : failed++); + (test('blocks dev launch after a $$ that a quote follows', () => { + for (const command of ["echo $$'\\'; npm run dev", "cat <<$$'EOF'\nbody\n$$EOF\nnpm run dev"]) { + const result = runScript(command); + assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`); + } + }) ? passed++ : failed++); + + (test('allows a dev command quoted after a $$', () => { + const result = runScript("echo $$'; npm run dev'"); + assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); + }) ? passed++ : failed++); + (test('allows a dev command mentioned inside an ANSI-C quoted string', () => { const result = runScript("echo $'x\\' && npm run dev'"); assert.strictEqual(result.code, 0, `Expected exit code 0, got ${result.code}`); diff --git a/tests/lib/shell-split.test.js b/tests/lib/shell-split.test.js index 794a69a09..cee8b00e6 100644 --- a/tests/lib/shell-split.test.js +++ b/tests/lib/shell-split.test.js @@ -91,6 +91,26 @@ test('ANSI-C quotes keep escaped apostrophes and shell operators as data', () => assert.strictEqual(text.stdout, "x' && npm run dev\n"); } }); +test('$$ before a quote is the process ID, not the start of ANSI-C quoting', () => { + const launch = "echo $$'\\'; npm run dev"; + const heredoc = "cat <<$$'EOF'\nbody\n$$EOF\nnpm run dev"; + const literalInstruction = "echo $$'; npm run dev'"; + assert.deepStrictEqual(splitShellSegments(launch), ["echo $$'\\'", 'npm run dev']); + assert.deepStrictEqual(splitShellSegments(heredoc), ["cat <<$$'EOF'", 'npm run dev']); + assert.deepStrictEqual(splitShellSegments(literalInstruction), [literalInstruction]); + if (process.platform !== 'win32') { + const run = command => spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' }); + const ran = run(launch); + assert.strictEqual(ran.status, 0, ran.stderr); + assert.ok(ran.stdout.endsWith('\\\nran\n'), ran.stdout); + const body = run(heredoc); + assert.strictEqual(body.status, 0, body.stderr); + assert.strictEqual(body.stdout, 'body\nran\n'); + const text = spawnSync('/bin/bash', ['-c', literalInstruction], { encoding: 'utf8' }); + assert.strictEqual(text.status, 0, text.stderr); + assert.ok(text.stdout.endsWith('; npm run dev\n'), text.stdout); + } +}); // Escaped operators outside quotes console.log('\nEscaped operators outside quotes:'); From 94d2c659ba1dfe86d63c29a15062a46e1975cdb7 Mon Sep 17 00:00:00 2001 From: haelyra <49814733+haelyra@users.noreply.github.com> Date: Thu, 5 Nov 2026 11:05:56 +0100 Subject: [PATCH 14/16] fix(hooks): scan substitutions nested in expanded here-document bodies The dev-guard half of 7632669d from #3735: segments that the splitter reads from an expanded here-document body are scanned again, so a dev command in a substitution nested inside one is still found. (split from commit 7632669d287118f412298d0c2b600723d114e084) --- scripts/hooks/pre-bash-dev-server-block.js | 15 +++++++-------- tests/hooks/pre-bash-dev-server-block.test.js | 12 ++++++++++++ 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/scripts/hooks/pre-bash-dev-server-block.js b/scripts/hooks/pre-bash-dev-server-block.js index c5c336e68..a92036204 100755 --- a/scripts/hooks/pre-bash-dev-server-block.js +++ b/scripts/hooks/pre-bash-dev-server-block.js @@ -192,7 +192,9 @@ const DEV_PATTERN = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+ */ function collectCheckSegments(cmd) { const segments = [...splitShellSegments(cmd)]; - const queue = [cmd]; + // Expanded here-document bodies enter through splitShellSegments, so their + // segments must also be scanned for substitutions nested inside them. + const queue = [cmd, ...segments]; const seen = new Set(); while (queue.length) { @@ -200,13 +202,10 @@ function collectCheckSegments(cmd) { if (seen.has(current)) continue; seen.add(current); - for (const body of extractCommandSubstitutions(current)) { - for (const seg of splitShellSegments(body)) segments.push(seg); - queue.push(body); - } - for (const body of extractSubshellGroups(current)) { - for (const seg of splitShellSegments(body)) segments.push(seg); - queue.push(body); + for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) { + const bodySegments = splitShellSegments(body); + segments.push(...bodySegments); + queue.push(body, ...bodySegments); } } diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index ce0f02dfe..48f723dc2 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -323,6 +323,18 @@ function runTests() { assert.strictEqual(result.code, 2, `Expected exit code 2 for ${JSON.stringify(command)}, got ${result.code}`); } }) ? passed++ : failed++); + + (test('blocks nested dev commands in expanded here-document substitutions', () => { + for (const command of [ + 'cat < { From 30eb570117aaf5fa1f550e4f71c6b9fd3fcd79f7 Mon Sep 17 00:00:00 2001 From: L4XB Date: Thu, 5 Nov 2026 13:07:21 +0100 Subject: [PATCH 15/16] fix(hooks): read NUL-ended delimiters, Bash blanks before #, and long bodies Bash ends a decoded $'...' string at its first NUL, so `cat <<$'EOF\0X'` ends at the line EOF, but the splitter looked for EOF\0X and swallowed the commands after the body. A carriage return or a no-break space is not a blank to Bash, so `echo foo\r# && npm run dev` runs the dev server, but the splitter read the # as a comment. And spreading a long substitution's segments into push() threw RangeError, which the hook's catch turned into an allow. Truncate the decoded part at the NUL, use Bash's blanks for word starts, and append the segments one at a time. --- scripts/hooks/pre-bash-dev-server-block.js | 8 ++++++-- scripts/lib/shell-split.js | 6 ++++-- tests/hooks/pre-bash-dev-server-block.test.js | 6 ++++++ tests/lib/shell-split.test.js | 19 +++++++++++++++++++ 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/scripts/hooks/pre-bash-dev-server-block.js b/scripts/hooks/pre-bash-dev-server-block.js index a92036204..a1a868cb0 100755 --- a/scripts/hooks/pre-bash-dev-server-block.js +++ b/scripts/hooks/pre-bash-dev-server-block.js @@ -204,8 +204,12 @@ function collectCheckSegments(cmd) { for (const body of [...extractCommandSubstitutions(current), ...extractSubshellGroups(current)]) { const bodySegments = splitShellSegments(body); - segments.push(...bodySegments); - queue.push(body, ...bodySegments); + // One at a time: spreading a long command's segments into push() exceeds the argument limit. + queue.push(body); + for (const segment of bodySegments) { + segments.push(segment); + queue.push(segment); + } } } diff --git a/scripts/lib/shell-split.js b/scripts/lib/shell-split.js index c1c26c919..d25684d99 100644 --- a/scripts/lib/shell-split.js +++ b/scripts/lib/shell-split.js @@ -67,7 +67,8 @@ function readWord(command, start) { // $'...' decodes its escapes, so $'E\x4fF' is EOF const decoded = decodeAnsiC(ansiC[1]); if (decoded === null) utf8 = false; - else word += decoded; + // Bash ends the decoded string at a NUL, so $'EOF\0X' is EOF + else word += decoded.split('\0', 1)[0]; quoted = true; i += ansiC[0].length - 1; } else if (ch === "'" || ch === '"') { @@ -165,7 +166,8 @@ function startsWord(command, index, current) { while (before >= 1 && command[before] === '\n' && command[before - 1] === '\\' && !isEscaped(command, before - 1)) { before -= 2; } - return before < 0 || (/[\s;&|(]/.test(command[before]) && !isEscaped(command, before)); + // Bash's blanks are a space and a tab; a carriage return or a no-break space is part of a word. + return before < 0 || (/[ \t\n;&|(]/.test(command[before]) && !isEscaped(command, before)); } // The end of a span copied as is, or -1: a comment, which runs to the end of its line, or an diff --git a/tests/hooks/pre-bash-dev-server-block.test.js b/tests/hooks/pre-bash-dev-server-block.test.js index 48f723dc2..aaccc316f 100644 --- a/tests/hooks/pre-bash-dev-server-block.test.js +++ b/tests/hooks/pre-bash-dev-server-block.test.js @@ -324,6 +324,12 @@ function runTests() { } }) ? passed++ : failed++); + (test('blocks a dev command in a substitution with a very long body', () => { + const command = `echo "$(npm run dev; ${'true; '.repeat(150000)})"`; + const result = runScript(command); + assert.strictEqual(result.code, 2, `Expected exit code 2, got ${result.code}`); + }) ? passed++ : failed++); + (test('blocks nested dev commands in expanded here-document substitutions', () => { for (const command of [ 'cat < { + const command = "cat <<$'EOF\\0X'\nbody\nEOF\nnpm run dev"; + assert.deepStrictEqual(splitShellSegments(command), ["cat <<$'EOF\\0X'", 'npm run dev']); + if (process.platform !== 'win32') { + const ran = spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' }); + assert.strictEqual(ran.stdout, 'body\nran\n', ran.stderr); + } +}); +test('a # after a carriage return or a no-break space is part of the word', () => { + for (const blankLike of ['\r', ' ']) { + const command = `echo foo${blankLike}# && npm run dev`; + assert.deepStrictEqual(splitShellSegments(command), [`echo foo${blankLike}#`, 'npm run dev']); + if (process.platform !== 'win32') { + const ran = spawnSync('/bin/bash', ['-c', command.replace('npm run dev', "printf 'ran\\n'")], { encoding: 'utf8' }); + assert.ok(ran.stdout.endsWith('ran\n'), JSON.stringify(ran.stdout)); + } + } +}); + // Escaped operators outside quotes console.log('\nEscaped operators outside quotes:'); test('escaped && outside quotes not split', () => { From 34e41430b1b6ae3d6c9f81f3edd9cb3bac8b3f5c Mon Sep 17 00:00:00 2001 From: L4XB Date: Thu, 5 Nov 2026 13:14:48 +0100 Subject: [PATCH 16/16] perf(hooks): read the dev guard's segment queue by index Since expanded here-document segments are queued too, a long substitution puts every segment in the queue, and shift() copied it each time: 130,000 segments took about 20 s, past the hook timeout. An index keeps the walk linear (under 0.3 s). --- scripts/hooks/pre-bash-dev-server-block.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/hooks/pre-bash-dev-server-block.js b/scripts/hooks/pre-bash-dev-server-block.js index a1a868cb0..f326f160c 100755 --- a/scripts/hooks/pre-bash-dev-server-block.js +++ b/scripts/hooks/pre-bash-dev-server-block.js @@ -197,8 +197,9 @@ function collectCheckSegments(cmd) { const queue = [cmd, ...segments]; const seen = new Set(); - while (queue.length) { - const current = queue.shift(); + // Read by index: shift() copies the queue each time, which is quadratic on a long command. + for (let head = 0; head < queue.length; head++) { + const current = queue[head]; if (seen.has(current)) continue; seen.add(current);