@openai/codex-security 0.1.3 → 0.1.5

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 (49) hide show
  1. package/README.md +224 -14
  2. package/_bundled_plugin/examples/completed-scan/findings.json +6 -0
  3. package/_bundled_plugin/examples/completed-scan/scan-manifest.json +1 -1
  4. package/_bundled_plugin/references/finding-detail-fields.md +10 -2
  5. package/_bundled_plugin/references/scan-contract.md +2 -0
  6. package/_bundled_plugin/scripts/finalize_scan_contract.py +18 -0
  7. package/_bundled_plugin/scripts/workbench_cli.py +4 -0
  8. package/_bundled_plugin/scripts/workbench_db.py +93 -23
  9. package/_bundled_plugin/scripts/workbench_scan_start.py +13 -0
  10. package/_bundled_plugin/scripts/workbench_target.py +14 -1
  11. package/dist/api.d.ts +3 -2
  12. package/dist/api.d.ts.map +1 -1
  13. package/dist/api.js +288 -70
  14. package/dist/api.js.map +1 -1
  15. package/dist/auth.d.ts.map +1 -1
  16. package/dist/auth.js +262 -44
  17. package/dist/auth.js.map +1 -1
  18. package/dist/cli.d.ts +4 -3
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +364 -154
  21. package/dist/cli.js.map +1 -1
  22. package/dist/config.d.ts.map +1 -1
  23. package/dist/config.js +29 -1
  24. package/dist/config.js.map +1 -1
  25. package/dist/contract.d.ts +1 -0
  26. package/dist/contract.d.ts.map +1 -1
  27. package/dist/contract.js +33 -22
  28. package/dist/contract.js.map +1 -1
  29. package/dist/cost.d.ts.map +1 -1
  30. package/dist/cost.js +57 -14
  31. package/dist/cost.js.map +1 -1
  32. package/dist/errors.d.ts +2 -0
  33. package/dist/errors.d.ts.map +1 -1
  34. package/dist/errors.js +48 -0
  35. package/dist/errors.js.map +1 -1
  36. package/dist/multiscan.d.ts.map +1 -1
  37. package/dist/multiscan.js +2 -7
  38. package/dist/multiscan.js.map +1 -1
  39. package/dist/runtime.d.ts +34 -0
  40. package/dist/runtime.d.ts.map +1 -1
  41. package/dist/runtime.js +655 -20
  42. package/dist/runtime.js.map +1 -1
  43. package/dist/scan-comparison.d.ts +2 -0
  44. package/dist/scan-comparison.d.ts.map +1 -1
  45. package/dist/scan-comparison.js +26 -2
  46. package/dist/scan-comparison.js.map +1 -1
  47. package/dist/trusted-executable.js +1 -1
  48. package/dist/trusted-executable.js.map +1 -1
  49. package/package.json +5 -4
package/dist/cli.js CHANGED
@@ -1,11 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { execFileSync, spawn } from "node:child_process";
3
- import { accessSync, constants, lstatSync, realpathSync, writeSync, } from "node:fs";
3
+ import { accessSync, constants, existsSync, lstatSync, realpathSync, writeSync, } from "node:fs";
4
4
  import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
5
5
  import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep, win32, } from "node:path";
6
6
  import { cwd } from "node:process";
7
- import { createInterface } from "node:readline";
8
- import { Readable, Writable as NodeWritable } from "node:stream";
7
+ import { Writable as NodeWritable } from "node:stream";
9
8
  import { pipeline } from "node:stream/promises";
10
9
  import { fileURLToPath, pathToFileURL } from "node:url";
11
10
  import { Cli, z } from "incur";
@@ -15,9 +14,9 @@ import { accountStatus } from "./auth.js";
15
14
  import { createBulkScanDiscoveryDependencies, runBulkScanWizard, } from "./bulk-scan-discovery.js";
16
15
  import { DEFAULT_CODEX_CONFIG, mergedCodexConfig, scanModelConfiguration, } from "./config.js";
17
16
  import { formatUsd } from "./cost.js";
18
- import { CodexSecurityError, OutputInsideProtectedRootError, ScanInterruptedError, } from "./errors.js";
17
+ import { CodexSecurityError, ConfigurationError, InvalidTargetError, OutputDirectoryError, OutputInsideProtectedRootError, PluginPythonUnavailableError, redactedErrorMessage, ScanInterruptedError, } from "./errors.js";
19
18
  import { runMultiscan } from "./multiscan.js";
20
- import { bundledPluginRoot, codexSecurityStateDirectory, expandHome, resolveCodexCommand, resolvePluginPython, runWorkbench, } from "./runtime.js";
19
+ import { bundledPluginRoot, codexSecurityCredentialHome, codexSecurityStateDirectory, expandHome, prepareCodexSecurityCredentialHome, resolveCodexCommand, resolvePluginPython, runWorkbench, setCodexSecurityCredentialLogout, } from "./runtime.js";
21
20
  import { matchScanFindings, } from "./scan-comparison.js";
22
21
  import { renderScanHistory, } from "./scan-history-renderer.js";
23
22
  import { DiffTarget } from "./targets.js";
@@ -28,11 +27,15 @@ const MAX_CODEX_OVERRIDE_VALUE_LENGTH = 64 * 1_024;
28
27
  const MAX_CODEX_OVERRIDE_DEPTH = 64;
29
28
  const MAX_SKILL_INPUT_BYTES = 1_024 * 1_024;
30
29
  const MAX_SKILL_INPUT_COUNT = 64;
30
+ const MAX_SKILL_EVENT_BYTES = 1_024 * 1_024;
31
+ const MAX_SKILL_RESPONSE_BYTES = 256 * 1_024;
32
+ const SKILL_OUTPUT_LIMIT_MESSAGE = "Codex skill output exceeded the 1 MiB event or 256 KiB response safety limit.";
31
33
  const WINDOWS_NETWORK_PATH = /^[\\/]{2}/u;
