文档导航

Codex Security TypeScript SDK

使用 TypeScript 运行 Codex Security 扫描、选择目标、查看结果并管理扫描生命周期。

使用 Codex Security TypeScript SDK,您可以从应用或开发者工具中对代码仓库和代码变更运行安全扫描。SDK 会返回具有明确类型的发现项、扫描清单以及已保存报告的路径。

SDK 使用 ECMAScript 模块(ESM),在服务端运行,支持 Node.js 24、26,以及 22.x 系列中从 22.13.0 起的版本。扫描还需要 Python 3.10 或更高版本。如果使用 Python 3.10,还需要安装 tomli 包。

如需了解通用编程智能体,请参阅 Codex SDK 指南。如需了解终端和 CI 工作流,请参阅 Codex Security CLI 快速入门。

设置 SDK

安装 SDK:

npm install @openai/codex-security

开始扫描前,请设置 OPENAI_API_KEY 或 CODEX_API_KEY,使用已保存在文件中的 Codex 登录凭据,或配置其他提供商。Amazon Bedrock 使用 AWS 凭据,OpenRouter 和 Fireworks 则使用各自的 API 密钥和配置。

要发出部分网络安全请求或访问受保护的发现项,您的 ChatGPT 账号或 API 组织需要获得 Trusted Access for Cyber 权限。

运行扫描

SDK 使用您在本地操作系统中的权限运行,不会暂停等待审批。扫描进程可能会继承您的环境,因此请在开始前移除无关凭据。请参阅本地扫描权限。

将以下示例保存为 scan.mjs。通过命令行参数依次传入代码仓库路径和结果目录路径。运行标准代码仓库扫描,并在扫描完成后关闭客户端。传入 outputDir,将结果保存在代码仓库所在 Git 工作树之外的私有目录中。

如果省略 outputDir,Codex Security 会将结果保存到自身的持久化状态目录中。结果可能包含源代码片段和漏洞详情。请设置读取权限和保留期限。

import { CodexSecurity } from "@openai/codex-security";

const [repository, outputDir] = process.argv.slice(2);
if (!repository || !outputDir) {
  throw new Error("Usage: node scan.mjs <repository> <results-directory>");
}
const security = new CodexSecurity();

try {
  const result = await security.run(repository, {
    outputDir,
  });

  console.log(result.reportPath);
  console.log(result.manifest.scan.status);
  console.log(result.findings.findings.length);
} finally {
  await security.close();
}

使用 Node.js 运行示例:

node scan.mjs /path/to/repository /path/outside/repository/results

示例会输出报告路径、扫描状态和发现项数量。打开报告即可查看证据。

run 会验证已保存的产物,并返回一个 ScanResult,前提是 result.manifest.scan.status 为 "completed"。查看 result.manifest.scan.scope 可了解请求扫描的目标,查看 result.manifest.scan.warnings 可了解是否有警告。仅凭完成状态无法判断哪些文件已接受审查。运行时故障、输入错误或结果完整性校验失败都可能引发错误。

在后续示例中,请复用已打开的 security 客户端,并保留 close() 调用,将其放在 finally 块中以释放运行时资源。请在 scan.mjs 顶部添加所需的其他导入语句。

使用预检检查输入

开始扫描前,使用 preflight 检查代码仓库、目标、模式、知识库文档、输出位置和 Codex 配置。以下示例从代码仓库根目录读取 security.md:

import { join } from "node:path";

const knowledgeBase = join(repository, "security.md");

const plan = await security.preflight(repository, {
  target: ["services/billing", "packages/auth"],
  knowledgeBasePaths: [knowledgeBase],
  outputDir: outputDir,
});

console.log(plan.repository);
console.log(plan.target.kind);
console.log(plan.mode);
console.log(plan.outputDir);

预检只检查本地输入,不会启动 Codex、加载凭据或检查 Python 和插件是否可用。预检成功并不保证扫描能够通过身份验证或正常启动。

要预览现有结果目录的归档位置,请设置 archiveExisting: true:

const plan = await security.preflight(repository, {
  outputDir: outputDir,
  archiveExisting: true,
});

console.log(plan.archiveDir);

返回的 archiveDir 展示了归档目录的命名方式。最终路径可能不同,因为 run 会自行生成唯一的目标路径。使用 onOutputArchived 获取实际归档路径:

try {
  await security.run(repository, {
    outputDir: outputDir,
    archiveExisting: true,
    onOutputArchived(archiveDir) {
      console.log("Archived results:", archiveDir);
    },
  });
} finally {
  await security.close();
}

扫描会先将之前的结果归档,然后使用空的输出目录开始扫描。

选择扫描目标

SDK 支持扫描代码仓库、指定路径、提交之间的差异和工作树中的变更。默认目标是整个代码仓库。

要跳过文件或目录,请在扫描选项中设置 excludePaths: ["examples/"]。

扫描指定路径

传入由代码仓库内的路径组成的数组:

try {
  const result = await security.run(repository, {
    target: ["services/billing", "packages/auth"],
  });
} finally {
  await security.close();
}

路径可以指向文件或目录。SDK 会在代码仓库内解析每个路径并移除重复项。

扫描已提交的变更

使用 DiffTarget.refs 扫描本地可用的两个 Git 修订版本之间已提交的变更:

import { DiffTarget } from "@openai/codex-security";

const target = DiffTarget.refs({
  base: "HEAD~1",
  head: "HEAD",
});

try {
  const result = await security.run(repository, { target });
} finally {
  await security.close();
}

比较的目标版本默认为 HEAD。请将 Git 工作树的根目录作为代码仓库路径传入,并在扫描前检出要比较的目标版本。

扫描工作树

使用 DiffTarget.workingTree 扫描相对于基准版本的已暂存和未暂存变更:

import { DiffTarget } from "@openai/codex-security";
const target = DiffTarget.workingTree({ base: "HEAD" });
try {
  const result = await security.run(repository, { target });
} finally {
  await security.close();
}

基准版本默认为 HEAD。开始差异扫描或工作树扫描前,请先获取所选的修订版本。

选择深度模式

如果代码仓库或路径扫描需要更全面的审查,请设置 mode: "deep":

try {
  const result = await security.run(repository, {
    target: ["services/billing"],
    mode: "deep",
    workers: 2,
    subagents: 0,
    stopAfterNoNew: 3,
    maxDiscoveryRuns: 10,
    maxTimeMinutes: 90,
  });
} finally {
  await security.close();
}

深度模式支持代码仓库和路径目标。对于差异扫描和工作树扫描,请使用标准模式。在深度模式下,workers 限制并发执行扫描的工作进程数,subagents 设置每个工作进程的子智能体数量。stopAfterNoNew 指定停止探索的条件:如果工作进程连续运行指定次数都没有新的发现项,就停止探索。maxDiscoveryRuns 限制所有工作进程的运行总次数。

设置 maxTimeMinutes 可限制深度探索的时长。默认值和最大值均为 5,760 分钟(96 小时)。达到时限后,探索会停止,SDK 会合并已完成的工作进程的结果。标准扫描将 maxTimeMinutes 作为调查阶段的建议时长。报告可以在此后完成。自定义验证和扫描后指令的执行时间不计入该时长。

添加安全知识库

通过 knowledgeBasePaths 传入架构文档、威胁模型或安全策略:

import { join } from "node:path";

const knowledgeBase = join(repository, "security.md");

try {
  const result = await security.run(repository, {
    knowledgeBasePaths: [knowledgeBase],
  });
} finally {
  await security.close();
}

SDK 接受文件或目录,并会递归搜索目录。支持的格式包括 UTF-8 文本(包括 JSON 和 SARIF)、PDF 和 DOCX。SDK 会拒绝链接形式的输入路径,并跳过目录中的链接条目。

SDK 会将提取的文档文本保存到与扫描产物位于同一目录的私有文件 .scan-knowledge.json 中。请将此文件保留在扫描目录中。恢复中断的深度扫描时,codex-security scans resume 会使用已保存的文本,即使原始文档已更改或删除。正式报告不会嵌入这些文档文本。

