Codex Security TypeScript SDK
從 TypeScript 執行 Codex Security 掃描,選擇目標和供應商,檢查結果並管理掃描生命週期。
使用 Codex Security TypeScript SDK,可從你的應用程式或開發者工具中對儲存庫和 程式碼更改執行安全掃描。SDK 會傳回類型化的 發現、覆蓋範圍詳情和掃描產物路徑。對於耗時較長的掃描,它 支援預檢、成本限制、進度回呼和取消操作。
SDK 使用 ECMAScript 模組(ESM),在服務端執行,支援 Node.js 24 或 26,或 22.13.0 及以上的 Node.js 22。掃描還需要 Python 3.10 或更高版本。
Python 3.10 還需要 tomli 軟體包。
設定 SDK
安裝 SDK:
npm install @openai/codex-security開始掃描前,請設定 OPENAI_API_KEY 或 CODEX_API_KEY、使用
現有的檔案型 Codex 登入資訊,或設定其他
供應商。Amazon Bedrock 使用 AWS
憑據;OpenRouter 和 Fireworks 使用供應商專用的 API key 和
設定。
為獲得最佳效果,請使用已通過 Trusted Access for Cyber 驗證的帳戶。登入或提供 API key 並不會 授予 Trusted Access 權限。
執行掃描
SDK 使用你的本機作業系統權限執行,且不會暫停 以等待核准。 掃描程序可能繼承你的環境,因此請在開始前移除無關憑據。 請參閱本機掃描 權限。
將此範例儲存為 scan.mjs。替換路徑,執行標準儲存庫
掃描,並在工作完成後關閉客戶端。傳入 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.manifest.scan.status);
console.log(result.findings.findings.length);
} finally {
await security.close();
}使用 Node.js 執行:
node scan.mjs該範例會列印報告路徑、掃描狀態和發現項數量。 開啟報告以審查證據。數量會因儲存庫 和掃描而異,因此不要用預期數量來判斷整合是否正常工作。
run 會驗證已儲存的產物,並在
result.manifest.scan.status 為 "completed" 時傳回 ScanResult。檢視 result.coverage,瞭解
已審查的範圍、排除項和推遲的工作。已完成的掃描仍可能
存在覆蓋缺口。執行時、輸入或結果完整性方面的故障可能丟擲
錯誤。
在後續範例中,複用已開啟的 security 客戶端,並將 close() 保留在
finally 中,以釋放執行時。將其他需要的匯入語句新增到
scan.mjs 的頂部。
使用預檢檢查輸入
使用 preflight 可在開始掃描前檢查儲存庫、目標、模式、知識庫文件、
輸出位置和 Codex 設定:
const plan = await security.preflight("/path/to/repository", {
target: ["services/billing", "packages/auth"],
knowledgeBasePaths: ["/path/to/architecture.md"],
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。差異目標要求儲存庫參數
為 Git 工作樹根目錄。
掃描工作樹
使用 DiffTarget.workingTree 掃描相對於基準
修訂版本的暫存和未暫存更改:
const target = DiffTarget.workingTree({ base: "HEAD" });
const result = await security.run("/path/to/repository", { target });基準預設為 HEAD。開始差異或工作樹掃描前,請取得選定的修訂版本。
選擇深度模式
對於需要更廣泛審查的儲存庫或路徑掃描,請設定 mode: "deep":
const result = await security.run("/path/to/repository", {
target: ["services/billing"],
mode: "deep",
workers: 2,
subagents: 0,
stopAfterNoNew: 3,
maxDiscoveryRuns: 10,
maxTimeHours: 1.5,
});深度模式支援儲存庫和路徑目標。差異和
工作樹掃描請使用標準模式。可選設定用於控制並發的獨立
標準掃描工作程序、每個工作程序的子智能體數量、連續完成但
沒有新發現的工作程序掃描次數,以及工作程序執行的總次數和時長。這些設定
需要 mode: "deep"。
maxTimeHours 預設為 96,接受不超過 96 的正數,
小時數可以為小數。到達截止時間時,Codex Security 會停止未完成的
工作程序,保留已完成的掃描結果,並將其彙總到最終
報告中。檢視 result.coverage,瞭解推遲的工作和待解答的問題。
新增安全知識庫
通過 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 會拒絕符號連結輸入路徑、跳過符號連結目錄條目,並將
提取的文件內容儲存在掃描結果之外。
新增掃描和後續指令
使用 scanPrompt 聚焦掃描,並使用 postScanPrompt 請求後續操作:
const result = await security.run("/path/to/repository", {
scanPrompt: "Focus on tenant isolation and authorization checks.",
postScanPrompt: "Write confirmed findings to post-scan-summary.md.",
});如果後續操作失敗,SDK 會保留已完成的掃描,並通過
onWarning 報告錯誤。它還會恢復被後續操作更改的所有已完成掃描產物。
設定掃描預算
設定 maxCostUsd,在掃描的估算模型成本超過限制時停止掃描。
使用 onCost 可在掃描執行期間跟蹤成本:
const result = await security.run("/path/to/repository", {
maxCostUsd: 5,
onCost(cost) {
console.log(cost.estimatedUsd);
},
});
console.log(result.cost?.estimatedUsd);該限制用於估算支出,並非嚴格的上限,因此已經在
進行中的請求完成時,費用可能略微超出限制。如果深度掃描在
Codex Security 彙總已完成的工作程序結果後達到限制,run 可以傳回一個
將 manifest.scan.status 設為 "completed" 的結果,並通過
onWarning 報告預算警告。檢視 result.coverage,瞭解尚未完成的工作。
如果掃描無法生成有效的已完成結果,run 會丟擲
ScanCostLimitExceededError,並保留所有可用輸出。
使用掃描結果
ScanResult 會提供結構化文件、掃描後設資料和產物
路徑:
| 屬性 | 內容 |
|---|---|
manifest |
已封存的掃描清單,包含目標、範圍、生成方和產物記錄。 |
findings |
當前掃描的發現項。從 findings.findings 讀取發現項物件。 |
repositoryFindings |
掃描歷史可用時,提供儲存庫歷次掃描中尚未關閉的發現項。 |
coverage |
已審查的範圍、排除項、推遲的工作和待解答的問題。 |
scanDir |
掃描目錄。 |
threadId |
此次掃描的 Codex 執行緒識別符。 |
turnResult |
輪次狀態、響應和可用的用量後設資料。 |
cost |
預估的模型和 token 費用,不可用時為 null。 |
reportPath |
report.md 的路徑。 |
manifestPath |
scan-manifest.json 的路徑。 |
findingsPath |
findings.json 的路徑。 |
coveragePath |
coverage.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
);
}
for (const deferred of result.coverage.deferred) {
console.log(deferred.id, deferred.reason);
}發現可以包含可選的 codeEvidence、rootCause、validation、
attackPath、remediationTests 和 preventiveControls 欄位。
對於儲存庫範圍的發現,confirmedInLatestScan 會區分
最新掃描中發現的問題與先前掃描中仍未解決的問題:
for (const finding of result.repositoryFindings ?? []) {
console.log(finding.title, finding.confirmedInLatestScan);
}新結果不包含 coverage.completeness。使用 manifest.scan.status
檢視執行狀態,並審查 coverage 中推遲審查的範圍、排除項和待解答的
問題,瞭解掃描審查了哪些內容。
result.toJSON() 會在一個可直接轉換為 JSON 的物件中傳回清單、儲存庫和當前掃描的發現、
覆蓋範圍、掃描和聊天識別符、reportPath、artifactsDir、
sarifPath、成本以及輪次後設資料。
跟蹤或取消掃描
傳入 ScanOptions 回呼,以報告掃描啟動、工作程序進度和
連線重試:
const result = await security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
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);傳入請求或作業控制器提供的 AbortSignal,以取消掃描。
如果掃描在 30 分鐘後仍在執行,此範例會中斷掃描,並
列印包含已儲存輸出的目錄:
try {
await security.run("/path/to/repository", {
outputDir: "/path/outside/repository/results",
signal: AbortSignal.timeout(30 * 60 * 1000),
});
} catch (error) {
if (error instanceof ScanInterruptedError) {
console.error(error.scanDir);
} else {
throw error;
}
}中斷的掃描可能會在 scanDir 中留下部分輸出。當需要調查
結果時,請保留該目錄。
顯示掃描設定進度的應用程式還可以使用 ScanOptions
生命週期回呼:
| 回呼 | 呼叫時機 |
|---|---|
onAuthentication(authentication) |
掃描選擇身份驗證方法時。 |
onOutputArchived(archiveDir) |
現有結果移動到歸檔目錄時。 |
onOutputDirReady(scanDir) |
私有掃描目錄準備就緒時。 |
onScanStarted() |
掃描設定完成並開始執行時。 |
onTrustedAccessStatus(status) |
Trusted Access 狀態變為可用時。 |
onReconnect(attempt, maxAttempts) |
SDK 重試已斷開的掃描流時。 |
onActivity(activity) |
命令、工具、推理步驟或訊息更新時。 |
onProgress(progress) |
掃描階段或已審查檔案數發生變化時。 |
onWorkerStatus(status) |
工作程序預檢或分派狀態發生變化時。 |
onSessionEvent(session) |
掃描或工作程序會話發出事件時。 |
onCost(cost) |
有更新後的掃描成本估算值可用時。 |
onWarning(warning) |
掃描報告警告時。 |
onObserverError(observer, error) |
其他掃描生命週期回呼引發錯誤時。 |
Trusted Access 狀態為 granted、not_granted 或 unknown。缺失或
未知的存取權限也會觸發 onWarning。
onSessionEvent 接收未經脫敏的事件,其中可能包含源
程式碼或憑據。請先過濾這些事件,再將其傳送到共享日誌或其他
服務。
設定執行時和憑據
需要特定外掛、直譯器或 Codex 設定時,請傳入執行時設定。請選擇你的憑據有權存取的模型。如果你使用 ChatGPT 登入,請先檢視 GPT-6.1 Sol 可用性,再 使用此範例:
const security = new CodexSecurity({
pluginPath: "/path/to/codex-security-plugin",
pythonPath: "/path/to/python",
codexOverrides: {
model: "gpt-6.1-sol",
model_reasoning_effort: "medium",
},
});pluginPath 接受外掛目錄或 ZIP。pythonPath 選擇
外掛直譯器。codexOverrides 會將支援的值合併到隔離的
Codex 設定中。掃描預設使用 gpt-5.6-sol 和超高推理強度。
在 codexOverrides 中設定 model 和 model_reasoning_effort,可使用
其他模型或推理強度。若要使用 Amazon
Bedrock,請在 codexOverrides 中設定
model_provider 和 model。
codexOverrides 無法限制掃描的檔案系統存取權限或更改其
核准策略。請參閱本機掃描
權限。
對於 OpenRouter 或 Fireworks,還需提供相應的 API key,並在
codexOverrides 中提供完整的供應商設定。例如,設定
OPENROUTER_API_KEY 並設定 OpenRouter:
const security = new CodexSecurity({
codexOverrides: {
model: "anthropic/claude-sonnet-4.5",
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 key 對隔離的執行時進行身份驗證。 |
loginChatGPT() |
啟動瀏覽器登入流程並傳回登入控制代碼。 |
loginChatGPTDeviceCode() |
啟動裝置碼登入流程並傳回登入控制代碼。 |
account() |
傳回當前身份驗證狀態。 |
logout() |
清除隔離環境中的身份驗證資訊。 |
登入控制代碼提供 waitForInstructions、authUrl、verificationUrl、
userCode、wait 和 cancel,以便應用呈現並完成
所選的登入流程。SDK 可以複用基於檔案儲存的 Codex 登入資訊。對於 CI 和服務端自動化,
請使用 API key。
當 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 |
中斷停止了掃描,並且可能留下部分輸出。 |