@openai/codex-security 0.1.5 → 0.1.6

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 (94) hide show
  1. package/README.md +79 -8
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/.mcp.json +8 -1
  4. package/_bundled_plugin/mcp/mcp-app.html.br +0 -0
  5. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  6. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  7. package/_bundled_plugin/preflight/capability-profiles.toml +0 -57
  8. package/_bundled_plugin/references/config-preflight.md +1 -1
  9. package/_bundled_plugin/references/final-report.md +15 -7
  10. package/_bundled_plugin/references/scan-artifacts.md +11 -9
  11. package/_bundled_plugin/references/scan-contract.md +3 -1
  12. package/_bundled_plugin/schemas/definitions/artifact-common.schema.json +42 -0
  13. package/_bundled_plugin/schemas/definitions/discovery-candidate.schema.json +100 -0
  14. package/_bundled_plugin/schemas/tools/candidate-attack-paths.schema.json +181 -0
  15. package/_bundled_plugin/schemas/tools/candidate-validations.schema.json +166 -0
  16. package/_bundled_plugin/schemas/tools/deep-reducer.schema.json +120 -0
  17. package/_bundled_plugin/schemas/tools/discovery-candidates.schema.json +83 -0
  18. package/_bundled_plugin/schemas/tools/review-items.schema.json +80 -0
  19. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +572 -0
  20. package/_bundled_plugin/schemas/tools/worker-threat-model.schema.json +18 -0
  21. package/_bundled_plugin/scripts/deep_scan_config.py +11 -3
  22. package/_bundled_plugin/scripts/deep_scan_workbench.py +153 -133
  23. package/_bundled_plugin/scripts/finalize_scan_contract.py +21 -0
  24. package/_bundled_plugin/scripts/generate_in_scope_files.py +134 -0
  25. package/_bundled_plugin/scripts/workbench_cli.py +33 -1
  26. package/_bundled_plugin/scripts/workbench_db.py +127 -117
  27. package/_bundled_plugin/scripts/workbench_feedback.py +2 -0
  28. package/_bundled_plugin/scripts/workbench_native_indexes.py +5 -49
  29. package/_bundled_plugin/scripts/workbench_progress.py +86 -3
  30. package/_bundled_plugin/scripts/workbench_remediation.py +19 -1
  31. package/_bundled_plugin/scripts/workbench_scan_history.py +7 -1
  32. package/_bundled_plugin/scripts/workbench_scan_start.py +11 -5
  33. package/_bundled_plugin/scripts/workbench_scan_usage.py +557 -0
  34. package/_bundled_plugin/scripts/workbench_schema.py +501 -0
  35. package/_bundled_plugin/scripts/workbench_validation.py +117 -13
  36. package/_bundled_plugin/skills/attack-path-analysis/SKILL.md +4 -4
  37. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +34 -28
  38. package/_bundled_plugin/skills/finding-discovery/SKILL.md +1 -1
  39. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +11 -8
  40. package/_bundled_plugin/skills/security-scan/SKILL.md +16 -9
  41. package/_bundled_plugin/skills/security-scan/references/repository-wide-scan.md +26 -14
  42. package/_bundled_plugin/skills/security-scan/references/scan-artifacts-and-ledger.md +1 -1
  43. package/_bundled_plugin/skills/threat-model/SKILL.md +2 -2
  44. package/_bundled_plugin/skills/validation/SKILL.md +5 -5
  45. package/_bundled_plugin/skills/vulnerability-writeup/SKILL.md +145 -227
  46. package/_bundled_plugin/skills/vulnerability-writeup/references/report-format.md +53 -68
  47. package/dist/api.d.ts +29 -7
  48. package/dist/api.d.ts.map +1 -1
  49. package/dist/api.js +323 -47
  50. package/dist/api.js.map +1 -1
  51. package/dist/auth.js +1 -1
  52. package/dist/auth.js.map +1 -1
  53. package/dist/cli.d.ts +3 -2
  54. package/dist/cli.d.ts.map +1 -1
  55. package/dist/cli.js +458 -40
  56. package/dist/cli.js.map +1 -1
  57. package/dist/config.d.ts +28 -0
  58. package/dist/config.d.ts.map +1 -1
  59. package/dist/config.js +39 -2
  60. package/dist/config.js.map +1 -1
  61. package/dist/cost.d.ts +7 -0
  62. package/dist/cost.d.ts.map +1 -1
  63. package/dist/cost.js +345 -17
  64. package/dist/cost.js.map +1 -1
  65. package/dist/index.d.ts +3 -2
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.js.map +1 -1
  68. package/dist/multiscan.d.ts +1 -0
  69. package/dist/multiscan.d.ts.map +1 -1
  70. package/dist/multiscan.js +3 -0
  71. package/dist/multiscan.js.map +1 -1
  72. package/dist/runtime.d.ts +16 -0
  73. package/dist/runtime.d.ts.map +1 -1
  74. package/dist/runtime.js +540 -25
  75. package/dist/runtime.js.map +1 -1
  76. package/dist/scan-activity.d.ts +13 -0
  77. package/dist/scan-activity.d.ts.map +1 -0
  78. package/dist/scan-activity.js +319 -0
  79. package/dist/scan-activity.js.map +1 -0
  80. package/dist/scan-dashboard.d.ts +47 -0
  81. package/dist/scan-dashboard.d.ts.map +1 -0
  82. package/dist/scan-dashboard.js +444 -0
  83. package/dist/scan-dashboard.js.map +1 -0
  84. package/dist/scan-history-renderer.d.ts.map +1 -1
  85. package/dist/scan-history-renderer.js +4 -1
  86. package/dist/scan-history-renderer.js.map +1 -1
  87. package/dist/version.d.ts +1 -1
  88. package/dist/version.js +1 -1
  89. package/dist/version.js.map +1 -1
  90. package/dist/worker-progress.d.ts +7 -0
  91. package/dist/worker-progress.d.ts.map +1 -1
  92. package/dist/worker-progress.js +68 -0
  93. package/dist/worker-progress.js.map +1 -1
  94. package/package.json +3 -3
