Skip to content

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

fix(cli): update the active installation and migrate legacy options (#2579)

Michael D'Angelo6b17ee2d0fd4
diff --git a/github-action/README.md b/github-action/README.md
index 9a313252f..c43846214 100644
--- a/github-action/README.md
+++ b/github-action/README.md
@@ -444,7 +444,7 @@ with:
max-time-hours: "1"
```
-Deep mode does not support diff scans. `max-time-hours` limits Deep discovery;
+Deep mode does not support diff scans. `max-time-hours` limits Deep discovery (the Action converts hours to CLI minutes);
finalization can take additional time. It is unset by default, which uses the
CLI's default of 96 hours. Set an explicit budget for Deep scans that leaves
room for finalization within your job timeout. The one-hour discovery budget
diff --git a/github-action/dist/index.cjs b/github-action/dist/index.cjs
index a63febb34..45cd0743b 100644
--- a/github-action/dist/index.cjs
+++ b/github-action/dist/index.cjs
@@ -53829,7 +53829,7 @@ function scanArguments(inputs, target, resultsDirectory) {
["--diff", target.diffBase],
["--head", target.diffHead],
["--max-cost", inputs.maxCost],
- ["--max-time-hours", inputs.maxTimeHours]
+ ["--max-time", inputs.maxTimeHours === void 0 ? void 0 : inputs.maxTimeHours * 60]
];
for (const [name, value] of options) if (value !== void 0) args.push(name, String(value));
if (inputs.failOnSeverity !== "none") args.push("--fail-on-severity", inputs.failOnSeverity);
diff --git a/github-action/scripts/cli-integration.ts b/github-action/scripts/cli-integration.ts
index aee60a32d..e8b09fb0c 100644
--- a/github-action/scripts/cli-integration.ts
+++ b/github-action/scripts/cli-integration.ts
@@ -100,6 +100,7 @@ try {
assert.equal(deepPreflight.dryRun, true);
assert.equal(deepPreflight.mode, 'deep');
assert.equal(deepPreflight.maxTimeHours, 0.25);
+ assert.equal(deepPreflight.maxTimeMinutes, 15);
assert.deepEqual(deepPreflight.target.paths, ['example.ts']);
// Validate workflow model and cost settings against both the published pin and release candidates.
diff --git a/github-action/src/inputs.ts b/github-action/src/inputs.ts
index aae5bb34b..7e6335968 100644
--- a/github-action/src/inputs.ts
+++ b/github-action/src/inputs.ts
@@ -76,7 +76,7 @@ export function scanArguments(inputs: Inputs, target: {repository: string; diffB
const options: Array<[string, string | number | undefined]> = [
['--cyber-access-program', inputs.cyberAccessProgram],
['--diff', target.diffBase], ['--head', target.diffHead], ['--max-cost', inputs.maxCost],
- ['--max-time-hours', inputs.maxTimeHours],
+ ['--max-time', inputs.maxTimeHours === undefined ? undefined : inputs.maxTimeHours * 60],
];
for (const [name, value] of options) if (value !== undefined) args.push(name, String(value));
if (inputs.failOnSeverity !== 'none') args.push('--fail-on-severity', inputs.failOnSeverity);
diff --git a/github-action/tests/inputs.test.ts b/github-action/tests/inputs.test.ts
index 577a52646..119ae0564 100644
--- a/github-action/tests/inputs.test.ts
+++ b/github-action/tests/inputs.test.ts
@@ -13,7 +13,7 @@ test('defaults are stable across events', () => {
});
const args = scanArguments(input, {repository:'/checkout'}, '/results');
assert.equal(args[args.indexOf('--mode') + 1], 'standard');
- assert.ok(!args.includes('--max-time-hours'));
+ assert.ok(!args.includes('--max-time'));
assert.ok(!args.includes('--fail-on-severity'));
assert.ok(!args.includes('--python'));
assert.ok(!args.includes('--cyber-access-program'));
@@ -58,7 +58,7 @@ test('Deep scans forward an explicit discovery budget and selected repository pa
assert.equal(input.maxTimeHours, 1.5);
const args = scanArguments(input, {repository:'/checkout'}, '/results');
assert.equal(args[args.indexOf('--mode') + 1], 'deep');
- assert.equal(args[args.indexOf('--max-time-hours') + 1], '1.5');
+ assert.equal(args[args.indexOf('--max-time') + 1], '90');
assert.deepEqual(args.filter(arg => arg.startsWith('--path=')).map(arg => arg.slice('--path=./'.length)), ['src', 'lib']);
});
test('Deep scans leave an unset discovery budget to the CLI', () => {
@@ -66,7 +66,7 @@ test('Deep scans leave an unset discovery budget to the CLI', () => {
assert.equal(input.maxTimeHours, undefined);
const args = scanArguments(input, {repository:'/checkout'}, '/results');
assert.equal(args[args.indexOf('--mode') + 1], 'deep');
- assert.ok(!args.includes('--max-time-hours'));
+ assert.ok(!args.includes('--max-time'));
});
test('Deep scan mode and discovery budgets reject unsupported combinations', () => {
assert.throws(() => parse({mode:'thorough'}), /mode must be one of: standard, deep/);
diff --git a/github-action/tests/main.test.ts b/github-action/tests/main.test.ts
index 2405d8643..e5a0c8d67 100644
--- a/github-action/tests/main.test.ts
+++ b/github-action/tests/main.test.ts
@@ -280,7 +280,7 @@ test('Deep scans forward their budget and publish completed reports with cleanup
const result = await app.run();
assertAttribution(result.args, 'openai');
assert.equal(result.args[result.args.indexOf('--mode') + 1], 'deep');
- assert.equal(result.args[result.args.indexOf('--max-time-hours') + 1], '1.5');
+ assert.equal(result.args[result.args.indexOf('--max-time') + 1], '90');
assert.equal(result.exitCode, 0); assert.equal(result.cleanups, 1);
assert.equal(result.outputs['scan-status'], 'completed');
assert.equal(result.outputs['policy-status'], 'passed');
diff --git a/sdk/typescript/docs/cli.md b/sdk/typescript/docs/cli.md
index 5c22e6bc6..eaa02717c 100644
--- a/sdk/typescript/docs/cli.md
+++ b/sdk/typescript/docs/cli.md
@@ -37,6 +37,23 @@ codex-security info --json
- [Use a hosted executor](#hosted-standard-scan) or
[run bulk scans in containers](#containerized-bulk-scans).
+## Updating the CLI
+
+Run `cs --update` to update an npm global installation managed by the running
+Node distribution. It uses Node’s bundled npm, the public npm registry, and
+disabled lifecycle scripts. If you use a custom registry or proxy, run your
+package manager’s update command directly.
+
+For a project dependency, `cs --update` prints the package-manager command for
+you to run in the declaring project. For other global installations it prints
+the corresponding package-manager command and installation location. For npx,
+use `npx @openai/codex-security@latest` on the next run. For a standalone
+release, download and extract the latest release.
+
+Interactive update notices use the same installation detection. Set
+`CODEX_SECURITY_NO_UPDATE_NOTICE=1` to disable these notices. Explicit updates
+are available with notifications disabled.
+
## Authentication
Sign in with ChatGPT, or supply an API key for CI:
@@ -1774,7 +1791,8 @@ Select one completed scan by ID, prefix, `latest`, or directory; omit the select
for the picker. Live publication and `--skip-existing` require local history.
A directory-only dry run does not.
-`--linear-project PROJECT_ID` (`--project`) selects a project. Flags override
+`--linear-project PROJECT_ID` selects a project. Existing scripts using the deprecated
+`--project PROJECT_ID` spelling continue to work. Flags override
`CODEX_SECURITY_LINEAR_TEAM` and `CODEX_SECURITY_LINEAR_PROJECT`. `--dry-run`
previews titles offline; `--json` returns structured output.
@@ -1786,10 +1804,10 @@ Keys are omitted from saved results; diagnostic messages remain unchanged.
```bash
codex-security publish check /path/to/completed-scan \
- --to linear --linear-team TEAM_ID --json
+ --linear-team TEAM_ID --json
```
-`publish check` verifies artifacts and recorded publications. With an API key,
+`publish check` defaults to `--to linear`. It verifies artifacts and recorded publications. With an API key,
it also checks authentication and destination access. It does not test issue
creation; connected-app access is reported as `not-checked`.
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.ts
index 54b2bc9db..c5ff49ed4 100644
--- a/sdk/typescript/src/cli.ts
+++ b/sdk/typescript/src/cli.ts
@@ -403,6 +403,7 @@ import {
CODEX_EXECUTABLE_VERSION,
CODEX_SDK_VERSION,
formatUpdateNotice,
+ installUpdate,
invokedWithNpx,
updateNoticeEnabled,
type UpdateNotice,
@@ -588,7 +589,10 @@ function linearApiKeyOption() {
}
const PUBLICATION_DESTINATION_OPTIONS = z.object({
- to: z.literal("linear").describe("Publication destination."),
+ to: z
+ .literal("linear")
+ .default("linear")
+ .describe("Publication destination."),
linearTeam: optionValue("--linear-team")
.optional()
.describe("Linear team ID; defaults to CODEX_SECURITY_LINEAR_TEAM."),
@@ -4867,8 +4871,29 @@ export async function main(
configuration: z.record(z.string(), z.unknown()),
});
+ const inspectionFlags = [
+ "-h",
+ "--help",
+ "--version",
+ "--schema",
+ "--llms",
+ "--llms-full",
+ ];
+ if (
+ argv.includes("--update") &&
+ argv.some((arg) => inspectionFlags.includes(arg))
+ )
+ argv = argv.filter((arg) => arg !== "--update");
const cliOptions: Cli.create.Options = {
aliases: ["cs"],
+ // The SDK owns update notices and uses the same installation resolver for
+ // the explicit update action. Avoid Incur's second, global npm updater.
+ update: argv.includes("--update")
+ ? {
+ package: "@openai/codex-security",
+ install: () => installUpdate(dependencies.environment),
+ }
+ : false,
description: "Find, review, and fix security issues in your code.",
version: VERSION,
mcp: {
@@ -7716,15 +7741,7 @@ export async function main(
argv.length > 0 &&
argv[0] !== "completions" &&
!argv.some((argument) =>
- [
- "--help",
- "-h",
- "--version",
- "--llms",
- "--llms-full",
- "--schema",
- "--dry-run",
- ].includes(argument),
+ [...inspectionFlags, "--dry-run", "--update"].includes(argument),
) &&
updateNoticeEnabled(dependencies.environment)
? dependencies
diff --git a/sdk/typescript/src/version.ts b/sdk/typescript/src/version.ts
index c6db1b8da..da88b787b 100644
--- a/sdk/typescript/src/version.ts
+++ b/sdk/typescript/src/version.ts
@@ -1,6 +1,10 @@
import { isNonEmptyString } from "./value.js";
-import { readFileSync, realpathSync } from "node:fs";
-import { win32 } from "node:path";
+import { existsSync, readFileSync, realpathSync } from "node:fs";
+import { mkdtemp, rm } from "node:fs/promises";
+import { tmpdir, userInfo } from "node:os";
+import { dirname, join, resolve, win32 } from "node:path";
+import { once } from "node:events";
+import { spawn } from "node:child_process";
import { fileURLToPath } from "node:url";
import semverGt from "semver/functions/gt.js";
@@ -14,6 +18,8 @@ export const CODEX_EXECUTABLE_VERSION = PACKAGE_VERSIONS.executable;
export const BUNDLED_PLUGIN_VERSION = "0.1.95" as const;
const PACKAGE_NAME = "@openai/codex-security";
+const LATEST_PACKAGE = `${PACKAGE_NAME}@latest`;
+const PUBLIC_REGISTRY = "https://registry.npmjs.org/";
export interface UpdateNotice {
readonly currentVersion: string;
@@ -25,6 +31,7 @@ export function updateNoticeEnabled(environment: NodeJS.ProcessEnv): boolean {
return (
environment["CODEX_SECURITY_NO_UPDATE_NOTICE"] === undefined &&
environment["NO_UPDATE_NOTIFIER"] === undefined &&
+ environment["npm_config_update_notifier"] !== "false" &&
environment["CI"] === undefined
);
}
@@ -41,26 +48,27 @@ export function invokedWithNpx(
);
}
-export function updateCommand(
+function resolveUpdate(
environment: NodeJS.ProcessEnv = process.env,
entrypoint: string = fileURLToPath(import.meta.url),
nodeExecutable: string | undefined = process.platform === "win32"
? realpathSync(process.execPath)
: undefined,
-): string {
+) {
const windowsPath =
!entrypoint.startsWith("/") && win32.isAbsolute(entrypoint);
const path =
process.platform === "linux" && !windowsPath
? entrypoint
: entrypoint.replaceAll("\\", "/").toLowerCase();
- const agent = (environment["npm_config_user_agent"] ?? "").toLowerCase();
if (invokedWithNpx(environment, path)) {
- return `npx ${PACKAGE_NAME}@latest`;
+ return { command: `npx ${LATEST_PACKAGE}` } as const;
}
if (path.includes("/.install/node_modules/")) {
- return "download and extract the latest Codex Security release";
+ return {
+ command: "download and extract the latest Codex Security release",
+ } as const;
}
const nodeModulesDirectory =
@@ -70,35 +78,206 @@ export function updateCommand(
.join(win32.dirname(nodeExecutable), "node_modules")
.replaceAll("\\", "/")
.toLowerCase();
+ const modules = path.indexOf("/node_modules/");
+ const directory =
+ modules < 0 ? dirname(entrypoint) : entrypoint.slice(0, modules + 1);
+ const installRoot = modules < 0 ? path : path.slice(0, modules + 1);
+ let manifest: Record<string, unknown> | undefined;
+ if (modules >= 0) {
+ try {
+ manifest = JSON.parse(
+ readFileSync(join(directory, "package.json"), "utf8"),
+ );
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ }
+ const fields = [
+ "dependencies",
+ "devDependencies",
+ "optionalDependencies",
+ "peerDependencies",
+ ].filter((key) => Object.hasOwn(manifest?.[key] ?? {}, PACKAGE_NAME));
+ const globalLayouts = [
+ ["/pnpm/global/", "pnpm"],
+ ["/.bun/install/global/", "bun"],
+ ["/.yarn/global/", "yarn"],
+ ["/yarn/global/", "yarn"],
+ ["/yarn/data/global/", "yarn"],
+ ] as const;
+ const globalManager = globalLayouts.find(([part]) =>
+ installRoot.includes(part),
+ )?.[1];
const global =
- environment["npm_config_global"] === "true" ||
- path.includes("/lib/node_modules/") ||
- path.includes("/appdata/roaming/npm/node_modules/") ||
+ Boolean(globalManager) ||
+ (installRoot.endsWith("/lib/") && manifest === undefined) ||
+ installRoot.endsWith("/appdata/roaming/npm/") ||
(nodeModulesDirectory !== undefined &&
- path.startsWith(`${nodeModulesDirectory}/`)) ||
- path.includes("/pnpm/global/") ||
- path.includes("/.bun/install/global/") ||
- path.includes("/.yarn/global/") ||
- path.includes("/yarn/global/") ||
- path.includes("/yarn/data/global/");
-
- if (agent.startsWith("pnpm/") || path.includes("/.pnpm/")) {
- return `pnpm add${global ? " -g" : ""} ${PACKAGE_NAME}@latest`;
+ path.startsWith(`${nodeModulesDirectory}/`));
+ if (!global && modules < 0)
+ return { command: `npx ${LATEST_PACKAGE}` } as const;
+
+ // A manager-specific store takes precedence over manifests, lockfiles, and
+ // the shell's user agent. Global installs are independent of the caller.
+ const managers = ["pnpm", "yarn", "bun"];
+ let manager =
+ globalManager ?? managers.find((name) => path.includes(`/.${name}/`));
+ if (!manager && !global) {
+ const packageManager = manifest?.["packageManager"];
+ const locks = [
+ ["pnpm-lock.yaml", "pnpm"],
+ ["yarn.lock", "yarn"],
+ ["bun.lock", "bun"],
+ ["bun.lockb", "bun"],
+ ["package-lock.json", "npm"],
+ ] as const;
+ const selected =
+ (typeof packageManager === "string"
+ ? packageManager.split("@")[0]
+ : undefined) ??
+ locks.find(([file]) => existsSync(join(directory, file)))?.[1] ??
+ environment["npm_config_user_agent"]?.toLowerCase().split("/")[0];
+ manager = managers.find((name) => name === selected);
}
- if (
- agent.startsWith("yarn/") ||
- path.includes("/.yarn/") ||
- path.includes("/yarn/global/") ||
- path.includes("/yarn/data/global/")
- ) {
- return `yarn${global ? " global" : ""} add ${PACKAGE_NAME}@latest`;
+ manager ??= "npm";
+ const args = [manager === "npm" ? "install" : "add"];
+ const direct = fields.length === 1;
+ if (global) {
+ if (manager === "yarn") args.unshift("global");
+ else args.push("-g");
+ } else if (direct) {
+ if (
+ manager === "pnpm" &&
+ existsSync(join(directory, "pnpm-workspace.yaml"))
+ )
+ args.push("--workspace-root");
+ const npmFlags = manager === "npm" || manager === "pnpm";
+ const flags: Record<string, string> = {
+ devDependencies: npmFlags ? "--save-dev" : "--dev",
+ optionalDependencies: npmFlags ? "--save-optional" : "--optional",
+ peerDependencies: npmFlags ? "--save-peer" : "--peer",
+ };
+ const flag = flags[fields[0]!];
+ if (flag) args.push(flag);
}
- if (agent.startsWith("bun/") || path.includes("/.bun/")) {
- return `bun add${global ? " -g" : ""} ${PACKAGE_NAME}@latest`;
+ args.push(LATEST_PACKAGE);
+ return {
+ command: [manager, ...args].join(" "),
+ manager,
+ global,
+ directory,
+ direct,
+ } as const;
+}
+
+export function updateCommand(
+ environment?: NodeJS.ProcessEnv,
+ entrypoint?: string,
+ nodeExecutable?: string,
+): string {
+ return resolveUpdate(environment, entrypoint, nodeExecutable).command;
+}
+
+/** Update a known npm global installation, or explain how to update it manually. */
+export async function installUpdate(
+ environment: NodeJS.ProcessEnv,
+ entrypoint = fileURLToPath(import.meta.url),
+ nodeExecutable = process.execPath,
+): Promise<void> {
+ const windows = process.platform === "win32";
+ const update = resolveUpdate(
+ environment,
+ entrypoint,
+ windows ? nodeExecutable : undefined,
+ );
+ if (!update.manager)
+ throw new Error(`To use the latest version, ${update.command}.`);
+ if (!update.global) {
+ const project = update.direct
+ ? JSON.stringify(resolve(update.directory))
+ : `the project that declares ${PACKAGE_NAME}`;
+ throw new Error(`Run ${update.command} from ${project}.`);
+ }
+
+ // Only Node's own npm can run without consulting PATH, shims or project
+ // package-manager plugins. Point other global installations to their owner.
+ const prefix =
+ !windows && update.manager === "npm"
+ ? dirname(update.directory)
+ : resolve(update.directory);
+ const manual = `Use the installation at ${JSON.stringify(prefix)} to run ${update.command}.`;
+ if (update.manager !== "npm") throw new Error(manual);
+ const node = realpathSync(nodeExecutable);
+ const nodeBin = dirname(node);
+ const nodePrefix = windows ? nodeBin : dirname(nodeBin);
+ if (
+ resolve(prefix) !== nodePrefix &&
+ !(
+ windows &&
+ resolve(prefix) === join(userInfo().homedir, "AppData", "Roaming", "npm")
+ )
+ )
+ throw new Error(manual);
+ const npm = join(
+ windows ? nodePrefix : join(nodePrefix, "lib"),
+ "node_modules",
+ "npm",
+ "bin",
+ "npm-cli.js",
+ );
+ if (!existsSync(npm) || realpathSync(npm) !== npm) throw new Error(manual);
+
+ process.stderr.write(
+ `Running ${update.command} for ${JSON.stringify(prefix)}\n`,
+ );
+ await runGlobalNpm(node, npm, prefix);
+}
+
+async function runGlobalNpm(
+ node: string,
+ npm: string,
+ prefix: string,
+): Promise<void> {
+ const scratch = realpathSync(
+ await mkdtemp(join(tmpdir(), "codex-security-update-")),
+ );
+ try {
+ // A fresh home and cache avoid user credentials and registry overrides.
+ // Global npm ignores project configuration; explicitly disable lifecycle
+ // scripts and pin both the default registry and the @openai scope.
+ const env: NodeJS.ProcessEnv = {
+ HOME: scratch,
+ USERPROFILE: scratch,
+ PATH: dirname(node),
+ npm_config_cache: join(scratch, "cache"),
+ npm_config_userconfig: join(scratch, "user.npmrc"),
+ npm_config_globalconfig: join(scratch, "global.npmrc"),
+ ...(process.platform === "win32" && {
+ SystemRoot: process.env["SystemRoot"],
+ }),
+ };
+ const args = [
+ npm,
+ "install",
+ "-g",
+ LATEST_PACKAGE,
+ "--prefix",
+ prefix,
+ "--ignore-scripts",
+ `--registry=${PUBLIC_REGISTRY}`,
+ `--@openai:registry=${PUBLIC_REGISTRY}`,
+ ];
+ const child = spawn(node, args, {
+ cwd: scratch,
+ env,
+ stdio: ["ignore", process.stderr, process.stderr],
+ });
+ const [code, signal] = await once(child, "close");
+ if (code !== 0)
+ throw new Error(`npm install exited with ${signal ?? code}.`);
+ } finally {
+ await rm(scratch, { force: true, recursive: true });
}
- return agent.startsWith("npm/") || path.includes("/node_modules/")
- ? `npm install${global ? " -g" : ""} ${PACKAGE_NAME}@latest`
- : `npx ${PACKAGE_NAME}@latest`;
}
export async function checkForUpdate({
@@ -124,7 +303,7 @@ export async function checkForUpdate({
environment["CODEX_SECURITY_NPM_REGISTRY"] ??
environment["npm_config_registry"] ??
environment["NPM_CONFIG_REGISTRY"] ??
- "https://registry.npmjs.org/";
+ PUBLIC_REGISTRY;
const timeout = AbortSignal.timeout(3_000);
const response = await fetchLatest(
new URL(
diff --git a/sdk/typescript/tests-ts/cli-publish.test.ts b/sdk/typescript/tests-ts/cli-publish.test.ts
index 31db8fa01..1a986f4c9 100644
--- a/sdk/typescript/tests-ts/cli-publish.test.ts
+++ b/sdk/typescript/tests-ts/cli-publish.test.ts
@@ -726,9 +726,12 @@ describe("publish check", () => {
expect(stdout.text().trim()).toBe("");
});
- test.each(["completed-scan", "~/completed-scan"])(
+ test.each([
+ ["completed-scan", DESTINATION_OPTIONS.slice(2)],
+ ["~/completed-scan", DESTINATION_OPTIONS],
+ ] as const)(
"resolves %s and shared options without invoking publication",
- async (scanDir) => {
+ async (scanDir, options) => {
const { stdout, stderr, runCli } = createCliTest(main);
const currentDirectory = join(tmpdir(), "codex-security-check-current");
@@ -781,7 +784,7 @@ describe("publish check", () => {
"publish",
"check",
scanDir,
- ...DESTINATION_OPTIONS,
+ ...options,
"--linear-api-key",
"explicit-key",
"--linear-assignee",
diff --git a/sdk/typescript/tests-ts/update-notice.test.ts b/sdk/typescript/tests-ts/update-notice.test.ts
index a0b124d3d..784b53f75 100644
--- a/sdk/typescript/tests-ts/update-notice.test.ts
+++ b/sdk/typescript/tests-ts/update-notice.test.ts
@@ -1,12 +1,21 @@
import { createCliTest, runCapturedCli } from "./support/cli-run.js";
import { once } from "node:events";
-import { mkdirSync, symlinkSync, writeFileSync } from "node:fs";
+import {
+ copyFileSync,
+ existsSync,
+ constants,
+ mkdirSync,
+ readFileSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
import { join } from "node:path";
import { resolving } from "./support/promises.js";
import { describe, expect, test, mock } from "bun:test";
import {
checkForUpdate,
formatUpdateNotice,
+ installUpdate,
updateCommand,
} from "../src/version.js";
import { capture, dependencies, FakeSignals } from "./cli-fixtures.js";
@@ -160,6 +169,179 @@ describe("CLI update notice", () => {
}
});
+ test("selects supported options for workspace roots and optional dependencies", () => {
+ const directories = createTemporaryDirectoriesSync(true);
+ const root = directories.create("codex-update-options-");
+ const entrypoint = join(
+ root,
+ "node_modules",
+ "@openai",
+ "codex-security",
+ "dist",
+ "version.js",
+ );
+ try {
+ writeFileSync(join(root, "pnpm-workspace.yaml"), "packages: ['apps/*']");
+ for (const [manager, category, expected] of [
+ [
+ "pnpm",
+ "optionalDependencies",
+ "pnpm add --workspace-root --save-optional",
+ ],
+ ["pnpm", "peerDependencies", "pnpm add --workspace-root --save-peer"],
+ ["bun", "optionalDependencies", "bun add --optional"],
+ ] as const) {
+ writeFileSync(
+ join(root, "package.json"),
+ JSON.stringify({
+ packageManager: manager + "@1.0.0",
+ [category]: { "@openai/codex-security": "0.9.0" },
+ }),
+ );
+ expect(updateCommand({}, entrypoint)).toBe(
+ expected + " @openai/codex-security@latest",
+ );
+ }
+ } finally {
+ directories.cleanup();
+ }
+ });
+
+ test("project updates provide a command without loading package-manager configuration", async () => {
+ const directories = createTemporaryDirectoriesSync(true);
+ const project = directories.create("codex-update-project-");
+ const marker = join(project, "manager-ran");
+ const entrypoint = join(
+ project,
+ "node_modules",
+ "@openai",
+ "codex-security",
+ "dist",
+ "version.js",
+ );
+ try {
+ writeFileSync(
+ join(project, ".npmrc"),
+ "@openai:registry=http://127.0.0.1:1/",
+ );
+ writeFileSync(
+ join(project, "package.json"),
+ JSON.stringify({
+ devDependencies: { "@openai/codex-security": "0.9.0" },
+ scripts: { preinstall: "node hook.cjs" },
+ }),
+ );
+ writeFileSync(
+ join(project, "hook.cjs"),
+ 'require("node:fs").writeFileSync("manager-ran", "ran")',
+ );
+ writeFileSync(
+ join(project, process.platform === "win32" ? "npm.cmd" : "npm"),
+ process.platform === "win32"
+ ? '@echo ran > "%UPDATE_MARKER%"'
+ : '#!/bin/sh\necho ran > "$UPDATE_MARKER"',
+ { mode: 0o755 },
+ );
+ const env = {
+ PATH: project,
+ UPDATE_MARKER: marker,
+ npm_config_userconfig: join(project, ".npmrc"),
+ };
+ await expect(installUpdate(env, entrypoint)).rejects.toThrow(
+ `Run npm install --save-dev @openai/codex-security@latest from ${JSON.stringify(project)}`,
+ );
+ expect(existsSync(marker)).toBe(false);
+ writeFileSync(join(project, "package.json"), "{}");
+ await expect(installUpdate(env, entrypoint)).rejects.toThrow(
+ "from the project that declares",
+ );
+ await expect(
+ installUpdate({ ...env, npm_command: "exec" }, entrypoint),
+ ).rejects.toThrow("npx @openai/codex-security@latest");
+ } finally {
+ directories.cleanup();
+ }
+ });
+
+ test("global npm updates support nvm checkouts and isolate npm from the invoking project", async () => {
+ const directories = createTemporaryDirectoriesSync(true);
+ const root = directories.create("codex-update-global-");
+ const nvm = join(root, ".nvm");
+ const prefix = join(nvm, "versions", "node", "v24.0.0");
+ const windows = process.platform === "win32";
+ const bin = windows ? prefix : join(prefix, "bin");
+ const modules = join(
+ windows ? prefix : join(prefix, "lib"),
+ "node_modules",
+ );
+ const npmBin = join(modules, "npm", "bin");
+ const node = join(bin, windows ? "node.exe" : "node");
+ const entrypoint = join(
+ modules,
+ "@openai",
+ "codex-security",
+ "dist",
+ "version.js",
+ );
+ const record = join(prefix, "invocation.json");
+ try {
+ mkdirSync(join(nvm, ".git"), { recursive: true });
+ mkdirSync(bin, { recursive: true });
+ mkdirSync(npmBin, { recursive: true });
+ copyFileSync(process.execPath, node, constants.COPYFILE_FICLONE);
+ writeFileSync(
+ join(npmBin, "npm-cli.js"),
+ `require("node:fs").writeFileSync(${JSON.stringify(record)}, JSON.stringify({cwd: process.cwd(), env: process.env, args: process.argv.slice(2)}));`,
+ );
+ const env = {
+ PATH: prefix,
+ OPENAI_API_KEY: "test-value",
+ NODE_OPTIONS: "--require=missing.cjs",
+ npm_config_registry: "http://127.0.0.1:1/",
+ };
+ await installUpdate(env, entrypoint, node);
+ const call = JSON.parse(readFileSync(record, "utf8"));
+ expect(call.env.OPENAI_API_KEY).toBeUndefined();
+ expect(call.env.NODE_OPTIONS).toBeUndefined();
+ expect(call.env.npm_config_registry).toBeUndefined();
+ expect(existsSync(call.cwd)).toBe(false);
+ expect(call.env.HOME).toBe(call.cwd);
+ expect(call.env.PATH).toBe(bin);
+ expect(call.env.npm_config_userconfig).toBe(join(call.cwd, "user.npmrc"));
+ expect(call.env.npm_config_globalconfig).toBe(
+ join(call.cwd, "global.npmrc"),
+ );
+ expect(call.args).toEqual([
+ "install",
+ "-g",
+ "@openai/codex-security@latest",
+ "--prefix",
+ prefix,
+ "--ignore-scripts",
+ "--registry=https://registry.npmjs.org/",
+ "--@openai:registry=https://registry.npmjs.org/",
+ ]);
+ } finally {
+ directories.cleanup();
+ }
+ });
+
+ test("metadata takes precedence over an explicit update", async () => {
+ for (const flag of ["--help", "--version", "--schema", "--llms"]) {
+ const { stdout, stderr, runCli } = createCliTest(main);
+ expect(
+ await runCli(
+ ["--update", flag],
+ dependencies({
+ environment: { npm_command: "exec" },
+ }),
+ ),
+ ).toBe(0);
+ expect(stdout.text()).not.toBe("");
+ expect(stderr.text()).toBe("");
+ }
+ });
+
test("recognizes Windows globals through a linked Node directory", () => {
const temporaryDirectories = createTemporaryDirectoriesSync(true);
const root = temporaryDirectories.create("codex-update-notice-");
@@ -260,6 +442,7 @@ describe("CLI update notice", () => {
for (const environment of [
{ CODEX_SECURITY_NO_UPDATE_NOTICE: "1" },
{ NO_UPDATE_NOTIFIER: "1" },
+ { npm_config_update_notifier: "false" },
{ CI: "true" },
]) {
expect(