@openai/codex-security 0.1.23 → 0.1.25

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.
Files changed (135) hide show
  1. package/README.md +200 -23
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +1 -0
  4. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  6. package/_bundled_plugin/references/scan-contract.md +10 -0
  7. package/_bundled_plugin/scripts/deep_scan_workbench.py +6 -1
  8. package/_bundled_plugin/scripts/finalize_scan_contract.py +27 -78
  9. package/_bundled_plugin/scripts/generate_in_scope_files.py +2 -8
  10. package/_bundled_plugin/scripts/generate_rank_input.py +1 -5
  11. package/_bundled_plugin/scripts/rank_preview.py +12 -1
  12. package/_bundled_plugin/scripts/report_projection.py +8 -14
  13. package/_bundled_plugin/scripts/validate_scan_contract.py +1 -3
  14. package/_bundled_plugin/scripts/windows_scan_local_files.py +5 -15
  15. package/_bundled_plugin/scripts/workbench_cli.py +14 -1
  16. package/_bundled_plugin/scripts/workbench_dashboard.py +41 -18
  17. package/_bundled_plugin/scripts/workbench_db.py +127 -541
  18. package/_bundled_plugin/scripts/workbench_finding_workflows.py +31 -13
  19. package/_bundled_plugin/scripts/workbench_findings.py +8 -3
  20. package/_bundled_plugin/scripts/workbench_native_indexes.py +1 -2
  21. package/_bundled_plugin/scripts/workbench_publication.py +520 -0
  22. package/_bundled_plugin/scripts/workbench_remediation.py +37 -0
  23. package/_bundled_plugin/scripts/workbench_saved_results.py +298 -90
  24. package/_bundled_plugin/scripts/workbench_scan_history.py +375 -68
  25. package/_bundled_plugin/scripts/workbench_scan_usage.py +9 -33
  26. package/_bundled_plugin/scripts/workbench_schema.py +49 -21
  27. package/_bundled_plugin/scripts/workbench_target.py +96 -17
  28. package/_bundled_plugin/scripts/workbench_validation.py +1 -5
  29. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +1 -5
  30. package/_bundled_plugin/skills/attack-path-analysis/references/severity-policy.md +6 -1
  31. package/dist/api.d.ts +18 -3
  32. package/dist/api.d.ts.map +1 -1
  33. package/dist/api.js +350 -28
  34. package/dist/api.js.map +1 -1
  35. package/dist/auth.d.ts.map +1 -1
  36. package/dist/auth.js +35 -3
  37. package/dist/auth.js.map +1 -1
  38. package/dist/cli.d.ts +2 -0
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +118 -35
  41. package/dist/cli.js.map +1 -1
  42. package/dist/component-plan.d.ts.map +1 -1
  43. package/dist/component-plan.js +4 -2
  44. package/dist/component-plan.js.map +1 -1
  45. package/dist/component-scan.d.ts.map +1 -1
  46. package/dist/component-scan.js +21 -6
  47. package/dist/component-scan.js.map +1 -1
  48. package/dist/config.d.ts.map +1 -1
  49. package/dist/config.js +46 -2
  50. package/dist/config.js.map +1 -1
  51. package/dist/cost.d.ts +1 -0
  52. package/dist/cost.d.ts.map +1 -1
  53. package/dist/cost.js +23 -11
  54. package/dist/cost.js.map +1 -1
  55. package/dist/deduplication/checkpointed-review.d.ts.map +1 -1
  56. package/dist/deduplication/checkpointed-review.js +2 -1
  57. package/dist/deduplication/checkpointed-review.js.map +1 -1
  58. package/dist/deduplication/codex-review.d.ts +3 -0
  59. package/dist/deduplication/codex-review.d.ts.map +1 -1
  60. package/dist/deduplication/codex-review.js +122 -36
  61. package/dist/deduplication/codex-review.js.map +1 -1
  62. package/dist/deduplication/deduplication-prompts.d.ts +4 -3
  63. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -1
  64. package/dist/deduplication/deduplication-prompts.js +18 -9
  65. package/dist/deduplication/deduplication-prompts.js.map +1 -1
  66. package/dist/deduplication/deduplication-reviewer.d.ts +2 -7
  67. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  68. package/dist/deduplication/deduplication-reviewer.js +46 -24
  69. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  70. package/dist/deduplication/deduplication.d.ts.map +1 -1
  71. package/dist/deduplication/deduplication.js +186 -23
  72. package/dist/deduplication/deduplication.js.map +1 -1
  73. package/dist/deduplication/scan.d.ts +9 -1
  74. package/dist/deduplication/scan.d.ts.map +1 -1
  75. package/dist/deduplication/scan.js +24 -7
  76. package/dist/deduplication/scan.js.map +1 -1
  77. package/dist/deep-progress.d.ts +21 -0
  78. package/dist/deep-progress.d.ts.map +1 -0
  79. package/dist/deep-progress.js +108 -0
  80. package/dist/deep-progress.js.map +1 -0
  81. package/dist/errors.d.ts +13 -0
  82. package/dist/errors.d.ts.map +1 -1
  83. package/dist/errors.js +7 -0
  84. package/dist/errors.js.map +1 -1
  85. package/dist/index.d.ts +6 -5
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +2 -2
  88. package/dist/index.js.map +1 -1
  89. package/dist/mock-scan.d.ts +4 -0
  90. package/dist/mock-scan.d.ts.map +1 -0
  91. package/dist/mock-scan.js +210 -0
  92. package/dist/mock-scan.js.map +1 -0
  93. package/dist/publish.d.ts.map +1 -1
  94. package/dist/publish.js +2 -2
  95. package/dist/publish.js.map +1 -1
  96. package/dist/runtime.d.ts +1 -0
  97. package/dist/runtime.d.ts.map +1 -1
  98. package/dist/runtime.js +54 -14
  99. package/dist/runtime.js.map +1 -1
  100. package/dist/scan-activity.d.ts.map +1 -1
  101. package/dist/scan-activity.js +12 -2
  102. package/dist/scan-activity.js.map +1 -1
  103. package/dist/scan-comparison.d.ts +11 -2
  104. package/dist/scan-comparison.d.ts.map +1 -1
  105. package/dist/scan-comparison.js +237 -39
  106. package/dist/scan-comparison.js.map +1 -1
  107. package/dist/scan-dashboard.d.ts +3 -1
  108. package/dist/scan-dashboard.d.ts.map +1 -1
  109. package/dist/scan-dashboard.js +70 -3
  110. package/dist/scan-dashboard.js.map +1 -1
  111. package/dist/scan-history-renderer.d.ts.map +1 -1
  112. package/dist/scan-history-renderer.js +21 -0
  113. package/dist/scan-history-renderer.js.map +1 -1
  114. package/dist/server/api.d.ts +6 -0
  115. package/dist/server/api.d.ts.map +1 -0
  116. package/dist/server/api.js +4 -0
  117. package/dist/server/api.js.map +1 -0
  118. package/dist/server/dashboard/app.css +1 -1
  119. package/dist/server/embeddings.d.ts +2 -1
  120. package/dist/server/embeddings.d.ts.map +1 -1
  121. package/dist/server/embeddings.js +8 -3
  122. package/dist/server/embeddings.js.map +1 -1
  123. package/dist/server/index.js +2 -28
  124. package/dist/server/index.js.map +1 -1
  125. package/dist/server/serve.d.ts +2 -0
  126. package/dist/server/serve.d.ts.map +1 -0
  127. package/dist/server/serve.js +28 -0
  128. package/dist/server/serve.js.map +1 -0
  129. package/dist/targets.d.ts.map +1 -1
  130. package/dist/targets.js +3 -5
  131. package/dist/targets.js.map +1 -1
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/version.js.map +1 -1
  135. package/package.json +10 -5
