@openai/codex-security 0.1.14 → 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 (98) hide show
  1. package/README.md +74 -19
  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 +259 -209
  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 +782 -120
  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/contract.d.ts.map +1 -1
  43. package/dist/contract.js +198 -2
  44. package/dist/contract.js.map +1 -1
  45. package/dist/cost.d.ts +7 -0
  46. package/dist/cost.d.ts.map +1 -1
  47. package/dist/cost.js +68 -47
  48. package/dist/cost.js.map +1 -1
  49. package/dist/errors.d.ts +4 -0
  50. package/dist/errors.d.ts.map +1 -1
  51. package/dist/errors.js +9 -0
  52. package/dist/errors.js.map +1 -1
  53. package/dist/index.d.ts +2 -2
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +1 -1
  56. package/dist/index.js.map +1 -1
  57. package/dist/linear.d.ts +19 -0
  58. package/dist/linear.d.ts.map +1 -0
  59. package/dist/linear.js +106 -0
  60. package/dist/linear.js.map +1 -0
  61. package/dist/models.d.ts +89 -2
  62. package/dist/models.d.ts.map +1 -1
  63. package/dist/models.js.map +1 -1
  64. package/dist/multiscan.d.ts.map +1 -1
  65. package/dist/multiscan.js +7 -6
  66. package/dist/multiscan.js.map +1 -1
  67. package/dist/patch-tui.d.ts +28 -0
  68. package/dist/patch-tui.d.ts.map +1 -0
  69. package/dist/patch-tui.js +384 -0
  70. package/dist/patch-tui.js.map +1 -0
  71. package/dist/publish.d.ts +2 -2
  72. package/dist/publish.d.ts.map +1 -1
  73. package/dist/publish.js +4 -8
  74. package/dist/publish.js.map +1 -1
  75. package/dist/runtime.d.ts +10 -7
  76. package/dist/runtime.d.ts.map +1 -1
  77. package/dist/runtime.js +63 -35
  78. package/dist/runtime.js.map +1 -1
  79. package/dist/scan-comparison.d.ts +2 -1
  80. package/dist/scan-comparison.d.ts.map +1 -1
  81. package/dist/scan-comparison.js +17 -15
  82. package/dist/scan-comparison.js.map +1 -1
  83. package/dist/scan-dashboard.d.ts +2 -1
  84. package/dist/scan-dashboard.d.ts.map +1 -1
  85. package/dist/scan-dashboard.js +219 -11
  86. package/dist/scan-dashboard.js.map +1 -1
  87. package/dist/targets.d.ts +1 -0
  88. package/dist/targets.d.ts.map +1 -1
  89. package/dist/targets.js +4 -2
  90. package/dist/targets.js.map +1 -1
  91. package/dist/trusted-executable.d.ts.map +1 -1
  92. package/dist/trusted-executable.js +26 -11
  93. package/dist/trusted-executable.js.map +1 -1
  94. package/dist/version.d.ts +1 -1
  95. package/dist/version.js +1 -1
  96. package/dist/version.js.map +1 -1
  97. package/package.json +7 -3
  98. 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 { jsonForPrompt, pluginPythonCommand, shellEnvironmentReference, } from "./codex-prompt.js";
9
10
  import { EXTERNAL_CODEX_PROVIDERS, isExternalModelProvider, mergedCodexConfig, scanApprovalPolicy, scanModelConfiguration, scanModelProvider, writeCodexConfig, } from "./config.js";
10
- import { estimateScanCost, ScanCostTracker } from "./cost.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,38 +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 approvalPolicy = scanApprovalPolicy(effectiveConfig);
161
- const preflightConfig = scanPreflightCodexConfig(effectiveConfig);
162
- if (runtime.configPath !== undefined) {
163
- await writeCodexConfig(runtime.configPath, preflightConfig);
164
- }
165
- const runtimeHome = await realpath(runtime.codexHome);
166
- requireOutputOutsideRepository(protectedRoot, runtimeHome, "runtime");
167
- 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;
168
143
  const deepScanConfigPath = mode === "deep"
169
144
  ? runtime.deepScanConfigPath ??
170
145
  join(runtimeHome, "codex-security", "config.toml")
