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
feat(cli): add findings service serve command (#719)
Kyle Brown68b187c2892a
diff --git a/README.md b/README.mdindex 8b3a61936..15f44770f 100644--- a/README.md+++ b/README.md@@ -52,6 +52,10 @@ findings service, use the same scanner image with the## Findings service (preview)+Run `codex-security serve` to start the service without Docker. See+[running without Docker](sdk/typescript/README.md#running-without-docker)+for prerequisites, credentials, and storage configuration.+The [findings service](sdk/typescript/README.md#findings-service-preview) runsfrom the same `ghcr.io/openai/codex-security` image as the scanner (or a localsource build), with a separate container and state volume configured bydiff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex aef85bd58..30cd43a7d 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1405,16 +1405,32 @@ migrated database.### Running without Docker-To run locally, use Node.js and Python 3 as described in the prerequisites.-Export the API key in your shell; the server does not load `.env` automatically.-From `sdk/typescript`, install dependencies, build, and start:+With Node.js and Python 3 installed:++```bash+npm install -g @openai/codex-security+CODEX_SECURITY_STATE_DIR="$HOME/.codex-security-findings" codex-security serve --port 3000+```++`--port` overrides `PORT` (default: `3000`). Open+`http://127.0.0.1:3000/dashboard`. Stop with Ctrl+C or SIGTERM.++Export `OPENAI_API_KEY` or `CODEX_API_KEY` to import findings with embeddings.+Startup and listing need no key. The service does not load `.env` or authenticate+requests; keep it on loopback or behind an authenticated TLS proxy.++From a source checkout's `sdk/typescript` directory:```bashpnpm install --frozen-lockfile+npm ci --prefix ../../plugins/codex-security/mcp-app+pnpm run build:pluginpnpm run build-pnpm run start:server+node bin/codex-security.mjs serve --port 3000```+`pnpm run start:server` and `node dist/server/index.js` still work.+Local defaults are `HOST=127.0.0.1` and `PORT=3000`. The existing`CODEX_SECURITY_STATE_DIR` and `PYTHON` settings select storage and Python;without a state override, the service uses the same default state directory asdiff --git a/sdk/typescript/scripts/check-package.mjs b/sdk/typescript/scripts/check-package.mjsindex 313f99fec..333dafd88 100644--- a/sdk/typescript/scripts/check-package.mjs+++ b/sdk/typescript/scripts/check-package.mjs@@ -219,6 +219,7 @@ const distFiles = new Set("server/findings-service","server/routes","server/server",+ "server/serve","server/sqlite-store","server/storage","server/validation",diff --git a/sdk/typescript/src/cli.ts b/sdk/typescript/src/cli.tsindex 5cdf25f7b..33bf8aca9 100644--- a/sdk/typescript/src/cli.ts+++ b/sdk/typescript/src/cli.ts@@ -240,6 +240,7 @@ const EXPORT_DEFAULT_OUTPUTS = {sarif: "results.sarif",} as const;const VALUE_OPTIONS = new Set([+ "--port","--workflow-id","--auth","--safety-identifier",@@ -4359,6 +4360,37 @@ export async function main(}},})+ .command("serve", {+ description:+ "Start the findings HTTP service (HOST=127.0.0.1, PORT=3000).",+ destructive: true,+ mcp: false,+ options: z.object({+ port: z+ .number()+ .int()+ .min(0)+ .max(65535)+ .optional()+ .describe(+ "Listen port (default: PORT or 3000; 0 picks a free port).",+ ),+ }),+ async run({ options }) {+ try {+ const { serveFindings } = await import("./server/serve.js");+ await serveFindings(+ options.port === undefined+ ? dependencies.environment+ : { ...dependencies.environment, PORT: String(options.port) },+ output,+ );+ } catch (error) {+ errorOutput.write(`codex-security: ${errorMessage(error)}\n`);+ exitCode = 1;+ }+ },+ }).command("info", {description: "Show read-only SDK and bundled-plugin metadata.",mcp: {@@ -4638,6 +4670,7 @@ function validateCliArguments("patch","login","logout",+ "serve","info",].includes(value),);@@ -4656,7 +4689,7 @@ function validateCliArguments();if (structuredOutput &&- ["validate", "login", "logout"].includes(command) &&+ ["validate", "login", "logout", "serve"].includes(command) &&!argv.includes("--schema")) {return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;@@ -4769,7 +4802,7 @@ function validateCliArguments(command !== "verify-fix" &&command !== "patch" &&positionals.length >- (command === "logout" || command === "info"+ (command === "logout" || command === "info" || command === "serve"? 0: subcommand === "compare" || subcommand === "match"? 2diff --git a/sdk/typescript/src/server/index.ts b/sdk/typescript/src/server/index.tsindex 6ebc86cec..0af340818 100644--- a/sdk/typescript/src/server/index.ts+++ b/sdk/typescript/src/server/index.ts@@ -1,38 +1,6 @@-import { startFindingsServer } from "./server.js";-import { SqliteFindingsStore } from "./sqlite-store.js";-import { OpenAiFindingEmbedder } from "./embeddings.js";+import { serveFindings } from "./serve.js";-async function main(): Promise<void> {- const host = process.env["HOST"] ?? "127.0.0.1";- const port = Number(process.env["PORT"] ?? 3000);- const server = await startFindingsServer({- store: new SqliteFindingsStore(),- embeddings: new OpenAiFindingEmbedder(- process.env["OPENAI_API_KEY"] ?? process.env["CODEX_API_KEY"],- ),- host,- port,- });- const address = server.address();- if (address !== null && typeof address !== "string") {- console.log(- `Findings service listening on ${address.address}:${address.port}`,- );- }-- const shutdown = () => {- server.close((error) => {- if (error !== undefined) {- console.error(error);- process.exitCode = 1;- }- });- };- process.once("SIGINT", shutdown);- process.once("SIGTERM", shutdown);-}--main().catch((error: unknown) => {+serveFindings().catch((error: unknown) => {console.error(error);process.exitCode = 1;});diff --git a/sdk/typescript/src/server/serve.ts b/sdk/typescript/src/server/serve.tsnew file mode 100644index 000000000..f7a6a9c10--- /dev/null+++ b/sdk/typescript/src/server/serve.ts@@ -0,0 +1,36 @@+import { startFindingsServer } from "./server.js";+import { SqliteFindingsStore } from "./sqlite-store.js";+import { OpenAiFindingEmbedder } from "./embeddings.js";++export async function serveFindings(+ environment: NodeJS.ProcessEnv = process.env,+ output: Pick<NodeJS.WriteStream, "write"> = process.stdout,+): Promise<void> {+ const host = environment["HOST"] ?? "127.0.0.1";+ const port = Number(environment["PORT"] ?? 3000);+ const server = await startFindingsServer({+ store: new SqliteFindingsStore(environment),+ embeddings: new OpenAiFindingEmbedder(+ environment["OPENAI_API_KEY"] ?? environment["CODEX_API_KEY"],+ ),+ host,+ port,+ });+ const address = server.address();+ if (address !== null && typeof address !== "string") {+ output.write(+ `Findings service listening on ${address.address}:${address.port}\n`,+ );+ }++ const shutdown = () => {+ server.close((error) => {+ if (error !== undefined) {+ console.error(error);+ process.exitCode = 1;+ }+ });+ };+ process.once("SIGINT", shutdown);+ process.once("SIGTERM", shutdown);+}diff --git a/sdk/typescript/tests-ts/cli-serve.test.ts b/sdk/typescript/tests-ts/cli-serve.test.tsnew file mode 100644index 000000000..d37e6c2ab--- /dev/null+++ b/sdk/typescript/tests-ts/cli-serve.test.ts@@ -0,0 +1,148 @@+import { spawn, spawnSync } from "node:child_process";+import { once } from "node:events";+import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { createInterface } from "node:readline";+import { expect, test } from "bun:test";+import { main } from "../src/cli.js";+import { capture, dependencies } from "./cli-fixtures.js";++const packageRoot = join(import.meta.dir, "..");+const cli = join(packageRoot, "src", "cli.ts");++for (const [name, args, port] of [+ ["CLI", [cli, "serve"], "0"],+ ["CLI --port overrides PORT", [cli, "serve", "--port", "0"], "invalid"],+ ["CLI --port=0 overrides PORT", [cli, "serve", "--port=0"], "invalid"],+ [+ "standalone entrypoint",+ [join(packageRoot, "src", "server", "index.ts")],+ "0",+ ],+] as const) {+ test(`${name} serves findings with isolated state and shuts down`, async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-serve-"));+ const state = join(root, "state with spaces");+ const child = spawn(process.execPath, [...args], {+ env: {+ ...process.env,+ CODEX_SECURITY_STATE_DIR: state,+ HOST: "127.0.0.1",+ PORT: port,+ OPENAI_API_KEY: "",+ CODEX_API_KEY: "",+ },+ stdio: ["ignore", "pipe", "pipe"],+ timeout: 20_000,+ });+ const exited = once(child, "exit");+ let stderr = "";+ child.stderr.setEncoding("utf8").on("data", (chunk) => {+ stderr += chunk;+ });+ try {+ let base: string | undefined;+ for await (const line of createInterface({ input: child.stdout })) {+ const match = /^Findings service listening on (127\.0\.0\.1:\d+)$/.exec(+ line,+ );+ if (match) {+ base = `http://${match[1]}`;+ break;+ }+ }+ expect(base, stderr).toBeDefined();+ const response = await fetch(`${base}/v1/findings`);+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({ findings: [], total: 0 });+ expect((await stat(join(state, "workbench.sqlite3"))).isFile()).toBe(+ true,+ );+ child.kill("SIGTERM");+ const [code] = await exited;+ // Windows terminates child processes instead of delivering SIGTERM.+ if (process.platform !== "win32") expect(code).toBe(0);+ expect(stderr).toBe("");+ } finally {+ if (child.exitCode === null && child.signalCode === null) {+ child.kill("SIGKILL");+ }+ await exited;+ await rm(root, { recursive: true, force: true });+ }+ }, 30_000);+}++test("serve reports startup failures with a nonzero exit", async () => {+ const root = await mkdtemp(join(tmpdir(), "codex-security-serve-failure-"));+ try {+ const state = join(root, "not-a-directory");+ await writeFile(state, "synthetic file");+ const child = spawnSync(process.execPath, [cli, "serve"], {+ env: { ...process.env, CODEX_SECURITY_STATE_DIR: state },+ encoding: "utf8",+ timeout: 20_000,+ });+ expect(child.error).toBeUndefined();+ expect(child.status).toBe(1);+ expect(child.stdout).toBe("");+ expect(child.stderr).toContain("Could not access the findings database");+ } finally {+ await rm(root, { recursive: true, force: true });+ }+});++test("serve exposes help and schema without starting the service", async () => {+ for (const args of [+ ["--help"],+ ["serve", "--help"],+ ["serve", "--schema", "--json"],+ ]) {+ const stdout = capture();+ const stderr = capture();+ expect(await main(args, stdout.stream, stderr.stream, dependencies())).toBe(+ 0,+ );+ if (args.includes("--schema")) {+ expect(JSON.parse(stdout.text())).toMatchObject({+ options: {+ properties: {+ port: { type: "integer", minimum: 0, maximum: 65535 },+ },+ },+ });+ } else {+ expect(stdout.text()).toContain("serve");+ }+ expect(stderr.text()).toBe("");+ }+});++test("serve rejects positional arguments and JSON output", async () => {+ for (const args of [+ ["serve", "repository"],+ ["serve", "--json"],+ ]) {+ const stdout = capture();+ const stderr = capture();+ expect(await main(args, stdout.stream, stderr.stream, dependencies())).toBe(+ 2,+ );+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("serve");+ }+});++test("serve rejects missing or invalid ports", async () => {+ for (const value of [undefined, "invalid", "-1", "65536", "1.5"]) {+ const stdout = capture();+ const stderr = capture();+ const args = ["serve", "--port", ...(value === undefined ? [] : [value])];+ expect(await main(args, stdout.stream, stderr.stream, dependencies())).toBe(+ 2,+ );+ expect(stdout.text()).toBe("");+ expect(stderr.text()).toContain("port");+ }+});