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

12.1 KB
Raw Blame
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import { isIP } from "node:net";
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { parse } from "smol-toml";
import { CODEX_AUTH_CONFIG_KEYS, type JsonObject } from "./config.js";
import {
  CodexSecurityError,
  PluginBootstrapError,
  errorMessage,
} from "./errors.js";
import {
  beginCredentialLogin,
  executablePathForSpawn,
  expandHome,
  runCodexCommand,
  writeCredentialHomeConfig,
  type CodexCommand,
  type ProcessEnvironment,
} from "./runtime.js";

const LOGIN_CHILD_TERMINATION_GRACE_MS = 1_000;

/** @internal */
export function environmentEntry(
  environment: ProcessEnvironment,
  requested: string,
): string | undefined {
  const exact = environment[requested];
  if (exact !== undefined || process.platform !== "win32") return exact;
  const upper = requested.toUpperCase();
  return Object.entries(environment).find(
    ([name]) => name.toUpperCase() === upper,
  )?.[1];
}

/** @internal */
export function withoutOpenAiApiKeys<Value>(
  environment: Record<string, Value>,
): Record<string, Value> {
  return Object.fromEntries(
    Object.entries(environment).filter(
      ([name]) =>
        !["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase()),
    ),
  );
}

/** @internal */
export function configuredCodexHome(environment: ProcessEnvironment): string {
  const configured = environmentEntry(environment, "CODEX_HOME");
  return resolve(
    expandHome(
      configured?.trim() ? configured : join(homedir(), ".codex"),
      environment,
    ),
  );
}

/** @internal */
export async function readCodexHomeConfig(
  environment: ProcessEnvironment,
  signal?: AbortSignal,
): Promise<JsonObject> {
  const path = join(configuredCodexHome(environment), "config.toml");
  try {
    return parse(
      await readFile(path, {
        encoding: "utf8",
        signal,
      }),
      { integersAsBigInt: "asNeeded" },
    ) as JsonObject;
  } catch (error) {
    signal?.throwIfAborted();
    if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
    throw new CodexSecurityError(
      `Could not read the configured Codex provider from ${path}: ${errorMessage(error)}`,
      { cause: error },
    );
  }
}

export interface LoginResult extends Awaited<
  ReturnType<typeof runCodexCommand>
> {}

export interface AccountStatus {
  authenticated: boolean;
  details: string;
}

export class CodexLoginHandle {
  readonly #child: ChildProcessWithoutNullStreams;
  readonly #completion: Promise<LoginResult>;
  readonly #urlReady = Promise.withResolvers<void>();
  readonly #deviceReady = Promise.withResolvers<void>();
  #canceled = false;
  #forcedTermination: ReturnType<typeof setTimeout> | undefined;
  readonly #output = { stdout: "", stderr: "" };
  readonly #tails = { stdout: "", stderr: "" };
  readonly #urls: Record<"stdout" | "stderr", string | null> = {
    stdout: null,
    stderr: null,
  };
  readonly #codes: Record<"stdout" | "stderr", string | null> = {
    stdout: null,
    stderr: null,
  };

  public constructor(
    command: CodexCommand,
    args: readonly string[],
    environment: ProcessEnvironment,
    onSuccess: () => void | Promise<void>,
    onFinish?: () => Promise<void>,
  ) {
    void this.#urlReady.promise.catch(() => undefined);
    void this.#deviceReady.promise.catch(() => undefined);
    this.#child = spawn(
      executablePathForSpawn(command.command),
      [...(command.args ?? []), ...args],
      {
        env: environment,
        stdio: ["pipe", "pipe", "pipe"],
        windowsHide: true,
      },
    );
    this.#child.stdin.end();
    this.#child.stdout.setEncoding("utf8");
    this.#child.stderr.setEncoding("utf8");
    this.#child.stdout.on("data", (chunk: string) => {
      this.#recordOutput("stdout", chunk);
    });
    this.#child.stderr.on("data", (chunk: string) => {
      this.#recordOutput("stderr", chunk);
    });
    this.#completion = new Promise<LoginResult>((resolve, reject) => {
      this.#child.once("close", (exitCode) => {
        clearTimeout(this.#forcedTermination);
        if (!this.#canceled) {
          this.#flushInstructionTails();
        }
        const result = {
          success: exitCode === 0 && !this.#canceled,
          exitCode,
          ...this.#output,
        };
        this.#settleInstructionWaiters(result);
        if (result.success) {
          Promise.resolve()
            .then(onSuccess)
            .then(() => resolve(result), reject);
        } else {
          resolve(result);
        }
      });
      this.#child.once("error", (error) => {
        clearTimeout(this.#forcedTermination);
        this.#settleInstructionWaiters({
          success: false,
          exitCode: null,
          stdout: this.#output.stdout,
          stderr: error.message,
        });
        reject(error);
      });
    }).finally(onFinish);
  }

  public get loginId(): null {
    return null;
  }

  public get authUrl(): string | null {
    return this.#urls.stdout ?? this.#urls.stderr;
  }

  public get verificationUrl(): string | null {
    return this.authUrl;
  }

  public get userCode(): string | null {
    return this.#codes.stdout ?? this.#codes.stderr;
  }

  public async wait(): Promise<LoginResult> {
    return await this.#completion;
  }

  public async waitForInstructions(
    options: { deviceCode?: boolean } = {},
  ): Promise<void> {
    await (options.deviceCode === true ? this.#deviceReady : this.#urlReady)
      .promise;
  }

  public cancel(): void {
    this.#canceled = true;
    if (this.#child.exitCode !== null || this.#child.signalCode !== null) {
      // Descendants can retain inherited pipes after the login process exits.
      // Cancellation must release those pipes so the close event can settle.
      this.#child.stdin.destroy();
      this.#child.stdout.destroy();
      this.#child.stderr.destroy();
      return;
    }
    this.#child.kill("SIGTERM");
    if (this.#forcedTermination !== undefined) return;
    this.#forcedTermination = setTimeout(() => {
      if (this.#child.exitCode === null && this.#child.signalCode === null) {
        this.#child.kill("SIGKILL");
      }
      this.#child.stdin.destroy();
      this.#child.stdout.destroy();
      this.#child.stderr.destroy();
    }, LOGIN_CHILD_TERMINATION_GRACE_MS);
  }

  #recordOutput(stream: "stdout" | "stderr", chunk: string): void {
    this.#output[stream] += chunk;
    const output = `${this.#tails[stream]}${chunk.replaceAll("\r", "\n")}`;
    const lastDelimiter = output.lastIndexOf("\n");
    const completed =
      lastDelimiter === -1 ? "" : output.slice(0, lastDelimiter + 1);
    this.#urls[stream] ??= preferredAuthUrl(completed);
    this.#codes[stream] ??= userCodeFromOutput(completed);
    this.#tails[stream] =
      lastDelimiter === -1 ? output : output.slice(lastDelimiter + 1);
    this.#notifyInstructions();
  }

  #flushInstructionTails(): void {
    for (const stream of ["stdout", "stderr"] as const) {
      this.#urls[stream] ??= preferredAuthUrl(this.#tails[stream]);
      this.#codes[stream] ??= userCodeFromOutput(this.#tails[stream]);
    }
  }

  #notifyInstructions(): void {
    if (this.authUrl !== null) this.#urlReady.resolve();
    if (this.verificationUrl !== null && this.userCode !== null)
      this.#deviceReady.resolve();
  }

  #settleInstructionWaiters(result: LoginResult): void {
    this.#notifyInstructions();
    if (result.success) {
      this.#urlReady.resolve();
      this.#deviceReady.resolve();
      return;
    }
    const error = new PluginBootstrapError(
      this.#canceled
        ? "Codex login was canceled."
        : `Codex login exited before authentication instructions were available: ${result.stderr.trim() || result.stdout.trim() || result.exitCode || "unknown error"}`,
    );
    this.#urlReady.reject(error);
    this.#deviceReady.reject(error);
  }
}