@@ -172,54 +147,10 @@ export class CodexSecurity {
172
147
  if (deepScanConfigPath !== undefined) {
173
148
  await prepareDeepScanConfig(deepScanConfigPath, this.#dependencies.environment, options, signal);
174
149
  }
175
- if (options.expectedPluginVersion !== undefined &&
176
- runtime.plugin.version !== options.expectedPluginVersion) {
177
- throw new CodexSecurityError(`The original scan used plugin version ${options.expectedPluginVersion}, but the installed version is ${runtime.plugin.version}.`);
178
- }
179
- checkOpen();
180
- if (authentication.method === "stored_credentials" &&
181
- this.#runtimeCredentialSource === "api_key") {
182
- const ambientHome = environmentValue(this.#dependencies.environment, "CODEX_HOME") ??
183
- join(homedir(), ".codex");
184
- runtime.credentialsAvailable = await importAmbientAuth(ambientHome, runtime.codexHome);
185
- this.#runtimeCredentialSource = runtime.credentialsAvailable
186
- ? "stored_credentials"
187
- : null;
188
- }
189
- if (mode !== "deep" || runtime.deepScanConfigPath !== undefined) {
190
- await releaseCredentialHome?.();
191
- releaseCredentialHome = null;
192
- }
193
- if (externalProvider === null && apiKey !== null) {
194
- this.#runtimeCredentialSource = "api_key";
195
- }
196
- if (!runtime.credentialsAvailable &&
197
- authentication.method === "stored_credentials") {
198
- const status = await accountStatus(this.#codexCommand(), runtime.environment, signal);
199
- runtime.credentialsAvailable = status.authenticated;
200
- this.#runtimeCredentialSource = status.authenticated
201
- ? "stored_credentials"
202
- : null;
203
- }
204
- if (!runtime.credentialsAvailable &&
205
- apiKey === null &&
206
- authentication.method !== "aws_credentials") {
207
- throw new AuthenticationRequiredError("No credentials were found. Run 'codex-security login', use " +
208
- "'codex-security login --device-auth' on a remote or headless machine, or set " +
209
- "OPENAI_API_KEY or CODEX_API_KEY for CI.");
210
- }
211
- authentication = await runtimeScanAuthentication(this.#dependencies.environment, runtime.codexHome, options.auth, modelProvider);
212
- notifyObserver("onAuthentication", options.onAuthentication, options.onObserverError, authentication);
213
- const python = await (this.#dependencies.resolvePluginPython ?? resolvePluginPython)({
214
- configuredPath: this.config.pythonPath,
215
- environment: scanEnvironment,
216
- protectedRoot,
217
- signal,
218
- });
219
150
  checkOpen();
220
151
  const scanOutputRoot = requestedOutput === null &&
221
152
  this.#dependencies.prepareOutputDir === undefined
222
- ? await preparePersistentScanRoot(stateDirectory, basename(repo))
153
+ ? await preparePersistentOutputRoot(stateDirectory, "scans", basename(repo))
223
154
  : temporaryRoot;
224
155
  if (scanOutputRoot !== undefined) {
225
156
  requireOutputOutsideRepository(protectedRoot, scanOutputRoot, scanOutputRoot === temporaryRoot ? "temporary" : "output");
@@ -294,6 +225,9 @@ export class CodexSecurity {
294
225
  onActivity: options.onActivity === undefined
295
226
  ? undefined
296
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),
297
231
  onProgress: options.onProgress === undefined ? undefined : reportProgress,
298
232
  onCost: options.onCost === undefined && options.maxCostUsd === undefined
299
233
  ? undefined
@@ -458,52 +392,13 @@ export class CodexSecurity {
458
392
  ? {}
459
393
  : { CODEX_SECURITY_TARGET_PATHS_FILE: targetPathsFile }),
460
394
  };
461
- const environment = {
462
- ...pluginExecutionEnvironment(python, withoutCodexHome(selectedScanEnvironment(runtime.environment, options.auth, modelProvider))),
463
- ...(externalProvider === null
464
- ? {}
465
- : { [externalProvider.env_key]: apiKey }),
466
- CODEX_HOME: runtime.codexHome,
467
- ...runtimePaths,
468
- };
469
- const sdkCodexConfig = { ...sessionConfig };
470
- // Projects and permissions already live in generated TOML files; the SDK
471
- // cannot safely encode their path and selector keys as dotted overrides.
472
- delete sdkCodexConfig["projects"];
473
- delete sdkCodexConfig["permissions"];
474
- const configuredResponsesMetadata = isRecord(sdkCodexConfig["responses_api_metadata"])
475
- ? sdkCodexConfig["responses_api_metadata"]
476
- : {};
477
- const codexPathOverride = environmentValue(this.#dependencies.environment, "CODEX_CLI_PATH") ===
478
- undefined
479
- ? undefined
480
- : this.#codexCommand().command;
481
- const codex = this.#dependencies.createCodex({
482
- ...(codexPathOverride === undefined ? {} : { codexPathOverride }),
483
- ...(externalProvider !== null || apiKey === null ? {} : { apiKey }),
484
- env: definedEnvironment(selectedScanEnvironment(environment, "chatgpt")),
485
- config: {
486
- ...sdkCodexConfig,
487
- approvals_reviewer: "auto_review",
488
- default_permissions: SCAN_PERMISSION_PROFILE,
489
- allow_login_shell: false,
490
- responses_api_metadata: {
491
- ...configuredResponsesMetadata,
492
- codex_security_surface: this.#surface,
493
- },
494
- },
495
- });
395
+ const { codex, environment } = this.#createSessionCodex(session, runtimePaths, options.auth);
496
396
  const thread = codex.startThread({
497
397
  workingDirectory: scanDir,
498
398
  skipGitRepoCheck: true,
499
399
  approvalPolicy,
500
400
  });
501
- const serializedPaths = normalized.kind === "paths"
502
- ? JSON.stringify(normalized.paths)
503
- .replaceAll("\u0085", "\\u0085")
504
- .replaceAll("\u2028", "\\u2028")
505
- .replaceAll("\u2029", "\\u2029")
506
- : null;
401
+ const serializedPaths = normalized.kind === "paths" ? jsonForPrompt(normalized.paths) : null;
507
402
  checkOpen();
508
403
  if (serializedPaths !== null && targetPathsFile !== null) {
509
404
  await writeFile(targetPathsFile, `${serializedPaths}\n`, {
@@ -966,6 +861,152 @@ export class CodexSecurity {
966
861
  }
967
862
  }
968
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
+ }
969
1010
  async #ensureRuntime(signal, temporaryRoot, validateLocation, auth = "auto", requestedConfig) {
970
1011
  this.#requireOpen();
971
1012
  if (this.#runtime !== null)
@@ -1170,7 +1211,7 @@ function deepScanOptions(options) {
1170
1211
  return selected;
1171
1212
  }
1172
1213
  async function prepareDeepScanConfig(destination, environment, options, signal) {
1173
- const ambientHome = environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex");
1214
+ const ambientHome = expandHome(environmentValue(environment, "CODEX_HOME") ?? join(homedir(), ".codex"), environment);
1174
1215
  const source = join(ambientHome, "codex-security", "config.toml");
1175
1216
  let configured = {};
1176
1217
  try {
@@ -1191,14 +1232,15 @@ async function prepareDeepScanConfig(destination, environment, options, signal)
1191
1232
  if (value !== undefined)
1192
1233
  overrides[key] = value;
1193
1234
  }
1235
+ const sharedConfig = await sameExistingPath(source, destination);
1194
1236
  const hasOverrides = Object.keys(overrides).length > 0;
1195
1237
  if (existing === undefined && !hasOverrides) {
1196
- if (destination !== source) {
1238
+ if (!sharedConfig) {
1197
1239
  await rm(destination, { force: true });
1198
1240
  }
1199
1241
  return;
1200
1242
  }
1201
- if (destination === source && !hasOverrides)
1243
+ if (sharedConfig && !hasOverrides)
1202
1244
  return;
1203
1245
  await mkdir(dirname(destination), { recursive: true, mode: 0o700 });
1204
1246
  await writeFile(destination, stringifyToml({
@@ -1206,6 +1248,15 @@ async function prepareDeepScanConfig(destination, environment, options, signal)
1206
1248
  deep_scan: { ...existing, ...overrides },
1207
1249
  }), { mode: 0o600, signal });
1208
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
+ }
1209
1260
  export function createSecurity(config = {}) {
1210
1261
  return createSecurityInternal(config, { surface: "sdk" });
1211
1262
  }
@@ -1225,14 +1276,14 @@ export async function initialCredentialsAvailable(environment, ambientHome, isol
1225
1276
  // Reports a cleanup failure without letting it decide the result of the scan. Only the
1226
1277
  // message is forwarded, and it reaches the onWarning observer alone: unlike the fail-scan
1227
1278
  // path it is never written to the workbench, so it adds no persisted warning text.
1228
- function warnCleanupFailed(options, reason) {
1279
+ function warnCleanupFailed(options, reason, operation = "scan") {
1229
1280
  // This runs where a throw would replace the scan result, so every step is inside the
1230
1281
  // guard: reading the reason, coercing it, and reading the observers off the options can
1231
1282
  // each throw for a sufficiently hostile value, and none of them may become the outcome
1232
1283
  // of the scan. Losing a warning is the correct trade against losing the result.
1233
1284
  try {
1234
1285
  const message = String(reason instanceof Error ? reason.message : reason);
1235
- 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}`);
1236
1287
  }
1237
1288
  catch { }
1238
1289
  }
@@ -1249,79 +1300,56 @@ async function removeTargetPathsFile(path) {
1249
1300
  await rm(path, { force: true });
1250
1301
  }
1251
1302
  }
1303
+ /** @internal */
1252
1304
  export async function runScanEvents(options) {
1253
- let threadId = options.thread.id;
1254
1305
  let scanStarted = false;
1255
- let status = "in_progress";
1256
- let finalResponse = "";
1257
- let usage = null;
1258
- let lastStreamError = null;
1259
1306
  let tacStatusReported = false;
1260
1307
  try {
1261
- for await (const event of scanEventsWithOptionalUsage(options.events)) {
1262
- if (!tacStatusReported) {
1263
- const tacStatus = trustedAccessStatusFromEvent(event);
1264
- if (tacStatus !== null) {
1265
- tacStatusReported = true;
1266
- notifyObserver("onTrustedAccessStatus", options.onTrustedAccessStatus, options.onObserverError, tacStatus);
1267
- if (tacStatus !== "granted") {
1268
- 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
+ }
1269
1320
  }
1270
1321
  }
1271
- }
1272
- for (const activity of scanActivitiesFromEvent(event, options.expectation.repository)) {
1273
- notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
1274
- }
1275
- for (const progress of scanProgressUpdatesFromEvent(event)) {
1276
- if (options.expectedFilesTotal !== undefined &&
1277
- progress.filesTotal !== options.expectedFilesTotal) {
1278
- continue;
1322
+ for (const activity of scanActivitiesFromEvent(event, options.expectation.repository)) {
1323
+ notifyObserver("onActivity", options.onActivity, options.onObserverError, activity);
1279
1324
  }
1280
- notifyObserver("onProgress", options.onProgress, options.onObserverError, progress);
1281
- }
1282
- const workerStatus = workerStatusFromEvent(event);
1283
- if (workerStatus !== null) {
1284
- notifyObserver("onWorkerStatus", options.onWorkerStatus, options.onObserverError, workerStatus);
1285
- }
1286
- if (event.type === "thread.started") {
1287
- const startedThreadId = event["thread_id"];
1288
- if (typeof startedThreadId === "string") {
1289
- threadId = startedThreadId;
1290
- 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);
1291
1331
  }
1292
- if (!scanStarted) {
1293
- scanStarted = true;
1294
- notifyObserver("onScanStarted", options.onScanStarted, options.onObserverError);
1332
+ const workerStatus = workerStatusFromEvent(event);
1333
+ if (workerStatus !== null) {
1334
+ notifyObserver("onWorkerStatus", options.onWorkerStatus, options.onObserverError, workerStatus);
1295
1335
  }
1296
- }
1297
- else if (event.type === "item.completed" &&
1298
- isRecord(event["item"]) &&
1299
- event["item"]["type"] === "agent_message" &&
1300
- typeof event["item"]["text"] === "string") {
1301
- finalResponse = event["item"]["text"];
1302
- }
1303
- else if (event.type === "turn.completed") {
1304
- status = "completed";
1305
- usage = event["usage"];
1306
- }
1307
- else if (event.type === "turn.failed") {
1308
- throw new CodexSecurityError(turnFailureMessage(event["error"]));
1309
- }
1310
- else if (event.type === "error" &&
1311
- typeof event["message"] === "string") {
1312
- const message = event["message"];
1313
- const classification = classifyConnectionFailure(message);
1314
- if (classification === "unauthorized" ||
1315
- classification === "forbidden") {
1316
- 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
+ }
1317
1345
  }
1318
- const reconnect = reconnectAttempt(message);
1319
- if (reconnect === null)
1320
- throw new CodexSecurityError(message);
1321
- lastStreamError = message;
1346
+ },
1347
+ onReconnect: (message, reconnect) => {
1322
1348
  notifyObserver("onReconnect", options.onReconnect, options.onObserverError, ...reconnect, reconnectDetails(message));
1323
- }
1324
- }
1349
+ },
1350
+ });
1351
+ const { status, threadId, finalResponse, lastStreamError } = turn;
1352
+ let { usage } = turn;
1325
1353
  if (options.signal.aborted) {
1326
1354
  throw new ScanInterruptedError(`Codex Security scan was interrupted; partial output remains at ${options.scanDir}.`, options.scanDir);
1327
1355
  }
@@ -1356,7 +1384,47 @@ export async function runScanEvents(options) {
1356
1384
  throw error;
1357
1385
  }
1358
1386
  }
1359
- 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) {
1360
1428
  try {
1361
1429
  yield* events;
1362
1430
  }
@@ -1433,7 +1501,7 @@ function trustedAccessWarning(status, authentication) {
1433
1501
  return `Some cybersecurity requests or findings may be refused because ${access} could not be verified. Check ${action} or apply at ${applicationUrl}.`;
1434
1502
  }
1435
1503
  function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasKnowledgeBase = false, additionalPrompt, enforceCostLimit = false) {
1436
- const python = `${process.platform === "win32" ? "& " : ""}${shellEnvironmentReference("PYTHON")}`;
1504
+ const python = pluginPythonCommand();
1437
1505
  return [
1438
1506
  `Use the installed $codex-security:${skillName} skill at ${shellEnvironmentReference("CODEX_SECURITY_PLUGIN_ROOT", `/skills/${skillName}/SKILL.md`)}.`,
1439
1507
  "Run this Codex Security scan non-interactively.",
@@ -1509,10 +1577,6 @@ function scanPrompt(target, mode, skillName, scanId, hasConfigPath = false, hasK
1509
1577
  : []),
1510
1578
  ].join("\n");
1511
1579
  }
1512
- function shellEnvironmentReference(name, suffix = "") {
1513
- const prefix = process.platform === "win32" ? "$env:" : "$";
1514
- return `"${prefix}${name}${suffix}"`;
1515
- }
1516
1580
  function skillNameFor(target, mode) {
1517
1581
  if (target.kind === "refs" || target.kind === "working_tree")
1518
1582
  return "security-diff-scan";
@@ -1979,20 +2043,6 @@ async function pluginSupportsIsolatedDeepScanConfig(pluginRoot) {
1979
2043
  return (Array.isArray(environment) &&
1980
2044
  environment.includes(DEEP_SCAN_CONFIG_PATH_ENVIRONMENT));
1981
2045
  }
1982
- function requireOutputOutsideRepository(repository, outputDirectory, pathKind = "output") {
1983
- const outputRelative = relative(repository, outputDirectory);
1984
- const repositoryRelative = relative(outputDirectory, repository);
1985
- if (outputRelative === "" ||
1986
- (outputRelative !== ".." &&
1987
- !outputRelative.startsWith(`..${sep}`) &&
1988
- !isAbsolute(outputRelative)) ||
1989
- (pathKind === "output" &&
1990
- repositoryRelative !== ".." &&
1991
- !repositoryRelative.startsWith(`..${sep}`) &&
1992
- !isAbsolute(repositoryRelative))) {
1993
- throw new OutputInsideProtectedRootError(outputDirectory, repository, pathKind);
1994
- }
1995
- }
1996
2046
  function throwIfAborted(signal, scanDir = "") {
1997
2047
  if (!signal?.aborted)
1998
2048
  return;