32
34
  const WINDOWS_LOCAL_DEVICE_ROOT = /^[\\/]{2}[?.][\\/](?:[A-Za-z]:|Volume\{[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\}|GLOBALROOT[\\/]Device[\\/]HarddiskVolume[0-9]+)(?=[\\/]|$)/iu;
33
35
  const SCAN_HISTORY_OUTPUT_OPTION = /^--(?:format|filter-output|full-output|token-count|token-limit|token-offset)(?:=|$)/u;
34
36
  const HIDE_CURSOR = "\u001B[?25l";
35
37
  const SHOW_CURSOR = "\u001B[?25h";
38
+ const CHILD_TERMINATION_GRACE_MS = 1_000;
36
39
  const REPORTABLE_SEVERITIES = [
37
40
  "critical",
38
41
  "high",
@@ -51,6 +54,9 @@ const MODEL_REASONING_EFFORTS = [
51
54
  "xhigh",
52
55
  ];
53
56
  const DEFAULT_SCAN_MODEL_CONFIGURATION = scanModelConfiguration(DEFAULT_CODEX_CONFIG);
57
+ const CODEX_OVERRIDE_DESCRIPTION = 'Repeat TOML KEY=VALUE; e.g. model_reasoning_effort="high" or features.multi_agent_v2.max_concurrent_threads_per_session=4.';
58
+ const PLUGIN_PATH_DESCRIPTION = "Codex Security plugin directory or ZIP (default: bundled plugin).";
59
+ const PYTHON_PATH_DESCRIPTION = "Python interpreter (default: PYTHON or automatic discovery).";
54
60
  const EXPORT_DEFAULT_OUTPUTS = {
55
61
  csv: "findings.csv",
56
62
  json: "findings.json",
@@ -98,12 +104,24 @@ function effortOption() {
98
104
  const DEFAULT_DEPENDENCIES = {
99
105
  createSecurity: (config) => new CodexSecurity(config),
100
106
  environment: process.env,
107
+ prepareAuthenticationHome: prepareCodexSecurityCredentialHome,
101
108
  checkForUpdate: () => checkForUpdate({ environment: process.env }),
102
109
  hasStoredChatGPTSignIn: async () => {
103
110
  const environment = Object.fromEntries(Object.entries(process.env).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
104
111
  name.toUpperCase() !== "CODEX_API_KEY"));
105
- const status = await accountStatus(resolveCodexCommand(), environment);
106
- return status.authenticated && /\bchatgpt\b/iu.test(status.details);
112
+ const command = resolveCodexCommand();
113
+ if (existsSync(codexSecurityCredentialHome(process.env))) {
114
+ const dedicatedStatus = await accountStatus(command, {
115
+ ...environment,
116
+ CODEX_HOME: await prepareCodexSecurityCredentialHome(process.env),
117
+ });
118
+ if (dedicatedStatus.authenticated &&
119
+ /\bchatgpt\b/iu.test(dedicatedStatus.details)) {
120
+ return true;
121
+ }
122
+ }
123
+ const ambientStatus = await accountStatus(command, environment);
124
+ return (ambientStatus.authenticated && /\bchatgpt\b/iu.test(ambientStatus.details));
107
125
  },
108
126
  currentDirectory: cwd,
109
127
  now: Date.now,
@@ -118,7 +136,7 @@ const DEFAULT_DEPENDENCIES = {
118
136
  writeSync(stream.fd, value);
119
137
  },
120
138
  forceExit: (signal) => process.kill(process.pid, signal),
121
- runCodex: runCodexSkillCommand,
139
+ runCodex: (args, output, environment) => runCodexSkillCommand(args, output, resolveCodexCommand(), environment),
122
140
  exportFindings: async (arguments_, output) => {
123
141
  const environment = exportEnvironment();
124
142
  const python = await resolvePluginPython({
@@ -188,9 +206,9 @@ const DEFAULT_DEPENDENCIES = {
188
206
  },
189
207
  matchFindings: matchScanFindings,
190
208
  };
191
- export async function runCodexSkillCommand(args, output, command = resolveCodexCommand()) {
192
- const configuredHome = process.env["CODEX_HOME"];
193
- const environment = { ...process.env };
209
+ export async function runCodexSkillCommand(args, output, command = resolveCodexCommand(), processEnvironment = process.env) {
210
+ const configuredHome = processEnvironment["CODEX_HOME"];
211
+ const environment = { ...processEnvironment };
194
212
  for (const name of Object.keys(environment)) {
195
213
  if (name.toUpperCase() === "CODEX_HOME")
196
214
  delete environment[name];
@@ -205,13 +223,32 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
205
223
  windowsHide: true,
206
224
  });
207
225
  let requestedSignal = null;
226
+ let skillOutputLimitExceeded = false;
227
+ let forcedTermination;
228
+ let forceStatusCompletion = null;
229
+ let forceCaptureCompletion = null;
230
+ let invocationStatus;
231
+ const requestTermination = (signal) => {
232
+ requestedSignal = signal;
233
+ invocation.kill(signal);
234
+ if (forcedTermination !== undefined)
235
+ return;
236
+ forcedTermination = setTimeout(() => {
237
+ forcedTermination = undefined;
238
+ if (invocation.exitCode === null && invocation.signalCode === null) {
239
+ invocation.kill("SIGKILL");
240
+ }
241
+ forceCaptureCompletion?.();
242
+ invocation.stdout?.destroy();
243
+ invocation.stderr?.destroy();
244
+ forceStatusCompletion?.();
245
+ }, CHILD_TERMINATION_GRACE_MS);
246
+ };
208
247
  const onInterrupt = () => {
209
- requestedSignal = "SIGINT";
210
- invocation.kill("SIGINT");
248
+ requestTermination("SIGINT");
211
249
  };
212
250
  const onTerminate = () => {
213
- requestedSignal = "SIGTERM";
214
- invocation.kill("SIGTERM");
251
+ requestTermination("SIGTERM");
215
252
  };
216
253
  process.on("SIGINT", onInterrupt);
217
254
  process.on("SIGTERM", onTerminate);
@@ -222,20 +259,42 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
222
259
  });
223
260
  const captured = output === undefined || invocation.stdout === null
224
261
  ? Promise.resolve(undefined)
225
- : readSkillCommandOutput(invocation.stdout);
226
- const [status, events] = await Promise.all([
227
- new Promise((resolve, reject) => {
228
- invocation.once("error", reject);
229
- invocation.once(output === undefined ? "exit" : "close", (code, signal) => {
230
- resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
231
- ? 130
232
- : requestedSignal === "SIGTERM" || signal === "SIGTERM"
233
- ? 143
234
- : code ?? 1);
235
- });
236
- }),
237
- captured,
238
- ]);
262
+ : Promise.race([
263
+ readSkillCommandOutput(invocation.stdout, () => {
264
+ skillOutputLimitExceeded = true;
265
+ requestTermination("SIGTERM");
266
+ }),
267
+ new Promise((resolve) => {
268
+ forceCaptureCompletion = () => resolve(undefined);
269
+ }),
270
+ ]);
271
+ invocationStatus = new Promise((resolve, reject) => {
272
+ let completed = false;
273
+ const complete = (code, signal) => {
274
+ if (completed)
275
+ return;
276
+ completed = true;
277
+ forceStatusCompletion = null;
278
+ resolve(requestedSignal === "SIGINT" || signal === "SIGINT"
279
+ ? 130
280
+ : requestedSignal === "SIGTERM" || signal === "SIGTERM"
281
+ ? 143
282
+ : code ?? 1);
283
+ };
284
+ forceStatusCompletion = () => complete(null, null);
285
+ invocation.once("error", (error) => {
286
+ if (completed)
287
+ return;
288
+ completed = true;
289
+ forceStatusCompletion = null;
290
+ reject(error);
291
+ });
292
+ invocation.once(output === undefined ? "exit" : "close", complete);
293
+ });
294
+ const [status, events] = await Promise.all([invocationStatus, captured]);
295
+ if (skillOutputLimitExceeded) {
296
+ throw new CodexSecurityError(SKILL_OUTPUT_LIMIT_MESSAGE);
297
+ }
239
298
  if (output === undefined || status === 130 || status === 143)
240
299
  return status;
241
300
  if (status !== 0) {
@@ -252,10 +311,15 @@ export async function runCodexSkillCommand(args, output, command = resolveCodexC
252
311
  catch (error) {
253
312
  invocation.stdout?.destroy();
254
313
  invocation.stderr?.destroy();
255
- invocation.kill();
314
+ requestTermination("SIGTERM");
315
+ await invocationStatus?.catch(() => undefined);
256
316
  throw error;
257
317
  }
258
318
  finally {
319
+ if (forcedTermination !== undefined)
320
+ clearTimeout(forcedTermination);
321
+ forceStatusCompletion = null;
322
+ forceCaptureCompletion = null;
259
323
  process.off("SIGINT", onInterrupt);
260
324
  process.off("SIGTERM", onTerminate);
261
325
  }
@@ -343,14 +407,34 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
343
407
  let renderedHistory;
344
408
  const history = async (args, select = (value) => value) => {
345
409
  try {
346
- return select(await dependencies.runWorkbench(args));
410
+ return await select(await dependencies.runWorkbench(args));
347
411
  }
348
412
  catch (error) {
349
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
413
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
350
414
  exitCode = 2;
351
415
  return undefined;
352
416
  }
353
417
  };
418
+ const matchScanPair = async (beforeId, afterId, force = false) => history([
419
+ "compare-scans",
420
+ "--before-scan-id",
421
+ beforeId,
422
+ "--after-scan-id",
423
+ afterId,
424
+ "--include-matching-inputs",
425
+ ], async ({ matchingCached, matchingInputs, ...comparison }) => {
426
+ if (matchingCached && !force)
427
+ return comparison;
428
+ return await dependencies.runWorkbench([
429
+ "save-scan-comparison",
430
+ "--before-scan-id",
431
+ beforeId,
432
+ "--after-scan-id",
433
+ afterId,
434
+ "--matches-json",
435
+ JSON.stringify(await dependencies.matchFindings(matchingInputs)),
436
+ ]);
437
+ });
354
438
  const presentHistory = (result, command, format, settings = {}) => {
355
439
  if (result === undefined ||
356
440
  format !== "toon" ||
@@ -490,7 +574,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
490
574
  scanArguments = scanArgumentsFromRecipe(recipe, args.scanId);
491
575
  }
492
576
  catch (error) {
493
- const message = cliErrorMessage(error);
577
+ const message = redactedErrorMessage(error);
494
578
  errorOutput.write(`codex-security: ${message}\n`);
495
579
  exitCode = 2;
496
580
  return incurError({
@@ -543,40 +627,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
543
627
  if (options.all) {
544
628
  return presentHistory(await matchAllScans(dependencies, options.force), "match-all", format);
545
629
  }
546
- const comparison = await history([
547
- "compare-scans",
548
- "--before-scan-id",
549
- args.beforeId,
550
- "--after-scan-id",
551
- args.afterId,
552
- "--include-matching-inputs",
553
- ]);
554
- if (comparison === undefined)
555
- return undefined;
556
- const { matchingCached, matchingInputs, ...visibleComparison } = comparison;
557
- if (matchingCached && !options.force) {
558
- return presentHistory(visibleComparison, "compare", format);
559
- }
560
- const matching = await dependencies.matchFindings(matchingInputs);
561
- return presentHistory(await history([
562
- "save-scan-comparison",
563
- "--before-scan-id",
564
- args.beforeId,
565
- "--after-scan-id",
566
- args.afterId,
567
- "--matches-json",
568
- JSON.stringify(matching),
569
- ]), "compare", format);
630
+ return presentHistory(await matchScanPair(args.beforeId, args.afterId, options.force), "compare", format);
570
631
  }
571
632
  catch (error) {
572
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
633
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
573
634
  exitCode = 2;
574
635
  return undefined;
575
636
  }
576
637
  },
577
638
  })
578
639
  .command("compare", {
579
- description: "Compare findings and coverage using saved matches.",
640
+ description: "Match and compare findings and coverage between scans.",
641
+ destructive: true,
580
642
  mcp: false,
581
643
  args: z.object({
582
644
  beforeId: z.string().min(1).describe("Earlier saved scan identifier."),
@@ -584,14 +646,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
584
646
  }),
585
647
  output: z.record(z.string(), z.unknown()).optional(),
586
648
  async run({ args, format }) {
587
- return presentHistory(await history([
588
- "compare-scans",
589
- "--before-scan-id",
590
- args.beforeId,
591
- "--after-scan-id",
592
- args.afterId,
593
- "--require-matches",
594
- ]), "compare", format);
649
+ return presentHistory(await matchScanPair(args.beforeId, args.afterId), "compare", format);
595
650
  },
596
651
  });
597
652
  const cli = Cli.create("codex-security", {
@@ -617,53 +672,53 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
617
672
  auth: z
618
673
  .enum(["auto", "chatgpt", "api-key"])
619
674
  .default("auto")
620
- .describe("Select automatic, ChatGPT, or API-key authentication."),
675
+ .describe("Select ChatGPT, OPENAI_API_KEY/CODEX_API_KEY, or automatic authentication."),
621
676
  path: z
622
677
  .array(optionValue("--path"))
623
678
  .default([])
624
- .describe("Scan only PATH; repeat for multiple paths."),
679
+ .describe("Scan only PATH; repeat for multiple repository-relative paths."),
625
680
  knowledgeBase: z
626
681
  .array(optionValue("--knowledge-base"))
627
682
  .default([])
628
- .describe("Read security docs; repeat for multiple paths."),
683
+ .describe("Add security-context files or directories; repeat for multiple paths."),
629
684
  diff: optionValue("--diff")
630
685
  .optional()
631
- .describe("Scan Git changes from BASE to --head."),
686
+ .describe("Scan committed Git changes from BASE to --head."),
632
687
  workingTree: z
633
688
  .boolean()
634
689
  .default(false)
635
- .describe("Scan staged and unstaged changes."),
690
+ .describe("Scan staged and unstaged changes against --base."),
636
691
  head: optionValue("--head")
637
692
  .optional()
638
- .describe("Git head ref for --diff."),
693
+ .describe("Git head ref for --diff (default: HEAD)."),
639
694
  base: optionValue("--base")
640
695
  .optional()
641
- .describe("Git base ref for --working-tree."),
696
+ .describe("Git base ref for --working-tree (default: HEAD)."),
642
697
  mode: z
643
698
  .enum(["standard", "deep"])
644
699
  .default("standard")
645
- .describe("Scan mode."),
700
+ .describe("Scan mode; deep supports repository and path targets."),
646
701
  model: optionValue("--model")
647
702
  .optional()
648
703
  .describe(`OpenAI model to use (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
649
704
  effort: effortOption(),
650
705
  outputDir: optionValue("--output-dir")
651
706
  .optional()
652
- .describe("Write scan artifacts to DIR."),
707
+ .describe("Artifact directory outside the repository (default: Codex Security state; CODEX_SECURITY_STATE_DIR)."),
653
708
  archiveExisting: z
654
709
  .boolean()
655
710
  .default(false)
656
- .describe("Archive existing results before scanning."),
711
+ .describe("Archive existing results; requires --output-dir."),
657
712
  pluginPath: optionValue("--plugin-path")
658
713
  .optional()
659
- .describe("Use a Codex Security plugin directory or ZIP."),
714
+ .describe(PLUGIN_PATH_DESCRIPTION),
660
715
  python: optionValue("--python")
661
716
  .optional()
662
- .describe("Python interpreter for the bundled plugin runtime."),
717
+ .describe(PYTHON_PATH_DESCRIPTION),
663
718
  codex: z
664
719
  .array(optionValue("--codex"))
665
720
  .default([])
666
- .describe('Override Codex settings; e.g. model_reasoning_effort="high".'),
721
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
667
722
  failOnSeverity: z
668
723
  .enum(REPORTABLE_SEVERITIES)
669
724
  .optional()
@@ -696,8 +751,16 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
696
751
  args: { repository: "." },
697
752
  options: { model: "gpt-5.6-terra", effort: "high" },
698
753
  },
699
- { args: { repository: "." }, options: { path: ["src", "tests"] } },
754
+ { args: { repository: "." }, options: { path: ["src"] } },
700
755
  { args: { repository: "." }, options: { diff: "origin/main" } },
756
+ {
757
+ args: { repository: "." },
758
+ options: {
759
+ codex: [
760
+ "features.multi_agent_v2.max_concurrent_threads_per_session=4",
761
+ ],
762
+ },
763
+ },
701
764
  ],
702
765
  output: z.record(z.string(), z.unknown()).optional(),
703
766
  async run({ args, error: incurError, format, options }) {
@@ -802,7 +865,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
802
865
  };
803
866
  }
804
867
  catch (error) {
805
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
868
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
806
869
  exitCode = 2;
807
870
  return undefined;
808
871
  }
@@ -819,16 +882,24 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
819
882
  .string()
820
883
  .min(1)
821
884
  .optional()
822
- .describe("CSV repository list; omit to discover repositories."),
885
+ .describe("CSV repository list; omit to discover repositories interactively."),
823
886
  }),
824
887
  options: z.object({
825
888
  outputDir: z
826
889
  .string()
827
890
  .min(1, "--output-dir must not be empty.")
828
891
  .optional()
829
- .describe("Directory for scan artifacts and resumable results."),
830
- workers: z.number().int().positive().default(4),
831
- mode: z.enum(["standard", "deep"]).default("standard"),
892
+ .describe("Resumable results directory; required with a repository CSV."),
893
+ workers: z
894
+ .number()
895
+ .int()
896
+ .positive()
897
+ .default(4)
898
+ .describe("Concurrent repository scans. Per-scan Codex workers are separate."),
899
+ mode: z
900
+ .enum(["standard", "deep"])
901
+ .default("standard")
902
+ .describe("Default scan mode for repositories without a CSV mode."),
832
903
  model: optionValue("--model")
833
904
  .optional()
834
905
  .describe(`OpenAI model for each repository (default: ${DEFAULT_SCAN_MODEL_CONFIGURATION.model}).`),
@@ -839,13 +910,27 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
839
910
  .positive()
840
911
  .default(1)
841
912
  .describe("Maximum scan attempts per repository."),
842
- pluginPath: z.string().min(1).optional(),
843
- python: z.string().min(1).optional(),
913
+ pluginPath: z
914
+ .string()
915
+ .min(1)
916
+ .optional()
917
+ .describe(PLUGIN_PATH_DESCRIPTION),
918
+ python: z.string().min(1).optional().describe(PYTHON_PATH_DESCRIPTION),
844
919
  codex: z
845
920
  .array(z.string().min(1))
846
921
  .default([])
847
- .describe('Override Codex settings; e.g. model_reasoning_effort="high".'),
922
+ .describe(CODEX_OVERRIDE_DESCRIPTION),
848
923
  }),
924
+ examples: [
925
+ {
926
+ args: {},
927
+ options: { model: "gpt-5.6-terra", effort: "high" },
928
+ },
929
+ ],
930
+ hint: "CSV example:\n" +
931
+ " codex-security bulk-scan repositories.csv " +
932
+ "--output-dir /path/outside/repositories/results " +
933
+ "--workers 4 --max-attempts 3",
849
934
  output: z.record(z.string(), z.unknown()).optional(),
850
935
  async run({ args, options }) {
851
936
  const controller = new AbortController();
@@ -918,7 +1003,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
918
1003
  createSecurity: dependencies.createSecurity,
919
1004
  signal: controller.signal,
920
1005
  onProgress: ({ repository, status, attempt, error }) => {
921
- errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${error === undefined ? "" : `: ${cliErrorMessage(error)}`}\n`);
1006
+ errorOutput.write(`codex-security: ${repository} ${status} (attempt ${attempt})${error === undefined ? "" : `: ${redactedErrorMessage(error)}`}\n`);
922
1007
  },
923
1008
  });
924
1009
  exitCode = interruptedExitCode() ?? (result.failed > 0 ? 2 : 0);
@@ -930,7 +1015,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
930
1015
  (error instanceof Error && error.name === "ExitPromptError"
931
1016
  ? 130
932
1017
  : 2);
933
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1018
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
934
1019
  }
935
1020
  finally {
936
1021
  dependencies.removeSignalListener("SIGINT", onInterrupt);
@@ -952,10 +1037,10 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
952
1037
  exportFormat: z
953
1038
  .enum(["csv", "json", "sarif"])
954
1039
  .default("sarif")
955
- .describe("Export format (default: sarif)."),
1040
+ .describe("Artifact format to export from the completed scan."),
956
1041
  output: optionValue("--output")
957
1042
  .optional()
958
- .describe("Write the selected format to FILE or stdout with '-'."),
1043
+ .describe("FILE or '-' for stdout (default: results.sarif, findings.json, or findings.csv)."),
959
1044
  sourceRoot: optionValue("--source-root")
960
1045
  .optional()
961
1046
  .describe("Repository checkout used for SARIF source-line fingerprints."),
@@ -998,7 +1083,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
998
1083
  codex: z
999
1084
  .array(optionValue("--codex"))
1000
1085
  .default([])
1001
- .describe('Set model="gpt-5.6-terra" or model_reasoning_effort="high".'),
1086
+ .describe('Repeat TOML model="gpt-5.6-terra" or model_reasoning_effort="high" only.'),
1002
1087
  }),
1003
1088
  async run({ options }) {
1004
1089
  try {
@@ -1006,7 +1091,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1006
1091
  }
1007
1092
  catch (error) {
1008
1093
  exitCode = 2;
1009
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1094
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1010
1095
  }
1011
1096
  },
1012
1097
  })
@@ -1025,7 +1110,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1025
1110
  codex: z
1026
1111
  .array(optionValue("--codex"))
1027
1112
  .default([])
1028
- .describe('Set model="gpt-5.6-terra" or model_reasoning_effort="high".'),
1113
+ .describe('Repeat TOML model="gpt-5.6-terra" or model_reasoning_effort="high" only.'),
1029
1114
  }),
