Skip to content

OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security

fix(plugin): select compatible Node runtimes for helpers

Michael D'Angeloab52e689877e
diff --git a/plugins/codex-security/mcp-app/src/helpers/helper-files.ts b/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
index 5144bdd7d..611197f45 100644
--- a/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/helper-files.ts
@@ -6,11 +6,11 @@ import {
readSync,
writeFileSync,
} from "node:fs";
-import { windowsBinding } from "../native";
+import { unixBinding, windowsBinding } from "../native";
import { widePath, windowsFileSystem } from "../../../native/windows-files.mjs";
-import { encodePosixPath } from "./posix-path";
+import { decodePosixBytes, encodePosixPath } from "./posix-path";
import { escapeControls } from "./json";
-import { parsedPath } from "./resolve-security-md";
+import { parsedPath, resolvedPath } from "./resolve-security-md";
import { decodeUtf8 } from "./utf8";
export function filesystemErrorMessage(error: unknown): string {
@@ -39,17 +39,55 @@ export function normalizePath(path: string): string {
);
}
-function readError(error: unknown, path: string, label?: string): never {
+export function resolvedPathText(path: string, strict = true): string {
+ if (process.platform !== "win32")
+ return decodePosixBytes(resolvedPath(encodePosixPath(path), strict));
+ const canonical = resolvedPath(widePath(path), strict);
+ const text = canonical.toString("utf16le");
+ if (
+ path.startsWith("\\\\?\\") ||
+ path.startsWith("\\\\.\\") ||
+ !text.startsWith("\\\\?\\")
+ )
+ return text;
+ const ordinary = text.startsWith("\\\\?\\UNC\\")
+ ? `\\\\${text.slice(8)}`
+ : text.slice(4);
+ try {
+ if (resolvedPath(widePath(ordinary), strict).equals(canonical))
+ return ordinary;
+ } catch {
+ // Some raw Windows names can only be opened with the namespace prefix.
+ }
+ return text;
+}
+
+export function environmentValue(name: string): string | undefined {
+ const windows = process.platform === "win32";
+ const value = windows
+ ? windowsBinding().windowsEnvironment(Buffer.from(name, "utf16le"))
+ : unixBinding().unixEnvironment(Buffer.from(name));
+ return value === null
+ ? undefined
+ : windows
+ ? value.toString("utf16le")
+ : decodePosixBytes(value);
+}
+
+export function isMissingPathError(error: unknown): boolean {
const { code, winerror } = error as NodeJS.ErrnoException & {
winerror?: number;
};
+ return (
+ ["ENOENT", "ENOTDIR", "ELOOP"].includes(code ?? "") ||
+ winerror === 21 ||
+ winerror === 123
+ );
+}
+
+function readError(error: unknown, path: string, label?: string): never {
// Preserve pathlib.exists() diagnostics only for callers with missing-file labels.
- if (
- label !== undefined &&
- (["ENOENT", "ENOTDIR", "ELOOP"].includes(code ?? "") ||
- winerror === 21 ||
- winerror === 123)
- )
+ if (label !== undefined && isMissingPathError(error))
throw new Error(`${label} missing: ${path}`);
throw error;
}
diff --git a/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts b/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
index 164f33b9f..b64fe8566 100644
--- a/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
+++ b/plugins/codex-security/mcp-app/src/helpers/resolve-security-md.ts
@@ -34,7 +34,7 @@ type FileInfo = Pick<Stats, "isDirectory" | "isFile" | "isSymbolicLink"> & {
const statPath = (path: Buffer): FileInfo =>
windows ? windowsFiles().stat(path) : statSync(path);
-function windowsJoin(left: string, right: string): string {
+export function windowsJoin(left: string, right: string): string {
if (right.startsWith("\\\\?\\") || right.startsWith("\\\\.\\")) return right;
const namespaced = left.startsWith("\\\\?\\");
const base = left.startsWith("\\\\?\\UNC\\")
@@ -116,7 +116,7 @@ export function expandHome(
return namespacedUnc ? win32.toNamespacedPath(expanded) : expanded;
}
if (path === "~" || path.startsWith("~/")) {
- const home = posixHome ?? homedir();
+ const home = (posixHome ?? homedir()).replace(/\/+$/u, "");
if (home.startsWith("~"))
throw new Error("Could not determine home directory.");
return home + path.slice(1) || "/";
diff --git a/plugins/codex-security/mcp-app/tests/test_helper_files.ts b/plugins/codex-security/mcp-app/tests/test_helper_files.ts
new file mode 100644
index 000000000..8b7a9930f
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_helper_files.ts
@@ -0,0 +1,136 @@
+import assert from "node:assert/strict";
+import { mkdir, rm, symlink } from "node:fs/promises";
+import { join, win32 } from "node:path";
+import { after, test } from "node:test";
+import { importModule, importSource } from "./import-module.ts";
+import { createTemporaryDirectories } from "./support/temporary-directories.ts";
+
+const { resolvedPathText, isMissingPathError } = (await importSource(
+ "src/helpers/helper-files.ts",
+ {
+ define: {
+ "import.meta.url": JSON.stringify(
+ new URL(
+ "../../../../sdk/typescript/_bundled_plugin/mcp/helpers.mjs",
+ import.meta.url,
+ ).href,
+ ),
+ },
+ },
+)) as typeof import("../src/helpers/helper-files.ts");
+const { expandHome } = (await importSource(
+ "src/helpers/resolve-security-md.ts",
+)) as typeof import("../src/helpers/resolve-security-md.ts");
+const { windowsFileSystem } = (await importModule({
+ entryPoints: ["../native/windows-files.mts"],
+})) as typeof import("../../native/windows-files.mjs");
+const directories = createTemporaryDirectories(true);
+after(() => directories.cleanup());
+
+test(
+ "POSIX home expansion removes boundary separators while retaining literal suffixes",
+ { skip: process.platform === "win32" },
+ () => {
+ for (const [home, path, expected] of [
+ ["/", "~", "/"],
+ ["/", "~/.codex", "/.codex"],
+ ["//", "~/.codex", "/.codex"],
+ ["", "~", "/"],
+ ["", "~/child", "/child"],
+ [
+ "/synthetic/home///",
+ "~/alias/../child",
+ "/synthetic/home/alias/../child",
+ ],
+ ["/synthetic/home/", "//literal/path", "//literal/path"],
+ ] as const)
+ assert.equal(expandHome(path, home), expected);
+ },
+);
+
+test("optional probes recognize unavailable Windows paths while retaining access errors", () => {
+ for (const [winerror, absent] of [
+ [21, true],
+ [123, true],
+ [5, false],
+ [32, false],
+ ] as const) {
+ const native = {
+ windowsAbsolutePath: (path: Buffer) => ({ error: 0, value: path }),
+ openWindowsFile: () => ({ error: winerror, handle: null }),
+ } as unknown as Parameters<typeof windowsFileSystem>[0];
+ assert.throws(
+ () =>
+ windowsFileSystem(native).stat(Buffer.from("R:\\marker", "utf16le")),
+ (error: unknown) => {
+ assert.equal((error as { winerror: number }).winerror, winerror);
+ assert.equal(isMissingPathError(error), absent);
+ return true;
+ },
+ );
+ }
+});
+
+test("resolved text preserves ordinary paths, aliases, and missing suffixes", async () => {
+ const root = await directories.create("helper-path-");
+ const target = join(root, "target");
+ const alias = join(root, "alias");
+ await mkdir(target);
+ await symlink(
+ target,
+ alias,
+ process.platform === "win32" ? "junction" : "dir",
+ );
+ assert.equal(resolvedPathText(target), target);
+ assert.equal(resolvedPathText(alias), target);
+ assert.equal(
+ resolvedPathText(join(alias, "missing"), false),
+ join(target, "missing"),
+ );
+ assert.throws(
+ () => resolvedPathText(join(alias, "missing")),
+ /ENOENT|filesystem error/u,
+ );
+ if (process.platform !== "win32")
+ assert.throws(
+ () => resolvedPathText(`${root}/missing/../target`, false),
+ /ENOENT/u,
+ );
+});
+
+test(
+ "Windows resolution keeps an explicitly requested namespace",
+ { skip: process.platform !== "win32" },
+ async () => {
+ const root = await directories.create("helper-namespace-");
+ const namespaced = win32.toNamespacedPath(root);
+ assert.equal(resolvedPathText(namespaced), namespaced);
+ assert.equal(
+ resolvedPathText(join(namespaced, "missing"), false),
+ join(namespaced, "missing"),
+ );
+ },
+);
+
+test(
+ "Windows display spelling still identifies a raw target through a junction",
+ { skip: process.platform !== "win32" },
+ async () => {
+ const root = await directories.create("helper-raw-path-");
+ const ordinary = join(root, "target");
+ const raw = `${win32.toNamespacedPath(ordinary)}. `;
+ const alias = join(root, "alias");
+ await mkdir(ordinary);
+ await mkdir(raw);
+ try {
+ await symlink(raw, alias, "junction");
+ const display = resolvedPathText(alias);
+ // An ordinary alias must never select the neighboring trimmed directory.
+ assert.notEqual(display, ordinary);
+ assert.equal(resolvedPathText(win32.toNamespacedPath(display)), raw);
+ } finally {
+ await rm(alias, { recursive: true, force: true });
+ await rm(raw, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/plugins/codex-security/mcp-app/tests/test_node_launcher.ts b/plugins/codex-security/mcp-app/tests/test_node_launcher.ts
new file mode 100644
index 000000000..5f395ce76
--- /dev/null
+++ b/plugins/codex-security/mcp-app/tests/test_node_launcher.ts
@@ -0,0 +1,388 @@
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import {
+ copyFile,
+ mkdir,
+ readdir,
+ readFile,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
+import path from "node:path";
+import { after, test } from "node:test";
+import { nativeTarget } from "../../native/platform.mts";
+import { createTemporaryDirectories } from "./support/temporary-directories.ts";
+
+const directories = createTemporaryDirectories(true);
+after(() => directories.cleanup());
+const sourcePluginRoot = path.resolve(import.meta.dirname, "../..");
+const pluginRoot = process.env.CODEX_SECURITY_TEST_PLUGIN_ROOT
+ ? path.resolve(process.env.CODEX_SECURITY_TEST_PLUGIN_ROOT)
+ : path.resolve(sourcePluginRoot, "../../sdk/typescript/_bundled_plugin");
+
+function shellQuote(value: string): string {
+ return "'" + value.replaceAll("'", "'\\''") + "'";
+}
+
+async function fixture(
+ rejectManaged: boolean,
+ rejectOrdinary = false,
+ nativeCommand = false,
+ ordinaryHasSqlite = true,
+) {
+ const root = await directories.create("codex-security-node-launcher-");
+ const launcher = path.join(root, "scripts", "launch_codex_security_mcp");
+ const mcp = path.join(root, "mcp");
+ const addon = path.join(mcp, "native", `darwin-${process.arch}`, "unix.node");
+ const log = path.join(root, "loads.jsonl");
+ const launchLog = path.join(root, "launches.jsonl");
+ const repo = path.join(root, "repo");
+ await Promise.all(
+ [path.dirname(launcher), path.dirname(addon), repo].map((directory) =>
+ mkdir(directory, { recursive: true }),
+ ),
+ );
+ // Keep host-installed Node runtimes out of the simulated macOS runtime set.
+ const tools = path.join(root, "shell-tools");
+ await mkdir(tools);
+ for (const name of ["dirname", "od", "tr"]) {
+ const executable = spawnSync("/bin/sh", ["-c", `command -v ${name}`], {
+ encoding: "utf8",
+ }).stdout.trim();
+ await symlink(executable, path.join(tools, name));
+ }
+ const source = await readFile(
+ path.join(sourcePluginRoot, "scripts", path.basename(launcher)),
+ "utf8",
+ );
+ await writeFile(
+ launcher,
+ source.replace(/^PATH=.*$/m, `PATH="\${PATH}:"${shellQuote(tools)}`),
+ );
+ for (const entry of await readdir(path.join(pluginRoot, "mcp"), {
+ withFileTypes: true,
+ })) {
+ if (entry.isFile())
+ await copyFile(
+ path.join(pluginRoot, "mcp", entry.name),
+ path.join(mcp, entry.name),
+ );
+ }
+ await copyFile(
+ path.join(pluginRoot, "mcp", "native", nativeTarget, "unix.node"),
+ addon,
+ );
+ if (nativeCommand)
+ await writeFile(
+ path.join(mcp, "helpers.mjs"),
+ `import { createRequire } from "node:module";
+try {
+ createRequire(import.meta.url)(${JSON.stringify(addon)});
+ console.log(JSON.stringify({ status: "ready" }));
+} catch (error) {
+ console.log(JSON.stringify({ status: "error", error: error.message }));
+ process.exitCode = 2;
+}
+`,
+ );
+ await writeFile(
+ path.join(repo, "SECURITY.md"),
+ "Synthetic repository policy.\n",
+ );
+
+ async function runtime(label: string, executable: string, reject: boolean) {
+ const preload = path.join(root, `${label}.cjs`);
+ await mkdir(path.dirname(executable), { recursive: true });
+ await writeFile(
+ preload,
+ `
+const { appendFileSync } = require("node:fs");
+appendFileSync(${JSON.stringify(launchLog)}, JSON.stringify({ runtime: ${JSON.stringify(label)}, argv: process.argv.slice(1) }) + "\\n");
+Object.defineProperty(process, "platform", { value: "darwin" });
+const Module = require("node:module");
+const load = Module._load;
+Module._load = function(request, ...args) {
+ if (${JSON.stringify(label === "ordinary" && !ordinaryHasSqlite)} && request === "node:sqlite")
+ throw new Error("No such built-in module: node:sqlite");
+ return load.call(this, request, ...args);
+};
+const dlopen = process.dlopen;
+process.dlopen = function(module, filename, ...args) {
+ appendFileSync(${JSON.stringify(log)}, JSON.stringify({ runtime: ${JSON.stringify(label)}, filename, argv: process.argv.slice(1) }) + "\\n");
+ ${reject ? 'throw new Error("dlopen: mapping process and mapped file have different Team IDs");' : "return dlopen.call(this, module, filename, ...args);"}
+};
+`,
+ );
+ await writeFile(
+ executable,
+ `#!/bin/sh\nexec ${shellQuote(process.execPath)} --require ${shellQuote(preload)} "$@"\n`,
+ { mode: 0o755 },
+ );
+ return executable;
+ }
+
+ const managed = await runtime(
+ "managed",
+ path.join(
+ root,
+ "codex-runtimes/codex-primary-runtime/dependencies/node/bin/node",
+ ),
+ rejectManaged,
+ );
+ const ordinary = await runtime(
+ "ordinary",
+ path.join(root, "bin", "node"),
+ rejectOrdinary,
+ );
+ const env: NodeJS.ProcessEnv = {
+ ...process.env,
+ HOME: root,
+ CODEX_HOME: root,
+ PATH: path.dirname(ordinary),
+ XDG_CACHE_HOME: root,
+ };
+ for (const name of [
+ "CODEX_MCP_NODE_PATH",
+ "CODEX_BROWSER_USE_NODE_PATH",
+ "CODEX_ELECTRON_RESOURCES_PATH",
+ "CODEX_CLI_PATH",
+ "CODEX_SECURITY_CONFIG_PATH",
+ ])
+ delete env[name];
+ return {
+ root,
+ repo,
+ addon,
+ managed,
+ ordinary,
+ async addPathRuntime() {
+ const executable = await runtime(
+ "later",
+ path.join(root, "later-bin", "node"),
+ false,
+ );
+ env.PATH += path.delimiter + path.dirname(executable);
+ },
+ run(args: string[], override?: string, input = "preserved helper input\n") {
+ return spawnSync("/bin/sh", [launcher, "--helper", ...args], {
+ cwd: root,
+ env: {
+ ...env,
+ ...(override === undefined ? {} : { CODEX_MCP_NODE_PATH: override }),
+ },
+ encoding: "utf8",
+ input,
+ });
+ },
+ async loads() {
+ return (await readFile(log, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ },
+ async launches() {
+ return (await readFile(launchLog, "utf8"))
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ },
+ };
+}
+
+test(
+ "macOS helpers skip managed runtimes that reject the packaged addon",
+ { skip: process.platform === "win32" },
+ async () => {
+ for (const command of ["synthetic-native-helper", "resolve-security-md"]) {
+ const setup = await fixture(
+ true,
+ false,
+ command === "synthetic-native-helper",
+ );
+ const result = setup.run(
+ command === "synthetic-native-helper"
+ ? [command]
+ : [command, "--repo", setup.repo, "--list"],
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, "");
+ if (command === "synthetic-native-helper")
+ assert.equal(JSON.parse(result.stdout).status, "ready");
+ else assert.deepEqual(JSON.parse(result.stdout), ["SECURITY.md"]);
+ const loads = await setup.loads();
+ assert.deepEqual(
+ loads.slice(0, 2).map((entry) => entry.runtime),
+ ["managed", "ordinary"],
+ );
+ assert.equal(loads[0].filename, setup.addon);
+ assert.equal(loads[1].filename, setup.addon);
+ assert.equal(
+ loads.filter((entry) => entry.runtime === "managed").length,
+ 1,
+ "Rejected runtimes must only probe; helpers must not start in them.",
+ );
+ if (command === "synthetic-native-helper")
+ assert.ok(
+ loads.length > 2,
+ "The native helper must load the actual packaged addon.",
+ );
+ }
+ },
+);
+
+test(
+ "macOS helpers try later PATH runtimes after an incompatible first runtime",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(true, true, true);
+ await setup.addPathRuntime();
+ const result = setup.run(["synthetic-native-helper"]);
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(JSON.parse(result.stdout).status, "ready");
+ assert.deepEqual(
+ (await setup.loads()).slice(0, 3).map((entry) => entry.runtime),
+ ["managed", "ordinary", "later"],
+ );
+ assert.deepEqual(
+ (await setup.launches())
+ .filter((entry) => entry.argv.includes("--helper"))
+ .map((entry) => entry.runtime),
+ ["later"],
+ );
+ },
+);
+
+test(
+ "compatible managed runtimes retain priority over PATH",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(false);
+ const result = setup.run([
+ "resolve-security-md",
+ "--repo",
+ setup.repo,
+ "--list",
+ ]);
+ assert.equal(result.status, 0, result.stderr);
+ assert.ok(
+ (await setup.loads()).every((entry) => entry.runtime === "managed"),
+ );
+ },
+);
+
+test(
+ "explicit runtime selection remains authoritative",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(true, false, true);
+ const result = setup.run(["synthetic-native-helper"], setup.managed);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stdout, /different Team IDs/);
+ const loads = await setup.loads();
+ assert.ok(loads.every((entry) => entry.runtime === "managed"));
+ assert.ok(
+ loads[0].argv.includes("--helper"),
+ "Explicit runtimes launch directly.",
+ );
+ },
+);
+
+test(
+ "helper failures are reported without trying another runtime",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(false);
+ const result = setup.run([
+ "resolve-security-md",
+ "--repo",
+ path.join(setup.root, "missing"),
+ "--list",
+ ]);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr, /missing/);
+ assert.ok(
+ (await setup.loads()).every((entry) => entry.runtime === "managed"),
+ );
+ },
+);
+
+test(
+ "helpers without native dependencies still run when all runtimes reject the addon",
+ { skip: process.platform === "win32" },
+ async () => {
+ for (const command of [
+ "validate-patch-risk-assessment",
+ "resolve-security-md",
+ ]) {
+ const setup = await fixture(true, true);
+ const result = setup.run(
+ command === "resolve-security-md"
+ ? [command, "--repo", setup.repo, "--list"]
+ : [command, "--help"],
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stderr, "");
+ if (command === "resolve-security-md")
+ assert.deepEqual(JSON.parse(result.stdout), ["SECURITY.md"]);
+ else assert.match(result.stdout, /usage:/i);
+ assert.deepEqual(
+ (await setup.loads()).map((entry) => entry.runtime),
+ ["managed", "ordinary"],
+ );
+ const helpers = (await setup.launches()).filter((entry) =>
+ entry.argv.includes("--helper"),
+ );
+ assert.deepEqual(
+ helpers.map((entry) => entry.runtime),
+ ["managed"],
+ "The original default must launch the command exactly once.",
+ );
+ }
+ },
+);
+
+test(
+ "native commands retain their error when no compatible runtime exists",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(true, true, true);
+ const result = setup.run(["synthetic-native-helper"]);
+ assert.equal(result.status, 2);
+ assert.equal(result.stderr, "");
+ const report = JSON.parse(result.stdout);
+ assert.equal(report.status, "error");
+ assert.match(report.error, /different Team IDs/);
+ assert.deepEqual(
+ (await setup.loads()).map((entry) => entry.runtime),
+ ["managed", "ordinary", "managed"],
+ );
+ const helpers = (await setup.launches()).filter((entry) =>
+ entry.argv.includes("--helper"),
+ );
+ assert.deepEqual(
+ helpers.map((entry) => entry.runtime),
+ ["managed"],
+ "A failing command must not retry in another runtime.",
+ );
+ },
+);
+
+test(
+ "database helpers retain the managed runtime when PATH Node lacks SQLite",
+ { skip: process.platform === "win32" },
+ async () => {
+ const setup = await fixture(true, false, false, false);
+ const result = setup.run(
+ ["database-info"],
+ undefined,
+ JSON.stringify(setup.root),
+ );
+ assert.equal(result.status, 0, result.stderr);
+ assert.deepEqual(
+ (await setup.launches())
+ .filter((entry) => entry.argv.includes("--helper"))
+ .map((entry) => entry.runtime),
+ ["managed"],
+ );
+ },
+);
diff --git a/plugins/codex-security/scripts/launch_codex_security_mcp b/plugins/codex-security/scripts/launch_codex_security_mcp
index 6e9847ff5..f19251085 100755
--- a/plugins/codex-security/scripts/launch_codex_security_mcp
+++ b/plugins/codex-security/scripts/launch_codex_security_mcp
@@ -47,20 +47,55 @@ case "${CODEX_CLI_PATH:-}" in
*/*) codex_resources=${CODEX_CLI_PATH%/*} ;;
esac
+# An explicitly selected runtime remains authoritative.
+if [ -n "${CODEX_MCP_NODE_PATH:-}" ] && [ -x "$CODEX_MCP_NODE_PATH" ]; then
+ launch_node "$CODEX_MCP_NODE_PATH" "$@"
+fi
+
+first_node=
+can_load_native() {
+ if [ -z "$first_node" ]; then
+ first_node=$1
+ fi
+ # Some managed macOS runtimes enforce library validation and cannot load the
+ # plugin's addon. Check before starting a server or helper with side effects.
+ # Capture output without opening a writable file for read-only callers.
+ _native_probe_output=$("$1" -e '
+ if (process.platform === "darwin") {
+ require("node:sqlite");
+ require(require("node:path").join(process.argv[1], "native",
+ `${process.platform}-${process.arch}`, "unix.node"));
+ }
+ ' "$launcher_dir/../mcp" </dev/null 2>&1)
+}
+
for candidate in \
- "${CODEX_MCP_NODE_PATH:-}" \
"${CODEX_BROWSER_USE_NODE_PATH:-}" \
"${CODEX_ELECTRON_RESOURCES_PATH:-}/cua_node/bin/node" \
"$codex_resources/cua_node/bin/node" \
"$cache_root/codex-runtimes/codex-primary-runtime/dependencies/node/bin/node"
do
- if [ -n "$candidate" ] && [ -x "$candidate" ]; then
+ if [ -n "$candidate" ] && [ -x "$candidate" ] && can_load_native "$candidate"; then
launch_node "$candidate" "$@"
fi
done
-if node_path=$(command -v node); then
- launch_node "$node_path" "$@"
+remaining_path=$PATH
+while :; do
+ path_entry=${remaining_path%%:*}
+ node_path=${path_entry:-.}/node
+ if [ -x "$node_path" ] && can_load_native "$node_path"; then
+ launch_node "$node_path" "$@"
+ fi
+ case "$remaining_path" in
+ *:*) remaining_path=${remaining_path#*:} ;;
+ *) break ;;
+ esac
+done
+
+if [ -n "$first_node" ]; then
+ # Helpers that do not use the addon can still run with the original default.
+ launch_node "$first_node" "$@"
fi
printf '%s\n' 'Codex Security could not find a Node runtime. Reinstall or update Codex, or set CODEX_MCP_NODE_PATH to an executable Node runtime.' >&2
diff --git a/sdk/typescript/tests-ts/mcp-launcher.test.ts b/sdk/typescript/tests-ts/mcp-launcher.test.ts
index 2cd297597..156a8bc1e 100644
--- a/sdk/typescript/tests-ts/mcp-launcher.test.ts
+++ b/sdk/typescript/tests-ts/mcp-launcher.test.ts
@@ -115,6 +115,118 @@ test.skipIf(process.platform !== "win32")(
},
);
+test.skipIf(process.platform !== "win32")(
+ "explicit Windows Node selection precedes every relocated runtime cache",
+ async () => {
+ const node = Bun.which("node");
+ if (node === null)
+ throw new Error("Node is required for the launcher test.");
+ const root = await realpath(
+ await mkdtemp(join(tmpdir(), "codex-security-runtime-precedence-")),
+ );
+ try {
+ const scripts = join(root, "plugin", "scripts");
+ const mcp = join(root, "plugin", "mcp");
+ const explicit = join(root, "explicit %RUNTIME% !RUNTIME!", "node.exe");
+ await Promise.all(
+ [scripts, mcp, dirname(explicit)].map((directory) =>
+ mkdir(directory, { recursive: true }),
+ ),
+ );
+ const launcher = join(scripts, "launch_codex_security_mcp.cmd");
+ await copyFile(
+ join(PLUGIN_ROOT, "scripts", "launch_codex_security_mcp.cmd"),
+ launcher,
+ );
+ await copyFile(node, explicit);
+ for (const script of ["server.mjs", "helpers.mjs"])
+ await writeFile(
+ join(mcp, script),
+ `import { readFileSync } from "node:fs";\nconsole.log(JSON.stringify({ executable: process.execPath, cwd: process.cwd(), args: process.argv.slice(2), input: readFileSync(0, "utf8") }));\nprocess.exitCode = 23;\n`,
+ );
+ const caches = {
+ LOCALAPPDATA: join(
+ root,
+ "OpenAI",
+ "Codex",
+ "runtimes",
+ "cua_node",
+ "fixture",
+ "bin",
+ "node.exe",
+ ),
+ XDG_CACHE_HOME: join(
+ root,
+ "codex-runtimes",
+ "codex-primary-runtime",
+ "dependencies",
+ "node",
+ "bin",
+ "node.exe",
+ ),
+ USERPROFILE: join(
+ root,
+ ".cache",
+ "codex-runtimes",
+ "codex-primary-runtime",
+ "dependencies",
+ "node",
+ "bin",
+ "node.exe",
+ ),
+ };
+ const argument = "argument with spaces %RUNTIME% !RUNTIME!";
+ for (const [name, cached] of Object.entries(caches)) {
+ await mkdir(dirname(cached), { recursive: true });
+ await copyFile(node, cached);
+ for (const helper of [false, true]) {
+ const args = helper ? ["--helper", "fixture-helper"] : ["--stdio"];
+ for (const override of [undefined, explicit]) {
+ const result = spawnSync(
+ join(process.env["SystemRoot"]!, "System32", "cmd.exe"),
+ [
+ "/d",
+ "/s",
+ "/c",
+ `""${launcher}" ${args.join(" ")} "%LAUNCH_ARGUMENT%""`,
+ ],
+ {
+ cwd: root,
+ env: {
+ SystemRoot: process.env["SystemRoot"],
+ PATH: "",
+ [name]: root,
+ LAUNCH_ARGUMENT: argument,
+ RUNTIME: "expanded-runtime",
+ ...(override === undefined
+ ? {}
+ : { CODEX_MCP_NODE_PATH: override }),
+ },
+ encoding: "utf8",
+ windowsHide: true,
+ windowsVerbatimArguments: true,
+ input: "launcher input\n",
+ },
+ );
+ expect(
+ result.status,
+ `${name}, helper=${helper}, override=${override !== undefined}: ${result.stderr || result.error?.message || ""}`,
+ ).toBe(23);
+ expect(JSON.parse(result.stdout)).toEqual({
+ executable: override ?? cached,
+ cwd: helper ? root : parse(launcher).root,
+ args: [...args, argument],
+ input: "launcher input\n",
+ });
+ }
+ }
+ }
+ } finally {
+ await removeTemporaryDirectory(root);
+ }
+ },
+);
+
test.skipIf(process.platform === "win32")(
"preserves helper argument bytes, stdin, and exit status",
async () => {
diff --git a/sdk/typescript/tests-ts/security-policy-helper.test.ts b/sdk/typescript/tests-ts/security-policy-helper.test.ts
index a1210b29b..ee1e8b655 100644
--- a/sdk/typescript/tests-ts/security-policy-helper.test.ts
+++ b/sdk/typescript/tests-ts/security-policy-helper.test.ts
@@ -708,6 +708,9 @@ binding.readdir = function (...args) {
const project = join(root, "project");
for (const [home, path] of [
[root, "~/project"],
+ [`${root}/`, "~/project"],
+ [`${root}///`, "~/project"],
+ ["/", `~${project}`],
[undefined, `~/${relative(userInfo().homedir, project)}`],
["", `~${project}`],
] as const) {