OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
refactor(native): remove unused OS primitives and proofs (#1192)
mldangelo-oai9b75176147ea
diff --git a/.github/workflows/native-windows.yml b/.github/workflows/native-windows.ymlindex be806bd93..2a62e4fdb 100644--- a/.github/workflows/native-windows.yml+++ b/.github/workflows/native-windows.yml@@ -89,10 +89,6 @@ jobs:if ($policy.proof.policySymlinkBoundary -ne $false -or $policy.proof.directoryIdentity -ne $true -or $policy.proof.policyHelperRawPaths -ne $true) {throw "The restricted policy proof did not report skipped symbolic links and verified directory identity."}- - name: Compare the existing Python completion lock- run: |- $python = (Get-Command python -ErrorAction Stop).Source- node --expose-gc proof-windows.mjs $python ../scripts- name: Set up Node.js 20uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0with:diff --git a/plugins/codex-security/native/README.md b/plugins/codex-security/native/README.mdindex 37f090393..c60b3b5d9 100644--- a/plugins/codex-security/native/README.md+++ b/plugins/codex-security/native/README.md@@ -1,10 +1,8 @@# Native OS primitives-These 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.+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 nine Node-API 8 functions are typed in `binding.mts`. Paths remain byte buffers. `statAt` never follows the final symlink; device and inode numbers are decimal strings so JavaScript does not round them. `openAt` and `duplicate` create descriptors with close-on-exec set. Node owns subsequent reads, writes, `fstat`, `fsync`, and close calls. `userHome` looks up raw username bytes through the operating system and returns raw home-directory bytes or a missing result, without Git.--`openAt` and `fileLock` retry EINTR, matching the current Python helpers. Other operations return their native errno. `readDescriptor` retries one interrupted Node read without losing earlier chunks. Blocking locks must run outside the main JavaScript event loop; a process that holds a lock releases it on close or exit. A Python signal handler can raise during a blocked call, so later routing must preserve cancellation through the worker lifecycle.+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.Install the pinned Rust toolchain and the existing TypeScript dependencies, then run from the repository root:@@ -17,11 +15,7 @@ cargo +1.97.1 fmt --check --manifest-path plugins/codex-security/native/Cargo.tocargo +1.97.1 clippy --locked --manifest-path plugins/codex-security/native/Cargo.toml -- -D warnings```-The proof runs without Python. It checks directory replacement, byte paths, unreadable-file metadata, long raw symlinks, descriptor duplication, Node descriptor I/O, account lookup, contention, unlock, and process-death release. Linux exercises undecodable filename bytes; macOS uses valid UTF-8 filenames required by APFS. CI invokes it with an empty `PATH`. During migration, the same protocol can compare the existing Python lock helper:--```sh-node plugins/codex-security/native/proof.mjs python3 plugins/codex-security/scripts-```+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`.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:@@ -35,9 +29,9 @@ The `native-unix` workflow builds Linux artifacts in digest-pinned manylinux 2.2The `native-musl` workflow uses native x64 and arm64 Ubuntu workers with digest-pinned Rust 1.97.1 Alpine compiler images. Musl builds disable static CRT linkage so Node can load the shared library. After the ELF and private-path checks, each unchanged artifact runs the full proof in pinned Node 20.0.0 Alpine 3.17 and Node 22.13.0 Alpine 3.21 images, with musl 1.2.3 and 1.2.5 respectively. Compilation uses the locked registry offline; runtime containers mount only the source and artifact read-only. Python is absent, and proof processes receive an empty `PATH`.-Windows uses `windows-binding.mts` and the same Rust crate. `WindowsHandle` owns a non-inheritable handle through Rust's `File`; explicit `close()` and garbage collection release it. Handles never cross into Node's CRT descriptor table. Paths and returned names are UTF-16LE buffers without a NUL terminator, preserving lone surrogates. Volume identities and file positions are decimal strings; file IDs retain all 128 bits in a buffer.+Windows uses `windows-binding.mts` and the same Rust crate. `WindowsHandle` owns a non-inheritable handle through Rust's `File`; explicit `close()` and garbage collection release it. Handles never cross into Node's CRT descriptor table. Paths and returned names are UTF-16LE buffers without a NUL terminator, preserving lone surrogates. Volume identities are decimal strings; file IDs retain all 128 bits in a buffer.-The binding exposes synchronous file and directory creation, attributes and reparse tags, identity and final/opened names, read/write/seek/size/EOF/flush, exact-handle rename and deletion, and exclusive whole-file locking. Rust's `File` supplies ordinary I/O, cursor-preserving truncation, `sync_all` for flush, and locks. Calls return numeric Windows errors, including 6 for closed handles and 33 for nonblocking lock contention. Buffer ranges, path encoding, and 64-bit seek arguments are checked before use. Overlapped handles are unsupported because pending operations could retain native buffers beyond the call. Path authorization, ancestor traversal, and reparse-point policy remain the caller's responsibility.+The binding exposes synchronous file and recursive directory creation, attributes and reparse tags, identity and final/opened names, read/write, and exact-handle rename and deletion. Rust's `File` supplies ordinary I/O. Calls return numeric Windows errors, including 6 for closed handles. Buffer ranges and path encoding are checked before use. Overlapped handles are unsupported because pending operations could retain native buffers beyond the call. Path authorization, ancestor traversal, and reparse-point policy remain the caller's responsibility.Four additional operations preserve Windows strings at the Node boundary. `windowsArguments` returns the complete OS argument vector, including the executable and Node options, using Rust's CRT-compatible parser. `windowsEnvironment` reads one wide environment name and distinguishes an absent value (`null`) from an empty buffer. `windowsAbsolutePath` resolves against the native current directory and drive directories without requiring the destination to exist. `windowsDirectoryEntries` uses `std::fs::read_dir` and cached `DirEntry::file_type()` values without opening each child; names remain UTF-16LE, and construction or iteration failures return their numeric Windows error and an empty array. Directory symlinks and junctions have both directory and symbolic-link flags. The typed adapter exposes this enumerator through `entriesWithTypes`, which `resolve-security-md --list` uses on Windows.@@ -51,11 +45,7 @@ node plugins/codex-security/native/check.mjsnode --expose-gc plugins/codex-security/native/proof-windows.mjs```-The `native-windows` workflow builds x64 and arm64 with MSVC and a static CRT. It checks PE architecture and private paths, then runs the same artifact on Node 22.13.0 and 20.0.0 with an empty `PATH`. The proof covers handle lifetime and garbage collection, ancestor replacement, junctions, exact-handle operations, raw UTF-16 and long paths, numeric errors, and whole-file locking and release. Blocking locks run in child processes. A separate Node 22 invocation uses the runner's Python to compare both directions of contention, unlock, close, and process-death release against the existing `msvcrt` byte-zero lock. Python is only an optional migration oracle:--```sh-node --expose-gc plugins/codex-security/native/proof-windows.mjs python plugins/codex-security/scripts-```+The `native-windows` workflow builds x64 and arm64 with MSVC and a static CRT. It checks PE architecture and private paths, then runs the same artifact on Node 22.13.0 and 20.0.0 with an empty `PATH`. The proof covers handle lifetime and garbage collection, ancestor replacement, junctions, exact-handle operations, raw UTF-16 and long paths, and numeric errors.The build also compiles the test-only `windows-wide-launcher` Rust example. It starts a Node proof child with lone surrogates in arguments, environment values, and its working directory. That child checks complete directory iteration, distinct surrogate and replacement-character files, canonical paths, bounded reads, output truncation, and recursive long paths through the typed adapter. A Rust file guard with sharing disabled remains open while the child enumerates its name; an explicit data read fails with a sharing violation. Attribute-only access is not blocked by Windows file sharing. Adapter path and I/O tests run on the same matrix. The launcher cleans up the wide fixtures and is never included in the uploaded or bundled native payloads.diff --git a/plugins/codex-security/native/binding.mts b/plugins/codex-security/native/binding.mtsindex bd6f40526..5f1a6f9ca 100644--- a/plugins/codex-security/native/binding.mts+++ b/plugins/codex-security/native/binding.mts@@ -1,5 +1,4 @@import { createRequire } from "node:module";-import { readSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import { nativeTarget } from "./platform.mjs";@@ -11,62 +10,11 @@ export const binaryPath = join(process.platform === "win32" ? "windows.node" : "unix.node",);-export interface SyscallResult {- value: number;- errno: number;-}--export interface MetadataResult {- errno: number;- mode: number;- device: string;- inode: string;-}--/** Paths are uninterpreted POSIX bytes. Only openAt and fileLock retry EINTR. */+/** Usernames and home directories are uninterpreted POSIX bytes. */export interface UnixBinding {- openAt(- directory: number,- name: Buffer,- flags: number,- mode: number,- ): SyscallResult;- duplicate(descriptor: number): SyscallResult;- makeDirectoryAt(directory: number, name: Buffer, mode: number): SyscallResult;- renameAt(- oldDirectory: number,- oldName: Buffer,- newDirectory: number,- newName: Buffer,- ): SyscallResult;- unlinkAt(directory: number, name: Buffer): SyscallResult;- statAt(directory: number, name: Buffer): MetadataResult;- readLinkAt(directory: number, name: Buffer): { errno: number; value: Buffer };- fileLock(- descriptor: number,- unlock: boolean,- nonblocking: boolean,- ): SyscallResult;userHome(username: Buffer): { errno: number; value: Buffer | null };}export function loadBinding(): UnixBinding {return createRequire(import.meta.url)(binaryPath) as UnixBinding;}--/** Retry the interrupted read, preserving the caller's previously read bytes. */-export function readDescriptor(- fd: number,- buffer: Buffer,- offset: number,- length: number,- position: number | null,-): number {- while (true) {- try {- return readSync(fd, buffer, offset, length, position);- } catch (error) {- if ((error as NodeJS.ErrnoException).code !== "EINTR") throw error;- }- }-}diff --git a/plugins/codex-security/native/proof-windows.mts b/plugins/codex-security/native/proof-windows.mtsindex dd6278029..16d1d8705 100644--- a/plugins/codex-security/native/proof-windows.mts+++ b/plugins/codex-security/native/proof-windows.mts@@ -1,5 +1,4 @@import assert from "node:assert/strict";-import { fork, spawn, type ChildProcess } from "node:child_process";import {existsSync,linkSync,@@ -14,8 +13,6 @@ import {} from "node:fs";import { tmpdir } from "node:os";import { basename, join, win32 } from "node:path";-import { createInterface } from "node:readline";-import { fileURLToPath } from "node:url";import { setImmediate } from "node:timers/promises";import { wideProcessProof } from "./proof-windows-wide.mjs";import { windowsFileSystem } from "./windows-files.mjs";@@ -32,7 +29,6 @@ const shareAll =const directoryFlags =flags.FILE_FLAG_BACKUP_SEMANTICS | flags.FILE_FLAG_OPEN_REPARSE_POINT;const readWrite = flags.GENERIC_READ | flags.GENERIC_WRITE;-const self = fileURLToPath(import.meta.url);const pathBytes = (path: string) =>Buffer.from(win32.toNamespacedPath(path), "utf16le");const checked = <T extends { error: number }>(result: T): T => {@@ -109,54 +105,22 @@ function handleProof(root: string) {checked(file.write(input, 6, payload.length)).value,payload.length,);- success(file.flush());- assert.equal(checked(file.size()).value, String(payload.length));assert.equal(checked(file.fileType()).value, 1);assert.equal(checked(file.attributes()).attributes & flags.FILE_ATTRIBUTE_DIRECTORY,0,);- assert.equal(checked(file.seek(0n, flags.FILE_BEGIN)).value, "0");+ const reader = keep(open(path, flags.GENERIC_READ));const buffer = Buffer.alloc(payload.length + 6, 0x7e);assert.equal(- checked(file.read(buffer, 3, payload.length)).value,+ checked(reader.read(buffer, 3, payload.length)).value,payload.length,);assert.deepEqual(buffer.subarray(3, -3), payload);assert.deepEqual(buffer.subarray(0, 3), Buffer.from("~~~"));assert.deepEqual(buffer.subarray(-3), Buffer.from("~~~"));- assert.equal(checked(file.read(buffer, 0, 1)).value, 0);- assert.equal(- checked(file.seek(0n, flags.FILE_CURRENT)).value,- String(payload.length),- );- const far = (1n << 53n) + 5n;- assert.equal(- checked(file.seek(far, flags.FILE_BEGIN)).value,- far.toString(),- );- assert.equal(- checked(file.seek(-2n, flags.FILE_END)).value,- String(payload.length - 2),- );- success(file.setEndOfFile());- assert.equal(checked(file.size()).value, String(payload.length - 2));- assert.equal(- checked(file.seek(0n, flags.FILE_CURRENT)).value,- String(payload.length - 2),- );- assert.equal(checked(file.read(buffer, 0, 1)).value, 0);- assert.equal(- checked(file.seek(1n, flags.FILE_CURRENT)).value,- String(payload.length - 1),- );- success(file.setEndOfFile());- assert.equal(checked(file.size()).value, String(payload.length - 1));- assert.equal(- checked(file.seek(0n, flags.FILE_CURRENT)).value,- String(payload.length - 1),- );- assert.equal(file.seek(0n, 99).error, 87);+ assert.equal(checked(reader.read(buffer, 0, 1)).value, 0);+ close(reader);samePath(checked(file.finalPath(0)).path, path);samePath(checked(file.finalPath(flags.FILE_NAME_OPENED)).path, path);@@ -217,29 +181,19 @@ function handleProof(root: string) {flags.FILE_FLAG_OVERLAPPED,),);- assert.throws(() => file.seek(1n << 63n, flags.FILE_BEGIN));const readOnly = keep(open(path, flags.GENERIC_READ));assert.equal(readOnly.write(buffer, 0, 1).error, 5);- assert.equal(readOnly.flush(), 5);- assert.equal(readOnly.setEndOfFile(), 5);close(readOnly);close(file);success(file.close());- assert.equal(file.size().error, 6);assert.equal(file.read(buffer, 0, 1).error, 6);assert.equal(file.write(buffer, 0, 1).error, 6);- assert.equal(file.seek(0n, flags.FILE_CURRENT).error, 6);- assert.equal(file.setEndOfFile(), 6);- assert.equal(file.flush(), 6);- assert.equal(file.lock(true), 6);- assert.equal(file.lock(false), 6);- assert.equal(file.unlock(), 6);const ancestor = join(root, "ancestor");const scan = join(ancestor, "scan");const child = join(scan, "child");for (const directory of [ancestor, scan, child]) {- success(native.createWindowsDirectory(pathBytes(directory)));+ success(native.createWindowsDirectories(pathBytes(directory)));}const directories = [ancestor, scan, child].map((directory) =>keep(@@ -336,7 +290,6 @@ function handleProof(root: string) {checked(exact.write(exactPayload, 0, exactPayload.length)).value,exactPayload.length,);- success(exact.flush());const exactIdentity = checked(exact.identity());renameSync(source, moved);writeFileSync(source, "replacement source");@@ -358,10 +311,10 @@ function handleProof(root: string) {let longDirectory = root;for (let index = 0; index < 5; index++) {longDirectory = join(longDirectory, `part-${index}-${"x".repeat(55)}`);- success(native.createWindowsDirectory(pathBytes(longDirectory)));+ success(native.createWindowsDirectories(pathBytes(longDirectory)));}const rawDirectory = join(longDirectory, "directory-\udfff");- success(native.createWindowsDirectory(pathBytes(rawDirectory)));+ success(native.createWindowsDirectories(pathBytes(rawDirectory)));rawPaths.push(rawDirectory);const rawPath = join(rawDirectory, "file-\ud800");// A lossy UTF-8 round trip would collide with this different filename.@@ -374,7 +327,6 @@ function handleProof(root: string) {checked(raw.write(exactPayload, 0, exactPayload.length)).value,exactPayload.length,);- success(raw.flush());const finalName = checked(raw.finalPath(flags.FILE_NAME_OPENED)).path;assert(finalName.length / 2 > 260);assert(@@ -397,8 +349,8 @@ function handleProof(root: string) {"replacement sentinel",);return {- handleReadWriteFlushSeekSizeAndEof: true,- exact64BitPositionAnd128BitIdentity: true,+ handleReadWriteAndEof: true,+ exact128BitIdentity: true,numericMissingSharingAndClosedErrors: true,ancestorReplacementBlockedUntilClose: true,junctionMetadataAndFinalNames: true,@@ -424,275 +376,26 @@ async function ownershipProof(root: string): Promise<boolean> {return true;}-interface Message {- type: string;- error?: number;-}-const send = (message: Message) =>- new Promise<void>((resolve, reject) => {- process.send!(message, (error) => (error ? reject(error) : resolve()));- });--async function worker(path: string): Promise<void> {- const handle = open(path, readWrite, shareAll, flags.OPEN_ALWAYS);- process.on("disconnect", () => {- handle.close();- process.exit(0);- });- process.on("message", async (command: string) => {- if (command === "probe") {- const error = handle.lock(true);- if (error === 0) success(handle.unlock());- await send({ type: "probe", error });- } else if (command === "lock") {- await send({ type: "attempting" });- success(handle.lock(false));- await send({ type: "acquired" });- } else if (command === "unlock") {- success(handle.unlock());- await send({ type: "released" });- } else if (command === "close") {- success(handle.close());- await send({ type: "closed" });- } else if (command === "exit") {- success(handle.close());- process.disconnect!();- } else throw new Error(`Unknown worker command: ${command}`);- });- await send({ type: "ready" });-}--// Migration oracle only: compare the existing Python byte-zero lock functions.-const pythonOracle = String.raw`-import json, os, sys-sys.path.insert(0, sys.argv[1])-from workbench_db import acquire_completion_file_lock, release_completion_file_lock, is_file_lock_contention, windows_file_lock-fd = os.open(sys.argv[2], os.O_RDWR | os.O_CREAT | os.O_BINARY, 0o600)-def send(kind, **values):- print(json.dumps({"type": kind, **values}), flush=True)-try:- send("ready")- for line in sys.stdin:- command = json.loads(line)- if command == "probe":- os.lseek(fd, 0, os.SEEK_SET)- try:- windows_file_lock.locking(fd, windows_file_lock.LK_NBLCK, 1)- except OSError as error:- if not is_file_lock_contention(error):- raise- send("probe", error=error.errno)- else:- release_completion_file_lock(fd)- send("probe", error=0)- elif command == "lock":- send("attempting")- acquire_completion_file_lock(fd)- send("acquired")- elif command == "unlock":- release_completion_file_lock(fd)- send("released")- elif command == "close":- os.close(fd)- fd = None- send("closed")- elif command == "exit":- break- else:- raise ValueError(command)-finally:- if fd is not None:- os.close(fd)-`;--const peers = new Set<Peer>();-class Peer {- readonly child: ChildProcess;- readonly exited: Promise<void>;- private messages: Message[] = [];- private pending?: (message: Message) => void;- private stderr = "";- private readonly python: boolean;- constructor(path: string, python?: string, scripts?: string) {- this.python = python !== undefined;- this.child =- python === undefined- ? fork(self, ["worker", path], {- execPath: process.execPath,- execArgv: [],- stdio: ["ignore", "pipe", "pipe", "ipc"],- })- : spawn(python, ["-u", "-c", pythonOracle, scripts!, path], {- stdio: ["pipe", "pipe", "pipe"],- });- peers.add(this);- this.child.stderr!.on("data", (chunk: Buffer) => {- this.stderr += chunk.toString();- });- const receive = (message: Message) => {- if (this.pending) {- const receive = this.pending;- this.pending = undefined;- receive(message);- } else this.messages.push(message);- };- if (this.python) {- createInterface({ input: this.child.stdout! }).on("line", (line) => {- receive(JSON.parse(line) as Message);- });- } else this.child.on("message", receive);- this.exited = new Promise((resolve) =>- this.child.once("exit", () => resolve()),- );- }- send(command: string): void {- if (this.python) this.child.stdin!.write(`${JSON.stringify(command)}\n`);- else this.child.send(command);- }- async next(type: string): Promise<Message> {- let timer: ReturnType<typeof setTimeout> | undefined;- try {- const message = await Promise.race([- this.messages.length- ? Promise.resolve(this.messages.shift()!)- : new Promise<Message>((resolve) => {- this.pending = resolve;- }),- this.exited.then(() => {- throw new Error(`Worker exited before ${type}: ${this.stderr}`);- }),- new Promise<never>((_, reject) => {- timer = setTimeout(- () =>- reject(- new Error(`Worker timed out before ${type}: ${this.stderr}`),- ),- 30_000,- );- }),- ]);- assert.equal(message.type, type);- return message;- } finally {- clearTimeout(timer);- }- }- async stop(kill = false): Promise<void> {- if (kill) this.child.kill("SIGKILL");- else this.send("exit");- let timer: ReturnType<typeof setTimeout> | undefined;- try {- await Promise.race([- this.exited,- new Promise<never>((_, reject) => {- timer = setTimeout(- () => reject(new Error(`Worker did not exit: ${this.stderr}`)),- 30_000,- );- }),- ]);- } finally {- clearTimeout(timer);- }- peers.delete(this);- if (!kill) {- assert.equal(this.child.exitCode, 0, this.stderr);- assert.equal(this.stderr, "");- }- }-}--async function lockProof(root: string, python?: string, scripts?: string) {- const path = join(root, "file-lock");- const parent = open(path, readWrite, shareAll, flags.OPEN_ALWAYS);- const other = open(path, readWrite, shareAll);- try {- success(parent.lock(true));- const first = new Peer(path, python, scripts);- await first.next("ready");- first.send("probe");- const contention = (await first.next("probe")).error!;- if (python === undefined) assert.equal(contention, 33);- else assert([13, 11, 36].includes(contention));- first.send("lock");- await first.next("attempting");- success(parent.unlock());- await first.next("acquired");- assert.equal(parent.lock(true), 33);- first.send("unlock");- await first.next("released");- success(parent.lock(true));- first.send("lock");- await first.next("attempting");- success(parent.close());- await first.next("acquired");- const second = new Peer(path);- await second.next("ready");- second.send("lock");- await second.next("attempting");- await first.stop(true);- await second.next("acquired");- assert.equal(other.lock(true), 33);- const third = new Peer(path, python, scripts);- await third.next("ready");- third.send("lock");- await third.next("attempting");- await second.stop(true);- await third.next("acquired");- third.send("close");- await third.next("closed");- success(other.lock(true));- success(other.unlock());- await third.stop();- return {- peerRuntime: python === undefined ? "node" : "python",- peerContentionError: contention,- wholeFileExclusiveContention: true,- blockingHandoff: true,- unlockCloseAndBidirectionalProcessDeathRelease: true,- };- } finally {- parent.close();- other.close();- for (const peer of peers) await peer.stop(true);- }-}--if (process.argv[2] === "worker") {- await worker(process.argv[3]!);-} else {- const [python, scripts] = process.argv.slice(2);- assert.equal(- Boolean(python),- Boolean(scripts),- "Pass both the Python executable and scripts directory.",- );- const root = realpathSync.native(- mkdtempSync(join(tmpdir(), "codex-security-windows-")),+const root = realpathSync.native(+ mkdtempSync(join(tmpdir(), "codex-security-windows-")),+);+try {+ console.log(+ JSON.stringify(+ {+ node: process.version,+ platform: process.platform,+ architecture: process.arch,+ nodeApi: 8,+ handles: handleProof(root),+ wideProcessAndPaths: wideProcessProof(root),+ garbageCollectionClosesHandle: await ownershipProof(root),+ fixture: basename(root),+ },+ null,+ 2,+ ),);- try {- console.log(- JSON.stringify(- {- node: process.version,- platform: process.platform,- architecture: process.arch,- nodeApi: 8,- handles: handleProof(root),- wideProcessAndPaths: wideProcessProof(root),- garbageCollectionClosesHandle: await ownershipProof(root),- locks: await lockProof(root),- pythonCompatibility:- python && scripts- ? await lockProof(root, python, scripts)- : undefined,- fixture: basename(root),- },- null,- 2,- ),- );- } finally {- rmSync(root, { recursive: true, force: true });- }+} finally {+ rmSync(root, { recursive: true, force: true });}diff --git a/plugins/codex-security/native/proof.mts b/plugins/codex-security/native/proof.mtsindex 981e9129c..1e7380b62 100644--- a/plugins/codex-security/native/proof.mts+++ b/plugins/codex-security/native/proof.mts@@ -1,32 +1,9 @@import assert from "node:assert/strict";-import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";-import {- closeSync,- constants,- existsSync,- fstatSync,- fsyncSync,- mkdirSync,- mkdtempSync,- openSync,- lstatSync,- readFileSync,- renameSync,- rmSync,- statSync,- symlinkSync,- writeFileSync,-} from "node:fs";-import { tmpdir, userInfo } from "node:os";+import { userInfo } from "node:os";import { randomUUID } from "node:crypto";-import { basename, join } from "node:path";-import { createInterface } from "node:readline";-import { fileURLToPath } from "node:url";-import { loadBinding, readDescriptor } from "./binding.mjs";-import { constants as osConstants } from "node:os";+import { loadBinding } from "./binding.mjs";const native = loadBinding();-const errno = osConstants.errno;class NativeError extends Error {constructor(readonly errno: number) {super(`Native operation failed: errno ${errno}`);@@ -36,39 +13,6 @@ function checked<T extends { errno: number }>(result: T): T {if (result.errno !== 0) throw new NativeError(result.errno);return result;}-const bytes = (path: string | Buffer) =>- typeof path === "string" ? Buffer.from(path) : path;-const openAt = (fd: number, path: string | Buffer, flags: number, mode = 0) =>- checked(native.openAt(fd, bytes(path), flags, mode)).value;-const mkdirAt = (fd: number, path: string | Buffer, mode: number) => {- checked(native.makeDirectoryAt(fd, bytes(path), mode));-};-const renameAt = (- oldFd: number,- oldPath: string | Buffer,- newFd: number,- newPath: string | Buffer,-) => {- checked(native.renameAt(oldFd, bytes(oldPath), newFd, bytes(newPath)));-};-const unlinkAt = (fd: number, path: string | Buffer) => {- checked(native.unlinkAt(fd, bytes(path)));-};-const duplicate = (fd: number) => checked(native.duplicate(fd)).value;-const fileLock = (fd: number, unlock = false, nonblocking = false) => {- checked(native.fileLock(fd, unlock, nonblocking));-};-const statAt = (fd: number, path: string | Buffer) =>- checked(native.statAt(fd, bytes(path)));-const readLinkAt = (fd: number, path: string | Buffer) =>- checked(native.readLinkAt(fd, bytes(path))).value;-const rawPath = (parent: string, name: Buffer) =>- Buffer.concat([Buffer.from(parent + "/"), name]);-// APFS requires valid UTF-8 names; Linux also exercises undecodable bytes.-const fixtureName = (prefix: string, byte: number) =>- process.platform === "darwin"- ? Buffer.from(`${prefix}-é`)- : Buffer.from([prefix.charCodeAt(0), byte]);function accountProof() {let currentHomeMatches: boolean | null = null;@@ -100,415 +44,16 @@ function accountProof() {};}-const directoryFlags =- constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;-const ownFileFlags =- constants.O_WRONLY |- constants.O_CREAT |- constants.O_EXCL |- constants.O_NOFOLLOW;-const readFlags =- constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;-const self = fileURLToPath(import.meta.url);--function expectedError(action: () => void, ...codes: number[]): number {- try {- action();- } catch (error) {- assert(error instanceof NativeError);- assert(codes.includes(error.errno), error.message);- return error.errno;- }- throw new Error("Expected native operation to fail");-}--function descriptorProof(root: string) {- const scan = join(root, "scan");- const movedScan = join(root, "held-scan");- const outside = join(root, "outside");- mkdirSync(scan);- mkdirSync(outside);- writeFileSync(join(outside, "result.json"), "outside sentinel");- const held = new Set<number>();- const keep = (fd: number) => {- held.add(fd);- return fd;- };- const close = (fd: number) => {- closeSync(fd);- held.delete(fd);- };- try {- const rootFd = keep(openSync(scan, directoryFlags));- const identity = fstatSync(rootFd, { bigint: true });- mkdirAt(rootFd, "artifacts", 0o700);- const originalParent = keep(openAt(rootFd, "artifacts", directoryFlags));- const parentFd = keep(duplicate(originalParent));- close(originalParent);- const unreadable = fixtureName("u", 0xff);- const rawLink = fixtureName("l", 0xfe);- const rawTarget = Buffer.concat([- Buffer.from("component/".repeat(80)),- Buffer.from([0xff]),- ]);- writeFileSync(rawPath(join(scan, "artifacts"), unreadable), "unreadable", {- mode: 0,- });- symlinkSync(rawTarget, rawPath(join(scan, "artifacts"), rawLink));- const unreadableMetadata = statAt(parentFd, unreadable);- const unreadableExpected = lstatSync(- rawPath(join(scan, "artifacts"), unreadable),- { bigint: true },- );- assert.equal(unreadableMetadata.mode, Number(unreadableExpected.mode));- assert.equal(unreadableMetadata.device, unreadableExpected.dev.toString());- assert.equal(unreadableMetadata.inode, unreadableExpected.ino.toString());- assert.equal(unreadableMetadata.mode & 0o777, 0);- if (process.geteuid?.() !== 0)- expectedError(- () => openAt(parentFd, unreadable, readFlags),- errno.EACCES!,- );- const linkMetadata = statAt(parentFd, rawLink);- assert.equal(linkMetadata.mode & constants.S_IFMT, constants.S_IFLNK);- assert.deepEqual(readLinkAt(parentFd, rawLink), rawTarget);-- // Replace both visible ancestor paths while keeping their validated FDs.- renameSync(scan, movedScan);- symlinkSync(outside, scan, "dir");- renameSync(join(movedScan, "artifacts"), join(movedScan, "held-artifacts"));- symlinkSync(outside, join(movedScan, "artifacts"), "dir");- assert.equal(fstatSync(rootFd, { bigint: true }).ino, identity.ino);- assert.equal(statSync(movedScan, { bigint: true }).dev, identity.dev);- assert.deepEqual(statAt(parentFd, unreadable), unreadableMetadata);- assert.deepEqual(statAt(parentFd, rawLink), linkMetadata);- assert.deepEqual(readLinkAt(parentFd, rawLink), rawTarget);- assert.equal(- statAt(rootFd, "artifacts").mode & constants.S_IFMT,- constants.S_IFLNK,- );- assert.equal(readLinkAt(rootFd, "artifacts").toString(), outside);- mkdirAt(parentFd, "nested", 0o700);-- const rawDirectory = fixtureName("d", 0xfd);- const rawSource = fixtureName("s", 0xfc);- const rawDestination = fixtureName("t", 0xfb);- mkdirAt(parentFd, rawDirectory, 0o700);- assert.equal(statAt(parentFd, rawDirectory).mode & 0o777, 0o700);- const rawDirectoryFd = keep(openAt(parentFd, rawDirectory, directoryFlags));- const rawFd = keep(openAt(parentFd, rawSource, ownFileFlags, 0o600));- writeFileSync(rawFd, "raw path contents");- close(rawFd);- renameAt(parentFd, rawSource, rawDirectoryFd, rawDestination);- const rawRead = keep(openAt(rawDirectoryFd, rawDestination, readFlags));- assert.equal(readFileSync(rawRead, "utf8"), "raw path contents");- close(rawRead);- unlinkAt(rawDirectoryFd, rawDestination);- close(rawDirectoryFd);- rmSync(rawPath(join(movedScan, "held-artifacts"), rawDirectory), {- recursive: true,- });- expectedError(() => statAt(parentFd, rawDirectory), errno.ENOENT!);-- const fd = keep(openAt(parentFd, ".result.tmp", ownFileFlags, 0o600));- const payload = Buffer.from('{"proof":"anchored 🔐"}\n');- writeFileSync(fd, payload);- fsyncSync(fd);- assert(fstatSync(fd).isFile());- assert.equal(fstatSync(fd).mode & 0o777, 0o600);- assert.equal(fstatSync(fd).size, payload.length);- close(fd);- renameAt(parentFd, ".result.tmp", parentFd, "result.json");-- const input = keep(openAt(parentFd, "result.json", readFlags));- const chunks: Buffer[] = [];- while (true) {- const chunk = Buffer.alloc(5);- const count = readDescriptor(input, chunk, 0, chunk.length, null);- if (count === 0) break;- chunks.push(chunk.subarray(0, count));- }- assert.deepEqual(Buffer.concat(chunks), payload);- close(input);- const anchoredDirectory = join(movedScan, "held-artifacts");- assert.deepEqual(- readFileSync(join(anchoredDirectory, "result.json")),- payload,- );- assert.equal(- readFileSync(join(outside, "result.json"), "utf8"),- "outside sentinel",- );- assert(!existsSync(join(outside, "nested")));-- symlinkSync(join(outside, "result.json"), join(anchoredDirectory, "link"));- const noFollowErrno = expectedError(- () => openAt(parentFd, "link", readFlags),- errno.ELOOP!,- );- unlinkAt(parentFd, "link");- unlinkAt(parentFd, "result.json");- assert(!existsSync(join(anchoredDirectory, "result.json")));- assert.equal(- readFileSync(join(outside, "result.json"), "utf8"),- "outside sentinel",- );- expectedError(- () => openAt(rootFd, "artifacts", directoryFlags),- errno.ELOOP!,- errno.ENOTDIR!,- );- expectedError(() => mkdirAt(parentFd, "nested", 0o700), errno.EEXIST!);- expectedError(- () => renameAt(parentFd, "missing", parentFd, "other"),- errno.ENOENT!,- );- expectedError(() => unlinkAt(parentFd, "missing"), errno.ENOENT!);- expectedError(() => statAt(-1, "missing"), errno.EBADF!);- expectedError(() => readLinkAt(-1, "missing"), errno.EBADF!);- const badFdErrno = expectedError(- () => openAt(-1, "missing", readFlags),- errno.EBADF!,- );- return {- anchoredMkdirWriteRenameReadDelete: true,- outsideSentinelPreserved: true,- nodeFdWriteReadFstatFsyncClose: true,- mode: "0600",- duplicateSurvivesOriginalClose: true,- rawMkdirOpenRenameUnlink: true,- unreadableMetadataMatches: true,- noFollowStatAndLongRawReadlinkSurviveReplacement: true,- rawLinkTargetBytes: rawTarget.length,- noFollowErrno,- badFdErrno,- };- } finally {- for (const fd of held) closeSync(fd);- }-}--async function nativeLockWorker(path: string): Promise<void> {- const fd = openSync(path, constants.O_RDWR | constants.O_CREAT, 0o600);- try {- if (process.argv[4] === "try") {- const result = native.fileLock(fd, false, true);- if (result.errno === 0) fileLock(fd, true);- console.log(- JSON.stringify({ acquired: result.errno === 0, errno: result.errno }),- );- return;- }- const commands = createInterface({ input: process.stdin })[- Symbol.asyncIterator- ]();- console.log("waiting");- fileLock(fd);- console.log("acquired");- await commands.next();- fileLock(fd, true);- console.log("released");- } finally {- closeSync(fd);- }-}--// Temporary interoperability oracle: import the actual current Python functions.-// This protocol scaffold is never a migrated implementation or shipped artifact.-const pythonOracle = String.raw`-import json, os, sys-sys.path.insert(0, sys.argv[1])-from workbench_db import acquire_completion_file_lock, release_completion_file_lock, posix_file_lock-fd = os.open(sys.argv[2], os.O_RDWR | os.O_CREAT, 0o600)-try:- if sys.argv[3] == "try":- try:- posix_file_lock.flock(fd, posix_file_lock.LOCK_EX | posix_file_lock.LOCK_NB)- except OSError as error:- print(json.dumps({"acquired": False, "errno": error.errno}), flush=True)- else:- release_completion_file_lock(fd)- print(json.dumps({"acquired": True}), flush=True)- else:- print("waiting", flush=True)- acquire_completion_file_lock(fd)- print("acquired", flush=True)- sys.stdin.buffer.readline()- release_completion_file_lock(fd)- print("released", flush=True)-finally:- os.close(fd)-`;--type Worker = {- child: ChildProcessWithoutNullStreams;- lines: AsyncIterableIterator<string>;- exit: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;- stderr: () => string;-};-const workers: Worker[] = [];--function worker(command: string, args: string[]): Worker {- const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });- let stderr = "";- child.stderr.setEncoding("utf8").on("data", (chunk: string) => {- stderr += chunk;- });- const result: Worker = {- child,- lines: createInterface({ input: child.stdout })[Symbol.asyncIterator](),- exit: new Promise((resolve, reject) => {- const timeout = setTimeout(() => {- child.kill("SIGKILL");- reject(new Error(`worker exit timeout: ${stderr}`));- }, 30_000);- child.once("error", (error) => {- clearTimeout(timeout);- reject(error);- });- child.once("exit", (code, signal) => {- clearTimeout(timeout);- resolve({ code, signal });- });- }),- stderr: () => stderr,- };- workers.push(result);- return result;-}--async function line(child: Worker, expected?: string): Promise<string> {- let timeout: ReturnType<typeof setTimeout>;- const value = await Promise.race([- child.lines.next(),- new Promise<never>((_resolve, reject) => {- timeout = setTimeout(- () => reject(new Error(`worker protocol timeout: ${child.stderr()}`)),- 10_000,- );- }),- ]).finally(() => clearTimeout(timeout));- assert(!value.done, `worker ended early: ${child.stderr()}`);- if (expected !== undefined) assert.equal(value.value, expected);- return value.value;-}--async function release(child: Worker): Promise<void> {- child.child.stdin.end("release\n");- await line(child, "released");- const ended = await child.exit;- assert.equal(ended.code, 0, child.stderr());-}--async function kill(child: Worker): Promise<void> {- child.child.kill("SIGKILL");- assert.equal((await child.exit).signal, "SIGKILL");-}--async function lockProof(root: string, python?: string, scripts?: string) {- const path = join(root, "completion.lock");- const fd = openSync(path, constants.O_RDWR | constants.O_CREAT, 0o600);- const peerWorker = (mode = "hold") =>- python !== undefined && scripts !== undefined- ? worker(python, ["-c", pythonOracle, scripts, path, mode])- : worker(process.execPath, [self, "lock-worker", path, mode]);- const nativeWorker = () =>- worker(process.execPath, [self, "lock-worker", path]);- try {- fileLock(fd);- const probe = peerWorker("try");- const contention = JSON.parse(await line(probe)) as {- acquired: boolean;- errno: number;- };- assert.equal(contention.acquired, false);- assert([errno.EAGAIN, errno.EWOULDBLOCK].includes(contention.errno));- assert.equal((await probe.exit).code, 0, probe.stderr());- const waitingPeer = peerWorker();- await line(waitingPeer, "waiting");- fileLock(fd, true);- await line(waitingPeer, "acquired");- const nativeContention = expectedError(- () => fileLock(fd, false, true),- errno.EAGAIN!,- errno.EWOULDBLOCK!,- );- await release(waitingPeer);-- const heldPeer = peerWorker();- await line(heldPeer, "waiting");- await line(heldPeer, "acquired");- const waitingNative = nativeWorker();- await line(waitingNative, "waiting");- await kill(heldPeer);- await line(waitingNative, "acquired");- await release(waitingNative);-- const heldNative = nativeWorker();- await line(heldNative, "waiting");- await line(heldNative, "acquired");- const peerAfterDeath = peerWorker();- await line(peerAfterDeath, "waiting");- await kill(heldNative);- await line(peerAfterDeath, "acquired");- await release(peerAfterDeath);- fileLock(fd, false, true);- fileLock(fd, true);- return {- peerRuntime: python === undefined ? "node" : "python",- peerContentionErrno: contention.errno,- nativeContentionErrno: nativeContention,- bidirectionalBlockingHandoff: true,- unlockHandoff: true,- peerDeathReleasesLock: true,- nativeDeathReleasesLock: true,- };- } finally {- closeSync(fd);- }-}--if (process.argv[2] === "lock-worker") {- await nativeLockWorker(process.argv[3]!);-} else {- const python = process.argv[2];- const scripts = process.argv[3];- assert.equal(- Boolean(python),- Boolean(scripts),- "Pass both the optional Python interpreter and legacy scripts directory",- );- const root = mkdtempSync(join(tmpdir(), "codex-security-native-"));- try {- const descriptors = descriptorProof(root);- const accounts = accountProof();- const locks = await lockProof(root);- const pythonCompatibility =- python && scripts ? await lockProof(root, python, scripts) : undefined;- console.log(- JSON.stringify(- {- node: process.version,- platform: process.platform,- architecture: process.arch,- nodeApi: 8,- descriptors,- accounts,- locks,- pythonCompatibility,- fixture: basename(root),- },- null,- 2,- ),- );- } finally {- for (const child of workers) {- if (child.child.exitCode === null && child.child.signalCode === null)- child.child.kill("SIGKILL");- }- await Promise.allSettled(workers.map((child) => child.exit));- rmSync(root, { recursive: true, force: true });- assert(!existsSync(root));- }-}+console.log(+ JSON.stringify(+ {+ node: process.version,+ platform: process.platform,+ architecture: process.arch,+ nodeApi: 8,+ accounts: accountProof(),+ },+ null,+ 2,+ ),+);diff --git a/plugins/codex-security/native/src/unix.rs b/plugins/codex-security/native/src/unix.rsindex 713b39abd..95e0f323d 100644--- a/plugins/codex-security/native/src/unix.rs+++ b/plugins/codex-security/native/src/unix.rs@@ -1,176 +1,6 @@use napi::bindgen_prelude::Buffer;use napi_derive::napi;-use std::{- ffi::{CStr, CString},- io,-};--#[napi(object)]-pub struct SyscallResult {- pub value: i32,- pub errno: i32,-}--fn result(value: i32) -> SyscallResult {- SyscallResult {- value,- errno: if value < 0 {- io::Error::last_os_error().raw_os_error().unwrap()- } else {- 0- },- }-}--fn retry_eintr(mut operation: impl FnMut() -> i32) -> SyscallResult {- loop {- let value = result(operation());- if value.errno != libc::EINTR {- return value;- }- }-}--fn path(value: Buffer) -> napi::Result<CString> {- CString::new(value.as_ref()).map_err(|_| napi::Error::from_reason("Path contains a NUL byte"))-}--#[napi]-pub fn open_at(directory: i32, name: Buffer, flags: i32, mode: u32) -> napi::Result<SyscallResult> {- let name = path(name)?;- let mode = mode as libc::mode_t;- // macOS mode_t is u16 and needs C integer promotion in this variadic call.- #[cfg(target_os = "macos")]- let mode = libc::c_int::from(mode);- Ok(retry_eintr(|| unsafe {- libc::openat(directory, name.as_ptr(), flags | libc::O_CLOEXEC, mode)- }))-}--#[napi]-pub fn make_directory_at(directory: i32, name: Buffer, mode: u32) -> napi::Result<SyscallResult> {- let name = path(name)?;- Ok(result(unsafe {- libc::mkdirat(directory, name.as_ptr(), mode as libc::mode_t)- }))-}--#[napi]-pub fn rename_at(- old_directory: i32,- old_name: Buffer,- new_directory: i32,- new_name: Buffer,-) -> napi::Result<SyscallResult> {- let old_name = path(old_name)?;- let new_name = path(new_name)?;- Ok(result(unsafe {- libc::renameat(- old_directory,- old_name.as_ptr(),- new_directory,- new_name.as_ptr(),- )- }))-}--#[napi]-pub fn unlink_at(directory: i32, name: Buffer) -> napi::Result<SyscallResult> {- let name = path(name)?;- Ok(result(unsafe {- libc::unlinkat(directory, name.as_ptr(), 0)- }))-}--#[napi]-pub fn duplicate(descriptor: i32) -> SyscallResult {- result(unsafe { libc::fcntl(descriptor, libc::F_DUPFD_CLOEXEC, 0) })-}--#[napi]-pub fn file_lock(descriptor: i32, unlock: bool, nonblocking: bool) -> SyscallResult {- let flags = if unlock {- libc::LOCK_UN- } else {- libc::LOCK_EX | if nonblocking { libc::LOCK_NB } else { 0 }- };- retry_eintr(|| unsafe { libc::flock(descriptor, flags) })-}--#[napi(object)]-pub struct MetadataResult {- pub errno: i32,- pub mode: u32,- pub device: String,- pub inode: String,-}--#[napi]-// libc stat field widths differ between Linux and macOS.-#[allow(clippy::unnecessary_cast)]-pub fn stat_at(directory: i32, name: Buffer) -> napi::Result<MetadataResult> {- let name = path(name)?;- let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();- let code = unsafe {- libc::fstatat(- directory,- name.as_ptr(),- stat.as_mut_ptr(),- libc::AT_SYMLINK_NOFOLLOW,- )- };- if code < 0 {- return Ok(MetadataResult {- errno: io::Error::last_os_error().raw_os_error().unwrap(),- mode: 0,- device: String::new(),- inode: String::new(),- });- }- let stat = unsafe { stat.assume_init() };- Ok(MetadataResult {- errno: 0,- mode: stat.st_mode as u32,- device: (stat.st_dev as u64).to_string(),- inode: stat.st_ino.to_string(),- })-}--#[napi(object)]-pub struct ReadLinkResult {- pub errno: i32,- pub value: Buffer,-}--#[napi]-pub fn read_link_at(directory: i32, name: Buffer) -> napi::Result<ReadLinkResult> {- let name = path(name)?;- let mut buffer = vec![0_u8; 256];- loop {- let length = unsafe {- libc::readlinkat(- directory,- name.as_ptr(),- buffer.as_mut_ptr().cast(),- buffer.len(),- )- };- if length < 0 {- return Ok(ReadLinkResult {- errno: io::Error::last_os_error().raw_os_error().unwrap(),- value: Vec::new().into(),- });- }- if (length as usize) < buffer.len() {- buffer.truncate(length as usize);- return Ok(ReadLinkResult {- errno: 0,- value: buffer.into(),- });- }- buffer.resize(buffer.len() * 2, 0);- }-}+use std::ffi::{CStr, CString};#[napi(object, use_nullable = true)]pub struct UserHomeResult {@@ -180,7 +10,8 @@ pub struct UserHomeResult {#[napi]pub fn user_home(username: Buffer) -> napi::Result<UserHomeResult> {- let username = path(username)?;+ let username = CString::new(username.as_ref())+ .map_err(|_| napi::Error::from_reason("Username contains a NUL byte"))?;let mut buffer = vec![0_u8; 1024];loop {let mut entry = std::mem::MaybeUninit::<libc::passwd>::uninit();diff --git a/plugins/codex-security/native/src/windows.rs b/plugins/codex-security/native/src/windows.rsindex 1ab3485e3..521fa721f 100644--- a/plugins/codex-security/native/src/windows.rs+++ b/plugins/codex-security/native/src/windows.rs@@ -1,9 +1,9 @@-use napi::bindgen_prelude::{BigInt, Buffer};+use napi::bindgen_prelude::Buffer;use napi_derive::napi;use std::{ffi::OsString,- fs::{self, File, TryLockError},- io::{self, Read, Seek, SeekFrom, Write},+ fs::{self, File},+ io::{self, Read, Write},mem::{offset_of, size_of, MaybeUninit},os::windows::{ffi::{OsStrExt, OsStringExt},@@ -13,10 +13,7 @@ use std::{ptr::{copy_nonoverlapping, null, null_mut},};use windows_sys::Win32::{- Foundation::{- GetLastError, SetLastError, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER,- ERROR_LOCK_VIOLATION, HANDLE, INVALID_HANDLE_VALUE,- },+ Foundation::{GetLastError, SetLastError, ERROR_INVALID_HANDLE, HANDLE, INVALID_HANDLE_VALUE},Storage::FileSystem::*,};@@ -229,12 +226,6 @@ pub struct IdentityResult {pub file_id: Buffer,}-#[napi(object)]-pub struct PositionResult {- pub error: u32,- pub value: String,-}-#[napi(object)]pub struct PathResult {pub error: u32,@@ -279,12 +270,6 @@ pub fn open_windows_file(})}-#[napi]-pub fn create_windows_directory(path: Buffer) -> napi::Result<u32> {- let path = wide_path(path)?;- Ok(status(unsafe { CreateDirectoryW(path.as_ptr(), null()) }))-}-#[napi]pub fn create_windows_directories(path: Buffer) -> napi::Result<u32> {Ok(io_status(fs::create_dir_all(os_string(path)?)))@@ -366,11 +351,7 @@ impl WindowsHandle {if length < capacity {return Ok(PathResult {error: 0,- path: path[..length as usize]- .iter()- .flat_map(|unit| unit.to_le_bytes())- .collect::<Vec<_>>()- .into(),+ path: wide_bytes(path[..length as usize].iter().copied()),});}path.resize(length as usize + 1, 0);@@ -398,56 +379,6 @@ impl WindowsHandle {})))}- #[napi]- pub fn seek(&self, distance: BigInt, origin: u32) -> napi::Result<PositionResult> {- let (distance, lossless) = distance.get_i64();- if !lossless {- return Err(invalid("Seek offset must fit a signed 64-bit integer"));- }- let result = self.file().and_then(|mut file| {- let position = match origin {- FILE_BEGIN => SeekFrom::Start(distance as u64),- FILE_CURRENT => SeekFrom::Current(distance),- FILE_END => SeekFrom::End(distance),- _ => return Err(io::Error::from_raw_os_error(ERROR_INVALID_PARAMETER as i32)),- };- file.seek(position)- });- Ok(match result {- Ok(value) => PositionResult {- error: 0,- value: (value as i64).to_string(),- },- Err(error) => PositionResult {- error: io_error(error),- value: "0".to_owned(),- },- })- }-- #[napi]- pub fn size(&self) -> PositionResult {- let mut value = 0;- let error = status(unsafe { GetFileSizeEx(self.raw(), &mut value) });- PositionResult {- error,- value: value.to_string(),- }- }-- #[napi]- pub fn set_end_of_file(&self) -> u32 {- io_status(self.file().and_then(|mut file| {- let position = file.stream_position()?;- file.set_len(position)- }))- }-- #[napi]- pub fn flush(&self) -> u32 {- io_status(self.file().and_then(File::sync_all))- }-#[napi]pub fn rename(&self, destination: Buffer, replace: bool) -> napi::Result<u32> {let path = wide_path(destination)?;@@ -493,25 +424,4 @@ impl WindowsHandle {)})}-- #[napi]- pub fn lock(&self, nonblocking: bool) -> u32 {- io_status(self.file().and_then(|file| {- if nonblocking {- file.try_lock().map_err(|error| match error {- TryLockError::WouldBlock => {- io::Error::from_raw_os_error(ERROR_LOCK_VIOLATION as i32)- }- TryLockError::Error(error) => error,- })- } else {- file.lock()- }- }))- }-- #[napi]- pub fn unlock(&self) -> u32 {- io_status(self.file().and_then(File::unlock))- }}diff --git a/plugins/codex-security/native/windows-binding.mts b/plugins/codex-security/native/windows-binding.mtsindex 7b90d458b..9a915f905 100644--- a/plugins/codex-security/native/windows-binding.mts+++ b/plugins/codex-security/native/windows-binding.mts@@ -15,15 +15,8 @@ export interface WindowsHandle {finalPath(flags: number): { error: number; path: Buffer };read(buffer: Buffer, offset: number, length: number): WindowsResult;write(buffer: Buffer, offset: number, length: number): WindowsResult;- seek(distance: bigint, origin: number): WindowsResult<string>;- size(): WindowsResult<string>;- setEndOfFile(): number;- flush(): number;rename(destination: Buffer, replace: boolean): number;setDisposition(deleteFile: boolean): number;- /** Acquires an exclusive whole-file lock; contention returns Windows error 33. */- lock(nonblocking: boolean): number;- unlock(): number;}/** Paths are UTF-16LE code units without a terminator, including lone surrogates. */@@ -43,7 +36,6 @@ export interface WindowsBinding {disposition: number,flags: number,): { error: number; handle?: WindowsHandle | null };- createWindowsDirectory(path: Buffer): number;createWindowsDirectories(path: Buffer): number;}diff --git a/plugins/codex-security/native/windows-flags.mts b/plugins/codex-security/native/windows-flags.mtsindex 5d351facf..032bf6346 100644--- a/plugins/codex-security/native/windows-flags.mts+++ b/plugins/codex-security/native/windows-flags.mts@@ -9,7 +9,6 @@ export const windowsFlags = {CREATE_NEW: 1,CREATE_ALWAYS: 2,OPEN_EXISTING: 3,- OPEN_ALWAYS: 4,FILE_ATTRIBUTE_DIRECTORY: 0x00000010,FILE_ATTRIBUTE_NORMAL: 0x00000080,FILE_ATTRIBUTE_REPARSE_POINT: 0x00000400,@@ -18,7 +17,4 @@ export const windowsFlags = {FILE_FLAG_OVERLAPPED: 0x40000000,FILE_NAME_OPENED: 8,VOLUME_NAME_GUID: 1,- FILE_BEGIN: 0,- FILE_CURRENT: 1,- FILE_END: 2,} as const;