export async function loginApiKey(
  command: CodexCommand,
  environment: ProcessEnvironment,
  apiKey: string,
  signal?: AbortSignal,
): Promise<LoginResult> {
  if (apiKey.trim().length === 0) {
    throw new PluginBootstrapError("The API key must be non-empty.");
  }
  return await runCodexCommand(
    command,
    ["login", "--with-api-key"],
    environment,
    `${apiKey}\n`,
    signal,
  );
}

export async function accountStatus(
  command: CodexCommand,
  environment: ProcessEnvironment,
  signal?: AbortSignal,
): Promise<AccountStatus> {
  const result = await runCodexCommand(
    command,
    ["login", "status"],
    environment,
    undefined,
    signal,
  );
  const details = [result.stdout.trim(), result.stderr.trim()]
    .filter(Boolean)
    .join("\n");
  return {
    authenticated:
      result.exitCode === 0 && !/not logged in|unauthenticated/i.test(details),
    details,
  };
}

export function nativeLogoutArgs(store?: string): string[] {
  return store === undefined
    ? ["logout"]
    : ["-c", `cli_auth_credentials_store=${JSON.stringify(store)}`, "logout"];
}

export async function logout(
  command: CodexCommand,
  environment: ProcessEnvironment,
  signal?: AbortSignal,
  store?: string,
): Promise<void> {
  const result = await runCodexCommand(
    command,
    nativeLogoutArgs(store),
    environment,
    undefined,
    signal,
  );
  if (!result.success) {
    throw new PluginBootstrapError(
      `Codex logout failed: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`,
    );
  }
}