package/dist/api.js CHANGED
@@ -1,15 +1,17 @@
1
1
  /// <reference lib="esnext.disposable" preserve="true" />
2
- import { chmod, lstat, mkdir, readFile, realpath, rm, writeFile, } from "node:fs/promises";
2
+ import { statSync } from "node:fs";
3
+ import { chmod, lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile, } from "node:fs/promises";
3
4
  import { randomUUID } from "node:crypto";
4
5
  import { homedir, tmpdir } from "node:os";
5
- import { basename, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
6
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep, } from "node:path";
6
7
  import { Codex, } from "@openai/codex-sdk";
7
8
  import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
8
9
  import { z } from "incur";
9
- import { accountStatus, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
10
+ import { accountStatus, configuredCodexHome, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
10
11
  import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
11
- import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
12
- import { estimateScanCost, ScanCostTracker, sumTokenUsage, } from "./cost.js";
12
+ import { DEFAULT_CODEX_CONFIG, EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, hasCommandAuth, mergedCodexConfig, modelProviderConfigOverride, resolveCommandAuthConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
13
+ import { estimateScanCost, ScanCostTracker, } from "./cost.js";
14
+ import { DeepScanProgressTracker, } from "./deep-progress.js";
13
15
  import { loadContract, readScanFile, requireScanFile, } from "./contract.js";
14
16
  import { runCustomValidation, writeCustomValidationStatus, } from "./custom-validation.js";
15
17
  import { customDiscoveryPrompt, customValidationConfig, } from "./custom-validation-prompt.js";
@@ -17,12 +19,13 @@ import { AuthenticationRequiredError, CodexSecurityError, ConfigurationError, In
17
19
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
18
20
  import { FindingWorkflow, workflowDigest } from "./finding-workflow.js";
19
21
  import { ScanResult, } from "./result.js";
22
+ import { writeMockScanDraft } from "./mock-scan.js";
20
23
  import { scanActivitiesFromEvent } from "./scan-activity.js";
21
24
  import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
22
25
  import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
23
26
  import { CODEX_SECURITY_THREAD_SOURCES } from "./thread-source.js";
24
27
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
25
- import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
28
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, bundledPluginRoot, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, executablePathForSpawn, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, pluginMetadata, planOutputArchive, prepareScanArtifactRestorer, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
26
29
  import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
27
30
  const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT = "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
28
31
  const VALIDATION_DISPOSITIONS = [
@@ -277,7 +280,7 @@ export class CodexSecurity {
277
280
  : {}),
278
281
  outputDir: inputs.outputDir,
279
282
  ...(archiveDir === null ? {} : { archiveDir }),
280
- authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider),
283
+ authentication: scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, hasCommandAuth(configuration)),
281
284
  ...model,
282
285
  ...(typeof modelProvider === "string" ? { modelProvider } : {}),
283
286
  ...(options.maxCostUsd === undefined
@@ -287,17 +290,28 @@ export class CodexSecurity {
287
290
  }
288
291
  async #run(repository, options) {
289
292
  this.#requireOpen();
293
+ if (options.mock)
294
+ return await this.#runMock(repository, options);
290
295
  const costAbortController = new AbortController();
291
296
  const signal = AbortSignal.any([
292
297
  this.#abortController.signal,
293
298
  costAbortController.signal,
294
299
  ...(options.signal === undefined ? [] : [options.signal]),
295
300
  ]);
301
+ const budgetAbortController = new AbortController();
302
+ const budgetSignal = AbortSignal.any([
303
+ signal,
304
+ budgetAbortController.signal,
305
+ ]);
306
+ let maxCostUsd = options.maxCostUsd;
307
+ let latestCost = null;
308
+ let notifiedLimit;
296
309
  let scanDir = "";
297
310
  let archivedScanDir = null;
298
311
  let targetPathsFile = null;
299
312
  let knowledgeBase = null;
300
313
  let costTracker = null;
314
+ let deepProgressTracker = null;
301
315
  let releaseCredentialHome = null;
302
316
  let scanFailure = false;
303
317
  let customValidationComplete = false;
@@ -428,11 +442,56 @@ export class CodexSecurity {
428
442
  onCost: options.onCost === undefined && options.maxCostUsd === undefined
429
443
  ? undefined
430
444
  : (cost) => {
431
- notifyObserver("onCost", options.onCost, options.onObserverError, cost);
432
- if (options.maxCostUsd !== undefined &&
433
- cost.estimatedUsd > options.maxCostUsd) {
434
- costAbortController.abort(new ScanCostLimitExceededError(options.maxCostUsd, cost, scanDir));
445
+ latestCost = cost;
446
+ notifyObserver("onCost", options.onCost, options.onObserverError, cost, maxCostUsd);
447
+ if (maxCostUsd !== undefined &&
448
+ cost.estimatedUsd > maxCostUsd) {
449
+ costAbortController.abort(new ScanCostLimitExceededError(maxCostUsd, cost, scanDir));
450
+ return;
435
451
  }
452
+ const request = options.onBudgetApproaching;
453
+ if (request === undefined ||
454
+ maxCostUsd === undefined ||
455
+ budgetSignal.aborted ||
456
+ notifiedLimit === maxCostUsd ||
457
+ cost.estimatedUsd < maxCostUsd * 0.8)
458
+ return;
459
+ const limit = maxCostUsd;
460
+ notifiedLimit = limit;
461
+ void Promise.resolve()
462
+ .then(async () => {
463
+ if (budgetSignal.aborted)
464
+ return;
465
+ const next = await request({
466
+ maxCostUsd: limit,
467
+ cost,
468
+ signal: budgetSignal,
469
+ });
470
+ if (next === undefined ||
471
+ budgetSignal.aborted ||
472
+ activeScan === null)
473
+ return;
474
+ if (!Number.isFinite(next) ||
475
+ next <= Math.max(limit, latestCost.estimatedUsd)) {
476
+ throw new CodexSecurityError("The new cost limit must exceed the current limit and estimated cost.");
477
+ }
478
+ await workbench({ ...activeScan.options, signal: budgetSignal }, [
479
+ "set-scan-cost-limit",
480
+ "--scan-id",
481
+ activeScan.id,
482
+ "--max-cost-usd",
483
+ String(next),
484
+ ]);
485
+ if (budgetSignal.aborted)
486
+ return;
487
+ maxCostUsd = next;
488
+ notifyObserver("onCost", options.onCost, options.onObserverError, latestCost, maxCostUsd);
489
+ })
490
+ .catch((error) => {
491
+ if (!budgetSignal.aborted) {
492
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not increase scan cost limit: ${errorMessage(error)}`);
493
+ }
494
+ });
436
495
  },
437
496
  onError: reportTrackingError,
438
497
  });
@@ -526,6 +585,23 @@ export class CodexSecurity {
526
585
  });
527
586
  }
528
587
  activeScan = { id: scanId, options: workbenchOptions };
588
+ if (mode === "deep" && options.onDeepProgress !== undefined) {
589
+ let progressWarningReported = false;
590
+ deepProgressTracker = new DeepScanProgressTracker({
591
+ read: (progressSignal) => workbench({
592
+ ...workbenchOptions,
593
+ signal: AbortSignal.any([signal, progressSignal]),
594
+ }, ["get-scan", "--scan-id", scanId]),
595
+ onProgress: (progress) => notifyObserver("onDeepProgress", options.onDeepProgress, options.onObserverError, progress),
596
+ onError: (error) => {
597
+ if (progressWarningReported)
598
+ return;
599
+ progressWarningReported = true;
600
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not track Deep Scan progress: ${errorMessage(error)}`);
601
+ },
602
+ });
603
+ deepProgressTracker.start();
604
+ }
529
605
  if (options.validationPrompt !== undefined) {
530
606
  await writeCustomValidationStatus(scanDir, { scanId, status: "pending" }, signal);
531
607
  }
@@ -653,6 +729,9 @@ export class CodexSecurity {
653
729
  },
654
730
  onFinalize: async (usage) => {
655
731
  if (options.validationPrompt !== undefined) {
732
+ tracker.recordUsage(usage);
733
+ await tracker.refresh().catch(reportTrackingError);
734
+ checkOpen();
656
735
  await runCustomValidation({
657
736
  repository: repo,
658
737
  target: normalized,
@@ -687,12 +766,16 @@ export class CodexSecurity {
687
766
  if (turn.status !== "completed")
688
767
  throw new IncompleteScanError(turn.lastStreamError ??
689
768
  "The custom validation turn did not complete.");
690
- usage = sumTokenUsage(usage, turn.usage);
769
+ budgetAbortController.abort();
770
+ tracker.recordUsage(turn.usage, turn.threadId);
771
+ await tracker.refresh().catch(reportTrackingError);
772
+ checkOpen();
691
773
  return turn.finalResponse;
692
774
  },
693
775
  });
694
776
  customValidationComplete = true;
695
777
  }
778
+ budgetAbortController.abort();
696
779
  const snapshot = await tracker.stop(usage).catch((error) => {
697
780
  if (options.maxCostUsd !== undefined)
698
781
  throw error;
@@ -848,6 +931,7 @@ export class CodexSecurity {
848
931
  matchFindings: this.#dependencies.matchFindings ??
849
932
  ((input, comparisonOptions) => matchScanFindingsInternal(input, comparisonOptions, {
850
933
  surface: this.#surface,
934
+ allowBatching: false,
851
935
  })),
852
936
  environment,
853
937
  model,
@@ -866,9 +950,14 @@ export class CodexSecurity {
866
950
  // scan, and cleanup must treat all of those as a failure it is not allowed to mask.
867
951
  scanFailure = true;
868
952
  const snapshot = await costTracker?.stop().catch(() => null);
869
- const failure = signal.reason instanceof ScanCostLimitExceededError
953
+ let failure = signal.reason instanceof ScanCostLimitExceededError
870
954
  ? signal.reason
871
955
  : error;
956
+ if (failure instanceof ScanCostLimitExceededError &&
957
+ snapshot?.cost &&
958
+ snapshot.cost.estimatedUsd > failure.cost.estimatedUsd) {
959
+ failure = new ScanCostLimitExceededError(failure.maxCostUsd, snapshot.cost, scanDir);
960
+ }
872
961
  if (failure instanceof ScanCostLimitExceededError &&
873
962
  budgetRecovery !== null &&
874
963
  budgetRecovery.threadId !== null &&
@@ -961,6 +1050,8 @@ export class CodexSecurity {
961
1050
  throw failure;
962
1051
  }
963
1052
  finally {
1053
+ budgetAbortController.abort();
1054
+ deepProgressTracker?.stop();
964
1055
  // Removing the temporary scan inputs is best effort. A throw here would replace the
965
1056
  // outcome the try and catch blocks already produced, so these failures are reported
966
1057
  // as warnings: a scan that failed has to say why it failed, not why its temporary
@@ -1030,6 +1121,9 @@ export class CodexSecurity {
1030
1121
  }
1031
1122
  const authentication = await this.#authentication();
1032
1123
  this.#requireOpen();
1124
+ const ambientHome = environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
1125
+ join(homedir(), ".codex");
1126
+ await initialCredentialsAvailable(this.#dependencies.environment, ambientHome, authentication.codexHome);
1033
1127
  return await accountStatus(this.#codexCommand(), authentication.environment, this.#abortController.signal);
1034
1128
  });
1035
1129
  }
@@ -1128,8 +1222,11 @@ export class CodexSecurity {
1128
1222
  }
1129
1223
  #createSessionCodex(session, runtimePaths, auth = "auto") {
1130
1224
  const { runtime, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
1225
+ const commandAuth = hasCommandAuth(sessionConfig);
1131
1226
  const environment = {
1132
- ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, auth, modelProvider))),
1227
+ ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(commandAuth
1228
+ ? withoutOpenAiApiKeys(runtime.environment)
1229
+ : runtime.environment, auth, modelProvider))),
1133
1230
  ...(externalProvider === null
1134
1231
  ? {}
1135
1232
  : { [externalProvider.env_key]: apiKey }),
@@ -1148,17 +1245,29 @@ export class CodexSecurity {
1148
1245
  // cannot safely encode their path and selector keys as dotted overrides.
1149
1246
  delete sdkCodexConfig["projects"];
1150
1247
  delete sdkCodexConfig["permissions"];
1248
+ if (commandAuth)
1249
+ delete sdkCodexConfig["model_providers"];
1151
1250
  const configuredResponsesMetadata = isRecord(sdkCodexConfig["responses_api_metadata"])
1152
1251
  ? sdkCodexConfig["responses_api_metadata"]
1153
1252
  : {};
1154
- const codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
1253
+ let codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
1155
1254
  undefined
1156
1255
  ? undefined
1157
1256
  : this.#codexCommand().command;
1257
+ let sdkEnvironment = definedEnvironment(withoutOpenAiApiKeys(environment));
1258
+ if (process.platform === "win32" && codexPathOverride === undefined) {
1259
+ codexPathOverride = environment["CODEX_CLI_PATH"];
1260
+ sdkEnvironment = bundledCodexSdkEnvironment(codexPathOverride, sdkEnvironment);
1261
+ }
1158
1262
  const codex = this.#dependencies.createCodex({
1159
- ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
1263
+ ...(codexPathOverride === undefined
1264
+ ? {}
1265
+ : { codexPathOverride: executablePathForSpawn(codexPathOverride) }),
1160
1266
  ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
1161
- env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
1267
+ ...(commandAuth
1268
+ ? { configOverrides: modelProviderConfigOverride(sessionConfig) }
1269
+ : {}),
1270
+ env: sdkEnvironment,
1162
1271
  config: {
1163
1272
  ...sdkCodexConfig,
1164
1273
  responses_api_metadata: {
@@ -1176,19 +1285,22 @@ export class CodexSecurity {
1176
1285
  throwIfAborted(signal);
1177
1286
  };
1178
1287
  try {
1179
- const requestedConfig = await mergedCodexConfig(this.config);
1288
+ const requestedConfig = resolveCommandAuthConfig(await mergedCodexConfig(this.config), configuredCodexHome(this.#dependencies.environment));
1289
+ const commandAuth = hasCommandAuth(requestedConfig);
1180
1290
  const modelProvider = scanModelProvider(requestedConfig);
1181
- const externalProvider = isExternalModelProvider(modelProvider)
1291
+ const externalProvider = !commandAuth && isExternalModelProvider(modelProvider)
1182
1292
  ? EXTERNAL_CODEX_PROVIDERS[modelProvider]
1183
1293
  : null;
1184
- let authentication = scanAuthentication(this.#dependencies.environment, options.auth, modelProvider);
1294
+ let authentication = scanAuthentication(this.#dependencies.environment, options.auth, modelProvider, commandAuth);
1185
1295
  const apiKey = authentication.method === "api_key"
1186
1296
  ? environmentApiKey(this.#dependencies.environment, modelProvider)
1187
1297
  : null;
1188
1298
  if (externalProvider !== null && apiKey === null) {
1189
1299
  throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`);
1190
1300
  }
1191
- const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth, modelProvider);
1301
+ const scanEnvironment = selectedScanEnvironment(commandAuth
1302
+ ? withoutOpenAiApiKeys(this.#dependencies.environment)
1303
+ : this.#dependencies.environment, options.auth, modelProvider);
1192
1304
  if (this.#dependencies.prepareRuntime === undefined) {
1193
1305
  const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
1194
1306
  releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
@@ -1239,12 +1351,14 @@ export class CodexSecurity {
1239
1351
  }
1240
1352
  if (!runtime.credentialsAvailable &&
1241
1353
  apiKey === null &&
1354
+ !commandAuth &&
1242
1355
  authentication.method !== "aws_credentials") {
1243
1356
  throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
1244
1357
  "'codex-security login --device-auth' on a remote or headless machine, or set " +
1245
1358
  "OPENAI_API_KEY or CODEX_API_KEY for CI.");
1246
1359
  }
1247
- authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
1360
+ if (!commandAuth)
1361
+ authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
1248
1362
  if (options.safetyIdentifier !== undefined &&
1249
1363
  authentication.method !== "api_key" &&
1250
1364
  !(authentication.method === "stored_credentials" &&
@@ -1332,7 +1446,165 @@ export class CodexSecurity {
1332
1446
  : undefined;
1333
1447
  runtime.effectiveConfig = mergedConfig;
1334
1448
  }
1449
+ async #runMock(repository, options) {
1450
+ const signal = AbortSignal.any([
1451
+ this.#abortController.signal,
1452
+ ...(options.signal ? [options.signal] : []),
1453
+ ]);
1454
+ const local = await this.#validateLocalInputs(repository, options, signal);
1455
+ const temporaryRoot = await realpath(tmpdir());
1456
+ requireOutputOutsideRepository(local.protectedRoot, temporaryRoot, "temporary");
1457
+ const workspace = await mkdtemp(join(temporaryRoot, "codex-security-mock-"));
1458
+ const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
1459
+ let activeScan;
1460
+ let scanDir = "";
1461
+ try {
1462
+ const pluginRoot = await resolvePluginPath(this.config.pluginPath, workspace, signal);
1463
+ const plugin = await pluginMetadata(pluginRoot);
1464
+ if (options.expectedPluginVersion !== undefined &&
1465
+ options.expectedPluginVersion !== plugin.version) {
1466
+ throw new CodexSecurityError("The selected plugin version does not match the expected plugin version.");
1467
+ }
1468
+ const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
1469
+ configuredPath: this.config.pythonPath,
1470
+ environment: this.#dependencies.environment,
1471
+ protectedRoot: local.protectedRoot,
1472
+ signal,
1473
+ });
1474
+ if (options.knowledgeBasePaths?.length) {
1475
+ const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal);
1476
+ await knowledgeBase.cleanup();
1477
+ }
1478
+ const outputRoot = local.outputDir === null
1479
+ ? await preparePersistentOutputRoot(local.stateDirectory, "scans", basename(local.repository))
1480
+ : undefined;
1481
+ let archivedScanDir;
1482
+ scanDir = await prepareOutputDir(local.outputDir ?? undefined, basename(local.repository), outputRoot, (path) => requireOutputOutsideRepository(local.protectedRoot, path), options.archiveExisting, (path) => {
1483
+ archivedScanDir = path;
1484
+ notifyObserver("onOutputArchived", options.onOutputArchived, options.onObserverError, path);
1485
+ });
1486
+ requireModelSafeOutputDir(scanDir);
1487
+ notifyObserver("onOutputDirReady", options.onOutputDirReady, options.onObserverError, scanDir);
1488
+ const revision = await repositoryRevision(local.repository, signal);
1489
+ const { model } = scanModelConfiguration({
1490
+ ...DEFAULT_CODEX_CONFIG,
1491
+ ...this.config.codexOverrides,
1492
+ });
1493
+ const workbenchOptions = {
1494
+ python,
1495
+ pluginRoot,
1496
+ environment: {
1497
+ ...this.#dependencies.environment,
1498
+ CODEX_SECURITY_STATE_DIR: local.stateDirectory,
1499
+ },
1500
+ signal,
1501
+ failureMessage: "Could not save the mock scan",
1502
+ };
1503
+ const registration = await workbench(workbenchOptions, [
1504
+ "register-cli-scan",
1505
+ "--repository",
1506
+ local.repository,
1507
+ "--scan-dir",
1508
+ scanDir,
1509
+ "--registration-json-stdin",
1510
+ ...(options.archiveExisting ? ["--archive-existing"] : []),
1511
+ ...(archivedScanDir === undefined
1512
+ ? []
1513
+ : ["--archived-scan-dir", archivedScanDir]),
1514
+ ...(options.parentScanId === undefined
1515
+ ? []
1516
+ : ["--parent-scan-id", options.parentScanId]),
1517
+ ], JSON.stringify({
1518
+ recipe: {
1519
+ ...scanRecipe(local.repository, local.target, local.mode, revision, plugin.version, { model }, options.failureSeverity, options.knowledgeBasePaths, options.maxCostUsd),
1520
+ mock: true,
1521
+ },
1522
+ userContext: options.scanPrompt,
1523
+ ...(options.workflowId === undefined
1524
+ ? {}
1525
+ : { workflowId: options.workflowId }),
1526
+ }));
1527
+ const scanId = registration["scanId"];
1528
+ const targetId = registration["targetId"];
1529
+ if (typeof scanId !== "string" ||
1530
+ typeof targetId !== "string" ||
1531
+ registration["scanDir"] !== scanDir) {
1532
+ throw new CodexSecurityError("The workbench returned an invalid mock scan registration.");
1533
+ }
1534
+ activeScan = { id: scanId, options: workbenchOptions };
1535
+ notifyObserver("onScanStarted", options.onScanStarted, options.onObserverError);
1536
+ await writeMockScanDraft(scanDir, scanId, local.target, registration, signal);
1537
+ const usage = {
1538
+ input_tokens: 0,
1539
+ cached_input_tokens: 0,
1540
+ output_tokens: 0,
1541
+ };
1542
+ const cost = estimateScanCost(model, usage);
1543
+ await workbench(workbenchOptions, [
1544
+ "prepare-scan-completion",
1545
+ "--scan-id",
1546
+ scanId,
1547
+ ]);
1548
+ const completion = await workbench(workbenchOptions, [
1549
+ "complete-scan",
1550
+ "--scan-id",
1551
+ scanId,
1552
+ ...(cost === null ? [] : ["--cost-json", JSON.stringify(cost)]),
1553
+ ]);
1554
+ activeScan = undefined;
1555
+ const completedScan = completion["scan"];
1556
+ if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
1557
+ for (const warning of completedScan["warnings"]) {
1558
+ if (typeof warning === "string")
1559
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, warning, Array.isArray(completion["targetWarnings"]) &&
1560
+ completion["targetWarnings"].includes(warning)
1561
+ ? { kind: "target_changed" }
1562
+ : undefined);
1563
+ }
1564
+ }
1565
+ const result = await collectResult({
1566
+ status: "completed",
1567
+ model,
1568
+ usage,
1569
+ mock: true,
1570
+ finalResponse: "Synthetic mock scan; no security analysis was performed.",
1571
+ }, "", scanDir, pluginRoot, {
1572
+ repository: local.repository,
1573
+ repositoryRevision: revision,
1574
+ target: local.target,
1575
+ mode: local.mode,
1576
+ pluginVersion: plugin.version,
1577
+ }, signal, true);
1578
+ // Stable fixture identities are indexed by complete-scan without model matching.
1579
+ result.repositoryFindings = (await listRepositoryFindings((args) => workbench(workbenchOptions, args), targetId));
1580
+ return result;
1581
+ }
1582
+ catch (error) {
1583
+ if (activeScan !== undefined) {
1584
+ await workbench({ ...activeScan.options, signal: undefined }, [
1585
+ "fail-scan",
1586
+ "--scan-id",
1587
+ activeScan.id,
1588
+ "--message",
1589
+ safeErrorMessage(error).slice(0, 2400),
1590
+ ]).catch(() => undefined);
1591
+ }
1592
+ if (this.#closed)
1593
+ this.#requireOpen();
1594
+ throwIfAborted(signal, scanDir);
1595
+ throw error;
1596
+ }
1597
+ finally {
1598
+ await cleanupSdkDirectory(workspace);
1599
+ }
1600
+ }
1335
1601
  async #validateLocalInputs(repository, options, signal) {
1602
+ if (options.mock &&
1603
+ (options.mode === "deep" ||
1604
+ options.validationPrompt !== undefined ||
1605
+ options.postScanPrompt !== undefined)) {
1606
+ throw new CodexSecurityError("Mock scans support Standard mode without custom validation or post-scan prompts; those workflows require model calls.");
1607
+ }
1336
1608
  deepScanOptions(options);
1337
1609
  const identifier = options.safetyIdentifier;
1338
1610
  if (identifier !== undefined &&
@@ -1403,7 +1675,9 @@ export class CodexSecurity {
1403
1675
  const modelProvider = requestedConfig === undefined
1404
1676
  ? undefined
1405
1677
  : scanModelProvider(requestedConfig);
1406
- const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth, modelProvider);
1678
+ const processEnvironment = selectedScanEnvironment(requestedConfig !== undefined && hasCommandAuth(requestedConfig)
1679
+ ? withoutOpenAiApiKeys(this.#dependencies.environment)
1680
+ : this.#dependencies.environment, auth, modelProvider);
1407
1681
  const codexHome = validateLocation === undefined
1408
1682
  ? await prepareCodexSecurityCredentialHome(processEnvironment)
1409
1683
  : await realpath(codexSecurityCredentialHome(processEnvironment));
@@ -1428,7 +1702,8 @@ export class CodexSecurity {
1428
1702
  const deepScanConfigPath = (await pluginSupportsIsolatedDeepScanConfig(plugin.pluginRoot))
1429
1703
  ? join(bootstrapWorkspace, "deep-scan-config.toml")
1430
1704
  : undefined;
1431
- const credentialsAvailable = isExternalModelProvider(modelProvider) ||
1705
+ const credentialsAvailable = hasCommandAuth(mergedConfig) ||
1706
+ isExternalModelProvider(modelProvider) ||
1432
1707
  modelProvider === "amazon-bedrock"
1433
1708
  ? false
1434
1709
  : await initialCredentialsAvailable(processEnvironment, ambientHome, codexHome);
@@ -1967,10 +2242,12 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
1967
2242
  sarifPath,
1968
2243
  });
1969
2244
  }
1970
- export function scanAuthentication(environment, auth = "auto", modelProvider) {
2245
+ export function scanAuthentication(environment, auth = "auto", modelProvider, commandAuth = false) {
1971
2246
  if (!SCAN_AUTH_MODES.includes(auth)) {
1972
2247
  throw new TypeError("Scan authentication mode must be auto, chatgpt, or api-key.");
1973
2248
  }
2249
+ if (commandAuth)
2250
+ return { method: "command", verified: false };
1974
2251
  if (modelProvider === "amazon-bedrock") {
1975
2252
  const sources = [
1976
2253
  "AWS_BEARER_TOKEN_BEDROCK",
@@ -2001,6 +2278,19 @@ export function scanAuthentication(environment, auth = "auto", modelProvider) {
2001
2278
  ? { method: "stored_credentials", verified: false }
2002
2279
  : { method: "api_key", source: key.source, verified: false };
2003
2280
  }
2281
+ /** Shell-neutral guidance so PowerShell users are not told to run POSIX `unset`. */
2282
+ export function formatEnvironmentVariableRemovalGuidance(names) {
2283
+ if (names.length === 0) {
2284
+ return "remove OPENAI_API_KEY and CODEX_API_KEY from the environment";
2285
+ }
2286
+ if (names.length === 1) {
2287
+ return `remove ${names[0]} from the environment`;
2288
+ }
2289
+ if (names.length === 2) {
2290
+ return `remove ${names[0]} and ${names[1]} from the environment`;
2291
+ }
2292
+ return `remove ${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]} from the environment`;
2293
+ }
2004
2294
  async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
2005
2295
  const authentication = scanAuthentication(environment, auth, modelProvider);
2006
2296
  if (authentication.method !== "stored_credentials")
@@ -2031,10 +2321,8 @@ export function selectedScanEnvironment(environment, auth = "auto", modelProvide
2031
2321
  if (auth !== "chatgpt" && selectedProviderKey === null && !bedrockProvider) {
2032
2322
  return environment;
2033
2323
  }
2034
- return Object.fromEntries(Object.entries(environment).filter(([name]) => {
2324
+ return Object.fromEntries(Object.entries(withoutOpenAiApiKeys(environment)).filter(([name]) => {
2035
2325
  const key = name.toUpperCase();
2036
- if (key === "OPENAI_API_KEY" || key === "CODEX_API_KEY")
2037
- return false;
2038
2326
  if (key === "OPENROUTER_API_KEY" || key === "FIREWORKS_API_KEY") {
2039
2327
  return (!bedrockProvider &&
2040
2328
  (selectedProviderKey === null || key === selectedProviderKey));
@@ -2042,6 +2330,9 @@ export function selectedScanEnvironment(environment, auth = "auto", modelProvide
2042
2330
  return true;
2043
2331
  }));
2044
2332
  }
2333
+ function withoutOpenAiApiKeys(environment) {
2334
+ return Object.fromEntries(Object.entries(environment).filter(([name]) => !["OPENAI_API_KEY", "CODEX_API_KEY"].includes(name.toUpperCase())));
2335
+ }
2045
2336
  function notifyObserver(observerName, observer, onObserverError, ...args) {
2046
2337
  void Promise.resolve()
2047
2338
  .then(() => observer?.(...args))
@@ -2179,6 +2470,12 @@ function sharedCredentialCodexConfig(config, credentialHome) {
2179
2470
  shared[key] = structuredClone(config[key]);
2180
2471
  }
2181
2472
  const modelProvider = scanModelProvider(config);
2473
+ if (hasCommandAuth(config)) {
2474
+ for (const key of ["profile", "profiles"]) {
2475
+ if (Object.hasOwn(config, key))
2476
+ shared[key] = structuredClone(config[key]);
2477
+ }
2478
+ }
2182
2479
  if (typeof modelProvider === "string" && modelProvider.length > 0) {
2183
2480
  shared["model_provider"] = modelProvider;
2184
2481
  const providers = config["model_providers"];
@@ -2353,6 +2650,31 @@ function throwIfAborted(signal, scanDir = "") {
2353
2650
  : "Codex Security scan was interrupted during preparation.";
2354
2651
  throw new ScanInterruptedError(message, scanDir, { cause: signal.reason });
2355
2652
  }
2653
+ function bundledCodexSdkEnvironment(command, environment) {
2654
+ // An SDK executable override disables its bundled-tool PATH setup.
2655
+ const toolsDirectory = join(dirname(dirname(command)), "codex-path");
2656
+ try {
2657
+ if (!statSync(toolsDirectory).isDirectory())
2658
+ return environment;
2659
+ }
2660
+ catch {
2661
+ return environment;
2662
+ }
2663
+ const result = { ...environment };
2664
+ const pathKeys = Object.keys(result).filter((key) => key.toLowerCase() === "path");
2665
+ const pathKey = pathKeys.includes("Path")
2666
+ ? "Path"
2667
+ : pathKeys.at(-1) ?? "PATH";
2668
+ for (const key of pathKeys) {
2669
+ if (key !== pathKey)
2670
+ delete result[key];
2671
+ }
2672
+ const entries = (result[pathKey] ?? "")
2673
+ .split(delimiter)
2674
+ .filter((entry) => entry.length > 0 && entry !== toolsDirectory);
2675
+ result[pathKey] = [toolsDirectory, ...entries].join(delimiter);
2676
+ return result;
2677
+ }
2356
2678
  function definedEnvironment(environment) {
2357
2679
  return Object.fromEntries(Object.entries(environment).filter((entry) => entry[1] !== undefined));
2358
2680
  }