package/dist/api.js CHANGED
@@ -1,17 +1,19 @@
1
1
  /// <reference lib="esnext.disposable" preserve="true" />
2
- import { chmod, lstat, mkdir, realpath, rm, writeFile } from "node:fs/promises";
2
+ import { chmod, lstat, mkdir, readFile, realpath, rm, writeFile, } from "node:fs/promises";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import { basename, dirname, isAbsolute, join, relative, sep } from "node:path";
6
6
  import { Codex } from "@openai/codex-sdk";
7
+ import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
7
8
  import { accountStatus, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
8
- import { mergedCodexConfig, scanModelConfiguration, writeCodexConfig, } from "./config.js";
9
+ import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, writeCodexConfig, } from "./config.js";
9
10
  import { estimateScanCost, ScanCostTracker } from "./cost.js";
10
11
  import { loadContract, requireScanFile, } from "./contract.js";
11
12
  import { AuthenticationRequiredError, CodexSecurityError, IncompleteScanError, OutputDirectoryError, OutputInsideProtectedRootError, redactedErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
12
13
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
13
14
  import { ScanResult } from "./result.js";
14
- import { workerStatusFromEvent, } from "./worker-progress.js";
15
+ import { scanActivitiesFromEvent } from "./scan-activity.js";
16
+ import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
15
17
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
16
18
  import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
17
19
  import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateMode, } from "./targets.js";
@@ -20,6 +22,14 @@ const DEFAULT_DEPENDENCIES = {
20
22
  environment: process.env,
21
23
  };
22
24
  const SCAN_PERMISSION_PROFILE = "codex_security_scan";