添加扫描指令和后续指令

使用 scanPrompt 指定扫描重点,并使用 postScanPrompt 请求执行后续任务:

try {
  const result = await security.run(repository, {
    scanPrompt: "Focus on tenant isolation and authorization checks.",
    postScanPrompt: "Write confirmed findings to post-scan-summary.md.",
  });
} finally {
  await security.close();
}

如果后续任务失败,SDK 会保留已完成的扫描,并通过 onWarning 报告错误。如果后续任务修改了已完成扫描的产物,SDK 会将其还原。后续任务在扫描费用跟踪结束后运行,不受 maxCostUsd 限制。

在您的环境中验证发现项

传入 validationPrompt,使用您自己的测试流程检查候选发现项。例如,可以在提示词中指定一个由您控制且位于代码检出目录之外的脚本,并针对本地测试服务器运行该脚本。在代码仓库路径和结果目录路径之后,依次传入验证脚本路径和服务器 URL:

const [validationScript, validationUrl] = process.argv.slice(4);
if (!validationScript || !validationUrl)
  throw new Error("Pass a validation script path and service URL.");
const result = await security.run(repository, {
  outputDir,
  validationPrompt: `Run ${validationScript} against ${validationUrl} and report which findings reproduce.`,
});
node scan.mjs /path/to/repository /path/outside/repository/results /path/to/validate.sh http://localhost:3000

validationPrompt 可用于标准模式下的代码仓库扫描、路径扫描、提交差异扫描或工作树扫描。要对每个组件的标准扫描使用相同的验证流程,请将 scanOptions.validationPrompt 传给 runComponentScans。深度扫描不接受自定义验证。

应用严重程度分级策略

传入 rubricPath 指定 Markdown 策略文件,按其中的标准评定发现项的严重程度。也可以传入 severityRubric 快照,其中须包含策略正文 markdown、正整数版本号 revision,以及根据该 Markdown 正文的原始 UTF-8 字节计算出的 sha256 摘要。同时提供快照和文件时,优先使用快照。标准扫描和深度扫描都会保存所选的分级标准,以便在重试、恢复或重新运行扫描时使用。

设置扫描预算

设置 maxCostUsd,使扫描在预估模型费用超过限额时停止。使用 onCost 在扫描过程中跟踪费用并报告 estimatedUsdRange:

try {
  const result = await security.run(repository, {
    maxCostUsd: 5,
    onCost(cost) {
      console.log(cost.estimatedUsdRange);
    },
  });

  console.log(result.cost?.estimatedUsdRange);
} finally {
  await security.close();
}

SDK 根据 estimatedUsd 判断是否超出限额,该值以短上下文价格为基准估算。已经开始处理的请求可能使预估费用超过限额。按长上下文价格计费也可能使 estimatedUsdRange 超过限额。此限额不限制实际账单金额。

如果扫描无法生成有效的完整结果,run 会抛出 ScanCostLimitExceededError 并保留所有可用输出。

扫描项目组件

使用 runComponentScans 并行扫描服务或软件包,并合并其发现项。为每个组件指定名称以及一个或多个相对于代码仓库根目录的路径。请在代码仓库所在 Git 工作树之外选择一个新目录或空目录作为输出目录。

import { runComponentScans } from "@openai/codex-security";

const result = await runComponentScans({
  repository: repository,
  outputDir: outputDir,
  components: [
    { name: "API", paths: ["services/api", "packages/auth"] },
    { name: "Web", paths: ["services/billing"] },
  ],
  workers: 2,
  onProgress: ({ name, status }) => console.log(name, status),
});

console.log(result.reportPath);
if (result.failed > 0) {
  throw new Error(`${result.failed} component scans failed.`);
}

设置 workers 可控制同时扫描的组件数量。默认值为 4。

要让 Codex 建议扫描哪些组件,请传入 auto: true 代替 components。添加 planOnly: true 可将计划保存到 components.json,而不运行任何扫描:

