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
fix(cli): keep optional update notices nonblocking (#409)
mldangelo-oaiedfe3a70df70
diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex abfc86f63..9f73b0489 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -368,7 +368,7 @@ interface CliDependencies {bulkScan?: BulkScanDiscoveryDependencies;runWorkbench(args: readonly string[]): Promise<JsonObject>;matchFindings: typeof matchScanFindings;- checkForUpdate(): Promise<UpdateNotice | undefined>;+ checkForUpdate(signal: AbortSignal): Promise<UpdateNotice | undefined>;}const DEFAULT_DEPENDENCIES: CliDependencies = {@@ -376,7 +376,8 @@ const DEFAULT_DEPENDENCIES: CliDependencies = {createSecurityInternal(config, { surface: "cli" }),environment: process.env,prepareAuthenticationHome: prepareCodexSecurityCredentialHome,- checkForUpdate: () => checkForUpdate({ environment: process.env }),+ checkForUpdate: (signal) =>+ checkForUpdate({ environment: process.env, signal }),hasStoredChatGPTSignIn: async () => {const environment = Object.fromEntries(Object.entries(process.env).filter(@@ -706,6 +707,7 @@ export async function main(errorOutput.write(`codex-security: ${argumentError}\n`);return 2;}+ const updateController = new AbortController();const pendingUpdate =errorOutput.isTTY === true &&argv.length > 0 &&@@ -722,7 +724,9 @@ export async function main(].includes(argument),) &&updateNoticeEnabled(dependencies.environment)- ? dependencies.checkForUpdate().catch(() => undefined)+ ? dependencies+ .checkForUpdate(updateController.signal)+ .catch(() => undefined): undefined;let exitCode = 0;let frameworkExit: number | undefined;@@ -1875,25 +1879,30 @@ export async function main(},});- await cli.serve(- argv.flatMap((argument) =>- argument.startsWith("--format=")- ? ["--format", argument.slice("--format=".length)]- : [argument],- ),- {- stdout: (value) => {- frameworkOutput += value;- },- exit: (code) => {- frameworkExit = code;+ let notice: UpdateNotice | undefined;+ try {+ await cli.serve(+ argv.flatMap((argument) =>+ argument.startsWith("--format=")+ ? ["--format", argument.slice("--format=".length)]+ : [argument],+ ),+ {+ stdout: (value) => {+ frameworkOutput += value;+ },+ exit: (code) => {+ frameworkExit = code;+ },},- },- );- if (pendingUpdate !== undefined) {- const notice = await pendingUpdate;- if (notice !== undefined) errorOutput.write(formatUpdateNotice(notice));+ );+ if (pendingUpdate !== undefined) {+ notice = await Promise.race([pendingUpdate, undefined]);+ }+ } finally {+ updateController.abort();}+ if (notice !== undefined) errorOutput.write(formatUpdateNotice(notice));if (frameworkExit !== undefined) {if (exitCode !== 0) return exitCode;errorOutput.write(diff --git a/sdk/typescript/src/version.ts b/sdk/typescript/src/version.tsindex ef777c7d4..01dd50067 100644--- a/sdk/typescript/src/version.ts+++ b/sdk/typescript/src/version.ts@@ -78,6 +78,7 @@ export async function checkForUpdate({entrypoint,currentVersion = VERSION,fetch: fetchLatest = fetch,+ signal,}: {environment?: NodeJS.ProcessEnv;entrypoint?: string;@@ -86,6 +87,7 @@ export async function checkForUpdate({input: Parameters<typeof fetch>[0],init?: Parameters<typeof fetch>[1],) => ReturnType<typeof fetch>;+ signal?: AbortSignal;} = {}): Promise<UpdateNotice | undefined> {if (!updateNoticeEnabled(environment)) return undefined;@@ -95,12 +97,16 @@ export async function checkForUpdate({environment["npm_config_registry"] ??environment["NPM_CONFIG_REGISTRY"] ??"https://registry.npmjs.org/";+ const timeout = AbortSignal.timeout(3_000);const response = await fetchLatest(new URL(`${encodeURIComponent(PACKAGE_NAME)}/latest`,registry.endsWith("/") ? registry : `${registry}/`,),- { signal: AbortSignal.timeout(3_000) },+ {+ signal:+ signal === undefined ? timeout : AbortSignal.any([signal, timeout]),+ },);if (!response.ok) return undefined;diff --git a/sdk/typescript/tests-ts/cli-fixtures.ts b/sdk/typescript/tests-ts/cli-fixtures.tsindex 4a51cc3e0..01b839bc1 100644--- a/sdk/typescript/tests-ts/cli-fixtures.ts+++ b/sdk/typescript/tests-ts/cli-fixtures.ts@@ -194,7 +194,7 @@ export function dependencies(bulkScan?: MainDependencies["bulkScan"];onWorkbench?: (args: readonly string[]) => JsonObject | Promise<JsonObject>;onMatch?: MainDependencies["matchFindings"];- onUpdateCheck?: () => Promise<UpdateNotice | undefined>;+ onUpdateCheck?: (signal: AbortSignal) => Promise<UpdateNotice | undefined>;currentDirectory?: string;preflight?: ScanPreflight;environment?: NodeJS.ProcessEnv;@@ -243,7 +243,7 @@ export function dependencies(return security;},environment: options.environment ?? {},- checkForUpdate: async () => await options.onUpdateCheck?.(),+ checkForUpdate: async (signal) => await options.onUpdateCheck?.(signal),currentDirectory: () => options.currentDirectory ?? "/current/repository",now: () => 0,setInterval: () => ({}) as NodeJS.Timeout,diff --git a/sdk/typescript/tests-ts/update-notice.test.ts b/sdk/typescript/tests-ts/update-notice.test.tsindex bc2f84241..4a41976a2 100644--- a/sdk/typescript/tests-ts/update-notice.test.ts+++ b/sdk/typescript/tests-ts/update-notice.test.ts@@ -49,6 +49,29 @@ describe("CLI update notice", () => {);});+ test("cancels registry requests when the caller aborts", async () => {+ const controller = new AbortController();+ let requestSignal: AbortSignal | undefined;+ const pending = checkForUpdate({+ environment: {},+ signal: controller.signal,+ fetch: async (_url, options) => {+ requestSignal = options?.signal ?? undefined;+ return await new Promise<Response>((_resolve, reject) => {+ requestSignal?.addEventListener(+ "abort",+ () => reject(requestSignal?.reason),+ { once: true },+ );+ });+ },+ });++ controller.abort();+ expect(requestSignal?.aborted).toBe(true);+ await expect(pending).resolves.toBeUndefined();+ });+test("recognizes npx and local or global npm, pnpm, Yarn, and Bun", () => {const installed = "/workspace/node_modules/pkg/dist/version.js";const packageName = "@openai/codex-security@latest";@@ -191,6 +214,30 @@ describe("CLI update notice", () => {expect(stderr.text()).not.toContain("CODEX_SECURITY_NO_UPDATE_NOTICE");});+ test("finishes the command and aborts an unfinished update check", async () => {+ const stdout = capture();+ const stderr = capture(true);+ let updateSignal: AbortSignal | undefined;+ const result = await main(+ ["info", "--json"],+ stdout.stream,+ stderr.stream,+ dependencies({+ onUpdateCheck: async (signal) => {+ updateSignal = signal;+ return await new Promise<undefined>(() => {});+ },+ }),+ );++ expect(result).toBe(0);+ expect(updateSignal?.aborted).toBe(true);+ expect(JSON.parse(stdout.text())).toMatchObject({+ cliVersion: expect.any(String),+ });+ expect(stderr.text()).toBe("");+ });+test("skips checks for noninteractive output, help, dry runs, and disabled notices", async () => {let checks = 0;const onUpdateCheck = async () => {