25
+ const PERSONAL_TRUSTED_ACCESS_URL = "https://chatgpt.com/cyber";
26
+ const ORGANIZATIONAL_TRUSTED_ACCESS_URL = "https://openai.com/form/enterprise-trusted-access-for-cyber/";
27
+ const DEEP_SCAN_SETTINGS = [
28
+ ["workers", "workers", 1],
29
+ ["subagents", "subagents", 0],
30
+ ["stopAfterNoNew", "stop_after_no_new", 1],
31
+ ["maxDiscoveryRuns", "max_discovery_runs", 1],
32
+ ];
23
33
  export class CodexSecurity {
24
34
  config;
25
35
  metadata = {
@@ -59,13 +69,17 @@ export class CodexSecurity {
59
69
  repository: inputs.repository,
60
70
  target: inputs.target,
61
71
  mode: inputs.mode,
72
+ ...deepScanOptions(options),
62
73
  ...(options.knowledgeBasePaths?.length
63
74
  ? { knowledgeBasePaths: options.knowledgeBasePaths }
64
75
  : {}),
65
76
  outputDir: inputs.outputDir,
66
77
  ...(archiveDir === null ? {} : { archiveDir }),
67
- authentication: scanAuthentication(this.#dependencies.environment, options.auth),
78
+ authentication: scanAuthentication(this.#dependencies.environment, options.auth, configuration["model_provider"]),
68
79
  ...model,
80
+ ...(typeof configuration["model_provider"] === "string"
81
+ ? { modelProvider: configuration["model_provider"] }
82
+ : {}),
69
83
  ...(options.maxCostUsd === undefined
70
84
  ? {}
71
85
  : { maxCostUsd: options.maxCostUsd }),
@@ -87,6 +101,7 @@ export class CodexSecurity {
87
101
  let releaseCredentialHome = null;
88
102
  let scanFailure = false;
89
103
  let completionCost = null;
104
+ let preparedTargetWarnings = [];
90
105
  let activeScan = null;
91
106
  const workbench = this.#dependencies.runWorkbench ?? runWorkbench;
92
107
  try {
@@ -113,26 +128,40 @@ export class CodexSecurity {
113
128
  knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal);
114
129
  }
115
130
  checkOpen();
116
- const authentication = scanAuthentication(this.#dependencies.environment, options.auth);
117
- const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth);
131
+ const requestedConfig = await mergedCodexConfig(this.config);
132
+ const modelProvider = requestedConfig["model_provider"];
133
+ const externalProvider = isExternalModelProvider(modelProvider)
134
+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider]
135
+ : null;
136
+ let authentication = scanAuthentication(this.#dependencies.environment, options.auth, modelProvider);
137
+ const apiKey = authentication.method === "api_key"
138
+ ? environmentApiKey(this.#dependencies.environment, modelProvider)
139
+ : null;
140
+ if (externalProvider !== null && apiKey === null) {
141
+ throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`);
142
+ }
143
+ const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth, modelProvider);
118
144
  if (authentication.method === "stored_credentials" &&
119
145
  this.#dependencies.prepareRuntime === undefined) {
120
146
  const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
121
147
  releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
122
148
  }
123
149
  const previousRuntime = this.#runtime;
124
- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth);
150
+ const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, modelProvider);
125
151
  if (runtime === previousRuntime &&
126
152
  runtime.persistentCredentialHome === true &&
127
153
  this.#dependencies.prepareRuntime === undefined) {
128
154
  await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal);
129
155
  }
130
- const effectiveConfig = runtime.effectiveConfig ?? (await mergedCodexConfig(this.config));
156
+ const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;
131
157
  if (runtime.configPath !== undefined) {
132
158
  await writeCodexConfig(runtime.configPath, scanPreflightCodexConfig(effectiveConfig, repo));
133
159
  }
134
160
  const runtimeHome = await realpath(runtime.codexHome);
135
161
  requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
162
+ if (mode === "deep") {
163
+ await prepareDeepScanConfig(runtimeHome, this.#dependencies.environment, options, signal);
164
+ }
136
165
  if (options.expectedPluginVersion !== undefined &&
137
166
  runtime.plugin.version !== options.expectedPluginVersion) {
138
167
  throw new CodexSecurityError(`The original scan used plugin version ${options.expectedPluginVersion}, but the installed version is ${runtime.plugin.version}.`);
@@ -147,10 +176,7 @@ export class CodexSecurity {
147
176
  ? "stored_credentials"
148
177
  : null;
149
178
  }
150
- const apiKey = authentication.method === "api_key"
151
- ? environmentApiKey(this.#dependencies.environment)
152
- : null;
153
- if (apiKey !== null) {
179
+ if (externalProvider === null && apiKey !== null) {
154
180
  this.#runtimeCredentialSource = "api_key";
155
181
  }
156
182
  if (!runtime.credentialsAvailable &&
@@ -166,6 +192,7 @@ export class CodexSecurity {
166
192
  "'codex-security login --device-auth' on a remote or headless machine, or set " +
167
193
  "OPENAI_API_KEY or CODEX_API_KEY for CI.");
168
194
  }
195
+ authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
169
196
  notifyObserver("onAuthentication", options.onAuthentication, options.onObserverError, authentication);
170
197
  const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
171
198
  configuredPath: this.config.pythonPath,
@@ -209,10 +236,26 @@ export class CodexSecurity {
209
236
  };
210
237
  const { model } = scanModelConfiguration(effectiveConfig);
211
238
  validateScanCostLimit(options.maxCostUsd, model);
239
+ let scopeFileCount = null;
240
+ let reviewedFileCount = 0;
241
+ const reportProgress = (progress) => {
242
+ if (scopeFileCount === null ||
243
+ progress.filesTotal > scopeFileCount ||
244
+ progress.filesCompleted < reviewedFileCount) {
245
+ return;
246
+ }
247
+ reviewedFileCount = progress.filesCompleted;
248
+ notifyObserver("onProgress", options.onProgress, options.onObserverError, { ...progress, filesTotal: scopeFileCount });
249
+ };
212
250
  const tracker = new ScanCostTracker({
213
251
  codexHome: runtime.codexHome,
214
252
  model,
253
+ repository: repo,
215
254
  maxCostUsd: options.maxCostUsd,
255
+ onActivity: (activity) => {
256
+ notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
257
+ },
258
+ onProgress: reportProgress,
216
259
  onCost: (cost) => {
217
260
  notifyObserver("onCost", options.onCost, options.onObserverError, cost);
218
261
  if (options.maxCostUsd !== undefined &&
@@ -223,12 +266,12 @@ export class CodexSecurity {
223
266
  onError: (error) => costAbortController.abort(error),
224
267
  });
225
268
  costTracker = tracker;
226
- const recipe = scanRecipe(repo, protectedRoot, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, effectiveConfig, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd);
269
+ const recipe = scanRecipe(repo, protectedRoot, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, effectiveConfig, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
227
270
  const workbenchOptions = {
228
271
  python,
229
272
  pluginRoot: runtime.plugin.pluginRoot,
230
273
  environment: {
231
- ...selectedScanEnvironment(runtime.environment, options.auth),
274
+ ...selectedScanEnvironment(runtime.environment, options.auth, modelProvider),
232
275
  CODEX_SECURITY_STATE_DIR: stateDirectory,
233
276
  },
234
277
  signal,
@@ -289,6 +332,21 @@ export class CodexSecurity {
289
332
  throw new CodexSecurityError("The Codex Security workbench returned an invalid scan registration.");
290
333
  }
291
334
  const targetRevision = registeredRevision === "unversioned" ? null : registeredRevision;
335
+ const registeredFileCount = registration["scopeFileCount"];
336
+ scopeFileCount =
337
+ typeof registeredFileCount === "number" &&
338
+ Number.isSafeInteger(registeredFileCount) &&
339
+ registeredFileCount >= 0
340
+ ? registeredFileCount
341
+ : null;
342
+ if (scopeFileCount !== null) {
343
+ tracker.setExpectedFilesTotal(scopeFileCount);
344
+ notifyObserver("onProgress", options.onProgress, options.onObserverError, {
345
+ phase: "preflight",
346
+ filesCompleted: 0,
347
+ filesTotal: scopeFileCount,
348
+ });
349
+ }
292
350
  activeScan = { id: scanId, options: workbenchOptions };
293
351
  checkOpen();
294
352
  const feedback = await workbench({
@@ -350,12 +408,15 @@ export class CodexSecurity {
350
408
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
351
409
  };
352
410
  const environment = {
353
- ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, options.auth))),
411
+ ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, options.auth, modelProvider))),
412
+ ...(externalProvider === null
413
+ ? {}
414
+ : { [externalProvider.env_key]: apiKey }),
354
415
  CODEX_HOME: runtime.codexHome,
355
416
  ...runtimePaths,
356
417
  };
357
418
  const codex = this.#dependencies.createCodex({
358
- ...(apiKey === null ? {} : { apiKey }),
419
+ ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
359
420
  env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
360
421
  config: {
361
422
  default_permissions: SCAN_PERMISSION_PROFILE,
@@ -394,6 +455,7 @@ export class CodexSecurity {
394
455
  scanDir,
395
456
  pluginRoot: runtime.plugin.installedRoot,
396
457
  expectation,
458
+ authentication,
397
459
  workbenchValidated: true,
398
460
  model,
399
461
  onThreadStarted: (threadId) => tracker.start(threadId),
@@ -404,16 +466,32 @@ export class CodexSecurity {
404
466
  notifyObserver("onWarning", options.onWarning, options.onObserverError, "Scan completed, but its cost limit could not be verified because model pricing or token usage is unavailable.");
405
467
  }
406
468
  completionCost = snapshot.cost;
407
- await workbench(workbenchOptions, [
469
+ const preparation = await workbench(workbenchOptions, [
408
470
  "prepare-scan-completion",
409
471
  "--scan-id",
410
472
  scanId,
411
473
  ]);
474
+ preparedTargetWarnings = Array.isArray(preparation["targetWarnings"])
475
+ ? preparation["targetWarnings"].filter((warning) => typeof warning === "string")
476
+ : [];
412
477
  return snapshot.usage;
413
478
  },
414
479
  onScanStarted: options.onScanStarted,
480
+ onTrustedAccessStatus: options.onTrustedAccessStatus,
415
481
  onReconnect: options.onReconnect,
482
+ onActivity: options.onActivity,
483
+ onProgress: (progress) => {
484
+ if (progress.phase === "discovery" &&
485
+ progress.filesCompleted === 0 &&
486
+ reviewedFileCount === 0 &&
487
+ progress.filesTotal !== scopeFileCount) {
488
+ scopeFileCount = progress.filesTotal;
489
+ tracker.setExpectedFilesTotal(scopeFileCount);
490
+ }
491
+ reportProgress(progress);
492
+ },
416
493
  onWorkerStatus: options.onWorkerStatus,
494
+ onWarning: options.onWarning,
417
495
  onObserverError: options.onObserverError,
418
496
  });
419
497
  checkOpen();
@@ -428,9 +506,17 @@ export class CodexSecurity {
428
506
  activeScan = null;
429
507
  const completedScan = completion["scan"];
430
508
  if (isRecord(completedScan) && Array.isArray(completedScan["warnings"])) {
509
+ const targetWarnings = new Set([
510
+ ...preparedTargetWarnings,
511
+ ...(Array.isArray(completion["targetWarnings"])
512
+ ? completion["targetWarnings"].filter((warning) => typeof warning === "string")
513
+ : []),
514
+ ]);
431
515
  for (const warning of completedScan["warnings"]) {
432
516
  if (typeof warning === "string") {
433
- notifyObserver("onWarning", options.onWarning, options.onObserverError, warning);
517
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, warning, targetWarnings.has(warning)
518
+ ? { kind: "target_changed" }
519
+ : undefined);
434
520
  }
435
521
  }
436
522
  }
@@ -632,11 +718,11 @@ export class CodexSecurity {
632
718
  }
633
719
  }
634
720
  }
635
- async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto") {
721
+ async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto", modelProvider) {
636
722
  this.#requireOpen();
637
723
  if (this.#runtime !== null) {
638
- const usePersistentCredentials = scanAuthentication(this.#dependencies.environment, auth).method ===
639
- "stored_credentials";
724
+ const usePersistentCredentials = scanAuthentication(this.#dependencies.environment, auth, modelProvider)
725
+ .method === "stored_credentials";
640
726
  if (this.#dependencies.prepareRuntime !== undefined ||
641
727
  this.#runtime.persistentCredentialHome === undefined ||
642
728
  this.#runtime.persistentCredentialHome === usePersistentCredentials) {
@@ -649,7 +735,7 @@ export class CodexSecurity {
649
735
  this.#requireOpen();
650
736
  }
651
737
  if (this.#runtimePromise === null) {
652
- const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal, temporaryRoot, validateLocation, auth);
738
+ const runtimePromise = this.#prepareRuntime(signal ?? this.#abortController.signal, temporaryRoot, validateLocation, auth, modelProvider);
653
739
  this.#runtimePromise = runtimePromise;
654
740
  void runtimePromise.catch(() => {
655
741
  if (this.#runtimePromise === runtimePromise) {
@@ -688,6 +774,7 @@ export class CodexSecurity {
688
774
  runtime.effectiveConfig = mergedConfig;
689
775
  }
690
776
  async #validateLocalInputs(repository, options, signal) {
777
+ deepScanOptions(options);
691
778
  if (options.maxCostUsd !== undefined &&
692
779
  (!Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) {
693
780
  throw new CodexSecurityError("The scan cost limit must be a positive USD amount.");
@@ -714,13 +801,13 @@ export class CodexSecurity {
714
801
  protectedRoot,
715
802
  };
716
803
  }
717
- async #prepareRuntime(signal, temporaryRoot, validateLocation, auth = "auto") {
804
+ async #prepareRuntime(signal, temporaryRoot, validateLocation, auth = "auto", modelProvider) {
718
805
  if (this.#dependencies.prepareRuntime !== undefined) {
719
806
  return await this.#dependencies.prepareRuntime(this.config, signal);
720
807
  }
721
- const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth);
722
- const persistentCredentialHome = scanAuthentication(this.#dependencies.environment, auth).method ===
723
- "stored_credentials";
808
+ const processEnvironment = selectedScanEnvironment(this.#dependencies.environment, auth, modelProvider);
809
+ const persistentCredentialHome = scanAuthentication(this.#dependencies.environment, auth, modelProvider)
810
+ .method === "stored_credentials";
724
811
  const codexHome = persistentCredentialHome
725
812
  ? await prepareCodexSecurityCredentialHome(processEnvironment, validateLocation)
726
813
  : await createIsolatedHome(temporaryRoot, validateLocation);
@@ -742,7 +829,9 @@ export class CodexSecurity {
742
829
  environment: withoutCodexHome(processEnvironment),
743
830
  signal,
744
831
  });
745
- const credentialsAvailable = await initialCredentialsAvailable(processEnvironment, ambientHome, codexHome);
832
+ const credentialsAvailable = isExternalModelProvider(modelProvider)
833
+ ? false
834
+ : await initialCredentialsAvailable(processEnvironment, ambientHome, codexHome);
746
835
  return {
747
836
  codexHome,
748
837
  persistentCredentialHome,
@@ -774,6 +863,60 @@ export class CodexSecurity {
774
863
  throw new CodexSecurityError("CodexSecurity is closed.");
775
864
  }
776
865
  }
866
+ function deepScanOptions(options) {
867
+ const selected = {};
868
+ for (const [name, , minimum] of DEEP_SCAN_SETTINGS) {
869
+ const value = options[name];
870
+ if (value === undefined)
871
+ continue;
872
+ if ((options.mode ?? "standard") !== "deep") {
873
+ throw new CodexSecurityError("Deep scan settings require deep mode.");
874
+ }
875
+ if (!Number.isSafeInteger(value) || value < minimum) {
876
+ throw new CodexSecurityError(`Deep scan ${name} must be ${minimum === 0 ? "a non-negative" : "a positive"} integer.`);
877
+ }
878
+ selected[name] = value;
879
+ }
880
+ return selected;
881
+ }
882
+ async function prepareDeepScanConfig(codexHome, environment, options, signal) {
883
+ const ambientHome = environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex");
884
+ const source = join(ambientHome, "codex-security", "config.toml");
885
+ let configured = {};
886
+ try {
887
+ configured = parseToml(await readFile(source, { encoding: "utf8", signal }));
888
+ }
889
+ catch (error) {
890
+ if (!isRecord(error) || error["code"] !== "ENOENT") {
891
+ throw new CodexSecurityError(`Cannot read Codex Security configuration at ${source}.`, { cause: error });
892
+ }
893
+ }
894
+ const existing = configured["deep_scan"];
895
+ if (existing !== undefined && !isRecord(existing)) {
896
+ throw new CodexSecurityError(`Codex Security configuration [deep_scan] at ${source} must be a TOML table.`);
897
+ }
898
+ const overrides = {};
899
+ for (const [name, key] of DEEP_SCAN_SETTINGS) {
900
+ const value = options[name];
901
+ if (value !== undefined)
902
+ overrides[key] = value;
903
+ }
904
+ const destination = join(codexHome, "codex-security", "config.toml");
905
+ const hasOverrides = Object.keys(overrides).length > 0;
906
+ if (existing === undefined && !hasOverrides) {
907
+ if (destination !== source) {
908
+ await rm(destination, { force: true });
909
+ }
910
+ return;
911
+ }
912
+ if (destination === source && !hasOverrides)
913
+ return;
914
+ await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
915
+ await writeFile(destination, stringifyToml({
916
+ ...configured,
917
+ deep_scan: { ...existing, ...overrides },
918
+ }), { mode: 0o600, signal });
919
+ }
777
920
  export async function initialCredentialsAvailable(environment, ambientHome, isolatedHome, importer = importAmbientAuth) {
778
921
  if (environmentApiKey(environment) !== null)
779
922
  return false;
@@ -818,8 +961,29 @@ export async function runScanEvents(options) {
818
961
  let finalResponse = "";
819
962
  let usage = null;
820
963
  let lastStreamError = null;
964
+ let tacStatusReported = false;
821
965
  try {
822
966
  for await (const event of options.events) {
967
+ if (!tacStatusReported) {
968
+ const tacStatus = trustedAccessStatusFromEvent(event);
969
+ if (tacStatus !== null) {
970
+ tacStatusReported = true;
971
+ notifyObserver("onTrustedAccessStatus", options.onTrustedAccessStatus, options.onObserverError, tacStatus);
972
+ if (tacStatus !== "granted") {
973
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, trustedAccessWarning(tacStatus, options.authentication));
974
+ }
975
+ }
976
+ }
977
+ for (const activity of scanActivitiesFromEvent(event, options.expectation.repository)) {
978
+ notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
979
+ }
980
+ for (const progress of scanProgressUpdatesFromEvent(event)) {
981
+ if (options.expectedFilesTotal !== undefined &&
982
+ progress.filesTotal !== options.expectedFilesTotal) {
983
+ continue;
984
+ }
985
+ notifyObserver("onProgress", options.onProgress, options.onObserverError, progress);
986
+ }
823
987
  const workerStatus = workerStatusFromEvent(event);
824
988
  if (workerStatus !== null) {
825
989
  notifyObserver("onWorkerStatus", options.onWorkerStatus, options.onObserverError, workerStatus);
@@ -897,6 +1061,68 @@ export async function runScanEvents(options) {
897
1061
  throw error;
898
1062
  }
899
1063
  }
1064
+ function trustedAccessStatusFromEvent(event) {
1065
+ if (event.type !== "item.completed" || !isRecord(event["item"])) {
1066
+ return null;
1067
+ }
1068
+ const item = event["item"];
1069
+ if (item["type"] !== "mcp_tool_call" ||
1070
+ item["server"] !== "codex_apps" ||
1071
+ item["tool"] !== "get_tac_status") {
1072
+ return null;
1073
+ }
1074
+ if (item["status"] !== "completed" || !isRecord(item["result"])) {
1075
+ return "unknown";
1076
+ }
1077
+ const result = item["result"]["structured_content"];
1078
+ if (!isRecord(result) ||
1079
+ result["schemaVersion"] !== 1 ||
1080
+ !Array.isArray(result["grants"]) ||
1081
+ typeof result["checkedAt"] !== "string" ||
1082
+ Number.isNaN(Date.parse(result["checkedAt"])) ||
1083
+ result["stale"] !== false) {
1084
+ return "unknown";
1085
+ }
1086
+ const status = result["status"];
1087
+ if (status !== "granted" &&
1088
+ status !== "not_granted" &&
1089
+ status !== "unknown") {
1090
+ return "unknown";
1091
+ }
1092
+ if (result["grants"].some((grant) => !isTrustedAccessGrant(grant)) ||
1093
+ (status === "granted") !== result["grants"].length > 0) {
1094
+ return "unknown";
1095
+ }
1096
+ return status;
1097
+ }
1098
+ function isTrustedAccessGrant(grant) {
1099
+ if (!isRecord(grant))
1100
+ return false;
1101
+ const level = grant["level"];
1102
+ const source = grant["source"];
1103
+ return ((source === "user" && (level === "tac1" || level === "tac2")) ||
1104
+ (source === "current_account" &&
1105
+ (level === "tac1" || level === "tac3" || level === "government")));
1106
+ }
1107
+ function trustedAccessWarning(status, authentication) {
1108
+ const apiOrganization = (authentication?.method === "api_key" &&
1109
+ (authentication.source === "OPENAI_API_KEY" ||
1110
+ authentication.source === "CODEX_API_KEY")) ||
1111
+ (authentication?.method === "stored_credentials" &&
1112
+ authentication.credentialType === "api_key");
1113
+ const applicationUrl = apiOrganization
1114
+ ? ORGANIZATIONAL_TRUSTED_ACCESS_URL
1115
+ : PERSONAL_TRUSTED_ACCESS_URL;
1116
+ if (status === "not_granted") {
1117
+ const account = apiOrganization ? "your API organization" : "your account";
1118
+ return `Some cybersecurity requests or findings may be refused because ${account} does not have Trusted Access for Cyber. Apply at ${applicationUrl}.`;
1119
+ }
1120
+ const access = apiOrganization
1121
+ ? "Trusted Access for Cyber for your API organization"
1122
+ : "your Trusted Access for Cyber status";
1123
+ const action = apiOrganization ? "your organization's access" : "your access";
1124
+ return `Some cybersecurity requests or findings may be refused because ${access} could not be verified. Check ${action} or apply at ${applicationUrl}.`;
1125
+ }
900
1126
  async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKnowledgeBase = false) {
901
1127
  const skillName = skillNameFor(target, mode);
902
1128
  const skillPath = join(pluginRoot, "skills", skillName, "SKILL.md");
@@ -907,6 +1133,11 @@ async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKn
907
1133
  return [
908
1134
  `Use the installed $codex-security:${skillName} skill at "$CODEX_SECURITY_PLUGIN_ROOT/skills/${skillName}/SKILL.md".`,
909
1135
  "Run this Codex Security scan non-interactively.",
1136
+ ...(mode === "deep"
1137
+ ? [
1138
+ 'The SDK has already registered this scan. Call start_codex_security_deep_scan with { scanId: "$CODEX_SECURITY_SCAN_ID" }; never pass targetPath or create another scan.',
1139
+ ]
1140
+ : []),
910
1141
  ...(skillName === "deep-security-scan"
911
1142
  ? []
912
1143
  : [
@@ -923,6 +1154,8 @@ async function scanPrompt(pluginRoot, target, mode, hasConfigPath = false, hasKn
923
1154
  'When "$CODEX_SECURITY_TARGET_REVISION" is set, use its exact value as scan.target.revision.',
924
1155
  'When "$CODEX_SECURITY_TARGET_SNAPSHOT_DIGEST" is set, use its exact value as scan.target.snapshotDigest. For git_revision, omit scan.target.snapshotDigest.',
925
1156
  'Use exactly "codex-security-plugin" as scan.producer.name.',
1157
+ 'After the file inventory, after each fully reviewed file batch, and when entering each later phase, emit one standalone CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":3,"filesTotal":8} line in a completed command output or agent message. Use the actual phase and file counts. Never count unread or partially reviewed files.',
1158
+ 'Every delegated review assignment must say: After each completed batch, emit CODEX_SECURITY_SCAN_PROGRESS {"phase":"discovery","filesCompleted":3,"filesTotal":8} on its own line using your worker-local reviewed and assigned file counts.',
926
1159
  ...(hasConfigPath
927
1160
  ? [
928
1161
  'For normal config-preflight helper calls, append --config "$CODEX_SECURITY_CONFIG_PATH" so preflight reads the sanitized active runtime config. Preserve the documented runtime and --effective-config arguments for session-only values.',
@@ -959,7 +1192,7 @@ function targetInstruction(target) {
959
1192
  }
960
1193
  return `Scan target: staged and unstaged working-tree changes against ${target.base}.`;
961
1194
  }
962
- function scanRecipe(repository, activeProjectPath, target, mode, repositoryRevision, pluginVersion, effectiveConfig, failOnSeverity, knowledgeBasePaths, maxCostUsd) {
1195
+ function scanRecipe(repository, activeProjectPath, target, mode, repositoryRevision, pluginVersion, effectiveConfig, failOnSeverity, knowledgeBasePaths, maxCostUsd, deepScan) {
963
1196
  return {
964
1197
  repository,
965
1198
  target: {
@@ -977,6 +1210,9 @@ function scanRecipe(repository, activeProjectPath, target, mode, repositoryRevis
977
1210
  ...(failOnSeverity === undefined ? {} : { failOnSeverity }),
978
1211
  ...(knowledgeBasePaths === undefined ? {} : { knowledgeBasePaths }),
979
1212
  ...(maxCostUsd === undefined ? {} : { maxCostUsd }),
1213
+ ...(deepScan === undefined || Object.keys(deepScan).length === 0
1214
+ ? {}
1215
+ : { deepScan: { ...deepScan } }),
980
1216
  };
981
1217
  }
982
1218
  function validateScanCostLimit(maxCostUsd, model) {
@@ -1031,12 +1267,14 @@ async function collectResult(turnResult, threadId, scanDir, pluginRoot, expectat
1031
1267
  sarifPath,
1032
1268
  });
1033
1269
  }
1034
- export function scanAuthentication(environment, auth = "auto") {
1035
- if (auth === "chatgpt") {
1270
+ export function scanAuthentication(environment, auth = "auto", modelProvider) {
1271
+ if (auth === "chatgpt" && !isExternalModelProvider(modelProvider)) {
1036
1272
  return { method: "stored_credentials", verified: false };
1037
1273
  }
1038
- const key = environmentApiKeyEntry(environment);
1039
- if (auth === "api-key" && key === null) {
1274
+ const key = environmentApiKeyEntry(environment, modelProvider);
1275
+ if (auth === "api-key" &&
1276
+ key === null &&
1277
+ !isExternalModelProvider(modelProvider)) {
1040
1278
  throw new AuthenticationRequiredError("API-key authentication requires OPENAI_API_KEY or CODEX_API_KEY. " +
1041
1279
  "Set a valid API key or use '--auth chatgpt'.");
1042
1280
  }
@@ -1044,11 +1282,44 @@ export function scanAuthentication(environment, auth = "auto") {
1044
1282
  ? { method: "stored_credentials", verified: false }
1045
1283
  : { method: "api_key", source: key.source, verified: false };
1046
1284
  }
1047
- function selectedScanEnvironment(environment, auth = "auto") {
1048
- if (auth !== "chatgpt")
1285
+ async function runtimeScanAuthentication(environment, codexHome, auth = "auto", modelProvider) {
1286
+ const authentication = scanAuthentication(environment, auth, modelProvider);
1287
+ if (authentication.method !== "stored_credentials")
1288
+ return authentication;
1289
+ try {
1290
+ const stored = JSON.parse(await readFile(join(codexHome, "auth.json"), "utf8"));
1291
+ if (!isRecord(stored))
1292
+ return authentication;
1293
+ const mode = stored["auth_mode"];
1294
+ if (mode === "apikey" || mode === "api_key") {
1295
+ return { ...authentication, credentialType: "api_key" };
1296
+ }
1297
+ if (mode === "chatgpt") {
1298
+ return { ...authentication, credentialType: "chatgpt" };
1299
+ }
1300
+ }
1301
+ catch {
1302
+ return authentication;
1303
+ }
1304
+ return authentication;
1305
+ }
1306
+ function selectedScanEnvironment(environment, auth = "auto", modelProvider) {
1307
+ const selectedProviderKey = isExternalModelProvider(modelProvider)
1308
+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key
1309
+ : null;
1310
+ if (auth !== "chatgpt" && selectedProviderKey === null)
1049
1311
  return environment;
1050
- return Object.fromEntries(Object.entries(environment).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
1051
- name.toUpperCase() !== "CODEX_API_KEY"));
1312
+ return Object.fromEntries(Object.entries(environment).filter(([name]) => {
1313
+ const key = name.toUpperCase();
1314
+ if (key === "OPENAI_API_KEY" || key === "CODEX_API_KEY")
1315
+ return false;
1316
+ if (selectedProviderKey === null)
1317
+ return true;
1318
+ if (key === "OPENROUTER_API_KEY" || key === "FIREWORKS_API_KEY") {
1319
+ return key === selectedProviderKey;
1320
+ }
1321
+ return true;
1322
+ }));
1052
1323
  }
1053
1324
  function notifyObserver(observerName, observer, onObserverError, ...args) {
1054
1325
  void Promise.resolve()
@@ -1056,18 +1327,17 @@ function notifyObserver(observerName, observer, onObserverError, ...args) {
1056
1327
  .catch((error) => onObserverError?.(observerName, error))
1057
1328
  .catch(() => { });
1058
1329
  }
1059
- function environmentApiKey(environment) {
1060
- return environmentApiKeyEntry(environment)?.value ?? null;
1330
+ function environmentApiKey(environment, modelProvider) {
1331
+ return environmentApiKeyEntry(environment, modelProvider)?.value ?? null;
1061
1332
  }
1062
- function environmentApiKeyEntry(environment) {
1063
- for (const requested of ["OPENAI_API_KEY", "CODEX_API_KEY"]) {
1064
- const canonical = environment[requested]?.trim();
1065
- if (canonical)
1066
- return { source: requested, value: canonical };
1067
- for (const [name, value] of Object.entries(environment)) {
1068
- if (name.toUpperCase() === requested && value?.trim())
1069
- return { source: requested, value: value.trim() };
1070
- }
1333
+ function environmentApiKeyEntry(environment, modelProvider) {
1334
+ const keys = isExternalModelProvider(modelProvider)
1335
+ ? [EXTERNAL_CODEX_PROVIDERS[modelProvider].env_key]
1336
+ : ["OPENAI_API_KEY", "CODEX_API_KEY"];
1337
+ for (const requested of keys) {
1338
+ const value = environmentValue(environment, requested)?.trim();
1339
+ if (value)
1340
+ return { source: requested, value };
1071
1341
  }
1072
1342
  return null;
1073
1343
  }
@@ -1248,6 +1518,12 @@ export function scanPreflightCodexConfig(config, activeProjectPath) {
1248
1518
  ];
1249
1519
  };
1250
1520
  const result = executionConfig(config);
1521
+ const modelProvider = result["model_provider"];
1522
+ if (isExternalModelProvider(modelProvider)) {
1523
+ result["model_providers"] = {
1524
+ [modelProvider]: { ...EXTERNAL_CODEX_PROVIDERS[modelProvider] },
1525
+ };
1526
+ }
1251
1527
  const selectedProfile = safeProfileName(config["profile"])
1252
1528
  ? config["profile"]
1253
1529
  : undefined;