@openai/codex-security 0.1.13 → 0.1.15

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 (102) hide show
  1. package/README.md +90 -29
  2. package/_bundled_plugin/.app.json +5 -0
  3. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  4. package/_bundled_plugin/examples/completed-scan/report.md +96 -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/references/config-preflight.md +5 -1
  8. package/_bundled_plugin/references/core-scan.md +6 -15
  9. package/_bundled_plugin/references/final-report.md +1 -1
  10. package/_bundled_plugin/references/scan-artifacts.md +1 -1
  11. package/_bundled_plugin/references/threat-model.md +64 -0
  12. package/_bundled_plugin/schemas/findings.schema.json +327 -2
  13. package/_bundled_plugin/schemas/tools/scan-draft.schema.json +286 -4
  14. package/_bundled_plugin/scripts/config_preflight.py +20 -1
  15. package/_bundled_plugin/scripts/deep_scan_workbench.py +12 -6
  16. package/_bundled_plugin/scripts/finalize_scan_contract.py +322 -33
  17. package/_bundled_plugin/scripts/finding_preview.py +81 -19
  18. package/_bundled_plugin/scripts/report_projection.py +253 -33
  19. package/_bundled_plugin/scripts/validate_scan_contract.py +5 -2
  20. package/_bundled_plugin/scripts/workbench_cli.py +7 -1
  21. package/_bundled_plugin/scripts/workbench_remediation.py +2 -0
  22. package/_bundled_plugin/skills/deep-security-scan/SKILL.md +4 -0
  23. package/_bundled_plugin/skills/security-diff-scan/SKILL.md +2 -2
  24. package/_bundled_plugin/skills/security-scan/SKILL.md +1 -1
  25. package/_bundled_plugin/skills/threat-model/SKILL.md +6 -49
  26. package/dist/api.d.ts +5 -73
  27. package/dist/api.d.ts.map +1 -1
  28. package/dist/api.js +266 -211
  29. package/dist/api.js.map +1 -1
  30. package/dist/bulk-scan-discovery.d.ts +3 -3
  31. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  32. package/dist/bulk-scan-discovery.js +8 -7
  33. package/dist/bulk-scan-discovery.js.map +1 -1
  34. package/dist/cli.d.ts +18 -2
  35. package/dist/cli.d.ts.map +1 -1
  36. package/dist/cli.js +785 -121
  37. package/dist/cli.js.map +1 -1
  38. package/dist/codex-prompt.d.ts +4 -0
  39. package/dist/codex-prompt.d.ts.map +1 -0
  40. package/dist/codex-prompt.js +14 -0
  41. package/dist/codex-prompt.js.map +1 -0
  42. package/dist/config.d.ts +1 -0
  43. package/dist/config.d.ts.map +1 -1
  44. package/dist/config.js +8 -1
  45. package/dist/config.js.map +1 -1
  46. package/dist/contract.d.ts.map +1 -1
  47. package/dist/contract.js +198 -2
  48. package/dist/contract.js.map +1 -1
  49. package/dist/cost.d.ts +7 -0
  50. package/dist/cost.d.ts.map +1 -1
  51. package/dist/cost.js +68 -47
  52. package/dist/cost.js.map +1 -1
  53. package/dist/errors.d.ts +4 -0
  54. package/dist/errors.d.ts.map +1 -1
  55. package/dist/errors.js +9 -0
  56. package/dist/errors.js.map +1 -1
  57. package/dist/index.d.ts +2 -2
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/linear.d.ts +19 -0
  62. package/dist/linear.d.ts.map +1 -0
  63. package/dist/linear.js +106 -0
  64. package/dist/linear.js.map +1 -0
  65. package/dist/models.d.ts +89 -2
  66. package/dist/models.d.ts.map +1 -1
  67. package/dist/models.js.map +1 -1
  68. package/dist/multiscan.d.ts.map +1 -1
  69. package/dist/multiscan.js +7 -6
  70. package/dist/multiscan.js.map +1 -1
  71. package/dist/patch-tui.d.ts +28 -0
  72. package/dist/patch-tui.d.ts.map +1 -0
  73. package/dist/patch-tui.js +384 -0
  74. package/dist/patch-tui.js.map +1 -0
  75. package/dist/publish.d.ts +2 -2
  76. package/dist/publish.d.ts.map +1 -1
  77. package/dist/publish.js +4 -8
  78. package/dist/publish.js.map +1 -1
  79. package/dist/runtime.d.ts +10 -7
  80. package/dist/runtime.d.ts.map +1 -1
  81. package/dist/runtime.js +63 -35
  82. package/dist/runtime.js.map +1 -1
  83. package/dist/scan-comparison.d.ts +2 -1
  84. package/dist/scan-comparison.d.ts.map +1 -1
  85. package/dist/scan-comparison.js +17 -15
  86. package/dist/scan-comparison.js.map +1 -1
  87. package/dist/scan-dashboard.d.ts +2 -1
  88. package/dist/scan-dashboard.d.ts.map +1 -1
  89. package/dist/scan-dashboard.js +219 -11
  90. package/dist/scan-dashboard.js.map +1 -1
  91. package/dist/targets.d.ts +1 -0
  92. package/dist/targets.d.ts.map +1 -1
  93. package/dist/targets.js +4 -2
  94. package/dist/targets.js.map +1 -1
  95. package/dist/trusted-executable.d.ts.map +1 -1
  96. package/dist/trusted-executable.js +26 -11
  97. package/dist/trusted-executable.js.map +1 -1
  98. package/dist/version.d.ts +1 -1
  99. package/dist/version.js +1 -1
  100. package/dist/version.js.map +1 -1
  101. package/package.json +7 -3
  102. package/_bundled_plugin/skills/threat-model/references/threat-model-guidance.md +0 -48