import { runComponentScans } from "@openai/codex-security";

const plan = await runComponentScans({
  repository: repository,
  outputDir: outputDir,
  auto: true,
  planOnly: true,
});

console.log(plan.planPath);

如果运行结束时有组件扫描失败,请读取 result.retryPlanPath 指向的 JSON 文件。将其中的 components 数组传给 runComponentScans,并指定新的 outputDir。重试报告仅涵盖这些组件。请查看两次运行的报告。

使用扫描结果

ScanResult 提供结构化文档、扫描元数据和产物路径:

属性 内容
manifest 已封存的扫描清单,包含目标、范围、生成方和产物记录。
findings 当前扫描的发现项。可从 findings.findings 读取发现项对象。
repositoryFindings 有扫描历史记录时,包含该代码仓库历次扫描中尚未关闭的发现项。
review 从审查范围中排除的路径模式(review.excludedPaths)。
scanDir 扫描目录。
threadId 此次扫描的 Codex 线程标识符。
turnResult 本轮状态、响应和可用的用量元数据。
cost 预估的模型和 Token 费用,不可用时为 null。
reportPath report.md 的路径。
threatModel 已保存的威胁模型,不可用时为 null。
threatModelPath 已保存的威胁模型文档路径,不可用时为 null。
manifestPath scan-manifest.json 的路径。
findingsPath findings.json 的路径。
artifactsDir 存放辅助产物的目录。
sarifPath 生成的 SARIF 文件路径,无 SARIF 文件时为 null。
pluginVersion 扫描结果生成方记录的版本。

要确保后续扫描使用相同的插件版本,请传入 expectedPluginVersion: result.pluginVersion。如果安装的插件版本不同,SDK 会拒绝扫描。

读取每个发现项的严重程度及其在源代码中的第一个位置:

for (const finding of result.findings.findings) {
  const location = finding.locations[0];
  if (location === undefined) continue;

  console.log(
    finding.severity.level,
    `${location.path}:${location.startLine}`,
    finding.title
  );
}

发现项可以包含 codeEvidence、rootCause、validation、attackPath、remediationTests 和 preventiveControls 等可选字段。

对于整个代码仓库的发现项,confirmedInLatestScan 用于区分最近一次扫描中观察到的发现项和此前发现但仍未关闭的发现项:

for (const finding of result.repositoryFindings ?? []) {
  console.log(finding.title, finding.confirmedInLatestScan);
}

使用 result.toJSON() 可序列化清单、发现项、已记录的审查排除项、产物路径和本轮元数据。

读取已保存的威胁模型

使用 threatModel 和 threatModelPath 前,请检查它们是否为 null。即使 Codex Security 未能写入威胁模型的 Markdown 文件,您仍可导出已保存的模型。请使用导出操作返回的路径,不要假定文件名。

导出已保存的产物

导出已保存的结果无需启动 Codex、加载凭据或调用模型。以下示例将已保存的威胁模型导出到标准输出。请将已有扫描结果目录的路径作为第一个命令行参数传入:

import { exportArtifact } from "@openai/codex-security";

const directory = process.argv[2];
if (!directory) {
  throw new Error(
    "Pass an existing scan results directory as the first argument."
  );
}

await exportArtifact({
  source: { directory },
  artifact: "threat-model",
  output: "-",
});

要按 ID 选择已保存的扫描,请改用 source: { scanId: "SCAN_ID" }。将 output 设为目标路径,即可将产物保存到文件。

威胁模型以 Markdown 格式导出。如果此次扫描没有已保存的威胁模型,导出操作会返回错误。要导出发现项,请设置 artifact: "findings",并选择 format: "sarif"(默认值)、"json"、"csv" 或 "servicenow-avit"。

结果包含输出路径 path。如果将威胁模型导出到文件,结果还包含取自同一份已保存扫描结果的来源信息 provenance。这两个字段均为 null 时,对应的是通过 output: "-" 写入标准输出的情况。导出需要 Python 3.10 或更高版本。

