Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(hooks): apply the Windows argv fix from #3322 to the other three shim copies (#3332)

Dragan Spiridonovc77d1b506261
diff --git a/.claude-plugin/scripts/ruflo-hook.cjs b/.claude-plugin/scripts/ruflo-hook.cjs
index 5b94703c2c..ad83151b68 100644
--- a/.claude-plugin/scripts/ruflo-hook.cjs
+++ b/.claude-plugin/scripts/ruflo-hook.cjs
@@ -24,7 +24,7 @@
'use strict';
-const { spawnSync, execSync } = require('child_process');
+const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
@@ -73,17 +73,129 @@ function readStdinSync() {
}
}
-/** Check if a binary is available on PATH */
-function commandExists(cmd) {
+/** Case-insensitive env lookup — Windows env keys are not case-stable. */
+function envValue(env, name) {
+ const key = Object.keys(env).find((c) => c.toLowerCase() === name.toLowerCase());
+ return key ? env[key] : undefined;
+}
+
+/**
+ * Locate a command on PATH using fs only.
+ *
+ * Deliberately NOT `execSync('where ...')` / `command -v`: that spawns a
+ * shell on every hook invocation, which is both the thing this file is
+ * trying to get away from and a per-turn cost. Taking `env` and `platform`
+ * as arguments is what lets the Windows branch be exercised from a
+ * Linux/macOS CI run — see the Windows argv tests.
+ */
+function resolveCommandPath(command, env = process.env, platform = process.platform) {
+ const hasSeparator = command.includes('/') || command.includes('\\');
+ const dirs = hasSeparator
+ ? ['']
+ : (envValue(env, 'PATH') || '').split(platform === 'win32' ? ';' : path.delimiter);
+ const hasExtension = path.extname(command) !== '';
+ const extensions = platform === 'win32' && !(hasSeparator && hasExtension)
+ ? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
+ : [''];
+ for (const dir of dirs) {
+ for (const ext of extensions) {
+ const base = path.resolve(dir || '.', command);
+ const candidates = ext
+ ? [base + ext.toLowerCase(), base + ext.toUpperCase()]
+ : [base];
+ for (const file of candidates) {
+ try {
+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
+ if (fs.statSync(file).isFile()) return file;
+ } catch { /* keep searching */ }
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Map an npm-generated Windows shim (ruflo.cmd / npx.cmd / …) to the .js
+ * entrypoint it would have run, so it can be executed as `node <entry>`
+ * with no shell.
+ *
+ * Handles both npm layouts: a global prefix (`<prefix>/ruflo.cmd` beside
+ * `<prefix>/node_modules/ruflo`) and a local one (`node_modules/.bin/ruflo.cmd`
+ * beside `node_modules/ruflo`). `npx` lives in the `npm` package, hence the
+ * command→package mapping rather than assuming they match.
+ *
+ * The entrypoint comes from the package's own `bin` field, never a guessed
+ * filename, and is required to resolve inside the package directory — a
+ * manifest pointing outside it is refused rather than followed.
+ */
+function resolveNpmShim(shimPath) {
+ const command = path.basename(shimPath, path.extname(shimPath)).toLowerCase();
+ const packageName = command === 'npx' ? 'npm' : command;
+ if (!['ruflo', 'claude-flow', 'npm'].includes(packageName)) return null;
try {
- const result = execSync(
- process.platform === 'win32' ? `where ${cmd}` : `command -v ${cmd}`,
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
- );
- return result.trim().length > 0;
- } catch {
- return false;
+ const shimDir = path.dirname(shimPath);
+ const packageDir = path.basename(shimDir).toLowerCase() === '.bin'
+ ? path.resolve(shimDir, '..', packageName)
+ : path.resolve(shimDir, 'node_modules', packageName);
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
+ const declared = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[command];
+ if (typeof declared !== 'string') return null;
+ const canonicalPackageDir = fs.realpathSync(packageDir);
+ const canonicalEntry = fs.realpathSync(path.resolve(packageDir, declared));
+ const relativeEntry = path.relative(canonicalPackageDir, canonicalEntry);
+ if (relativeEntry.startsWith('..' + path.sep) || path.isAbsolute(relativeEntry)) return null;
+ if (!fs.statSync(canonicalEntry).isFile()) return null;
+ return { command: process.execPath, args: [canonicalEntry] };
+ } catch { return null; }
+}
+
+/**
+ * Decide how to run `bin` without a shell. Returns {command, args}, or null
+ * when no shell-free invocation could be identified (Windows shim that is
+ * not an npm package entry) — the caller then falls back to the escaped
+ * cmd.exe path rather than dropping the hook.
+ */
+function resolveInvocation(bin, binArgs, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const commandPath = resolveCommandPath(bin, env, platform);
+ if (!commandPath) return null;
+ if (platform === 'win32' && /\.(?:cmd|bat|ps1)$/i.test(commandPath)) {
+ const npmBin = resolveNpmShim(commandPath);
+ return npmBin ? { command: npmBin.command, args: [...npmBin.args, ...binArgs] } : null;
}
+ return { command: commandPath, args: binArgs };
+}
+
+/**
+ * Escape one argv element so it survives BOTH parsers a Windows shell:true
+ * spawn puts it through before the target CLI ever sees it:
+ * 1. cmd.exe's own line tokenizer, which still scans for & | < > ^ % ! " ( )
+ * even inside a per-argument quoted segment — quoting alone does not
+ * shield cmd.exe metacharacters, and this runs a SECOND time when the
+ * resolved binary is itself a .cmd shim (npm's `ruflo`/`claude-flow`/
+ * `npx` global installs on Windows), because launching a .cmd file is
+ * cmd.exe re-invoking itself on the command line.
+ * 2. The eventual CommandLineToArgvW argv parse in the target process,
+ * which needs backslash-before-quote sequences doubled and the value
+ * quoted so it lands as ONE argument.
+ * Without this, a hook-derived value (e.g. a Bash tool's `command`, or a
+ * file path) containing a shell metacharacter can be reinterpreted as a
+ * separate command / redirection instead of reaching the CLI as literal
+ * data — this is the class of bug in CVE-2024-27980 (Node's own .bat/.cmd
+ * argument-injection advisory). Algorithm: https://qntm.org/cmd, the same
+ * reference the `cross-spawn` package's Windows escaping is built from.
+ *
+ * Byte-identical to plugins/ruflo-core/scripts/ruflo-hook.cjs so the four
+ * copies can be diffed against each other. This is the fallback, not the
+ * primary defence: resolveInvocation() above is preferred because it removes
+ * cmd.exe from the chain entirely rather than out-guessing its tokenizer.
+ */
+function escapeCmdArg(arg) {
+ let s = String(arg);
+ s = s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1');
+ s = `"${s}"`;
+ return s.replace(/[()%!^"<>&|;,]/g, '^$&');
}
/** Build the argv for the ruflo/claude-flow/npx invocation */
@@ -99,20 +211,40 @@ function buildArgs(subcommand, extraArgs) {
*
* Returns true on success (exit 0), false otherwise.
*/
-function invokeHook(bin, binArgs, hookArgs, stdinData) {
- const args = [...binArgs, ...hookArgs];
-
- // On Windows, shell: true is needed to resolve .cmd shims in node_modules
- const useShell = process.platform === 'win32';
-
- const result = spawnSync(bin, args, {
- shell: useShell,
+function invokeHook(bin, binArgs, hookArgs, stdinData, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const spawnOpts = {
input: stdinData || '',
encoding: 'utf8',
- stdio: ['pipe', 'ignore', 'ignore'], // swallow all output
+ stdio: ['pipe', 'ignore', 'ignore'],
timeout: 30_000,
- });
+ env,
+ };
+ // Layer 1: no shell. CreateProcess/execve receives the argv array
+ // verbatim, so nothing in it can be reinterpreted as syntax.
+ const invocation = resolveInvocation(bin, binArgs, { env, platform });
+ if (invocation) {
+ const result = spawnSync(invocation.command, [...invocation.args, ...hookArgs], {
+ ...spawnOpts,
+ shell: false,
+ });
+ return result.status === 0;
+ }
+
+ // Layer 2: Windows shim we could not map to an entrypoint. cmd.exe is
+ // unavoidable here (CreateProcess cannot launch a .cmd, and Node has
+ // refused to since CVE-2024-27980), so every element is escaped. Losing
+ // the hook entirely would be the wrong trade — telemetry is best-effort,
+ // but silently doing nothing hides breakage.
+ const useShell = platform === 'win32';
+ const args = [...binArgs, ...hookArgs];
+ const result = spawnSync(
+ useShell ? escapeCmdArg(bin) : bin,
+ useShell ? args.map(escapeCmdArg) : args,
+ { ...spawnOpts, shell: useShell },
+ );
return result.status === 0;
}
@@ -137,13 +269,13 @@ function main() {
const hookArgs = buildArgs(subcommand, rest);
// Priority 1: locally installed ruflo binary
- if (commandExists('ruflo')) {
+ if (resolveCommandPath('ruflo')) {
invokeHook('ruflo', [], hookArgs, stdinData);
done();
}
// Priority 2: locally installed claude-flow binary
- if (commandExists('claude-flow')) {
+ if (resolveCommandPath('claude-flow')) {
invokeHook('claude-flow', [], hookArgs, stdinData);
done();
}
@@ -163,4 +295,10 @@ function main() {
done();
}
-main();
+// Test seam: the Windows argv suite require()s this file to drive resolveInvocation()
+// and invokeHook() with a simulated { platform: 'win32', env } — which is how
+// the Windows branch is proved from a Linux/macOS CI run. hooks.json always
+// invokes this file directly, so main() runs unconditionally otherwise.
+if (!globalThis.__RUFLO_HOOK_IMPORT_ONLY__) main();
+
+module.exports = { invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
diff --git a/plugin/scripts/ruflo-hook.cjs b/plugin/scripts/ruflo-hook.cjs
index 5b94703c2c..ad83151b68 100644
--- a/plugin/scripts/ruflo-hook.cjs
+++ b/plugin/scripts/ruflo-hook.cjs
@@ -24,7 +24,7 @@
'use strict';
-const { spawnSync, execSync } = require('child_process');
+const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
@@ -73,17 +73,129 @@ function readStdinSync() {
}
}
-/** Check if a binary is available on PATH */
-function commandExists(cmd) {
+/** Case-insensitive env lookup — Windows env keys are not case-stable. */
+function envValue(env, name) {
+ const key = Object.keys(env).find((c) => c.toLowerCase() === name.toLowerCase());
+ return key ? env[key] : undefined;
+}
+
+/**
+ * Locate a command on PATH using fs only.
+ *
+ * Deliberately NOT `execSync('where ...')` / `command -v`: that spawns a
+ * shell on every hook invocation, which is both the thing this file is
+ * trying to get away from and a per-turn cost. Taking `env` and `platform`
+ * as arguments is what lets the Windows branch be exercised from a
+ * Linux/macOS CI run — see the Windows argv tests.
+ */
+function resolveCommandPath(command, env = process.env, platform = process.platform) {
+ const hasSeparator = command.includes('/') || command.includes('\\');
+ const dirs = hasSeparator
+ ? ['']
+ : (envValue(env, 'PATH') || '').split(platform === 'win32' ? ';' : path.delimiter);
+ const hasExtension = path.extname(command) !== '';
+ const extensions = platform === 'win32' && !(hasSeparator && hasExtension)
+ ? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
+ : [''];
+ for (const dir of dirs) {
+ for (const ext of extensions) {
+ const base = path.resolve(dir || '.', command);
+ const candidates = ext
+ ? [base + ext.toLowerCase(), base + ext.toUpperCase()]
+ : [base];
+ for (const file of candidates) {
+ try {
+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
+ if (fs.statSync(file).isFile()) return file;
+ } catch { /* keep searching */ }
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Map an npm-generated Windows shim (ruflo.cmd / npx.cmd / …) to the .js
+ * entrypoint it would have run, so it can be executed as `node <entry>`
+ * with no shell.
+ *
+ * Handles both npm layouts: a global prefix (`<prefix>/ruflo.cmd` beside
+ * `<prefix>/node_modules/ruflo`) and a local one (`node_modules/.bin/ruflo.cmd`
+ * beside `node_modules/ruflo`). `npx` lives in the `npm` package, hence the
+ * command→package mapping rather than assuming they match.
+ *
+ * The entrypoint comes from the package's own `bin` field, never a guessed
+ * filename, and is required to resolve inside the package directory — a
+ * manifest pointing outside it is refused rather than followed.
+ */
+function resolveNpmShim(shimPath) {
+ const command = path.basename(shimPath, path.extname(shimPath)).toLowerCase();
+ const packageName = command === 'npx' ? 'npm' : command;
+ if (!['ruflo', 'claude-flow', 'npm'].includes(packageName)) return null;
try {
- const result = execSync(
- process.platform === 'win32' ? `where ${cmd}` : `command -v ${cmd}`,
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
- );
- return result.trim().length > 0;
- } catch {
- return false;
+ const shimDir = path.dirname(shimPath);
+ const packageDir = path.basename(shimDir).toLowerCase() === '.bin'
+ ? path.resolve(shimDir, '..', packageName)
+ : path.resolve(shimDir, 'node_modules', packageName);
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
+ const declared = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[command];
+ if (typeof declared !== 'string') return null;
+ const canonicalPackageDir = fs.realpathSync(packageDir);
+ const canonicalEntry = fs.realpathSync(path.resolve(packageDir, declared));
+ const relativeEntry = path.relative(canonicalPackageDir, canonicalEntry);
+ if (relativeEntry.startsWith('..' + path.sep) || path.isAbsolute(relativeEntry)) return null;
+ if (!fs.statSync(canonicalEntry).isFile()) return null;
+ return { command: process.execPath, args: [canonicalEntry] };
+ } catch { return null; }
+}
+
+/**
+ * Decide how to run `bin` without a shell. Returns {command, args}, or null
+ * when no shell-free invocation could be identified (Windows shim that is
+ * not an npm package entry) — the caller then falls back to the escaped
+ * cmd.exe path rather than dropping the hook.
+ */
+function resolveInvocation(bin, binArgs, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const commandPath = resolveCommandPath(bin, env, platform);
+ if (!commandPath) return null;
+ if (platform === 'win32' && /\.(?:cmd|bat|ps1)$/i.test(commandPath)) {
+ const npmBin = resolveNpmShim(commandPath);
+ return npmBin ? { command: npmBin.command, args: [...npmBin.args, ...binArgs] } : null;
}
+ return { command: commandPath, args: binArgs };
+}
+
+/**
+ * Escape one argv element so it survives BOTH parsers a Windows shell:true
+ * spawn puts it through before the target CLI ever sees it:
+ * 1. cmd.exe's own line tokenizer, which still scans for & | < > ^ % ! " ( )
+ * even inside a per-argument quoted segment — quoting alone does not
+ * shield cmd.exe metacharacters, and this runs a SECOND time when the
+ * resolved binary is itself a .cmd shim (npm's `ruflo`/`claude-flow`/
+ * `npx` global installs on Windows), because launching a .cmd file is
+ * cmd.exe re-invoking itself on the command line.
+ * 2. The eventual CommandLineToArgvW argv parse in the target process,
+ * which needs backslash-before-quote sequences doubled and the value
+ * quoted so it lands as ONE argument.
+ * Without this, a hook-derived value (e.g. a Bash tool's `command`, or a
+ * file path) containing a shell metacharacter can be reinterpreted as a
+ * separate command / redirection instead of reaching the CLI as literal
+ * data — this is the class of bug in CVE-2024-27980 (Node's own .bat/.cmd
+ * argument-injection advisory). Algorithm: https://qntm.org/cmd, the same
+ * reference the `cross-spawn` package's Windows escaping is built from.
+ *
+ * Byte-identical to plugins/ruflo-core/scripts/ruflo-hook.cjs so the four
+ * copies can be diffed against each other. This is the fallback, not the
+ * primary defence: resolveInvocation() above is preferred because it removes
+ * cmd.exe from the chain entirely rather than out-guessing its tokenizer.
+ */
+function escapeCmdArg(arg) {
+ let s = String(arg);
+ s = s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, '$1$1');
+ s = `"${s}"`;
+ return s.replace(/[()%!^"<>&|;,]/g, '^$&');
}
/** Build the argv for the ruflo/claude-flow/npx invocation */
@@ -99,20 +211,40 @@ function buildArgs(subcommand, extraArgs) {
*
* Returns true on success (exit 0), false otherwise.
*/
-function invokeHook(bin, binArgs, hookArgs, stdinData) {
- const args = [...binArgs, ...hookArgs];
-
- // On Windows, shell: true is needed to resolve .cmd shims in node_modules
- const useShell = process.platform === 'win32';
-
- const result = spawnSync(bin, args, {
- shell: useShell,
+function invokeHook(bin, binArgs, hookArgs, stdinData, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const spawnOpts = {
input: stdinData || '',
encoding: 'utf8',
- stdio: ['pipe', 'ignore', 'ignore'], // swallow all output
+ stdio: ['pipe', 'ignore', 'ignore'],
timeout: 30_000,
- });
+ env,
+ };
+ // Layer 1: no shell. CreateProcess/execve receives the argv array
+ // verbatim, so nothing in it can be reinterpreted as syntax.
+ const invocation = resolveInvocation(bin, binArgs, { env, platform });
+ if (invocation) {
+ const result = spawnSync(invocation.command, [...invocation.args, ...hookArgs], {
+ ...spawnOpts,
+ shell: false,
+ });
+ return result.status === 0;
+ }
+
+ // Layer 2: Windows shim we could not map to an entrypoint. cmd.exe is
+ // unavoidable here (CreateProcess cannot launch a .cmd, and Node has
+ // refused to since CVE-2024-27980), so every element is escaped. Losing
+ // the hook entirely would be the wrong trade — telemetry is best-effort,
+ // but silently doing nothing hides breakage.
+ const useShell = platform === 'win32';
+ const args = [...binArgs, ...hookArgs];
+ const result = spawnSync(
+ useShell ? escapeCmdArg(bin) : bin,
+ useShell ? args.map(escapeCmdArg) : args,
+ { ...spawnOpts, shell: useShell },
+ );
return result.status === 0;
}
@@ -137,13 +269,13 @@ function main() {
const hookArgs = buildArgs(subcommand, rest);
// Priority 1: locally installed ruflo binary
- if (commandExists('ruflo')) {
+ if (resolveCommandPath('ruflo')) {
invokeHook('ruflo', [], hookArgs, stdinData);
done();
}
// Priority 2: locally installed claude-flow binary
- if (commandExists('claude-flow')) {
+ if (resolveCommandPath('claude-flow')) {
invokeHook('claude-flow', [], hookArgs, stdinData);
done();
}
@@ -163,4 +295,10 @@ function main() {
done();
}
-main();
+// Test seam: the Windows argv suite require()s this file to drive resolveInvocation()
+// and invokeHook() with a simulated { platform: 'win32', env } — which is how
+// the Windows branch is proved from a Linux/macOS CI run. hooks.json always
+// invokes this file directly, so main() runs unconditionally otherwise.
+if (!globalThis.__RUFLO_HOOK_IMPORT_ONLY__) main();
+
+module.exports = { invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
diff --git a/plugins/ruflo-core/scripts/ruflo-hook.cjs b/plugins/ruflo-core/scripts/ruflo-hook.cjs
index a939a8de5b..2844529db2 100644
--- a/plugins/ruflo-core/scripts/ruflo-hook.cjs
+++ b/plugins/ruflo-core/scripts/ruflo-hook.cjs
@@ -40,7 +40,7 @@
'use strict';
-const { spawnSync, execSync } = require('child_process');
+const { spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
@@ -51,17 +51,98 @@ function done() {
process.exit(0);
}
-/** Check if a binary is available on PATH */
-function commandExists(cmd) {
+/** Case-insensitive env lookup — Windows env keys are not case-stable. */
+function envValue(env, name) {
+ const key = Object.keys(env).find((c) => c.toLowerCase() === name.toLowerCase());
+ return key ? env[key] : undefined;
+}
+
+/**
+ * Locate a command on PATH using fs only.
+ *
+ * Deliberately NOT `execSync('where ...')` / `command -v`: that spawns a
+ * shell on every hook invocation, which is both the thing this file is
+ * trying to get away from and a per-turn cost. Taking `env` and `platform`
+ * as arguments is what lets the Windows branch be exercised from a
+ * Linux/macOS CI run — see the Windows argv tests.
+ */
+function resolveCommandPath(command, env = process.env, platform = process.platform) {
+ const hasSeparator = command.includes('/') || command.includes('\\');
+ const dirs = hasSeparator
+ ? ['']
+ : (envValue(env, 'PATH') || '').split(platform === 'win32' ? ';' : path.delimiter);
+ const hasExtension = path.extname(command) !== '';
+ const extensions = platform === 'win32' && !(hasSeparator && hasExtension)
+ ? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
+ : [''];
+ for (const dir of dirs) {
+ for (const ext of extensions) {
+ const base = path.resolve(dir || '.', command);
+ const candidates = ext
+ ? [base + ext.toLowerCase(), base + ext.toUpperCase()]
+ : [base];
+ for (const file of candidates) {
+ try {
+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
+ if (fs.statSync(file).isFile()) return file;
+ } catch { /* keep searching */ }
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Map an npm-generated Windows shim (ruflo.cmd / npx.cmd / …) to the .js
+ * entrypoint it would have run, so it can be executed as `node <entry>`
+ * with no shell.
+ *
+ * Handles both npm layouts: a global prefix (`<prefix>/ruflo.cmd` beside
+ * `<prefix>/node_modules/ruflo`) and a local one (`node_modules/.bin/ruflo.cmd`
+ * beside `node_modules/ruflo`). `npx` lives in the `npm` package, hence the
+ * command→package mapping rather than assuming they match.
+ *
+ * The entrypoint comes from the package's own `bin` field, never a guessed
+ * filename, and is required to resolve inside the package directory — a
+ * manifest pointing outside it is refused rather than followed.
+ */
+function resolveNpmShim(shimPath) {
+ const command = path.basename(shimPath, path.extname(shimPath)).toLowerCase();
+ const packageName = command === 'npx' ? 'npm' : command;
+ if (!['ruflo', 'claude-flow', 'npm'].includes(packageName)) return null;
try {
- const result = execSync(
- process.platform === 'win32' ? `where ${cmd}` : `command -v ${cmd}`,
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
- );
- return result.trim().length > 0;
- } catch {
- return false;
+ const shimDir = path.dirname(shimPath);
+ const packageDir = path.basename(shimDir).toLowerCase() === '.bin'
+ ? path.resolve(shimDir, '..', packageName)
+ : path.resolve(shimDir, 'node_modules', packageName);
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
+ const declared = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[command];
+ if (typeof declared !== 'string') return null;
+ const canonicalPackageDir = fs.realpathSync(packageDir);
+ const canonicalEntry = fs.realpathSync(path.resolve(packageDir, declared));
+ const relativeEntry = path.relative(canonicalPackageDir, canonicalEntry);
+ if (relativeEntry.startsWith('..' + path.sep) || path.isAbsolute(relativeEntry)) return null;
+ if (!fs.statSync(canonicalEntry).isFile()) return null;
+ return { command: process.execPath, args: [canonicalEntry] };
+ } catch { return null; }
+}
+
+/**
+ * Decide how to run `bin` without a shell. Returns {command, args}, or null
+ * when no shell-free invocation could be identified (Windows shim that is
+ * not an npm package entry) — the caller then falls back to the escaped
+ * cmd.exe path rather than dropping the hook.
+ */
+function resolveInvocation(bin, binArgs, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const commandPath = resolveCommandPath(bin, env, platform);
+ if (!commandPath) return null;
+ if (platform === 'win32' && /\.(?:cmd|bat|ps1)$/i.test(commandPath)) {
+ const npmBin = resolveNpmShim(commandPath);
+ return npmBin ? { command: npmBin.command, args: [...npmBin.args, ...binArgs] } : null;
}
+ return { command: commandPath, args: binArgs };
}
/**
@@ -94,35 +175,48 @@ function escapeCmdArg(arg) {
* Spawn the CLI with the hook subcommand + args, forwarding stdinData.
* Returns true on success (exit 0), false otherwise. Never throws.
*/
-function invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData) {
+function invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
const args = [...binArgs, 'hooks', hookSubcommand, ...hookArgs];
- // On Windows, shell: true is needed to resolve .cmd/.ps1 shims that npm
- // creates for globally-installed bins (`ruflo`, `claude-flow`, `npx`) —
- // CreateProcess cannot execute those directly. `node` itself is always a
- // real .exe (never a shim), so skip the shell entirely there —
- // CreateProcess gets the argv array verbatim, byte-for-byte, no
- // cmd.exe involved at all. This covers the common `node <cli.js>`
- // invocation (test harness, npx-resolved runs). A real global
- // `ruflo`/`claude-flow` install still goes through the shim path below;
- // every array element is escaped with escapeCmdArg() before it reaches
- // cmd.exe so hook-derived values can't be reinterpreted as shell syntax.
- const useShell = process.platform === 'win32' && bin !== 'node' && bin !== process.execPath;
- const spawnBin = useShell ? escapeCmdArg(bin) : bin;
- const spawnArgs = useShell ? args.map(escapeCmdArg) : args;
// Test-only: RUFLO_HOOK_DEBUG_STDOUT surfaces the invoked CLI's own
// stdout/stderr instead of swallowing them, so test-hooks.mjs can assert
// on the CLI's actual recorded value (e.g. catching #1859/#1862-style
// flag-wiring regressions). Production never sets this — hooks must
// never leak CLI output into the host (Cursor's PreToolUse contract).
- const debug = process.env.RUFLO_HOOK_DEBUG_STDOUT === '1';
+ const debug = (envValue(env, 'RUFLO_HOOK_DEBUG_STDOUT') || '') === '1';
+ const base = {
+ input: stdinData || '',
+ encoding: 'utf8',
+ stdio: debug ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'ignore', 'ignore'],
+ timeout: 30_000,
+ env,
+ };
try {
- const result = spawnSync(spawnBin, spawnArgs, {
- shell: useShell,
- input: stdinData || '',
- encoding: 'utf8',
- stdio: debug ? ['pipe', 'pipe', 'pipe'] : ['pipe', 'ignore', 'ignore'],
- timeout: 30_000,
- });
+ // Layer 1 — no shell. resolveInvocation() maps the command to a real
+ // executable, and on Windows maps npm's .cmd/.ps1 shim to the .js
+ // entrypoint it wraps, so this becomes `node <entry>` and CreateProcess
+ // receives the argv array verbatim. Nothing to escape, no second
+ // cmd.exe tokenizer, and no %VAR% expansion.
+ const invocation = resolveInvocation(bin, binArgs, { env, platform });
+ let result;
+ if (invocation) {
+ result = spawnSync(invocation.command, [...invocation.args, 'hooks', hookSubcommand, ...hookArgs], {
+ ...base,
+ shell: false,
+ });
+ } else {
+ // Layer 2 — a Windows shim we could not map to an entrypoint. cmd.exe
+ // is unavoidable (CreateProcess cannot launch a .cmd, and Node has
+ // refused to since CVE-2024-27980), so every element is escaped.
+ // Dropping the hook instead would hide breakage rather than surface it.
+ const useShell = platform === 'win32' && bin !== 'node' && bin !== process.execPath;
+ result = spawnSync(
+ useShell ? escapeCmdArg(bin) : bin,
+ useShell ? args.map(escapeCmdArg) : args,
+ { ...base, shell: useShell },
+ );
+ }
if (debug) {
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
@@ -146,11 +240,11 @@ function invokeCli(hookSubcommand, hookArgs, stdinData) {
invokeHook(bin, binArgs, hookSubcommand, hookArgs, stdinData);
return;
}
- if (commandExists('ruflo')) {
+ if (resolveCommandPath('ruflo')) {
invokeHook('ruflo', [], hookSubcommand, hookArgs, stdinData);
return;
}
- if (commandExists('claude-flow')) {
+ if (resolveCommandPath('claude-flow')) {
invokeHook('claude-flow', [], hookSubcommand, hookArgs, stdinData);
return;
}
@@ -346,4 +440,4 @@ if (process.env.RUFLO_HOOK_UNIT_TEST !== '1') {
main();
}
-module.exports = { escapeCmdArg };
+module.exports = { escapeCmdArg, invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim };
diff --git a/plugins/ruflo-core/scripts/test-hooks.mjs b/plugins/ruflo-core/scripts/test-hooks.mjs
index 6f09f62903..637ebde77d 100644
--- a/plugins/ruflo-core/scripts/test-hooks.mjs
+++ b/plugins/ruflo-core/scripts/test-hooks.mjs
@@ -38,13 +38,15 @@
* (windows-latest, macos-latest, ubuntu-latest).
*/
-import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { tmpdir } from 'node:os';
+import { createRequire } from 'node:module';
const __dirname = dirname(fileURLToPath(import.meta.url));
+const require = createRequire(import.meta.url);
const PLUGIN_ROOT = join(__dirname, '..');
const HOOKS_JSON = join(PLUGIN_ROOT, 'hooks', 'hooks.json');
const HOOK_RECORDER = join(__dirname, 'fixtures', 'hook-cli-recorder.cjs');
@@ -306,5 +308,130 @@ run('Stop hook runs session-end without error',
}
}
+// ---------------------------------------------------------------------------
+// Windows argv integrity: hook-derived values must never be re-parsed as
+// shell syntax. Extends the escaping added in #3322 to the remaining copies.
+//
+// This job runs on windows-latest as well as ubuntu/macos (see the "Plugin
+// hooks smoke" matrix in .github/workflows/v3-ci.yml), which makes it the one
+// place in the repo where the Windows behaviour can be executed for real
+// rather than asserted as a string transform. PR #3322 could only be verified
+// at the string level; this closes that gap.
+//
+// Layer 1 (all platforms): resolveInvocation() maps an npm .cmd shim to the
+// .js entrypoint it wraps, so the spawn is `node <entry>` with shell:false and
+// cmd.exe never runs. Driven with an injected { platform: 'win32', env }, so
+// the Windows branch is exercised on every OS in the matrix.
+//
+// Layer 2 (windows only): a .cmd that is NOT an npm package layout cannot be
+// resolved, so escapeCmdArg() + shell:true is used. On a real Windows runner
+// this executes cmd.exe for real.
+{
+ globalThis.__RUFLO_HOOK_IMPORT_ONLY__ = true;
+ process.env.RUFLO_HOOK_UNIT_TEST = '1';
+ const hook = require('./ruflo-hook.cjs');
+ delete globalThis.__RUFLO_HOOK_IMPORT_ONLY__;
+ delete process.env.RUFLO_HOOK_UNIT_TEST;
+
+ const secDir = mkdtempSync(join(tmpdir(), 'ruflo-hook-667-'));
+ // Every metacharacter escapeCmdArg() claims to neutralise. %VAR% is
+ // deliberately excluded here and probed separately below.
+ const PAYLOAD = 'x & calc.exe | "q" ^ !v! <in >out; a,b (c)';
+
+ try {
+ // ---- Layer 1: npm shim resolves to the package entry, no shell ----
+ for (const sc of [
+ { cmd: 'ruflo', pkg: 'ruflo', entry: 'bin/ruflo.js', binArgs: [] },
+ { cmd: 'claude-flow', pkg: 'claude-flow', entry: 'bin/cli.js', binArgs: [] },
+ { cmd: 'npx', pkg: 'npm', entry: 'bin/npx-cli.js', binArgs: ['--prefer-offline', '--yes', 'ruflo@latest'] },
+ ]) for (const layout of ['global', 'local']) {
+ const prefix = join(secDir, `${sc.cmd}-${layout} with spaces`);
+ const shimDir = layout === 'local' ? join(prefix, 'node_modules', '.bin') : prefix;
+ const pkgDir = join(prefix, 'node_modules', sc.pkg);
+ const entryPath = join(pkgDir, sc.entry);
+ const argvFile = join(prefix, 'argv.json');
+ mkdirSync(dirname(entryPath), { recursive: true });
+ mkdirSync(shimDir, { recursive: true });
+ // Sibling shims that must never execute — if one does, the resolver
+ // took a shell path instead of the package entrypoint.
+ writeFileSync(join(shimDir, `${sc.cmd}.cmd`), '@echo off\r\nexit /b 3\r\n');
+ writeFileSync(join(shimDir, `${sc.cmd}.ps1`), 'throw "must not execute"\r\n');
+ writeFileSync(join(shimDir, sc.cmd), '#!/bin/sh\nexit 99\n');
+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: sc.pkg, bin: { [sc.cmd]: sc.entry } }));
+ writeFileSync(entryPath, `#!${process.execPath}\nrequire('node:fs').writeFileSync(process.env.RUFLO_TEST_ARGV_FILE, JSON.stringify(process.argv.slice(2)));\n`);
+ chmodSync(entryPath, 0o755);
+
+ const ok = hook.invokeHook(sc.cmd, sc.binArgs, 'post-command', ['-c', PAYLOAD], '{}', {
+ platform: 'win32',
+ env: { ...process.env, PATH: shimDir, PATHEXT: '.COM;.EXE;.BAT;.CMD', RUFLO_TEST_ARGV_FILE: argvFile },
+ });
+ const argv = existsSync(argvFile) ? JSON.parse(readFileSync(argvFile, 'utf8')) : null;
+ const want = [...sc.binArgs, 'hooks', 'post-command', '-c', PAYLOAD];
+ const name = `win32 argv: ${layout} ${sc.cmd}.cmd resolves to the package entry and forwards argv intact`;
+ if (ok && JSON.stringify(argv) === JSON.stringify(want)) {
+ console.log(`ok: ${name}`);
+ } else {
+ console.error(`FAIL: ${name}\n got: ${JSON.stringify(argv)}`);
+ failed++;
+ }
+ cases.push(name);
+ }
+
+ // ---- Layer 2: unresolvable .cmd, escaped through real cmd.exe ----
+ // Only meaningful where cmd.exe exists. On the windows-latest runner this
+ // is the first real execution of the #3322 escaping.
+ if (process.platform === 'win32') {
+ const prefix = join(secDir, 'bare-shim');
+ mkdirSync(prefix, { recursive: true });
+ const argvFile = join(prefix, 'argv.json');
+ const marker = join(prefix, 'INJECTED');
+ const recorder = join(prefix, 'record.js');
+ writeFileSync(recorder, `require('node:fs').writeFileSync(process.env.RUFLO_TEST_ARGV_FILE, JSON.stringify(process.argv.slice(2)));\n`);
+ // No node_modules/<pkg> beside it, so resolveNpmShim() returns null and
+ // invokeHook() must fall back to the escaped shell. `%*` re-expands the
+ // arguments — the second cmd.exe parse the escaping exists to survive.
+ writeFileSync(join(prefix, 'ruflo.cmd'), `@echo off\r\n"${process.execPath}" "${recorder}" %*\r\n`);
+
+ const ok = hook.invokeHook('ruflo', [], 'post-command', ['-c', PAYLOAD], '{}', {
+ env: { ...process.env, PATH: prefix, PATHEXT: '.COM;.EXE;.BAT;.CMD', RUFLO_TEST_ARGV_FILE: argvFile },
+ });
+ const argv = existsSync(argvFile) ? JSON.parse(readFileSync(argvFile, 'utf8')) : null;
+ const want = ['hooks', 'post-command', '-c', PAYLOAD];
+ const name = 'win32 argv: unresolvable .cmd — escaped argv survives a real cmd.exe round trip';
+ if (ok && JSON.stringify(argv) === JSON.stringify(want) && !existsSync(marker)) {
+ console.log(`ok: ${name}`);
+ } else {
+ console.error(`FAIL: ${name}\n got: ${JSON.stringify(argv)}`);
+ failed++;
+ }
+ cases.push(name);
+
+ // Known residual: carets do not reliably escape %, and quoting does not
+ // suppress percent expansion, so a %VAR% in a hook value may be
+ // substituted on the shim's second parse. That is data corruption, not
+ // injection — so the hard assertion is only that nothing extra executed.
+ // The round-trip result is REPORTED so the Windows runner tells us what
+ // actually happens; it does not fail the build on a documented residual.
+ const pctFile = join(prefix, 'argv-pct.json');
+ const pctMarker = join(prefix, 'PCT_INJECTED');
+ hook.invokeHook('ruflo', [], 'post-command', ['-c', '%USERPROFILE% & echo pwned > "' + pctMarker + '"'], '{}', {
+ env: { ...process.env, PATH: prefix, PATHEXT: '.COM;.EXE;.BAT;.CMD', RUFLO_TEST_ARGV_FILE: pctFile },
+ });
+ const pctArgv = existsSync(pctFile) ? JSON.parse(readFileSync(pctFile, 'utf8')) : null;
+ const pctName = 'win32 argv: %VAR% in a hook value does not inject a command';
+ if (!existsSync(pctMarker)) {
+ console.log(`ok: ${pctName}`);
+ console.log(` note (known residual, not a failure) — %VAR% round trip: ${JSON.stringify(pctArgv?.[3])}`);
+ } else {
+ console.error(`FAIL: ${pctName} — a redirection executed`);
+ failed++;
+ }
+ cases.push(pctName);
+ }
+ } finally {
+ rmSync(secDir, { recursive: true, force: true });
+ }
+}
+
console.log(`\n${cases.length - failed}/${cases.length} passed`);
process.exit(failed === 0 ? 0 : 1);
diff --git a/v3/@claude-flow/cli/__tests__/ruflo-hook-windows-argv.test.ts b/v3/@claude-flow/cli/__tests__/ruflo-hook-windows-argv.test.ts
new file mode 100644
index 0000000000..b3baa67ad3
--- /dev/null
+++ b/v3/@claude-flow/cli/__tests__/ruflo-hook-windows-argv.test.ts
@@ -0,0 +1,221 @@
+/**
+ * Windows hook argv integrity — command re-execution through cmd.exe.
+ *
+ * A private report found that ruflo-hook.cjs forwards hook-derived values
+ * (a Bash tool's `command`, a file path) through `spawnSync(..., {shell:true})`
+ * on Windows, where cmd.exe re-tokenizes them. PR #3322 fixed exactly one of
+ * the four copies of that shim — `plugins/ruflo-core/scripts/ruflo-hook.cjs`.
+ * The other three, including the one `ruflo init` writes into every user
+ * project, kept the unescaped `spawnSync(bin, args, {shell: win32})`.
+ *
+ * The fix has two layers, and they are tested very differently:
+ *
+ * - Layer 1, resolveInvocation(), maps a command to a real executable —
+ * and on Windows maps npm's .cmd shim to the package's own .js entry —
+ * so the spawn is `node <entry>` with shell:false. Because it takes
+ * `platform` and `env` as arguments, the Windows branch is fully
+ * exercisable from a Linux/macOS CI run: the .cmd is *resolved past*,
+ * never executed, and the recorded argv proves the round trip. That is
+ * what most of this file does.
+ *
+ * - Layer 2, escapeCmdArg(), guards the residual path where layer 1 finds
+ * no entrypoint. It is only assertable as a string transform here; real
+ * cmd.exe execution remains an open follow-up gate on the issue. This is
+ * the asymmetry that motivates preferring layer 1.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, rmSync, chmodSync, realpathSync } from 'fs';
+import { createRequire } from 'module';
+import { tmpdir } from 'os';
+import path from 'path';
+import { generateRufloHookCjs } from '../src/init/helpers-generator';
+
+const REPO = path.resolve(__dirname, '../../../..');
+const require_ = createRequire(__filename);
+
+/** The committed copies of the shim that must not diverge. */
+const COPIES = [
+ 'plugins/ruflo-core/scripts/ruflo-hook.cjs',
+ '.claude-plugin/scripts/ruflo-hook.cjs',
+ 'plugin/scripts/ruflo-hook.cjs',
+];
+
+/**
+ * The functions all four copies must hold in common. escapeCmdArg is layer 2;
+ * the three resolvers are layer 1, and this recurred precisely because a fix
+ * reached one copy and not its siblings — so both layers are pinned, not just
+ * the one that happened to be patched first.
+ */
+const SHARED = ['escapeCmdArg', 'resolveCommandPath', 'resolveNpmShim', 'resolveInvocation'] as const;
+
+function fnOf(source: string, name: string, label: string): string {
+ const m = new RegExp(`function ${name}\\([\\s\\S]*?\\n\\}`).exec(source);
+ if (!m) throw new Error(`no ${name}() in ${label} — the Windows argv fix is incomplete in this copy`);
+ return m[0];
+}
+
+type HookModule = {
+ invokeHook: (bin: string, binArgs: string[], hookArgs: string[], stdin: string, opts?: any) => boolean;
+ resolveCommandPath: (cmd: string, env?: any, platform?: string) => string | null;
+ resolveInvocation: (bin: string, binArgs: string[], opts?: any) => { command: string; args: string[] } | null;
+ resolveNpmShim: (shimPath: string) => { command: string; args: string[] } | null;
+};
+
+let tmp: string;
+/** The shim as `ruflo init` writes it — the copy under test. */
+let hook: HookModule;
+
+beforeAll(() => {
+ tmp = mkdtempSync(path.join(tmpdir(), 'ruflo-hook-667-'));
+ const generated = path.join(tmp, 'ruflo-hook.cjs');
+ writeFileSync(generated, generateRufloHookCjs());
+ (globalThis as any).__RUFLO_HOOK_IMPORT_ONLY__ = true;
+ hook = require_(generated) as HookModule;
+ delete (globalThis as any).__RUFLO_HOOK_IMPORT_ONLY__;
+});
+
+afterAll(() => rmSync(tmp, { recursive: true, force: true }));
+
+/**
+ * Build the layout npm actually creates on Windows: sibling .cmd / .ps1 /
+ * extensionless shims, and the package itself with a recording JS entry.
+ * `global` is `<prefix>/ruflo.cmd` + `<prefix>/node_modules/ruflo`;
+ * `local` is `node_modules/.bin/ruflo.cmd` + `node_modules/ruflo`.
+ */
+function npmLayout(opts: {
+ dir: string; command: string; packageName: string; entry: string; layout: 'global' | 'local';
+}) {
+ const prefix = path.join(tmp, opts.dir);
+ const shimDir = opts.layout === 'local' ? path.join(prefix, 'node_modules', '.bin') : prefix;
+ const packageDir = path.join(prefix, 'node_modules', opts.packageName);
+ const entryPath = path.join(packageDir, opts.entry);
+ const argvFile = path.join(prefix, 'argv.json');
+
+ mkdirSync(path.dirname(entryPath), { recursive: true });
+ mkdirSync(shimDir, { recursive: true });
+ // Sibling shims that must never be executed — if any of them runs, the
+ // resolver picked a shell path instead of the package entrypoint.
+ writeFileSync(path.join(shimDir, `${opts.command}.cmd`), '@echo off\r\nexit /b 3\r\n');
+ writeFileSync(path.join(shimDir, `${opts.command}.ps1`), 'throw "must not execute"\r\n');
+ writeFileSync(path.join(shimDir, opts.command), '#!/bin/sh\nexit 99\n');
+ writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({ name: opts.packageName, bin: { [opts.command]: opts.entry } }),
+ );
+ writeFileSync(
+ entryPath,
+ '#!/usr/bin/env node\n' +
+ "require('fs').writeFileSync(process.env.RUFLO_TEST_ARGV_FILE, JSON.stringify(process.argv.slice(2)));\n",
+ );
+ chmodSync(entryPath, 0o755);
+
+ return {
+ entryPath,
+ argvFile,
+ env: { ...process.env, PATH: shimDir, PATHEXT: '.COM;.EXE;.BAT;.CMD', RUFLO_TEST_ARGV_FILE: argvFile },
+ };
+}
+
+describe('ruflo-hook.cjs windows argv — the shell is removed, not merely escaped', () => {
+ it.each(SHARED)('all four copies share a byte-identical %s()', (fn) => {
+ const sources = new Map<string, string>();
+ for (const rel of COPIES) sources.set(rel, readFileSync(path.join(REPO, rel), 'utf8'));
+ sources.set('init-generated', generateRufloHookCjs());
+
+ const bodies = new Map([...sources].map(([label, src]) => [label, fnOf(src, fn, label)]));
+ expect(
+ new Set(bodies.values()).size,
+ `${fn}() diverged across copies:\n${[...bodies.keys()].join('\n')}`,
+ ).toBe(1);
+ });
+
+ it('no copy still probes PATH through a shell', () => {
+ for (const rel of COPIES) {
+ const code = readFileSync(path.join(REPO, rel), 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
+ expect(code, `${rel} still uses execSync`).not.toContain('execSync');
+ expect(code, `${rel} still has the pre-fix spawn`).not.toContain('spawnSync(bin, args, {');
+ }
+ });
+
+ it('never probes PATH through a shell, and never spawns the pre-fix unescaped form', () => {
+ const src = generateRufloHookCjs();
+ const code = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '');
+ // The old `execSync('where ' + cmd)` probe spawned a shell on every hook.
+ expect(code).not.toContain('execSync');
+ // The pre-fix spawn must be gone, not merely supplemented.
+ expect(code).not.toContain('spawnSync(bin, args, {');
+ // The resolved path is explicitly shell-free.
+ expect(code).toContain('shell: false');
+ });
+
+ // ---- Layer 1: the Windows branch, proved without Windows ----
+
+ it.each([
+ { command: 'ruflo', packageName: 'ruflo', entry: 'bin/ruflo.js', binArgs: [] as string[] },
+ { command: 'claude-flow', packageName: 'claude-flow', entry: 'bin/cli.js', binArgs: [] as string[] },
+ // npx lives in the `npm` package — the command and package names differ.
+ { command: 'npx', packageName: 'npm', entry: 'bin/npx-cli.js', binArgs: ['--prefer-offline', '--yes', 'ruflo@latest'] },
+ ])('$command: a simulated win32 .cmd shim resolves to the package entry, no shell', ({ command, packageName, entry, binArgs }) => {
+ for (const layout of ['global', 'local'] as const) {
+ const l = npmLayout({ dir: `${command}-${layout} with spaces`, command, packageName, entry, layout });
+
+ // The resolver reaches the package's own .js, run under this node.
+ const invocation = hook.resolveInvocation(command, binArgs, { platform: 'win32', env: l.env });
+ expect(invocation, `${command}/${layout} did not resolve`).not.toBeNull();
+ expect(invocation!.command).toBe(process.execPath);
+ // resolveNpmShim() canonicalises via realpath (macOS /var -> /private/var).
+ expect(realpathSync(invocation!.args[0])).toBe(realpathSync(l.entryPath));
+
+ // And the value survives to the CLI byte-for-byte.
+ const payload = 'x & calc.exe | %USERPROFILE% "q" ^ !v! <in >out; a,b (c)\nsecond line';
+ const ok = hook.invokeHook(command, binArgs, ['hooks', 'post-command', '-c', payload], '{}', {
+ platform: 'win32',
+ env: l.env,
+ });
+ expect(ok, `${command}/${layout} invocation failed`).toBe(true);
+ expect(JSON.parse(readFileSync(l.argvFile, 'utf8'))).toEqual([
+ ...binArgs, 'hooks', 'post-command', '-c', payload,
+ ]);
+ }
+ });
+
+ it('refuses a manifest whose bin escapes the package directory', () => {
+ const prefix = path.join(tmp, 'escaping-manifest');
+ const packageDir = path.join(prefix, 'node_modules', 'ruflo');
+ mkdirSync(packageDir, { recursive: true });
+ mkdirSync(path.join(prefix, 'outside'), { recursive: true });
+ writeFileSync(path.join(prefix, 'outside', 'evil.js'), '');
+ writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({ name: 'ruflo', bin: { ruflo: '../../outside/evil.js' } }),
+ );
+ writeFileSync(path.join(prefix, 'ruflo.cmd'), '@echo off\r\n');
+ expect(hook.resolveNpmShim(path.join(prefix, 'ruflo.cmd'))).toBeNull();
+ });
+
+ // ---- Layer 1 on this host, for real ----
+
+ it.skipIf(process.platform === 'win32')('passes a metacharacter payload to a real child process byte-for-byte', () => {
+ const prefix = path.join(tmp, 'posix-real');
+ mkdirSync(path.join(prefix, 'bin'), { recursive: true });
+ const argvFile = path.join(prefix, 'argv.json');
+ const cli = path.join(prefix, 'bin', 'ruflo');
+ writeFileSync(
+ cli,
+ // Absolute shebang: PATH is stripped to the fake bin dir below, so
+ // `#!/usr/bin/env node` would not find node.
+ `#!${process.execPath}\n` +
+ `require('fs').writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv.slice(2)));\n`,
+ );
+ chmodSync(cli, 0o755);
+
+ const payload = 'x & calc.exe | $(id) `id` "q" ^ !v! <in >out; a,b (c)';
+ const ok = hook.invokeHook('ruflo', [], ['hooks', 'post-command', '-c', payload], '{}', {
+ env: { ...process.env, PATH: path.join(prefix, 'bin') },
+ });
+ expect(ok).toBe(true);
+ expect(JSON.parse(readFileSync(argvFile, 'utf8'))).toEqual(['hooks', 'post-command', '-c', payload]);
+ });
+});
diff --git a/v3/@claude-flow/cli/src/init/helpers-generator.ts b/v3/@claude-flow/cli/src/init/helpers-generator.ts
index 0b462bba5b..6145698c3c 100644
--- a/v3/@claude-flow/cli/src/init/helpers-generator.ts
+++ b/v3/@claude-flow/cli/src/init/helpers-generator.ts
@@ -1434,34 +1434,192 @@ export function generateRufloHookCjs(): string {
*
* Always exits 0 — hook subcommands are best-effort telemetry and must
* never block a Claude Code turn.
+ *
+ * Windows argv integrity: hook-derived values (a Bash tool's \`command\`, a file path) must
+ * reach the CLI as literal argv and never as shell syntax. Two layers, in
+ * this order:
+ *
+ * 1. resolveInvocation() maps the command to a real executable — and on
+ * Windows maps npm's .cmd shim to the package's own .js entrypoint —
+ * so the spawn runs \`node <entry>\` with shell:false and NO cmd.exe in
+ * the chain at all. Nothing to escape, nothing to re-tokenize, and no
+ * %VAR% expansion. (The escaped fallback was measured on a real
+ * windows-latest runner and does pass %VAR% through literally; layer 1
+ * is still preferred because it removes the parser rather than
+ * out-guessing it.)
+ * 2. escapeCmdArg() guards the residual Windows path where step 1 cannot
+ * identify an entrypoint. Escaping is strictly the weaker layer: it is
+ * only reachable when resolution fails, and it is the one part of this
+ * file that a non-Windows CI run cannot prove.
*/
'use strict';
-const { spawnSync, execSync } = require('child_process');
+const { spawnSync } = require('child_process');
const fs = require('fs');
+const path = require('path');
function done() { process.exit(0); }
-function commandExists(cmd) {
+/** Case-insensitive env lookup — Windows env keys are not case-stable. */
+function envValue(env, name) {
+ const key = Object.keys(env).find((c) => c.toLowerCase() === name.toLowerCase());
+ return key ? env[key] : undefined;
+}
+
+/**
+ * Locate a command on PATH using fs only.
+ *
+ * Deliberately NOT \`execSync('where ...')\` / \`command -v\`: that spawns a
+ * shell on every hook invocation, which is both the thing this file is
+ * trying to get away from and a per-turn cost. Taking \`env\` and \`platform\`
+ * as arguments is what lets the Windows branch be exercised from a
+ * Linux/macOS CI run — see the Windows argv tests.
+ */
+function resolveCommandPath(command, env = process.env, platform = process.platform) {
+ const hasSeparator = command.includes('/') || command.includes('\\\\');
+ const dirs = hasSeparator
+ ? ['']
+ : (envValue(env, 'PATH') || '').split(platform === 'win32' ? ';' : path.delimiter);
+ const hasExtension = path.extname(command) !== '';
+ const extensions = platform === 'win32' && !(hasSeparator && hasExtension)
+ ? (envValue(env, 'PATHEXT') || '.COM;.EXE;.BAT;.CMD').split(';')
+ : [''];
+ for (const dir of dirs) {
+ for (const ext of extensions) {
+ const base = path.resolve(dir || '.', command);
+ const candidates = ext
+ ? [base + ext.toLowerCase(), base + ext.toUpperCase()]
+ : [base];
+ for (const file of candidates) {
+ try {
+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);
+ if (fs.statSync(file).isFile()) return file;
+ } catch { /* keep searching */ }
+ }
+ }
+ }
+ return null;
+}
+
+/**
+ * Map an npm-generated Windows shim (ruflo.cmd / npx.cmd / …) to the .js
+ * entrypoint it would have run, so it can be executed as \`node <entry>\`
+ * with no shell.
+ *
+ * Handles both npm layouts: a global prefix (\`<prefix>/ruflo.cmd\` beside
+ * \`<prefix>/node_modules/ruflo\`) and a local one (\`node_modules/.bin/ruflo.cmd\`
+ * beside \`node_modules/ruflo\`). \`npx\` lives in the \`npm\` package, hence the
+ * command→package mapping rather than assuming they match.
+ *
+ * The entrypoint comes from the package's own \`bin\` field, never a guessed
+ * filename, and is required to resolve inside the package directory — a
+ * manifest pointing outside it is refused rather than followed.
+ */
+function resolveNpmShim(shimPath) {
+ const command = path.basename(shimPath, path.extname(shimPath)).toLowerCase();
+ const packageName = command === 'npx' ? 'npm' : command;
+ if (!['ruflo', 'claude-flow', 'npm'].includes(packageName)) return null;
try {
- const r = execSync(
- process.platform === 'win32' ? 'where ' + cmd : 'command -v ' + cmd,
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }
- );
- return r.trim().length > 0;
- } catch { return false; }
+ const shimDir = path.dirname(shimPath);
+ const packageDir = path.basename(shimDir).toLowerCase() === '.bin'
+ ? path.resolve(shimDir, '..', packageName)
+ : path.resolve(shimDir, 'node_modules', packageName);
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, 'package.json'), 'utf8'));
+ const declared = typeof manifest.bin === 'string' ? manifest.bin : manifest.bin?.[command];
+ if (typeof declared !== 'string') return null;
+ const canonicalPackageDir = fs.realpathSync(packageDir);
+ const canonicalEntry = fs.realpathSync(path.resolve(packageDir, declared));
+ const relativeEntry = path.relative(canonicalPackageDir, canonicalEntry);
+ if (relativeEntry.startsWith('..' + path.sep) || path.isAbsolute(relativeEntry)) return null;
+ if (!fs.statSync(canonicalEntry).isFile()) return null;
+ return { command: process.execPath, args: [canonicalEntry] };
+ } catch { return null; }
}
-function invokeHook(bin, binArgs, hookArgs, stdinData) {
- const args = [...binArgs, ...hookArgs];
- const result = spawnSync(bin, args, {
- shell: process.platform === 'win32',
+/**
+ * Decide how to run \`bin\` without a shell. Returns {command, args}, or null
+ * when no shell-free invocation could be identified (Windows shim that is
+ * not an npm package entry) — the caller then falls back to the escaped
+ * cmd.exe path rather than dropping the hook.
+ */
+function resolveInvocation(bin, binArgs, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const commandPath = resolveCommandPath(bin, env, platform);
+ if (!commandPath) return null;
+ if (platform === 'win32' && /\\.(?:cmd|bat|ps1)$/i.test(commandPath)) {
+ const npmBin = resolveNpmShim(commandPath);
+ return npmBin ? { command: npmBin.command, args: [...npmBin.args, ...binArgs] } : null;
+ }
+ return { command: commandPath, args: binArgs };
+}
+
+/**
+ * Escape one argv element so it survives BOTH parsers a Windows shell:true
+ * spawn puts it through before the target CLI ever sees it:
+ * 1. cmd.exe's own line tokenizer, which still scans for & | < > ^ % ! " ( )
+ * even inside a per-argument quoted segment — quoting alone does not
+ * shield cmd.exe metacharacters, and this runs a SECOND time when the
+ * resolved binary is itself a .cmd shim (npm's \`ruflo\`/\`claude-flow\`/
+ * \`npx\` global installs on Windows), because launching a .cmd file is
+ * cmd.exe re-invoking itself on the command line.
+ * 2. The eventual CommandLineToArgvW argv parse in the target process,
+ * which needs backslash-before-quote sequences doubled and the value
+ * quoted so it lands as ONE argument.
+ * Without this, a hook-derived value (e.g. a Bash tool's \`command\`, or a
+ * file path) containing a shell metacharacter can be reinterpreted as a
+ * separate command / redirection instead of reaching the CLI as literal
+ * data — this is the class of bug in CVE-2024-27980 (Node's own .bat/.cmd
+ * argument-injection advisory). Algorithm: https://qntm.org/cmd, the same
+ * reference the \`cross-spawn\` package's Windows escaping is built from.
+ *
+ * Byte-identical to plugins/ruflo-core/scripts/ruflo-hook.cjs so the four
+ * copies can be diffed against each other. This is the fallback, not the
+ * primary defence: resolveInvocation() above is preferred because it removes
+ * cmd.exe from the chain entirely rather than out-guessing its tokenizer.
+ */
+function escapeCmdArg(arg) {
+ let s = String(arg);
+ s = s.replace(/(\\\\*)"/g, '$1$1\\\\"').replace(/(\\\\*)$/, '$1$1');
+ s = \`"\${s}"\`;
+ return s.replace(/[()%!^"<>&|;,]/g, '^$&');
+}
+
+function invokeHook(bin, binArgs, hookArgs, stdinData, options = {}) {
+ const env = options.env || process.env;
+ const platform = options.platform || process.platform;
+ const spawnOpts = {
input: stdinData || '',
encoding: 'utf8',
stdio: ['pipe', 'ignore', 'ignore'],
timeout: 30_000,
- });
+ env,
+ };
+
+ // Layer 1: no shell. CreateProcess/execve receives the argv array
+ // verbatim, so nothing in it can be reinterpreted as syntax.
+ const invocation = resolveInvocation(bin, binArgs, { env, platform });
+ if (invocation) {
+ const result = spawnSync(invocation.command, [...invocation.args, ...hookArgs], {
+ ...spawnOpts,
+ shell: false,
+ });
+ return result.status === 0;
+ }
+
+ // Layer 2: Windows shim we could not map to an entrypoint. cmd.exe is
+ // unavoidable here (CreateProcess cannot launch a .cmd, and Node has
+ // refused to since CVE-2024-27980), so every element is escaped. Losing
+ // the hook entirely would be the wrong trade — telemetry is best-effort,
+ // but silently doing nothing hides breakage.
+ const useShell = platform === 'win32';
+ const args = [...binArgs, ...hookArgs];
+ const result = spawnSync(
+ useShell ? escapeCmdArg(bin) : bin,
+ useShell ? args.map(escapeCmdArg) : args,
+ { ...spawnOpts, shell: useShell },
+ );
return result.status === 0;
}
@@ -1476,12 +1634,20 @@ function main() {
const hookArgs = ['hooks', subcommand, ...rest];
- if (commandExists('ruflo')) { invokeHook('ruflo', [], hookArgs, stdinData); done(); }
- if (commandExists('claude-flow')) { invokeHook('claude-flow', [], hookArgs, stdinData); done(); }
+ // Presence is checked separately from invocation strategy: a command that
+ // exists but cannot be resolved to an entrypoint still runs, via layer 2.
+ if (resolveCommandPath('ruflo')) { invokeHook('ruflo', [], hookArgs, stdinData); done(); }
+ if (resolveCommandPath('claude-flow')) { invokeHook('claude-flow', [], hookArgs, stdinData); done(); }
invokeHook('npx', ['--prefer-offline', '--yes', 'ruflo@latest'], hookArgs, stdinData);
done();
}
-main();
+// Test seam: the Windows argv suite require()s this file to drive resolveInvocation()
+// and invokeHook() with a simulated { platform: 'win32', env } — which is how
+// the Windows branch is proved from a Linux/macOS CI run. hooks.json always
+// invokes this file directly, so main() runs unconditionally otherwise.
+if (!globalThis.__RUFLO_HOOK_IMPORT_ONLY__) main();
+
+module.exports = { invokeHook, resolveCommandPath, resolveInvocation, resolveNpmShim, escapeCmdArg };
`;
}