@openai/codex-security 0.1.26 → 0.1.28
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 +637 -74
- 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/artifact-storage.md +56 -0
- package/_bundled_plugin/references/config-preflight.md +9 -1
- package/_bundled_plugin/references/core-scan.md +1 -1
- package/_bundled_plugin/references/final-report.md +2 -0
- package/_bundled_plugin/references/scan-artifacts.md +6 -14
- package/_bundled_plugin/references/scan-contract.md +35 -35
- package/_bundled_plugin/references/scan-prologue.md +2 -0
- package/_bundled_plugin/references/security-guidance.md +9 -1
- package/_bundled_plugin/scripts/deep_scan_config.py +10 -8
- package/_bundled_plugin/scripts/deep_scan_defaults.json +8 -0
- 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/reserved_artifact_paths.json +6 -0
- package/_bundled_plugin/scripts/windows_scan_local_files.py +1 -3
- package/_bundled_plugin/scripts/workbench/storage.py +18 -0
- package/_bundled_plugin/scripts/workbench_cli.py +17 -0
- package/_bundled_plugin/scripts/workbench_db.py +46 -42
- package/_bundled_plugin/scripts/workbench_saved_results.py +72 -1
- package/_bundled_plugin/scripts/workbench_scan_history.py +117 -2
- package/_bundled_plugin/scripts/workbench_scan_usage.py +23 -10
- package/_bundled_plugin/scripts/workbench_validation.py +4 -0
- package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +2 -0
- package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +2 -0
- package/_bundled_plugin/skills/deep-security-scan/SKILL.md +5 -1
- package/_bundled_plugin/skills/define-security-policy/SKILL.md +3 -3
- package/_bundled_plugin/skills/finding-discovery/SKILL.md +2 -0
- package/_bundled_plugin/skills/fix-finding/SKILL.md +3 -1
- package/_bundled_plugin/skills/fix-finding/agents/openai.yaml +1 -1
- package/_bundled_plugin/skills/propose-security-hardening/SKILL.md +2 -0
- package/_bundled_plugin/skills/security-scan/references/desktop-scan.md +5 -1
- package/_bundled_plugin/skills/threat-model/SKILL.md +2 -0
- package/_bundled_plugin/skills/validation/SKILL.md +2 -0
- package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +2 -0
- package/dist/api.d.ts +14 -24
- package/dist/api.d.ts.map +1 -1
- package/dist/api.js +585 -168
- package/dist/api.js.map +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +10 -0
- package/dist/auth.js.map +1 -1
- package/dist/bulk-scan-discovery.d.ts +1 -1
- package/dist/bulk-scan-discovery.d.ts.map +1 -1
- package/dist/bulk-scan-discovery.js +2 -2
- package/dist/bulk-scan-discovery.js.map +1 -1
- package/dist/classify-scan-severity.js.map +1 -1
- package/dist/classify-severity.d.ts.map +1 -1
- package/dist/classify-severity.js.map +1 -1
- package/dist/cli.d.ts +24 -4
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +1577 -610
- 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/component-scan.d.ts +4 -2
- package/dist/component-scan.d.ts.map +1 -1
- package/dist/component-scan.js +7 -1
- package/dist/component-scan.js.map +1 -1
- package/dist/config-path.d.ts +6 -0
- package/dist/config-path.d.ts.map +1 -0
- package/dist/config-path.js +6 -0
- package/dist/config-path.js.map +1 -0
- package/dist/config.d.ts +3 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +30 -5
- 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 +30 -0
- package/dist/cost-model.d.ts.map +1 -1
- package/dist/cost-model.js +123 -4
- 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-publish.js.map +1 -1
- package/dist/custom-validation-prompt.js +1 -1
- package/dist/custom-validation-prompt.js.map +1 -1
- package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
- package/dist/deduplication/checkpointed-review.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-reviewer.d.ts.map +1 -1
- package/dist/deduplication/deduplication-reviewer.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/deep-config.d.ts +17 -0
- package/dist/deep-config.d.ts.map +1 -0
- package/dist/deep-config.js +145 -0
- package/dist/deep-config.js.map +1 -0
- package/dist/deep-progress.d.ts.map +1 -1
- package/dist/deep-scan-defaults.d.ts +9 -0
- package/dist/deep-scan-defaults.d.ts.map +1 -0
- package/dist/deep-scan-defaults.js +10 -0
- package/dist/deep-scan-defaults.js.map +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -2
- package/dist/errors.js.map +1 -1
- package/dist/feedback.d.ts +20 -0
- package/dist/feedback.d.ts.map +1 -0
- package/dist/feedback.js +135 -0
- package/dist/feedback.js.map +1 -0
- package/dist/finding-catalogue.js.map +1 -1
- package/dist/finding-workflow.d.ts.map +1 -1
- package/dist/finding-workflow.js.map +1 -1
- 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/github.d.ts +625 -7
- package/dist/github.d.ts.map +1 -1
- package/dist/github.js.map +1 -1
- 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 +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -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 +19 -8
- package/dist/knowledge-base.js.map +1 -1
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/multiscan.d.ts +7 -5
- package/dist/multiscan.d.ts.map +1 -1
- package/dist/multiscan.js +212 -55
- package/dist/multiscan.js.map +1 -1
- package/dist/patch-tui.d.ts.map +1 -1
- package/dist/patch-tui.js.map +1 -1
- package/dist/project-config-schema.d.ts +191 -0
- package/dist/project-config-schema.d.ts.map +1 -0
- package/dist/project-config-schema.js +85 -0
- package/dist/project-config-schema.js.map +1 -0
- package/dist/project-config.d.ts +50 -0
- package/dist/project-config.d.ts.map +1 -0
- package/dist/project-config.js +220 -0
- package/dist/project-config.js.map +1 -0
- package/dist/prompt-files.d.ts +13 -0
- package/dist/prompt-files.d.ts.map +1 -0
- package/dist/prompt-files.js +74 -0
- package/dist/prompt-files.js.map +1 -0
- 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/publish.d.ts.map +1 -1
- package/dist/publish.js +1 -1
- package/dist/publish.js.map +1 -1
- package/dist/result.d.ts +2 -1
- package/dist/result.d.ts.map +1 -1
- package/dist/result.js +5 -0
- package/dist/result.js.map +1 -1
- package/dist/runtime.d.ts +5 -1
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +12 -6
- package/dist/runtime.js.map +1 -1
- package/dist/scan-comparison.d.ts.map +1 -1
- package/dist/scan-comparison.js.map +1 -1
- package/dist/scan-dashboard.d.ts +1 -0
- package/dist/scan-dashboard.d.ts.map +1 -1
- package/dist/scan-dashboard.js +45 -20
- package/dist/scan-dashboard.js.map +1 -1
- package/dist/scan-history-renderer.d.ts.map +1 -1
- package/dist/scan-history-renderer.js.map +1 -1
- package/dist/scan-logs.d.ts +39 -3
- package/dist/scan-logs.d.ts.map +1 -1
- package/dist/scan-logs.js +77 -15
- package/dist/scan-logs.js.map +1 -1
- package/dist/scan-modes.d.ts +3 -0
- package/dist/scan-modes.d.ts.map +1 -0
- package/dist/scan-modes.js +2 -0
- package/dist/scan-modes.js.map +1 -0
- package/dist/scan-settings.d.ts +81 -0
- package/dist/scan-settings.d.ts.map +1 -0
- package/dist/scan-settings.js +123 -0
- package/dist/scan-settings.js.map +1 -0
- 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/server/dashboard/THIRD_PARTY_NOTICES.txt +2 -2
- package/dist/server/dashboard/app.js +2 -2
- package/dist/server/dashboard.js.map +1 -1
- package/dist/server/embeddings.d.ts.map +1 -1
- package/dist/server/embeddings.js.map +1 -1
- package/dist/server/errors.d.ts.map +1 -1
- package/dist/server/errors.js.map +1 -1
- package/dist/server/findings-service.d.ts.map +1 -1
- package/dist/server/findings-service.js.map +1 -1
- package/dist/server/serve.js.map +1 -1
- package/dist/server/sqlite-store.d.ts.map +1 -1
- package/dist/server/sqlite-store.js.map +1 -1
- package/dist/severity-store.js.map +1 -1
- package/dist/targets.d.ts +10 -2
- package/dist/targets.d.ts.map +1 -1
- package/dist/targets.js +243 -14
- package/dist/targets.js.map +1 -1
- package/dist/thread-source.d.ts.map +1 -1
- package/dist/version.js.map +1 -1
- package/dist/worker-progress.d.ts.map +1 -1
- package/dist/worker-progress.js.map +1 -1
- package/package.json +36 -29
- package/schemas/project-config.schema.json +211 -0
- package/_bundled_plugin/scripts/resolve_security_md.py +0 -158
package/dist/cli.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
import { execFile as execFileCallback, execFileSync, spawn, } from "node:child_process";
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { accessSync, constants, createReadStream, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
|
|
5
|
-
import { chmod, lstat, mkdir, mkdtemp,
|
|
5
|
+
import { chmod, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, writeFile, } from "node:fs/promises";
|
|
6
6
|
import { homedir, tmpdir } from "node:os";
|
|
7
|
-
import { basename, dirname, isAbsolute, join, parse, relative, resolve,
|
|
7
|
+
import { basename, dirname, isAbsolute, join, parse, relative, resolve, win32, } from "node:path";
|
|
8
8
|
import { cwd } from "node:process";
|
|
9
9
|
import { createInterface } from "node:readline";
|
|
10
10
|
import { Readable, Writable as NodeWritable } from "node:stream";
|
|
@@ -13,34 +13,46 @@ import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
13
13
|
import { promisify, stripVTControlCharacters } from "node:util";
|
|
14
14
|
import { Cli, z } from "incur";
|
|
15
15
|
import { parse as parseToml } from "smol-toml";
|
|
16
|
-
import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, } from "./api.js";
|
|
17
|
-
import { accountStatus } from "./auth.js";
|
|
16
|
+
import { classifyConnectionFailure, createSecurityInternal, environmentValue, formatEnvironmentVariableRemovalGuidance, initialCredentialsAvailable, listRepositoryFindings, SCAN_AUTH_MODES, scanAuthentication, runtimeScanAuthentication, selectedScanEnvironment, } from "./api.js";
|
|
17
|
+
import { accountStatus, CODEX_AUTH_CONFIG_KEYS, NO_CREDENTIALS_MESSAGE, configuredCodexHome, readCodexHomeConfig, } from "./auth.js";
|
|
18
|
+
import { loadContract } from "./contract.js";
|
|
18
19
|
import { publishScanToCustom } from "./custom-publish.js";
|
|
20
|
+
import { DEFAULT_DEDUPE_CONCURRENCY } from "./deduplication/deduplication.js";
|
|
19
21
|
import { deduplicateScanInternal } from "./deduplication/scan.js";
|
|
20
22
|
import { classifyScanSeverityInternal, classifyScanDirectorySeverityInternal, } from "./classify-scan-severity.js";
|
|
21
23
|
import { resolveCompletedScan, resolveWorkflowScan, } from "./saved-scan.js";
|
|
22
24
|
import { publishFindingsCsvToCloud, publishScanToCloud, } from "./cloud-publish.js";
|
|
23
25
|
import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
|
|
24
|
-
import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, } from "./config.js";
|
|
26
|
+
import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergeCodexOverrides, hasCommandAuth, inlineToml, modelProviderConfigOverride, resolveCommandAuthConfig, mergedCodexConfig, scanModel, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
|
|
25
27
|
import { formatUsd } from "./cost.js";
|
|
26
|
-
import {
|
|
28
|
+
import { formatScanCost, formatScanCostTokens, formatTokenUsage, } from "./cost-model.js";
|
|
29
|
+
import { isOutsidePath, readRegularInputFile, resolveScanPrompts, } from "./prompt-files.js";
|
|
30
|
+
import { CodexSecurityError, AuthenticationRequiredError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
|
|
27
31
|
import { GITHUB_ALERT_STATES, importGitHubCodeScanningAlerts, } from "./github.js";
|
|
28
32
|
import { importLinearIssues, isLinearIssueIdentifier, resolveLinearApiKey, } from "./linear.js";
|
|
29
33
|
import { runMultiscan } from "./multiscan.js";
|
|
30
34
|
import { componentPlanSchema } from "./component-plan.js";
|
|
31
35
|
import { runComponentScans, } from "./component-scan.js";
|
|
32
36
|
import { checkScanPublication, forceTerminatePublicationProcesses as terminatePublishers, publishScan, } from "./publish.js";
|
|
33
|
-
import {
|
|
37
|
+
import { importScan } from "./import-scan.js";
|
|
38
|
+
import { bundledPluginRoot, acquireCodexSecurityCredentialHomeLock, requireOutputOutsideRepositories, canonicalizeModelSafePath, codexSecurityCredentialHome, codexSecurityStateDirectory, executablePathForSpawn, expandHome, prepareCodexSecurityCredentialHome, pythonUtf8Environment, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
|
|
34
39
|
import { comparisonFindingGroups, comparisonForScan, matchScanFindingsInternal, unionFindingGroups, } from "./scan-comparison.js";
|
|
35
40
|
import { scanActivitiesFromEvent } from "./scan-activity.js";
|
|
36
41
|
import { CODEX_SECURITY_THREAD_SOURCES, } from "./thread-source.js";
|
|
37
|
-
import {
|
|
42
|
+
import { findScanSession, readSavedScanLogs, } from "./scan-logs.js";
|
|
43
|
+
import { sendFeedback } from "./feedback.js";
|
|
38
44
|
import { renderScanHistory, } from "./scan-history-renderer.js";
|
|
39
45
|
import { ScanDashboard } from "./scan-dashboard.js";
|
|
46
|
+
import { policyDisplayData, runPolicyCommand, } from "./security-policy-cli.js";
|
|
40
47
|
import { scanPhaseLabel as scanPhase, } from "./worker-progress.js";
|
|
41
|
-
import { abortable, DiffTarget, } from "./targets.js";
|
|
48
|
+
import { abortable, DiffTarget, enclosingGitWorktreeRoots, } from "./targets.js";
|
|
42
49
|
import { resolveTrustedExecutable } from "./trusted-executable.js";
|
|
43
50
|
import { BUNDLED_PLUGIN_VERSION, checkForUpdate, CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION, formatUpdateNotice, updateNoticeEnabled, VERSION, } from "./version.js";
|
|
51
|
+
import { readProjectConfig, resolveScanSettings, projectScopeTarget, configurationSources, projectConfigStarter, } from "./project-config.js";
|
|
52
|
+
import { resolveConfigPath } from "./config-path.js";
|
|
53
|
+
import { resolveDeepScanConfig } from "./deep-config.js";
|
|
54
|
+
import { SCAN_MODES } from "./scan-modes.js";
|
|
55
|
+
import { DEEP_SCAN_SETTINGS, DeepScanSettingsSchema, DEFAULT_SCAN_AUTH, FailureSeveritySchema, REPORTABLE_SEVERITIES, SCAN_SEVERITIES, ScanSettingsSchema, pickScanSettings, meetsSeverity, } from "./scan-settings.js";
|
|
44
56
|
const PROGRESS_REFRESH_MILLISECONDS = 1_000;
|
|
45
57
|
const execFile = promisify(execFileCallback);
|
|
46
58
|
const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
|
|
@@ -53,16 +65,7 @@ const DUPLICATE_SIGNAL_WINDOW_MS = 500;
|
|
|
53
65
|
const PUBLICATION_GRAPHEME_SEGMENTER = new Intl.Segmenter(undefined, {
|
|
54
66
|
granularity: "grapheme",
|
|
55
67
|
});
|
|
56
|
-
const
|
|
57
|
-
"critical",
|
|
58
|
-
"high",
|
|
59
|
-
"medium",
|
|
60
|
-
"low",
|
|
61
|
-
];
|
|
62
|
-
const DISPLAY_SEVERITIES = [
|
|
63
|
-
...REPORTABLE_SEVERITIES,
|
|
64
|
-
"informational",
|
|
65
|
-
];
|
|
68
|
+
const DISPLAY_SEVERITIES = SCAN_SEVERITIES;
|
|
66
69
|
const MODEL_REASONING_EFFORTS = [
|
|
67
70
|
"minimal",
|
|
68
71
|
"low",
|
|
@@ -75,14 +78,20 @@ const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CO
|
|
|
75
78
|
const CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML KEY=VALUE; e.g. model_reasoning_effort="high" or features.multi_agent_v2.max_concurrent_threads_per_session=4.';
|
|
76
79
|
const PLUGIN_PATH_DESCRIPTION = "Codex Security plugin directory or ZIP (default: bundled plugin).";
|
|
77
80
|
const PYTHON_PATH_DESCRIPTION = "Python interpreter (default: PYTHON or automatic discovery).";
|
|
81
|
+
const PROJECT_CONFIG_OPTION = optionValue("--config")
|
|
82
|
+
.optional()
|
|
83
|
+
.describe("Load a trusted YAML/JSON file (default: CODEX_SECURITY_PROJECT_CONFIG, otherwise no file).");
|
|
78
84
|
const EXPORT_DEFAULT_OUTPUTS = {
|
|
79
85
|
csv: "findings.csv",
|
|
80
86
|
json: "findings.json",
|
|
81
87
|
sarif: "results.sarif",
|
|
82
88
|
};
|
|
83
89
|
const VALUE_OPTIONS = new Set([
|
|
90
|
+
"--config",
|
|
91
|
+
"-c",
|
|
84
92
|
"--port",
|
|
85
93
|
"--workflow-id",
|
|
94
|
+
"--concurrency",
|
|
86
95
|
"--auth",
|
|
87
96
|
"--safety-identifier",
|
|
88
97
|
"--path",
|
|
@@ -145,6 +154,10 @@ const PROVIDER_OPTION = z
|
|
|
145
154
|
.enum(["openai", "openrouter", "fireworks", "amazon-bedrock"])
|
|
146
155
|
.default("openai")
|
|
147
156
|
.describe("Inference provider for scans.");
|
|
157
|
+
const SHOW_COST_OPTION = z
|
|
158
|
+
.boolean()
|
|
159
|
+
.default(false)
|
|
160
|
+
.describe("Show estimated USD cost; always shown when a cost limit is set.");
|
|
148
161
|
const CREATE_PR_OPTION = z
|
|
149
162
|
.boolean()
|
|
150
163
|
.default(false)
|
|
@@ -597,95 +610,21 @@ function effortOption() {
|
|
|
597
610
|
.optional()
|
|
598
611
|
.describe(`Model reasoning effort (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort}).`);
|
|
599
612
|
}
|
|
600
|
-
const DEEP_SCAN_OPTION_SCHEMAS =
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
.describe("Maximum concurrent deep-scan discovery workers."),
|
|
607
|
-
subagents: z
|
|
608
|
-
.number()
|
|
609
|
-
.int()
|
|
610
|
-
.nonnegative()
|
|
611
|
-
.optional()
|
|
612
|
-
.describe("Subagents available to each deep-scan worker."),
|
|
613
|
-
stopAfterNoNew: z
|
|
614
|
-
.number()
|
|
615
|
-
.int()
|
|
616
|
-
.positive()
|
|
617
|
-
.optional()
|
|
618
|
-
.describe("Stop after this many runs find no new issues."),
|
|
619
|
-
maxDiscoveryRuns: z
|
|
620
|
-
.number()
|
|
621
|
-
.int()
|
|
622
|
-
.positive()
|
|
623
|
-
.optional()
|
|
624
|
-
.describe("Maximum deep-scan discovery runs."),
|
|
625
|
-
maxTimeHours: z
|
|
626
|
-
.number()
|
|
627
|
-
.positive()
|
|
628
|
-
.max(96)
|
|
629
|
-
.optional()
|
|
630
|
-
.describe("Maximum deep-scan discovery hours (default: 96; maximum: 96)."),
|
|
631
|
-
};
|
|
632
|
-
async function readPromptFiles(directory, scanPromptFile, postScanPromptFile, repository = directory, validationPromptFile) {
|
|
633
|
-
const [scanPrompt, postScanPrompt, validationPrompt] = await Promise.all([
|
|
634
|
-
scanPromptFile === undefined
|
|
635
|
-
? undefined
|
|
636
|
-
: readRegularInputFile(resolveCliPath(directory, scanPromptFile), repository),
|
|
637
|
-
postScanPromptFile === undefined
|
|
638
|
-
? undefined
|
|
639
|
-
: readRegularInputFile(resolveCliPath(directory, postScanPromptFile), repository),
|
|
640
|
-
validationPromptFile === undefined
|
|
641
|
-
? undefined
|
|
642
|
-
: readRegularInputFile(resolveCliPath(directory, validationPromptFile), repository),
|
|
643
|
-
]);
|
|
644
|
-
if (validationPrompt !== undefined && !validationPrompt.trim()) {
|
|
645
|
-
throw new CodexSecurityError("The validation prompt must not be empty.");
|
|
646
|
-
}
|
|
647
|
-
return {
|
|
648
|
-
...(scanPrompt?.trim() ? { scanPrompt } : {}),
|
|
649
|
-
...(validationPrompt === undefined ? {} : { validationPrompt }),
|
|
650
|
-
...(postScanPrompt?.trim() ? { postScanPrompt } : {}),
|
|
651
|
-
};
|
|
613
|
+
const DEEP_SCAN_OPTION_SCHEMAS = Object.fromEntries(DEEP_SCAN_SETTINGS.filter(([, , , flag]) => flag !== null).map(([name]) => [
|
|
614
|
+
name,
|
|
615
|
+
DeepScanSettingsSchema.shape[name],
|
|
616
|
+
]));
|
|
617
|
+
export function resolveCliPath(directory, value) {
|
|
618
|
+
return resolveConfigPath(directory, value);
|
|
652
619
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
const canonicalRepository = await realpath(repository);
|
|
659
|
-
const canonicalParent = await realpath(dirname(path));
|
|
660
|
-
if (isOutsidePath(relative(canonicalRepository, canonicalParent))) {
|
|
661
|
-
for (let ancestor = dirname(path);; ancestor = dirname(ancestor)) {
|
|
662
|
-
if (!isOutsidePath(relative(canonicalRepository, await realpath(ancestor)))) {
|
|
663
|
-
throw new CodexSecurityError("Input files must not follow repository directory links outside the selected repository.");
|
|
664
|
-
}
|
|
665
|
-
if (dirname(ancestor) === ancestor) {
|
|
666
|
-
break;
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
}
|
|
670
|
-
const file = await open(join(canonicalParent, basename(path)), constants.O_RDONLY |
|
|
671
|
-
(constants.O_NOFOLLOW ?? 0) |
|
|
672
|
-
(constants.O_NONBLOCK ?? 0));
|
|
673
|
-
try {
|
|
674
|
-
const opened = await file.stat({ bigint: true });
|
|
675
|
-
if (!opened.isFile() ||
|
|
676
|
-
opened.dev !== selected.dev ||
|
|
677
|
-
opened.ino !== selected.ino) {
|
|
678
|
-
throw new CodexSecurityError("Input files must remain regular files.");
|
|
679
|
-
}
|
|
680
|
-
return await file.readFile({ encoding: "utf8" });
|
|
681
|
-
}
|
|
682
|
-
finally {
|
|
683
|
-
await file.close();
|
|
620
|
+
class PatchCommandError extends CodexSecurityError {
|
|
621
|
+
code;
|
|
622
|
+
constructor(code, message) {
|
|
623
|
+
super(message);
|
|
624
|
+
this.code = code;
|
|
684
625
|
}
|
|
685
626
|
}
|
|
686
|
-
|
|
687
|
-
return resolve(directory, expandHome(value));
|
|
688
|
-
}
|
|
627
|
+
const SANDBOX_UNAVAILABLE_MESSAGE = "The patch sandbox could not start. Check the runner's sandbox permissions and retry. No patch was applied; 0 files changed.";
|
|
689
628
|
const findingPatchSchema = z.object({
|
|
690
629
|
occurrenceId: z.string(),
|
|
691
630
|
status: z.enum(["verified", "no_change", "blocked", "failed"]),
|
|
@@ -786,7 +725,7 @@ const DEFAULT_DEPENDENCIES = {
|
|
|
786
725
|
[status] = await Promise.all([
|
|
787
726
|
new Promise((resolve, reject) => {
|
|
788
727
|
invocation.once("error", reject);
|
|
789
|
-
invocation.once("close", (code, signal) => resolve(signal === null ? code ?? 1 : 1));
|
|
728
|
+
invocation.once("close", (code, signal) => resolve(signal === null ? (code ?? 1) : 1));
|
|
790
729
|
}),
|
|
791
730
|
forwarded,
|
|
792
731
|
]);
|
|
@@ -820,144 +759,272 @@ const DEFAULT_DEPENDENCIES = {
|
|
|
820
759
|
matchFindings: (input, options) => matchScanFindingsInternal(input, options, { surface: "cli" }),
|
|
821
760
|
};
|
|
822
761
|
export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env, input) {
|
|
823
|
-
|
|
824
|
-
? environmentValue(processEnvironment, "CODEX_HOME")
|
|
825
|
-
: processEnvironment["CODEX_HOME"];
|
|
826
|
-
const environment = { ...processEnvironment };
|
|
827
|
-
for (const name of Object.keys(environment)) {
|
|
828
|
-
if (name.toUpperCase() === "CODEX_HOME")
|
|
829
|
-
delete environment[name];
|
|
830
|
-
}
|
|
831
|
-
if (configuredHome?.trim()) {
|
|
832
|
-
environment["CODEX_HOME"] = resolve(expandHome(configuredHome, processEnvironment));
|
|
833
|
-
}
|
|
834
|
-
const invocation = spawn(executablePathForSpawn(command.command), [...args], {
|
|
835
|
-
env: environment,
|
|
836
|
-
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
|
|
837
|
-
stdio: output === undefined
|
|
838
|
-
? input === undefined
|
|
839
|
-
? "inherit"
|
|
840
|
-
: ["pipe", "inherit", "inherit"]
|
|
841
|
-
: [
|
|
842
|
-
output.appServer !== undefined || input !== undefined
|
|
843
|
-
? "pipe"
|
|
844
|
-
: "ignore",
|
|
845
|
-
"pipe",
|
|
846
|
-
"pipe",
|
|
847
|
-
],
|
|
848
|
-
windowsHide: true,
|
|
849
|
-
});
|
|
850
|
-
if (input !== undefined) {
|
|
851
|
-
invocation.stdin?.on("error", () => { });
|
|
852
|
-
invocation.stdin?.end(input);
|
|
853
|
-
}
|
|
854
|
-
let requestedSignal = null;
|
|
855
|
-
let forcedTermination;
|
|
856
|
-
let forceStatusCompletion = null;
|
|
857
|
-
let forceCaptureCompletion = null;
|
|
858
|
-
let invocationStatus;
|
|
859
|
-
const requestTermination = (signal) => {
|
|
860
|
-
requestedSignal = signal;
|
|
861
|
-
invocation.kill(signal);
|
|
862
|
-
if (forcedTermination !== undefined)
|
|
863
|
-
return;
|
|
864
|
-
forcedTermination = setTimeout(() => {
|
|
865
|
-
forcedTermination = undefined;
|
|
866
|
-
if (invocation.exitCode === null && invocation.signalCode === null) {
|
|
867
|
-
invocation.kill("SIGKILL");
|
|
868
|
-
}
|
|
869
|
-
forceCaptureCompletion?.();
|
|
870
|
-
invocation.stdout?.destroy();
|
|
871
|
-
invocation.stderr?.destroy();
|
|
872
|
-
forceStatusCompletion?.();
|
|
873
|
-
}, CHILD_TERMINATION_GRACE_MS);
|
|
874
|
-
};
|
|
875
|
-
const onInterrupt = () => {
|
|
876
|
-
requestTermination("SIGINT");
|
|
877
|
-
};
|
|
878
|
-
const onTerminate = () => {
|
|
879
|
-
requestTermination("SIGTERM");
|
|
880
|
-
};
|
|
881
|
-
process.on("SIGINT", onInterrupt);
|
|
882
|
-
process.on("SIGTERM", onTerminate);
|
|
762
|
+
let releaseCredentialHome;
|
|
883
763
|
try {
|
|
884
|
-
let
|
|
885
|
-
|
|
886
|
-
|
|
764
|
+
let apiKey;
|
|
765
|
+
let authentication = null;
|
|
766
|
+
let modelProvider;
|
|
767
|
+
// runSkill selects auth; other process callers supply their own environment.
|
|
768
|
+
if (output?.auth !== undefined) {
|
|
769
|
+
const config = output.modelProvider !== undefined
|
|
770
|
+
? {
|
|
771
|
+
model_provider: output.modelProvider,
|
|
772
|
+
...(output.providerConfiguration === undefined
|
|
773
|
+
? {}
|
|
774
|
+
: {
|
|
775
|
+
model_providers: {
|
|
776
|
+
[output.modelProvider]: output.providerConfiguration,
|
|
777
|
+
},
|
|
778
|
+
}),
|
|
779
|
+
}
|
|
780
|
+
: output.appServer === undefined
|
|
781
|
+
? {}
|
|
782
|
+
: await readCodexHomeConfig(processEnvironment);
|
|
783
|
+
const provider = scanModelProvider(config);
|
|
784
|
+
const providerConfiguration = typeof provider === "string"
|
|
785
|
+
? config["model_providers"]?.[provider]
|
|
786
|
+
: undefined;
|
|
787
|
+
const requiresOpenAiAuth = provider === undefined ||
|
|
788
|
+
provider === "openai" ||
|
|
789
|
+
providerConfiguration?.["requires_openai_auth"] === true;
|
|
790
|
+
modelProvider = output.modelProvider;
|
|
791
|
+
let credentialConfig;
|
|
792
|
+
authentication = scanAuthentication(processEnvironment, output.auth, provider, hasCommandAuth(config));
|
|
793
|
+
if (authentication.method === "stored_credentials" &&
|
|
794
|
+
isExternalModelProvider(provider)) {
|
|
795
|
+
const externalProvider = EXTERNAL_CODEX_PROVIDERS[provider];
|
|
796
|
+
throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run ${output.command} through ${externalProvider.name}.`);
|
|
797
|
+
}
|
|
798
|
+
let selected = selectedScanEnvironment(processEnvironment, authentication.method === "command" ? "chatgpt" : output.auth, provider);
|
|
799
|
+
if (authentication.method === "stored_credentials" &&
|
|
800
|
+
requiresOpenAiAuth) {
|
|
801
|
+
const directory = await realpath(output.directory ?? output.appServer?.directory ?? process.cwd());
|
|
802
|
+
const protectedRoots = [
|
|
803
|
+
directory,
|
|
804
|
+
...(await enclosingGitWorktreeRoots(directory)),
|
|
805
|
+
];
|
|
806
|
+
const codexHome = await prepareCodexSecurityCredentialHome(selected, (path) => requireOutputOutsideRepositories(protectedRoots, path, "runtime"));
|
|
807
|
+
releaseCredentialHome =
|
|
808
|
+
await acquireCodexSecurityCredentialHomeLock(codexHome);
|
|
809
|
+
let credentialsAvailable;
|
|
810
|
+
const ambientConfig = await readCodexHomeConfig(selected);
|
|
811
|
+
credentialConfig = await readCodexHomeConfig({
|
|
812
|
+
...selected,
|
|
813
|
+
CODEX_HOME: codexHome,
|
|
814
|
+
});
|
|
815
|
+
// Let native Codex apply the ambient home's project-trust decisions.
|
|
816
|
+
for (const key of [
|
|
817
|
+
...CODEX_AUTH_CONFIG_KEYS,
|
|
818
|
+
"projects",
|
|
819
|
+
"project_root_markers",
|
|
820
|
+
]) {
|
|
821
|
+
const value = ambientConfig[key];
|
|
822
|
+
if (value === undefined)
|
|
823
|
+
delete credentialConfig[key];
|
|
824
|
+
else
|
|
825
|
+
credentialConfig[key] = value;
|
|
826
|
+
}
|
|
827
|
+
if (typeof provider === "string")
|
|
828
|
+
credentialConfig["model_provider"] = provider;
|
|
829
|
+
else
|
|
830
|
+
delete credentialConfig["model_provider"];
|
|
831
|
+
delete credentialConfig["profile"];
|
|
832
|
+
if (typeof provider !== "string" || providerConfiguration === undefined)
|
|
833
|
+
delete credentialConfig["model_providers"];
|
|
834
|
+
else
|
|
835
|
+
credentialConfig["model_providers"] = {
|
|
836
|
+
[provider]: providerConfiguration,
|
|
837
|
+
};
|
|
838
|
+
await writeCodexConfig(join(codexHome, "config.toml"), credentialConfig);
|
|
839
|
+
credentialsAvailable = await initialCredentialsAvailable(selected, configuredCodexHome(selected), codexHome);
|
|
840
|
+
selected = {
|
|
841
|
+
...selected,
|
|
842
|
+
CODEX_HOME: codexHome,
|
|
843
|
+
CODEX_SECURITY_STATE_DIR: codexSecurityStateDirectory(selected),
|
|
844
|
+
};
|
|
845
|
+
if (!credentialsAvailable &&
|
|
846
|
+
!(await accountStatus(command, selected)).authenticated) {
|
|
847
|
+
throw new AuthenticationRequiredError(NO_CREDENTIALS_MESSAGE);
|
|
848
|
+
}
|
|
849
|
+
authentication = await runtimeScanAuthentication(selected, codexHome, output.auth, provider);
|
|
850
|
+
}
|
|
851
|
+
else if (authentication.method === "api_key" && requiresOpenAiAuth) {
|
|
852
|
+
apiKey = environmentValue(selected, authentication.source)?.trim();
|
|
853
|
+
// Match the SDK's key selection for native and nested plugin workers.
|
|
854
|
+
selected = {
|
|
855
|
+
...selectedScanEnvironment(selected, "chatgpt"),
|
|
856
|
+
CODEX_API_KEY: apiKey,
|
|
857
|
+
};
|
|
858
|
+
if (output.appServer !== undefined) {
|
|
859
|
+
args = [
|
|
860
|
+
...args,
|
|
861
|
+
"--config",
|
|
862
|
+
'cli_auth_credentials_store="ephemeral"',
|
|
863
|
+
];
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
if (output.appServer === undefined) {
|
|
867
|
+
const authConfig = credentialConfig ?? (await readCodexHomeConfig(selected));
|
|
868
|
+
args = [
|
|
869
|
+
...args,
|
|
870
|
+
...CODEX_AUTH_CONFIG_KEYS.flatMap((key) => authConfig[key] === undefined
|
|
871
|
+
? []
|
|
872
|
+
: ["--config", `${key}=${inlineToml(authConfig[key])}`]),
|
|
873
|
+
];
|
|
874
|
+
}
|
|
875
|
+
if (output.appServer === undefined)
|
|
876
|
+
await releaseCredentialHome?.();
|
|
877
|
+
processEnvironment = selected;
|
|
878
|
+
}
|
|
879
|
+
const configuredHome = process.platform === "win32"
|
|
880
|
+
? environmentValue(processEnvironment, "CODEX_HOME")
|
|
881
|
+
: processEnvironment["CODEX_HOME"];
|
|
882
|
+
const environment = { ...processEnvironment };
|
|
883
|
+
for (const name of Object.keys(environment)) {
|
|
884
|
+
if (name.toUpperCase() === "CODEX_HOME")
|
|
885
|
+
delete environment[name];
|
|
886
|
+
}
|
|
887
|
+
if (configuredHome?.trim()) {
|
|
888
|
+
environment["CODEX_HOME"] = resolve(expandHome(configuredHome, processEnvironment));
|
|
889
|
+
}
|
|
890
|
+
const invocation = spawn(executablePathForSpawn(command.command), [...args], {
|
|
891
|
+
env: environment,
|
|
892
|
+
cwd: output?.appServer?.directory ?? parse(process.execPath).root,
|
|
893
|
+
stdio: output === undefined
|
|
894
|
+
? input === undefined
|
|
895
|
+
? "inherit"
|
|
896
|
+
: ["pipe", "inherit", "inherit"]
|
|
897
|
+
: [
|
|
898
|
+
output.appServer !== undefined || input !== undefined
|
|
899
|
+
? "pipe"
|
|
900
|
+
: "ignore",
|
|
901
|
+
"pipe",
|
|
902
|
+
"pipe",
|
|
903
|
+
],
|
|
904
|
+
windowsHide: true,
|
|
887
905
|
});
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
906
|
+
if (input !== undefined) {
|
|
907
|
+
invocation.stdin?.on("error", () => { });
|
|
908
|
+
invocation.stdin?.end(input);
|
|
909
|
+
}
|
|
910
|
+
let requestedSignal = null;
|
|
911
|
+
let forcedTermination;
|
|
912
|
+
let forceStatusCompletion = null;
|
|
913
|
+
let forceCaptureCompletion = null;
|
|
914
|
+
let invocationStatus;
|
|
915
|
+
const requestTermination = (signal) => {
|
|
916
|
+
requestedSignal = signal;
|
|
917
|
+
invocation.kill(signal);
|
|
918
|
+
if (forcedTermination !== undefined)
|
|
919
|
+
return;
|
|
920
|
+
forcedTermination = setTimeout(() => {
|
|
921
|
+
forcedTermination = undefined;
|
|
922
|
+
if (invocation.exitCode === null && invocation.signalCode === null) {
|
|
923
|
+
invocation.kill("SIGKILL");
|
|
924
|
+
}
|
|
925
|
+
forceCaptureCompletion?.();
|
|
926
|
+
invocation.stdout?.destroy();
|
|
927
|
+
invocation.stderr?.destroy();
|
|
928
|
+
forceStatusCompletion?.();
|
|
929
|
+
}, CHILD_TERMINATION_GRACE_MS);
|
|
930
|
+
};
|
|
931
|
+
const onInterrupt = () => {
|
|
932
|
+
requestTermination("SIGINT");
|
|
933
|
+
};
|
|
934
|
+
const onTerminate = () => {
|
|
935
|
+
requestTermination("SIGTERM");
|
|
936
|
+
};
|
|
937
|
+
process.on("SIGINT", onInterrupt);
|
|
938
|
+
process.on("SIGTERM", onTerminate);
|
|
939
|
+
try {
|
|
940
|
+
let diagnostic = "";
|
|
941
|
+
invocation.stderr?.on("data", (chunk) => {
|
|
942
|
+
diagnostic = `${diagnostic}${chunk.toString("utf8")}`.slice(-64 * 1_024);
|
|
943
|
+
});
|
|
944
|
+
const captured = output === undefined || invocation.stdout === null
|
|
945
|
+
? Promise.resolve(undefined)
|
|
946
|
+
: Promise.race([
|
|
947
|
+
readSkillCommandOutput(invocation.stdout, output.appServer === undefined
|
|
948
|
+
? undefined
|
|
949
|
+
: {
|
|
950
|
+
apiKey,
|
|
951
|
+
modelProvider,
|
|
952
|
+
onThreadStarted: releaseCredentialHome,
|
|
953
|
+
directory: output.appServer.directory,
|
|
954
|
+
prompt: output.appServer.prompt,
|
|
955
|
+
threadSource: output.appServer.threadSource,
|
|
956
|
+
input: invocation.stdin,
|
|
957
|
+
sandbox: output.appServer.sandbox,
|
|
958
|
+
externalSandbox: output.appServer.externalSandbox,
|
|
959
|
+
onEvent: output.appServer.onEvent,
|
|
960
|
+
}),
|
|
961
|
+
new Promise((resolve) => {
|
|
962
|
+
forceCaptureCompletion = () => resolve(undefined);
|
|
900
963
|
}),
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
reject(error);
|
|
964
|
+
]);
|
|
965
|
+
invocationStatus = new Promise((resolve, reject) => {
|
|
966
|
+
let completed = false;
|
|
967
|
+
const complete = (code, signal) => {
|
|
968
|
+
if (completed)
|
|
969
|
+
return;
|
|
970
|
+
completed = true;
|
|
971
|
+
forceStatusCompletion = null;
|
|
972
|
+
resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
|
|
973
|
+
? 130
|
|
974
|
+
: requestedSignal === "SIGTERM" || signal === "SIGTERM"
|
|
975
|
+
? 143
|
|
976
|
+
: (code ?? 1));
|
|
977
|
+
};
|
|
978
|
+
forceStatusCompletion = () => complete(null, null);
|
|
979
|
+
invocation.once("error", (error) => {
|
|
980
|
+
if (completed)
|
|
981
|
+
return;
|
|
982
|
+
completed = true;
|
|
983
|
+
forceStatusCompletion = null;
|
|
984
|
+
reject(error);
|
|
985
|
+
});
|
|
986
|
+
invocation.once(output === undefined ? "exit" : "close", complete);
|
|
925
987
|
});
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
status
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
988
|
+
let [status, events] = await Promise.all([invocationStatus, captured]);
|
|
989
|
+
if (events?.sandboxUnavailable && requestedSignal === null) {
|
|
990
|
+
throw new PatchCommandError("SANDBOX_UNAVAILABLE", SANDBOX_UNAVAILABLE_MESSAGE);
|
|
991
|
+
}
|
|
992
|
+
if (status === 0 && output?.appServer !== undefined && events?.error) {
|
|
993
|
+
status = 1;
|
|
994
|
+
}
|
|
995
|
+
if (output === undefined || status === 130 || status === 143)
|
|
996
|
+
return status;
|
|
997
|
+
if (status !== 0) {
|
|
998
|
+
await writeCliOutput(output.stderr, `codex-security: ${skillCommandFailure(output.command, status, events?.error ?? diagnostic, authentication)}\n`);
|
|
999
|
+
return status;
|
|
1000
|
+
}
|
|
1001
|
+
if ((output.appServer !== undefined && events?.completed !== true) ||
|
|
1002
|
+
events?.message === undefined ||
|
|
1003
|
+
events.message.trim().length === 0) {
|
|
1004
|
+
await writeCliOutput(output.stderr, `codex-security: Codex did not return a completed ${output.command} response.\n`);
|
|
1005
|
+
return 2;
|
|
1006
|
+
}
|
|
1007
|
+
await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
|
|
936
1008
|
return status;
|
|
937
1009
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
1010
|
+
catch (error) {
|
|
1011
|
+
invocation.stdout?.destroy();
|
|
1012
|
+
invocation.stderr?.destroy();
|
|
1013
|
+
requestTermination("SIGTERM");
|
|
1014
|
+
await invocationStatus?.catch(() => undefined);
|
|
1015
|
+
throw error;
|
|
1016
|
+
}
|
|
1017
|
+
finally {
|
|
1018
|
+
if (forcedTermination !== undefined)
|
|
1019
|
+
clearTimeout(forcedTermination);
|
|
1020
|
+
forceStatusCompletion = null;
|
|
1021
|
+
forceCaptureCompletion = null;
|
|
1022
|
+
process.off("SIGINT", onInterrupt);
|
|
1023
|
+
process.off("SIGTERM", onTerminate);
|
|
943
1024
|
}
|
|
944
|
-
await writeCliOutput(output.stdout, `${events.message.trimEnd()}\n`);
|
|
945
|
-
return status;
|
|
946
|
-
}
|
|
947
|
-
catch (error) {
|
|
948
|
-
invocation.stdout?.destroy();
|
|
949
|
-
invocation.stderr?.destroy();
|
|
950
|
-
requestTermination("SIGTERM");
|
|
951
|
-
await invocationStatus?.catch(() => undefined);
|
|
952
|
-
throw error;
|
|
953
1025
|
}
|
|
954
1026
|
finally {
|
|
955
|
-
|
|
956
|
-
clearTimeout(forcedTermination);
|
|
957
|
-
forceStatusCompletion = null;
|
|
958
|
-
forceCaptureCompletion = null;
|
|
959
|
-
process.off("SIGINT", onInterrupt);
|
|
960
|
-
process.off("SIGTERM", onTerminate);
|
|
1027
|
+
await releaseCredentialHome?.();
|
|
961
1028
|
}
|
|
962
1029
|
}
|
|
963
1030
|
async function writeCliOutput(output, value) {
|
|
@@ -1015,10 +1082,11 @@ export function exportEnvironment(environment = process.env) {
|
|
|
1015
1082
|
.map((key) => [key, environment[key]])));
|
|
1016
1083
|
}
|
|
1017
1084
|
export async function main(argv = process.argv.slice(2), output = process.stdout, errorOutput = process.stderr, dependencies = DEFAULT_DEPENDENCIES) {
|
|
1018
|
-
argv = defaultListCommand(argv);
|
|
1085
|
+
argv = normalizeScanImportArguments(defaultListCommand(argv));
|
|
1086
|
+
const policyFullOutput = argv[cliCommandIndex(argv)] === "policy" && argv.includes("--full-output");
|
|
1019
1087
|
const positionals = [];
|
|
1020
1088
|
const argumentError = validateCliArguments(argv, positionals);
|
|
1021
|
-
if (argumentError !== undefined) {
|
|
1089
|
+
if (argumentError !== undefined && !policyFullOutput) {
|
|
1022
1090
|
errorOutput.write(`codex-security: ${argumentError}\n`);
|
|
1023
1091
|
return 2;
|
|
1024
1092
|
}
|
|
@@ -1045,6 +1113,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1045
1113
|
let frameworkOutput = "";
|
|
1046
1114
|
let renderedHistory;
|
|
1047
1115
|
let renderedPublication;
|
|
1116
|
+
let renderedPolicy;
|
|
1117
|
+
let renderedPatch;
|
|
1118
|
+
let patchStructuredError = false;
|
|
1119
|
+
const runImport = (options) => runScanImport(options, errorOutput, dependencies);
|
|
1048
1120
|
const history = async (args, select = (value) => value) => {
|
|
1049
1121
|
try {
|
|
1050
1122
|
return await select(await dependencies.runWorkbench(args));
|
|
@@ -1320,26 +1392,68 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1320
1392
|
const scanId = args.scanId ?? (await latestScans(1, "any"))?.[0]?.scanId;
|
|
1321
1393
|
if (scanId === undefined)
|
|
1322
1394
|
return;
|
|
1323
|
-
return await history(["get-scan", "--scan-id", scanId], async (value) =>
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1395
|
+
return await history(["get-scan", "--scan-id", scanId], async (value) => (await readSavedScanLogs(value["scan"], codexSecurityCredentialHome(dependencies.environment))));
|
|
1396
|
+
},
|
|
1397
|
+
})
|
|
1398
|
+
.command("resume", {
|
|
1399
|
+
description: "Resume an interrupted Deep Scan in its original session.",
|
|
1400
|
+
mcp: false,
|
|
1401
|
+
args: z.object({
|
|
1402
|
+
scanId: z.string().min(1).describe("Interrupted Deep Scan identifier."),
|
|
1403
|
+
}),
|
|
1404
|
+
options: z.object({
|
|
1405
|
+
showCost: SHOW_COST_OPTION,
|
|
1406
|
+
verbose: z
|
|
1407
|
+
.boolean()
|
|
1408
|
+
.default(false)
|
|
1409
|
+
.describe("Print scan diagnostics to stderr."),
|
|
1410
|
+
}),
|
|
1411
|
+
output: z.record(z.string(), z.unknown()).optional(),
|
|
1412
|
+
async run({ args, error: incurError, options }) {
|
|
1413
|
+
let scanArguments;
|
|
1414
|
+
try {
|
|
1415
|
+
const saved = await dependencies.runWorkbench([
|
|
1416
|
+
"get-cli-scan-resume",
|
|
1417
|
+
"--scan-id",
|
|
1418
|
+
args.scanId,
|
|
1419
|
+
]);
|
|
1420
|
+
if (typeof saved["scanId"] !== "string" ||
|
|
1421
|
+
typeof saved["scanDir"] !== "string") {
|
|
1422
|
+
throw new CodexSecurityError("The workbench returned invalid scan resume context.");
|
|
1423
|
+
}
|
|
1424
|
+
scanArguments = await prepareScanArgumentsFromRecipe(saved["recipe"], saved["scanId"], {
|
|
1425
|
+
scanPrompt: typeof saved["userContext"] === "string"
|
|
1426
|
+
? saved["userContext"]
|
|
1427
|
+
: undefined,
|
|
1428
|
+
}, dependencies.currentDirectory());
|
|
1429
|
+
scanArguments.resumeScanId = saved["scanId"];
|
|
1430
|
+
scanArguments.outputDir = resolveCliPath(dependencies.currentDirectory(), saved["scanDir"]);
|
|
1431
|
+
scanArguments.parentScanId = undefined;
|
|
1432
|
+
// Resume uses the installed engine with the saved recipe and checkpoints.
|
|
1433
|
+
scanArguments.expectedPluginVersion = undefined;
|
|
1434
|
+
scanArguments.verbose = options.verbose;
|
|
1435
|
+
scanArguments.showCost = options.showCost;
|
|
1436
|
+
}
|
|
1437
|
+
catch (error) {
|
|
1438
|
+
const message = errorMessage(error);
|
|
1439
|
+
errorOutput.write(`codex-security: ${message}\n`);
|
|
1440
|
+
exitCode = 2;
|
|
1441
|
+
return incurError({
|
|
1442
|
+
code: "SCAN_RESUME_UNAVAILABLE",
|
|
1443
|
+
message,
|
|
1444
|
+
exitCode,
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
const outcome = await runScan(scanArguments, errorOutput, dependencies);
|
|
1448
|
+
exitCode = outcome.exitCode;
|
|
1449
|
+
if (outcome.error !== undefined) {
|
|
1450
|
+
return incurError({
|
|
1451
|
+
code: "SCAN_FAILED",
|
|
1452
|
+
message: outcome.error,
|
|
1453
|
+
exitCode,
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
return outcome.data;
|
|
1343
1457
|
},
|
|
1344
1458
|
})
|
|
1345
1459
|
.command("rerun", {
|
|
@@ -1354,6 +1468,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1354
1468
|
.describe("Saved scan identifier (default: latest completed scan)."),
|
|
1355
1469
|
}),
|
|
1356
1470
|
options: z.object({
|
|
1471
|
+
showCost: SHOW_COST_OPTION,
|
|
1472
|
+
scanPromptFile: optionValue("--scan-prompt-file")
|
|
1473
|
+
.optional()
|
|
1474
|
+
.describe("Supply additional scan instructions; required when the saved scan used them."),
|
|
1357
1475
|
validationPromptFile: optionValue("--validation-prompt-file")
|
|
1358
1476
|
.optional()
|
|
1359
1477
|
.describe("Use FILE for custom validation; required when rerunning a custom-validation scan."),
|
|
@@ -1374,8 +1492,50 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
1374
1492
|
"--scan-id",
|
|
1375
1493
|
scanId,
|
|
1376
1494
|
]);
|
|
1377
|
-
|
|
1495
|
+
if (recipe !== undefined &&
|
|
1496
|
+
isJsonObject(recipe) &&
|
|
1497
|
+
recipe["import"] !== undefined &&
|
|
1498
|
+
isJsonObject(recipe["import"])) {
|
|
1499
|
+
if (options.validationPromptFile !== undefined ||
|
|
1500
|
+
options.scanPromptFile !== undefined) {
|
|
1501
|
+
const option = options.validationPromptFile !== undefined
|
|
1502
|
+
? "--validation-prompt-file"
|
|
1503
|
+
: "--scan-prompt-file";
|
|
1504
|
+
throw new CodexSecurityError(`${option} is not supported when rerunning an imported scan; imports do not perform security analysis.`);
|
|
1505
|
+
}
|
|
1506
|
+
const imported = recipe["import"];
|
|
1507
|
+
const sourcePath = imported["sourcePath"];
|
|
1508
|
+
const format = imported["format"];
|
|
1509
|
+
if (typeof sourcePath !== "string" ||
|
|
1510
|
+
sourcePath.length === 0 ||
|
|
1511
|
+
(format !== "csv" && format !== "json")) {
|
|
1512
|
+
throw new CodexSecurityError("The saved scan recipe contains invalid import settings.");
|
|
1513
|
+
}
|
|
1514
|
+
const outcome = await runImport({
|
|
1515
|
+
sourcePath,
|
|
1516
|
+
format,
|
|
1517
|
+
parentScanId: scanId,
|
|
1518
|
+
});
|
|
1519
|
+
exitCode = outcome.exitCode;
|
|
1520
|
+
if (outcome.error !== undefined) {
|
|
1521
|
+
return incurError({
|
|
1522
|
+
code: "SCAN_IMPORT_FAILED",
|
|
1523
|
+
message: outcome.error,
|
|
1524
|
+
exitCode,
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
return outcome.data;
|
|
1528
|
+
}
|
|
1529
|
+
scanArguments = await prepareScanArgumentsFromRecipe(recipe, scanId, {
|
|
1530
|
+
scanPromptFile: options.scanPromptFile === undefined
|
|
1531
|
+
? undefined
|
|
1532
|
+
: resolveCliPath(dependencies.currentDirectory(), options.scanPromptFile),
|
|
1533
|
+
validationPromptFile: options.validationPromptFile === undefined
|
|
1534
|
+
? undefined
|
|
1535
|
+
: resolveCliPath(dependencies.currentDirectory(), options.validationPromptFile),
|
|
1536
|
+
}, dependencies.currentDirectory());
|
|
1378
1537
|
scanArguments.verbose = options.verbose;
|
|
1538
|
+
scanArguments.showCost = options.showCost;
|
|
1379
1539
|
}
|
|
1380
1540
|
catch (error) {
|
|
1381
1541
|
const message = errorMessage(error);
|
|
@@ -2051,17 +2211,175 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2051
2211
|
},
|
|
2052
2212
|
});
|
|
2053
2213
|
const cli = Cli.create("codex-security", {
|
|
2054
|
-
description: "
|
|
2214
|
+
description: "Draft security policies; run, import, validate, patch, verify fixes, export, and publish Codex Security findings.",
|
|
2055
2215
|
version: VERSION,
|
|
2056
2216
|
mcp: {
|
|
2057
2217
|
command: "npx --yes @openai/codex-security --mcp",
|
|
2218
|
+
tools: { discovery: "direct" },
|
|
2058
2219
|
instructions: "Use info for read-only SDK metadata. Scans and other state-changing commands are CLI-only because the MCP transport cannot cancel active commands.",
|
|
2059
2220
|
},
|
|
2221
|
+
})
|
|
2222
|
+
.command("policy", {
|
|
2223
|
+
description: "Draft SECURITY.md guidance for future scans and owner review.",
|
|
2224
|
+
destructive: true,
|
|
2225
|
+
mcp: false,
|
|
2226
|
+
args: z.object({
|
|
2227
|
+
repository: z
|
|
2228
|
+
.string()
|
|
2229
|
+
.optional()
|
|
2230
|
+
.describe("Repository or component directory (default: current directory)."),
|
|
2231
|
+
}),
|
|
2232
|
+
options: z.object({
|
|
2233
|
+
path: optionValue("--path")
|
|
2234
|
+
.optional()
|
|
2235
|
+
.describe("Generate SECURITY.md for this repository-relative component directory."),
|
|
2236
|
+
knowledgeBase: z
|
|
2237
|
+
.array(optionValue("--knowledge-base"))
|
|
2238
|
+
.default([])
|
|
2239
|
+
.describe("Add architecture or security-context files; repeat for multiple paths."),
|
|
2240
|
+
outputDir: optionValue("--output-dir")
|
|
2241
|
+
.optional()
|
|
2242
|
+
.describe("Private artifact directory outside the repository (default: Codex Security state)."),
|
|
2243
|
+
headless: z
|
|
2244
|
+
.boolean()
|
|
2245
|
+
.default(false)
|
|
2246
|
+
.describe("Skip owner questions and authentication prompts."),
|
|
2247
|
+
dryRun: z
|
|
2248
|
+
.boolean()
|
|
2249
|
+
.default(false)
|
|
2250
|
+
.describe("Validate local generation inputs without starting Codex."),
|
|
2251
|
+
auth: z
|
|
2252
|
+
.enum(["auto", "chatgpt", "api-key"])
|
|
2253
|
+
.default("auto")
|
|
2254
|
+
.describe("Select ChatGPT, API-key, or automatic authentication."),
|
|
2255
|
+
model: optionValue("--model")
|
|
2256
|
+
.optional()
|
|
2257
|
+
.describe(`Model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
|
|
2258
|
+
effort: effortOption(),
|
|
2259
|
+
provider: PROVIDER_OPTION.describe("Inference provider for policy generation."),
|
|
2260
|
+
maxCost: z
|
|
2261
|
+
.number()
|
|
2262
|
+
.positive()
|
|
2263
|
+
.optional()
|
|
2264
|
+
.describe("Stop when estimated total USD cost across all three stages exceeds AMOUNT."),
|
|
2265
|
+
pluginPath: optionValue("--plugin-path")
|
|
2266
|
+
.optional()
|
|
2267
|
+
.describe(PLUGIN_PATH_DESCRIPTION),
|
|
2268
|
+
python: optionValue("--python")
|
|
2269
|
+
.optional()
|
|
2270
|
+
.describe(PYTHON_PATH_DESCRIPTION),
|
|
2271
|
+
codex: z
|
|
2272
|
+
.array(optionValue("--codex"))
|
|
2273
|
+
.default([])
|
|
2274
|
+
.describe(CODEX_OVERRIDE_DESCRIPTION),
|
|
2275
|
+
}),
|
|
2276
|
+
examples: [
|
|
2277
|
+
{ args: { repository: "." } },
|
|
2278
|
+
{ args: { repository: "." }, options: { path: "services/api" } },
|
|
2279
|
+
],
|
|
2280
|
+
hint: "Save a draft for review:\n" +
|
|
2281
|
+
" codex-security policy . --headless --output-dir /path/outside/repository/policy --json",
|
|
2282
|
+
output: z
|
|
2283
|
+
.union([z.record(z.string(), z.unknown()), z.string()])
|
|
2284
|
+
.optional(),
|
|
2285
|
+
async run({ args, error: incurError, options, format, formatExplicit }) {
|
|
2286
|
+
const outputOptions = argv.filter((argument) => OUTPUT_OPTION.test(argument));
|
|
2287
|
+
const explicitOutput = formatExplicit || outputOptions.length > 0;
|
|
2288
|
+
const transformOutput = outputOptions.some((argument) => !argument.startsWith("--format"));
|
|
2289
|
+
const filterOutput = outputOptions.some((argument) => argument.startsWith("--filter-output"));
|
|
2290
|
+
const fail = (message, failureExitCode) => {
|
|
2291
|
+
exitCode = failureExitCode;
|
|
2292
|
+
return incurError({
|
|
2293
|
+
code: "POLICY_FAILED",
|
|
2294
|
+
message,
|
|
2295
|
+
exitCode: failureExitCode,
|
|
2296
|
+
});
|
|
2297
|
+
};
|
|
2298
|
+
try {
|
|
2299
|
+
if (argumentError !== undefined)
|
|
2300
|
+
return fail(argumentError, 2);
|
|
2301
|
+
const directory = dependencies.currentDirectory();
|
|
2302
|
+
const outcome = await withTerminalErrorsHandled(errorOutput, () => runPolicyCommand({
|
|
2303
|
+
repository: resolveCliPath(directory, args.repository ?? "."),
|
|
2304
|
+
config: {
|
|
2305
|
+
pluginPath: options.pluginPath,
|
|
2306
|
+
pythonPath: options.python,
|
|
2307
|
+
codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
|
|
2308
|
+
},
|
|
2309
|
+
generation: {
|
|
2310
|
+
auth: options.auth,
|
|
2311
|
+
path: options.path,
|
|
2312
|
+
knowledgeBasePaths: options.knowledgeBase.map((path) => resolveCliPath(directory, path)),
|
|
2313
|
+
outputDir: options.outputDir === undefined
|
|
2314
|
+
? undefined
|
|
2315
|
+
: resolveCliPath(directory, options.outputDir),
|
|
2316
|
+
maxCostUsd: options.maxCost,
|
|
2317
|
+
},
|
|
2318
|
+
headless: options.headless || explicitOutput,
|
|
2319
|
+
dryRun: options.dryRun,
|
|
2320
|
+
format,
|
|
2321
|
+
explicitOutput,
|
|
2322
|
+
}, {
|
|
2323
|
+
createSecurity: dependencies.createPolicySecurity ??
|
|
2324
|
+
((config) => createSecurityInternal(config, { surface: "cli" })),
|
|
2325
|
+
chooseAuthentication: (config, auth, signal) => chooseInteractiveAuthentication({
|
|
2326
|
+
auth,
|
|
2327
|
+
provider: scanModelProvider({
|
|
2328
|
+
...DEFAULT_CODEX_CONFIG,
|
|
2329
|
+
...config.codexOverrides,
|
|
2330
|
+
}),
|
|
2331
|
+
command: "policy",
|
|
2332
|
+
signal,
|
|
2333
|
+
}, errorOutput, dependencies),
|
|
2334
|
+
prompt: dependencies.policyPrompt ??
|
|
2335
|
+
createBulkScanDiscoveryDependencies({
|
|
2336
|
+
output: errorOutput,
|
|
2337
|
+
now: dependencies.now,
|
|
2338
|
+
currentDirectory: dependencies.currentDirectory,
|
|
2339
|
+
}).prompt,
|
|
2340
|
+
environment: dependencies.environment,
|
|
2341
|
+
errorOutput,
|
|
2342
|
+
now: dependencies.now,
|
|
2343
|
+
addSignalListener: dependencies.addSignalListener,
|
|
2344
|
+
removeSignalListener: dependencies.removeSignalListener,
|
|
2345
|
+
forceExit: dependencies.forceExit,
|
|
2346
|
+
}));
|
|
2347
|
+
exitCode = outcome.exitCode;
|
|
2348
|
+
if (exitCode !== 0) {
|
|
2349
|
+
return fail(outcome.error ?? "Policy command failed.", exitCode);
|
|
2350
|
+
}
|
|
2351
|
+
if (format === "md" &&
|
|
2352
|
+
outcome.markdown !== undefined &&
|
|
2353
|
+
!filterOutput) {
|
|
2354
|
+
if (!transformOutput)
|
|
2355
|
+
renderedPolicy = outcome.markdown;
|
|
2356
|
+
return outcome.markdown;
|
|
2357
|
+
}
|
|
2358
|
+
return format === "toon" && !explicitOutput && !options.dryRun
|
|
2359
|
+
? undefined
|
|
2360
|
+
: format === "toon"
|
|
2361
|
+
? policyDisplayData(outcome.data)
|
|
2362
|
+
: outcome.data;
|
|
2363
|
+
}
|
|
2364
|
+
catch (error) {
|
|
2365
|
+
const message = safeErrorMessage(error);
|
|
2366
|
+
try {
|
|
2367
|
+
errorOutput.write(`codex-security: ${message}\n`);
|
|
2368
|
+
}
|
|
2369
|
+
catch { }
|
|
2370
|
+
return fail(message, 2);
|
|
2371
|
+
}
|
|
2372
|
+
},
|
|
2060
2373
|
})
|
|
2061
2374
|
.command("scan", {
|
|
2062
2375
|
description: "Run a Codex Security scan.",
|
|
2376
|
+
hint: "Import existing findings without security analysis:\n" +
|
|
2377
|
+
" codex-security scan import --csv findings.csv\n" +
|
|
2378
|
+
" codex-security scan import --json findings.json\n" +
|
|
2379
|
+
"Use ./import to scan a repository named import.",
|
|
2063
2380
|
destructive: true,
|
|
2064
2381
|
mcp: false,
|
|
2382
|
+
alias: { config: "c" },
|
|
2065
2383
|
args: z.object({
|
|
2066
2384
|
repository: z
|
|
2067
2385
|
.string()
|
|
@@ -2070,13 +2388,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2070
2388
|
}),
|
|
2071
2389
|
options: z
|
|
2072
2390
|
.object({
|
|
2391
|
+
config: PROJECT_CONFIG_OPTION,
|
|
2073
2392
|
workflowId: optionValue("--workflow-id")
|
|
2074
2393
|
.optional()
|
|
2075
2394
|
.describe("Reuse completed work in the named local findings workflow."),
|
|
2076
|
-
auth:
|
|
2077
|
-
.enum(SCAN_AUTH_MODES)
|
|
2078
|
-
.default("auto")
|
|
2079
|
-
.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
|
|
2395
|
+
auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication (default: auto)."),
|
|
2080
2396
|
verbose: z
|
|
2081
2397
|
.boolean()
|
|
2082
2398
|
.default(false)
|
|
@@ -2086,11 +2402,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2086
2402
|
.describe("Stable hashed end-user ID for this scan's model requests (1–64 characters)."),
|
|
2087
2403
|
path: z
|
|
2088
2404
|
.array(optionValue("--path"))
|
|
2089
|
-
.
|
|
2405
|
+
.optional()
|
|
2406
|
+
.meta({ default: [] })
|
|
2090
2407
|
.describe("Scan only PATH; repeat for multiple repository-relative paths."),
|
|
2091
2408
|
knowledgeBase: z
|
|
2092
2409
|
.array(optionValue("--knowledge-base"))
|
|
2093
|
-
.
|
|
2410
|
+
.optional()
|
|
2411
|
+
.meta({ default: [] })
|
|
2094
2412
|
.describe("Add security-context files or directories; repeat for multiple paths."),
|
|
2095
2413
|
scanPromptFile: optionValue("--scan-prompt-file")
|
|
2096
2414
|
.optional()
|
|
@@ -2106,7 +2424,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2106
2424
|
.describe("Scan committed Git changes from BASE to --head."),
|
|
2107
2425
|
workingTree: z
|
|
2108
2426
|
.boolean()
|
|
2109
|
-
.
|
|
2427
|
+
.optional()
|
|
2428
|
+
.meta({ default: false })
|
|
2110
2429
|
.describe("Scan staged and unstaged changes against --base."),
|
|
2111
2430
|
head: optionValue("--head")
|
|
2112
2431
|
.optional()
|
|
@@ -2114,10 +2433,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2114
2433
|
base: optionValue("--base")
|
|
2115
2434
|
.optional()
|
|
2116
2435
|
.describe("Git base ref for --working-tree (default: HEAD)."),
|
|
2117
|
-
mode:
|
|
2118
|
-
.enum(["standard", "deep"])
|
|
2119
|
-
.default("standard")
|
|
2120
|
-
.describe("Scan mode; deep supports repository and path targets."),
|
|
2436
|
+
mode: ScanSettingsSchema.shape.mode.describe("Scan mode (default: standard); deep supports repository and path targets."),
|
|
2121
2437
|
...DEEP_SCAN_OPTION_SCHEMAS,
|
|
2122
2438
|
model: optionValue("--model")
|
|
2123
2439
|
.optional()
|
|
@@ -2141,10 +2457,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2141
2457
|
.array(optionValue("--codex"))
|
|
2142
2458
|
.default([])
|
|
2143
2459
|
.describe(CODEX_OVERRIDE_DESCRIPTION),
|
|
2144
|
-
failOnSeverity:
|
|
2145
|
-
.enum(REPORTABLE_SEVERITIES)
|
|
2146
|
-
.optional()
|
|
2147
|
-
.describe("Exit 1 for findings at or above LEVEL."),
|
|
2460
|
+
failOnSeverity: FailureSeveritySchema.optional().describe("Exit 1 for findings at or above LEVEL."),
|
|
2148
2461
|
patch: z
|
|
2149
2462
|
.boolean()
|
|
2150
2463
|
.default(false)
|
|
@@ -2154,11 +2467,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2154
2467
|
.optional()
|
|
2155
2468
|
.describe("Patch findings at or above LEVEL; requires --patch."),
|
|
2156
2469
|
createPr: CREATE_PR_OPTION,
|
|
2157
|
-
maxCost:
|
|
2158
|
-
|
|
2159
|
-
.positive()
|
|
2160
|
-
.optional()
|
|
2161
|
-
.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
|
|
2470
|
+
maxCost: ScanSettingsSchema.shape.maxCostUsd.describe("Stop above AMOUNT in estimated USD; the dashboard offers increases near the limit."),
|
|
2471
|
+
showCost: SHOW_COST_OPTION,
|
|
2162
2472
|
headless: z
|
|
2163
2473
|
.boolean()
|
|
2164
2474
|
.default(false)
|
|
@@ -2172,17 +2482,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2172
2482
|
.default(false)
|
|
2173
2483
|
.describe("Save synthetic Standard scan findings without calling an LLM."),
|
|
2174
2484
|
})
|
|
2175
|
-
.refine((options) => Number(options.path.length > 0) +
|
|
2176
|
-
Number(options.diff !== undefined) +
|
|
2177
|
-
Number(options.workingTree) <=
|
|
2178
|
-
1, {
|
|
2179
|
-
message: "--path, --diff, and --working-tree are mutually exclusive.",
|
|
2180
|
-
})
|
|
2181
|
-
.refine((options) => options.head === undefined || options.diff !== undefined, { message: "--head requires --diff." })
|
|
2182
|
-
.refine((options) => options.base === undefined || options.workingTree, {
|
|
2183
|
-
message: "--base requires --working-tree.",
|
|
2184
|
-
})
|
|
2185
|
-
.refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." })
|
|
2186
2485
|
.refine((options) => options.patchSeverity === undefined || options.patch, {
|
|
2187
2486
|
message: "--patch-severity requires --patch.",
|
|
2188
2487
|
})
|
|
@@ -2194,15 +2493,13 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2194
2493
|
})
|
|
2195
2494
|
.refine((options) => !options.mock || (!options.dryRun && !options.patch), {
|
|
2196
2495
|
message: "--mock cannot be combined with --dry-run or --patch.",
|
|
2197
|
-
})
|
|
2198
|
-
.refine((options) => options.mode === "deep" ||
|
|
2199
|
-
(options.workers === undefined &&
|
|
2200
|
-
options.subagents === undefined &&
|
|
2201
|
-
options.stopAfterNoNew === undefined &&
|
|
2202
|
-
options.maxDiscoveryRuns === undefined &&
|
|
2203
|
-
options.maxTimeHours === undefined), { message: "Deep scan settings require --mode deep." }),
|
|
2496
|
+
}),
|
|
2204
2497
|
examples: [
|
|
2205
2498
|
{ args: { repository: "." } },
|
|
2499
|
+
{
|
|
2500
|
+
args: { repository: "." },
|
|
2501
|
+
options: { config: "codex-security.yaml" },
|
|
2502
|
+
},
|
|
2206
2503
|
{ args: { repository: "." }, options: { model: "gpt-5.6-terra" } },
|
|
2207
2504
|
{
|
|
2208
2505
|
args: { repository: "." },
|
|
@@ -2226,44 +2523,63 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2226
2523
|
exitCode = 2;
|
|
2227
2524
|
return;
|
|
2228
2525
|
}
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2526
|
+
let outcome;
|
|
2527
|
+
try {
|
|
2528
|
+
const directory = dependencies.currentDirectory();
|
|
2529
|
+
const project = await selectedProjectConfig(options.config, dependencies);
|
|
2530
|
+
const scope = resolveCliScope(project?.input.scan?.scope, {
|
|
2531
|
+
paths: options.path,
|
|
2532
|
+
diff: options.diff,
|
|
2533
|
+
workingTree: options.workingTree,
|
|
2534
|
+
head: options.head,
|
|
2535
|
+
base: options.base,
|
|
2536
|
+
});
|
|
2537
|
+
const { config, options: settings, projectConfig: provenance, } = resolveScanSettings(project, {
|
|
2538
|
+
auth: options.auth,
|
|
2539
|
+
target: scope.target,
|
|
2540
|
+
knowledgeBasePaths: options.knowledgeBase,
|
|
2541
|
+
scanPromptFile: options.scanPromptFile,
|
|
2542
|
+
validationPromptFile: options.validationPromptFile,
|
|
2543
|
+
postScanPromptFile: options.postScanPromptFile,
|
|
2544
|
+
mode: options.mode,
|
|
2545
|
+
workers: options.workers,
|
|
2546
|
+
subagents: options.subagents,
|
|
2547
|
+
stopAfterNoNew: options.stopAfterNoNew,
|
|
2548
|
+
maxDiscoveryRuns: options.maxDiscoveryRuns,
|
|
2549
|
+
maxTimeHours: options.maxTimeHours,
|
|
2550
|
+
outputDir: options.outputDir,
|
|
2551
|
+
failureSeverity: options.failOnSeverity,
|
|
2552
|
+
maxCostUsd: options.maxCost,
|
|
2553
|
+
codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
|
|
2554
|
+
}, directory, scope.sources);
|
|
2555
|
+
if (options.archiveExisting && settings.outputDir === undefined) {
|
|
2556
|
+
throw new CodexSecurityError("--archive-existing requires --output-dir.");
|
|
2557
|
+
}
|
|
2558
|
+
outcome = await runScan({
|
|
2559
|
+
...settings,
|
|
2560
|
+
codexOverrides: config.codexOverrides,
|
|
2561
|
+
projectConfig: provenance,
|
|
2562
|
+
workflowId: options.workflowId,
|
|
2563
|
+
safetyIdentifier: options.safetyIdentifier,
|
|
2564
|
+
verbose: options.verbose,
|
|
2565
|
+
repository: args.repository,
|
|
2566
|
+
archiveExisting: options.archiveExisting,
|
|
2567
|
+
pluginPath: options.pluginPath,
|
|
2568
|
+
pythonPath: options.python,
|
|
2569
|
+
patch: options.patch,
|
|
2570
|
+
patchSeverity: options.patchSeverity,
|
|
2571
|
+
createPr: options.createPr,
|
|
2572
|
+
showCost: options.showCost,
|
|
2573
|
+
headless: options.headless,
|
|
2574
|
+
dryRun: options.dryRun,
|
|
2575
|
+
mock: options.mock,
|
|
2576
|
+
}, errorOutput, dependencies, format !== "json" && format !== "jsonl");
|
|
2577
|
+
}
|
|
2578
|
+
catch (error) {
|
|
2579
|
+
const message = errorMessage(error);
|
|
2580
|
+
errorOutput.write(`${message}\n`);
|
|
2581
|
+
outcome = { exitCode: 2, error: message };
|
|
2582
|
+
}
|
|
2267
2583
|
exitCode = outcome.exitCode;
|
|
2268
2584
|
if (outcome.error !== undefined) {
|
|
2269
2585
|
return incurError({
|
|
@@ -2429,6 +2745,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2429
2745
|
destructive: true,
|
|
2430
2746
|
mcp: false,
|
|
2431
2747
|
options: z.object({
|
|
2748
|
+
concurrency: z
|
|
2749
|
+
.number()
|
|
2750
|
+
.int()
|
|
2751
|
+
.positive()
|
|
2752
|
+
.default(DEFAULT_DEDUPE_CONCURRENCY)
|
|
2753
|
+
.describe("Maximum concurrent dedupe jobs across Luna and Sol; use 1 for serial execution."),
|
|
2432
2754
|
workflowId: optionValue("--workflow-id")
|
|
2433
2755
|
.optional()
|
|
2434
2756
|
.describe("Resume the named local findings workflow; reuses its saved scan."),
|
|
@@ -2468,6 +2790,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2468
2790
|
throw new CodexSecurityError("Deduplication requires --scan or --workflow-id.");
|
|
2469
2791
|
return await (dependencies.deduplicateScan ?? deduplicateScanInternal)(scanId, {
|
|
2470
2792
|
findingsUrl: options.findingsUrl,
|
|
2793
|
+
concurrency: options.concurrency,
|
|
2471
2794
|
...(options.workflowId === undefined
|
|
2472
2795
|
? {}
|
|
2473
2796
|
: { workflowId: options.workflowId }),
|
|
@@ -2498,6 +2821,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2498
2821
|
description: "Run standard scans for project components and combine the results.",
|
|
2499
2822
|
destructive: true,
|
|
2500
2823
|
mcp: false,
|
|
2824
|
+
alias: { config: "c" },
|
|
2501
2825
|
args: z.object({
|
|
2502
2826
|
repository: z
|
|
2503
2827
|
.string()
|
|
@@ -2507,10 +2831,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2507
2831
|
}),
|
|
2508
2832
|
options: z
|
|
2509
2833
|
.object({
|
|
2510
|
-
|
|
2511
|
-
|
|
2512
|
-
.default("auto")
|
|
2513
|
-
.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
|
|
2834
|
+
config: PROJECT_CONFIG_OPTION,
|
|
2835
|
+
auth: ScanSettingsSchema.shape.auth.describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
|
|
2514
2836
|
component: z
|
|
2515
2837
|
.array(optionValue("--component"))
|
|
2516
2838
|
.default([])
|
|
@@ -2530,16 +2852,19 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2530
2852
|
.boolean()
|
|
2531
2853
|
.default(false)
|
|
2532
2854
|
.describe("Print status lines instead of the interactive dashboard."),
|
|
2533
|
-
outputDir: optionValue("--output-dir")
|
|
2855
|
+
outputDir: optionValue("--output-dir")
|
|
2856
|
+
.optional()
|
|
2857
|
+
.describe("Empty results directory outside the repository."),
|
|
2534
2858
|
workers: z
|
|
2535
2859
|
.number()
|
|
2536
2860
|
.int()
|
|
2537
2861
|
.positive()
|
|
2538
2862
|
.default(4)
|
|
2539
|
-
.describe("Concurrent
|
|
2863
|
+
.describe("Concurrent component scans; deep workers are configured per scan."),
|
|
2540
2864
|
knowledgeBase: z
|
|
2541
2865
|
.array(optionValue("--knowledge-base"))
|
|
2542
|
-
.
|
|
2866
|
+
.optional()
|
|
2867
|
+
.meta({ default: [] })
|
|
2543
2868
|
.describe("Read shared security docs for every component."),
|
|
2544
2869
|
scanPromptFile: optionValue("--scan-prompt-file")
|
|
2545
2870
|
.optional()
|
|
@@ -2557,6 +2882,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2557
2882
|
.positive()
|
|
2558
2883
|
.optional()
|
|
2559
2884
|
.describe("Stop each component scan if estimated USD cost exceeds AMOUNT."),
|
|
2885
|
+
showCost: SHOW_COST_OPTION,
|
|
2560
2886
|
pluginPath: optionValue("--plugin-path")
|
|
2561
2887
|
.optional()
|
|
2562
2888
|
.describe(PLUGIN_PATH_DESCRIPTION),
|
|
@@ -2597,10 +2923,23 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2597
2923
|
try {
|
|
2598
2924
|
const directory = dependencies.currentDirectory();
|
|
2599
2925
|
const repository = resolveCliPath(directory, args.repository ?? ".");
|
|
2926
|
+
const project = await selectedProjectConfig(options.config, dependencies);
|
|
2927
|
+
const resolved = resolveScanSettings(project, {
|
|
2928
|
+
auth: options.auth,
|
|
2929
|
+
outputDir: options.outputDir,
|
|
2930
|
+
knowledgeBasePaths: options.knowledgeBase,
|
|
2931
|
+
scanPromptFile: options.scanPromptFile,
|
|
2932
|
+
postScanPromptFile: options.postScanPromptFile,
|
|
2933
|
+
maxCostUsd: options.maxCost,
|
|
2934
|
+
codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex),
|
|
2935
|
+
}, directory);
|
|
2936
|
+
const settings = resolved.options;
|
|
2937
|
+
if (settings.outputDir === undefined)
|
|
2938
|
+
throw new ConfigurationError("--output-dir or output.directory is required for component scans.");
|
|
2600
2939
|
const config = {
|
|
2940
|
+
...resolved.config,
|
|
2601
2941
|
pluginPath: options.pluginPath,
|
|
2602
2942
|
pythonPath: options.python,
|
|
2603
|
-
codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
|
|
2604
2943
|
};
|
|
2605
2944
|
const components = options.componentsFile === undefined
|
|
2606
2945
|
? options.component.map((path) => ({ name: path, paths: [path] }))
|
|
@@ -2614,7 +2953,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2614
2953
|
repository,
|
|
2615
2954
|
presentation: "components",
|
|
2616
2955
|
model: scanModelConfiguration(await mergedCodexConfig(config)),
|
|
2617
|
-
|
|
2956
|
+
mode: settings.mode,
|
|
2957
|
+
maxCostUsd: settings.maxCostUsd,
|
|
2958
|
+
showCost: options.showCost,
|
|
2618
2959
|
clock: dependencies,
|
|
2619
2960
|
color: dependencies.environment["NO_COLOR"] === undefined,
|
|
2620
2961
|
sanitize: safeErrorMessage,
|
|
@@ -2635,18 +2976,14 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2635
2976
|
}
|
|
2636
2977
|
const result = await runComponentScans({
|
|
2637
2978
|
repository,
|
|
2638
|
-
outputDir:
|
|
2979
|
+
outputDir: settings.outputDir,
|
|
2639
2980
|
...(options.auto ? { auto: true } : { components }),
|
|
2640
2981
|
planOnly: options.planOnly,
|
|
2641
2982
|
workers: options.workers,
|
|
2642
2983
|
config,
|
|
2643
2984
|
scanOptions: {
|
|
2644
|
-
|
|
2645
|
-
|
|
2646
|
-
...(await readPromptFiles(directory, options.scanPromptFile, options.postScanPromptFile, repository)),
|
|
2647
|
-
...(options.maxCost === undefined
|
|
2648
|
-
? {}
|
|
2649
|
-
: { maxCostUsd: options.maxCost }),
|
|
2985
|
+
...settings,
|
|
2986
|
+
...(await resolveScanPrompts(settings, repository, directory)),
|
|
2650
2987
|
},
|
|
2651
2988
|
createSecurity: dependencies.createSecurity,
|
|
2652
2989
|
planComponents: dependencies.planComponents,
|
|
@@ -2660,7 +2997,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2660
2997
|
? (event) => {
|
|
2661
2998
|
const componentName = componentNames.get(event.componentId) ??
|
|
2662
2999
|
event.componentId;
|
|
2663
|
-
const line = componentScanEventLine(componentName, event);
|
|
3000
|
+
const line = componentScanEventLine(componentName, event, options.showCost || settings.maxCostUsd !== undefined);
|
|
2664
3001
|
if (line !== null)
|
|
2665
3002
|
errorOutput.write(line);
|
|
2666
3003
|
}
|
|
@@ -2693,7 +3030,9 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2693
3030
|
result.incomplete ||
|
|
2694
3031
|
result.deduplication?.status === "incomplete"
|
|
2695
3032
|
? 2
|
|
2696
|
-
:
|
|
3033
|
+
: result.policyFailed
|
|
3034
|
+
? 1
|
|
3035
|
+
: 0);
|
|
2697
3036
|
return { ...result };
|
|
2698
3037
|
}
|
|
2699
3038
|
catch (error) {
|
|
@@ -2712,6 +3051,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2712
3051
|
description: "Discover repositories and run resumable bulk security scans.",
|
|
2713
3052
|
destructive: true,
|
|
2714
3053
|
mcp: false,
|
|
3054
|
+
alias: { config: "c" },
|
|
2715
3055
|
args: z.object({
|
|
2716
3056
|
input: z
|
|
2717
3057
|
.string()
|
|
@@ -2720,6 +3060,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2720
3060
|
.describe("CSV repository list; omit to discover repositories interactively."),
|
|
2721
3061
|
}),
|
|
2722
3062
|
options: z.object({
|
|
3063
|
+
config: PROJECT_CONFIG_OPTION,
|
|
3064
|
+
recover: z
|
|
3065
|
+
.boolean()
|
|
3066
|
+
.default(false)
|
|
3067
|
+
.describe("Recover failed or interrupted attempts in an existing campaign, preserving their artifacts and checkouts."),
|
|
2723
3068
|
outputDir: z
|
|
2724
3069
|
.string()
|
|
2725
3070
|
.min(1, "--output-dir must not be empty.")
|
|
@@ -2727,7 +3072,8 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2727
3072
|
.describe("Resumable results directory; required with a repository CSV."),
|
|
2728
3073
|
knowledgeBase: z
|
|
2729
3074
|
.array(optionValue("--knowledge-base"))
|
|
2730
|
-
.
|
|
3075
|
+
.optional()
|
|
3076
|
+
.meta({ default: [] })
|
|
2731
3077
|
.describe("Read shared security docs for every repository."),
|
|
2732
3078
|
workers: z
|
|
2733
3079
|
.number()
|
|
@@ -2735,10 +3081,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2735
3081
|
.positive()
|
|
2736
3082
|
.default(4)
|
|
2737
3083
|
.describe("Concurrent repository scans. Per-scan Codex workers are separate."),
|
|
2738
|
-
mode:
|
|
2739
|
-
.enum(["standard", "deep"])
|
|
2740
|
-
.default("standard")
|
|
2741
|
-
.describe("Default scan mode for repositories without a CSV mode."),
|
|
3084
|
+
mode: ScanSettingsSchema.shape.mode.describe("Default scan mode for repositories without a CSV mode."),
|
|
2742
3085
|
scanPromptFile: optionValue("--scan-prompt-file")
|
|
2743
3086
|
.optional()
|
|
2744
3087
|
.describe("Append instructions from FILE to every scan."),
|
|
@@ -2799,7 +3142,29 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2799
3142
|
dependencies.addSignalListener("SIGTERM", onTerminate);
|
|
2800
3143
|
try {
|
|
2801
3144
|
const currentDirectory = dependencies.currentDirectory();
|
|
2802
|
-
|
|
3145
|
+
if (options.recover && args.input === undefined) {
|
|
3146
|
+
throw new Error("Bulk recovery requires the original repository CSV and --output-dir.");
|
|
3147
|
+
}
|
|
3148
|
+
const project = await selectedProjectConfig(options.config, dependencies);
|
|
3149
|
+
const overrides = {
|
|
3150
|
+
mode: options.mode,
|
|
3151
|
+
outputDir: options.outputDir,
|
|
3152
|
+
knowledgeBasePaths: options.knowledgeBase,
|
|
3153
|
+
scanPromptFile: options.scanPromptFile,
|
|
3154
|
+
validationPromptFile: options.validationPromptFile,
|
|
3155
|
+
postScanPromptFile: options.postScanPromptFile,
|
|
3156
|
+
maxCostUsd: options.maxCost,
|
|
3157
|
+
};
|
|
3158
|
+
const resolved = resolveScanSettings(project, overrides, currentDirectory);
|
|
3159
|
+
const settings = resolved.options;
|
|
3160
|
+
// A CSV row may choose a different mode; resolve the same file for both
|
|
3161
|
+
// modes so inactive deep defaults remain available to deep rows.
|
|
3162
|
+
const scanOptionsByMode = project === undefined
|
|
3163
|
+
? undefined
|
|
3164
|
+
: Object.fromEntries(SCAN_MODES.map((mode) => [
|
|
3165
|
+
mode,
|
|
3166
|
+
resolveScanSettings(project, { ...overrides, mode }, currentDirectory).options,
|
|
3167
|
+
]));
|
|
2803
3168
|
let inputPath;
|
|
2804
3169
|
let outputDir;
|
|
2805
3170
|
let githubHost;
|
|
@@ -2812,7 +3177,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2812
3177
|
output: errorOutput,
|
|
2813
3178
|
now: dependencies.now,
|
|
2814
3179
|
currentDirectory: dependencies.currentDirectory,
|
|
2815
|
-
}), controller.signal);
|
|
3180
|
+
}), controller.signal, settings.outputDir);
|
|
2816
3181
|
if (wizard === null)
|
|
2817
3182
|
return;
|
|
2818
3183
|
inputPath = wizard.inputPath;
|
|
@@ -2820,30 +3185,99 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2820
3185
|
githubHost = wizard.githubHost;
|
|
2821
3186
|
}
|
|
2822
3187
|
else {
|
|
2823
|
-
if (
|
|
3188
|
+
if (settings.outputDir === undefined) {
|
|
2824
3189
|
throw new Error("--output-dir is required with a repository CSV.");
|
|
2825
3190
|
}
|
|
2826
3191
|
inputPath = resolveCliPath(currentDirectory, args.input);
|
|
2827
|
-
outputDir =
|
|
3192
|
+
outputDir = settings.outputDir;
|
|
2828
3193
|
}
|
|
2829
3194
|
const result = await runMultiscan({
|
|
2830
3195
|
inputPath,
|
|
2831
3196
|
outputDir,
|
|
2832
3197
|
...(githubHost === undefined ? {} : { githubHost }),
|
|
2833
3198
|
workers: options.workers,
|
|
2834
|
-
mode:
|
|
3199
|
+
mode: settings.mode,
|
|
2835
3200
|
maxAttempts: options.maxAttempts,
|
|
2836
|
-
...(
|
|
3201
|
+
...(settings.maxCostUsd === undefined
|
|
2837
3202
|
? {}
|
|
2838
|
-
: { maxCostUsd:
|
|
2839
|
-
knowledgeBasePaths:
|
|
2840
|
-
|
|
3203
|
+
: { maxCostUsd: settings.maxCostUsd }),
|
|
3204
|
+
knowledgeBasePaths: settings.knowledgeBasePaths,
|
|
3205
|
+
scanOptionsByMode,
|
|
3206
|
+
scanPromptFile: settings.scanPromptFile,
|
|
3207
|
+
validationPromptFile: settings.validationPromptFile,
|
|
3208
|
+
postScanPromptFile: settings.postScanPromptFile,
|
|
2841
3209
|
config: {
|
|
3210
|
+
codexOverrides: mergeCodexOverrides(resolved.config.codexOverrides, parseCodexOverrides(options.codex, options.model, options.effort, options.provider, project?.input.codex)),
|
|
2842
3211
|
pluginPath: options.pluginPath,
|
|
2843
3212
|
pythonPath: options.python,
|
|
2844
|
-
codexOverrides: parseCodexOverrides(options.codex, options.model, options.effort, options.provider),
|
|
2845
3213
|
},
|
|
2846
3214
|
createSecurity: dependencies.createSecurity,
|
|
3215
|
+
...(options.recover
|
|
3216
|
+
? {
|
|
3217
|
+
recoverScan: async (scanDir, prompts) => {
|
|
3218
|
+
const history = await dependencies.runWorkbench(["list-scans", "--scan-root", scanDir], undefined, controller.signal);
|
|
3219
|
+
const scan = history["scans"].find((scan) => resolve(scan.scanDir) === scanDir);
|
|
3220
|
+
if (scan === undefined)
|
|
3221
|
+
return undefined;
|
|
3222
|
+
const status = scan["progress"]["status"];
|
|
3223
|
+
if (status === "complete") {
|
|
3224
|
+
const contract = await loadContract(scanDir, {
|
|
3225
|
+
pluginRoot: await bundledPluginRoot(),
|
|
3226
|
+
expectedScanId: scan.scanId,
|
|
3227
|
+
signal: controller.signal,
|
|
3228
|
+
});
|
|
3229
|
+
return {
|
|
3230
|
+
coverage: contract.coverage,
|
|
3231
|
+
findings: contract.findings,
|
|
3232
|
+
cost: scan["cost"] ??
|
|
3233
|
+
null,
|
|
3234
|
+
};
|
|
3235
|
+
}
|
|
3236
|
+
if (status !== "running" || scan["mode"] !== "deep")
|
|
3237
|
+
return undefined;
|
|
3238
|
+
const saved = await dependencies.runWorkbench([
|
|
3239
|
+
"get-cli-scan-resume",
|
|
3240
|
+
"--scan-id",
|
|
3241
|
+
scan.scanId,
|
|
3242
|
+
"--allow-unavailable",
|
|
3243
|
+
], undefined, controller.signal);
|
|
3244
|
+
if (typeof saved["unavailable"] === "string") {
|
|
3245
|
+
errorOutput.write(`codex-security: ${scan.scanId}: ${saved["unavailable"]} Preserving this attempt and starting a new one.\n`);
|
|
3246
|
+
return undefined;
|
|
3247
|
+
}
|
|
3248
|
+
const session = typeof saved["threadId"] === "string"
|
|
3249
|
+
? await findScanSession(codexSecurityCredentialHome(dependencies.environment), saved["threadId"])
|
|
3250
|
+
: null;
|
|
3251
|
+
if (session?.workingDirectory !== scanDir) {
|
|
3252
|
+
errorOutput.write(`codex-security: ${scan.scanId}: Original session logs are unavailable. Preserving this attempt and starting a new one.\n`);
|
|
3253
|
+
return undefined;
|
|
3254
|
+
}
|
|
3255
|
+
const recipe = await prepareScanArgumentsFromRecipe(saved["recipe"], scan.scanId, {
|
|
3256
|
+
scanPrompt: typeof saved["userContext"] === "string"
|
|
3257
|
+
? saved["userContext"]
|
|
3258
|
+
: undefined,
|
|
3259
|
+
}, currentDirectory);
|
|
3260
|
+
const security = dependencies.createSecurity({
|
|
3261
|
+
pluginPath: options.pluginPath,
|
|
3262
|
+
pythonPath: options.python,
|
|
3263
|
+
codexOverrides: recipe.codexOverrides,
|
|
3264
|
+
});
|
|
3265
|
+
try {
|
|
3266
|
+
return await security.run(recipe.repository, {
|
|
3267
|
+
...pickScanSettings(recipe),
|
|
3268
|
+
resumeScanId: scan.scanId,
|
|
3269
|
+
outputDir: scanDir,
|
|
3270
|
+
safetyIdentifier: recipe.safetyIdentifier,
|
|
3271
|
+
postScanPrompt: recipe.postScanPrompt ?? prompts.postScanPrompt,
|
|
3272
|
+
signal: controller.signal,
|
|
3273
|
+
});
|
|
3274
|
+
}
|
|
3275
|
+
finally {
|
|
3276
|
+
await security.close();
|
|
3277
|
+
}
|
|
3278
|
+
},
|
|
3279
|
+
}
|
|
3280
|
+
: {}),
|
|
2847
3281
|
signal: controller.signal,
|
|
2848
3282
|
onProgress: ({ repository, status, attempt, error, warning }) => {
|
|
2849
3283
|
const detail = error ?? warning;
|
|
@@ -2852,7 +3286,11 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2852
3286
|
});
|
|
2853
3287
|
exitCode =
|
|
2854
3288
|
interruptedExitCode() ??
|
|
2855
|
-
(result.failed > 0 || result.incomplete > 0
|
|
3289
|
+
(result.failed > 0 || result.incomplete > 0
|
|
3290
|
+
? 2
|
|
3291
|
+
: result.policyFailed
|
|
3292
|
+
? 1
|
|
3293
|
+
: 0);
|
|
2856
3294
|
return { ...result };
|
|
2857
3295
|
}
|
|
2858
3296
|
catch (error) {
|
|
@@ -2929,6 +3367,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2929
3367
|
.describe("Finding text or a file containing findings."),
|
|
2930
3368
|
}),
|
|
2931
3369
|
options: z.object({
|
|
3370
|
+
auth: z
|
|
3371
|
+
.enum(SCAN_AUTH_MODES)
|
|
3372
|
+
.default("auto")
|
|
3373
|
+
.describe("Credential source: auto, chatgpt, or api-key."),
|
|
2932
3374
|
effort: effortOption(),
|
|
2933
3375
|
codex: z
|
|
2934
3376
|
.array(optionValue("--codex"))
|
|
@@ -2937,7 +3379,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2937
3379
|
}),
|
|
2938
3380
|
async run({ options }) {
|
|
2939
3381
|
try {
|
|
2940
|
-
exitCode = await runSkill("validation", positionals, options.codex, options.effort, output, errorOutput, dependencies);
|
|
3382
|
+
exitCode = await runSkill("validation", positionals, options.codex, options.effort, output, errorOutput, dependencies, { auth: options.auth });
|
|
2941
3383
|
}
|
|
2942
3384
|
catch (error) {
|
|
2943
3385
|
exitCode = 2;
|
|
@@ -2957,6 +3399,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
2957
3399
|
.describe("Finding text, a file, or a saved finding identifier."),
|
|
2958
3400
|
}),
|
|
2959
3401
|
options: z.object({
|
|
3402
|
+
auth: z
|
|
3403
|
+
.enum(SCAN_AUTH_MODES)
|
|
3404
|
+
.default("auto")
|
|
3405
|
+
.describe("Credential source: auto, chatgpt, or api-key."),
|
|
2960
3406
|
effort: effortOption(),
|
|
2961
3407
|
scan: optionValue("--scan")
|
|
2962
3408
|
.optional()
|
|
@@ -3048,6 +3494,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3048
3494
|
...(selected === undefined
|
|
3049
3495
|
? {}
|
|
3050
3496
|
: { findings: selected.findings }),
|
|
3497
|
+
auth: options.auth,
|
|
3051
3498
|
verificationIds: identifiers,
|
|
3052
3499
|
environment,
|
|
3053
3500
|
onEvent: progress.observe.bind(progress),
|
|
@@ -3115,7 +3562,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3115
3562
|
.describe("Issue text or a file containing issues."),
|
|
3116
3563
|
}),
|
|
3117
3564
|
options: z.object({
|
|
3565
|
+
auth: z
|
|
3566
|
+
.enum(SCAN_AUTH_MODES)
|
|
3567
|
+
.default("auto")
|
|
3568
|
+
.describe("Credential source: auto, chatgpt, or api-key."),
|
|
3118
3569
|
effort: effortOption(),
|
|
3570
|
+
externalSandbox: z
|
|
3571
|
+
.boolean()
|
|
3572
|
+
.default(false)
|
|
3573
|
+
.describe("Use the container's isolation instead of the Codex sandbox (default: false)."),
|
|
3119
3574
|
scan: optionValue("--scan")
|
|
3120
3575
|
.optional()
|
|
3121
3576
|
.describe("Patch open findings from a saved scan."),
|
|
@@ -3145,7 +3600,15 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3145
3600
|
.describe('Repeat TOML model="gpt-5.6-terra", model_reasoning_effort="high", or analytics.enabled=false.'),
|
|
3146
3601
|
}),
|
|
3147
3602
|
output: z.record(z.string(), z.unknown()).optional(),
|
|
3148
|
-
async run({ format, options }) {
|
|
3603
|
+
async run({ format, options, error: commandError }) {
|
|
3604
|
+
const jsonOutput = format === "json" || format === "jsonl";
|
|
3605
|
+
const fullOutput = argv.includes("--full-output");
|
|
3606
|
+
const structuredOutput = jsonOutput || fullOutput;
|
|
3607
|
+
let patchResult = {
|
|
3608
|
+
applied: false,
|
|
3609
|
+
filesChanged: 0,
|
|
3610
|
+
files: [],
|
|
3611
|
+
};
|
|
3149
3612
|
try {
|
|
3150
3613
|
const linear = options.linearIssue.length > 0 || !!options.linearProject;
|
|
3151
3614
|
if (options.resumePr !== undefined) {
|
|
@@ -3154,10 +3617,12 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3154
3617
|
options.severity !== undefined ||
|
|
3155
3618
|
options.createPr ||
|
|
3156
3619
|
options.assessPatchRisk ||
|
|
3620
|
+
options.externalSandbox ||
|
|
3157
3621
|
linear ||
|
|
3158
3622
|
options.linearFilter !== undefined ||
|
|
3159
3623
|
options.linearApiKey !== undefined ||
|
|
3160
3624
|
options.effort !== undefined ||
|
|
3625
|
+
options.auth !== "auto" ||
|
|
3161
3626
|
options.codex.length > 0) {
|
|
3162
3627
|
throw new CodexSecurityError("--resume-pr cannot be combined with patch inputs or options.");
|
|
3163
3628
|
}
|
|
@@ -3181,15 +3646,33 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3181
3646
|
if (savedFindings && linear) {
|
|
3182
3647
|
throw new CodexSecurityError("Saved findings cannot be combined with Linear issues or projects.");
|
|
3183
3648
|
}
|
|
3649
|
+
if (options.externalSandbox) {
|
|
3650
|
+
errorOutput.write("WARNING: --external-sandbox disables Codex sandbox enforcement for patching. The container must provide isolation.\n");
|
|
3651
|
+
}
|
|
3184
3652
|
if (savedFindings) {
|
|
3185
3653
|
const selected = await selectSavedFindings(positionals, options.scan, options.severity, dependencies);
|
|
3186
3654
|
const patchRiskBase = options.assessPatchRisk
|
|
3187
3655
|
? await snapshotPatchTree(selected.repository, dependencies)
|
|
3188
3656
|
: undefined;
|
|
3189
|
-
const
|
|
3657
|
+
const patchBase = patchRiskBase ??
|
|
3658
|
+
(await snapshotPatchState(selected.repository, dependencies));
|
|
3659
|
+
const patches = await runFindingPatches(selected, options.codex, options.effort, errorOutput, dependencies, { auth: options.auth, externalSandbox: options.externalSandbox });
|
|
3190
3660
|
exitCode = patchExitCode(patches);
|
|
3661
|
+
const files = await changedPatchFiles(selected.repository, patchBase, dependencies);
|
|
3662
|
+
patchResult = {
|
|
3663
|
+
scanId: selected.scanId,
|
|
3664
|
+
repository: selected.repository,
|
|
3665
|
+
patches,
|
|
3666
|
+
applied: files.length > 0,
|
|
3667
|
+
filesChanged: files.length,
|
|
3668
|
+
files,
|
|
3669
|
+
};
|
|
3670
|
+
if (exitCode !== 0 || files.length === 0) {
|
|
3671
|
+
throw new PatchCommandError(exitCode === 0 ? "NO_PATCH_APPLIED" : "PATCH_FAILED", `Patch did not complete successfully; ${files.length} files changed. Review the patch results before retrying.`);
|
|
3672
|
+
}
|
|
3673
|
+
errorOutput.write(`Patch applied. Files changed: ${files.length}.\n`);
|
|
3191
3674
|
let patchRisk;
|
|
3192
|
-
if (
|
|
3675
|
+
if (patchRiskBase !== undefined) {
|
|
3193
3676
|
const files = verifiedPatchFiles(selected, patches);
|
|
3194
3677
|
if (files.length > 0) {
|
|
3195
3678
|
patchRisk = await runPatchRiskAssessment({
|
|
@@ -3198,17 +3681,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3198
3681
|
files,
|
|
3199
3682
|
codexOverrides: options.codex,
|
|
3200
3683
|
effort: options.effort,
|
|
3684
|
+
auth: options.auth,
|
|
3201
3685
|
}, errorOutput, dependencies);
|
|
3202
3686
|
}
|
|
3203
3687
|
}
|
|
3204
|
-
const pullRequest = options.createPr
|
|
3688
|
+
const pullRequest = options.createPr
|
|
3205
3689
|
? await createPatchPullRequest(selected.repository, selected.scanId, verifiedPatchFiles(selected, patches), errorOutput, dependencies, patchRisk?.summary)
|
|
3206
3690
|
: undefined;
|
|
3207
|
-
if (
|
|
3691
|
+
if (structuredOutput) {
|
|
3208
3692
|
return {
|
|
3209
|
-
|
|
3210
|
-
repository: selected.repository,
|
|
3211
|
-
patches,
|
|
3693
|
+
...patchResult,
|
|
3212
3694
|
...(patchRisk === undefined
|
|
3213
3695
|
? {}
|
|
3214
3696
|
: { patchRisk: { report: patchRisk.report } }),
|
|
@@ -3223,9 +3705,6 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3223
3705
|
if (options.severity !== undefined) {
|
|
3224
3706
|
throw new CodexSecurityError("--severity requires a saved finding identifier or --scan.");
|
|
3225
3707
|
}
|
|
3226
|
-
if (format === "json" || format === "jsonl") {
|
|
3227
|
-
throw new CodexSecurityError("JSON patch output requires a saved finding identifier or --scan.");
|
|
3228
|
-
}
|
|
3229
3708
|
const imports = linear
|
|
3230
3709
|
? await importLinearIssues({
|
|
3231
3710
|
issues: options.linearIssue,
|
|
@@ -3240,35 +3719,85 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3240
3719
|
? undefined
|
|
3241
3720
|
: Object.fromEntries(Object.entries(dependencies.environment).filter(([name]) => !/^(?:CODEX_SECURITY_)?LINEAR_(?:API_KEY|ACCESS_TOKEN)$/iu.test(name)));
|
|
3242
3721
|
const repository = dependencies.currentDirectory();
|
|
3243
|
-
const
|
|
3722
|
+
const patchGitBase = options.assessPatchRisk || options.createPr
|
|
3244
3723
|
? await snapshotPatchTree(repository, dependencies)
|
|
3245
3724
|
: undefined;
|
|
3725
|
+
const patchBase = patchGitBase ??
|
|
3726
|
+
(await snapshotPatchState(repository, dependencies));
|
|
3246
3727
|
if (options.createPr) {
|
|
3247
|
-
await requireCleanPatchPullRequestBase(repository,
|
|
3248
|
-
}
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
|
|
3253
|
-
|
|
3254
|
-
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
|
|
3728
|
+
await requireCleanPatchPullRequestBase(repository, patchGitBase, dependencies);
|
|
3729
|
+
}
|
|
3730
|
+
let report = "";
|
|
3731
|
+
exitCode = await runSkill("fix-finding", [...positionals, ...imports], options.codex, options.effort, {
|
|
3732
|
+
write: (value) => {
|
|
3733
|
+
report += value.toString();
|
|
3734
|
+
return true;
|
|
3735
|
+
},
|
|
3736
|
+
}, errorOutput, dependencies, {
|
|
3737
|
+
environment,
|
|
3738
|
+
auth: options.auth,
|
|
3739
|
+
externalSandbox: options.externalSandbox,
|
|
3740
|
+
});
|
|
3741
|
+
if (!jsonOutput)
|
|
3742
|
+
output.write(report);
|
|
3743
|
+
const files = await changedPatchFiles(repository, patchBase, dependencies);
|
|
3744
|
+
patchResult = {
|
|
3745
|
+
repository,
|
|
3746
|
+
applied: files.length > 0,
|
|
3747
|
+
filesChanged: files.length,
|
|
3748
|
+
files,
|
|
3749
|
+
};
|
|
3750
|
+
if (exitCode !== 0) {
|
|
3751
|
+
throw new PatchCommandError("PATCH_FAILED", `Patch command exited with status ${exitCode}.`);
|
|
3752
|
+
}
|
|
3753
|
+
if (files.length === 0) {
|
|
3754
|
+
throw new PatchCommandError("NO_PATCH_APPLIED", "No patch was applied; 0 files changed.");
|
|
3755
|
+
}
|
|
3756
|
+
errorOutput.write(`Patch applied. Files changed: ${files.length}.\n`);
|
|
3757
|
+
const patchRisk = options.assessPatchRisk
|
|
3758
|
+
? await runPatchRiskAssessment({
|
|
3759
|
+
repository,
|
|
3760
|
+
environment,
|
|
3761
|
+
base: patchGitBase,
|
|
3762
|
+
files,
|
|
3763
|
+
codexOverrides: options.codex,
|
|
3764
|
+
effort: options.effort,
|
|
3765
|
+
auth: options.auth,
|
|
3766
|
+
}, errorOutput, dependencies)
|
|
3767
|
+
: undefined;
|
|
3768
|
+
if (options.createPr) {
|
|
3769
|
+
const identifier = directPatchIdentifier(positionals, imports);
|
|
3770
|
+
await createPatchPullRequest(repository, identifier ?? directPatchDigest(positionals, imports), files, errorOutput, dependencies, patchRisk?.summary, identifier === undefined
|
|
3771
|
+
? "Applies a security fix generated from supplied issue data."
|
|
3772
|
+
: `Applies a security fix generated for ${identifier}.`);
|
|
3267
3773
|
}
|
|
3774
|
+
if (structuredOutput)
|
|
3775
|
+
return {
|
|
3776
|
+
...patchResult,
|
|
3777
|
+
...(jsonOutput ? { report } : {}),
|
|
3778
|
+
};
|
|
3268
3779
|
}
|
|
3269
3780
|
catch (error) {
|
|
3270
|
-
exitCode
|
|
3271
|
-
|
|
3781
|
+
if (exitCode === 0)
|
|
3782
|
+
exitCode = 2;
|
|
3783
|
+
const message = safeErrorMessage(error);
|
|
3784
|
+
errorOutput.write(`codex-security: ${message}\n`);
|
|
3785
|
+
if (!structuredOutput)
|
|
3786
|
+
return;
|
|
3787
|
+
patchStructuredError = true;
|
|
3788
|
+
const failure = {
|
|
3789
|
+
code: error instanceof PatchCommandError ? error.code : "PATCH_FAILED",
|
|
3790
|
+
message,
|
|
3791
|
+
};
|
|
3792
|
+
if (!fullOutput) {
|
|
3793
|
+
renderedPatch =
|
|
3794
|
+
JSON.stringify({
|
|
3795
|
+
ok: false,
|
|
3796
|
+
...patchResult,
|
|
3797
|
+
error: failure,
|
|
3798
|
+
}) + "\n";
|
|
3799
|
+
}
|
|
3800
|
+
return commandError({ ...failure, exitCode });
|
|
3272
3801
|
}
|
|
3273
3802
|
},
|
|
3274
3803
|
})
|
|
@@ -3393,9 +3922,103 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3393
3922
|
exitCode = 1;
|
|
3394
3923
|
}
|
|
3395
3924
|
},
|
|
3925
|
+
})
|
|
3926
|
+
.command("init", {
|
|
3927
|
+
description: "Write a starter project configuration without overwriting an existing file.",
|
|
3928
|
+
destructive: true,
|
|
3929
|
+
mcp: false,
|
|
3930
|
+
args: z.object({
|
|
3931
|
+
file: z
|
|
3932
|
+
.string()
|
|
3933
|
+
.min(1)
|
|
3934
|
+
.optional()
|
|
3935
|
+
.describe("YAML or JSON destination (default: codex-security.yaml)."),
|
|
3936
|
+
}),
|
|
3937
|
+
output: z.object({ path: z.string() }).optional(),
|
|
3938
|
+
async run({ args }) {
|
|
3939
|
+
try {
|
|
3940
|
+
const directory = dependencies.currentDirectory();
|
|
3941
|
+
const path = resolveCliPath(directory, args.file ?? "codex-security.yaml");
|
|
3942
|
+
await writeFile(path, projectConfigStarter(path, directory), {
|
|
3943
|
+
flag: "wx",
|
|
3944
|
+
mode: 0o600,
|
|
3945
|
+
});
|
|
3946
|
+
return { path };
|
|
3947
|
+
}
|
|
3948
|
+
catch (error) {
|
|
3949
|
+
exitCode = 2;
|
|
3950
|
+
errorOutput.write(`codex-security: ${errorMessage(error)}\n`);
|
|
3951
|
+
}
|
|
3952
|
+
},
|
|
3953
|
+
})
|
|
3954
|
+
.command("feedback", {
|
|
3955
|
+
description: "Send feedback to OpenAI and return a feedback ID.",
|
|
3956
|
+
destructive: true,
|
|
3957
|
+
mcp: false,
|
|
3958
|
+
args: z.object({
|
|
3959
|
+
scanId: z
|
|
3960
|
+
.string()
|
|
3961
|
+
.min(1)
|
|
3962
|
+
.optional()
|
|
3963
|
+
.describe("Scan ID or unique prefix (default: most recently started scan in the current repository)."),
|
|
3964
|
+
}),
|
|
3965
|
+
options: z.object({
|
|
3966
|
+
reason: z.string().trim().min(1).describe("Describe the problem."),
|
|
3967
|
+
includeLogs: z
|
|
3968
|
+
.boolean()
|
|
3969
|
+
.default(false)
|
|
3970
|
+
.describe("Upload diagnostic logs, including scan and worker conversations and tool output. Defaults to off."),
|
|
3971
|
+
}),
|
|
3972
|
+
output: z.object({
|
|
3973
|
+
feedbackId: z.string(),
|
|
3974
|
+
scanId: z.string().nullable(),
|
|
3975
|
+
includedLogs: z.boolean(),
|
|
3976
|
+
}),
|
|
3977
|
+
async run({ args, options }) {
|
|
3978
|
+
let scanId = args.scanId;
|
|
3979
|
+
if (scanId === undefined) {
|
|
3980
|
+
const value = await history([
|
|
3981
|
+
"list-scans",
|
|
3982
|
+
"--repository",
|
|
3983
|
+
dependencies.currentDirectory(),
|
|
3984
|
+
]);
|
|
3985
|
+
const scans = value["scans"];
|
|
3986
|
+
scanId = scans.toSorted((a, b) => b.startedAt.localeCompare(a.startedAt))[0]?.scanId;
|
|
3987
|
+
}
|
|
3988
|
+
const scan = scanId === undefined
|
|
3989
|
+
? undefined
|
|
3990
|
+
: (await history(["get-scan", "--scan-id", scanId]))["scan"];
|
|
3991
|
+
const controller = new AbortController();
|
|
3992
|
+
const onInterrupt = () => controller.abort("SIGINT");
|
|
3993
|
+
const onTerminate = () => controller.abort("SIGTERM");
|
|
3994
|
+
dependencies.addSignalListener("SIGINT", onInterrupt);
|
|
3995
|
+
dependencies.addSignalListener("SIGTERM", onTerminate);
|
|
3996
|
+
try {
|
|
3997
|
+
return await (dependencies.sendFeedback ?? sendFeedback)({
|
|
3998
|
+
...options,
|
|
3999
|
+
scan,
|
|
4000
|
+
environment: dependencies.environment,
|
|
4001
|
+
workingDirectory: dependencies.currentDirectory(),
|
|
4002
|
+
signal: controller.signal,
|
|
4003
|
+
});
|
|
4004
|
+
}
|
|
4005
|
+
catch (error) {
|
|
4006
|
+
if (controller.signal.aborted) {
|
|
4007
|
+
exitCode = controller.signal.reason === "SIGINT" ? 130 : 143;
|
|
4008
|
+
errorOutput.write("codex-security: Feedback upload canceled.\n");
|
|
4009
|
+
}
|
|
4010
|
+
throw error;
|
|
4011
|
+
}
|
|
4012
|
+
finally {
|
|
4013
|
+
dependencies.removeSignalListener("SIGINT", onInterrupt);
|
|
4014
|
+
dependencies.removeSignalListener("SIGTERM", onTerminate);
|
|
4015
|
+
}
|
|
4016
|
+
},
|
|
3396
4017
|
})
|
|
3397
4018
|
.command("info", {
|
|
3398
|
-
description: "Show
|
|
4019
|
+
description: "Show SDK metadata and resolved configuration without preparing a scan.",
|
|
4020
|
+
alias: { config: "c" },
|
|
4021
|
+
options: z.object({ config: PROJECT_CONFIG_OPTION }),
|
|
3399
4022
|
mcp: {
|
|
3400
4023
|
annotations: {
|
|
3401
4024
|
readOnlyHint: true,
|
|
@@ -3415,8 +4038,17 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3415
4038
|
model: z.string(),
|
|
3416
4039
|
reasoningEffort: z.string(),
|
|
3417
4040
|
nextStep: z.string(),
|
|
4041
|
+
configuration: z.record(z.string(), z.unknown()),
|
|
3418
4042
|
}),
|
|
3419
|
-
run() {
|
|
4043
|
+
async run({ options }) {
|
|
4044
|
+
const directory = dependencies.currentDirectory();
|
|
4045
|
+
const project = await selectedProjectConfig(options.config, dependencies);
|
|
4046
|
+
const resolved = resolveScanSettings(project, {}, directory);
|
|
4047
|
+
const codex = await mergedCodexConfig(resolved.config);
|
|
4048
|
+
const deep = resolved.options.mode === "deep"
|
|
4049
|
+
? await resolveDeepScanConfig(resolved.options, join(expandHome(environmentValue(dependencies.environment, "CODEX_HOME") ??
|
|
4050
|
+
join(homedir(), ".codex"), dependencies.environment), "codex-security", "config.toml"))
|
|
4051
|
+
: undefined;
|
|
3420
4052
|
return {
|
|
3421
4053
|
sdkVersion: VERSION,
|
|
3422
4054
|
bundledPluginVersion: BUNDLED_PLUGIN_VERSION,
|
|
@@ -3425,11 +4057,83 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3425
4057
|
cliVersion: VERSION,
|
|
3426
4058
|
codexVersion: CODEX_EXECUTABLE_VERSION,
|
|
3427
4059
|
codexSdkVersion: CODEX_SDK_VERSION,
|
|
3428
|
-
...scanModelConfiguration(
|
|
4060
|
+
...scanModelConfiguration(codex),
|
|
3429
4061
|
nextStep: "codex-security scan . --dry-run",
|
|
4062
|
+
configuration: {
|
|
4063
|
+
...(project?.path === undefined ? {} : { path: project.path }),
|
|
4064
|
+
settings: { ...resolved.options, ...deep?.settings },
|
|
4065
|
+
sources: configurationSources(resolved.sources, deep?.sources),
|
|
4066
|
+
},
|
|
3430
4067
|
};
|
|
3431
4068
|
},
|
|
3432
4069
|
});
|
|
4070
|
+
// Incur cannot mount a command with both a handler and subcommands.
|
|
4071
|
+
// Select the nested import route while preserving scan [repository].
|
|
4072
|
+
if (isScanImportCommand(argv)) {
|
|
4073
|
+
cli.command(Cli.create("scan", {
|
|
4074
|
+
description: "Run or import a saved scan.",
|
|
4075
|
+
}).command("import", {
|
|
4076
|
+
description: "Save CSV or JSON findings as a completed scan without security analysis.",
|
|
4077
|
+
destructive: true,
|
|
4078
|
+
mcp: false,
|
|
4079
|
+
options: z
|
|
4080
|
+
.object({
|
|
4081
|
+
csv: optionValue("--csv")
|
|
4082
|
+
.optional()
|
|
4083
|
+
.describe("Findings CSV in the codex-security export format."),
|
|
4084
|
+
json: optionValue("--json")
|
|
4085
|
+
.optional()
|
|
4086
|
+
.describe("Findings JSON document or object with a findings array."),
|
|
4087
|
+
outputDir: optionValue("--output-dir")
|
|
4088
|
+
.optional()
|
|
4089
|
+
.describe("Artifact directory (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
|
|
4090
|
+
archiveExisting: z
|
|
4091
|
+
.boolean()
|
|
4092
|
+
.default(false)
|
|
4093
|
+
.describe("Archive existing results; requires --output-dir."),
|
|
4094
|
+
dryRun: z
|
|
4095
|
+
.boolean()
|
|
4096
|
+
.default(false)
|
|
4097
|
+
.describe("Validate the input without saving a scan."),
|
|
4098
|
+
})
|
|
4099
|
+
.refine((options) => Number(options.csv !== undefined) +
|
|
4100
|
+
Number(options.json !== undefined) ===
|
|
4101
|
+
1, { message: "Provide exactly one of --csv FILE or --json FILE." })
|
|
4102
|
+
.refine((options) => !options.archiveExisting || options.outputDir !== undefined, { message: "--archive-existing requires --output-dir." }),
|
|
4103
|
+
examples: [
|
|
4104
|
+
{ options: { csv: "findings.csv" } },
|
|
4105
|
+
{ options: { json: "findings.json" } },
|
|
4106
|
+
],
|
|
4107
|
+
hint: "Each input row is retained, including duplicates. --json selects the input file; use --format json for JSON output.",
|
|
4108
|
+
output: z.record(z.string(), z.unknown()).optional(),
|
|
4109
|
+
async run({ options, format, error: incurError }) {
|
|
4110
|
+
const directory = dependencies.currentDirectory();
|
|
4111
|
+
const outcome = await runImport({
|
|
4112
|
+
sourcePath: resolveCliPath(directory, options.csv ?? options.json),
|
|
4113
|
+
format: options.csv === undefined ? "json" : "csv",
|
|
4114
|
+
outputDir: options.outputDir === undefined
|
|
4115
|
+
? undefined
|
|
4116
|
+
: resolveCliPath(directory, options.outputDir),
|
|
4117
|
+
archiveExisting: options.archiveExisting,
|
|
4118
|
+
dryRun: options.dryRun,
|
|
4119
|
+
});
|
|
4120
|
+
exitCode = outcome.exitCode;
|
|
4121
|
+
if (outcome.error !== undefined) {
|
|
4122
|
+
return incurError({
|
|
4123
|
+
code: "SCAN_IMPORT_FAILED",
|
|
4124
|
+
message: outcome.error,
|
|
4125
|
+
exitCode,
|
|
4126
|
+
});
|
|
4127
|
+
}
|
|
4128
|
+
if (!options.dryRun &&
|
|
4129
|
+
format === "toon" &&
|
|
4130
|
+
!argv.some((argument) => OUTPUT_OPTION.test(argument))) {
|
|
4131
|
+
return;
|
|
4132
|
+
}
|
|
4133
|
+
return outcome.data;
|
|
4134
|
+
},
|
|
4135
|
+
}));
|
|
4136
|
+
}
|
|
3433
4137
|
let notice;
|
|
3434
4138
|
try {
|
|
3435
4139
|
await cli.serve(argv.flatMap((argument) => argument.startsWith("--format=")
|
|
@@ -3452,15 +4156,25 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3452
4156
|
if (notice !== undefined)
|
|
3453
4157
|
errorOutput.write(formatUpdateNotice(notice));
|
|
3454
4158
|
if (frameworkExit !== undefined) {
|
|
3455
|
-
if (
|
|
3456
|
-
|
|
3457
|
-
|
|
3458
|
-
|
|
4159
|
+
if (policyFullOutput || patchStructuredError) {
|
|
4160
|
+
if (exitCode === 0)
|
|
4161
|
+
exitCode = 2;
|
|
4162
|
+
}
|
|
4163
|
+
else {
|
|
4164
|
+
if (exitCode !== 0)
|
|
4165
|
+
return exitCode;
|
|
4166
|
+
errorOutput.write(`codex-security: ${errorMessage(incurErrorMessage(frameworkOutput))}\n`);
|
|
4167
|
+
return 2;
|
|
4168
|
+
}
|
|
3459
4169
|
}
|
|
3460
4170
|
if (frameworkOutput.length === 0)
|
|
3461
4171
|
return exitCode;
|
|
3462
4172
|
try {
|
|
3463
|
-
await writeCliOutput(output,
|
|
4173
|
+
await writeCliOutput(output, renderedPolicy ??
|
|
4174
|
+
renderedPatch ??
|
|
4175
|
+
renderedPublication ??
|
|
4176
|
+
renderedHistory ??
|
|
4177
|
+
frameworkOutput);
|
|
3464
4178
|
return exitCode;
|
|
3465
4179
|
}
|
|
3466
4180
|
catch (error) {
|
|
@@ -3468,12 +4182,75 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
|
|
|
3468
4182
|
return 2;
|
|
3469
4183
|
}
|
|
3470
4184
|
}
|
|
3471
|
-
function
|
|
3472
|
-
const
|
|
4185
|
+
async function runScanImport(options, errorOutput, dependencies) {
|
|
4186
|
+
const controller = new AbortController();
|
|
4187
|
+
const onInterrupt = () => controller.abort("SIGINT");
|
|
4188
|
+
const onTerminate = () => controller.abort("SIGTERM");
|
|
4189
|
+
dependencies.addSignalListener("SIGINT", onInterrupt);
|
|
4190
|
+
dependencies.addSignalListener("SIGTERM", onTerminate);
|
|
4191
|
+
try {
|
|
4192
|
+
const result = await (dependencies.importScan ?? importScan)({ ...options, signal: controller.signal }, { environment: dependencies.environment });
|
|
4193
|
+
if ("dryRun" in result)
|
|
4194
|
+
return { exitCode: 0, data: { ...result } };
|
|
4195
|
+
try {
|
|
4196
|
+
errorOutput.write(`Imported ${result.findings.findings.length} findings as scan ${result.manifest.scan.id}.\n` +
|
|
4197
|
+
`Artifacts: ${result.scanDir}\n`);
|
|
4198
|
+
}
|
|
4199
|
+
catch { }
|
|
4200
|
+
return { exitCode: 0, data: result.toJSON() };
|
|
4201
|
+
}
|
|
4202
|
+
catch (error) {
|
|
4203
|
+
const signal = controller.signal.reason;
|
|
4204
|
+
const message = signal === "SIGINT" || signal === "SIGTERM"
|
|
4205
|
+
? "Scan import canceled."
|
|
4206
|
+
: safeErrorMessage(error);
|
|
4207
|
+
errorOutput.write(`codex-security: ${message}\n`);
|
|
4208
|
+
return {
|
|
4209
|
+
exitCode: signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 2,
|
|
4210
|
+
error: message,
|
|
4211
|
+
};
|
|
4212
|
+
}
|
|
4213
|
+
finally {
|
|
4214
|
+
dependencies.removeSignalListener("SIGINT", onInterrupt);
|
|
4215
|
+
dependencies.removeSignalListener("SIGTERM", onTerminate);
|
|
4216
|
+
}
|
|
4217
|
+
}
|
|
4218
|
+
function isScanImportCommand(argv) {
|
|
4219
|
+
const commandIndex = cliCommandIndex(argv);
|
|
4220
|
+
return argv[commandIndex] === "scan" && argv[commandIndex + 1] === "import";
|
|
4221
|
+
}
|
|
4222
|
+
function normalizeScanImportArguments(argv) {
|
|
4223
|
+
if (!isScanImportCommand(argv))
|
|
4224
|
+
return argv;
|
|
4225
|
+
const normalized = [];
|
|
4226
|
+
const subcommandIndex = cliCommandIndex(argv) + 1;
|
|
4227
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
4228
|
+
const argument = argv[index];
|
|
4229
|
+
const next = argv[index + 1];
|
|
4230
|
+
// Incur reserves bare --json for output, but parses --json=FILE normally.
|
|
4231
|
+
if (index > subcommandIndex &&
|
|
4232
|
+
argument === "--json" &&
|
|
4233
|
+
next !== undefined &&
|
|
4234
|
+
!next.startsWith("--") &&
|
|
4235
|
+
next !== "-h") {
|
|
4236
|
+
normalized.push(`--json=${next}`);
|
|
4237
|
+
index += 1;
|
|
4238
|
+
}
|
|
4239
|
+
else {
|
|
4240
|
+
normalized.push(argument);
|
|
4241
|
+
}
|
|
4242
|
+
}
|
|
4243
|
+
return normalized;
|
|
4244
|
+
}
|
|
4245
|
+
function cliCommandIndex(argv) {
|
|
4246
|
+
return argv.findIndex((value, index) => {
|
|
3473
4247
|
if (value.startsWith("-"))
|
|
3474
4248
|
return false;
|
|
3475
4249
|
return index === 0 || !VALUE_OPTIONS.has(argv[index - 1]);
|
|
3476
4250
|
});
|
|
4251
|
+
}
|
|
4252
|
+
function defaultListCommand(argv) {
|
|
4253
|
+
const commandIndex = cliCommandIndex(argv);
|
|
3477
4254
|
if (commandIndex < 0 ||
|
|
3478
4255
|
!["scans", "findings"].includes(argv[commandIndex]) ||
|
|
3479
4256
|
argv.includes("--help") ||
|
|
@@ -3489,10 +4266,15 @@ function defaultListCommand(argv) {
|
|
|
3489
4266
|
...argv.slice(commandIndex + 1),
|
|
3490
4267
|
];
|
|
3491
4268
|
}
|
|
3492
|
-
function
|
|
4269
|
+
async function prepareScanArgumentsFromRecipe(recipe, parentScanId, { scanPrompt, scanPromptFile, validationPromptFile, }, directory) {
|
|
3493
4270
|
if (recipe === undefined || !isJsonObject(recipe)) {
|
|
3494
4271
|
throw new CodexSecurityError("This scan does not have a saved launch recipe.");
|
|
3495
4272
|
}
|
|
4273
|
+
if (recipe["requiresScanPrompt"] === true &&
|
|
4274
|
+
scanPrompt === undefined &&
|
|
4275
|
+
scanPromptFile === undefined) {
|
|
4276
|
+
throw new CodexSecurityError("This scan used additional instructions. Supply --scan-prompt-file to rerun it.");
|
|
4277
|
+
}
|
|
3496
4278
|
if (recipe["validationMode"] === "custom" &&
|
|
3497
4279
|
validationPromptFile === undefined) {
|
|
3498
4280
|
throw new CodexSecurityError("This scan used custom validation. Supply --validation-prompt-file to rerun it.");
|
|
@@ -3552,35 +4334,53 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
|
|
|
3552
4334
|
maxCostUsd <= 0)) {
|
|
3553
4335
|
throw new CodexSecurityError("The saved scan recipe contains an invalid cost limit.");
|
|
3554
4336
|
}
|
|
3555
|
-
const deepScan =
|
|
3556
|
-
.object(DEEP_SCAN_OPTION_SCHEMAS)
|
|
3557
|
-
.optional()
|
|
3558
|
-
.safeParse(recipe["deepScan"]);
|
|
4337
|
+
const deepScan = DeepScanSettingsSchema.optional().safeParse(recipe["deepScan"]);
|
|
3559
4338
|
if (!deepScan.success) {
|
|
3560
4339
|
throw new CodexSecurityError("The saved scan recipe contains invalid deep scan settings.");
|
|
3561
4340
|
}
|
|
4341
|
+
if (recipe["deepScanResolved"] === true &&
|
|
4342
|
+
DEEP_SCAN_SETTINGS.some(([name]) => deepScan.data?.[name] === undefined)) {
|
|
4343
|
+
throw new CodexSecurityError("The saved scan recipe is missing resolved deep scan settings.");
|
|
4344
|
+
}
|
|
4345
|
+
const auth = z.enum(SCAN_AUTH_MODES).optional().safeParse(recipe["auth"]);
|
|
4346
|
+
if (!auth.success)
|
|
4347
|
+
throw new CodexSecurityError("The saved scan recipe contains an invalid authentication choice.");
|
|
3562
4348
|
if (mode !== "deep" &&
|
|
3563
4349
|
deepScan.data !== undefined &&
|
|
3564
4350
|
Object.keys(deepScan.data).length > 0) {
|
|
3565
4351
|
throw new CodexSecurityError("The saved scan recipe contains deep scan settings for a standard scan.");
|
|
3566
4352
|
}
|
|
4353
|
+
const safetyIdentifier = recipe["safetyIdentifier"];
|
|
4354
|
+
const postScanPrompt = recipe["postScanPrompt"];
|
|
4355
|
+
if ((safetyIdentifier !== undefined && typeof safetyIdentifier !== "string") ||
|
|
4356
|
+
(postScanPrompt !== undefined && typeof postScanPrompt !== "string")) {
|
|
4357
|
+
throw new CodexSecurityError("The saved scan recipe contains invalid launch settings.");
|
|
4358
|
+
}
|
|
4359
|
+
const prompts = await resolveScanPrompts({ scanPrompt, scanPromptFile, validationPromptFile }, repository, directory);
|
|
4360
|
+
if (recipe["requiresScanPrompt"] === true && !prompts.scanPrompt?.trim()) {
|
|
4361
|
+
throw new CodexSecurityError("This scan used additional instructions. The --scan-prompt-file must not be empty.");
|
|
4362
|
+
}
|
|
3567
4363
|
return {
|
|
3568
4364
|
repository,
|
|
3569
|
-
|
|
3570
|
-
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
4365
|
+
auth: auth.data ?? DEFAULT_SCAN_AUTH,
|
|
4366
|
+
target: paths.length > 0
|
|
4367
|
+
? paths
|
|
4368
|
+
: kind === "refs"
|
|
4369
|
+
? DiffTarget.refs({ base: reference, head: head ?? "HEAD" })
|
|
4370
|
+
: kind === "working_tree"
|
|
4371
|
+
? DiffTarget.workingTree({ base: reference ?? "HEAD" })
|
|
4372
|
+
: "repository",
|
|
4373
|
+
knowledgeBasePaths: knowledgeBasePaths.map((path) => resolveCliPath(directory, path)),
|
|
4374
|
+
...prompts,
|
|
4375
|
+
safetyIdentifier,
|
|
4376
|
+
postScanPrompt,
|
|
3576
4377
|
mode,
|
|
3577
4378
|
...deepScan.data,
|
|
3578
4379
|
archiveExisting: false,
|
|
3579
|
-
codex: [],
|
|
3580
4380
|
codexOverrides: Object.hasOwn(config, "approval_policy")
|
|
3581
4381
|
? config
|
|
3582
4382
|
: { ...config, approval_policy: "never" },
|
|
3583
|
-
|
|
4383
|
+
failureSeverity: threshold,
|
|
3584
4384
|
maxCostUsd,
|
|
3585
4385
|
dryRun: false,
|
|
3586
4386
|
parentScanId,
|
|
@@ -3593,27 +4393,32 @@ function scanArgumentsFromRecipe(recipe, parentScanId, validationPromptFile) {
|
|
|
3593
4393
|
function validateCliArguments(argv, positionals) {
|
|
3594
4394
|
if (argv.includes("--help") || argv.includes("-h"))
|
|
3595
4395
|
return undefined;
|
|
3596
|
-
const commandIndex = argv
|
|
3597
|
-
"scan",
|
|
3598
|
-
"install-hook",
|
|
3599
|
-
"bulk-scan",
|
|
3600
|
-
"scan-components",
|
|
3601
|
-
"scans",
|
|
3602
|
-
"findings",
|
|
3603
|
-
"export",
|
|
3604
|
-
"publish",
|
|
3605
|
-
"import",
|
|
3606
|
-
"validate",
|
|
3607
|
-
"verify-fix",
|
|
3608
|
-
"patch",
|
|
3609
|
-
"login",
|
|
3610
|
-
"logout",
|
|
3611
|
-
"serve",
|
|
3612
|
-
"info",
|
|
3613
|
-
].includes(value));
|
|
3614
|
-
if (commandIndex < 0)
|
|
3615
|
-
return undefined;
|
|
4396
|
+
const commandIndex = cliCommandIndex(argv);
|
|
3616
4397
|
const command = argv[commandIndex];
|
|
4398
|
+
if (command === undefined ||
|
|
4399
|
+
![
|
|
4400
|
+
"scan",
|
|
4401
|
+
"policy",
|
|
4402
|
+
"install-hook",
|
|
4403
|
+
"bulk-scan",
|
|
4404
|
+
"scan-components",
|
|
4405
|
+
"scans",
|
|
4406
|
+
"findings",
|
|
4407
|
+
"export",
|
|
4408
|
+
"publish",
|
|
4409
|
+
"import",
|
|
4410
|
+
"validate",
|
|
4411
|
+
"verify-fix",
|
|
4412
|
+
"patch",
|
|
4413
|
+
"login",
|
|
4414
|
+
"logout",
|
|
4415
|
+
"serve",
|
|
4416
|
+
"feedback",
|
|
4417
|
+
"info",
|
|
4418
|
+
"init",
|
|
4419
|
+
].includes(command)) {
|
|
4420
|
+
return undefined;
|
|
4421
|
+
}
|
|
3617
4422
|
const structuredOutput = argv.some((value, index) => value === "--json" ||
|
|
3618
4423
|
((value === "--format" ||
|
|
3619
4424
|
value === "--format=json" ||
|
|
@@ -3644,7 +4449,9 @@ function validateCliArguments(argv, positionals) {
|
|
|
3644
4449
|
return "Markdown output is not supported for scan results.";
|
|
3645
4450
|
}
|
|
3646
4451
|
}
|
|
3647
|
-
const
|
|
4452
|
+
const scanImport = isScanImportCommand(argv);
|
|
4453
|
+
const nestedCommand = scanImport ||
|
|
4454
|
+
command === "scans" ||
|
|
3648
4455
|
command === "findings" ||
|
|
3649
4456
|
command === "publish" ||
|
|
3650
4457
|
command === "import";
|
|
@@ -3661,6 +4468,7 @@ function validateCliArguments(argv, positionals) {
|
|
|
3661
4468
|
"model",
|
|
3662
4469
|
"reasoningEffort",
|
|
3663
4470
|
"nextStep",
|
|
4471
|
+
"configuration",
|
|
3664
4472
|
]);
|
|
3665
4473
|
for (let index = 0; index < argv.length; index += 1) {
|
|
3666
4474
|
const argument = argv[index];
|
|
@@ -3685,7 +4493,8 @@ function validateCliArguments(argv, positionals) {
|
|
|
3685
4493
|
}
|
|
3686
4494
|
const equals = value.indexOf("=");
|
|
3687
4495
|
const option = equals < 0 ? value : value.slice(0, equals);
|
|
3688
|
-
if (equals >= 0 ||
|
|
4496
|
+
if (equals >= 0 ||
|
|
4497
|
+
(!VALUE_OPTIONS.has(option) && !(scanImport && option === "--json")))
|
|
3689
4498
|
continue;
|
|
3690
4499
|
const next = argv[index + 1];
|
|
3691
4500
|
if (next === undefined || next.startsWith("--") || next === "-h") {
|
|
@@ -3706,7 +4515,10 @@ function validateCliArguments(argv, positionals) {
|
|
|
3706
4515
|
command !== "verify-fix" &&
|
|
3707
4516
|
command !== "patch" &&
|
|
3708
4517
|
positionals.length >
|
|
3709
|
-
(
|
|
4518
|
+
(scanImport ||
|
|
4519
|
+
command === "logout" ||
|
|
4520
|
+
command === "info" ||
|
|
4521
|
+
command === "serve"
|
|
3710
4522
|
? 0
|
|
3711
4523
|
: subcommand === "compare" || subcommand === "match"
|
|
3712
4524
|
? 2
|
|
@@ -3795,10 +4607,6 @@ function staysWithinWindowsDeviceRoot(input, root) {
|
|
|
3795
4607
|
function isFindingIdentifier(value) {
|
|
3796
4608
|
return /^(?:occ|csf)_[A-Za-z0-9_-]+$/u.test(value);
|
|
3797
4609
|
}
|
|
3798
|
-
function meetsSeverity(finding, threshold) {
|
|
3799
|
-
const severity = DISPLAY_SEVERITIES.indexOf(finding.severity.level);
|
|
3800
|
-
return severity >= 0 && severity <= REPORTABLE_SEVERITIES.indexOf(threshold);
|
|
3801
|
-
}
|
|
3802
4610
|
async function* workbenchFindings(arguments_, dependencies) {
|
|
3803
4611
|
let offset;
|
|
3804
4612
|
do {
|
|
@@ -4085,10 +4893,57 @@ async function requireCleanPatchPullRequestBase(repository, base, dependencies)
|
|
|
4085
4893
|
}
|
|
4086
4894
|
}
|
|
4087
4895
|
async function changedPatchFiles(repository, base, dependencies) {
|
|
4896
|
+
if (base instanceof Map) {
|
|
4897
|
+
const head = await snapshotPatchDirectory(repository);
|
|
4898
|
+
return [...new Set([...base.keys(), ...head.keys()])]
|
|
4899
|
+
.filter((path) => base.get(path) !== head.get(path))
|
|
4900
|
+
.sort();
|
|
4901
|
+
}
|
|
4088
4902
|
const head = await snapshotPatchTree(repository, dependencies);
|
|
4089
4903
|
const output = await dependencies.runRepositoryCommand("git", ["--literal-pathspecs", "diff", "--name-only", "-z", base, head], repository, { trim: false });
|
|
4090
4904
|
return output.split("\0").filter(Boolean);
|
|
4091
4905
|
}
|
|
4906
|
+
async function snapshotPatchState(repository, dependencies) {
|
|
4907
|
+
try {
|
|
4908
|
+
await dependencies.runRepositoryCommand("git", ["rev-parse", "--show-toplevel"], repository, { environment: { LC_ALL: "C" } });
|
|
4909
|
+
}
|
|
4910
|
+
catch (error) {
|
|
4911
|
+
const message = errorMessage(error);
|
|
4912
|
+
if (!message.includes("not a git repository") &&
|
|
4913
|
+
message !== "git is not available on a trusted PATH.")
|
|
4914
|
+
throw error;
|
|
4915
|
+
return snapshotPatchDirectory(repository);
|
|
4916
|
+
}
|
|
4917
|
+
return snapshotPatchTree(repository, dependencies);
|
|
4918
|
+
}
|
|
4919
|
+
// Literal patch inputs also work in directories without Git metadata.
|
|
4920
|
+
async function snapshotPatchDirectory(repository) {
|
|
4921
|
+
const files = new Map();
|
|
4922
|
+
const visit = async (directory) => {
|
|
4923
|
+
for (const entry of await readdir(join(repository, directory), {
|
|
4924
|
+
withFileTypes: true,
|
|
4925
|
+
})) {
|
|
4926
|
+
if (entry.name === ".git")
|
|
4927
|
+
continue;
|
|
4928
|
+
const path = directory ? `${directory}/${entry.name}` : entry.name;
|
|
4929
|
+
const absolute = join(repository, path);
|
|
4930
|
+
if (entry.isDirectory()) {
|
|
4931
|
+
await visit(path);
|
|
4932
|
+
}
|
|
4933
|
+
else if (entry.isSymbolicLink()) {
|
|
4934
|
+
files.set(path, `link:${await readlink(absolute)}`);
|
|
4935
|
+
}
|
|
4936
|
+
else if (entry.isFile()) {
|
|
4937
|
+
const hash = createHash("sha256");
|
|
4938
|
+
for await (const chunk of createReadStream(absolute))
|
|
4939
|
+
hash.update(chunk);
|
|
4940
|
+
files.set(path, `${(await lstat(absolute)).mode & 0o111}:${hash.digest("hex")}`);
|
|
4941
|
+
}
|
|
4942
|
+
}
|
|
4943
|
+
};
|
|
4944
|
+
await visit("");
|
|
4945
|
+
return files;
|
|
4946
|
+
}
|
|
4092
4947
|
function safePatchText(value) {
|
|
4093
4948
|
return stripVTControlCharacters(safeErrorMessage(value)).replaceAll(/[\u0000-\u001F\u007F-\u009F\u2028\u2029]/gu, " ");
|
|
4094
4949
|
}
|
|
@@ -4174,6 +5029,8 @@ async function assessPatchRisk(request, stderr, dependencies) {
|
|
|
4174
5029
|
};
|
|
4175
5030
|
const status = await runSkill("assess-patch-risk", [], request.codexOverrides, request.effort, stdout, stderr, dependencies, {
|
|
4176
5031
|
directory: request.repository,
|
|
5032
|
+
auth: request.auth,
|
|
5033
|
+
environment: request.environment,
|
|
4177
5034
|
patchArtifact: {
|
|
4178
5035
|
path: patchPath,
|
|
4179
5036
|
repository: basename(resolve(request.repository)),
|
|
@@ -4216,6 +5073,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
|
|
|
4216
5073
|
stderr.write(`\nPatching ${selected.findings.length} confirmed finding${selected.findings.length === 1 ? "" : "s"}...\n`);
|
|
4217
5074
|
const patches = [];
|
|
4218
5075
|
for (const finding of selected.findings) {
|
|
5076
|
+
const base = await snapshotPatchState(selected.repository, dependencies);
|
|
4219
5077
|
let response = "";
|
|
4220
5078
|
const stdout = {
|
|
4221
5079
|
write(value) {
|
|
@@ -4235,6 +5093,7 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
|
|
|
4235
5093
|
if (status === 130 || status === 143) {
|
|
4236
5094
|
throw new CodexSecurityError("Patch operation was interrupted.");
|
|
4237
5095
|
}
|
|
5096
|
+
const changedFiles = await changedPatchFiles(selected.repository, base, dependencies);
|
|
4238
5097
|
const failed = (reason, files = []) => ({
|
|
4239
5098
|
occurrenceId: finding.occurrenceId,
|
|
4240
5099
|
status: "failed",
|
|
@@ -4263,6 +5122,10 @@ async function runFindingPatches(selected, codexOverrides, effort, stderr, depen
|
|
|
4263
5122
|
!parsed.data.verification?.trim()) {
|
|
4264
5123
|
patch = failed("Patch verification was not reported.", parsed.data.files);
|
|
4265
5124
|
}
|
|
5125
|
+
else if (parsed.data.status === "verified" &&
|
|
5126
|
+
changedFiles.length === 0) {
|
|
5127
|
+
patch = failed("No patch was applied; 0 files changed.");
|
|
5128
|
+
}
|
|
4266
5129
|
else {
|
|
4267
5130
|
patch = parsed.data;
|
|
4268
5131
|
}
|
|
@@ -4411,10 +5274,14 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
|
|
|
4411
5274
|
...(options.provider === undefined
|
|
4412
5275
|
? []
|
|
4413
5276
|
: ["--config", `model_provider=${JSON.stringify(options.provider)}`]),
|
|
4414
|
-
...
|
|
4415
|
-
|
|
4416
|
-
|
|
4417
|
-
|
|
5277
|
+
...(options.provider === undefined ||
|
|
5278
|
+
options.providerConfiguration === undefined
|
|
5279
|
+
? []
|
|
5280
|
+
: modelProviderConfigOverride(resolveCommandAuthConfig({
|
|
5281
|
+
model_providers: {
|
|
5282
|
+
[options.provider]: options.providerConfiguration,
|
|
5283
|
+
},
|
|
5284
|
+
}, configuredCodexHome(options.environment ?? dependencies.environment))).flatMap((value) => ["--config", value])),
|
|
4418
5285
|
"--config",
|
|
4419
5286
|
verify || assess
|
|
4420
5287
|
? 'approval_policy="on-request"'
|
|
@@ -4442,6 +5309,10 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
|
|
|
4442
5309
|
]),
|
|
4443
5310
|
], {
|
|
4444
5311
|
command: verify ? "verify-fix" : patch || assess ? "patch" : "validate",
|
|
5312
|
+
auth: options.auth ?? "auto",
|
|
5313
|
+
directory,
|
|
5314
|
+
modelProvider: options.provider,
|
|
5315
|
+
providerConfiguration: options.providerConfiguration,
|
|
4445
5316
|
stdout,
|
|
4446
5317
|
stderr,
|
|
4447
5318
|
...(appServer
|
|
@@ -4450,6 +5321,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
|
|
|
4450
5321
|
directory,
|
|
4451
5322
|
prompt,
|
|
4452
5323
|
threadSource,
|
|
5324
|
+
...(options.externalSandbox ? { externalSandbox: true } : {}),
|
|
4453
5325
|
...(verify || assess ? { sandbox: "read-only" } : {}),
|
|
4454
5326
|
...(options.onEvent === undefined
|
|
4455
5327
|
? {}
|
|
@@ -4457,7 +5329,7 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
|
|
|
4457
5329
|
},
|
|
4458
5330
|
}
|
|
4459
5331
|
: {}),
|
|
4460
|
-
}, options.environment, appServer ? undefined : prompt);
|
|
5332
|
+
}, options.environment ?? dependencies.environment, appServer ? undefined : prompt);
|
|
4461
5333
|
}
|
|
4462
5334
|
export async function readSkillCommandOutput(stream, appServer) {
|
|
4463
5335
|
let message;
|
|
@@ -4466,9 +5338,24 @@ export async function readSkillCommandOutput(stream, appServer) {
|
|
|
4466
5338
|
let threadId;
|
|
4467
5339
|
let turnId;
|
|
4468
5340
|
let completed = false;
|
|
5341
|
+
let sandboxUnavailable = false;
|
|
5342
|
+
const externalSandbox = appServer?.externalSandbox
|
|
5343
|
+
? { type: "externalSandbox", networkAccess: "enabled" }
|
|
5344
|
+
: undefined;
|
|
4469
5345
|
const send = (request) => {
|
|
4470
5346
|
appServer?.input.write(`${JSON.stringify(request)}\n`);
|
|
4471
5347
|
};
|
|
5348
|
+
const startTurn = () => {
|
|
5349
|
+
send({
|
|
5350
|
+
id: 3,
|
|
5351
|
+
method: "turn/start",
|
|
5352
|
+
params: {
|
|
5353
|
+
threadId: threadId,
|
|
5354
|
+
...(externalSandbox ? { sandboxPolicy: externalSandbox } : {}),
|
|
5355
|
+
input: [{ type: "text", text: appServer.prompt, text_elements: [] }],
|
|
5356
|
+
},
|
|
5357
|
+
});
|
|
5358
|
+
};
|
|
4472
5359
|
const startThread = (config) => {
|
|
4473
5360
|
if (appServer === undefined)
|
|
4474
5361
|
return;
|
|
@@ -4479,6 +5366,9 @@ export async function readSkillCommandOutput(stream, appServer) {
|
|
|
4479
5366
|
// Inherit the child process cwd and preserve the user's decision.
|
|
4480
5367
|
params: {
|
|
4481
5368
|
threadSource: appServer.threadSource,
|
|
5369
|
+
...(appServer.modelProvider === undefined
|
|
5370
|
+
? {}
|
|
5371
|
+
: { modelProvider: appServer.modelProvider }),
|
|
4482
5372
|
approvalPolicy: appServer?.sandbox === "read-only" ? "on-request" : "never",
|
|
4483
5373
|
sandbox: appServer?.sandbox ?? "workspace-write",
|
|
4484
5374
|
...(config === undefined ? {} : { config }),
|
|
@@ -4530,10 +5420,21 @@ export async function readSkillCommandOutput(stream, appServer) {
|
|
|
4530
5420
|
}
|
|
4531
5421
|
else if (value["error"] !== undefined) {
|
|
4532
5422
|
error = value["error"].message;
|
|
5423
|
+
sandboxUnavailable = value["id"] === 5;
|
|
4533
5424
|
appServer.input.end();
|
|
4534
5425
|
}
|
|
4535
|
-
else if (value["id"] === 1) {
|
|
4536
|
-
|
|
5426
|
+
else if (value["id"] === 1 || value["id"] === "login") {
|
|
5427
|
+
if (value["id"] === 1) {
|
|
5428
|
+
send({ method: "notifications/initialized" });
|
|
5429
|
+
if (appServer.apiKey !== undefined) {
|
|
5430
|
+
send({
|
|
5431
|
+
id: "login",
|
|
5432
|
+
method: "account/login/start",
|
|
5433
|
+
params: { type: "apiKey", apiKey: appServer.apiKey },
|
|
5434
|
+
});
|
|
5435
|
+
continue;
|
|
5436
|
+
}
|
|
5437
|
+
}
|
|
4537
5438
|
if (appServer.sandbox === "read-only") {
|
|
4538
5439
|
if (appServer.directory === undefined) {
|
|
4539
5440
|
error =
|
|
@@ -4610,17 +5511,32 @@ export async function readSkillCommandOutput(stream, appServer) {
|
|
|
4610
5511
|
});
|
|
4611
5512
|
}
|
|
4612
5513
|
else if (value["id"] === 2) {
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
4623
|
-
|
|
5514
|
+
await appServer.onThreadStarted?.();
|
|
5515
|
+
const result = value["result"];
|
|
5516
|
+
threadId = result.thread.id;
|
|
5517
|
+
if (appServer.threadSource === CODEX_SECURITY_THREAD_SOURCES.remediation) {
|
|
5518
|
+
send({
|
|
5519
|
+
id: 5,
|
|
5520
|
+
method: "command/exec",
|
|
5521
|
+
params: {
|
|
5522
|
+
command: [process.execPath, "-e", ""],
|
|
5523
|
+
cwd: appServer.directory,
|
|
5524
|
+
sandboxPolicy: externalSandbox ?? result.sandbox,
|
|
5525
|
+
},
|
|
5526
|
+
});
|
|
5527
|
+
continue;
|
|
5528
|
+
}
|
|
5529
|
+
startTurn();
|
|
5530
|
+
}
|
|
5531
|
+
else if (value["id"] === 5) {
|
|
5532
|
+
const result = value["result"];
|
|
5533
|
+
if (result.exitCode !== 0) {
|
|
5534
|
+
sandboxUnavailable = true;
|
|
5535
|
+
error = SANDBOX_UNAVAILABLE_MESSAGE;
|
|
5536
|
+
appServer.input.end();
|
|
5537
|
+
continue;
|
|
5538
|
+
}
|
|
5539
|
+
startTurn();
|
|
4624
5540
|
}
|
|
4625
5541
|
else if (value["id"] === 3) {
|
|
4626
5542
|
turnId = value["result"].turn.id;
|
|
@@ -4684,11 +5600,12 @@ export async function readSkillCommandOutput(stream, appServer) {
|
|
|
4684
5600
|
...(error === undefined ? {} : { error }),
|
|
4685
5601
|
malformed,
|
|
4686
5602
|
...(appServer === undefined ? {} : { completed }),
|
|
5603
|
+
...(sandboxUnavailable ? { sandboxUnavailable } : {}),
|
|
4687
5604
|
};
|
|
4688
5605
|
}
|
|
4689
|
-
export function skillCommandFailure(command, status, detail) {
|
|
5606
|
+
export function skillCommandFailure(command, status, detail, authentication = null) {
|
|
4690
5607
|
if (/401|invalid.api.key|token.expired|unauthori[sz]ed|authorizationrequired/iu.test(detail)) {
|
|
4691
|
-
return
|
|
5608
|
+
return authenticationFailureMessage(authentication);
|
|
4692
5609
|
}
|
|
4693
5610
|
if (/403|model.not.found|model.*access|access.*model|permission/iu.test(detail)) {
|
|
4694
5611
|
return "The selected model is unavailable for the current credentials.";
|
|
@@ -4719,9 +5636,6 @@ function incurErrorMessage(output) {
|
|
|
4719
5636
|
return message;
|
|
4720
5637
|
}
|
|
4721
5638
|
}
|
|
4722
|
-
function isOutsidePath(path) {
|
|
4723
|
-
return path === ".." || path.startsWith(`..${sep}`) || isAbsolute(path);
|
|
4724
|
-
}
|
|
4725
5639
|
async function runExport(arguments_, output, errorOutput, dependencies) {
|
|
4726
5640
|
try {
|
|
4727
5641
|
const canonicalScan = await realpath(arguments_.scanDir).catch(() => arguments_.scanDir);
|
|
@@ -4843,6 +5757,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4843
5757
|
let fileProgress = null;
|
|
4844
5758
|
let runningCost = null;
|
|
4845
5759
|
let maxCostUsd = arguments_.maxCostUsd;
|
|
5760
|
+
const showCost = arguments_.showCost === true || maxCostUsd !== undefined;
|
|
4846
5761
|
let phase = null;
|
|
4847
5762
|
const targetWarnings = [];
|
|
4848
5763
|
const configuredLogLevel = dependencies.environment["CODEX_SECURITY_LOG_LEVEL"]?.trim() ||
|
|
@@ -4918,7 +5833,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4918
5833
|
let preflight = null;
|
|
4919
5834
|
let effectiveModel = DEFAULT_SCAN_MODEL_CONFIGURATION.model;
|
|
4920
5835
|
let effectiveReasoningEffort = DEFAULT_SCAN_MODEL_CONFIGURATION.reasoningEffort;
|
|
4921
|
-
let providerOptions = {};
|
|
5836
|
+
let providerOptions = { provider: "openai" };
|
|
5837
|
+
let auth = arguments_.auth;
|
|
4922
5838
|
let patchAnalyticsOverride;
|
|
4923
5839
|
let selectedAuthentication = null;
|
|
4924
5840
|
let repository = "";
|
|
@@ -4927,13 +5843,12 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4927
5843
|
try {
|
|
4928
5844
|
const directory = dependencies.currentDirectory();
|
|
4929
5845
|
repository = arguments_.repository ?? directory;
|
|
4930
|
-
const target =
|
|
4931
|
-
const prompts = await
|
|
5846
|
+
const target = arguments_.target;
|
|
5847
|
+
const prompts = await resolveScanPrompts(arguments_, resolve(directory, repository), directory);
|
|
4932
5848
|
const config = {
|
|
4933
5849
|
pluginPath: arguments_.pluginPath,
|
|
4934
5850
|
pythonPath: arguments_.pythonPath,
|
|
4935
|
-
codexOverrides: arguments_.codexOverrides
|
|
4936
|
-
parseCodexOverrides(arguments_.codex, arguments_.model, arguments_.effort, arguments_.provider),
|
|
5851
|
+
codexOverrides: arguments_.codexOverrides,
|
|
4937
5852
|
};
|
|
4938
5853
|
const selectedProfileName = config.codexOverrides?.["profile"];
|
|
4939
5854
|
const effectiveConfiguration = {
|
|
@@ -4949,23 +5864,27 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4949
5864
|
analytics["enabled"] !== undefined) {
|
|
4950
5865
|
patchAnalyticsOverride = `analytics.enabled=${JSON.stringify(analytics["enabled"])}`;
|
|
4951
5866
|
}
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
5867
|
+
auth =
|
|
5868
|
+
!arguments_.dryRun && !arguments_.mock && interactive
|
|
5869
|
+
? await chooseInteractiveAuthentication({
|
|
5870
|
+
auth: arguments_.auth,
|
|
5871
|
+
provider,
|
|
5872
|
+
command: "scan",
|
|
5873
|
+
signal: preparationAbortController.signal,
|
|
5874
|
+
}, errorOutput, dependencies)
|
|
5875
|
+
: arguments_.auth;
|
|
5876
|
+
if (typeof provider === "string") {
|
|
4961
5877
|
providerOptions = {
|
|
4962
5878
|
provider,
|
|
4963
|
-
providerConfiguration: effectiveConfiguration["model_providers"]?.[provider]
|
|
5879
|
+
providerConfiguration: effectiveConfiguration["model_providers"]?.[provider] ??
|
|
5880
|
+
(isExternalModelProvider(provider)
|
|
5881
|
+
? EXTERNAL_CODEX_PROVIDERS[provider]
|
|
5882
|
+
: undefined),
|
|
4964
5883
|
};
|
|
4965
5884
|
}
|
|
4966
5885
|
selectedAuthentication = arguments_.mock
|
|
4967
5886
|
? null
|
|
4968
|
-
: scanAuthentication(dependencies.environment, auth, provider);
|
|
5887
|
+
: scanAuthentication(dependencies.environment, auth, provider, hasCommandAuth(effectiveConfiguration));
|
|
4969
5888
|
diagnostic("scan.configuration", {
|
|
4970
5889
|
cli_version: VERSION,
|
|
4971
5890
|
bundled_plugin_version: BUNDLED_PLUGIN_VERSION,
|
|
@@ -4973,14 +5892,14 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4973
5892
|
codex_sdk_version: CODEX_SDK_VERSION,
|
|
4974
5893
|
mode: arguments_.mode,
|
|
4975
5894
|
max_cost_usd: arguments_.maxCostUsd,
|
|
4976
|
-
target:
|
|
5895
|
+
target: Array.isArray(target) && target.length > 0
|
|
4977
5896
|
? "paths"
|
|
4978
|
-
:
|
|
5897
|
+
: target instanceof DiffTarget && target.kind === "refs"
|
|
4979
5898
|
? "diff"
|
|
4980
|
-
:
|
|
5899
|
+
: target instanceof DiffTarget
|
|
4981
5900
|
? "working_tree"
|
|
4982
5901
|
: "repository",
|
|
4983
|
-
requested_auth: auth ??
|
|
5902
|
+
requested_auth: auth ?? DEFAULT_SCAN_AUTH,
|
|
4984
5903
|
dry_run: arguments_.dryRun,
|
|
4985
5904
|
mock: arguments_.mock,
|
|
4986
5905
|
profile: typeof selectedProfileName === "string"
|
|
@@ -4997,6 +5916,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
4997
5916
|
dashboard = new ScanDashboard(errorOutput, {
|
|
4998
5917
|
repository,
|
|
4999
5918
|
mode: arguments_.mode,
|
|
5919
|
+
showCost,
|
|
5000
5920
|
model: scanModelConfiguration(await mergedCodexConfig(config)),
|
|
5001
5921
|
...(arguments_.maxCostUsd === undefined
|
|
5002
5922
|
? {}
|
|
@@ -5023,14 +5943,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5023
5943
|
details.push(`Files: ${fileProgress.filesCompleted.toLocaleString("en-US")}/${fileProgress.filesTotal.toLocaleString("en-US")}`);
|
|
5024
5944
|
}
|
|
5025
5945
|
if (runningCost !== null) {
|
|
5026
|
-
|
|
5027
|
-
|
|
5028
|
-
|
|
5029
|
-
output_tokens: runningCost.outputTokens,
|
|
5030
|
-
});
|
|
5031
|
-
if (tokens !== null)
|
|
5032
|
-
details.push(`Tokens: ${tokens}`);
|
|
5033
|
-
details.push(`Cost: ${formatUsd(runningCost.estimatedUsd)}`);
|
|
5946
|
+
details.push(`Tokens: ${formatScanCostTokens(runningCost)}`);
|
|
5947
|
+
if (showCost)
|
|
5948
|
+
details.push(`Cost: ${formatScanCost(runningCost)}`);
|
|
5034
5949
|
}
|
|
5035
5950
|
return details.length === 0 ? stage : `${stage} | ${details.join(" | ")}`;
|
|
5036
5951
|
};
|
|
@@ -5052,27 +5967,20 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5052
5967
|
errorOutput.write("codex-security: Mock scan: generating synthetic findings; no security analysis or LLM calls.\n");
|
|
5053
5968
|
}
|
|
5054
5969
|
const options = {
|
|
5970
|
+
...pickScanSettings(arguments_),
|
|
5971
|
+
...(arguments_.resumeScanId === undefined
|
|
5972
|
+
? {}
|
|
5973
|
+
: { resumeScanId: arguments_.resumeScanId }),
|
|
5055
5974
|
...(arguments_.mock ? { mock: true } : {}),
|
|
5056
5975
|
...(arguments_.workflowId === undefined
|
|
5057
5976
|
? {}
|
|
5058
5977
|
: { workflowId: arguments_.workflowId }),
|
|
5059
5978
|
auth,
|
|
5060
5979
|
safetyIdentifier: arguments_.safetyIdentifier,
|
|
5061
|
-
target,
|
|
5062
|
-
knowledgeBasePaths: arguments_.knowledgeBasePaths,
|
|
5063
5980
|
...prompts,
|
|
5064
|
-
mode: arguments_.mode,
|
|
5065
|
-
workers: arguments_.workers,
|
|
5066
|
-
subagents: arguments_.subagents,
|
|
5067
|
-
stopAfterNoNew: arguments_.stopAfterNoNew,
|
|
5068
|
-
maxDiscoveryRuns: arguments_.maxDiscoveryRuns,
|
|
5069
|
-
maxTimeHours: arguments_.maxTimeHours,
|
|
5070
|
-
outputDir: arguments_.outputDir,
|
|
5071
5981
|
archiveExisting: arguments_.archiveExisting,
|
|
5072
5982
|
parentScanId: arguments_.parentScanId,
|
|
5073
5983
|
expectedPluginVersion: arguments_.expectedPluginVersion,
|
|
5074
|
-
failureSeverity: arguments_.failOnSeverity,
|
|
5075
|
-
maxCostUsd: arguments_.maxCostUsd,
|
|
5076
5984
|
onCost: (cost, limit = maxCostUsd) => {
|
|
5077
5985
|
if (limit !== maxCostUsd && limit !== undefined) {
|
|
5078
5986
|
dashboard?.note(`Total cost limit increased to ${formatUsd(limit)}.`);
|
|
@@ -5080,7 +5988,8 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5080
5988
|
maxCostUsd = limit;
|
|
5081
5989
|
diagnostic("cost.updated", {
|
|
5082
5990
|
model: cost.model,
|
|
5083
|
-
estimated_usd: cost.estimatedUsd,
|
|
5991
|
+
estimated_usd: showCost ? cost.estimatedUsd : undefined,
|
|
5992
|
+
cost_estimate: showCost ? formatScanCost(cost) : undefined,
|
|
5084
5993
|
input_tokens: cost.inputTokens,
|
|
5085
5994
|
cached_input_tokens: cost.cachedInputTokens,
|
|
5086
5995
|
cache_write_input_tokens: cost.cacheWriteInputTokens,
|
|
@@ -5094,15 +6003,10 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5094
6003
|
}
|
|
5095
6004
|
progress?.stopTimer();
|
|
5096
6005
|
if (maxCostUsd === undefined) {
|
|
5097
|
-
|
|
5098
|
-
input_tokens: cost.inputTokens,
|
|
5099
|
-
cached_input_tokens: cost.cachedInputTokens,
|
|
5100
|
-
output_tokens: cost.outputTokens,
|
|
5101
|
-
});
|
|
5102
|
-
progress?.stage(`${tokens === null ? "" : `Tokens: ${tokens}. `}Estimated cost: ${formatUsd(cost.estimatedUsd)} USD.`);
|
|
6006
|
+
progress?.stage(`Tokens: ${formatScanCostTokens(cost)}.${showCost ? ` Estimated cost: ${formatScanCost(cost)}.` : ""}`);
|
|
5103
6007
|
}
|
|
5104
6008
|
else {
|
|
5105
|
-
progress?.stage(`Estimated cost: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`);
|
|
6009
|
+
progress?.stage(`Estimated cost: ${formatScanCost(cost)}; short-context budget baseline: ${formatUsd(cost.estimatedUsd)} of ${formatUsd(maxCostUsd)} limit`);
|
|
5106
6010
|
}
|
|
5107
6011
|
if (maxCostUsd === undefined || cost.estimatedUsd <= maxCostUsd) {
|
|
5108
6012
|
progress?.startTimer(runningMessage());
|
|
@@ -5128,7 +6032,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5128
6032
|
onAuthentication: (authentication) => {
|
|
5129
6033
|
selectedAuthentication = authentication;
|
|
5130
6034
|
diagnostic("authentication.selected", {
|
|
5131
|
-
requested: auth ??
|
|
6035
|
+
requested: auth ?? DEFAULT_SCAN_AUTH,
|
|
5132
6036
|
method: authentication.method,
|
|
5133
6037
|
source: "source" in authentication ? authentication.source : undefined,
|
|
5134
6038
|
verified: authentication.verified,
|
|
@@ -5258,11 +6162,10 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5258
6162
|
if (status.kind === "dispatch") {
|
|
5259
6163
|
dashboard.setStage(scanPhase(status.phase));
|
|
5260
6164
|
}
|
|
5261
|
-
|
|
5262
|
-
dashboard.note(message);
|
|
6165
|
+
dashboard.note(message);
|
|
5263
6166
|
return;
|
|
5264
6167
|
}
|
|
5265
|
-
if (
|
|
6168
|
+
if (progress === null)
|
|
5266
6169
|
return;
|
|
5267
6170
|
progress.stopTimer();
|
|
5268
6171
|
progress.stage(message);
|
|
@@ -5349,6 +6252,9 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5349
6252
|
partial_output: scanDir !== null,
|
|
5350
6253
|
max_cost_usd: costLimitFailure?.maxCostUsd,
|
|
5351
6254
|
estimated_usd: costLimitFailure?.cost.estimatedUsd,
|
|
6255
|
+
cost_estimate: costLimitFailure === undefined
|
|
6256
|
+
? undefined
|
|
6257
|
+
: formatScanCost(costLimitFailure.cost),
|
|
5352
6258
|
});
|
|
5353
6259
|
errorOutput.write(`${message}\n`);
|
|
5354
6260
|
if (failure instanceof ScanInterruptedError) {
|
|
@@ -5376,7 +6282,24 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5376
6282
|
verified: effectivePreflight.authentication.verified,
|
|
5377
6283
|
});
|
|
5378
6284
|
progress?.stopTimer();
|
|
5379
|
-
return {
|
|
6285
|
+
return {
|
|
6286
|
+
exitCode: 0,
|
|
6287
|
+
data: {
|
|
6288
|
+
dryRun: true,
|
|
6289
|
+
...effectivePreflight,
|
|
6290
|
+
...(arguments_.projectConfig === undefined
|
|
6291
|
+
? {}
|
|
6292
|
+
: {
|
|
6293
|
+
projectConfig: {
|
|
6294
|
+
...arguments_.projectConfig,
|
|
6295
|
+
sources: configurationSources(arguments_.projectConfig.sources, preflight.deepScanSources),
|
|
6296
|
+
},
|
|
6297
|
+
scanPromptFile: arguments_.scanPromptFile,
|
|
6298
|
+
validationPromptFile: arguments_.validationPromptFile,
|
|
6299
|
+
failOnSeverity: arguments_.failureSeverity,
|
|
6300
|
+
}),
|
|
6301
|
+
},
|
|
6302
|
+
};
|
|
5380
6303
|
}
|
|
5381
6304
|
if (result === null) {
|
|
5382
6305
|
diagnostic("scan.failed", {
|
|
@@ -5386,7 +6309,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5386
6309
|
errorOutput.write("scan completed without a result\n");
|
|
5387
6310
|
return { exitCode: 2, error: "Scan completed without a result." };
|
|
5388
6311
|
}
|
|
5389
|
-
const threshold = arguments_.
|
|
6312
|
+
const threshold = arguments_.failureSeverity;
|
|
5390
6313
|
const findings = result.findings.findings;
|
|
5391
6314
|
const actionableFindings = findings.filter((finding) => meetsSeverity(finding, "low"));
|
|
5392
6315
|
let scanData = targetWarnings.length === 0
|
|
@@ -5402,13 +6325,16 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5402
6325
|
progress?.stage(`Scan complete · ${result.manifest.scan.id.slice(0, 8)}`);
|
|
5403
6326
|
printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
|
|
5404
6327
|
dependencies.environment["NO_COLOR"] === undefined &&
|
|
5405
|
-
dependencies.environment["TERM"] !== "dumb", deepScanStop);
|
|
6328
|
+
dependencies.environment["TERM"] !== "dumb", showCost, deepScanStop);
|
|
5406
6329
|
const completedScan = (exitCode) => {
|
|
5407
6330
|
diagnostic("scan.completed", {
|
|
5408
6331
|
coverage: result.coverage.completeness,
|
|
5409
6332
|
findings: findings.length,
|
|
5410
6333
|
scan_id: result.manifest.scan.id,
|
|
5411
|
-
estimated_usd: result.cost?.estimatedUsd,
|
|
6334
|
+
estimated_usd: showCost ? result.cost?.estimatedUsd : undefined,
|
|
6335
|
+
cost_estimate: showCost && result.cost !== null
|
|
6336
|
+
? formatScanCost(result.cost)
|
|
6337
|
+
: undefined,
|
|
5412
6338
|
exit_code: exitCode,
|
|
5413
6339
|
});
|
|
5414
6340
|
progress?.stopTimer();
|
|
@@ -5425,7 +6351,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5425
6351
|
return completedScan(2);
|
|
5426
6352
|
}
|
|
5427
6353
|
let patchThreshold = arguments_.patch
|
|
5428
|
-
? arguments_.patchSeverity ?? "low"
|
|
6354
|
+
? (arguments_.patchSeverity ?? "low")
|
|
5429
6355
|
: undefined;
|
|
5430
6356
|
let patchSelection = null;
|
|
5431
6357
|
if (!arguments_.mock &&
|
|
@@ -5463,15 +6389,6 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5463
6389
|
(patchSelection === null ||
|
|
5464
6390
|
patchSelection.occurrenceIds.includes(finding.occurrenceId))),
|
|
5465
6391
|
};
|
|
5466
|
-
const environment = { ...dependencies.environment };
|
|
5467
|
-
if (selectedAuthentication?.method === "stored_credentials") {
|
|
5468
|
-
for (const name of Object.keys(environment)) {
|
|
5469
|
-
if (["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase())) {
|
|
5470
|
-
delete environment[name];
|
|
5471
|
-
}
|
|
5472
|
-
}
|
|
5473
|
-
environment["CODEX_HOME"] = codexSecurityCredentialHome(dependencies.environment);
|
|
5474
|
-
}
|
|
5475
6392
|
try {
|
|
5476
6393
|
patches = await runFindingPatches(selected, [
|
|
5477
6394
|
`model=${JSON.stringify(effectiveModel)}`,
|
|
@@ -5481,7 +6398,7 @@ async function executeScan(arguments_, errorOutput, dependencies, interactive =
|
|
|
5481
6398
|
], effectiveReasoningEffort, errorOutput, dependencies, {
|
|
5482
6399
|
...providerOptions,
|
|
5483
6400
|
safetyIdentifier: arguments_.safetyIdentifier,
|
|
5484
|
-
|
|
6401
|
+
auth,
|
|
5485
6402
|
findingInstructions: patchSelection?.instructions,
|
|
5486
6403
|
});
|
|
5487
6404
|
scanData = { ...scanData, patchSeverity: patchThreshold, patches };
|
|
@@ -5545,6 +6462,36 @@ function isLocalScanFailure(error) {
|
|
|
5545
6462
|
typeof error.code === "string" &&
|
|
5546
6463
|
LOCAL_SYSCALL_CODES.has(error.code));
|
|
5547
6464
|
}
|
|
6465
|
+
function authenticationFailureMessage(authentication) {
|
|
6466
|
+
if (authentication?.method === "command") {
|
|
6467
|
+
return "Native Codex command authentication failed. Check the configured provider auth command.";
|
|
6468
|
+
}
|
|
6469
|
+
if (authentication?.method === "aws_credentials") {
|
|
6470
|
+
return (`Authentication failed using AWS credentials from ${authentication.source}. ` +
|
|
6471
|
+
"Check your Amazon Bedrock bearer token or AWS credential chain.");
|
|
6472
|
+
}
|
|
6473
|
+
if (authentication?.method === "stored_credentials" &&
|
|
6474
|
+
authentication.credentialType === "api_key") {
|
|
6475
|
+
return ("Authentication failed using a stored API key. " +
|
|
6476
|
+
"Sign in again with 'codex-security login --with-api-key' or provide a valid API key.");
|
|
6477
|
+
}
|
|
6478
|
+
if (authentication?.method === "api_key") {
|
|
6479
|
+
const openAiKey = authentication.source === "OPENAI_API_KEY" ||
|
|
6480
|
+
authentication.source === "CODEX_API_KEY";
|
|
6481
|
+
return (`Authentication failed using ${authentication.source}. ` +
|
|
6482
|
+
(openAiKey
|
|
6483
|
+
? "Retry with '--auth chatgpt' or provide a valid API key."
|
|
6484
|
+
: `Provide a valid ${authentication.source} for the selected provider.`));
|
|
6485
|
+
}
|
|
6486
|
+
if (authentication?.method === "stored_credentials") {
|
|
6487
|
+
return authentication.credentialType === "chatgpt"
|
|
6488
|
+
? "Authentication failed using stored ChatGPT credentials. " +
|
|
6489
|
+
"Sign in again with 'codex-security login' or provide a valid API key."
|
|
6490
|
+
: "Authentication failed using stored credentials. " +
|
|
6491
|
+
"Check 'codex-security login status' and refresh the stored login or provide a valid API key.";
|
|
6492
|
+
}
|
|
6493
|
+
return "Authentication failed. Check the selected provider's credentials and retry.";
|
|
6494
|
+
}
|
|
5548
6495
|
function scanFailureMessage(error, authentication) {
|
|
5549
6496
|
// A local failure keeps its own message. Classification matches bare words
|
|
5550
6497
|
// such as "permission denied" anywhere in the text, so an EACCES from a
|
|
@@ -5568,18 +6515,7 @@ function scanFailureMessage(error, authentication) {
|
|
|
5568
6515
|
}
|
|
5569
6516
|
switch (classifyConnectionFailure(error)) {
|
|
5570
6517
|
case "unauthorized":
|
|
5571
|
-
|
|
5572
|
-
return "Native Codex command authentication failed. Check the configured provider auth command.";
|
|
5573
|
-
}
|
|
5574
|
-
if (authentication?.method === "aws_credentials") {
|
|
5575
|
-
return (`Authentication failed using AWS credentials from ${authentication.source}. ` +
|
|
5576
|
-
"Check your Amazon Bedrock bearer token or AWS credential chain.");
|
|
5577
|
-
}
|
|
5578
|
-
return authentication?.method === "api_key"
|
|
5579
|
-
? `Authentication failed using ${authentication.source}. ` +
|
|
5580
|
-
"Retry with '--auth chatgpt' or provide a valid API key."
|
|
5581
|
-
: "Authentication failed using stored ChatGPT credentials. " +
|
|
5582
|
-
"Sign in again with 'codex-security login' or provide a valid API key.";
|
|
6518
|
+
return authenticationFailureMessage(authentication);
|
|
5583
6519
|
case "forbidden":
|
|
5584
6520
|
if (authentication?.method === "command") {
|
|
5585
6521
|
return "The configured Codex provider denied access. Check the command credentials and provider permissions.";
|
|
@@ -5602,8 +6538,11 @@ function scanFailureMessage(error, authentication) {
|
|
|
5602
6538
|
}
|
|
5603
6539
|
}
|
|
5604
6540
|
function scanScope(arguments_) {
|
|
5605
|
-
|
|
5606
|
-
|
|
6541
|
+
const paths = Array.isArray(arguments_.target)
|
|
6542
|
+
? arguments_.target
|
|
6543
|
+
: [];
|
|
6544
|
+
if (paths.length > 0) {
|
|
6545
|
+
const displayed = paths.slice(0, 3).map((path) => {
|
|
5607
6546
|
const portable = path.replaceAll("\\", "/");
|
|
5608
6547
|
const scoped = isAbsolute(path) ||
|
|
5609
6548
|
/^[A-Za-z]:\//u.test(portable) ||
|
|
@@ -5612,12 +6551,12 @@ function scanScope(arguments_) {
|
|
|
5612
6551
|
: portable;
|
|
5613
6552
|
return errorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
|
|
5614
6553
|
});
|
|
5615
|
-
return `${displayed.join(", ")}${
|
|
6554
|
+
return `${displayed.join(", ")}${paths.length > displayed.length ? `, +${paths.length - displayed.length} more` : ""}`;
|
|
5616
6555
|
}
|
|
5617
|
-
if (arguments_.
|
|
5618
|
-
return
|
|
5619
|
-
|
|
5620
|
-
|
|
6556
|
+
if (arguments_.target instanceof DiffTarget)
|
|
6557
|
+
return arguments_.target.kind === "refs"
|
|
6558
|
+
? "committed changes"
|
|
6559
|
+
: "working-tree changes";
|
|
5621
6560
|
return null;
|
|
5622
6561
|
}
|
|
5623
6562
|
async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
|
|
@@ -5665,7 +6604,7 @@ async function readDeepScanStop(result, maxCostUsd, runWorkbench) {
|
|
|
5665
6604
|
reason: "Stopped before the review finished. See the report for details.",
|
|
5666
6605
|
};
|
|
5667
6606
|
}
|
|
5668
|
-
function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
|
|
6607
|
+
function printScanSummary(result, progress, errorOutput, color, showCost, deepScanStop) {
|
|
5669
6608
|
const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
|
|
5670
6609
|
const repositoryFindings = result.repositoryFindings;
|
|
5671
6610
|
const findings = repositoryFindings ?? result.findings.findings;
|
|
@@ -5685,7 +6624,7 @@ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
|
|
|
5685
6624
|
Number.isFinite(completed) &&
|
|
5686
6625
|
completed >= started
|
|
5687
6626
|
? Math.floor((completed - started) / 1_000)
|
|
5688
|
-
: progress?.elapsedSeconds ?? 0;
|
|
6627
|
+
: (progress?.elapsedSeconds ?? 0);
|
|
5689
6628
|
const duration = elapsed < 60
|
|
5690
6629
|
? `${elapsed}s`
|
|
5691
6630
|
: `${Math.floor(elapsed / 60)}m ${elapsed % 60}s`;
|
|
@@ -5713,35 +6652,18 @@ function printScanSummary(result, progress, errorOutput, color, deepScanStop) {
|
|
|
5713
6652
|
if (tokenSummary !== null) {
|
|
5714
6653
|
errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);
|
|
5715
6654
|
}
|
|
5716
|
-
if (
|
|
5717
|
-
|
|
6655
|
+
if (showCost) {
|
|
6656
|
+
const costSummary = result.cost === null
|
|
6657
|
+
? "unavailable (model pricing or usage missing)"
|
|
6658
|
+
: formatScanCost(result.cost);
|
|
6659
|
+
errorOutput.write(` ${paint("COST", 1)} ${costSummary}\n`);
|
|
5718
6660
|
}
|
|
5719
6661
|
errorOutput.write(` ${paint("RESULTS", 1)} ${errorMessage(result.scanDir)}\n`);
|
|
5720
6662
|
if (deepScanStop?.nextStep !== undefined) {
|
|
5721
6663
|
errorOutput.write(`\n ${deepScanStop.nextStep}\n`);
|
|
5722
6664
|
}
|
|
5723
6665
|
}
|
|
5724
|
-
function
|
|
5725
|
-
if (usage === null || typeof usage !== "object")
|
|
5726
|
-
return null;
|
|
5727
|
-
const values = usage;
|
|
5728
|
-
return ([
|
|
5729
|
-
["input_tokens", "input"],
|
|
5730
|
-
["cached_input_tokens", "cached"],
|
|
5731
|
-
["output_tokens", "output"],
|
|
5732
|
-
]
|
|
5733
|
-
.map(([key, label]) => {
|
|
5734
|
-
const value = values[key];
|
|
5735
|
-
return typeof value === "number" &&
|
|
5736
|
-
Number.isSafeInteger(value) &&
|
|
5737
|
-
value >= 0
|
|
5738
|
-
? `${value.toLocaleString("en-US")} ${label}`
|
|
5739
|
-
: null;
|
|
5740
|
-
})
|
|
5741
|
-
.filter((value) => value !== null)
|
|
5742
|
-
.join(", ") || null);
|
|
5743
|
-
}
|
|
5744
|
-
function componentScanEventLine(componentName, event) {
|
|
6666
|
+
function componentScanEventLine(componentName, event, showCost) {
|
|
5745
6667
|
if (event.type === "progress") {
|
|
5746
6668
|
const progress = event.value;
|
|
5747
6669
|
return `codex-security: ${componentName} ${scanPhase(progress.phase)} | Files: ${progress.filesCompleted.toLocaleString("en-US")}/${progress.filesTotal.toLocaleString("en-US")}\n`;
|
|
@@ -5749,12 +6671,7 @@ function componentScanEventLine(componentName, event) {
|
|
|
5749
6671
|
if (event.type !== "cost")
|
|
5750
6672
|
return null;
|
|
5751
6673
|
const cost = event.value;
|
|
5752
|
-
|
|
5753
|
-
input_tokens: cost.inputTokens,
|
|
5754
|
-
cached_input_tokens: cost.cachedInputTokens,
|
|
5755
|
-
output_tokens: cost.outputTokens,
|
|
5756
|
-
});
|
|
5757
|
-
return `codex-security: ${componentName} | ${tokens === null ? "" : `Tokens: ${tokens} | `}Cost: ${formatUsd(cost.estimatedUsd)}\n`;
|
|
6674
|
+
return `codex-security: ${componentName} | Tokens: ${formatScanCostTokens(cost)}${showCost ? ` | Cost: ${formatScanCost(cost)}` : ""}\n`;
|
|
5758
6675
|
}
|
|
5759
6676
|
function protectedRootErrorMessage(error) {
|
|
5760
6677
|
const description = error.pathKind === "output"
|
|
@@ -5816,21 +6733,67 @@ function quoteCliPath(path) {
|
|
|
5816
6733
|
? `"${path}"`
|
|
5817
6734
|
: `'${path.replaceAll("'", `'"'"'`)}'`;
|
|
5818
6735
|
}
|
|
5819
|
-
function
|
|
5820
|
-
|
|
5821
|
-
|
|
5822
|
-
|
|
5823
|
-
|
|
5824
|
-
|
|
5825
|
-
|
|
5826
|
-
|
|
5827
|
-
}
|
|
5828
|
-
|
|
5829
|
-
|
|
6736
|
+
async function selectedProjectConfig(file, dependencies) {
|
|
6737
|
+
const selected = file ??
|
|
6738
|
+
environmentValue(dependencies.environment, "CODEX_SECURITY_PROJECT_CONFIG");
|
|
6739
|
+
return selected === undefined
|
|
6740
|
+
? undefined
|
|
6741
|
+
: readProjectConfig(selected, dependencies.currentDirectory());
|
|
6742
|
+
}
|
|
6743
|
+
function resolveCliScope(configured, overrides) {
|
|
6744
|
+
const sources = {};
|
|
6745
|
+
const explicitScopes = Number(!!overrides.paths?.length) +
|
|
6746
|
+
Number(overrides.diff !== undefined) +
|
|
6747
|
+
Number(overrides.workingTree === true);
|
|
6748
|
+
if (explicitScopes > 1)
|
|
6749
|
+
throw new ConfigurationError("--path, --diff, and --working-tree are mutually exclusive.");
|
|
6750
|
+
if (explicitScopes === 0 &&
|
|
6751
|
+
overrides.workingTree !== false &&
|
|
6752
|
+
overrides.head === undefined &&
|
|
6753
|
+
overrides.base === undefined) {
|
|
6754
|
+
return { sources };
|
|
6755
|
+
}
|
|
6756
|
+
let scope = configured;
|
|
6757
|
+
let changed = false;
|
|
6758
|
+
sources["scan.scope"] = scope === undefined ? "default" : "project";
|
|
6759
|
+
if (overrides.paths?.length)
|
|
6760
|
+
scope = { paths: overrides.paths };
|
|
6761
|
+
else if (overrides.diff !== undefined)
|
|
6762
|
+
scope = { diff: { base: overrides.diff } };
|
|
6763
|
+
else if (overrides.workingTree === true)
|
|
6764
|
+
scope = { working_tree: {} };
|
|
6765
|
+
else if (overrides.workingTree === false &&
|
|
6766
|
+
scope !== undefined &&
|
|
6767
|
+
"working_tree" in scope) {
|
|
6768
|
+
scope = undefined;
|
|
6769
|
+
changed = true;
|
|
6770
|
+
}
|
|
6771
|
+
if (explicitScopes > 0 || changed) {
|
|
6772
|
+
changed = true;
|
|
6773
|
+
sources["scan.scope"] = "cli";
|
|
6774
|
+
}
|
|
6775
|
+
// A ref-only override refines the selected project scope; it does not take
|
|
6776
|
+
// ownership of the whole scope variant.
|
|
6777
|
+
if (overrides.head !== undefined) {
|
|
6778
|
+
if (scope === undefined || !("diff" in scope))
|
|
6779
|
+
throw new ConfigurationError("--head requires --diff.");
|
|
6780
|
+
scope = { diff: { ...scope.diff, head: overrides.head } };
|
|
6781
|
+
sources["scan.scope.diff.head"] = "cli";
|
|
6782
|
+
changed = true;
|
|
6783
|
+
}
|
|
6784
|
+
if (overrides.base !== undefined) {
|
|
6785
|
+
if (scope === undefined || !("working_tree" in scope))
|
|
6786
|
+
throw new ConfigurationError("--base requires --working-tree.");
|
|
6787
|
+
scope = { working_tree: { base: overrides.base } };
|
|
6788
|
+
sources["scan.scope.working_tree.base"] = "cli";
|
|
6789
|
+
changed = true;
|
|
5830
6790
|
}
|
|
5831
|
-
return
|
|
6791
|
+
return {
|
|
6792
|
+
...(changed ? { target: projectScopeTarget(scope) ?? "repository" } : {}),
|
|
6793
|
+
sources,
|
|
6794
|
+
};
|
|
5832
6795
|
}
|
|
5833
|
-
export function parseCodexOverrides(values, model, effort, provider) {
|
|
6796
|
+
export function parseCodexOverrides(values, model, effort, provider, defaults) {
|
|
5834
6797
|
const result = Object.create(null);
|
|
5835
6798
|
if (model !== undefined)
|
|
5836
6799
|
result["model"] = model;
|
|
@@ -5897,9 +6860,13 @@ export function parseCodexOverrides(values, model, effort, provider) {
|
|
|
5897
6860
|
}
|
|
5898
6861
|
cursor[final] = parsed;
|
|
5899
6862
|
}
|
|
5900
|
-
if (
|
|
5901
|
-
|
|
5902
|
-
|
|
6863
|
+
if (isExternalModelProvider(provider) || provider === "amazon-bedrock") {
|
|
6864
|
+
const selectedModel = scanModel(mergeCodexOverrides(defaults ?? {}, result));
|
|
6865
|
+
if (typeof selectedModel !== "string" || !selectedModel.trim()) {
|
|
6866
|
+
throw new CodexSecurityError(selectedModel === undefined
|
|
6867
|
+
? `--model is required when using --provider ${provider}`
|
|
6868
|
+
: `--model must be a nonempty string when using --provider ${provider}`);
|
|
6869
|
+
}
|
|
5903
6870
|
}
|
|
5904
6871
|
return result;
|
|
5905
6872
|
}
|