package/dist/api.js CHANGED
@@ -3,20 +3,21 @@ import { chmod, lstat, mkdir, readFile, realpath, rename, rm, writeFile, } from
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
- import { Codex } from "@openai/codex-sdk";
6
+ import { Codex, } from "@openai/codex-sdk";
7
7
  import { parse as parseToml, stringify as stringifyToml, } from "smol-toml";
8
8
  import { accountStatus, CodexLoginHandle, loginApiKey as persistApiKey, logout as codexLogout, } from "./auth.js";
9
- import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
10
- import { estimateScanCost, ScanCostTracker } from "./cost.js";
9
+ import { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
10
+ import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
11
+ import { estimateScanCost, ScanCostTracker, } from "./cost.js";
11
12
  import { loadContract, requireScanFile, } from "./contract.js";
12
- import { AuthenticationRequiredError, CodexSecurityError, IncompleteScanError, OutputDirectoryError, OutputInsideProtectedRootError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
13
+ import { AuthenticationRequiredError, CodexSecurityError, IncompleteScanError, OutputDirectoryError, errorMessage, safeErrorMessage, ScanCostLimitExceededError, ScanInterruptedError, } from "./errors.js";
13
14
  import { prepareKnowledgeBase, } from "./knowledge-base.js";
14
15
  import { ScanResult, } from "./result.js";
15
16
  import { scanActivitiesFromEvent } from "./scan-activity.js";
16
17
  import { matchCompletedScan, matchScanFindingsInternal, } from "./scan-comparison.js";
17
18
  import { scanProgressUpdatesFromEvent, workerStatusFromEvent, } from "./worker-progress.js";
18
19
  import { CODEX_EXECUTABLE_VERSION, CODEX_SDK_VERSION } from "./version.js";
19
- import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentScanRoot, requireModelSafeOutputDir, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
20
+ import { acquireCodexSecurityCredentialHomeLock, bootstrapPlugin, cleanupSdkDirectory, codexSecurityCredentialAllowsAmbientImport, codexSecurityCredentialHome, codexSecurityHasStoredFileCredentials, codexSecurityStateDirectory, createIsolatedHome, expandHome, importAmbientAuth, prepareCodexSecurityCredentialHome, preserveCodexSecurityPluginRegistration, pluginExecutionEnvironment, planOutputArchive, prepareOutputDir, preparePersistentOutputRoot, requireModelSafeOutputDir, requireOutputOutsideRepository, resolveCodexCommand, resolvePluginPath, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, validateOutputDir, } from "./runtime.js";
20
21
  import { enclosingGitWorktreeRoot, normalizeRepository, normalizeTarget, repositoryRevision, resolveRepositoryPath, validatedGitEnvironment, validateCommittedDiffCheckout, validateMode, } from "./targets.js";
21
22
  const DEEP_SCAN_CONFIG_PATH_ENVIRONMENT = "CODEX_SECURITY_DEEP_SCAN_CONFIG_PATH";
22
23
  const DEFAULT_DEPENDENCIES = {
@@ -62,6 +63,9 @@ export class CodexSecurity {
62
63
  async preflight(repository, options = {}) {
63
64
  this.#requireOpen();
64
65
  const inputs = await this.#validateLocalInputs(repository, options, options.signal);
66
+ return await this.#preflightInputs(inputs, options);
67
+ }
68
+ async #preflightInputs(inputs, options) {
65
69
  requireOutputOutsideRepository(inputs.protectedRoot, await realpath(tmpdir()), "temporary");
66
70
  if (options.knowledgeBasePaths?.length) {
67
71
  const knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, options.signal);
@@ -133,37 +137,9 @@ export class CodexSecurity {
133
137
  knowledgeBase = await prepareKnowledgeBase(options.knowledgeBasePaths, signal);
134
138
  }
135
139
  checkOpen();
136
- const requestedConfig = await mergedCodexConfig(this.config);
137
- const modelProvider = scanModelProvider(requestedConfig);
138
- const externalProvider = isExternalModelProvider(modelProvider)
139
- ? EXTERNAL_CODEX_PROVIDERS[modelProvider]
140
- : null;
141
- let authentication = scanAuthentication(this.#dependencies.environment, options.auth, modelProvider);
142
- const apiKey = authentication.method === "api_key"
143
- ? environmentApiKey(this.#dependencies.environment, modelProvider)
144
- : null;
145
- if (externalProvider !== null && apiKey === null) {
146
- throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`);
147
- }
148
- const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth, modelProvider);
149
- if (this.#dependencies.prepareRuntime === undefined) {
150
- const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
151
- releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
152
- }
153
- const previousRuntime = this.#runtime;
154
- const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, requestedConfig);
155
- if (runtime === previousRuntime &&
156
- this.#dependencies.prepareRuntime === undefined) {
157
- await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
158
- }
159
- const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;
160
- const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
161
- if (runtime.configPath !== undefined) {
162
- await writeCodexConfig(runtime.configPath, preflightConfig);
163
- }
164
- const runtimeHome = await realpath(runtime.codexHome);
165
- requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
166
- const sessionConfig = scanRuntimeCodexConfig(effectiveConfig, stateDirectory, runtimeHome);
140
+ const session = await this.#prepareSession({ protectedRoot, stateDirectory }, options, signal, temporaryRoot, mode === "deep");
141
+ const { runtime, runtimeHome, effectiveConfig, preflightConfig, modelProvider, authentication, approvalPolicy, python, } = session;
142
+ releaseCredentialHome = session.releaseCredentialHome;
167
143
  const deepScanConfigPath = mode === "deep"
168
144
  ? runtime.deepScanConfigPath ??
169
145
  join(runtimeHome, "codex-security", "config.toml")
@@ -171,54 +147,10 @@ export class CodexSecurity {
171
147
  if (deepScanConfigPath !== undefined) {
172
148
  await prepareDeepScanConfig(deepScanConfigPath, this.#dependencies.environment, options, signal);
173
149
  }
174
- if (options.expectedPluginVersion !== undefined &&
175
- runtime.plugin.version !== options.expectedPluginVersion) {
176
- throw new CodexSecurityError(`The original scan used plugin version ${options.expectedPluginVersion}, but the installed version is ${runtime.plugin.version}.`);
177
- }
178
- checkOpen();
179
- if (authentication.method === "stored_credentials" &&
180
- this.#runtimeCredentialSource === "api_key") {
181
- const ambientHome = environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
182
- join(homedir(), ".codex");
183
- runtime.credentialsAvailable = await importAmbientAuth(ambientHome, runtime.codexHome);
184
- this.#runtimeCredentialSource = runtime.credentialsAvailable
185
- ? "stored_credentials"
186
- : null;
187
- }
188
- if (mode !== "deep" || runtime.deepScanConfigPath !== undefined) {
189
- await releaseCredentialHome?.();
190
- releaseCredentialHome = null;
191
- }
192
- if (externalProvider === null && apiKey !== null) {
193
- this.#runtimeCredentialSource = "api_key";
194
- }
195
- if (!runtime.credentialsAvailable &&
196
- authentication.method === "stored_credentials") {
197
- const status = await accountStatus(this.#codexCommand(), runtime.environment, signal);
198
- runtime.credentialsAvailable = status.authenticated;
199
- this.#runtimeCredentialSource = status.authenticated
200
- ? "stored_credentials"
201
- : null;
202
- }
203
- if (!runtime.credentialsAvailable &&
204
- apiKey === null &&
205
- authentication.method !== "aws_credentials") {
206
- throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
207
- "'codex-security login --device-auth' on a remote or headless machine, or set " +
208
- "OPENAI_API_KEY or CODEX_API_KEY for CI.");
209
- }
210
- authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
211
- notifyObserver("onAuthentication", options.onAuthentication, options.onObserverError, authentication);
212
- const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
213
- configuredPath: this.config.pythonPath,
214
- environment: scanEnvironment,
215
- protectedRoot,
216
- signal,
217
- });
218
150
  checkOpen();
219
151
  const scanOutputRoot = requestedOutput === null &&
220
152
  this.#dependencies.prepareOutputDir === undefined
221
- ? await preparePersistentScanRoot(stateDirectory, basename(repo))
153
+ ? await preparePersistentOutputRoot(stateDirectory, "scans", basename(repo))
222
154
  : temporaryRoot;
223
155
  if (scanOutputRoot !== undefined) {
224
156
  requireOutputOutsideRepository(protectedRoot, scanOutputRoot, scanOutputRoot === temporaryRoot ? "temporary" : "output");
@@ -293,6 +225,9 @@ export class CodexSecurity {
293
225
  onActivity: options.onActivity === undefined
294
226
  ? undefined
295
227
  : (activity) => notifyObserver("onActivity", options.onActivity, options.onObserverError, activity),
228
+ onSessionEvent: options.onSessionEvent === undefined
229
+ ? undefined
230
+ : (event) => notifyObserver("onSessionEvent", options.onSessionEvent, options.onObserverError, event),
296
231
  onProgress: options.onProgress === undefined ? undefined : reportProgress,
297
232
  onCost: options.onCost === undefined && options.maxCostUsd === undefined
298
233
  ? undefined
@@ -306,7 +241,7 @@ export class CodexSecurity {
306
241
  onError: reportTrackingError,
307
242
  });
308
243
  costTracker = tracker;
309
- const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, preflightConfig, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
244
+ const recipe = scanRecipe(repo, normalized, mode, expectation.repositoryRevision, runtime.plugin.version, { ...preflightConfig, approval_policy: approvalPolicy }, options.failureSeverity, knowledgeBase?.sources, options.maxCostUsd, deepScanOptions(options));
310
245
  const workbenchOptions = {
311
246
  python,
312
247
  pluginRoot: runtime.plugin.pluginRoot,
@@ -457,51 +392,13 @@ export class CodexSecurity {
457
392
  ? {}
458
393
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
459
394
  };
460
- const environment = {
461
- ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, options.auth, modelProvider))),
462
- ...(externalProvider === null
463
- ? {}
464
- : { [externalProvider.env_key]: apiKey }),
465
- CODEX_HOME: runtime.codexHome,
466
- ...runtimePaths,
467
- };
468
- const sdkCodexConfig = { ...sessionConfig };
469
- // Projects and permissions already live in generated TOML files; the SDK
470
- // cannot safely encode their path and selector keys as dotted overrides.
471
- delete sdkCodexConfig["projects"];
472
- delete sdkCodexConfig["permissions"];
473
- const configuredResponsesMetadata = isRecord(sdkCodexConfig["responses_api_metadata"])
474
- ? sdkCodexConfig["responses_api_metadata"]
475
- : {};
476
- const codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
477
- undefined
478
- ? undefined
479
- : this.#codexCommand().command;
480
- const codex = this.#dependencies.createCodex({
481
- ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
482
- ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
483
- env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
484
- config: {
485
- ...sdkCodexConfig,
486
- default_permissions: SCAN_PERMISSION_PROFILE,
487
- allow_login_shell: false,
488
- responses_api_metadata: {
489
- ...configuredResponsesMetadata,
490
- codex_security_surface: this.#surface,
491
- },
492
- },
493
- });
395
+ const { codex, environment } = this.#createSessionCodex(session, runtimePaths, options.auth);
494
396
  const thread = codex.startThread({
495
397
  workingDirectory: scanDir,
496
398
  skipGitRepoCheck: true,
497
- approvalPolicy: "never",
399
+ approvalPolicy,
498
400
  });
499
- const serializedPaths = normalized.kind === "paths"
500
- ? JSON.stringify(normalized.paths)
501
- .replaceAll("\u0085", "\\u0085")
502
- .replaceAll("\u2028", "\\u2028")
503
- .replaceAll("\u2029", "\\u2029")
504
- : null;
401
+ const serializedPaths = normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
505
402
  checkOpen();
506
403
  if (serializedPaths !== null && targetPathsFile !== null) {
507
404
  await writeFile(targetPathsFile, `${serializedPaths}\n`, {
@@ -964,6 +861,152 @@ export class CodexSecurity {
964
861
  }
965
862
  }
966
863
  }
864
+ #createSessionCodex(session, runtimePaths, auth = "auto") {
865
+ const { runtime, python, modelProvider, externalProvider, apiKey, sessionConfig, } = session;
866
+ const environment = {
867
+ ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, auth, modelProvider))),
868
+ ...(externalProvider === null
869
+ ? {}
870
+ : { [externalProvider.env_key]: apiKey }),
871
+ CODEX_HOME: runtime.codexHome,
872
+ ...runtimePaths,
873
+ };
874
+ const sdkCodexConfig = { ...sessionConfig };
875
+ // Projects and permissions already live in generated TOML files; the SDK
876
+ // cannot safely encode their path and selector keys as dotted overrides.
877
+ delete sdkCodexConfig["projects"];
878
+ delete sdkCodexConfig["permissions"];
879
+ const configuredResponsesMetadata = isRecord(sdkCodexConfig["responses_api_metadata"])
880
+ ? sdkCodexConfig["responses_api_metadata"]
881
+ : {};
882
+ const codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
883
+ undefined
884
+ ? undefined
885
+ : this.#codexCommand().command;
886
+ const codex = this.#dependencies.createCodex({
887
+ ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
888
+ ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
889
+ env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
890
+ config: {
891
+ ...sdkCodexConfig,
892
+ responses_api_metadata: {
893
+ ...configuredResponsesMetadata,
894
+ codex_security_surface: this.#surface,
895
+ },
896
+ },
897
+ });
898
+ return { codex, environment };
899
+ }
900
+ async #prepareSession({ protectedRoot, stateDirectory, }, options, signal, temporaryRoot, keepCredentialLock = false) {
901
+ let releaseCredentialHome = null;
902
+ const checkOpen = () => {
903
+ this.#requireOpen();
904
+ throwIfAborted(signal);
905
+ };
906
+ try {
907
+ const requestedConfig = await mergedCodexConfig(this.config);
908
+ const modelProvider = scanModelProvider(requestedConfig);
909
+ const externalProvider = isExternalModelProvider(modelProvider)
910
+ ? EXTERNAL_CODEX_PROVIDERS[modelProvider]
911
+ : null;
912
+ let authentication = scanAuthentication(this.#dependencies.environment, options.auth, modelProvider);
913
+ const apiKey = authentication.method === "api_key"
914
+ ? environmentApiKey(this.#dependencies.environment, modelProvider)
915
+ : null;
916
+ if (externalProvider !== null && apiKey === null) {
917
+ throw new AuthenticationRequiredError(`Set ${externalProvider.env_key} to run a scan through ${externalProvider.name}.`);
918
+ }
919
+ const scanEnvironment = selectedScanEnvironment(this.#dependencies.environment, options.auth, modelProvider);
920
+ if (this.#dependencies.prepareRuntime === undefined) {
921
+ const credentialHome = await prepareCodexSecurityCredentialHome(scanEnvironment, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"));
922
+ releaseCredentialHome = await acquireCodexSecurityCredentialHomeLock(credentialHome, signal);
923
+ }
924
+ const previousRuntime = this.#runtime;
925
+ const runtime = await this.#ensureRuntime(signal, temporaryRoot, (path) => requireOutputOutsideRepository(protectedRoot, path, "runtime"), options.auth, requestedConfig);
926
+ if (runtime === previousRuntime &&
927
+ this.#dependencies.prepareRuntime === undefined) {
928
+ await this.#refreshPersistentRuntime(runtime, scanEnvironment, signal, requestedConfig);
929
+ }
930
+ const effectiveConfig = runtime.effectiveConfig ?? requestedConfig;
931
+ const approvalPolicy = scanApprovalPolicy(effectiveConfig);
932
+ const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
933
+ if (runtime.configPath !== undefined) {
934
+ await writeCodexConfig(runtime.configPath, preflightConfig);
935
+ }
936
+ const runtimeHome = await realpath(runtime.codexHome);
937
+ requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
938
+ const sessionConfig = scanRuntimeCodexConfig(effectiveConfig, stateDirectory, runtimeHome);
939
+ if (options.expectedPluginVersion !== undefined &&
940
+ runtime.plugin.version !== options.expectedPluginVersion) {
941
+ throw new CodexSecurityError(`The original scan used plugin version ${options.expectedPluginVersion}, but the installed version is ${runtime.plugin.version}.`);
942
+ }
943
+ checkOpen();
944
+ if (authentication.method === "stored_credentials" &&
945
+ this.#runtimeCredentialSource === "api_key") {
946
+ const ambientHome = environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
947
+ join(homedir(), ".codex");
948
+ runtime.credentialsAvailable = await importAmbientAuth(ambientHome, runtime.codexHome);
949
+ this.#runtimeCredentialSource = runtime.credentialsAvailable
950
+ ? "stored_credentials"
951
+ : null;
952
+ }
953
+ if (!keepCredentialLock || runtime.deepScanConfigPath !== undefined) {
954
+ await releaseCredentialHome?.();
955
+ releaseCredentialHome = null;
956
+ }
957
+ if (externalProvider === null && apiKey !== null) {
958
+ this.#runtimeCredentialSource = "api_key";
959
+ }
960
+ if (!runtime.credentialsAvailable &&
961
+ authentication.method === "stored_credentials") {
962
+ const status = await accountStatus(this.#codexCommand(), runtime.environment, signal);
963
+ runtime.credentialsAvailable = status.authenticated;
964
+ this.#runtimeCredentialSource = status.authenticated
965
+ ? "stored_credentials"
966
+ : null;
967
+ }
968
+ if (!runtime.credentialsAvailable &&
969
+ apiKey === null &&
970
+ authentication.method !== "aws_credentials") {
971
+ throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
972
+ "'codex-security login --device-auth' on a remote or headless machine, or set " +
973
+ "OPENAI_API_KEY or CODEX_API_KEY for CI.");
974
+ }
975
+ authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
976
+ notifyObserver("onAuthentication", options.onAuthentication, options.onObserverError, authentication);
977
+ const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
978
+ configuredPath: this.config.pythonPath,
979
+ environment: scanEnvironment,
980
+ protectedRoot,
981
+ signal,
982
+ });
983
+ checkOpen();
984
+ return {
985
+ runtime,
986
+ runtimeHome,
987
+ effectiveConfig,
988
+ preflightConfig,
989
+ sessionConfig,
990
+ modelProvider,
991
+ externalProvider,
992
+ apiKey,
993
+ scanEnvironment,
994
+ authentication,
995
+ approvalPolicy,
996
+ python,
997
+ releaseCredentialHome,
998
+ };
999
+ }
1000
+ catch (error) {
1001
+ try {
1002
+ await releaseCredentialHome?.();
1003
+ }
1004
+ catch (cleanupError) {
1005
+ warnCleanupFailed(options, cleanupError, "runtime preparation");
1006
+ }
1007
+ throw error;
1008
+ }
1009
+ }
967
1010
  async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto", requestedConfig) {
968
1011
  this.#requireOpen();
969
1012
  if (this.#runtime !== null)
@@ -1168,7 +1211,7 @@ function deepScanOptions(options) {
1168
1211
  return selected;
1169
1212
  }
1170
1213
  async function prepareDeepScanConfig(destination, environment, options, signal) {
1171
- const ambientHome = environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex");
1214
+ const ambientHome = expandHome(environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex"), environment);
1172
1215
  const source = join(ambientHome, "codex-security", "config.toml");
1173
1216
  let configured = {};
1174
1217
  try {
@@ -1189,14 +1232,15 @@ async function prepareDeepScanConfig(destination, environment, options, signal)
1189
1232
  if (value !== undefined)
1190
1233
  overrides[key] = value;
1191
1234
  }
1235
+ const sharedConfig = await sameExistingPath(source, destination);
1192
1236
  const hasOverrides = Object.keys(overrides).length > 0;
1193
1237
  if (existing === undefined && !hasOverrides) {
1194
- if (destination !== source) {
1238
+ if (!sharedConfig) {
1195
1239
  await rm(destination, { force: true });
1196
1240
  }
1197
1241
  return;
1198
1242
  }
1199
- if (destination === source && !hasOverrides)
1243
+ if (sharedConfig && !hasOverrides)
1200
1244
  return;
1201
1245
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1202
1246
  await writeFile(destination, stringifyToml({
@@ -1204,6 +1248,15 @@ async function prepareDeepScanConfig(destination, environment, options, signal)
1204
1248
  deep_scan: { ...existing, ...overrides },
1205
1249
  }), { mode: 0o600, signal });
1206
1250
  }
1251
+ async function sameExistingPath(left, right) {
1252
+ if (left === right)
1253
+ return true;
1254
+ const [canonicalLeft, canonicalRight] = await Promise.all([
1255
+ realpath(left).catch(() => null),
1256
+ realpath(right).catch(() => null),
1257
+ ]);
1258
+ return canonicalLeft !== null && canonicalLeft === canonicalRight;
1259
+ }
1207
1260
  export function createSecurity(config = {}) {
1208
1261
  return createSecurityInternal(config, { surface: "sdk" });
1209
1262
  }
@@ -1223,14 +1276,14 @@ export async function initialCredentialsAvailable(environment, ambientHome, isol
1223
1276
  // Reports a cleanup failure without letting it decide the result of the scan. Only the
1224
1277
  // message is forwarded, and it reaches the onWarning observer alone: unlike the fail-scan
1225
1278
  // path it is never written to the workbench, so it adds no persisted warning text.
1226
- function warnCleanupFailed(options, reason) {
1279
+ function warnCleanupFailed(options, reason, operation = "scan") {
1227
1280
  // This runs where a throw would replace the scan result, so every step is inside the
1228
1281
  // guard: reading the reason, coercing it, and reading the observers off the options can
1229
1282
  // each throw for a sufficiently hostile value, and none of them may become the outcome
1230
1283
  // of the scan. Losing a warning is the correct trade against losing the result.
1231
1284
  try {
1232
1285
  const message = String(reason instanceof Error ? reason.message : reason);
1233
- notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not clean up after the Codex Security scan: ${message}`);
1286
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, `Could not clean up after the Codex Security ${operation}: ${message}`);
1234
1287
  }
1235
1288
  catch { }
1236
1289
  }
@@ -1247,79 +1300,56 @@ async function removeTargetPathsFile(path) {
1247
1300
  await rm(path, { force: true });
1248
1301
  }
1249
1302
  }
1303
+ /** @internal */
1250
1304
  export async function runScanEvents(options) {
1251
- let threadId = options.thread.id;
1252
1305
  let scanStarted = false;
1253
- let status = "in_progress";
1254
- let finalResponse = "";
1255
- let usage = null;
1256
- let lastStreamError = null;
1257
1306
  let tacStatusReported = false;
1258
1307
  try {
1259
- for await (const event of scanEventsWithOptionalUsage(options.events)) {
1260
- if (!tacStatusReported) {
1261
- const tacStatus = trustedAccessStatusFromEvent(event);
1262
- if (tacStatus !== null) {
1263
- tacStatusReported = true;
1264
- notifyObserver("onTrustedAccessStatus", options.onTrustedAccessStatus, options.onObserverError, tacStatus);
1265
- if (tacStatus !== "granted") {
1266
- notifyObserver("onWarning", options.onWarning, options.onObserverError, trustedAccessWarning(tacStatus, options.authentication));
1308
+ const turn = await readCodexTurn({
1309
+ thread: options.thread,
1310
+ events: options.events,
1311
+ onEvent: async (event) => {
1312
+ if (!tacStatusReported) {
1313
+ const tacStatus = trustedAccessStatusFromEvent(event);
1314
+ if (tacStatus !== null) {
1315
+ tacStatusReported = true;
1316
+ notifyObserver("onTrustedAccessStatus", options.onTrustedAccessStatus, options.onObserverError, tacStatus);
1317
+ if (tacStatus !== "granted") {
1318
+ notifyObserver("onWarning", options.onWarning, options.onObserverError, trustedAccessWarning(tacStatus, options.authentication));
1319
+ }
1267
1320
  }
1268
1321
  }
1269
- }
1270
- for (const activity of scanActivitiesFromEvent(event, options.expectation.repository)) {
1271
- notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
1272
- }
1273
- for (const progress of scanProgressUpdatesFromEvent(event)) {
1274
- if (options.expectedFilesTotal !== undefined &&
1275
- progress.filesTotal !== options.expectedFilesTotal) {
1276
- continue;
1322
+ for (const activity of scanActivitiesFromEvent(event, options.expectation.repository)) {
1323
+ notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
1277
1324
  }
1278
- notifyObserver("onProgress", options.onProgress, options.onObserverError, progress);
1279
- }
1280
- const workerStatus = workerStatusFromEvent(event);
1281
- if (workerStatus !== null) {
1282
- notifyObserver("onWorkerStatus", options.onWorkerStatus, options.onObserverError, workerStatus);
1283
- }
1284
- if (event.type === "thread.started") {
1285
- const startedThreadId = event["thread_id"];
1286
- if (typeof startedThreadId === "string") {
1287
- threadId = startedThreadId;
1288
- await options.onThreadStarted?.(startedThreadId);
1325
+ for (const progress of scanProgressUpdatesFromEvent(event)) {
1326
+ if (options.expectedFilesTotal !== undefined &&
1327
+ progress.filesTotal !== options.expectedFilesTotal) {
1328
+ continue;
1329
+ }
1330
+ notifyObserver("onProgress", options.onProgress, options.onObserverError, progress);
1289
1331
  }
1290
- if (!scanStarted) {
1291
- scanStarted = true;
1292
- notifyObserver("onScanStarted", options.onScanStarted, options.onObserverError);
1332
+ const workerStatus = workerStatusFromEvent(event);
1333
+ if (workerStatus !== null) {
1334
+ notifyObserver("onWorkerStatus", options.onWorkerStatus, options.onObserverError, workerStatus);
1293
1335
  }
1294
- }
1295
- else if (event.type === "item.completed" &&
1296
- isRecord(event["item"]) &&
1297
- event["item"]["type"] === "agent_message" &&
1298
- typeof event["item"]["text"] === "string") {
1299
- finalResponse = event["item"]["text"];
1300
- }
1301
- else if (event.type === "turn.completed") {
1302
- status = "completed";
1303
- usage = event["usage"];
1304
- }
1305
- else if (event.type === "turn.failed") {
1306
- throw new CodexSecurityError(turnFailureMessage(event["error"]));
1307
- }
1308
- else if (event.type === "error" &&
1309
- typeof event["message"] === "string") {
1310
- const message = event["message"];
1311
- const classification = classifyConnectionFailure(message);
1312
- if (classification === "unauthorized" ||
1313
- classification === "forbidden") {
1314
- throw new CodexSecurityError(message);
1336
+ if (event.type === "thread.started") {
1337
+ const startedThreadId = event["thread_id"];
1338
+ if (typeof startedThreadId === "string") {
1339
+ await options.onThreadStarted?.(startedThreadId);
1340
+ }
1341
+ if (!scanStarted) {
1342
+ scanStarted = true;
1343
+ notifyObserver("onScanStarted", options.onScanStarted, options.onObserverError);
1344
+ }
1315
1345
  }
1316
- const reconnect = reconnectAttempt(message);
1317
- if (reconnect === null)
1318
- throw new CodexSecurityError(message);
1319
- lastStreamError = message;
1346
+ },
1347
+ onReconnect: (message, reconnect) => {
1320
1348
  notifyObserver("onReconnect", options.onReconnect, options.onObserverError, ...reconnect, reconnectDetails(message));
1321
- }
1322
- }
1349
+ },
1350
+ });
1351
+ const { status, threadId, finalResponse, lastStreamError } = turn;
1352
+ let { usage } = turn;
1323
1353
  if (options.signal.aborted) {
1324
1354
  throw new ScanInterruptedError(`Codex Security scan was interrupted; partial output remains at ${options.scanDir}.`, options.scanDir);
1325
1355
  }
@@ -1354,7 +1384,47 @@ export async function runScanEvents(options) {
1354
1384
  throw error;
1355
1385
  }
1356
1386
  }
1357
- async function* scanEventsWithOptionalUsage(events) {
1387
+ async function readCodexTurn(options) {
1388
+ let threadId = options.thread.id;
1389
+ let status = "in_progress";
1390
+ let finalResponse = "";
1391
+ let usage = null;
1392
+ let lastStreamError = null;
1393
+ for await (const event of eventsWithOptionalUsage(options.events)) {
1394
+ await options.onEvent?.(event);
1395
+ if (event.type === "thread.started" &&
1396
+ typeof event["thread_id"] === "string") {
1397
+ threadId = event["thread_id"];
1398
+ }
1399
+ else if (event.type === "item.completed" &&
1400
+ isRecord(event["item"]) &&
1401
+ event["item"]["type"] === "agent_message" &&
1402
+ typeof event["item"]["text"] === "string") {
1403
+ finalResponse = event["item"]["text"];
1404
+ }
1405
+ else if (event.type === "turn.completed") {
1406
+ status = "completed";
1407
+ usage = event["usage"];
1408
+ }
1409
+ else if (event.type === "turn.failed") {
1410
+ throw new CodexSecurityError(turnFailureMessage(event["error"]));
1411
+ }
1412
+ else if (event.type === "error" && typeof event["message"] === "string") {
1413
+ const message = event["message"];
1414
+ const classification = classifyConnectionFailure(message);
1415
+ if (classification === "unauthorized" || classification === "forbidden") {
1416
+ throw new CodexSecurityError(message);
1417
+ }
1418
+ const reconnect = reconnectAttempt(message);
1419
+ if (reconnect === null)
1420
+ throw new CodexSecurityError(message);
1421
+ lastStreamError = message;
1422
+ options.onReconnect?.(message, reconnect);
1423
+ }
1424
+ }
1425
+ return { threadId, status, finalResponse, usage, lastStreamError };
1426
+ }
1427
+ async function* eventsWithOptionalUsage(events) {
1358
1428
  try {
1359
1429
  yield* events;
1360
1430
  }
@@ -1431,7 +1501,7 @@ function trustedAccessWarning(status, authentication) {
1431
1501
  return `Some cybersecurity requests or findings may be refused because ${access} could not be verified. Check ${action} or apply at ${applicationUrl}.`;
1432
1502
  }
1433
1503
  function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false) {
1434
- const python = `${process.platform === "win32" ? "& " : ""}${shellEnvironmentReference("PYTHON")}`;
1504
+ const python = pluginPythonCommand();
1435
1505
  return [
1436
1506
  `Use the installed $codex-security:${skillName} skill at ${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", `/skills/${skillName}/SKILL.md`)}.`,
1437
1507
  "Run this Codex Security scan non-interactively.",
@@ -1507,10 +1577,6 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
1507
1577
  : []),
1508
1578
  ].join("\n");
1509
1579
  }
1510
- function shellEnvironmentReference(name, suffix = "") {
1511
- const prefix = process.platform === "win32" ? "$env:" : "$";
1512
- return `"${prefix}${name}${suffix}"`;
1513
- }
1514
1580
  function skillNameFor(target, mode) {
1515
1581
  if (target.kind === "refs" || target.kind === "working_tree")
1516
1582
  return "security-diff-scan";
@@ -1759,6 +1825,7 @@ export function classifyConnectionFailure(error) {
1759
1825
  return "unknown";
1760
1826
  }
1761
1827
  export function scanRuntimeCodexConfig(config, stateDirectory, protectedCredentialHome) {
1828
+ const approvalPolicy = scanApprovalPolicy(config);
1762
1829
  const hardened = structuredClone(config);
1763
1830
  delete hardened["sandbox_mode"];
1764
1831
  delete hardened["approvals_reviewer"];
@@ -1779,7 +1846,8 @@ export function scanRuntimeCodexConfig(config, stateDirectory, protectedCredenti
1779
1846
  : {};
1780
1847
  return {
1781
1848
  ...hardened,
1782
- approval_policy: "never",
1849
+ approval_policy: approvalPolicy,
1850
+ approvals_reviewer: "auto_review",
1783
1851
  allow_login_shell: false,
1784
1852
  default_permissions: SCAN_PERMISSION_PROFILE,
1785
1853
  permissions: {
@@ -1799,6 +1867,7 @@ export function scanRuntimeCodexConfig(config, stateDirectory, protectedCredenti
1799
1867
  }
1800
1868
  function sharedCredentialCodexConfig(config, stateDirectory, credentialHome) {
1801
1869
  const shared = {
1870
+ approval_policy: scanApprovalPolicy(config),
1802
1871
  features: { plugins: true },
1803
1872
  };
1804
1873
  for (const key of [
@@ -1974,20 +2043,6 @@ async function pluginSupportsIsolatedDeepScanConfig(pluginRoot) {
1974
2043
  return (Array.isArray(environment) &&
1975
2044
  environment.includes(DEEP_SCAN_CONFIG_PATH_ENVIRONMENT));
1976
2045
  }
1977
- function requireOutputOutsideRepository(repository, outputDirectory, pathKind = "output") {
1978
- const outputRelative = relative(repository, outputDirectory);
1979
- const repositoryRelative = relative(outputDirectory, repository);
1980
- if (outputRelative === "" ||
1981
- (outputRelative !== ".." &&
1982
- !outputRelative.startsWith(`..${sep}`) &&
1983
- !isAbsolute(outputRelative)) ||
1984
- (pathKind === "output" &&
1985
- repositoryRelative !== ".." &&
1986
- !repositoryRelative.startsWith(`..${sep}`) &&
1987
- !isAbsolute(repositoryRelative))) {
1988
- throw new OutputInsideProtectedRootError(outputDirectory, repository, pathKind);
1989
- }
1990
- }
1991
2046
  function throwIfAborted(signal, scanDir = "") {
1992
2047
  if (!signal?.aborted)
1993
2048
  return;