要使用 ServiceNow 的手动 AVIT 导入功能,请设置 artifact: "findings" 和 format: "servicenow-avit"。准备应用模板,并将模板路径作为 avitTemplate 传入。将 output 设为代码仓库外私有目录中的目标 CSV 文件路径。使用 source.directory 指定现有的扫描结果目录。

验证已有的发现项

使用 validate 可对照源代码检查来自其他工具或工作流的发现项。此操作不会启动新的扫描、运行应用或执行应用的测试。如果需要运行时证据,请单独进行复现。

const validation = await security.validate({
  repositoryPath: repository,
  finding: {
    title: "Possible SQL injection",
    location: "src/index.js:1",
  },
});

console.log(validation.disposition);
console.log(validation.report);

请以非空文本或 JSON 对象的形式传入发现项。如果发现项存储在文件中,请先读取文件,再传入其内容。

disposition 表示发现项的处理结论,可能为 reportable(可报告)、suppressed(已抑制)、not_applicable(不适用)或 deferred(暂缓处理)。validation.report 中的 Markdown 文本说明了现有证据和尚待确认之处。如果需要报告文件,请保存该字符串。

跟踪或取消扫描

传入 ScanOptions 回调可报告扫描启动、工作进程进度和连接重试情况:

try {
  const result = await security.run(repository, {
    outputDir: outputDir,
    onScanStarted() {
      console.log("Scan started");
    },
    onProgress(progress) {
      console.log(progress.phase, progress.filesCompleted, progress.filesTotal);
    },
    onWorkerStatus(status) {
      console.log(status.kind, status);
    },
    onSessionEvent(session) {
      console.log(session.threadId, session.worker, session.event["type"]);
    },
    onReconnect(attempt, maxAttempts) {
      console.log(`Reconnect attempt ${attempt} of ${maxAttempts}`);
    },
    onObserverError(observer, error) {
      console.error(`${observer} failed`, error);
    },
  });

  console.log(result.reportPath);
} finally {
  await security.close();
}

传入请求或作业控制器提供的 AbortSignal 可取消扫描。在以下示例中,如果扫描在 30 分钟后仍在运行,代码会中断扫描并输出已保存结果所在的目录:

import { ScanInterruptedError } from "@openai/codex-security";

try {
  await security.run(repository, {
    outputDir: outputDir,
    signal: AbortSignal.timeout(30 * 60 * 1000),
  });
} catch (error) {
  if (error instanceof ScanInterruptedError) {
    console.error(error.scanDir);
  } else {
    throw error;
  }
} finally {
  await security.close();
}

扫描中断后,scanDir 中可能会留下部分输出。如果需要调查扫描结果,请保留该目录。

需要显示扫描准备进度的应用还可以使用 ScanOptions 的生命周期回调:

回调 调用时机
onAuthentication(authentication) 扫描选定身份验证方式时。
onOutputArchived(archiveDir) 现有结果移至归档目录时。
onOutputDirReady(scanDir) 私有扫描目录就绪时。
onScanStarted() 扫描准备完成并开始执行时。
onTrustedAccessStatus(status) 可以获取可信访问状态时。
onReconnect(attempt, maxAttempts) SDK 尝试重新连接已断开的扫描流时。
onActivity(activity) 命令、工具、推理步骤或消息有更新时。
onProgress(progress) 扫描阶段或已审查文件数发生变化时。
onDeepProgress(progress) 正在进行或已完成的深度审查数量发生变化时。
onWorkerStatus(status) 报告计划启动和已启动的工作进程数时,计数以当时可获取的信息为准。
onSessionEvent(session) 扫描会话或工作进程会话发出事件时。
onCost(cost) 扫描费用估算更新时。
onWarning(warning) 扫描报告警告时。
onObserverError(observer, error) 其他扫描生命周期回调抛出错误时。

可信访问状态为 granted、not_granted 或 unknown。未获得访问权限或状态未知时,也会触发 onWarning。