/** Prepare native login under the credential-home lock, preserving unrelated settings. */
export async function prepareLoginConfig(
  credentialHome: string,
  requested: JsonObject,
): Promise<void> {
  const config = await readCodexHomeConfig({ CODEX_HOME: credentialHome });
  let changed = false;
  for (const key of CODEX_AUTH_CONFIG_KEYS) {
    const value = requested[key];
    // Keep existing users in their native store until they select another.
    if (key === "cli_auth_credentials_store" && value === undefined) continue;
    if (config[key] === value) continue;
    if (value === undefined) delete config[key];
    else config[key] = value;
    changed = true;
  }
  if (changed) await writeCredentialHomeConfig(credentialHome, config);
  await beginCredentialLogin(credentialHome);
}

/** @internal Shared login recovery guidance for model commands. */
export const NO_CREDENTIALS_MESSAGE =
  "No credentials were found. Run 'codex-security login'. On a remote or headless " +
  "machine, use 'codex-security login --device-auth' if your workspace allows it. " +
  "If device auth is disabled, see 'codex-security login --help' for browser login over SSH. " +
  "For CI, set OPENAI_API_KEY or CODEX_API_KEY.";

function preferredAuthUrl(value: string): string | null {
  for (const match of plainTerminalText(value).matchAll(
    /https?:\/\/[^\s<>"']+/g,
  )) {
    // A bracket ending an IPv6 authority belongs to the URL, even in prose.
    const candidate = match[0];
    const ipv6Authority =
      candidate.match(/^https?:\/\/(?:[^\\/?#]*@)?\[[\da-fA-F:.]+\]/)?.[0] ??
      "";
    const url =
      ipv6Authority +
      candidate.slice(ipv6Authority.length).replace(/[.,;:!?)\]}]+$/, "");
    try {
      const parsed = new URL(url);
      const hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
      if (
        parsed.protocol === "https:" &&
        hostname !== "localhost" &&
        !hostname.endsWith(".localhost") &&
        !(isIP(hostname) === 4 && hostname.startsWith("127.")) &&
        hostname !== "0.0.0.0" &&
        hostname !== "[::1]" &&
        hostname !== "[::]" &&
        hostname !== "[::ffff:0:0]" &&
        !hostname.startsWith("[::ffff:7f") &&
        !hostname.startsWith("[::7f")
      ) {
        return url;
      }
    } catch {
      continue;
    }
  }
  return null;
}

function userCodeFromOutput(value: string): string | null {
  const output = plainTerminalText(value).replace(/https?:\/\/[^\s<>"']+/g, "");
  return (
    output.match(/(?:code|user code)\s*[:=]\s*([A-Z0-9-]{4,})/i)?.[1] ??
    output.match(/\b[A-Z0-9]{4,}(?:-[A-Z0-9]{4,})+\b/)?.[0] ??
    null
  );
}

function plainTerminalText(value: string): string {
  return value
    .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, "")
    .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, "")
    .replace(/\r/g, "");
}