1030
1115
  async run({ options }) {
1031
1116
  try {
@@ -1033,7 +1118,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1033
1118
  }
1034
1119
  catch (error) {
1035
1120
  exitCode = 2;
1036
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1121
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1037
1122
  }
1038
1123
  },
1039
1124
  })
@@ -1059,15 +1144,25 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1059
1144
  .describe("Read an access token from stdin."),
1060
1145
  }),
1061
1146
  async run({ args, options }) {
1147
+ const credentialHome = dependencies.prepareAuthenticationHome !== undefined
1148
+ ? await dependencies.prepareAuthenticationHome(dependencies.environment)
1149
+ : await prepareCodexSecurityCredentialHome(dependencies.environment);
1150
+ const authenticationEnvironment = {
1151
+ ...dependencies.environment,
1152
+ CODEX_HOME: credentialHome,
1153
+ };
1062
1154
  exitCode = await dependencies.runCodex([
1063
1155
  "login",
1064
1156
  ...(args.action === undefined ? [] : [args.action]),
1065
1157
  ...(options.deviceAuth ? ["--device-auth"] : []),
1066
1158
  ...(options.withApiKey ? ["--with-api-key"] : []),
1067
1159
  ...(options.withAccessToken ? ["--with-access-token"] : []),
1068
- "-c",
1069
- 'cli_auth_credentials_store="file"',
1070
- ]);
1160
+ ], undefined, authenticationEnvironment);
1161
+ if (args.action === undefined &&
1162
+ exitCode === 0 &&
1163
+ dependencies.prepareAuthenticationHome !== undefined) {
1164
+ await setCodexSecurityCredentialLogout(credentialHome, false);
1165
+ }
1071
1166
  if (args.action === "status") {
1072
1167
  const authentication = scanAuthentication(dependencies.environment);
1073
1168
  if (authentication.method === "api_key" &&
@@ -1104,11 +1199,18 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1104
1199
  destructive: true,
1105
1200
  mcp: false,
1106
1201
  async run() {
1107
- exitCode = await dependencies.runCodex([
1108
- "logout",
1109
- "-c",
1110
- 'cli_auth_credentials_store="file"',
1111
- ]);
1202
+ const credentialHome = dependencies.prepareAuthenticationHome !== undefined
1203
+ ? await dependencies.prepareAuthenticationHome(dependencies.environment)
1204
+ : await prepareCodexSecurityCredentialHome(dependencies.environment);
1205
+ const authenticationEnvironment = {
1206
+ ...dependencies.environment,
1207
+ CODEX_HOME: credentialHome,
1208
+ };
1209
+ exitCode = await dependencies.runCodex(["logout"], undefined, authenticationEnvironment);
1210
+ if (exitCode === 0 &&
1211
+ dependencies.prepareAuthenticationHome !== undefined) {
1212
+ await setCodexSecurityCredentialLogout(credentialHome, true);
1213
+ }
1112
1214
  },
1113
1215
  })
