Codex Security TypeScript SDK
從 TypeScript 執行 Codex Security 掃描、選擇目標和提供商、檢查結果並管理掃描生命週期。
使用 Codex Security TypeScript SDK,從應用或開發工具對儲存庫和程式碼變更執行安全掃描。SDK 會返回類型化的安全發現、覆蓋範圍詳情和掃描產物路徑。對於耗時較長的掃描,它還支援預檢、成本限制、進度回撥和取消。
SDK 使用 ECMAScript 模組(ESM),並在 Node.js 22 或更高版本的服務端環境中執行。掃描還需要 Python 3.10 或更高版本。
設定 SDK
安裝 SDK:
npm install @openai/codex-security開始掃描前,請設定 OPENAI_API_KEY 或 CODEX_API_KEY、複用現有的檔案式 Codex 登入,或使用 AWS 憑據以及顯式的 model_provider 和 model 覆蓋來設定 Amazon Bedrock。
為取得最佳效果,請使用已通過 Trusted Access for Cyber 驗證的賬號。登入或提供 API key 不會授予 Trusted Access。
執行掃描
建立一個 CodexSecurity 客戶端,執行標準儲存庫掃描,並在工作完成後關閉客戶端。傳入 outputDir,選擇外層 Git 工作樹之外的私有結果目錄。
如果省略 outputDir,Codex Security 會將結果儲存在其自己的持久狀態目錄中。結果可以包括源程式碼摘錄和漏洞詳細資訊,因此請選擇適當的權限和保留策略。
const security = new CodexSecurity();
try {
const result = await security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
});
console.log(result.reportPath);
console.log(result.coverage.completeness);
console.log(result.findings.findings.length);
} finally {
await security.close();
}run 會啟動掃描、等待掃描完成、驗證已封存的產物,並返回 ScanResult。close 會釋放隔離執行時,而且可以重複呼叫。
使用預檢檢查輸入
在開始掃描之前,使用 preflight 檢查儲存庫、目標、模式、輸出位置和 Codex 設定:
const plan = await security.preflight("/path/to/repository", {
target: ["services/billing", "packages/auth"],
outputDir: "/path/outside/repository/results",
});
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("/path/to/repository", {
outputDir: "/path/outside/repository/results",
archiveExisting: true,
});
console.log(plan.archiveDir);返回的 archiveDir 用於預覽存檔名稱。最終路徑可能不同,因為 run 會生成唯一的目標目錄。使用 onOutputArchived 獲取實際存檔路徑:
await security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
archiveExisting: true,
onOutputArchived(archiveDir) {
console.log("Archived results:", archiveDir);
},
});掃描會存檔早期結果並從空輸出目錄開始。
選擇掃描目標
SDK 支援儲存庫、路徑、提交差異和工作樹目標。預設目標是完整的儲存庫。
掃描選定的路徑
傳遞儲存庫內的路徑陣列:
const result = await security.run("/path/to/repository", {
target: ["services/billing", "packages/auth"],
});路徑可以標識檔案或目錄。SDK 解析儲存庫內的每個路徑並刪除重複項。
掃描提交的更改
使用 DiffTarget.refs 掃描兩個本機可用的 Git 修訂版之間提交的更改:
const target = DiffTarget.refs({
base: "origin/main",
head: "HEAD",
});
const result = await security.run("/path/to/repository", { target });head revision 預設為 HEAD。Diff 目標要求儲存庫參數指向 Git 工作樹根目錄。
掃描工作樹
使用 DiffTarget.workingTree 掃描針對基本修訂的暫存和未暫存更改:
const target = DiffTarget.workingTree({ base: "HEAD" });
const result = await security.run("/path/to/repository", { target });base revision 預設為 HEAD。開始差異或工作樹掃描前,請先獲取選定的 revision。
選擇深度模式
為需要更廣泛審查的儲存庫或路徑掃描設定 mode: "deep":
const result = await security.run("/path/to/repository", {
target: ["services/billing"],
mode: "deep",
});深度模式支援儲存庫和路徑目標。使用標準模式進行差異和工作樹掃描。
新增安全知識庫
通過 knowledgeBasePaths 傳入架構文件、威脅模型或安全策略:
const result = await security.run("/path/to/repository", {
knowledgeBasePaths: [
"/path/to/architecture.md",
"/path/to/security-policies",
],
});SDK 接受檔案或目錄並遞迴搜尋目錄。支援的文件格式為 .md、.markdown、.txt、.pdf 和 .docx。SDK 拒絕連結的輸入路徑,跳過連結的目錄條目,並將提取的文件內容保留在儲存的掃描結果之外。
設定掃描預算
設定 maxCostUsd 以在估計模型成本超過限制時停止掃描。使用 onCost 跟蹤掃描執行時的成本:
const result = await security.run("/path/to/repository", {
maxCostUsd: 5,
onCost(cost) {
console.log(cost.estimatedUsd);
},
});
console.log(result.cost?.estimatedUsd);該限制是估算值,而非硬性支出上限。已經發出的請求可能使最終成本超過該限制。如果掃描超出限制,SDK 會丟擲 ScanCostLimitExceededError 並保留可用結果。
處理掃描結果
ScanResult 公開結構化文件、掃描後設資料和產物路徑:
| 欄位 | 內容 |
|---|---|
manifest |
已封存的掃描 manifest,包括目標、範圍、生產者和產物記錄。 |
findings |
安全發現檔案。各項安全發現位於 findings.findings。 |
coverage |
已審查範圍、排除、延後處理的工作、懸而未決的問題和完整性。 |
scanDir |
掃描目錄。 |
threadId |
掃描對應的 Codex thread 識別符號。 |
turnResult |
turn 的狀態、響應和可用的用量後設資料。 |
cost |
估算的模型和 token 成本;不可用時為 null。 |
reportPath |
report.md 的路徑。 |
manifestPath |
scan-manifest.json 的路徑。 |
findingsPath |
findings.json 的路徑。 |
coveragePath |
coverage.json 的路徑。 |
artifactsDir |
支援產物目錄。 |
sarifPath |
生成的 SARIF 路徑,或者當 SARIF 不存在時為 null。 |
pluginVersion |
掃描製作者記錄的版本。 |
直接使用結構化發現和覆蓋範圍:
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
);
}
for (const deferred of result.coverage.deferred) {
console.log(deferred.id, deferred.reason);
}覆蓋完整性為 complete、partial 或 unknown。在使用掃描作為安全決策的證據之前,請檢視延遲的表面、排除和未解決的問題。
result.toJSON() 返回一個可直接序列化為 JSON 的物件,其中包含 manifest、安全發現、覆蓋範圍、掃描與 thread 識別符號、reportPath、artifactsDir、sarifPath 和 turn 後設資料。
跟蹤或取消掃描
傳遞 ScanOptions 回撥來報告掃描啟動、工作程序和連線重試:
const result = await security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
onScanStarted() {
console.log("Scan started");
},
onWorkerStatus(status) {
console.log(status.kind, status);
},
onReconnect(attempt, maxAttempts) {
console.log(`Reconnect attempt ${attempt} of ${maxAttempts}`);
},
onObserverError(observer, error) {
console.error(`${observer} failed`, error);
},
});
console.log(result.reportPath);當取消來自請求、作業控制器或超時時,傳遞 AbortSignal:
const controller = new AbortController();
try {
const scan = security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
signal: controller.signal,
});
controller.abort();
await scan;
} catch (error) {
if (error instanceof ScanInterruptedError) {
console.error(error.scanDir);
} else {
throw error;
}
}中斷的掃描可能會在 scanDir 中留下部分輸出。當結果需要調查時保留該目錄。
顯示掃描設定進度的應用還可以使用 ScanOptions 生命週期回撥:
| 回撥 | 何時呼叫 |
|---|---|
onOutputArchived(archiveDir) |
現有結果移至存檔目錄。 |
onOutputDirReady(scanDir) |
私有掃描目錄已準備就緒。 |
onScanStarted() |
掃描設定完成並開始執行。 |
onReconnect(attempt, maxAttempts) |
SDK 重試斷開連線的掃描流。 |
onWorkerStatus(status) |
worker 預檢或排程狀態發生變化。 |
onCost(cost) |
提供更新的估計掃描成本。 |
onObserverError(observer, error) |
另一個掃描生命週期回撥會引發錯誤。 |
設定執行時和憑據
當你需要特定外掛、直譯器或 Codex 設定時傳遞執行時設定:
const security = new CodexSecurity({
pluginPath: "/path/to/codex-security-plugin",
pythonPath: "/path/to/python",
codexOverrides: {
model: "gpt-5.6-terra",
model_reasoning_effort: "high",
},
});pluginPath 接受外掛目錄或 ZIP。pythonPath 用於選擇外掛直譯器。codexOverrides 會把支援的值合併到隔離的 Codex 設定中。掃描預設使用 gpt-5.6-sol 和 extra-high 推理強度;要使用其它模型或推理強度,請在 codexOverrides 中設定 model 和 model_reasoning_effort。要使用 Amazon Bedrock,請在 codexOverrides 中設定 model_provider 和 model。
客戶端還公開支援的認證方法:
| 方法 | 目的 |
|---|---|
loginApiKey(apiKey) |
使用 API key 驗證隔離執行時。 |
loginChatGPT() |
啟動瀏覽器登入流程並返回登入控制代碼。 |
loginChatGPTDeviceCode() |
啟動裝置程式碼登入流程並返回登入控制代碼。 |
account() |
返回當前的認證狀態。 |
logout() |
清除隔離的認證。 |
登入控制代碼提供 waitForInstructions、authUrl、verificationUrl、userCode、wait 和 cancel,以便應用可以呈現並完成所選的登入流程。SDK 可以複用檔案式 Codex 登入,API key 則很適合 CI 和服務端自動化。
當 API key 和已儲存的登入同時可用時,SDK 預設使用 API key。要改用 ChatGPT 登入,請為掃描顯式選擇:
const result = await security.run("/path/to/repository", {
auth: "chatgpt",
});設定 auth: "api-key" 可強制使用環境中的 API key。preflight 接受相同的 auth 選項。
處理掃描錯誤
根據應用可以採取的操作,捕獲對應的錯誤類:
| 錯誤 | 意義 |
|---|---|
AuthenticationRequiredError |
掃描需要受支援的憑據。 |
ConfigurationError |
Codex 設定或覆蓋不合適。 |
InvalidTargetError |
儲存庫、路徑、模式或 Git 目標不合適。 |
OutputDirectoryError |
輸出位置或其權限不合適。 |
OutputInsideProtectedRootError |
輸出目錄位於掃描的儲存庫或工作樹內。 |
PluginPythonUnavailableError |
可用的 Python 直譯器不可用。 |
PluginBootstrapError |
外掛執行時無法啟動。 |
ScanCostLimitExceededError |
掃描超出了其估計的成本限制。 |
IncompleteScanError |
掃描在產生所需結果之前結束。 |
ContractValidationError |
完成的掃描返回了結構化合約錯誤。 |
ScanInterruptedError |
中斷停止了掃描並可能留下了部分輸出。 |