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

6.8 KB
Raw Blame
import { spawn } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
import { configuredCodexHome, readCodexHomeConfig } from "./auth.js";
import { CodexSecurityError } from "./errors.js";
import {
  codexSecurityCredentialHome,
  executablePathForSpawn,
  resolveCodexCommand,
  type StartCodex,
} from "./runtime.js";
import {
  readSavedScanLogs,
  savedScanLogBoundaries,
  type ScanLogSource,
} from "./scan-logs.js";
import {
  BUNDLED_PLUGIN_VERSION,
  CODEX_EXECUTABLE_VERSION,
  CODEX_SDK_VERSION,
  VERSION,
} from "./version.js";

interface FeedbackOptions {
  reason: string;
  includeLogs: boolean;
  scan?: ScanLogSource;
  environment: NodeJS.ProcessEnv;
  workingDirectory: string;
  signal?: AbortSignal;
}

export async function sendFeedback(
  options: FeedbackOptions,
  startCodex: StartCodex = spawn,
) {
  const { scan, environment, includeLogs } = options;
  options.signal?.throwIfAborted();
  const codexHome = codexSecurityCredentialHome(environment);
  const config = await readCodexHomeConfig(environment);
  const feedback = config["feedback"] as { enabled?: boolean } | undefined;
  if (feedback?.enabled === false) {
    throw new CodexSecurityError(
      "Sending feedback is disabled by configuration.",
    );
  }

  let directory: string | undefined;
  try {
    const extraLogFiles: string[] = [];
    if (includeLogs && scan !== undefined) {
      try {
        const logs = await readSavedScanLogs(
          scan,
          [codexHome, configuredCodexHome(environment)],
          { allowMissingRoot: true },
        );
        if (logs.sessions.length > 0) {
          directory = await mkdtemp(join(tmpdir(), "codex-security-feedback-"));
          const path = join(directory, "scan-logs.json");
          await writeFile(path, JSON.stringify(logs), { mode: 0o600 });
          extraLogFiles.push(path);
        }
      } catch {
        options.signal?.throwIfAborted();
        console.warn(
          "Codex Security could not attach saved scan logs; sending feedback with available Codex logs.",
        );
      }
    }

    options.signal?.throwIfAborted();
    const command = resolveCodexCommand(environment);
    const child = startCodex(
      executablePathForSpawn(command.command),
      ["app-server", "--stdio"],
      {
        cwd: options.workingDirectory,
        env: { ...environment, CODEX_HOME: codexHome },
        stdio: ["pipe", "pipe", "pipe"],
        windowsHide: true,
        signal: options.signal,
      },
    );
    const uploaded = Promise.withResolvers<string>();
    let stderr = "";
    let stdinError: Error | undefined;
    const closed = new Promise<void>((resolve) => {
      child.once("close", () => {
        uploaded.reject(
          new CodexSecurityError(
            stderr || "Codex exited before feedback was uploaded.",
          ),
        );
        resolve();
      });
    });
    child.once("error", uploaded.reject);
    child.stdin.on("error", (error: Error) => {
      stdinError ??= error;
      uploaded.reject(error);
    });
    child.stderr.setEncoding("utf8").on("data", (chunk: string) => {
      stderr += chunk;
    });
    const send = (message: object) =>
      child.stdin.write(`${JSON.stringify(message)}\n`);
    const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
    const releaseCanceledPipes = () => {
      if (!options.signal?.aborted) return;
      uploaded.reject(options.signal.reason);
      if (child.exitCode === null && child.signalCode === null) return;
      lines.close();
      child.stdin.destroy();
      child.stdout.destroy();
      child.stderr.destroy();
    };
    options.signal?.addEventListener("abort", releaseCanceledPipes, {
      once: true,
    });
    child.once("exit", releaseCanceledPipes);
    lines.on("line", (line) => {
      try {
        const message = JSON.parse(line) as {
          id?: number;
          method?: string;
          error?: { message: string };
          result?: { threadId?: string };
        };
        if (message.method !== undefined || message.id === undefined) return;
        if (message.error) throw new CodexSecurityError(message.error.message);
        if (message.id === 1) {
          send({ method: "initialized" });
          send({
            id: 2,
            method: "feedback/upload",
            params: {
              classification: "bug",
              reason: options.reason,
              // Codex collects the whole thread and its descendants. Use the
              // scoped attachment for shared owners and completed scan turns.
              threadId:
                !includeLogs ||
                (scan?.executionThreadIds?.includes(
                  scan.continuationThreadId ?? "",
                ) &&
                  savedScanLogBoundaries(scan).logCompletedAt === null)
                  ? scan?.continuationThreadId
                  : undefined,
              includeLogs,
              extraLogFiles,
              tags: {
                codex_security_version: VERSION,
                codex_security_plugin_version: BUNDLED_PLUGIN_VERSION,
                codex_security_codex_version: CODEX_EXECUTABLE_VERSION,
                codex_security_sdk_version: CODEX_SDK_VERSION,
                ...(scan === undefined
                  ? {}
                  : { codex_security_scan_id: scan.scanId }),
              },
            },
          });
        } else if (message.id === 2) {
          const feedbackId = message.result?.threadId;
          if (!feedbackId)
            throw new CodexSecurityError("Codex did not return a feedback ID.");
          uploaded.resolve(feedbackId);
        }
      } catch (error) {
        uploaded.reject(error);
      }
    });
    try {
      try {
        send({
          id: 1,
          method: "initialize",
          params: { clientInfo: { name: "codex-security", version: VERSION } },
        });
        return {
          feedbackId: await uploaded.promise,
          scanId: scan?.scanId ?? null,
          includedLogs: includeLogs,
        };
      } finally {
        lines.close();
        child.stdin.end();
        child.kill();
        const timer = setTimeout(() => child.kill("SIGKILL"), 1_000);
        try {
          await closed;
        } finally {
          clearTimeout(timer);
          options.signal?.removeEventListener("abort", releaseCanceledPipes);
          child.removeListener("exit", releaseCanceledPipes);
        }
      }
    } catch (error) {
      options.signal?.throwIfAborted();
      if (error === stdinError && stderr)
        throw new CodexSecurityError(stderr, { cause: error });
      throw error;
    }
  } finally {
    if (directory !== undefined)
      await rm(directory, { recursive: true, force: true });
  }
}