1114
1216
  .command("info", {
@@ -1165,7 +1267,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1165
1267
  if (frameworkExit !== undefined) {
1166
1268
  if (exitCode !== 0)
1167
1269
  return exitCode;
1168
- errorOutput.write(`codex-security: ${cliErrorMessage(incurErrorMessage(frameworkOutput))}\n`);
1270
+ errorOutput.write(`codex-security: ${redactedErrorMessage(incurErrorMessage(frameworkOutput))}\n`);
1169
1271
  return 2;
1170
1272
  }
1171
1273
  if (frameworkOutput.length === 0)
@@ -1175,7 +1277,7 @@ export async function main(argv = process.argv.slice(2), output = process.stdout
1175
1277
  return exitCode;
1176
1278
  }
1177
1279
  catch (error) {
1178
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1280
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1179
1281
  return 2;
1180
1282
  }
1181
1283
  }
@@ -1308,8 +1410,9 @@ function validateCliArguments(argv, positionals) {
1308
1410
  argv[index + 1] === "json" ||
1309
1411
  argv[index + 1] === "jsonl")));
1310
1412
  if (structuredOutput &&
1311
- ["validate", "patch", "login", "logout"].includes(command)) {
1312
- return `${command} does not support noninteractive JSON output; run it without --json or --format json.`;
1413
+ ["validate", "patch", "login", "logout"].includes(command) &&
1414
+ !argv.includes("--schema")) {
1415
+ return `${command} does not support noninteractive JSON output; run it without --json, --format json, or --format jsonl.`;
1313
1416
  }