onSessionEvent 接收的事件未经脱敏,可能包含源代码或凭据。请先过滤事件,再将其发送到共享日志或其他服务。

配置运行时和凭据

如果需要指定插件、解释器或 Codex 设置,请传入运行时配置。请选择您的账号可用的模型:

const security = new CodexSecurity({
  // To override the bundled plugin, add pluginPath: "/path/to/plugin".
  pythonPath: "python3",
  codexOverrides: {
    model: "gpt-6.1-sol",
    model_reasoning_effort: "medium",
  },
});

将 pluginPath 设为插件目录或 ZIP 文件的路径,即可使用指定插件替代随 SDK 提供的插件。pythonPath 指定插件使用的解释器。codexOverrides 将支持的配置值合并到隔离的 Codex 配置中。要使用 Amazon Bedrock,请设置 model_provider 和 model,并将两者放在 codexOverrides 中。

将 codexOverrides.approval_policy 设为 "never" 可拒绝权限请求。否则,扫描会自动审查审批请求。有关文件系统访问权限和继承的凭据,请参阅本地扫描权限。

对于 OpenRouter 或 Fireworks,还需提供相应的 API 密钥,并在 codexOverrides 中提供完整的提供商配置。请设置 OPENROUTER_API_KEY,并将可用的 OpenRouter 模型 ID 传给以下 TypeScript 函数:

function createOpenRouterClient(model: string) {
  return new CodexSecurity({
    codexOverrides: {
      model,
      model_provider: "openrouter",
      model_providers: {
        openrouter: {
          name: "OpenRouter",
          base_url: "https://openrouter.ai/api/v1",
          env_key: "OPENROUTER_API_KEY",
          wire_api: "responses",
        },
      },
    },
  });
}

对于 Fireworks,请将两处 openrouter 键改为 fireworks,将 name 设为 Fireworks AI,将 env_key 设为 FIREWORKS_API_KEY,使用 https://api.fireworks.ai/inference/v1 作为 base_url,并选择一个 Fireworks 模型。

客户端还提供以下身份验证方法:

方法 用途
loginApiKey(apiKey) 使用 API 密钥为隔离的运行时进行身份验证。
loginChatGPT() 启动浏览器登录流程并返回登录句柄。
loginChatGPTDeviceCode() 启动设备代码登录流程并返回登录句柄。
account() 返回当前身份验证状态。
logout() 清除隔离运行时中的身份验证信息。

登录句柄提供 waitForInstructions、authUrl、verificationUrl、userCode、wait 和 cancel,供应用向用户展示并完成所选的登录流程。SDK 可以复用保存在文件中的 Codex 登录凭据。对于 CI 和服务端自动化,请使用 API 密钥。

如果 API 密钥和已保存的登录凭据均可用,SDK 默认使用 API 密钥。如果希望使用 ChatGPT 登录凭据,请在扫描选项中指定:

const result = await security.run(repository, {
  auth: "chatgpt",
});

设置 auth: "api-key" 可要求使用环境变量中的 API 密钥。preflight 也接受相同的 auth 选项。

处理扫描错误

根据应用可采取的处理措施,捕获 SDK 导出的相应错误类:

错误 含义
AuthenticationRequiredError 扫描需要受支持的凭据。
ConfigurationError Codex 配置或覆盖设置不符合要求。
InvalidTargetError 代码仓库、路径、模式或 Git 目标不符合要求。
OutputDirectoryError 输出位置或其权限不符合要求。
OutputInsideProtectedRootError 输出目录位于被扫描的代码仓库或工作树内。
PluginPythonUnavailableError 没有可用的 Python 解释器。
PluginBootstrapError 插件运行时未能启动。
ScanCostLimitExceededError 扫描的预估费用超过限额。
IncompleteScanError 扫描在生成所需结果之前结束。
ContractValidationError 已完成的扫描返回了结构化数据契约错误。
ScanInterruptedError 扫描因中断而停止,可能留下了部分输出。

接下来可参阅 CLI 快速入门、CI 指南或 CLI 参考。

输入关键词搜索中文文档。