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

refactor(native): preserve process paths and environment values (#1429)

Michael D'Angelo1c409ceea2d7
diff --git a/plugins/codex-security/native/Cargo.toml b/plugins/codex-security/native/Cargo.toml
index e317e1342..f68a8143d 100644
--- a/plugins/codex-security/native/Cargo.toml
+++ b/plugins/codex-security/native/Cargo.toml
@@ -17,7 +17,7 @@ napi-derive = "=3.6.10"
libc = "=0.2.190"
[target.'cfg(windows)'.dependencies]
-windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Threading"] }
+windows-sys = { version = "=0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_Environment", "Win32_System_Threading", "Win32_System_JobObjects"] }
[build-dependencies]
napi-build = "=2.6.0"
diff --git a/plugins/codex-security/native/README.md b/plugins/codex-security/native/README.md
index d471d01cb..f618eddff 100644
--- a/plugins/codex-security/native/README.md
+++ b/plugins/codex-security/native/README.md
@@ -2,7 +2,7 @@
These internal bindings supply OS operations that Node does not expose. The `resolve-security-md` helper uses native account lookup on Unix and native path, file, and directory operations on Windows.
-The Unix Node-API 8 binding is typed in `binding.mts`. `userHome` looks up raw username bytes through the operating system and returns raw home-directory bytes or a missing result, without Git.
+The Unix Node-API 8 binding is typed in `binding.mts`. `userHome` looks up raw username bytes through the operating system and returns raw home-directory bytes or a missing result, without Git. `unixEnvironment` reads one named environment value as raw bytes, preserving the distinction between empty and unset values. This keeps configured filesystem locations such as `CODEX_HOME` intact when Node would replace undecodable bytes.
Install the pinned Rust toolchain and the existing TypeScript dependencies, then run from the repository root:
@@ -15,7 +15,7 @@ cargo +1.97.1 fmt --check --manifest-path plugins/codex-security/native/Cargo.to
cargo +1.97.1 clippy --locked --manifest-path plugins/codex-security/native/Cargo.toml -- -D warnings
```
-The proof runs without Python. It checks current and named account lookup, missing accounts, and embedded-NUL rejection. CI invokes it with an empty `PATH`.
+The proof runs without Python. It checks current and named account lookup, missing accounts, and embedded-NUL rejection. A shell-launched child verifies raw environment bytes, empty values and missing values. CI invokes it with an empty `PATH`.
Build outputs stay under ignored `target` and `dist` directories. Linux output directories include the C runtime: `linux-x64-gnu`, `linux-arm64-gnu`, `linux-x64-musl`, and `linux-arm64-musl`. The dependency-free `platform.mts` helper distinguishes glibc from musl using the Node diagnostic report header, without a subprocess. macOS and Windows retain their platform and architecture directories. Source, Cargo registry, and compiler paths are remapped before compilation; actual payload bytes are checked for private paths. Before an artifact is uploaded, run:
@@ -37,6 +37,12 @@ Four additional operations preserve Windows strings at the Node boundary. `windo
`windows-files.mts` uses native absolute and final paths, preserving raw UTF-16 and the returned device prefix. Non-strict `realpath` resolves the nearest existing ancestor of a missing path; dangling links and other access errors remain errors. Callers must check containment independently. It follows native Windows path behavior rather than emulating Python's special cases for device names, whitespace, verbatim dot segments, and prefix removal. `stat(path, false)` retains exact symbolic-link and reparse-point metadata so callers can reject junction traversal independently of the enumerator's link label. The SDK's public runtime floor remains Node 22.13.0. Node 20.0.0 is an additional native-foundation compatibility proof; it does not change the SDK engine requirement.
+Windows process arguments and working directories can also contain unpaired UTF-16 units. `windows-process.mts` runs a private Node subprocess shim that passes those values as bytes to `runWindowsProcess`; ordinary invocations still use Node directly. The native call inherits stdin, stdout, stderr, and the shim's environment. The shim joins a kill-on-close Job Object before starting the child and retains its handle until process exit. Descendants inherit membership, so terminating the shim also closes the child's streams. Startup errors return through Node IPC, separately from command stderr and exit status. The Windows proof checks raw arguments and working directories, binary stream forwarding, environment inheritance, exit status, startup errors, and termination cleanup. The file adapter's `readChunks` callback supports bounded reads and closes the handle when a consumer stops or throws.
+
+Target `NODE_OPTIONS`, `NODE_DEBUG`, and `NODE_EXTRA_CA_CERTS` values travel through the same environment override payload instead of affecting the private shim's startup. This preserves relative preloads and certificate paths in the target's working directory and keeps shim diagnostics out of the target's stderr. The one-command shim restores target environment overrides before lookup and changes to the target directory before launching it, so relative executable paths and `PATH` entries use that directory. Bare executable names also check that directory before Rust's `PATH` lookup, honoring the Windows current-directory search setting. The effective `PATH` is explicit in the target command, so its entries precede the shim's executable directory and Rust's parent-PATH fallback uses the same exact value. Early cancellation skips the IPC handoff and its cancellation-induced transport errors.
+
+Explicitly selected `.com` paths use `CreateProcessW` with that exact application name, because Rust's `Command` otherwise prefers an existing `.com.exe` sibling. This branch preserves UTF-16 arguments with CRT quoting, duplicates the shim's standard handles for inheritance, and uses the same restored environment, job lifetime, and error reporting. Other executables continue to use `Command`.
+
Build on Windows after compiling the TypeScript tools, then run:
```sh
diff --git a/plugins/codex-security/native/binding.mts b/plugins/codex-security/native/binding.mts
index 5f1a6f9ca..c6717dbba 100644
--- a/plugins/codex-security/native/binding.mts
+++ b/plugins/codex-security/native/binding.mts
@@ -10,8 +10,9 @@ export const binaryPath = join(
process.platform === "win32" ? "windows.node" : "unix.node",
);
-/** Usernames and home directories are uninterpreted POSIX bytes. */
+/** Usernames, home directories and environment values are uninterpreted POSIX bytes. */
export interface UnixBinding {
+ unixEnvironment(name: Buffer): Buffer | null;
userHome(username: Buffer): { errno: number; value: Buffer | null };
}
diff --git a/plugins/codex-security/native/proof-process-windows.mts b/plugins/codex-security/native/proof-process-windows.mts
new file mode 100644
index 000000000..d9975e2e1
--- /dev/null
+++ b/plugins/codex-security/native/proof-process-windows.mts
@@ -0,0 +1,648 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { copyFileSync, mkdirSync, readFileSync } from "node:fs";
+import { join, win32 } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { rootCertificates } from "node:tls";
+import { binaryPath } from "./binding.mjs";
+import { loadWindowsBinding } from "./windows-binding.mjs";
+import { widePath, windowsFileSystem } from "./windows-files.mjs";
+import { spawnWindowsProcess } from "./windows-process.mjs";
+
+async function processExit(
+ child: ReturnType<typeof spawnWindowsProcess>,
+ scenario: string,
+ options?: { signal: AbortSignal },
+) {
+ try {
+ return await once(child, "close", options);
+ } catch (cause) {
+ throw new Error(`Windows process proof failed: ${scenario}`, { cause });
+ }
+}
+
+export async function processProof(
+ root: string,
+): Promise<Record<string, boolean>> {
+ const native = loadWindowsBinding(),
+ files = windowsFileSystem(native);
+ const cwd = join(root, "process-\ud800");
+ files.mkdir(widePath(cwd));
+ const cleanupPaths = [cwd];
+ let proofError: unknown;
+ try {
+ const arguments_ = [
+ "high-\ud800",
+ "low-\udfff",
+ "replacement-�",
+ 'quote"and\\',
+ "",
+ "東京 😀",
+ ...[0, 1, 2, 3].flatMap((count) => [
+ `slashes${"\\".repeat(count)}"quote`,
+ `space ${"\\".repeat(count)}`,
+ ]),
+ ];
+ const script = `const fs=require('node:fs'), native=require(${JSON.stringify(binaryPath)}); const args=native.windowsArguments().slice(3).map(value=>value.toString('utf16le')); const cwd=native.windowsAbsolutePath(Buffer.from('.', 'utf16le')).value.toString('utf16le'); process.stderr.write(JSON.stringify({args,cwd,executable:process.execPath,setting:process.env.INVENTORY_PROCESS_FIXTURE,rawSetting:native.windowsEnvironment(Buffer.from("INVENTORY_PROCESS_RAW", "utf16le")).toString("utf16le")})); process.stdout.write(fs.readFileSync(0)); process.exitCode=23;`;
+ const child = spawnWindowsProcess(
+ binaryPath,
+ process.execPath,
+ ["-e", script, ...arguments_],
+ {
+ cwd,
+ env: { ...process.env, INVENTORY_PROCESS_FIXTURE: "inherited" },
+ stdio: ["pipe", "pipe", "pipe"],
+ },
+ { INVENTORY_PROCESS_RAW: "raw-\udfff" },
+ );
+ const stdout: Buffer[] = [],
+ stderr: Buffer[] = [];
+ child.stdout!.on("data", (data: Buffer) => stdout.push(data));
+ child.stderr!.on("data", (data: Buffer) => stderr.push(data));
+ const done = processExit(child, "raw arguments and cwd");
+ const bytes = Buffer.concat([
+ Buffer.from([0, 255, 128]),
+ Buffer.alloc(256 * 1024, 17),
+ ]);
+ child.stdin!.end(bytes);
+ assert.deepEqual(await done, [23, null]);
+ assert.deepEqual(Buffer.concat(stdout), bytes);
+ const result = JSON.parse(Buffer.concat(stderr).toString("utf8"));
+ assert.deepEqual(result.args, arguments_);
+ assert.equal(result.cwd.toLowerCase(), cwd.toLowerCase());
+ assert.equal(result.setting, "inherited");
+ assert.equal(result.rawSetting, "raw-\udfff");
+
+ const callerCwd = process.cwd();
+ const tools = join(root, "relative-tools");
+ mkdirSync(tools);
+ copyFileSync(process.execPath, join(tools, "process-probe.exe"));
+ copyFileSync(process.execPath, join(tools, "process-probe.com"));
+ copyFileSync(process.execPath, join(tools, "process-probe.com.exe"));
+ const relativeEnvironment = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) =>
+ !["PATH", "NODEFAULTCURRENTDIRECTORYINEXEPATH"].includes(
+ name.toUpperCase(),
+ ),
+ ),
+ );
+ for (const [executable, directory, path, selected] of [
+ ["process-probe", cwd, "..\\relative-tools", "process-probe.exe"],
+ [
+ "..\\relative-tools\\process-probe.exe",
+ cwd,
+ "..\\relative-tools",
+ "process-probe.exe",
+ ],
+ ["process-probe", tools, join(root, "absent-tools"), "process-probe.com"],
+ [
+ "process-probe.exe",
+ tools,
+ join(root, "absent-tools"),
+ "process-probe.exe",
+ ],
+ [
+ "process-probe.com",
+ tools,
+ join(root, "absent-tools"),
+ "process-probe.com",
+ ],
+ [
+ join(tools, "process-probe.com"),
+ cwd,
+ join(root, "absent-tools"),
+ "process-probe.com",
+ ],
+ ] as const) {
+ const relativeChild = spawnWindowsProcess(
+ binaryPath,
+ executable,
+ ["-e", script, ...arguments_],
+ {
+ cwd: directory,
+ env: {
+ ...relativeEnvironment,
+ PATH: path,
+ INVENTORY_PROCESS_FIXTURE: "relative target",
+ },
+ stdio: ["pipe", "pipe", "pipe"],
+ },
+ { INVENTORY_PROCESS_RAW: "raw-\udfff" },
+ );
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ relativeChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ relativeChild.stderr!.on("data", (data: Buffer) => errors.push(data));
+ const completed = processExit(
+ relativeChild,
+ `lookup ${JSON.stringify(executable)} in ${directory === cwd ? "raw cwd" : "tool cwd"}`,
+ );
+ relativeChild.stdin!.end(bytes);
+ assert.deepEqual(await completed, [23, null]);
+ assert.deepEqual(Buffer.concat(output), bytes);
+ assert.deepEqual(JSON.parse(Buffer.concat(errors).toString()), {
+ args: arguments_,
+ cwd: directory,
+ executable: join(tools, selected),
+ setting: "relative target",
+ rawSetting: "raw-\udfff",
+ });
+ assert.equal(process.cwd(), callerCwd);
+ }
+
+ const executableBytes = readFileSync(process.execPath);
+ const rawTools = join(root, "path-tools-\ud800"),
+ replacementTools = join(root, "path-tools-�");
+ const rawProbe = join(rawTools, "process-probe.exe"),
+ replacementProbe = join(replacementTools, "process-probe.exe");
+ files.mkdir(widePath(rawTools));
+ cleanupPaths.push(rawTools);
+ files.mkdir(widePath(replacementTools));
+ cleanupPaths.push(replacementTools);
+ files.writeFile(widePath(replacementProbe), executableBytes);
+ cleanupPaths.push(replacementProbe);
+ const callerPath = native.windowsEnvironment(widePath("PATH"));
+ const rawPathEnvironment = {
+ ...relativeEnvironment,
+ PATH: replacementTools,
+ NoDefaultCurrentDirectoryInExePath: "1",
+ };
+ const rawPathSnapshot = { ...rawPathEnvironment };
+ for (const available of [false, true]) {
+ if (available) {
+ files.writeFile(widePath(rawProbe), executableBytes);
+ cleanupPaths.push(rawProbe);
+ }
+ // Model Node's lossy shim PATH separately from the exact target override.
+ const pathChild = spawnWindowsProcess(
+ binaryPath,
+ "process-probe",
+ [
+ "-e",
+ `const native=require(${JSON.stringify(binaryPath)}); process.stdout.write(JSON.stringify({args:native.windowsArguments().slice(3).map(value=>value.toString('utf16le')),path:native.windowsEnvironment(Buffer.from('PATH','utf16le')).toString('utf16le')}));`,
+ ...arguments_,
+ ],
+ {
+ cwd,
+ env: rawPathEnvironment,
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ { PATH: rawTools },
+ );
+ const output: Buffer[] = [],
+ diagnostics: Buffer[] = [];
+ pathChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ pathChild.stderr!.on("data", (data: Buffer) => diagnostics.push(data));
+ if (available) {
+ assert.deepEqual(
+ await processExit(pathChild, "raw PATH collision with target tool"),
+ [0, null],
+ );
+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {
+ args: arguments_,
+ path: rawTools,
+ });
+ } else {
+ const errors: NodeJS.ErrnoException[] = [];
+ pathChild.on("error", (error) => errors.push(error));
+ await new Promise<void>((resolve) =>
+ pathChild.once("close", () => resolve()),
+ );
+ assert.deepEqual(
+ errors.map((error) => error.code),
+ ["WINDOWS_PROCESS_ERROR"],
+ "raw PATH must not fall back to the replacement PATH tool",
+ );
+ assert.equal(Buffer.concat(output).length, 0);
+ }
+ assert.equal(Buffer.concat(diagnostics).toString(), "");
+ assert.deepEqual(rawPathEnvironment, rawPathSnapshot);
+ assert.deepEqual(native.windowsEnvironment(widePath("PATH")), callerPath);
+ assert.equal(process.cwd(), callerCwd);
+ }
+
+ const longTools = join(
+ root,
+ ...[0, 1, 2, 3].map((i) => `${i}-${"x".repeat(70)}`),
+ );
+ files.mkdir(widePath(longTools));
+ const rawCom = join(longTools, "program-\udfff.com");
+ files.writeFile(widePath(rawCom), executableBytes);
+ cleanupPaths.push(rawCom);
+ files.writeFile(widePath(`${rawCom}.exe`), executableBytes);
+ cleanupPaths.push(`${rawCom}.exe`);
+ for (const executable of [rawCom, win32.toNamespacedPath(rawCom)]) {
+ const exactChild = spawnWindowsProcess(
+ binaryPath,
+ executable,
+ [
+ "-e",
+ `const native=require(${JSON.stringify(binaryPath)}); process.stdout.write(JSON.stringify({selected:process.execPath.endsWith('.com'),args:native.windowsArguments().slice(3).map(value=>value.toString('utf16le'))}));`,
+ ...arguments_,
+ ],
+ { cwd, stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ exactChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ exactChild.stderr!.on("data", (data: Buffer) => errors.push(data));
+ assert.deepEqual(
+ await processExit(
+ exactChild,
+ `${executable === rawCom ? "ordinary" : "namespaced"} long raw .com (${executable.length} UTF-16 units)`,
+ ),
+ [0, null],
+ );
+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {
+ selected: true,
+ args: arguments_,
+ });
+ assert.equal(Buffer.concat(errors).toString(), "");
+ }
+
+ const shimTools = join(root, "shim-tools");
+ mkdirSync(shimTools);
+ copyFileSync(process.execPath, join(shimTools, "node.exe"));
+ copyFileSync(process.execPath, join(shimTools, "process-probe.exe"));
+ for (const overridePath of [undefined, tools]) {
+ const originalNode = process.execPath;
+ let selectedChild: ReturnType<typeof spawnWindowsProcess>;
+ try {
+ process.execPath = join(shimTools, "node.exe");
+ selectedChild = spawnWindowsProcess(
+ binaryPath,
+ "process-probe",
+ [
+ "-e",
+ "process.stdout.write(JSON.stringify({executable:process.execPath,path:process.env.PATH,setting:process.env.INVENTORY_PROCESS_FIXTURE}));",
+ ],
+ {
+ cwd,
+ env: {
+ ...relativeEnvironment,
+ PATH: overridePath === undefined ? tools : shimTools,
+ INVENTORY_PROCESS_FIXTURE: "selected target",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ overridePath === undefined ? {} : { Path: overridePath },
+ );
+ } finally {
+ process.execPath = originalNode;
+ }
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ selectedChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ selectedChild.stderr!.on("data", (data: Buffer) => errors.push(data));
+ assert.deepEqual(
+ await processExit(
+ selectedChild,
+ `PATH collision (override=${overridePath !== undefined})`,
+ ),
+ [0, null],
+ );
+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {
+ executable: join(tools, "process-probe.exe"),
+ path: tools,
+ setting: "selected target",
+ });
+ assert.equal(Buffer.concat(errors).toString(), "");
+ }
+
+ const disabledCwdSearch = spawnWindowsProcess(
+ binaryPath,
+ "process-probe",
+ [],
+ {
+ cwd: tools,
+ env: {
+ ...relativeEnvironment,
+ PATH: join(root, "absent-tools"),
+ NoDefaultCurrentDirectoryInExePath: "1",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ const searchErrors: Error[] = [];
+ disabledCwdSearch.on("error", (error) => searchErrors.push(error));
+ disabledCwdSearch.stdout!.resume();
+ disabledCwdSearch.stderr!.resume();
+ await new Promise<void>((resolve) =>
+ disabledCwdSearch.once("close", () => resolve()),
+ );
+ assert.equal(searchErrors.length, 1);
+
+ for (const [key, override] of [
+ ["NODE_DEBUG", undefined],
+ ["Node_Debug", undefined],
+ ["NODE_DEBUG", "module,net"],
+ ] as const) {
+ const env = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "NODE_DEBUG",
+ ),
+ );
+ env["node_debug"] = "ignored duplicate";
+ env[key] = "module";
+ const snapshot = { ...env };
+ const debugChild = spawnWindowsProcess(
+ binaryPath,
+ process.env["ComSpec"]!,
+ ["/d", "/c", "echo %NODE_DEBUG%"],
+ { cwd, env, stdio: ["ignore", "pipe", "pipe"] },
+ override === undefined ? {} : { Node_Debug: override },
+ );
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ debugChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ debugChild.stderr!.on("data", (data: Buffer) => errors.push(data));
+ assert.deepEqual(await processExit(debugChild, `target debug ${key}`), [
+ 0,
+ null,
+ ]);
+ assert.equal(
+ Buffer.concat(output).toString().trim(),
+ override ?? "module",
+ );
+ assert.equal(Buffer.concat(errors).toString(), "");
+ assert.deepEqual(env, snapshot);
+ }
+
+ files.writeFile(
+ widePath(join(root, "target-certificates.pem")),
+ Buffer.from(rootCertificates[0]!),
+ );
+ for (const [key, inheritedCertificate, override] of [
+ ["NODE_EXTRA_CA_CERTS", "target-certificates.pem", undefined],
+ ["Node_Extra_Ca_Certs", "target-certificates.pem", undefined],
+ [
+ "NODE_EXTRA_CA_CERTS",
+ "missing-certificates.pem",
+ "target-certificates.pem",
+ ],
+ ] as const) {
+ const env = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "NODE_EXTRA_CA_CERTS",
+ ),
+ );
+ env["node_extra_ca_certs"] = "missing-duplicate.pem";
+ env[key] = inheritedCertificate;
+ const snapshot = { ...env };
+ const certificateChild = spawnWindowsProcess(
+ binaryPath,
+ process.execPath,
+ [
+ "-e",
+ "process.stdout.write(process.env.NODE_EXTRA_CA_CERTS); process.exitCode=2;",
+ ],
+ { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] },
+ override === undefined ? {} : { Node_Extra_Ca_Certs: override },
+ );
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ certificateChild.stdout!.on("data", (data: Buffer) => output.push(data));
+ certificateChild.stderr!.on("data", (data: Buffer) => errors.push(data));
+ assert.deepEqual(
+ await processExit(
+ certificateChild,
+ `target certificates ${key} (override=${override !== undefined})`,
+ ),
+ [2, null],
+ );
+ assert.equal(Buffer.concat(output).toString(), "target-certificates.pem");
+ assert.equal(Buffer.concat(errors).toString(), "");
+ assert.deepEqual(env, snapshot);
+ }
+
+ const moduleOptions = "--input-type=module";
+ const moduleChild = spawnWindowsProcess(
+ binaryPath,
+ process.execPath,
+ [
+ "-e",
+ "import process from 'node:process'; process.stdout.write(process.env.NODE_OPTIONS);",
+ ],
+ {
+ cwd,
+ env: { ...process.env, NODE_OPTIONS: moduleOptions },
+ stdio: ["ignore", "pipe", "pipe"],
+ },
+ );
+ const moduleOutput: Buffer[] = [];
+ moduleChild.stdout!.on("data", (data: Buffer) => moduleOutput.push(data));
+ moduleChild.stderr!.resume();
+ assert.deepEqual(await processExit(moduleChild, "target module options"), [
+ 0,
+ null,
+ ]);
+ assert.equal(Buffer.concat(moduleOutput).toString("utf8"), moduleOptions);
+
+ files.writeFile(
+ widePath(join(root, "hook.cjs")),
+ Buffer.from("process.env.INVENTORY_PRELOAD = 'cjs';"),
+ );
+ files.writeFile(
+ widePath(join(root, "preload.mjs")),
+ Buffer.from("process.env.INVENTORY_PRELOAD = 'esm';"),
+ );
+ for (const [key, nodeOptions, expected, override] of [
+ ["NODE_OPTIONS", "--require ./hook.cjs", "cjs", undefined],
+ ["Node_Options", "--import=./preload.mjs", "esm", undefined],
+ ["NODE_OPTIONS", "--require ./absent.cjs", "cjs", "--require ./hook.cjs"],
+ ] as const) {
+ const env = Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([name]) => name.toUpperCase() !== "NODE_OPTIONS",
+ ),
+ );
+ if (key === "NODE_OPTIONS" && override === undefined)
+ env["node_options"] = "--require ./absent.cjs";
+ env[key] = nodeOptions;
+ const snapshot = { ...env };
+ const preloaded = spawnWindowsProcess(
+ binaryPath,
+ process.execPath,
+ [
+ "-e",
+ "process.stdout.write(JSON.stringify({options:process.env.NODE_OPTIONS,preloaded:process.env.INVENTORY_PRELOAD}));",
+ ],
+ { cwd: root, env, stdio: ["ignore", "pipe", "pipe"] },
+ override === undefined ? {} : { Node_Options: override },
+ );
+ const output: Buffer[] = [],
+ errors: Buffer[] = [];
+ preloaded.stdout!.on("data", (data: Buffer) => output.push(data));
+ preloaded.stderr!.on("data", (data: Buffer) => errors.push(data));
+ assert.deepEqual(
+ await processExit(
+ preloaded,
+ `target preload ${key} (override=${override !== undefined})`,
+ ),
+ [0, null],
+ Buffer.concat(errors).toString(),
+ );
+ assert.deepEqual(JSON.parse(Buffer.concat(output).toString()), {
+ options: override ?? nodeOptions,
+ preloaded: expected,
+ });
+ assert.deepEqual(env, snapshot);
+ }
+
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const quick = spawnWindowsProcess(
+ binaryPath,
+ process.execPath,
+ ["-e", "process.exit(19)"],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ assert.deepEqual(await processExit(quick, `quick exit ${attempt}`), [
+ 19,
+ null,
+ ]);
+ }
+ for (const malformed of [Buffer.from([1]), widePath("bad\0value")])
+ assert.throws(() =>
+ native.runWindowsProcess(widePath(process.execPath), [malformed]),
+ );
+ const missing = spawnWindowsProcess(
+ binaryPath,
+ join(cwd, "absent-\udfff.exe"),
+ [],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const errors: Error[] = [];
+ missing.on("error", (error) => errors.push(error));
+ await new Promise<void>((resolve) =>
+ missing.once("close", () => resolve()),
+ );
+ assert.equal(errors.length, 1);
+ assert(errors[0]!.message.length > 0);
+
+ const originalExecutable = process.execPath;
+ let missingShim: ReturnType<typeof spawnWindowsProcess>;
+ try {
+ process.execPath = join(root, "absent-node.exe");
+ missingShim = spawnWindowsProcess(binaryPath, originalExecutable, [], {
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ } finally {
+ process.execPath = originalExecutable;
+ }
+ const shimErrors: NodeJS.ErrnoException[] = [];
+ missingShim.on("error", (error) => shimErrors.push(error));
+ await new Promise<void>((resolve) =>
+ missingShim.once("close", () => resolve()),
+ );
+ assert.deepEqual(
+ shimErrors.map((error) => error.code),
+ ["ENOENT"],
+ );
+
+ for (const mode of ["abort", "kill"] as const) {
+ const controller = new AbortController();
+ const cancelled = spawnWindowsProcess(binaryPath, process.execPath, [], {
+ stdio: ["ignore", "pipe", "pipe"],
+ ...(mode === "abort" ? { signal: controller.signal } : {}),
+ });
+ const errors: NodeJS.ErrnoException[] = [];
+ cancelled.on("error", (error) => errors.push(error));
+ const closed = new Promise<void>((resolve) =>
+ cancelled.once("close", () => resolve()),
+ );
+ if (mode === "abort") controller.abort();
+ else assert.equal(cancelled.kill(), true);
+ await closed;
+ assert.deepEqual(
+ errors.map((error) => error.code),
+ mode === "abort" ? ["ABORT_ERR"] : [],
+ );
+ }
+
+ // Descendant readiness proves that closing the shim also closes every inherited pipe.
+ for (const executable of [
+ process.execPath,
+ join(tools, "process-probe.com"),
+ ]) {
+ const hanging = spawnWindowsProcess(
+ binaryPath,
+ executable,
+ [
+ "-e",
+ "require('node:child_process').spawn(process.execPath, ['-e', \"process.stdout.write('ready'); setInterval(()=>{},1000)\"], {stdio:'inherit'}); setInterval(()=>{},1000)",
+ "raw-\ud800",
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+ const closed = processExit(
+ hanging,
+ `descendant cancellation ${JSON.stringify(executable)}`,
+ {
+ signal: AbortSignal.timeout(10_000),
+ },
+ );
+ await once(hanging.stdout!, "data", {
+ signal: AbortSignal.timeout(10_000),
+ });
+ assert.equal(hanging.kill(), true);
+ await closed;
+ assert(hanging.stdout!.readableEnded);
+ assert(hanging.stderr!.readableEnded);
+ }
+ return {
+ wideArgumentsAndCwd: true,
+ relativeExecutableAndPathUseTargetCwd: true,
+ bareExecutableUsesTargetCwd: true,
+ explicitComSelectionAndArgumentQuoting: true,
+ longAndNamespacedRawComPaths: true,
+ inheritedAndOverriddenPathPrecedeShimDirectory: true,
+ rawPathDoesNotFallBackToReplacementTool: true,
+ disabledCurrentDirectorySearchPreserved: true,
+ inheritedSettingsAndBinaryStreams: true,
+ targetDebugSettingsWithoutShimDiagnostics: true,
+ targetCertificatesWithoutShimDiagnostics: true,
+ inheritedModuleModeForTarget: true,
+ targetPreloadsAndOverrides: true,
+ exitAndSpawnErrors: true,
+ failedShimReportsOnce: true,
+ earlyCancellationReportsOnce: true,
+ killingShimClosesChildStreams: true,
+ killingShimClosesComDescendantStreams: true,
+ };
+ } catch (error) {
+ proofError = error;
+ throw error;
+ } finally {
+ const cleanupErrors: unknown[] = [];
+ for (const path of cleanupPaths.reverse()) {
+ try {
+ // Match package-fixture cleanup: exited Windows images can remain delete-pending.
+ for (let attempt = 0; ; attempt++) {
+ try {
+ files.unlink(widePath(path));
+ break;
+ } catch (error) {
+ if (
+ ![5, 32, 145].includes(
+ (error as { winerror: number }).winerror,
+ ) ||
+ attempt === 10
+ )
+ throw error;
+ await delay(100 * (attempt + 1));
+ }
+ }
+ } catch (error) {
+ cleanupErrors.push(error);
+ }
+ }
+ if (cleanupErrors.length)
+ throw new AggregateError(
+ proofError === undefined
+ ? cleanupErrors
+ : [proofError, ...cleanupErrors],
+ "Windows process proof fixture cleanup failed",
+ );
+ }
+}
diff --git a/plugins/codex-security/native/proof-windows-wide.mts b/plugins/codex-security/native/proof-windows-wide.mts
index cadd8ccd1..02e97b8c5 100644
--- a/plugins/codex-security/native/proof-windows-wide.mts
+++ b/plugins/codex-security/native/proof-windows-wide.mts
@@ -332,6 +332,29 @@ function worker(root: string): Record<string, boolean> {
["file-\udc80"],
);
+ const chunked = widePath(win32.join(cwd, "chunked"));
+ files.writeFile(chunked, [Buffer.alloc(64 * 1024 + 5, 17)]);
+ const sizes: number[] = [];
+ files.readChunks(chunked, (chunk) => {
+ sizes.push(chunk.length);
+ return true;
+ });
+ assert.deepEqual(sizes, [64 * 1024, 5]);
+ let reads = 0;
+ files.readChunks(chunked, () => {
+ reads++;
+ return false;
+ });
+ assert.equal(reads, 1);
+ assert.throws(
+ () =>
+ files.readChunks(chunked, () => {
+ throw new Error("consumer stopped");
+ }),
+ /consumer stopped/u,
+ );
+ files.unlink(chunked);
+
for (const malformed of [Buffer.from([0x61]), widePath("bad\0value")]) {
assert.throws(() => native.windowsEnvironment(malformed));
assert.throws(() => native.windowsAbsolutePath(malformed));
diff --git a/plugins/codex-security/native/proof-windows.mts b/plugins/codex-security/native/proof-windows.mts
index 81f312974..0171591b6 100644
--- a/plugins/codex-security/native/proof-windows.mts
+++ b/plugins/codex-security/native/proof-windows.mts
@@ -7,14 +7,15 @@ import {
readFileSync,
realpathSync,
renameSync,
- rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
+import { rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { basename, join, win32 } from "node:path";
import { setImmediate } from "node:timers/promises";
import { privateDirectoryProof } from "./proof-windows-acl.mjs";
+import { processProof } from "./proof-process-windows.mjs";
import { wideProcessProof } from "./proof-windows-wide.mjs";
import { windowsFileSystem } from "./windows-files.mjs";
import {
@@ -380,6 +381,7 @@ async function ownershipProof(root: string): Promise<boolean> {
const root = realpathSync.native(
mkdtempSync(join(tmpdir(), "codex-security-windows-")),
);
+let proofError: unknown;
try {
console.log(
JSON.stringify(
@@ -391,6 +393,7 @@ try {
handles: handleProof(root),
privateDirectories: privateDirectoryProof(root, native),
wideProcessAndPaths: wideProcessProof(root),
+ childProcesses: await processProof(root),
garbageCollectionClosesHandle: await ownershipProof(root),
fixture: basename(root),
},
@@ -398,6 +401,23 @@ try {
2,
),
);
+} catch (error) {
+ proofError = error;
+ throw error;
} finally {
- rmSync(root, { recursive: true, force: true });
+ try {
+ await rm(root, {
+ recursive: true,
+ force: true,
+ maxRetries: 10,
+ retryDelay: 100,
+ });
+ } catch (error) {
+ if (proofError !== undefined)
+ throw new AggregateError(
+ [proofError, error],
+ "Windows proof and cleanup failed",
+ );
+ throw error;
+ }
}
diff --git a/plugins/codex-security/native/proof.mts b/plugins/codex-security/native/proof.mts
index 1e7380b62..2cba7d618 100644
--- a/plugins/codex-security/native/proof.mts
+++ b/plugins/codex-security/native/proof.mts
@@ -1,6 +1,8 @@
import assert from "node:assert/strict";
import { userInfo } from "node:os";
import { randomUUID } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
import { loadBinding } from "./binding.mjs";
const native = loadBinding();
@@ -44,16 +46,64 @@ function accountProof() {
};
}
-console.log(
- JSON.stringify(
- {
- node: process.version,
- platform: process.platform,
- architecture: process.arch,
- nodeApi: 8,
- accounts: accountProof(),
- },
+function environmentProof(): Record<string, boolean> {
+ const script = [
+ "value=$(printf '\\377\\376\\012.'); value=${value%.}",
+ 'CODEX_SECURITY_ENV_PROOF_RAW="$value"; export CODEX_SECURITY_ENV_PROOF_RAW',
+ "CODEX_SECURITY_ENV_PROOF_EMPTY=''; export CODEX_SECURITY_ENV_PROOF_EMPTY",
+ "unset CODEX_SECURITY_ENV_PROOF_ABSENT",
+ 'exec "$1" "$2" environment-child',
+ ].join("\n");
+ const child = spawnSync(
+ "/bin/sh",
+ [
+ "-c",
+ script,
+ "environment-proof",
+ process.execPath,
+ fileURLToPath(import.meta.url),
+ ],
+ { encoding: "utf8" },
+ );
+ assert.equal(child.error, undefined);
+ assert.equal(child.status, 0, child.stderr);
+ assert.equal(child.stderr, "");
+ return JSON.parse(child.stdout) as Record<string, boolean>;
+}
+
+if (process.argv[2] === "environment-child") {
+ assert.deepEqual(
+ native.unixEnvironment(Buffer.from("CODEX_SECURITY_ENV_PROOF_RAW")),
+ Buffer.from([255, 254, 10]),
+ );
+ assert.deepEqual(
+ native.unixEnvironment(Buffer.from("CODEX_SECURITY_ENV_PROOF_EMPTY")),
+ Buffer.alloc(0),
+ );
+ assert.equal(
+ native.unixEnvironment(Buffer.from("CODEX_SECURITY_ENV_PROOF_ABSENT")),
null,
- 2,
- ),
-);
+ );
+ assert.throws(() => native.unixEnvironment(Buffer.from([0])));
+ console.log(
+ JSON.stringify({
+ rawBytes: true,
+ emptyAndUnset: true,
+ rejectsNulNames: true,
+ }),
+ );
+} else
+ console.log(
+ JSON.stringify(
+ {
+ node: process.version,
+ platform: process.platform,
+ architecture: process.arch,
+ nodeApi: 8,
+ accounts: accountProof(),
+ environment: environmentProof(),
+ },
+ null,
+ 2,
+ ),
+ );
diff --git a/plugins/codex-security/native/src/unix.rs b/plugins/codex-security/native/src/unix.rs
index 95e0f323d..862d6e378 100644
--- a/plugins/codex-security/native/src/unix.rs
+++ b/plugins/codex-security/native/src/unix.rs
@@ -1,6 +1,7 @@
use napi::bindgen_prelude::Buffer;
use napi_derive::napi;
-use std::ffi::{CStr, CString};
+use std::ffi::{CStr, CString, OsStr};
+use std::os::unix::ffi::OsStrExt;
#[napi(object, use_nullable = true)]
pub struct UserHomeResult {
@@ -8,6 +9,17 @@ pub struct UserHomeResult {
pub value: Option<Buffer>,
}
+#[napi]
+pub fn unix_environment(name: Buffer) -> napi::Result<Option<Buffer>> {
+ if name.contains(&0) {
+ return Err(napi::Error::from_reason(
+ "Environment variable name contains a NUL byte",
+ ));
+ }
+ Ok(std::env::var_os(OsStr::from_bytes(name.as_ref()))
+ .map(|value| value.as_bytes().to_vec().into()))
+}
+
#[napi]
pub fn user_home(username: Buffer) -> napi::Result<UserHomeResult> {
let username = CString::new(username.as_ref())
diff --git a/plugins/codex-security/native/src/windows.rs b/plugins/codex-security/native/src/windows.rs
index 9310d3658..48527e288 100644
--- a/plugins/codex-security/native/src/windows.rs
+++ b/plugins/codex-security/native/src/windows.rs
@@ -1,7 +1,7 @@
use napi::bindgen_prelude::Buffer;
use napi_derive::napi;
use std::{
- ffi::{CStr, OsString},
+ ffi::{CStr, OsStr, OsString},
fs::{self, File},
io::{self, Read, Write},
mem::{offset_of, size_of, MaybeUninit},
@@ -108,6 +108,316 @@ pub struct DirectoryEntriesResult {
pub value: Vec<DirectoryEntry>,
}
+#[napi(object)]
+pub struct WindowsEnvironmentValue {
+ pub name: Buffer,
+ pub value: Buffer,
+}
+
+#[napi(object)]
+pub struct WindowsProcessResult {
+ pub error: u32,
+ pub message: Option<String>,
+ pub status: i32,
+}
+
+fn windows_command_line(executable: &OsStr, arguments: &[OsString]) -> Vec<u16> {
+ let mut line = vec![b'"' as u16];
+ line.extend(executable.encode_wide());
+ line.push(b'"' as u16);
+ for argument in arguments {
+ line.push(b' ' as u16);
+ let quote = argument.is_empty()
+ || argument
+ .as_encoded_bytes()
+ .iter()
+ .any(|byte| matches!(byte, b' ' | b'\t'));
+ if quote {
+ line.push(b'"' as u16);
+ }
+ let mut slashes = 0;
+ for unit in argument.encode_wide() {
+ if unit == b'\\' as u16 {
+ slashes += 1;
+ continue;
+ }
+ line.extend(std::iter::repeat_n(
+ b'\\' as u16,
+ if unit == b'"' as u16 {
+ slashes * 2 + 1
+ } else {
+ slashes
+ },
+ ));
+ line.push(unit);
+ slashes = 0;
+ }
+ line.extend(std::iter::repeat_n(
+ b'\\' as u16,
+ if quote { slashes * 2 } else { slashes },
+ ));
+ if quote {
+ line.push(b'"' as u16);
+ }
+ }
+ line.push(0);
+ line
+}
+
+fn windows_application_path(executable: &OsStr) -> io::Result<Vec<u16>> {
+ use windows_sys::Win32::Foundation::MAX_PATH;
+
+ let namespaced = |path: &OsStr| {
+ let bytes = path.as_encoded_bytes();
+ bytes.starts_with(br"\\?\") || bytes.starts_with(br"\\.\") || bytes.starts_with(br"\??\")
+ };
+ let terminated = |path: &OsStr| path.encode_wide().chain([0]).collect::<Vec<_>>();
+ if namespaced(executable) {
+ return Ok(terminated(executable));
+ }
+ // Resolve lexically, without canonicalizing the selected file or changing argv.
+ let absolute = std::path::absolute(executable)?;
+ if namespaced(absolute.as_os_str()) {
+ return Ok(terminated(absolute.as_os_str()));
+ }
+ let units = absolute.as_os_str().encode_wide().collect::<Vec<_>>();
+ if units.len() < MAX_PATH as usize {
+ return Ok(terminated(executable));
+ }
+ // CreateProcessW needs a namespace for an ordinary long application path.
+ let (prefix, tail) = if units.starts_with(&[b'\\' as u16; 2]) {
+ (r"\\?\UNC\", &units[2..])
+ } else {
+ (r"\\?\", units.as_slice())
+ };
+ Ok(prefix
+ .encode_utf16()
+ .chain(tail.iter().copied())
+ .chain([0])
+ .collect())
+}
+
+fn run_exact_com_process(executable: &OsStr, arguments: &[OsString]) -> io::Result<i32> {
+ use windows_sys::Win32::{
+ Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, WAIT_OBJECT_0},
+ System::Threading::{
+ CreateProcessW, GetExitCodeProcess, WaitForSingleObject, CREATE_UNICODE_ENVIRONMENT,
+ INFINITE, PROCESS_INFORMATION, STARTF_USESTDHANDLES, STARTUPINFOW,
+ },
+ };
+
+ fn duplicate(handle: HANDLE) -> io::Result<Option<OwnedHandle>> {
+ if handle.is_null() || handle == INVALID_HANDLE_VALUE {
+ return Ok(None);
+ }
+ let process = unsafe { GetCurrentProcess() };
+ let mut inherited = null_mut();
+ if unsafe {
+ DuplicateHandle(
+ process,
+ handle,
+ process,
+ &mut inherited,
+ 0,
+ 1,
+ DUPLICATE_SAME_ACCESS,
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(Some(unsafe { OwnedHandle::from_raw_handle(inherited) }))
+ }
+
+ let application = windows_application_path(executable)?;
+ let handles = [
+ duplicate(io::stdin().as_raw_handle())?,
+ duplicate(io::stdout().as_raw_handle())?,
+ duplicate(io::stderr().as_raw_handle())?,
+ ];
+ let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() };
+ startup.cb = size_of::<STARTUPINFOW>() as u32;
+ startup.dwFlags = STARTF_USESTDHANDLES;
+ startup.hStdInput = handles[0]
+ .as_ref()
+ .map_or(null_mut(), AsRawHandle::as_raw_handle);
+ startup.hStdOutput = handles[1]
+ .as_ref()
+ .map_or(null_mut(), AsRawHandle::as_raw_handle);
+ startup.hStdError = handles[2]
+ .as_ref()
+ .map_or(null_mut(), AsRawHandle::as_raw_handle);
+ let mut process: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
+ let mut command_line = windows_command_line(executable, arguments);
+ if unsafe {
+ CreateProcessW(
+ application.as_ptr(),
+ command_line.as_mut_ptr(),
+ null(),
+ null(),
+ 1,
+ CREATE_UNICODE_ENVIRONMENT,
+ null(),
+ null(),
+ &startup,
+ &mut process,
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ let child = unsafe { OwnedHandle::from_raw_handle(process.hProcess) };
+ drop(unsafe { OwnedHandle::from_raw_handle(process.hThread) });
+ drop(handles);
+ if unsafe { WaitForSingleObject(child.as_raw_handle(), INFINITE) } != WAIT_OBJECT_0 {
+ return Err(io::Error::last_os_error());
+ }
+ let mut exit_code = 0;
+ if unsafe { GetExitCodeProcess(child.as_raw_handle(), &mut exit_code) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ Ok(exit_code as i32)
+}
+
+/// Run only inside the Node subprocess shim: blocking here keeps pipe ownership in that process.
+#[napi]
+pub fn run_windows_process(
+ executable: Buffer,
+ arguments: Vec<Buffer>,
+ cwd: Option<Buffer>,
+ environment: Option<Vec<WindowsEnvironmentValue>>,
+) -> napi::Result<WindowsProcessResult> {
+ use std::process::{Command, Stdio};
+
+ let executable = os_string(executable)?;
+ let arguments = arguments
+ .into_iter()
+ .map(os_string)
+ .collect::<napi::Result<Vec<_>>>()?;
+ let cwd = cwd.map(os_string).transpose()?;
+ let environment = environment
+ .unwrap_or_default()
+ .into_iter()
+ .map(|entry| Ok((os_string(entry.name)?, os_string(entry.value)?)))
+ .collect::<napi::Result<Vec<_>>>()?;
+ fn run(
+ mut executable: OsString,
+ arguments: Vec<OsString>,
+ cwd: Option<OsString>,
+ environment: Vec<(OsString, OsString)>,
+ ) -> io::Result<i32> {
+ use std::path::Path;
+ use windows_sys::Win32::System::Environment::{
+ NeedCurrentDirectoryForExePathW, SetEnvironmentVariableW,
+ };
+ use windows_sys::Win32::System::JobObjects::{
+ AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation,
+ SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
+ };
+ // Restore target settings inside the one-command shim after Node startup.
+ // Lookup must use the exact environment, including Rust's parent-PATH fallback.
+ for (name, value) in environment {
+ let name = name.encode_wide().chain([0]).collect::<Vec<_>>();
+ let value = value.encode_wide().chain([0]).collect::<Vec<_>>();
+ if unsafe { SetEnvironmentVariableW(name.as_ptr(), value.as_ptr()) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ }
+ // The private shim runs one command. Resolve relative executables and PATH
+ // entries from the target directory without changing the caller's cwd.
+ if let Some(directory) = cwd {
+ std::env::set_current_dir(directory)?;
+ }
+ // Rust searches PATH but omits Node's current-directory lookup for bare names.
+ if Path::new(&executable).file_name() == Some(executable.as_os_str())
+ && unsafe { NeedCurrentDirectoryForExePathW([0_u16].as_ptr()) } != 0
+ {
+ let bytes = executable.as_encoded_bytes();
+ let has_extension = bytes
+ .iter()
+ .position(|&byte| byte == b'.')
+ .is_some_and(|index| index + 1 < bytes.len());
+ let mut candidates = Vec::new();
+ if has_extension {
+ candidates.push(executable.clone());
+ }
+ for extension in ["com", "exe"] {
+ let mut candidate = executable.clone();
+ if bytes.last() != Some(&b'.') {
+ candidate.push(".");
+ }
+ candidate.push(extension);
+ candidates.push(candidate);
+ }
+ if let Some(candidate) = candidates
+ .into_iter()
+ .find(|path| Path::new(path).is_file())
+ {
+ executable = std::env::current_dir()?.join(candidate).into_os_string();
+ }
+ }
+ let raw_job = unsafe { CreateJobObjectW(null(), null()) };
+ if raw_job.is_null() {
+ return Err(io::Error::last_os_error());
+ }
+ let job = unsafe { OwnedHandle::from_raw_handle(raw_job) };
+ let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
+ limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
+ if unsafe {
+ SetInformationJobObject(
+ job.as_raw_handle(),
+ JobObjectExtendedLimitInformation,
+ &limits as *const _ as *const _,
+ size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
+ )
+ } == 0
+ {
+ return Err(io::Error::last_os_error());
+ }
+ if unsafe { AssignProcessToJobObject(job.as_raw_handle(), GetCurrentProcess()) } == 0 {
+ return Err(io::Error::last_os_error());
+ }
+ // This function runs once in the private shim. Keep its job handle until
+ // process exit, so descendants inherit membership before they can run.
+ // Closing the handle on return would terminate the shim before reporting status.
+ std::mem::forget(job);
+ // Rust otherwise prefers a sibling .com.exe over an explicitly selected .com.
+ let path = Path::new(&executable);
+ let bytes = executable.as_encoded_bytes();
+ if path.file_name() != Some(executable.as_os_str())
+ && bytes[bytes.len().saturating_sub(4)..].eq_ignore_ascii_case(b".com")
+ {
+ return run_exact_com_process(&executable, &arguments);
+ }
+ let mut command = Command::new(executable);
+ // Explicit PATH is searched before the shim's executable and system directories.
+ if let Some(path) = std::env::var_os("PATH") {
+ command.env("PATH", path);
+ }
+ command.args(arguments);
+ Ok(command
+ .stdin(Stdio::inherit())
+ .stdout(Stdio::inherit())
+ .stderr(Stdio::inherit())
+ .status()?
+ .code()
+ .unwrap_or(1))
+ }
+ match run(executable, arguments, cwd, environment) {
+ Ok(status) => Ok(WindowsProcessResult {
+ error: 0,
+ message: None,
+ status,
+ }),
+ Err(error) => Ok(WindowsProcessResult {
+ error: error.raw_os_error().unwrap_or(1) as u32,
+ message: Some(error.to_string()),
+ status: 127,
+ }),
+ }
+}
+
#[napi]
pub fn windows_arguments() -> Vec<Buffer> {
std::env::args_os()
diff --git a/plugins/codex-security/native/windows-binding.mts b/plugins/codex-security/native/windows-binding.mts
index 48df485ea..dbf908f09 100644
--- a/plugins/codex-security/native/windows-binding.mts
+++ b/plugins/codex-security/native/windows-binding.mts
@@ -22,6 +22,12 @@ export interface WindowsHandle {
/** Paths are UTF-16LE code units without a terminator, including lone surrogates. */
export interface WindowsBinding {
windowsArguments(): Buffer[];
+ runWindowsProcess(
+ executable: Buffer,
+ arguments_: Buffer[],
+ cwd?: Buffer,
+ environment?: { name: Buffer; value: Buffer }[],
+ ): { error: number; message?: string | null; status: number };
windowsEnvironment(name: Buffer): Buffer | null;
windowsAbsolutePath(path: Buffer): WindowsResult<Buffer>;
windowsDirectoryEntries(
diff --git a/plugins/codex-security/native/windows-files.mts b/plugins/codex-security/native/windows-files.mts
index 0c62eae45..e11091fe9 100644
--- a/plugins/codex-security/native/windows-files.mts
+++ b/plugins/codex-security/native/windows-files.mts
@@ -165,19 +165,27 @@ export function windowsFileSystem(native: WindowsBinding) {
});
}
- function readFile(path: Buffer): Buffer {
- return withFile(path, flags.GENERIC_READ, (handle) => {
- const chunks: Buffer[] = [];
+ function readChunks(path: Buffer, consume: (chunk: Buffer) => boolean): void {
+ withFile(path, flags.GENERIC_READ, (handle) => {
while (true) {
const chunk = Buffer.alloc(64 * 1024);
const result = handle.read(chunk, 0, chunk.length);
check(result.error, path);
- if (result.value === 0) return Buffer.concat(chunks);
- chunks.push(chunk.subarray(0, result.value));
+ if (result.value === 0 || !consume(chunk.subarray(0, result.value)))
+ return;
}
});
}
+ function readFile(path: Buffer): Buffer {
+ const chunks: Buffer[] = [];
+ readChunks(path, (chunk) => {
+ chunks.push(chunk);
+ return true;
+ });
+ return Buffer.concat(chunks);
+ }
+
function writeFile(
path: Buffer,
data: Buffer | Iterable<Buffer>,
@@ -241,6 +249,7 @@ export function windowsFileSystem(native: WindowsBinding) {
mkdir,
mkdirPrivate,
readInto,
+ readChunks,
readFile,
writeFile,
rename,
diff --git a/plugins/codex-security/native/windows-process.mts b/plugins/codex-security/native/windows-process.mts
new file mode 100644
index 000000000..3f343e4e3
--- /dev/null
+++ b/plugins/codex-security/native/windows-process.mts
@@ -0,0 +1,86 @@
+import { spawn, type SpawnOptions } from "node:child_process";
+
+// The wrapper is private: target values travel as UTF-16 bytes, never as script text.
+const shim = `
+process.once('message', ({ binary, executable, args, cwd, environment }) => {
+const wide = value => Buffer.from(value, 'base64');
+const disconnect = () => { if (process.connected) process.disconnect(); };
+try {
+ const result = require(binary).runWindowsProcess(wide(executable), args.map(wide), cwd === undefined ? undefined : wide(cwd), environment.map(({name,value}) => ({name:wide(name),value:wide(value)})));
+ process.exitCode = result.status;
+ if (result.error) process.send({ spawnError: { errno: result.error, message: result.message } }, disconnect);
+ else disconnect();
+} catch (error) {
+ process.exitCode = 1;
+ process.send({ spawnError: { message: error.message } }, disconnect);
+}
+});
+`;
+
+/** Keep Node's asynchronous byte streams while Windows receives exact UTF-16 argv/cwd. */
+export function spawnWindowsProcess(
+ binary: string,
+ executable: string,
+ args: string[],
+ options: Pick<SpawnOptions, "env" | "signal"> & {
+ cwd?: string;
+ stdio: ["ignore" | "pipe", "pipe", "pipe"];
+ },
+ environment: Record<string, string> = {},
+) {
+ const wide = (value: string) =>
+ Buffer.from(value, "utf16le").toString("base64");
+ const inherited = options.env ?? process.env;
+ const env: NodeJS.ProcessEnv = Object.create(null);
+ for (const name in inherited) env[name] = inherited[name];
+ // Target preloads, diagnostics, and certificates must not affect the private shim.
+ const targetEnvironment: Record<string, string> = {};
+ for (const key of ["NODE_OPTIONS", "NODE_DEBUG", "NODE_EXTRA_CA_CERTS"]) {
+ // Windows keeps the first lexicographic spelling of a duplicated env key.
+ const names = Object.keys(env)
+ .filter((name) => name.toUpperCase() === key)
+ .sort();
+ const name = names[0];
+ if (name !== undefined && env[name] !== undefined)
+ targetEnvironment[name] = env[name];
+ for (const name of names) delete env[name];
+ }
+ Object.assign(targetEnvironment, environment);
+ const payload = {
+ binary,
+ executable: wide(executable),
+ args: args.map(wide),
+ environment: Object.entries(targetEnvironment).map(([name, value]) => ({
+ name: wide(name),
+ value: wide(value),
+ })),
+ ...(typeof options.cwd === "string" ? { cwd: wide(options.cwd) } : {}),
+ };
+ const child = spawn(process.execPath, ["--input-type=commonjs", "-e", shim], {
+ ...options,
+ env,
+ cwd: undefined,
+ stdio: [...options.stdio, "ipc"],
+ });
+ const cancelled = () => child.killed || options.signal?.aborted === true;
+ child.once("spawn", () => {
+ if (cancelled()) return;
+ child.send(payload, (error) => {
+ if (error && !cancelled()) child.emit("error", error);
+ });
+ });
+ child.on("message", (message: unknown) => {
+ const report = message as {
+ spawnError?: { errno?: number; message?: string };
+ };
+ if (report.spawnError)
+ child.emit(
+ "error",
+ Object.assign(new Error(report.spawnError.message), {
+ code: "WINDOWS_PROCESS_ERROR",
+ errno: report.spawnError.errno,
+ }),
+ );
+ });
+ return child;
+}