@openai/codex-security 0.1.26 → 0.1.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +398 -30
- package/_bundled_plugin/.mcp.json +1 -0
- package/_bundled_plugin/mcp/helpers.mjs +24 -0
- package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/native/COPYRIGHT-library.html +5556 -0
- package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +5989 -0
- package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
- package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
- package/_bundled_plugin/mcp/native/licenses/Apache-2.0.txt +73 -0
- package/_bundled_plugin/mcp/native/licenses/BSD-2-Clause.txt +9 -0
- package/_bundled_plugin/mcp/native/licenses/MIT.txt +9 -0
- package/_bundled_plugin/mcp/native/licenses/Unicode-3.0.txt +39 -0
- package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
- package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
- package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
- package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
- package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
- package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
- package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
- package/_bundled_plugin/references/config-preflight.md +2 -0
- package/_bundled_plugin/references/core-scan.md +1 -1
- package/_bundled_plugin/references/scan-contract.md +35 -35
- package/_bundled_plugin/references/security-guidance.md +7 -1
- package/_bundled_plugin/scripts/generate_in_scope_files.py +2 -2
- package/_bundled_plugin/scripts/generate_rank_input.py +8 -1
- package/_bundled_plugin/scripts/launch_codex_security_mcp +6 -0
- package/_bundled_plugin/scripts/launch_codex_security_mcp.cmd +43 -9
- package/_bundled_plugin/scripts/rank_preview.py +4 -1
- package/_bundled_plugin/scripts/workbench_cli.py +4 -0
- package/_bundled_plugin/scripts/workbench_db.py +33 -29
- package/_bundled_plugin/scripts/workbench_scan_history.py +117 -2
- package/_bundled_plugin/scripts/workbench_validation.py +4 -0
- package/_bundled_plugin/skills/define-security-policy/SKILL.md +3 -3
- package/dist/api.d.ts +7 -1
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +481 -60
- package/dist/api.js.map +1 -1
- package/dist/auth.js +10 -0
- package/dist/auth.js.map +1 -1
- package/dist/cli.d.ts +18 -2
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +962 -276
- package/dist/cli.js.map +1 -1
- package/dist/cloud-publish.d.ts.map +1 -1
- package/dist/cloud-publish.js +2 -207
- package/dist/cloud-publish.js.map +1 -1
- package/dist/component-plan.d.ts.map +1 -1
- package/dist/component-plan.js +116 -32
- package/dist/component-plan.js.map +1 -1
- package/dist/config.d.ts +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +17 -2
- package/dist/config.js.map +1 -1
- package/dist/contract.d.ts +5 -10
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js.map +1 -1
- package/dist/cost-model.d.ts +16 -0
- package/dist/cost-model.d.ts.map +1 -1
- package/dist/cost-model.js +57 -3
- package/dist/cost-model.js.map +1 -1
- package/dist/cost.d.ts.map +1 -1
- package/dist/cost.js +18 -3
- package/dist/cost.js.map +1 -1
- package/dist/custom-validation-prompt.js +1 -1
- package/dist/custom-validation-prompt.js.map +1 -1
- package/dist/deduplication/codex-review.d.ts +6 -1
- package/dist/deduplication/codex-review.d.ts.map +1 -1
- package/dist/deduplication/codex-review.js +72 -17
- package/dist/deduplication/codex-review.js.map +1 -1
- package/dist/deduplication/deduplication.d.ts +2 -0
- package/dist/deduplication/deduplication.d.ts.map +1 -1
- package/dist/deduplication/deduplication.js +99 -26
- package/dist/deduplication/deduplication.js.map +1 -1
- package/dist/deduplication/retry.d.ts +3 -0
- package/dist/deduplication/retry.d.ts.map +1 -0
- package/dist/deduplication/retry.js +15 -0
- package/dist/deduplication/retry.js.map +1 -0
- package/dist/deduplication/scan.d.ts +2 -0
- package/dist/deduplication/scan.d.ts.map +1 -1
- package/dist/deduplication/scan.js +4 -2
- package/dist/deduplication/scan.js.map +1 -1
- package/dist/feedback.d.ts +20 -0
- package/dist/feedback.d.ts.map +1 -0
- package/dist/feedback.js +121 -0
- package/dist/feedback.js.map +1 -0
- package/dist/findings-client.d.ts +7 -1
- package/dist/findings-client.d.ts.map +1 -1
- package/dist/findings-client.js +55 -10
- package/dist/findings-client.js.map +1 -1
- package/dist/findings-import.d.ts +44 -0
- package/dist/findings-import.d.ts.map +1 -0
- package/dist/findings-import.js +302 -0
- package/dist/findings-import.js.map +1 -0
- package/dist/import-scan.d.ts +27 -0
- package/dist/import-scan.d.ts.map +1 -0
- package/dist/import-scan.js +236 -0
- package/dist/import-scan.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/knowledge-base.d.ts +1 -1
- package/dist/knowledge-base.d.ts.map +1 -1
- package/dist/knowledge-base.js +2 -2
- package/dist/knowledge-base.js.map +1 -1
- package/dist/multiscan.d.ts +2 -0
- package/dist/multiscan.d.ts.map +1 -1
- package/dist/multiscan.js +144 -52
- package/dist/multiscan.js.map +1 -1
- package/dist/publication-events.d.ts.map +1 -1
- package/dist/publication-events.js +7 -2
- package/dist/publication-events.js.map +1 -1
- package/dist/runtime.d.ts +5 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +8 -2
- package/dist/runtime.js.map +1 -1
- package/dist/scan-dashboard.d.ts.map +1 -1
- package/dist/scan-dashboard.js +19 -6
- package/dist/scan-dashboard.js.map +1 -1
- package/dist/scan-logs.d.ts +29 -0
- package/dist/scan-logs.d.ts.map +1 -1
- package/dist/scan-logs.js +36 -5
- package/dist/scan-logs.js.map +1 -1
- package/dist/security-policy-cli.d.ts +39 -0
- package/dist/security-policy-cli.d.ts.map +1 -0
- package/dist/security-policy-cli.js +193 -0
- package/dist/security-policy-cli.js.map +1 -0
- package/dist/security-policy.d.ts +80 -0
- package/dist/security-policy.d.ts.map +1 -0
- package/dist/security-policy.js +672 -0
- package/dist/security-policy.js.map +1 -0
- package/dist/targets.d.ts +8 -1
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +243 -14
- package/dist/targets.js.map +1 -1
- package/package.json +8 -4
- package/_bundled_plugin/scripts/resolve_security_md.py +0 -158
package/dist/api.js
CHANGED
|
@@ -7,26 +7,28 @@ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep,
|
|
|
7
7
|
import { Codex, } from "@openai/codex-sdk";
|
|
8
8
|
import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
|
|
9
9
|
import { z } from "incur";
|
|
10
|
-
import { accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
|
|
10
|
+
import { CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
|
|
11
11
|
import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
|
|
12
|
-
import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
|
|
12
|
+
import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, inlineToml, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, resolveCodexProfile, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
|
|
13
13
|
import { estimateScanCost, ScanCostTracker, } from "./cost.js";
|
|
14
14
|
import { DeepScanProgressTracker, } from "./deep-progress.js";
|
|
15
|
+
import { findScanSession } from "./scan-logs.js";
|
|
15
16
|
import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
|
|
16
17
|
import { runCustomValidation, writeCustomValidationStatus, } from "./custom-validation.js";
|
|
17
18
|
import { customDiscoveryPrompt, customValidationConfig, } from "./custom-validation-prompt.js";
|
|
18
|
-
import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
|
|
19
|
+
import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, IncompleteScanError, OutputDirectoryError, OutputDirectoryNotEmptyError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
|
|
19
20
|
import { prepareKnowledgeBase, } from "./knowledge-base.js";
|
|
20
21
|
import { FindingWorkflow, workflowDigest } from "./finding-workflow.js";
|
|
21
22
|
import { ScanResult, } from "./result.js";
|
|
23
|
+
import { formatSecurityPolicyText, inspectSecurityPolicySources, readSecurityPolicySnapshot, requireUnchangedSecurityPolicy, resolveSecurityPolicyGuidance, resolveSecurityPolicyTarget, runSecurityPolicyStages, parseSecurityPolicyStageResult, securityPolicyDiff, securityPolicyProtectedRoots, requireSecurityPolicyRepositoryBinding, securityPolicyStageOutputSchema, } from "./security-policy.js";
|
|
22
24
|
import { writeMockScanDraft } from "./mock-scan.js";
|
|
23
25
|
import { scanActivitiesFromEvent } from "./scan-activity.js";
|
|
24
26
|
import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
|
|
25
27
|
import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
|
|
26
28
|
import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
|
|
27
29
|
import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
|
|
28
|
-
import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
|
|
29
|
-
import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
|
|
30
|
+
import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepositories, requireOutputOutsideRepository, requirePrivatePolicyOutputDirectory, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
|
|
31
|
+
import { enclosingGitWorktreeRoot, enclosingGitWorktreeRoots, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
|
|
30
32
|
const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT = "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
|
|
31
33
|
const VALIDATION_DISPOSITIONS = [
|
|
32
34
|
"reportable",
|
|
@@ -46,6 +48,7 @@ const DEFAULT_DEPENDENCIES = {
|
|
|
46
48
|
environment: process.env,
|
|
47
49
|
};
|
|
48
50
|
const SCAN_PERMISSION_PROFILE = "codex_security_scan";
|
|
51
|
+
const POLICY_PERMISSION_PROFILE = "codex_security_policy";
|
|
49
52
|
const SAFETY_IDENTIFIER_ENV = "CODEX_SAFETY_IDENTIFIER";
|
|
50
53
|
const PERSONAL_TRUSTED_ACCESS_URL = "https://chatgpt.com/cyber";
|
|
51
54
|
const ORGANIZATIONAL_TRUSTED_ACCESS_URL = "https://openai.com/form/enterprise-trusted-access-for-cyber/";
|
|
@@ -257,7 +260,7 @@ export class CodexSecurity {
|
|
|
257
260
|
return await this.#preflightInputs(inputs, options);
|
|
258
261
|
}
|
|
259
262
|
async #preflightInputs(inputs, options) {
|
|
260
|
-
|
|
263
|
+
requireOutputOutsideRepositories(inputs.protectedRoots, await realpath(tmpdir()), "temporary");
|
|
261
264
|
if (options.knowledgeBasePaths?.length) {
|
|
262
265
|
const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, options.signal);
|
|
263
266
|
await knowledgeBase.cleanup();
|
|
@@ -288,6 +291,241 @@ export class CodexSecurity {
|
|
|
288
291
|
: { maxCostUsd: options.maxCostUsd }),
|
|
289
292
|
};
|
|
290
293
|
}
|
|
294
|
+
async preflightPolicy(repository, options = {}) {
|
|
295
|
+
this.#requireOpen();
|
|
296
|
+
const target = await resolveSecurityPolicyTarget(repository, options.path, options.signal);
|
|
297
|
+
const inputs = await this.#validatePolicyInputs(target, options, options.signal).catch(rethrowPolicyOutputError);
|
|
298
|
+
await readSecurityPolicySnapshot(target, options.signal, inputs.gitMetadataPaths);
|
|
299
|
+
const preflight = await this.#preflightInputs(inputs, options);
|
|
300
|
+
return {
|
|
301
|
+
...target,
|
|
302
|
+
outputDir: preflight.outputDir,
|
|
303
|
+
authentication: preflight.authentication,
|
|
304
|
+
model: preflight.model,
|
|
305
|
+
reasoningEffort: preflight.reasoningEffort,
|
|
306
|
+
...(options.maxCostUsd === undefined
|
|
307
|
+
? {}
|
|
308
|
+
: { maxCostUsd: options.maxCostUsd }),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
async generatePolicy(repository, options = {}) {
|
|
312
|
+
return await this.#trackOperation(() => this.#generatePolicy(repository, options)).catch(rethrowPolicyOutputError);
|
|
313
|
+
}
|
|
314
|
+
async previewPolicy(draft, options = {}) {
|
|
315
|
+
return await this.#trackOperation(async () => {
|
|
316
|
+
const signal = AbortSignal.any([
|
|
317
|
+
this.#abortController.signal,
|
|
318
|
+
...(options.signal === undefined ? [] : [options.signal]),
|
|
319
|
+
]);
|
|
320
|
+
return formatSecurityPolicyText(await securityPolicyDiff(draft, async () => await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
|
|
321
|
+
configuredPath: this.config.pythonPath,
|
|
322
|
+
environment: this.#dependencies.environment,
|
|
323
|
+
protectedRoot: (await enclosingGitWorktreeRoots(draft.repository, signal)).at(-1) ?? draft.repository,
|
|
324
|
+
signal,
|
|
325
|
+
}), signal), true);
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
async #generatePolicy(repository, options) {
|
|
329
|
+
const budgetController = new AbortController();
|
|
330
|
+
const signal = AbortSignal.any([
|
|
331
|
+
this.#abortController.signal,
|
|
332
|
+
budgetController.signal,
|
|
333
|
+
...(options.signal === undefined ? [] : [options.signal]),
|
|
334
|
+
]);
|
|
335
|
+
let outputDir = "";
|
|
336
|
+
let knowledgeBase = null;
|
|
337
|
+
let accumulatedCost = null;
|
|
338
|
+
let completeCost = true;
|
|
339
|
+
const warn = (message) => notifyObserver("onWarning", options.onWarning, options.onObserverError, message);
|
|
340
|
+
try {
|
|
341
|
+
const target = await resolveSecurityPolicyTarget(repository, options.path, signal);
|
|
342
|
+
const inputs = await this.#validatePolicyInputs(target, options, signal);
|
|
343
|
+
const snapshot = await readSecurityPolicySnapshot(target, signal, inputs.gitMetadataPaths);
|
|
344
|
+
const temporaryRoot = await realpath(tmpdir());
|
|
345
|
+
requireOutputOutsideRepositories(inputs.protectedRoots, temporaryRoot, "temporary");
|
|
346
|
+
const session = await this.#prepareSession(inputs, options, signal, temporaryRoot);
|
|
347
|
+
const { runtime, effectiveConfig } = session;
|
|
348
|
+
const model = scanModelConfiguration(effectiveConfig);
|
|
349
|
+
validateScanCostLimit(options.maxCostUsd, model.model);
|
|
350
|
+
for (const path of [
|
|
351
|
+
"references/threat-model.md",
|
|
352
|
+
"references/security-guidance.md",
|
|
353
|
+
"skills/define-security-policy/SKILL.md",
|
|
354
|
+
"mcp/helpers.mjs",
|
|
355
|
+
]) {
|
|
356
|
+
const metadata = await lstat(join(runtime.plugin.pluginRoot, path)).catch(() => null);
|
|
357
|
+
if (metadata === null ||
|
|
358
|
+
!metadata.isFile() ||
|
|
359
|
+
metadata.isSymbolicLink()) {
|
|
360
|
+
throw new CodexSecurityError(`Installed plugin is missing policy-generation support: ${path}`);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
const root = inputs.outputDir === null &&
|
|
364
|
+
this.#dependencies.prepareOutputDir === undefined
|
|
365
|
+
? await preparePersistentOutputRoot(inputs.stateDirectory, "policies", basename(target.repository))
|
|
366
|
+
: temporaryRoot;
|
|
367
|
+
outputDir = await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(inputs.outputDir ?? undefined, `${basename(target.repository)}-policy`, root, (path) => requireOutputOutsideRepositories(inputs.protectedRoots, path));
|
|
368
|
+
requireOutputOutsideRepositories(inputs.protectedRoots, outputDir);
|
|
369
|
+
requireModelSafeOutputDir(outputDir);
|
|
370
|
+
await (this.#dependencies.requirePrivatePolicyOutputDirectory ??
|
|
371
|
+
requirePrivatePolicyOutputDirectory)(outputDir);
|
|
372
|
+
if (options.knowledgeBasePaths?.length) {
|
|
373
|
+
knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal, outputDir);
|
|
374
|
+
}
|
|
375
|
+
notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, outputDir);
|
|
376
|
+
const guidance = await resolveSecurityPolicyGuidance(target, runtime.plugin.pluginRoot, session.scanEnvironment, signal, inputs.policyPaths, inputs.gitMetadataPaths);
|
|
377
|
+
await requireUnchangedSecurityPolicy(target, snapshot, signal, inputs.gitMetadataPaths);
|
|
378
|
+
await requireSecurityPolicyRepositoryBinding(target, signal);
|
|
379
|
+
const policyReadRoots = [
|
|
380
|
+
dirname(target.targetPath),
|
|
381
|
+
runtime.plugin.pluginRoot,
|
|
382
|
+
...(knowledgeBase === null ? [] : [knowledgeBase.path]),
|
|
383
|
+
].filter((path, index, roots) => roots.indexOf(path) === index);
|
|
384
|
+
const { codex } = this.#createSessionCodex(session, {
|
|
385
|
+
CODEX_SECURITY_REPOSITORY: target.repository,
|
|
386
|
+
CODEX_SECURITY_PLUGIN_ROOT: runtime.plugin.pluginRoot,
|
|
387
|
+
CODEX_SECURITY_STATE_DIR: inputs.stateDirectory,
|
|
388
|
+
CODEX_SECURITY_SURFACE: this.#surface,
|
|
389
|
+
...(knowledgeBase === null
|
|
390
|
+
? {}
|
|
391
|
+
: { CODEX_SECURITY_KNOWLEDGE_BASE: knowledgeBase.path }),
|
|
392
|
+
}, options.auth, policyCodexConfig(session.sessionConfig), inputs.gitMetadataPaths.length === 0
|
|
393
|
+
? []
|
|
394
|
+
: [
|
|
395
|
+
// CLI override keys split on dots, so keep paths inside the TOML value.
|
|
396
|
+
`permissions.${POLICY_PERMISSION_PROFILE}.filesystem=${inlineToml(policyFilesystemPermissions(inputs.gitMetadataPaths))}`,
|
|
397
|
+
]);
|
|
398
|
+
const reportCost = (current) => {
|
|
399
|
+
const total = addScanCosts(accumulatedCost, current);
|
|
400
|
+
if (completeCost)
|
|
401
|
+
notifyObserver("onCost", options.onCost, options.onObserverError, total);
|
|
402
|
+
if (options.maxCostUsd !== undefined &&
|
|
403
|
+
total.estimatedUsd > options.maxCostUsd) {
|
|
404
|
+
budgetController.abort(new CodexSecurityError(`Security-policy generation exceeded its $${options.maxCostUsd} cost limit; partial output remains at ${outputDir}.`));
|
|
405
|
+
}
|
|
406
|
+
};
|
|
407
|
+
const outputSchema = securityPolicyStageOutputSchema();
|
|
408
|
+
const run = async (stage, prompt) => {
|
|
409
|
+
const thread = codex.startThread({
|
|
410
|
+
workingDirectory: outputDir,
|
|
411
|
+
additionalDirectories: policyReadRoots,
|
|
412
|
+
skipGitRepoCheck: true,
|
|
413
|
+
approvalPolicy: "never",
|
|
414
|
+
networkAccessEnabled: false,
|
|
415
|
+
webSearchMode: "disabled",
|
|
416
|
+
});
|
|
417
|
+
const tracker = new ScanCostTracker({
|
|
418
|
+
codexHome: runtime.codexHome,
|
|
419
|
+
model: model.model,
|
|
420
|
+
repository: target.repository,
|
|
421
|
+
scanDirectory: outputDir,
|
|
422
|
+
maxCostUsd: options.maxCostUsd,
|
|
423
|
+
onCost: options.onCost === undefined && options.maxCostUsd === undefined
|
|
424
|
+
? undefined
|
|
425
|
+
: reportCost,
|
|
426
|
+
onError: (error) => {
|
|
427
|
+
if (options.maxCostUsd !== undefined)
|
|
428
|
+
budgetController.abort(error);
|
|
429
|
+
else
|
|
430
|
+
warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
|
|
431
|
+
},
|
|
432
|
+
});
|
|
433
|
+
let stopped = false;
|
|
434
|
+
let usage = null;
|
|
435
|
+
try {
|
|
436
|
+
const { events } = await thread.runStreamed(prompt, {
|
|
437
|
+
signal,
|
|
438
|
+
outputSchema,
|
|
439
|
+
});
|
|
440
|
+
const turn = await readCodexTurn({
|
|
441
|
+
thread,
|
|
442
|
+
events,
|
|
443
|
+
onEvent: (event) => {
|
|
444
|
+
if (event.type === "thread.started" &&
|
|
445
|
+
typeof event["thread_id"] === "string") {
|
|
446
|
+
tracker.start(event["thread_id"]);
|
|
447
|
+
}
|
|
448
|
+
},
|
|
449
|
+
onReconnect: (message) => warn(safeErrorMessage(message)),
|
|
450
|
+
});
|
|
451
|
+
usage = turn.usage;
|
|
452
|
+
signal.throwIfAborted();
|
|
453
|
+
if (turn.status !== "completed")
|
|
454
|
+
throw new CodexSecurityError(turn.lastStreamError ??
|
|
455
|
+
`Security-policy ${stage} stage ended before the turn completed.`);
|
|
456
|
+
const snapshot = await tracker.stop(usage).catch((error) => {
|
|
457
|
+
if (options.maxCostUsd !== undefined)
|
|
458
|
+
throw error;
|
|
459
|
+
warn(`Could not track policy-generation cost: ${safeErrorMessage(error)}`);
|
|
460
|
+
const cost = estimateScanCost(model.model, usage);
|
|
461
|
+
if (cost !== null)
|
|
462
|
+
reportCost(cost);
|
|
463
|
+
return { usage, cost };
|
|
464
|
+
});
|
|
465
|
+
stopped = true;
|
|
466
|
+
if (snapshot.cost === null) {
|
|
467
|
+
completeCost = false;
|
|
468
|
+
if (options.maxCostUsd !== undefined)
|
|
469
|
+
throw new CodexSecurityError("Could not verify the requested policy-generation cost limit.");
|
|
470
|
+
}
|
|
471
|
+
else {
|
|
472
|
+
accumulatedCost = addScanCosts(accumulatedCost, snapshot.cost);
|
|
473
|
+
}
|
|
474
|
+
signal.throwIfAborted();
|
|
475
|
+
try {
|
|
476
|
+
return parseSecurityPolicyStageResult(JSON.parse(turn.finalResponse));
|
|
477
|
+
}
|
|
478
|
+
catch (error) {
|
|
479
|
+
throw new CodexSecurityError(`Security-policy ${stage} stage returned an invalid document response.`, { cause: error });
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
if (!stopped)
|
|
484
|
+
await tracker
|
|
485
|
+
.stop(usage)
|
|
486
|
+
.catch((error) => warn(safeErrorMessage(error)));
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
return await runSecurityPolicyStages({
|
|
490
|
+
target,
|
|
491
|
+
snapshot,
|
|
492
|
+
policyPaths: inputs.policyPaths,
|
|
493
|
+
gitMetadataPaths: inputs.gitMetadataPaths,
|
|
494
|
+
outputDir,
|
|
495
|
+
guidance,
|
|
496
|
+
pluginRoot: runtime.plugin.pluginRoot,
|
|
497
|
+
...(this.config.pluginPath === undefined
|
|
498
|
+
? {}
|
|
499
|
+
: { pluginPath: resolve(expandHome(this.config.pluginPath)) }),
|
|
500
|
+
...(knowledgeBase === null
|
|
501
|
+
? {}
|
|
502
|
+
: { knowledgeBasePath: knowledgeBase.path }),
|
|
503
|
+
revision: await (this.#dependencies.repositoryRevision ?? repositoryRevision)(target.repository, signal),
|
|
504
|
+
...model,
|
|
505
|
+
pluginVersion: runtime.plugin.version,
|
|
506
|
+
signal,
|
|
507
|
+
onStage: (stage) => notifyObserver("onStage", options.onStage, options.onObserverError, stage),
|
|
508
|
+
answerQuestions: options.answerQuestions,
|
|
509
|
+
run,
|
|
510
|
+
cost: () => (completeCost ? accumulatedCost : null),
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
catch (error) {
|
|
514
|
+
if (budgetController.signal.aborted)
|
|
515
|
+
throw budgetController.signal.reason;
|
|
516
|
+
if (signal.aborted)
|
|
517
|
+
throw new CodexSecurityError(`Security-policy generation was interrupted${outputDir ? `; partial output remains at ${outputDir}` : ""}.`, { cause: error });
|
|
518
|
+
throw error;
|
|
519
|
+
}
|
|
520
|
+
finally {
|
|
521
|
+
try {
|
|
522
|
+
await knowledgeBase?.cleanup();
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
warnCleanupFailed(options, error, "policy generation");
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
291
529
|
async #run(repository, options) {
|
|
292
530
|
this.#requireOpen();
|
|
293
531
|
if (options.mock)
|
|
@@ -360,10 +598,13 @@ export class CodexSecurity {
|
|
|
360
598
|
if (scanOutputRoot !== undefined) {
|
|
361
599
|
requireOutputOutsideRepository(protectedRoot, scanOutputRoot, scanOutputRoot === temporaryRoot ? "temporary" : "output");
|
|
362
600
|
}
|
|
363
|
-
scanDir =
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
601
|
+
scanDir =
|
|
602
|
+
options.resumeScanId !== undefined
|
|
603
|
+
? requestedOutput
|
|
604
|
+
: await (this.#dependencies.prepareOutputDir ?? prepareOutputDir)(requestedOutput ?? undefined, basename(repo), scanOutputRoot, (path) => requireOutputOutsideRepository(protectedRoot, path), options.archiveExisting, (archiveDir) => {
|
|
605
|
+
archivedScanDir = archiveDir;
|
|
606
|
+
notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, archiveDir);
|
|
607
|
+
});
|
|
367
608
|
requireOutputOutsideRepository(protectedRoot, scanDir);
|
|
368
609
|
requireModelSafeOutputDir(scanDir);
|
|
369
610
|
notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, scanDir);
|
|
@@ -497,6 +738,10 @@ export class CodexSecurity {
|
|
|
497
738
|
});
|
|
498
739
|
costTracker = tracker;
|
|
499
740
|
const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, { ...preflightConfig, approval_policy: approvalPolicy }, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
|
|
741
|
+
if (options.safetyIdentifier !== undefined)
|
|
742
|
+
recipe["safetyIdentifier"] = options.safetyIdentifier;
|
|
743
|
+
if (options.postScanPrompt !== undefined)
|
|
744
|
+
recipe["postScanPrompt"] = options.postScanPrompt;
|
|
500
745
|
if (options.validationPrompt !== undefined)
|
|
501
746
|
recipe["validationMode"] = "custom";
|
|
502
747
|
const workbenchOptions = {
|
|
@@ -509,28 +754,59 @@ export class CodexSecurity {
|
|
|
509
754
|
signal,
|
|
510
755
|
failureMessage: "Could not save the Codex Security scan",
|
|
511
756
|
};
|
|
512
|
-
const registration =
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
757
|
+
const registration = options.resumeScanId !== undefined
|
|
758
|
+
? await workbench(workbenchOptions, [
|
|
759
|
+
"get-cli-scan-resume",
|
|
760
|
+
"--scan-id",
|
|
761
|
+
options.resumeScanId,
|
|
762
|
+
])
|
|
763
|
+
: await workbench(workbenchOptions, [
|
|
764
|
+
"register-cli-scan",
|
|
765
|
+
"--repository",
|
|
766
|
+
repo,
|
|
767
|
+
"--scan-dir",
|
|
768
|
+
scanDir,
|
|
769
|
+
"--registration-json-stdin",
|
|
770
|
+
...(options.archiveExisting === true
|
|
771
|
+
? ["--archive-existing"]
|
|
772
|
+
: []),
|
|
773
|
+
...(archivedScanDir === null
|
|
774
|
+
? []
|
|
775
|
+
: ["--archived-scan-dir", archivedScanDir]),
|
|
776
|
+
...(options.parentScanId === undefined
|
|
777
|
+
? []
|
|
778
|
+
: ["--parent-scan-id", options.parentScanId]),
|
|
779
|
+
], JSON.stringify({
|
|
780
|
+
recipe,
|
|
781
|
+
userContext: options.scanPrompt,
|
|
782
|
+
...(options.workflowId === undefined
|
|
783
|
+
? {}
|
|
784
|
+
: { workflowId: options.workflowId }),
|
|
785
|
+
}));
|
|
533
786
|
const scanId = registration["scanId"];
|
|
787
|
+
const resumeThreadId = options.resumeScanId === undefined
|
|
788
|
+
? undefined
|
|
789
|
+
: registration["threadId"];
|
|
790
|
+
if (options.resumeScanId !== undefined) {
|
|
791
|
+
const savedRecipe = registration["recipe"];
|
|
792
|
+
if (scanId !== options.resumeScanId ||
|
|
793
|
+
!isRecord(savedRecipe) ||
|
|
794
|
+
savedRecipe["repository"] !== repo ||
|
|
795
|
+
typeof resumeThreadId !== "string" ||
|
|
796
|
+
!resumeThreadId ||
|
|
797
|
+
JSON.stringify(savedRecipe["target"]) !==
|
|
798
|
+
JSON.stringify(recipe["target"])) {
|
|
799
|
+
throw new CodexSecurityError("The workbench returned mismatched scan resume context.");
|
|
800
|
+
}
|
|
801
|
+
const savedSession = await findScanSession(runtime.codexHome, resumeThreadId);
|
|
802
|
+
if (savedSession === null ||
|
|
803
|
+
savedSession.workingDirectory !== scanDir) {
|
|
804
|
+
throw new CodexSecurityError(`The original Codex session for scan ${scanId} is unavailable. Restore its session logs in the original Codex Security state directory before resuming.`);
|
|
805
|
+
}
|
|
806
|
+
if (typeof registration["sealedProducerVersion"] === "string") {
|
|
807
|
+
expectation.pluginVersion = registration["sealedProducerVersion"];
|
|
808
|
+
}
|
|
809
|
+
}
|
|
534
810
|
const targetId = registration["targetId"];
|
|
535
811
|
const contract = registration["contract"];
|
|
536
812
|
const contractTarget = isRecord(contract)
|
|
@@ -606,7 +882,10 @@ export class CodexSecurity {
|
|
|
606
882
|
await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
|
|
607
883
|
}
|
|
608
884
|
checkOpen();
|
|
609
|
-
const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.
|
|
885
|
+
const basePrompt = scanPrompt(normalized, mode, skillName, scanId, runtime.configPath !== undefined, knowledgeBase !== null, options.resumeScanId !== undefined &&
|
|
886
|
+
typeof registration["userContext"] === "string"
|
|
887
|
+
? registration["userContext"]
|
|
888
|
+
: options.scanPrompt, options.maxCostUsd !== undefined, discoveryPrompt);
|
|
610
889
|
checkOpen();
|
|
611
890
|
const feedback = await workbench({
|
|
612
891
|
...workbenchOptions,
|
|
@@ -626,7 +905,12 @@ export class CodexSecurity {
|
|
|
626
905
|
let prompt = scopeFileCount === null
|
|
627
906
|
? basePrompt
|
|
628
907
|
: `${basePrompt}\nThe SDK's current in-scope file-count estimate is ${scopeFileCount}; use it for scan progress unless exact scoped-source enumeration establishes a different total before review begins.`;
|
|
629
|
-
if (
|
|
908
|
+
if (options.resumeScanId !== undefined) {
|
|
909
|
+
prompt +=
|
|
910
|
+
"\nResume the existing Deep Scan through its coordinator. Preserve completed workers and saved artifacts; do not recreate the scan directory or restart completed analysis. If the coordinator already finished, continue with completion of this same scan.";
|
|
911
|
+
}
|
|
912
|
+
if (falsePositiveExamples.length > 0 &&
|
|
913
|
+
options.resumeScanId === undefined) {
|
|
630
914
|
const feedbackPath = join(scanDir, "artifacts", "01_context", "false_positive_feedback.json");
|
|
631
915
|
await mkdir(dirname(feedbackPath), { recursive: true, mode: 0o700 });
|
|
632
916
|
await writeFile(feedbackPath, `${JSON.stringify(falsePositiveExamples)}\n`, { flag: "wx", mode: 0o600, signal });
|
|
@@ -643,7 +927,10 @@ export class CodexSecurity {
|
|
|
643
927
|
: null;
|
|
644
928
|
const runtimePaths = {
|
|
645
929
|
PYTHON: python,
|
|
646
|
-
CODEX_SECURITY_STARTED_AT:
|
|
930
|
+
CODEX_SECURITY_STARTED_AT: options.resumeScanId !== undefined &&
|
|
931
|
+
typeof registration["startedAt"] === "string"
|
|
932
|
+
? registration["startedAt"]
|
|
933
|
+
: new Date().toISOString(),
|
|
647
934
|
CODEX_SECURITY_REPOSITORY: repo,
|
|
648
935
|
CODEX_SECURITY_SCAN_DIR: scanDir,
|
|
649
936
|
CODEX_SECURITY_PLUGIN_ROOT: shellPluginRoot,
|
|
@@ -675,12 +962,27 @@ export class CodexSecurity {
|
|
|
675
962
|
: { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
|
|
676
963
|
};
|
|
677
964
|
const { codex, environment } = this.#createSessionCodex(session, runtimePaths, options.auth);
|
|
678
|
-
const
|
|
965
|
+
const threadOptions = {
|
|
679
966
|
threadSource: CODEX_SECURITY_THREAD_SOURCES.scan,
|
|
680
967
|
workingDirectory: scanDir,
|
|
681
968
|
skipGitRepoCheck: true,
|
|
682
969
|
approvalPolicy,
|
|
683
|
-
}
|
|
970
|
+
};
|
|
971
|
+
let thread;
|
|
972
|
+
if (typeof resumeThreadId === "string") {
|
|
973
|
+
if (codex.resumeThread === undefined) {
|
|
974
|
+
throw new CodexSecurityError("The configured Codex client does not support resuming sessions.");
|
|
975
|
+
}
|
|
976
|
+
thread = codex.resumeThread(resumeThreadId, threadOptions);
|
|
977
|
+
tracker.start(resumeThreadId);
|
|
978
|
+
if (budgetRecovery !== null)
|
|
979
|
+
budgetRecovery.threadId = resumeThreadId;
|
|
980
|
+
await tracker.refresh().catch(reportTrackingError);
|
|
981
|
+
checkOpen();
|
|
982
|
+
}
|
|
983
|
+
else {
|
|
984
|
+
thread = codex.startThread(threadOptions);
|
|
985
|
+
}
|
|
684
986
|
const serializedPaths = normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
|
|
685
987
|
checkOpen();
|
|
686
988
|
if (serializedPaths !== null && targetPathsFile !== null) {
|
|
@@ -711,6 +1013,12 @@ export class CodexSecurity {
|
|
|
711
1013
|
workbenchValidated: true,
|
|
712
1014
|
model,
|
|
713
1015
|
onThreadStarted: async (threadId) => {
|
|
1016
|
+
if (resumeThreadId !== undefined) {
|
|
1017
|
+
if (threadId !== resumeThreadId) {
|
|
1018
|
+
throw new CodexSecurityError("Codex did not resume the original scan session.");
|
|
1019
|
+
}
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
714
1022
|
if (budgetRecovery !== null)
|
|
715
1023
|
budgetRecovery.threadId = threadId;
|
|
716
1024
|
tracker.start(threadId);
|
|
@@ -1005,7 +1313,9 @@ export class CodexSecurity {
|
|
|
1005
1313
|
}
|
|
1006
1314
|
catch { }
|
|
1007
1315
|
}
|
|
1008
|
-
|
|
1316
|
+
// A failed attachment must not turn a resumable coordinator into a terminal failure.
|
|
1317
|
+
// Deep Scan orchestration persists its own terminal failures and cancellations.
|
|
1318
|
+
if (activeScan !== null && options.resumeScanId === undefined) {
|
|
1009
1319
|
if (options.validationPrompt !== undefined &&
|
|
1010
1320
|
!customValidationComplete) {
|
|
1011
1321
|
await writeCustomValidationStatus(scanDir, {
|
|
@@ -1219,7 +1529,7 @@ export class CodexSecurity {
|
|
|
1219
1529
|
}
|
|
1220
1530
|
}
|
|
1221
1531
|
}
|
|
1222
|
-
#createSessionCodex(session, runtimePaths, auth = "auto") {
|
|
1532
|
+
#createSessionCodex(session, runtimePaths, auth = "auto", config, configOverrides = []) {
|
|
1223
1533
|
const { runtime, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
|
|
1224
1534
|
const commandAuth = hasCommandAuth(sessionConfig);
|
|
1225
1535
|
const environment = {
|
|
@@ -1239,7 +1549,7 @@ export class CodexSecurity {
|
|
|
1239
1549
|
if (session.safetyIdentifier !== undefined) {
|
|
1240
1550
|
environment[SAFETY_IDENTIFIER_ENV] = session.safetyIdentifier;
|
|
1241
1551
|
}
|
|
1242
|
-
const sdkCodexConfig = { ...sessionConfig };
|
|
1552
|
+
const sdkCodexConfig = { ...(config ?? sessionConfig) };
|
|
1243
1553
|
// Projects and permissions already live in generated TOML files; the SDK
|
|
1244
1554
|
// cannot safely encode their path and selector keys as dotted overrides.
|
|
1245
1555
|
delete sdkCodexConfig["projects"];
|
|
@@ -1263,8 +1573,15 @@ export class CodexSecurity {
|
|
|
1263
1573
|
? {}
|
|
1264
1574
|
: { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
|
|
1265
1575
|
...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
|
|
1266
|
-
...(commandAuth
|
|
1267
|
-
? {
|
|
1576
|
+
...(commandAuth || configOverrides.length > 0
|
|
1577
|
+
? {
|
|
1578
|
+
configOverrides: [
|
|
1579
|
+
...(commandAuth
|
|
1580
|
+
? modelProviderConfigOverride(sessionConfig)
|
|
1581
|
+
: []),
|
|
1582
|
+
...configOverrides,
|
|
1583
|
+
],
|
|
1584
|
+
}
|
|
1268
1585
|
: {}),
|
|
1269
1586
|
env: sdkEnvironment,
|
|
1270
1587
|
config: {
|
|
@@ -1277,7 +1594,7 @@ export class CodexSecurity {
|
|
|
1277
1594
|
});
|
|
1278
1595
|
return { codex, environment };
|
|
1279
1596
|
}
|
|
1280
|
-
async #prepareSession({ protectedRoot }, options, signal, temporaryRoot, keepCredentialLock = false) {
|
|
1597
|
+
async #prepareSession({ protectedRoot, protectedRoots = [protectedRoot], }, options, signal, temporaryRoot, keepCredentialLock = false) {
|
|
1281
1598
|
let releaseCredentialHome = null;
|
|
1282
1599
|
const checkOpen = () => {
|
|
1283
1600
|
this.#requireOpen();
|
|
@@ -1301,11 +1618,11 @@ export class CodexSecurity {
|
|
|
1301
1618
|
? withoutOpenAiApiKeys(this.#dependencies.environment)
|
|
1302
1619
|
: this.#dependencies.environment, options.auth, modelProvider);
|
|
1303
1620
|
if (this.#dependencies.prepareRuntime === undefined) {
|
|
1304
|
-
const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) =>
|
|
1621
|
+
const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
|
|
1305
1622
|
releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
|
|
1306
1623
|
}
|
|
1307
1624
|
const previousRuntime = this.#runtime;
|
|
1308
|
-
const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) =>
|
|
1625
|
+
const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"), options.auth, requestedConfig);
|
|
1309
1626
|
if (runtime === previousRuntime &&
|
|
1310
1627
|
this.#dependencies.prepareRuntime === undefined) {
|
|
1311
1628
|
await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
|
|
@@ -1317,7 +1634,7 @@ export class CodexSecurity {
|
|
|
1317
1634
|
await writeCodexConfig(runtime.configPath, preflightConfig);
|
|
1318
1635
|
}
|
|
1319
1636
|
const runtimeHome = await realpath(runtime.codexHome);
|
|
1320
|
-
|
|
1637
|
+
requireOutputOutsideRepositories(protectedRoots, runtimeHome, "runtime");
|
|
1321
1638
|
const sessionConfig = scanRuntimeCodexConfig(effectiveConfig, runtimeHome);
|
|
1322
1639
|
if (options.expectedPluginVersion !== undefined &&
|
|
1323
1640
|
runtime.plugin.version !== options.expectedPluginVersion) {
|
|
@@ -1352,9 +1669,7 @@ export class CodexSecurity {
|
|
|
1352
1669
|
apiKey === null &&
|
|
1353
1670
|
!commandAuth &&
|
|
1354
1671
|
authentication.method !== "aws_credentials") {
|
|
1355
|
-
throw new AuthenticationRequiredError(
|
|
1356
|
-
"'codex-security login --device-auth' on a remote or headless machine, or set " +
|
|
1357
|
-
"OPENAI_API_KEY or CODEX_API_KEY for CI.");
|
|
1672
|
+
throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
|
|
1358
1673
|
}
|
|
1359
1674
|
if (!commandAuth)
|
|
1360
1675
|
authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
|
|
@@ -1445,6 +1760,29 @@ export class CodexSecurity {
|
|
|
1445
1760
|
: undefined;
|
|
1446
1761
|
runtime.effectiveConfig = mergedConfig;
|
|
1447
1762
|
}
|
|
1763
|
+
async #validatePolicyInputs(target, options, signal) {
|
|
1764
|
+
policyCodexConfig(await mergedCodexConfig(this.config));
|
|
1765
|
+
const sources = await inspectSecurityPolicySources(target, signal);
|
|
1766
|
+
const protectedRoots = [
|
|
1767
|
+
...new Set([
|
|
1768
|
+
...(await securityPolicyProtectedRoots(target, signal)),
|
|
1769
|
+
...sources.gitMetadataPaths,
|
|
1770
|
+
]),
|
|
1771
|
+
];
|
|
1772
|
+
const inputs = await this.#validateLocalInputs(target.repository, {
|
|
1773
|
+
auth: options.auth,
|
|
1774
|
+
target: target.scope === "." ? "repository" : [dirname(target.targetPath)],
|
|
1775
|
+
outputDir: options.outputDir,
|
|
1776
|
+
maxCostUsd: options.maxCostUsd,
|
|
1777
|
+
}, signal, protectedRoots);
|
|
1778
|
+
return {
|
|
1779
|
+
...inputs,
|
|
1780
|
+
policyPaths: sources.policyPaths,
|
|
1781
|
+
gitMetadataPaths: [
|
|
1782
|
+
...new Set([...protectedRoots.slice(1), ...sources.gitMetadataPaths]),
|
|
1783
|
+
],
|
|
1784
|
+
};
|
|
1785
|
+
}
|
|
1448
1786
|
async #runMock(repository, options) {
|
|
1449
1787
|
const signal = AbortSignal.any([
|
|
1450
1788
|
this.#abortController.signal,
|
|
@@ -1597,7 +1935,16 @@ export class CodexSecurity {
|
|
|
1597
1935
|
await cleanupSdkDirectory(workspace);
|
|
1598
1936
|
}
|
|
1599
1937
|
}
|
|
1600
|
-
async #validateLocalInputs(repository, options, signal) {
|
|
1938
|
+
async #validateLocalInputs(repository, options, signal, protectedRoots) {
|
|
1939
|
+
if (options.resumeScanId !== undefined &&
|
|
1940
|
+
(options.mode !== "deep" ||
|
|
1941
|
+
!options.outputDir ||
|
|
1942
|
+
options.archiveExisting ||
|
|
1943
|
+
options.parentScanId !== undefined ||
|
|
1944
|
+
options.workflowId !== undefined ||
|
|
1945
|
+
options.mock)) {
|
|
1946
|
+
throw new CodexSecurityError("Resume requires the original Deep Scan output directory without archive, rerun, or workflow options.");
|
|
1947
|
+
}
|
|
1601
1948
|
if (options.mock &&
|
|
1602
1949
|
(options.mode === "deep" ||
|
|
1603
1950
|
options.validationPrompt !== undefined ||
|
|
@@ -1636,10 +1983,13 @@ export class CodexSecurity {
|
|
|
1636
1983
|
}
|
|
1637
1984
|
await validateCommittedDiffCheckout(repo, normalized, signal);
|
|
1638
1985
|
throwIfAborted(signal);
|
|
1639
|
-
const protectedRoot =
|
|
1640
|
-
|
|
1986
|
+
const protectedRoot = protectedRoots?.[0] ??
|
|
1987
|
+
(await enclosingGitWorktreeRoot(repo, signal)) ??
|
|
1988
|
+
repo;
|
|
1989
|
+
protectedRoots ??= [protectedRoot];
|
|
1990
|
+
const requestedOutput = await validateOutputDir(options.outputDir, options.resumeScanId !== undefined || options.archiveExisting);
|
|
1641
1991
|
if (requestedOutput !== null) {
|
|
1642
|
-
|
|
1992
|
+
requireOutputOutsideRepositories(protectedRoots, requestedOutput);
|
|
1643
1993
|
}
|
|
1644
1994
|
const stateDirectory = codexSecurityStateDirectory(this.#dependencies.environment);
|
|
1645
1995
|
let canonicalStateDirectory = stateDirectory;
|
|
@@ -1657,13 +2007,14 @@ export class CodexSecurity {
|
|
|
1657
2007
|
canonicalStateDirectory = parent;
|
|
1658
2008
|
}
|
|
1659
2009
|
}
|
|
1660
|
-
|
|
2010
|
+
requireOutputOutsideRepositories(protectedRoots, canonicalStateDirectory);
|
|
1661
2011
|
return {
|
|
1662
2012
|
repository: repo,
|
|
1663
2013
|
target: normalized,
|
|
1664
2014
|
mode,
|
|
1665
2015
|
outputDir: requestedOutput,
|
|
1666
2016
|
protectedRoot,
|
|
2017
|
+
protectedRoots,
|
|
1667
2018
|
stateDirectory,
|
|
1668
2019
|
};
|
|
1669
2020
|
}
|
|
@@ -2095,7 +2446,7 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
|
|
|
2095
2446
|
"This exhaustive scan authorizes the delegated-worker phases required by the selected skill; use available subagent tools and continue with parent-agent fallback if capacity changes.",
|
|
2096
2447
|
]),
|
|
2097
2448
|
"This SDK host does not render MCP Apps; use the terminal/chat workflow.",
|
|
2098
|
-
`Use ${python} as <python_command> for
|
|
2449
|
+
`Use ${python} as <python_command> for plugin Python helper scripts (.py files); replace any literal python or python3 helper invocation with this exact interpreter.`,
|
|
2099
2450
|
`Repository root: ${shellEnvironmentReference("CODEX_SECURITY_REPOSITORY")}`,
|
|
2100
2451
|
`Use this exact scan directory for all scan output: ${shellEnvironmentReference("CODEX_SECURITY_SCAN_DIR")}`,
|
|
2101
2452
|
`Use exactly ${JSON.stringify(scanId)} as the scan ID in the manifest, findings, and coverage.`,
|
|
@@ -2196,6 +2547,18 @@ function validateScanCostLimit(maxCostUsd, model) {
|
|
|
2196
2547
|
throw new CodexSecurityError(`A scan cost limit is not available for the configured model: ${model}.`);
|
|
2197
2548
|
}
|
|
2198
2549
|
}
|
|
2550
|
+
function addScanCosts(previous, current) {
|
|
2551
|
+
if (previous === null)
|
|
2552
|
+
return { ...current };
|
|
2553
|
+
return {
|
|
2554
|
+
model: current.model,
|
|
2555
|
+
inputTokens: previous.inputTokens + current.inputTokens,
|
|
2556
|
+
cachedInputTokens: previous.cachedInputTokens + current.cachedInputTokens,
|
|
2557
|
+
cacheWriteInputTokens: previous.cacheWriteInputTokens + current.cacheWriteInputTokens,
|
|
2558
|
+
outputTokens: previous.outputTokens + current.outputTokens,
|
|
2559
|
+
estimatedUsd: previous.estimatedUsd + current.estimatedUsd,
|
|
2560
|
+
};
|
|
2561
|
+
}
|
|
2199
2562
|
async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectation, signal, workbenchValidated = false) {
|
|
2200
2563
|
const required = [
|
|
2201
2564
|
"scan-manifest.json",
|
|
@@ -2290,7 +2653,8 @@ export function formatEnvironmentVariableRemovalGuidance(names) {
|
|
|
2290
2653
|
}
|
|
2291
2654
|
return `remove ${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]} from the environment`;
|
|
2292
2655
|
}
|
|
2293
|
-
|
|
2656
|
+
/** @internal */
|
|
2657
|
+
export async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
|
|
2294
2658
|
const authentication = scanAuthentication(environment, auth, modelProvider);
|
|
2295
2659
|
if (authentication.method !== "stored_credentials")
|
|
2296
2660
|
return authentication;
|
|
@@ -2452,7 +2816,62 @@ export function scanRuntimeCodexConfig(config, protectedCredentialHome) {
|
|
|
2452
2816
|
: { [protectedCredentialHome]: "read" }),
|
|
2453
2817
|
},
|
|
2454
2818
|
},
|
|
2819
|
+
[POLICY_PERMISSION_PROFILE]: {
|
|
2820
|
+
filesystem: policyFilesystemPermissions(),
|
|
2821
|
+
network: { enabled: false },
|
|
2822
|
+
},
|
|
2823
|
+
},
|
|
2824
|
+
};
|
|
2825
|
+
}
|
|
2826
|
+
function policyFilesystemPermissions(gitMetadataPaths = []) {
|
|
2827
|
+
return {
|
|
2828
|
+
":minimal": "read",
|
|
2829
|
+
":workspace_roots": "read",
|
|
2830
|
+
// A scoped "." keeps native permission paths literal, including glob characters.
|
|
2831
|
+
...Object.fromEntries(gitMetadataPaths.map((path) => [path, { ".": "deny" }])),
|
|
2832
|
+
};
|
|
2833
|
+
}
|
|
2834
|
+
function rethrowPolicyOutputError(error) {
|
|
2835
|
+
if (error instanceof OutputDirectoryNotEmptyError)
|
|
2836
|
+
throw new OutputDirectoryNotEmptyError(error.directory, "policy");
|
|
2837
|
+
throw error;
|
|
2838
|
+
}
|
|
2839
|
+
function requirePolicyConfigKeys(config) {
|
|
2840
|
+
const tables = [config];
|
|
2841
|
+
if (isRecord(config["features"]))
|
|
2842
|
+
tables.push(config["features"]);
|
|
2843
|
+
// The Codex SDK flattens these keys without quoting their components.
|
|
2844
|
+
if (tables.some((table) => Object.keys(table).some((key) => !/^[A-Za-z0-9_-]+$/u.test(key))))
|
|
2845
|
+
throw new ConfigurationError("Policy generation does not accept dotted or quoted Codex override keys. Use nested objects instead.");
|
|
2846
|
+
}
|
|
2847
|
+
function policyCodexConfig(config) {
|
|
2848
|
+
const resolved = resolveCodexProfile(config);
|
|
2849
|
+
requirePolicyConfigKeys(resolved);
|
|
2850
|
+
// The selected provider is already written as TOML. The SDK cannot quote
|
|
2851
|
+
// provider names when it flattens this table into command-line overrides.
|
|
2852
|
+
delete resolved["model_providers"];
|
|
2853
|
+
const features = isRecord(resolved["features"]) ? resolved["features"] : {};
|
|
2854
|
+
return {
|
|
2855
|
+
...resolved,
|
|
2856
|
+
approval_policy: "never",
|
|
2857
|
+
default_permissions: POLICY_PERMISSION_PROFILE,
|
|
2858
|
+
// The artifact directory may be inside an unrelated checkout.
|
|
2859
|
+
project_doc_max_bytes: 0,
|
|
2860
|
+
project_root_markers: [],
|
|
2861
|
+
allow_login_shell: false,
|
|
2862
|
+
shell_environment_policy: {
|
|
2863
|
+
inherit: "core",
|
|
2864
|
+
ignore_default_excludes: false,
|
|
2455
2865
|
},
|
|
2866
|
+
features: {
|
|
2867
|
+
...features,
|
|
2868
|
+
plugins: false,
|
|
2869
|
+
apps: false,
|
|
2870
|
+
shell_snapshot: false,
|
|
2871
|
+
},
|
|
2872
|
+
mcp_servers: {},
|
|
2873
|
+
web_search: "disabled",
|
|
2874
|
+
sandbox_workspace_write: { network_access: false },
|
|
2456
2875
|
};
|
|
2457
2876
|
}
|
|
2458
2877
|
function sharedCredentialCodexConfig(config, credentialHome) {
|
|
@@ -2460,11 +2879,7 @@ function sharedCredentialCodexConfig(config, credentialHome) {
|
|
|
2460
2879
|
approval_policy: scanApprovalPolicy(config),
|
|
2461
2880
|
features: { plugins: true },
|
|
2462
2881
|
};
|
|
2463
|
-
for (const key of
|
|
2464
|
-
"cli_auth_credentials_store",
|
|
2465
|
-
"forced_login_method",
|
|
2466
|
-
"forced_chatgpt_workspace_id",
|
|
2467
|
-
]) {
|
|
2882
|
+
for (const key of CODEX_AUTH_CONFIG_KEYS) {
|
|
2468
2883
|
if (Object.hasOwn(config, key))
|
|
2469
2884
|
shared[key] = structuredClone(config[key]);
|
|
2470
2885
|
}
|
|
@@ -2524,6 +2939,7 @@ export function scanPreflightCodexConfig(config) {
|
|
|
2524
2939
|
for (const key of [
|
|
2525
2940
|
"model",
|
|
2526
2941
|
"model_reasoning_effort",
|
|
2942
|
+
"model_reasoning_summary",
|
|
2527
2943
|
"model_provider",
|
|
2528
2944
|
"service_tier",
|
|
2529
2945
|
]) {
|
|
@@ -2554,6 +2970,11 @@ export function scanPreflightCodexConfig(config) {
|
|
|
2554
2970
|
return result;
|
|
2555
2971
|
};
|
|
2556
2972
|
const result = executionConfig(config);
|
|
2973
|
+
// Keep the effective summary even when preflight filters the profile name.
|
|
2974
|
+
const reasoningSummary = resolveCodexProfile(config)["model_reasoning_summary"];
|
|
2975
|
+
if (safeString(reasoningSummary)) {
|
|
2976
|
+
result["model_reasoning_summary"] = reasoningSummary;
|
|
2977
|
+
}
|
|
2557
2978
|
const selectedProfile = safeProfileName(config["profile"])
|
|
2558
2979
|
? config["profile"]
|
|
2559
2980
|
: undefined;
|