From da934cdfb7d5679dd552a4abe98dd2817ddf9f8e Mon Sep 17 00:00:00 2001 From: Roland Foerther Date: Sat, 29 Aug 2026 21:35:10 +0200 Subject: [PATCH] Fix all open CodeQL code scanning alerts index.mjs is the package main entry and exports the Support class (also declared in index.d.ts), so cli.mjs's argument validation is bypassed entirely by any library consumer. That is what made the four security alerts real rather than theoretical. Shell command injection (alerts #5, #6, index.mjs:120) killProcess interpolated the pid directly into a shell command string. Pass arguments as an array via execFile so no shell interprets them, and reject anything that is not a positive integer. The pid check also closes an unreported hazard: killProcess(-1, _, true) would have run `kill -9 -1`, signalling every process owned by the user. Regular expression injection (alerts #3, #4, index.mjs:59, index.mjs:81) The port was interpolated into new RegExp(). Escape it first. This was not only a ReDoS concern: passing `.*` previously matched an arbitrary listening process, so the wrong process could be selected and killed. Identity replacement (alert #7, scripts/create-local-bin.mjs:27) replace(/\\/g, '\\') replaced a backslash with itself and did nothing. Neither batch nor PowerShell treats a backslash as an escape character, so drop the escaping in both templates. On Windows path values the .ps1 output is byte-identical, confirming the call was dead code, while the .cmd output loses the stray doubled separators produced by the other replace. Missing workflow permissions (alerts #1, #2) Add an explicit read-only GITHUB_TOKEN scope to the build job and to test.yml. The publish-gpr and npmjs workflows already had one. Co-Authored-By: Claude Opus 5 --- .../workflows/npm-publish-github-packages.yml | 2 ++ .github/workflows/test.yml | 3 ++ index.mjs | 28 ++++++++++++++++--- scripts/create-local-bin.mjs | 4 +-- 4 files changed, 31 insertions(+), 6 deletions(-) diff --git a/.github/workflows/npm-publish-github-packages.yml b/.github/workflows/npm-publish-github-packages.yml index 9236bf4..5b5fb6a 100644 --- a/.github/workflows/npm-publish-github-packages.yml +++ b/.github/workflows/npm-publish-github-packages.yml @@ -11,6 +11,8 @@ on: jobs: build: runs-on: ubuntu-latest + permissions: + contents: read steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index df2b833..6411c76 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -6,6 +6,9 @@ on: pull_request: branches: [ main, master ] +permissions: + contents: read + jobs: test: runs-on: ${{ matrix.os }} diff --git a/index.mjs b/index.mjs index dea9137..4b735e0 100644 --- a/index.mjs +++ b/index.mjs @@ -7,11 +7,23 @@ import util from 'node:util' import childProcess from 'node:child_process' const execAsync = util.promisify(childProcess.exec) +const execFileAsync = util.promisify(childProcess.execFile) const isWindows = os.platform() === 'win32' // Cached regular expressions for performance const WHITESPACE_REGEX = /\s+/ +const REGEXP_METACHARACTERS = /[.*+?^${}()|[\]\\]/g + +/** + * Escapes regular expression metacharacters so that a value can be embedded + * safely into a dynamically built regular expression. + * @param {*} value - The value to escape + * @returns {string} The value as a string with all metacharacters escaped + */ +function escapeRegExp(value) { + return String(value).replace(REGEXP_METACHARACTERS, '\\$&') +} /** * Terminates a process listening on a specific TCP port or its parent process including children. @@ -56,7 +68,7 @@ export class Support { if (!stdout) throw new Error(`No process running on port ${port}`) const lines = stdout.split('\n') - const portRegex = new RegExp(`TCP.*:.*${port}.*(LISTEN)`) + const portRegex = new RegExp(`TCP.*:.*${escapeRegExp(port)}.*(LISTEN)`) const foundProcess = lines.filter((line) => line.match(portRegex)) if (foundProcess.length === 0) throw new Error(`No process running on port ${port}`) if (foundProcess.length > 1) throw new Error('More than one process found') @@ -78,7 +90,7 @@ export class Support { // Use /\r?\n/ to handle Windows CRLF and Unix LF line endings const lines = stdout.split(/\r?\n/) // Match port exactly using \s after port number to avoid partial matches (e.g. port 80 matching 8080) - const lineWithLocalPortRegEx = new RegExp(`^ *TCP\\s+[^ ]*:${port}\\s`, 'i') + const lineWithLocalPortRegEx = new RegExp(`^ *TCP\\s+[^ ]*:${escapeRegExp(port)}\\s`, 'i') const linesWithLocalPort = lines.filter(line => lineWithLocalPortRegEx.test(line)) const pids = linesWithLocalPort.reduce((acc, line) => { @@ -113,11 +125,19 @@ export class Support { * @param {boolean} verbose - Enable verbose output (not used internally) * @param {boolean} force - Force kill using SIGKILL on Unix (kill -9), always forced on Windows * @returns {Promise} True if successful - * @throws {Error} When the kill command fails + * @throws {Error} When the process ID is not a positive integer or the kill command fails */ async killProcess(pid, verbose, force) { + // Reject anything that is not a plain positive integer. Besides guarding against + // injection, this stops targets like -1, which would signal every process of the user. + const processId = Number(pid) + if (!Number.isInteger(processId) || processId <= 0) throw new Error(`Invalid process id: ${pid}`) + try { - isWindows ? await execAsync(`TaskKill /F /PID ${pid}`) : await execAsync(`kill${force ? ' -9' : ''} ${pid}`) + // Arguments are passed as an array so that no shell interprets them + isWindows + ? await execFileAsync('TaskKill', ['/F', '/PID', String(processId)]) + : await execFileAsync('kill', force ? ['-9', String(processId)] : [String(processId)]) return true; } catch (e) { throw new Error("Kill command failed: " + e.stderr) diff --git a/scripts/create-local-bin.mjs b/scripts/create-local-bin.mjs index 76c3e2f..a20fda4 100644 --- a/scripts/create-local-bin.mjs +++ b/scripts/create-local-bin.mjs @@ -20,11 +20,11 @@ await chmod(path.join(binDir, 'killp'), 0o755) if (process.platform === 'win32') { const cmdScript = `@ECHO off -node "%~dp0\\${cliRelativePath.replace(/\\/g, '\\\\')}" %* +node "%~dp0\\${cliRelativePath}" %* ` const ps1Script = `#!/usr/bin/env pwsh $basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent -node "$basedir\\${cliRelativePath.replace(/\\/g, '\\')}" $args +node "$basedir\\${cliRelativePath}" $args ` await writeFile(path.join(binDir, 'killp.cmd'), cmdScript)