1314
1417
  if (command === "export" &&
1315
1418
  structuredOutput &&
@@ -1566,24 +1669,33 @@ async function runSkill(skill, inputs, codexOverrides, effort, stdout, stderr, d
1566
1669
  stderr,
1567
1670
  });
1568
1671
  }
1569
- export async function readSkillCommandOutput(stream) {
1672
+ export async function readSkillCommandOutput(stream, onLimitExceeded) {
1570
1673
  let message;
1571
1674
  let error;
1572
1675
  let malformed = false;
1573
- for await (const line of createInterface({ input: Readable.from(stream) })) {
1676
+ let exceeded = false;
1677
+ const markExceeded = () => {
1678
+ if (exceeded)
1679
+ return;
1680
+ exceeded = true;
1681
+ onLimitExceeded?.();
1682
+ };
1683
+ const readLine = (bytes) => {
1684
+ const content = bytes.at(-1) === 0x0d ? bytes.subarray(0, bytes.length - 1) : bytes;
1685
+ const line = content.toString("utf8");
1574
1686
  if (line.trim().length === 0)
1575
- continue;
1687
+ return;
1576
1688
  let event;
1577
1689
  try {
1578
1690
  event = JSON.parse(line);
1579
1691
  }
1580
1692
  catch {
1581
1693
  malformed = true;
1582
- continue;
1694
+ return;
1583
1695
  }
1584
1696
  if (typeof event !== "object" || event === null) {
1585
1697
  malformed = true;
1586
- continue;
1698
+ return;
1587
1699
  }
1588
1700
  const value = event;
1589
1701
  if (value["type"] === "item.completed") {
@@ -1594,7 +1706,12 @@ export async function readSkillCommandOutput(stream) {
1594
1706
  item.type === "agent_message" &&
1595
1707
  "text" in item &&
1596
1708
  typeof item.text === "string") {
1597
- message = item.text;
1709
+ if (Buffer.byteLength(item.text, "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1710
+ markExceeded();
1711
+ }
1712
+ else {
1713
+ message = item.text;
1714
+ }
1598
1715
  }
1599
1716
  }
1600
1717
  else if (value["type"] === "turn.failed") {
@@ -1603,14 +1720,62 @@ export async function readSkillCommandOutput(stream) {
1603
1720
  detail !== null &&
1604
1721
  "message" in detail &&
1605
1722
  typeof detail.message === "string") {
1606
- error = detail.message;
1723
+ if (Buffer.byteLength(detail.message, "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1724
+ markExceeded();
1725
+ }
1726
+ else {
1727
+ error = detail.message;
1728
+ }
1607
1729
  }
1608
1730
  }
1609
1731
  else if (value["type"] === "error" &&
1610
1732
  typeof value["message"] === "string") {
1611
- error = value["message"];
1733
+ if (Buffer.byteLength(value["message"], "utf8") > MAX_SKILL_RESPONSE_BYTES) {
1734
+ markExceeded();
1735
+ }
1736
+ else {
1737
+ error = value["message"];
1738
+ }
1739
+ }
1740
+ };
1741
+ const pending = Buffer.alloc(MAX_SKILL_EVENT_BYTES);
1742
+ let pendingBytes = 0;
1743
+ let discardingOversizedLine = false;
1744
+ for await (const rawChunk of stream) {
1745
+ const chunk = Buffer.isBuffer(rawChunk)
1746
+ ? rawChunk
1747
+ : Buffer.from(rawChunk, "utf8");
1748
+ let start = 0;
1749
+ while (start < chunk.length) {
1750
+ const newline = chunk.indexOf(0x0a, start);
1751
+ const end = newline === -1 ? chunk.length : newline;
1752
+ const segment = chunk.subarray(start, end);
1753
+ if (!discardingOversizedLine) {
1754
+ if (pendingBytes + segment.length > MAX_SKILL_EVENT_BYTES) {
1755
+ markExceeded();
1756
+ discardingOversizedLine = true;
1757
+ pendingBytes = 0;
1758
+ }
1759
+ else if (segment.length > 0) {
1760
+ segment.copy(pending, pendingBytes);
1761
+ pendingBytes += segment.length;
1762
+ }
1763
+ }
1764
+ if (newline === -1)
1765
+ break;
1766
+ if (!discardingOversizedLine) {
1767
+ readLine(pending.subarray(0, pendingBytes));
1768
+ }
1769
+ pendingBytes = 0;
1770
+ discardingOversizedLine = false;
1771
+ start = newline + 1;
1612
1772
  }
1613
1773
  }
1774
+ if (!discardingOversizedLine && pendingBytes > 0) {
1775
+ readLine(pending.subarray(0, pendingBytes));
1776
+ }
1777
+ if (exceeded)
1778
+ throw new CodexSecurityError(SKILL_OUTPUT_LIMIT_MESSAGE);
1614
1779
  return {
1615
1780
  ...(message === undefined ? {} : { message }),
1616
1781
  ...(error === undefined ? {} : { error }),
@@ -1696,7 +1861,7 @@ async function runExport(arguments_, output, errorOutput, dependencies) {
1696
1861
  return 0;
1697
1862
  }
1698
1863
  catch (error) {
1699
- errorOutput.write(`codex-security: ${cliErrorMessage(error)}\n`);
1864
+ errorOutput.write(`codex-security: ${redactedErrorMessage(error)}\n`);
1700
1865
  return 2;
1701
1866
  }
1702
1867
  }
@@ -1812,7 +1977,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1812
1977
  },
1813
1978
  onOutputArchived: (archiveDir) => {
1814
1979
  progress?.stopTimer();
1815
- errorOutput.write(`Moved existing results to: ${cliErrorMessage(archiveDir)}\n`);
1980
+ errorOutput.write(`Moved existing results to: ${redactedErrorMessage(archiveDir)}\n`);
1816
1981
  },
1817
1982
  signal: preparationAbortController.signal,
1818
1983
  onOutputDirReady: (path) => {
@@ -1867,10 +2032,10 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1867
2032
  progress.startTimer(runningMessage());
1868
2033
  },
1869
2034
  onWarning: (warning) => {
1870
- errorOutput.write(`codex-security: warning: ${cliErrorMessage(warning)}\n`);
2035
+ errorOutput.write(`codex-security: warning: ${redactedErrorMessage(warning)}\n`);
1871
2036
  },
1872
2037
  onObserverError: (observer, error) => {
1873
- errorOutput.write(`codex-security: warning: ${observer} observer failed: ${cliErrorMessage(error)}\n`);
2038
+ errorOutput.write(`codex-security: warning: ${observer} observer failed: ${redactedErrorMessage(error)}\n`);
1874
2039
  },
1875
2040
  };
1876
2041
  if (arguments_.dryRun) {
@@ -1906,19 +2071,14 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1906
2071
  }
1907
2072
  if (failed) {
1908
2073
  const message = failure instanceof OutputInsideProtectedRootError
1909
- ? cliErrorMessage(protectedRootErrorMessage(failure))
2074
+ ? redactedErrorMessage(protectedRootErrorMessage(failure))
1910
2075
  : scanFailureMessage(failure, selectedAuthentication);
1911
- if (failure instanceof OutputInsideProtectedRootError) {
1912
- errorOutput.write(`${message}\n`);
1913
- }
1914
- else {
1915
- errorOutput.write(`codex-security: ${message}\n`);
1916
- }
2076
+ errorOutput.write(`${message}\n`);
1917
2077
  if (failure instanceof ScanInterruptedError) {
1918
2078
  return { exitCode: 2, error: message };
1919
2079
  }
1920
2080
  if (scanDir !== null) {
1921
- errorOutput.write(`codex-security: Partial output was kept at ${cliErrorMessage(scanDir)}.\n`);
2081
+ errorOutput.write(`Partial output was kept at ${redactedErrorMessage(scanDir)}.\n`);
1922
2082
  }
1923
2083
  return { exitCode: 2, error: message };
1924
2084
  }
@@ -1927,7 +2087,7 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1927
2087
  return { exitCode: 0, data: { dryRun: true, ...preflight } };
1928
2088
  }
1929
2089
  if (result === null) {
1930
- errorOutput.write("codex-security: scan completed without a result\n");
2090
+ errorOutput.write("scan completed without a result\n");
1931
2091
  return { exitCode: 2, error: "Scan completed without a result." };
1932
2092
  }
1933
2093
  const threshold = arguments_.failOnSeverity;
@@ -1937,7 +2097,9 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1937
2097
  const blockingCount = result.findings.findings.filter(({ severity }) => blockingSeverities.has(severity.level)).length;
1938
2098
  const incomplete = result.coverage.completeness !== "complete";
1939
2099
  progress?.stage("Scan complete");
1940
- printScanSummary(result, progress, errorOutput);
2100
+ printScanSummary(result, progress, errorOutput, progress?.interactive === true &&
2101
+ dependencies.environment["NO_COLOR"] === undefined &&
2102
+ dependencies.environment["TERM"] !== "dumb");
1941
2103
  if (incomplete) {
1942
2104
  errorOutput.write(threshold === undefined
1943
2105
  ? `codex-security: Scan coverage is ${result.coverage.completeness}; results may be incomplete.\n`
@@ -1946,7 +2108,53 @@ async function runScan(arguments_, errorOutput, dependencies, interactive = true
1946
2108
  }
1947
2109
  return { exitCode: blockingCount > 0 ? 1 : 0, data: result.toJSON() };
1948
2110
  }
2111
+ // Filesystem and OS syscall failures cannot originate from the model transport,
2112
+ // so they must never be rewritten as connectivity or credential advice. Network
2113
+ // errno codes are deliberately absent: they are genuine transport failures.
2114
+ const LOCAL_SYSCALL_CODES = new Set([
2115
+ "EACCES",
2116
+ "EBUSY",
2117
+ "EEXIST",
2118
+ "EFBIG",
2119
+ "EIO",
2120
+ "EISDIR",
2121
+ "ELOOP",
2122
+ "EMFILE",
2123
+ "ENAMETOOLONG",
2124
+ "ENFILE",
2125
+ "ENOENT",
2126
+ "ENOMEM",
2127
+ "ENOSPC",
2128
+ "ENOTDIR",
2129
+ "ENOTEMPTY",
2130
+ "EPERM",
2131
+ "EROFS",
2132
+ "EXDEV",
2133
+ ]);
2134
+ function isLocalScanFailure(error) {
2135
+ if (error instanceof InvalidTargetError ||
2136
+ error instanceof OutputDirectoryError ||
2137
+ error instanceof ConfigurationError ||
2138
+ error instanceof PluginPythonUnavailableError) {
2139
+ return true;
2140
+ }
2141
+ return (typeof error === "object" &&
2142
+ error !== null &&
2143
+ "code" in error &&
2144
+ typeof error.code === "string" &&
2145
+ LOCAL_SYSCALL_CODES.has(error.code));
2146
+ }
1949
2147
  function scanFailureMessage(error, authentication) {
2148
+ // A local failure keeps its own message. Classification matches bare words
2149
+ // such as "permission denied" anywhere in the text, so an EACCES from a
2150
+ // read-only TMPDIR would otherwise be reported as a credential problem.
2151
+ //
2152
+ // The advice branches below still replace the underlying text rather than
2153
+ // appending it. That is deliberate: upstream authentication and authorization
2154
+ // errors can name the organization or project, which must not reach stderr or
2155
+ // the JSON error field.
2156
+ if (isLocalScanFailure(error))
2157
+ return redactedErrorMessage(error);
1950
2158
  switch (classifyConnectionFailure(error)) {
1951
2159
  case "unauthorized":
1952
2160
  return authentication?.method === "api_key"
@@ -1966,7 +2174,7 @@ function scanFailureMessage(error, authentication) {
1966
2174
  case "network_error":
1967
2175
  case "timeout":
1968
2176
  case "unknown":
1969
- return cliErrorMessage(error);
2177
+ return redactedErrorMessage(error);
1970
2178
  }
1971
2179
  }
1972
2180
  function scanScope(arguments_) {
@@ -1978,7 +2186,7 @@ function scanScope(arguments_) {
1978
2186
  portable.startsWith("//")
1979
2187
  ? portable.split("/").at(-1) ?? portable
1980
2188
  : portable;
1981
- return cliErrorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
2189
+ return redactedErrorMessage(scoped.replaceAll(/[\u0000-\u001F\u007F]/gu, " "));
1982
2190
  });
1983
2191
  return `${displayed.join(", ")}${arguments_.paths.length > displayed.length ? `, +${arguments_.paths.length - displayed.length} more` : ""}`;
1984
2192
  }
@@ -1996,7 +2204,8 @@ function scanPhase(value) {
1996
2204
  attack_path: "analyzing attack paths",
1997
2205
  }[value];
1998
2206
  }
1999
- function printScanSummary(result, progress, errorOutput) {
2207
+ function printScanSummary(result, progress, errorOutput, color) {
2208
+ const paint = (value, code) => color ? `\u001B[${code}m${value}\u001B[0m` : value;
2000
2209
  const severities = new Map();
2001
2210
  for (const finding of result.findings.findings) {
2002
2211
  severities.set(finding.severity.level, (severities.get(finding.severity.level) ?? 0) + 1);
@@ -2007,7 +2216,6 @@ function printScanSummary(result, progress, errorOutput) {
2007
2216
  })
2008
2217
  .filter((value) => value !== null)
2009
2218
  .join(", ");
2010
- errorOutput.write(`codex-security: Findings: ${result.findings.findings.length}${severitySummary === "" ? "" : ` (${severitySummary})`}. Coverage: ${result.coverage.completeness}.\n`);
2011
2219
  const started = Date.parse(result.manifest.scan.startedAt);
2012
2220
  const completed = Date.parse(result.manifest.scan.completedAt);
2013
2221
  const elapsed = Number.isFinite(started) &&
@@ -2015,16 +2223,29 @@ function printScanSummary(result, progress, errorOutput) {
2015
2223
  completed >= started
2016
2224
  ? Math.floor((completed - started) / 1_000)
2017
2225
  : progress?.elapsedSeconds ?? 0;
2018
- errorOutput.write(`codex-security: Elapsed: ${elapsed}s.\n`);
2226
+ const duration = elapsed < 60
2227
+ ? `${elapsed}s`
2228
+ : `${Math.floor(elapsed / 60)}m ${elapsed % 60}s`;
2229
+ const findingCount = result.findings.findings.length;
2230
+ const findingColor = findingCount === 0
2231
+ ? 32
2232
+ : severities.has("critical") || severities.has("high")
2233
+ ? 31
2234
+ : severities.has("medium")
2235
+ ? 33
2236
+ : 36;
2237
+ errorOutput.write(`\n ${paint("REPORT", "1;36")} ${paint(redactedErrorMessage(result.reportPath), 4)}\n\n` +
2238
+ ` ${paint("FINDINGS", 1)} ${paint(`${findingCount}${severitySummary === "" ? "" : ` (${severitySummary})`}`, findingColor)}\n` +
2239
+ ` ${paint("COVERAGE", 1)} ${result.coverage.completeness}\n` +
2240
+ ` ${paint("ELAPSED", 1)} ${duration}\n`);
2019
2241
  const tokenSummary = formatTokenUsage(result.turnResult.usage);
2020
2242
  if (tokenSummary !== null) {
2021
- errorOutput.write(`codex-security: Tokens: ${tokenSummary}.\n`);
2243
+ errorOutput.write(` ${paint("TOKENS", 1)} ${tokenSummary}\n`);
2022
2244
  }
2023
2245
  if (result.cost !== null) {
2024
- errorOutput.write(`codex-security: Estimated cost: ${formatUsd(result.cost.estimatedUsd)} USD.\n`);
2246
+ errorOutput.write(` ${paint("COST", 1)} ${formatUsd(result.cost.estimatedUsd)}\n`);
2025
2247
  }
2026
- errorOutput.write(`codex-security: Report: ${cliErrorMessage(result.reportPath)}\n`);
2027
- errorOutput.write(`codex-security: Results: ${cliErrorMessage(result.scanDir)}\n`);
2248
+ errorOutput.write(` ${paint("RESULTS", 1)} ${redactedErrorMessage(result.scanDir)}\n`);
2028
2249
  }
2029
2250
  function formatTokenUsage(usage) {
2030
2251
  if (usage === null || typeof usage !== "object")
@@ -2064,7 +2285,7 @@ function protectedRootErrorMessage(error) {
2064
2285
  ? "Set TMPDIR (or TEMP on Windows) to a writable directory outside the protected root."
2065
2286
  : `Set TMPDIR (or TEMP on Windows) to ${quoteCliPath(suggestion)} after creating that directory.`;
2066
2287
  return [
2067
- `codex-security: ${description} must be outside the scanned directory and any enclosing Git worktree.`,
2288
+ `${description} must be outside the scanned directory and any enclosing Git worktree.`,
2068
2289
  ` Resolved path: ${error.outputDirectory}`,
2069
2290
  ` Protected root: ${error.protectedRoot}`,
2070
2291
  ` Reason: ${reason}`,
@@ -2265,7 +2486,7 @@ function interruptedExit(signal, scanDir, errorOutput) {
2265
2486
  errorOutput.write(`codex-security: Scan ${ctrlC ? "canceled by Ctrl-C" : "terminated by SIGTERM"}.\n`);
2266
2487
  errorOutput.write(scanDir === null
2267
2488
  ? "codex-security: No partial output was kept.\n"
2268
- : `codex-security: Partial output was kept at ${cliErrorMessage(scanDir)}.\n`);
2489
+ : `codex-security: Partial output was kept at ${redactedErrorMessage(scanDir)}.\n`);
2269
2490
  return ctrlC ? 130 : 143;
2270
2491
  }
2271
2492
  function isJsonObject(value) {
@@ -2284,22 +2505,11 @@ function invokedAsMain() {
2284
2505
  return false;
2285
2506
  }
2286
2507
  }
2287
- function cliErrorMessage(error) {
2288
- const message = error instanceof Error ? error.message : String(error);
2289
- return message
2290
- .replaceAll(/(\b[A-Za-z0-9_-]{0,64}(?:api[_-]?key|access[_-]?key(?:[_-]?id)?|token|secret|credential|signature|sig|password|passwd)\b(?:\\?["'])?\s*[:=]\s*(?:\\?["'])?)[^\s"',;}&\\\]]+/giu, "$1[redacted]")
2291
- .replaceAll(/sk-(?:proj-)?[A-Za-z0-9_*=-]{8,}/gu, "[redacted]")
2292
- .replaceAll(/(?:github_pat_|gh[pousr]_)[A-Za-z0-9_-]{8,}/giu, "[redacted]")
2293
- .replaceAll(/npm_[A-Za-z0-9_-]{8,}/giu, "[redacted]")
2294
- .replaceAll(/(^|%20|[^A-Za-z0-9_])(Bearer|Basic|Token)((?:\s|%20|\+)+)[A-Za-z0-9.%_~+/*=-]{8,}/giu, "$1$2$3[redacted]")
2295
- .replaceAll(/((?:https?|ssh|git\+ssh):\/\/)[^\s/@]+@/giu, "$1[redacted]@")
2296
- .replaceAll(/((?:[?&]|%3F|%26)(?:(?!%3F|%26|%3D)(?:[A-Za-z0-9_.%-]|\[|\])){0,64}(?:api[_-]?key|access(?:[_-]|%5F|%2D)?key(?:(?:[_-]|%5F|%2D)?id)?|token|secret|credential|signature|sig|password|passwd)(?:\]|%5D)?(?:=|%3D))(?:(?!%26)[^&\s])+/giu, "$1[redacted]");
2297
- }
2298
2508
  if (invokedAsMain()) {
2299
2509
  void main().then((exitCode) => {
2300
2510
  process.exitCode = exitCode;
2301
2511
  }, (error) => {
2302
- process.stderr.write(`codex-security: ${cliErrorMessage(error)}\n`);
2512
+ process.stderr.write(`codex-security: ${redactedErrorMessage(error)}\n`);
2303
2513
  process.exitCode = 2;
2304
2514
  });
2305
2515
  }