@openai/codex-security 0.1.20 → 0.1.23

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 (187) hide show
  1. package/README.md +1101 -865
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -1
  3. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  5. package/_bundled_plugin/references/config-preflight.md +2 -30
  6. package/_bundled_plugin/references/core-scan.md +1 -1
  7. package/_bundled_plugin/references/final-report.md +1 -1
  8. package/_bundled_plugin/references/finding-detail-fields.md +5 -10
  9. package/_bundled_plugin/references/sarif-adapter.md +1 -1
  10. package/_bundled_plugin/schemas/patch-risk-assessment.schema.json +243 -0
  11. package/_bundled_plugin/scripts/config_preflight.py +2 -8
  12. package/_bundled_plugin/scripts/finalize_scan_contract.py +206 -35
  13. package/_bundled_plugin/scripts/finding_preview.py +22 -4
  14. package/_bundled_plugin/scripts/generate_in_scope_files.py +27 -1
  15. package/_bundled_plugin/scripts/launch_codex_security_mcp +0 -0
  16. package/_bundled_plugin/scripts/windows_scan_local_files.py +101 -7
  17. package/_bundled_plugin/scripts/workbench_cli.py +21 -1
  18. package/_bundled_plugin/scripts/workbench_dashboard.py +115 -0
  19. package/_bundled_plugin/scripts/workbench_db.py +29 -2
  20. package/_bundled_plugin/scripts/workbench_finding_index.py +42 -24
  21. package/_bundled_plugin/scripts/workbench_finding_workflows.py +190 -0
  22. package/_bundled_plugin/scripts/workbench_findings.py +216 -0
  23. package/_bundled_plugin/scripts/workbench_saved_results.py +30 -5
  24. package/_bundled_plugin/scripts/workbench_schema.py +263 -58
  25. package/_bundled_plugin/scripts/workbench_target.py +22 -3
  26. package/_bundled_plugin/skills/assess-patch-risk/SKILL.md +88 -0
  27. package/_bundled_plugin/skills/assess-patch-risk/agents/openai.yaml +4 -0
  28. package/_bundled_plugin/skills/assess-patch-risk/references/risk-rubric.md +76 -0
  29. package/_bundled_plugin/skills/assess-patch-risk/scripts/validate_patch_risk_assessment.py +163 -0
  30. package/_bundled_plugin/skills/fix-finding/SKILL.md +16 -48
  31. package/_bundled_plugin/skills/track-findings/SKILL.md +2 -0
  32. package/dist/api.d.ts +3 -1
  33. package/dist/api.d.ts.map +1 -1
  34. package/dist/api.js +129 -45
  35. package/dist/api.js.map +1 -1
  36. package/dist/bulk-scan-discovery.d.ts.map +1 -1
  37. package/dist/bulk-scan-discovery.js +6 -24
  38. package/dist/bulk-scan-discovery.js.map +1 -1
  39. package/dist/cli.d.ts +28 -2
  40. package/dist/cli.d.ts.map +1 -1
  41. package/dist/cli.js +525 -96
  42. package/dist/cli.js.map +1 -1
  43. package/dist/cloud-publish.d.ts +5 -1
  44. package/dist/cloud-publish.d.ts.map +1 -1
  45. package/dist/cloud-publish.js +312 -10
  46. package/dist/cloud-publish.js.map +1 -1
  47. package/dist/component-plan.d.ts.map +1 -1
  48. package/dist/component-plan.js +5 -1
  49. package/dist/component-plan.js.map +1 -1
  50. package/dist/contract.d.ts +1 -0
  51. package/dist/contract.d.ts.map +1 -1
  52. package/dist/contract.js +9 -0
  53. package/dist/contract.js.map +1 -1
  54. package/dist/custom-publish.d.ts +22 -0
  55. package/dist/custom-publish.d.ts.map +1 -0
  56. package/dist/custom-publish.js +47 -0
  57. package/dist/custom-publish.js.map +1 -0
  58. package/dist/custom-validation-prompt.js +1 -1
  59. package/dist/custom-validation-prompt.js.map +1 -1
  60. package/dist/deduplication/checkpointed-review.d.ts +16 -0
  61. package/dist/deduplication/checkpointed-review.d.ts.map +1 -0
  62. package/dist/deduplication/checkpointed-review.js +76 -0
  63. package/dist/deduplication/checkpointed-review.js.map +1 -0
  64. package/dist/deduplication/codex-review.d.ts +21 -0
  65. package/dist/deduplication/codex-review.d.ts.map +1 -0
  66. package/dist/deduplication/codex-review.js +252 -0
  67. package/dist/deduplication/codex-review.js.map +1 -0
  68. package/dist/deduplication/deduplication-prompts.d.ts +8 -0
  69. package/dist/deduplication/deduplication-prompts.d.ts.map +1 -0
  70. package/dist/deduplication/deduplication-prompts.js +35 -0
  71. package/dist/deduplication/deduplication-prompts.js.map +1 -0
  72. package/dist/deduplication/deduplication-reviewer.d.ts +46 -0
  73. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -0
  74. package/dist/deduplication/deduplication-reviewer.js +105 -0
  75. package/dist/deduplication/deduplication-reviewer.js.map +1 -0
  76. package/dist/deduplication/deduplication.d.ts +6 -0
  77. package/dist/deduplication/deduplication.d.ts.map +1 -0
  78. package/dist/deduplication/deduplication.js +85 -0
  79. package/dist/deduplication/deduplication.js.map +1 -0
  80. package/dist/deduplication/scan.d.ts +16 -0
  81. package/dist/deduplication/scan.d.ts.map +1 -0
  82. package/dist/deduplication/scan.js +101 -0
  83. package/dist/deduplication/scan.js.map +1 -0
  84. package/dist/finding-dedupe-groups.d.ts +7 -0
  85. package/dist/finding-dedupe-groups.d.ts.map +1 -0
  86. package/dist/finding-dedupe-groups.js +2 -0
  87. package/dist/finding-dedupe-groups.js.map +1 -0
  88. package/dist/finding-retrieval.d.ts +13 -0
  89. package/dist/finding-retrieval.d.ts.map +1 -0
  90. package/dist/finding-retrieval.js +2 -0
  91. package/dist/finding-retrieval.js.map +1 -0
  92. package/dist/finding-workflow.d.ts +53 -0
  93. package/dist/finding-workflow.d.ts.map +1 -0
  94. package/dist/finding-workflow.js +117 -0
  95. package/dist/finding-workflow.js.map +1 -0
  96. package/dist/findings-client.d.ts +15 -0
  97. package/dist/findings-client.d.ts.map +1 -0
  98. package/dist/findings-client.js +60 -0
  99. package/dist/findings-client.js.map +1 -0
  100. package/dist/github.d.ts +161 -0
  101. package/dist/github.d.ts.map +1 -0
  102. package/dist/github.js +158 -0
  103. package/dist/github.js.map +1 -0
  104. package/dist/index.d.ts +6 -0
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +3 -0
  107. package/dist/index.js.map +1 -1
  108. package/dist/publication.js +28 -40
  109. package/dist/publication.js.map +1 -1
  110. package/dist/publish.d.ts +10 -0
  111. package/dist/publish.d.ts.map +1 -1
  112. package/dist/publish.js +29 -5
  113. package/dist/publish.js.map +1 -1
  114. package/dist/runtime.d.ts +5 -4
  115. package/dist/runtime.d.ts.map +1 -1
  116. package/dist/runtime.js +371 -197
  117. package/dist/runtime.js.map +1 -1
  118. package/dist/saved-scan.d.ts +15 -0
  119. package/dist/saved-scan.d.ts.map +1 -0
  120. package/dist/saved-scan.js +68 -0
  121. package/dist/saved-scan.js.map +1 -0
  122. package/dist/scan-comparison.d.ts +6 -2
  123. package/dist/scan-comparison.d.ts.map +1 -1
  124. package/dist/scan-comparison.js +7 -2
  125. package/dist/scan-comparison.js.map +1 -1
  126. package/dist/server/dashboard/THIRD_PARTY_NOTICES.txt +276 -0
  127. package/dist/server/dashboard/app.css +2 -0
  128. package/dist/server/dashboard/app.js +66 -0
  129. package/dist/server/dashboard/index.html +18 -0
  130. package/dist/server/dashboard-types.d.ts +45 -0
  131. package/dist/server/dashboard-types.d.ts.map +1 -0
  132. package/dist/server/dashboard-types.js +2 -0
  133. package/dist/server/dashboard-types.js.map +1 -0
  134. package/dist/server/dashboard.d.ts +6 -0
  135. package/dist/server/dashboard.d.ts.map +1 -0
  136. package/dist/server/dashboard.js +45 -0
  137. package/dist/server/dashboard.js.map +1 -0
  138. package/dist/server/embeddings.d.ts +16 -0
  139. package/dist/server/embeddings.d.ts.map +1 -0
  140. package/dist/server/embeddings.js +114 -0
  141. package/dist/server/embeddings.js.map +1 -0
  142. package/dist/server/errors.d.ts +5 -0
  143. package/dist/server/errors.d.ts.map +1 -0
  144. package/dist/server/errors.js +8 -0
  145. package/dist/server/errors.js.map +1 -0
  146. package/dist/server/findings-service.d.ts +20 -0
  147. package/dist/server/findings-service.d.ts.map +1 -0
  148. package/dist/server/findings-service.js +31 -0
  149. package/dist/server/findings-service.js.map +1 -0
  150. package/dist/server/index.d.ts +2 -0
  151. package/dist/server/index.d.ts.map +1 -0
  152. package/dist/server/index.js +32 -0
  153. package/dist/server/index.js.map +1 -0
  154. package/dist/server/routes.d.ts +6 -0
  155. package/dist/server/routes.d.ts.map +1 -0
  156. package/dist/server/routes.js +86 -0
  157. package/dist/server/routes.js.map +1 -0
  158. package/dist/server/server.d.ts +10 -0
  159. package/dist/server/server.d.ts.map +1 -0
  160. package/dist/server/server.js +17 -0
  161. package/dist/server/server.js.map +1 -0
  162. package/dist/server/sqlite-store.d.ts +22 -0
  163. package/dist/server/sqlite-store.d.ts.map +1 -0
  164. package/dist/server/sqlite-store.js +82 -0
  165. package/dist/server/sqlite-store.js.map +1 -0
  166. package/dist/server/storage.d.ts +32 -0
  167. package/dist/server/storage.d.ts.map +1 -0
  168. package/dist/server/storage.js +2 -0
  169. package/dist/server/storage.js.map +1 -0
  170. package/dist/server/validation.d.ts +17 -0
  171. package/dist/server/validation.d.ts.map +1 -0
  172. package/dist/server/validation.js +53 -0
  173. package/dist/server/validation.js.map +1 -0
  174. package/dist/targets.d.ts.map +1 -1
  175. package/dist/targets.js +1 -0
  176. package/dist/targets.js.map +1 -1
  177. package/dist/thread-source.d.ts +8 -0
  178. package/dist/thread-source.d.ts.map +1 -0
  179. package/dist/thread-source.js +7 -0
  180. package/dist/thread-source.js.map +1 -0
  181. package/dist/trusted-executable.d.ts.map +1 -1
  182. package/dist/trusted-executable.js +2 -1
  183. package/dist/trusted-executable.js.map +1 -1
  184. package/dist/version.d.ts +1 -1
  185. package/dist/version.js +1 -1
  186. package/dist/version.js.map +1 -1
  187. package/package.json +23 -8
package/dist/runtime.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { execFile as execFileCallback, spawn } from "node:child_process";
2
2
  import { randomUUID } from "node:crypto";
3
- import { constants, existsSync, readdirSync, } from "node:fs";
4
- import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, opendir, readFile, readdir, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
3
+ import { chmodSync, constants, existsSync, readdirSync, } from "node:fs";
4
+ import { chmod, cp, copyFile, link, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, utimes, writeFile, } from "node:fs/promises";
5
5
  import { homedir, tmpdir } from "node:os";
6
6
  import { createRequire } from "node:module";
7
7
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep, } from "node:path";
@@ -24,12 +24,51 @@ const MAX_ZIP_ENTRY_SIZE = 128 * 1024 * 1024;
24
24
  const MAX_ZIP_EXPANDED_SIZE = 512 * 1024 * 1024;
25
25
  const MODEL_UNSAFE_PATH = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/u;
26
26
  const CREDENTIAL_LOCK_NAME = ".codex-security-scan.lock";
27
+ const CREDENTIAL_LOCK_DATABASE = ".codex-security-scan.sqlite3";
27
28
  const CREDENTIAL_LOGOUT_MARKER = ".codex-security-logged-out";
28
29
  const CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS = 5_000;
29
30
  const CREDENTIAL_LOCK_POLL_MILLISECONDS = 25;
30
31
  const INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS = 30_000;
31
32
  const MAX_PROCESS_ID = 2_147_483_647;
32
33
  const MAX_WINDOWS_CREDENTIAL_ACL_STDERR = 64 * 1024;
34
+ const PLUGIN_HELPER_SECRET_ENVIRONMENT_VARIABLES = new Set([
35
+ "OPENAI_API_KEY",
36
+ "CODEX_API_KEY",
37
+ "OPENROUTER_API_KEY",
38
+ "FIREWORKS_API_KEY",
39
+ ]);
40
+ const PREPARE_SCAN_ARTIFACT_RESTORER_PROGRAM = `
41
+ from pathlib import Path
42
+ from runpy import run_path
43
+ import json
44
+ import sys
45
+
46
+ module = run_path(sys.argv[1])
47
+ canonical_path, root_identity = module["scan_root_identity"](Path(sys.argv[2]))
48
+ print(json.dumps({
49
+ "canonicalPath": str(canonical_path),
50
+ "dev": str(root_identity[0]),
51
+ "ino": str(root_identity[1]),
52
+ }, ensure_ascii=False))
53
+ `.trim();
54
+ const RESTORE_SCAN_ARTIFACT_PROGRAM = `
55
+ from pathlib import Path
56
+ from runpy import run_path
57
+ import sys
58
+
59
+ module = run_path(sys.argv[1])
60
+ try:
61
+ module["write_scan_local_bytes"](
62
+ Path(sys.argv[2]),
63
+ sys.argv[3],
64
+ sys.stdin.buffer.read(),
65
+ expected_root_identity=(int(sys.argv[4]), int(sys.argv[5])),
66
+ )
67
+ except (module["ContractError"], OSError) as error:
68
+ raise SystemExit(str(error))
69
+ `.trim();
70
+ const WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX = "CODEX_SECURITY_ACL_COMPLETE:";
71
+ const WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE = 2;
33
72
  function environmentValue(environment, requested) {
34
73
  const exact = environment[requested]?.trim();
35
74
  if (exact)
@@ -234,6 +273,8 @@ class RepairableWindowsCredentialOwnerError extends Error {
234
273
  super(cause.message, { cause });
235
274
  }
236
275
  }
276
+ class WindowsCredentialDescendantsChangedError extends Error {
277
+ }
237
278
  /** Inspect a Windows DACL without translating locale-specific account names. */
238
279
  export function inspectWindowsCredentialAcl(descriptor, currentUserSid, options = {}) {
239
280
  if (!WINDOWS_SID.test(currentUserSid)) {
@@ -400,43 +441,6 @@ function windowsAceAllowsAncestorReplacement(rights, inheritanceFlags) {
400
441
  }
401
442
  return false;
402
443
  }
403
- export async function verifyStableWindowsCredentialDescendants(path, inspectDescriptors, options = {}) {
404
- for (let attempt = 0; attempt < 3; attempt += 1) {
405
- let descendants = 0;
406
- const pending = [path];
407
- try {
408
- while (pending.length !== 0) {
409
- const current = pending.pop();
410
- const directory = await opendir(current);
411
- for await (const entry of directory) {
412
- const child = join(current, entry.name);
413
- const metadata = await lstat(child);
414
- if (metadata.isSymbolicLink()) {
415
- throw new Error("Windows credential home contains a symbolic link or junction");
416
- }
417
- if (!metadata.isDirectory() && !metadata.isFile()) {
418
- throw new Error("Windows credential home contains an unsafe entry");
419
- }
420
- descendants += 1;
421
- if (metadata.isDirectory())
422
- pending.push(child);
423
- }
424
- }
425
- }
426
- catch (error) {
427
- const failure = error;
428
- if (failure.code === "ENOENT" && failure.path !== path) {
429
- continue;
430
- }
431
- throw error;
432
- }
433
- if (descendants === 0 && options.inspectEmpty !== true)
434
- return;
435
- if ((await inspectDescriptors()) === descendants)
436
- return;
437
- }
438
- throw new Error("Windows credential descendants could not be verified");
439
- }
440
444
  export async function streamWindowsCredentialAclDescriptors(command, args, inspectDescriptor, options = {}) {
441
445
  const child = spawn(command, [...args], {
442
446
  env: options.environment,
@@ -450,6 +454,7 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
450
454
  if (remaining > 0)
451
455
  stderr += chunk.slice(0, remaining);
452
456
  });
457
+ let descendantsChanged = false;
453
458
  const completion = new Promise((resolve, reject) => {
454
459
  child.once("error", reject);
455
460
  child.once("close", (code, signal) => {
@@ -457,6 +462,11 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
457
462
  resolve();
458
463
  return;
459
464
  }
465
+ if (code === WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE) {
466
+ descendantsChanged = true;
467
+ resolve();
468
+ return;
469
+ }
460
470
  const reason = signal === null ? `exit code ${code}` : `signal ${signal}`;
461
471
  reject(Object.assign(new Error(`Windows credential ACL inspection failed with ${reason}`), { code, signal, stderr }));
462
472
  });
@@ -484,6 +494,10 @@ export async function streamWindowsCredentialAclDescriptors(command, args, inspe
484
494
  child.kill();
485
495
  throw error;
486
496
  }
497
+ if (descendantsChanged) {
498
+ // Finish descriptor callbacks before allowing another snapshot attempt.
499
+ throw new WindowsCredentialDescendantsChangedError("Windows credential descendants changed during ACL inspection");
500
+ }
487
501
  return descriptors;
488
502
  }
489
503
  export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid, options) {
@@ -493,58 +507,78 @@ export async function inspectWindowsCredentialAclSnapshot(path, currentUserSid,
493
507
  if (ancestor === dirname(ancestor))
494
508
  break;
495
509
  }
496
- let home;
497
- let descendantsArePrivate = true;
498
- await verifyStableWindowsCredentialDescendants(path, async () => {
499
- home = undefined;
500
- descendantsArePrivate = true;
510
+ for (let attempt = 0; attempt < 3; attempt += 1) {
511
+ let home;
512
+ let descendantsArePrivate = true;
501
513
  let inspected = 0;
502
- const descriptors = await streamWindowsCredentialAclDescriptors(options.command, options.args, async (descriptor) => {
503
- const index = inspected;
504
- inspected += 1;
505
- await options.resolveDescriptorAliases?.(descriptor);
506
- if (index < ancestors) {
507
- const ancestor = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
508
- resolvedAliases: options.resolvedAliases,
509
- scope: "ancestor",
510
- });
511
- if (ancestor.untrustedPrincipals.length !== 0) {
512
- throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
514
+ let completed = false;
515
+ try {
516
+ await streamWindowsCredentialAclDescriptors(options.command, options.args, async (descriptor) => {
517
+ if (completed) {
518
+ throw new Error("Windows credential ACL inspection continued after completion");
513
519
  }
514
- return;
515
- }
516
- if (index === ancestors) {
517
- try {
518
- home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
520
+ if (descriptor.startsWith(WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX)) {
521
+ if (descriptor !==
522
+ `${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}${inspected}`) {
523
+ throw new Error("Windows credential descendants could not be verified");
524
+ }
525
+ completed = true;
526
+ return;
527
+ }
528
+ const index = inspected;
529
+ inspected += 1;
530
+ await options.resolveDescriptorAliases?.(descriptor);
531
+ if (index < ancestors) {
532
+ const ancestor = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
519
533
  resolvedAliases: options.resolvedAliases,
534
+ scope: "ancestor",
520
535
  });
536
+ if (ancestor.untrustedPrincipals.length !== 0) {
537
+ throw new Error("Windows credential-home ancestor allows another identity to replace the directory");
538
+ }
539
+ return;
521
540
  }
522
- catch (error) {
523
- if (error instanceof UntrustedWindowsCredentialOwnerError) {
524
- throw new RepairableWindowsCredentialOwnerError(error);
541
+ if (index === ancestors) {
542
+ try {
543
+ home = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
544
+ resolvedAliases: options.resolvedAliases,
545
+ });
546
+ }
547
+ catch (error) {
548
+ if (error instanceof UntrustedWindowsCredentialOwnerError) {
549
+ throw new RepairableWindowsCredentialOwnerError(error);
550
+ }
551
+ throw new RepairableWindowsCredentialAclError(error);
525
552
  }
526
- throw new RepairableWindowsCredentialAclError(error);
553
+ return;
527
554
  }
528
- return;
529
- }
530
- const descendant = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
531
- resolvedAliases: options.resolvedAliases,
532
- scope: "file",
533
- });
534
- if (!descendant.grantsCurrentUserAccess ||
535
- descendant.untrustedPrincipals.length !== 0) {
536
- descendantsArePrivate = false;
537
- }
538
- }, { environment: options.environment });
539
- if (descriptors <= ancestors) {
555
+ const descendant = inspectWindowsCredentialAcl(descriptor, currentUserSid, {
556
+ resolvedAliases: options.resolvedAliases,
557
+ scope: "file",
558
+ });
559
+ if (!descendant.grantsCurrentUserAccess ||
560
+ descendant.untrustedPrincipals.length !== 0) {
561
+ descendantsArePrivate = false;
562
+ }
563
+ }, { environment: options.environment });
564
+ }
565
+ catch (error) {
566
+ if (error instanceof WindowsCredentialDescendantsChangedError)
567
+ continue;
568
+ throw error;
569
+ }
570
+ if (inspected <= ancestors) {
540
571
  throw new Error("Windows credential-home ancestry could not be verified");
541
572
  }
542
- return descriptors - ancestors - 1;
543
- }, { inspectEmpty: true });
544
- if (home === undefined) {
545
- throw new Error("Windows credential ACL could not be verified");
573
+ if (!completed) {
574
+ throw new Error("Windows credential descendants could not be verified");
575
+ }
576
+ if (home === undefined) {
577
+ throw new Error("Windows credential ACL could not be verified");
578
+ }
579
+ return { home, descendantsArePrivate };
546
580
  }
547
- return { home, descendantsArePrivate };
581
+ throw new Error("Windows credential descendants could not be verified");
548
582
  }
549
583
  async function secureWindowsCredentialHome(path) {
550
584
  const systemRoot = process.env["SystemRoot"] ?? "C:\\Windows";
@@ -568,15 +602,33 @@ async function secureWindowsCredentialHome(path) {
568
602
  }
569
603
  // Signed built-in cmdlets remain available under ConstrainedLanguage;
570
604
  // arbitrary .NET constructors, static methods, and SID translation do not.
605
+ // Enumerate and count ACLs in the same process: parallel startup can create
606
+ // or remove private cache and lock files while this traversal is running.
571
607
  const script = [
572
608
  "$ErrorActionPreference = 'Stop'",
609
+ "$script:descriptorCount = 0",
610
+ "function Write-CredentialAcl($path) { $descriptor = Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $path | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; if (-not $descriptor) { throw 'Windows credential ACL could not be verified' }; $script:descriptorCount += 1; $descriptor }",
611
+ "function Read-CredentialDescendants($path) {",
612
+ " try { $entries = @(Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $path -Force) } catch {",
613
+ // A child can disappear while an existing directory is being enumerated.
614
+ // Retry that incomplete listing before accepting a vanished descendant.
615
+ ` if ($_.FullyQualifiedErrorId -eq 'System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.GetChildItemCommand') { exit ${WINDOWS_CREDENTIAL_DESCENDANTS_CHANGED_EXIT_CODE} }`,
616
+ " if ($path -ne $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -and $_.CategoryInfo.Category -eq 'ObjectNotFound') { return }",
617
+ " throw",
618
+ " }",
619
+ " foreach ($entry in $entries) {",
620
+ " if (($entry.Attributes -band 1024) -and ($entry.LinkType -in @('SymbolicLink', 'Junction'))) { throw 'Windows credential home contains a symbolic link or junction' }",
621
+ " if ($entry.PSObject.TypeNames -notcontains 'System.IO.DirectoryInfo' -and $entry.PSObject.TypeNames -notcontains 'System.IO.FileInfo') { throw 'Windows credential home contains an unsafe entry' }",
622
+ " try { Write-CredentialAcl $entry.FullName } catch { if ($_.FullyQualifiedErrorId -like 'GetAcl_PathNotFound,*') { continue }; throw }",
623
+ " if ($entry.PSIsContainer) { Read-CredentialDescendants $entry.FullName }",
624
+ " }",
625
+ "}",
573
626
  "$path = $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
574
- "while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $parent | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl; $path = $parent }",
575
- "Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl",
576
- // A temporary descendant can disappear after enumeration. Its missing
577
- // descriptor reduces the count and retries the stable snapshot.
578
- "Microsoft.PowerShell.Management\\Get-ChildItem -LiteralPath $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH -Recurse -Force | Microsoft.PowerShell.Core\\ForEach-Object { try { Microsoft.PowerShell.Security\\Get-Acl -LiteralPath $_.FullName | Microsoft.PowerShell.Utility\\Select-Object -ExpandProperty Sddl } catch { if ($_.FullyQualifiedErrorId -notlike 'GetAcl_PathNotFound,*') { throw } } }",
579
- ].join("; ");
627
+ "while ($true) { $parent = Microsoft.PowerShell.Management\\Split-Path -Path $path -Parent; if (-not $parent -or $parent -eq $path) { break }; Write-CredentialAcl $parent; $path = $parent }",
628
+ "Write-CredentialAcl $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
629
+ "Read-CredentialDescendants $env:CODEX_SECURITY_CREDENTIAL_ACL_PATH",
630
+ `"${WINDOWS_CREDENTIAL_ACL_COMPLETE_PREFIX}$script:descriptorCount"`,
631
+ ].join("\n");
580
632
  const resolvePrincipalScript = [
581
633
  "$ErrorActionPreference = 'Stop'",
582
634
  "$descriptor = 'O:' + $env:CODEX_SECURITY_CREDENTIAL_PRINCIPAL + 'G:SYD:(A;;GA;;;SY)'",
@@ -712,82 +764,155 @@ async function secureWindowsCredentialHome(path) {
712
764
  }
713
765
  }
714
766
  export async function acquireCodexSecurityCredentialHomeLock(codexHome, signal, securityOptions = {}) {
767
+ throwIfSignalAborted(signal);
715
768
  const homeMetadata = await requireSecureCredentialHome(codexHome, securityOptions);
716
769
  const expectedDevice = homeMetadata.dev;
717
770
  const expectedInode = homeMetadata.ino;
718
771
  const lock = join(codexHome, CREDENTIAL_LOCK_NAME);
719
772
  const ownerPath = join(lock, "owner.json");
720
773
  const token = randomUUID();
721
- while (true) {
722
- throwIfSignalAborted(signal);
723
- await requireSecureCredentialHome(codexHome, {
724
- ...securityOptions,
725
- expectedDevice,
726
- expectedInode,
727
- validateWindowsAcl: false,
728
- });
729
- const existingLock = await lstat(lock).catch((error) => {
730
- if (nodeErrorCode(error) === "ENOENT")
731
- return null;
732
- throw error;
733
- });
734
- if (existingLock !== null) {
735
- if (await recoverStaleCredentialHomeLock(lock, signal))
736
- continue;
737
- await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
738
- continue;
739
- }
740
- await requireSecureCredentialHome(codexHome, {
741
- ...securityOptions,
742
- expectedDevice,
743
- expectedInode,
744
- });
745
- try {
746
- await mkdir(lock, { mode: 0o700 });
747
- }
748
- catch (error) {
749
- if (nodeErrorCode(error) !== "EEXIST")
774
+ const databasePath = join(codexHome, CREDENTIAL_LOCK_DATABASE);
775
+ const existingDatabaseMetadata = await lstat(databasePath).catch((error) => {
776
+ if (nodeErrorCode(error) === "ENOENT")
777
+ return null;
778
+ throw error;
779
+ });
780
+ if (existingDatabaseMetadata !== null) {
781
+ requireCredentialLockDatabaseFile(existingDatabaseMetadata, databasePath);
782
+ }
783
+ const require = createRequire(import.meta.url);
784
+ // Both supported runtimes bundle SQLite. Keep the transaction in the process
785
+ // doing the protected work, so pausing it cannot expire its lock.
786
+ const Database = process.versions["bun"]
787
+ ? require("bun:sqlite")
788
+ .Database
789
+ : require("node:sqlite").DatabaseSync;
790
+ // Let SQLite create a missing guard so no separate descriptor can close after
791
+ // another connection acquires its process-owned POSIX lock. Keep the guard
792
+ // across releases so every contender locks the same inode.
793
+ const database = new Database(databasePath);
794
+ let databaseLocked = false;
795
+ try {
796
+ // SQLite creates new databases with the process umask. Tighten or repair
797
+ // the guard synchronously before yielding so concurrent first-time callers
798
+ // cannot reject its transient mode. The credential home is already private,
799
+ // and the pre-open check above rejects linked existing files.
800
+ if (process.platform !== "win32")
801
+ chmodSync(databasePath, 0o600);
802
+ const databaseMetadata = await lstat(databasePath);
803
+ requireCredentialLockDatabaseFile(databaseMetadata, databasePath);
804
+ if (existingDatabaseMetadata !== null &&
805
+ (databaseMetadata.dev !== existingDatabaseMetadata.dev ||
806
+ databaseMetadata.ino !== existingDatabaseMetadata.ino)) {
807
+ throw new OutputDirectoryError(`Codex Security credential-home lock changed while opening it: ${databasePath}`);
808
+ }
809
+ requirePrivateCredentialFile(databaseMetadata, databasePath);
810
+ database.exec("PRAGMA busy_timeout = 0");
811
+ while (true) {
812
+ throwIfSignalAborted(signal);
813
+ await requireSecureCredentialHome(codexHome, {
814
+ ...securityOptions,
815
+ expectedDevice,
816
+ expectedInode,
817
+ validateWindowsAcl: false,
818
+ });
819
+ if (!databaseLocked) {
820
+ try {
821
+ database.exec("BEGIN EXCLUSIVE");
822
+ }
823
+ catch (error) {
824
+ if (!isRecord(error) ||
825
+ (error["errcode"] !== 5 && error["code"] !== "SQLITE_BUSY")) {
826
+ throw error;
827
+ }
828
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
829
+ continue;
830
+ }
831
+ const currentDatabase = await lstat(databasePath);
832
+ if (currentDatabase.dev !== databaseMetadata.dev ||
833
+ currentDatabase.ino !== databaseMetadata.ino) {
834
+ throw new OutputDirectoryError(`Codex Security credential-home lock changed while acquiring it: ${databasePath}`);
835
+ }
836
+ databaseLocked = true;
837
+ }
838
+ const existingLock = await lstat(lock).catch((error) => {
839
+ if (nodeErrorCode(error) === "ENOENT")
840
+ return null;
750
841
  throw error;
751
- if (await recoverStaleCredentialHomeLock(lock, signal))
842
+ });
843
+ if (existingLock !== null) {
844
+ if (await recoverStaleCredentialHomeLock(lock))
845
+ continue;
846
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
752
847
  continue;
753
- await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
754
- continue;
755
- }
756
- try {
757
- await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
758
- }
759
- catch (error) {
760
- await rm(lock, { recursive: true, force: true }).catch(() => undefined);
761
- throw error;
762
- }
763
- const heartbeat = setInterval(async () => {
764
- try {
765
- const now = new Date();
766
- await utimes(lock, now, now);
767
848
  }
768
- catch { }
769
- }, CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS);
770
- heartbeat.unref();
771
- let released = false;
772
- return async () => {
773
- if (released)
774
- return;
775
- clearInterval(heartbeat);
776
849
  await requireSecureCredentialHome(codexHome, {
777
850
  ...securityOptions,
778
851
  expectedDevice,
779
852
  expectedInode,
780
853
  });
781
- const owner = JSON.parse(await readFile(ownerPath, "utf8"));
782
- if (owner.token !== token) {
783
- throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
854
+ try {
855
+ await mkdir(lock, { mode: 0o700 });
856
+ }
857
+ catch (error) {
858
+ if (nodeErrorCode(error) !== "EEXIST")
859
+ throw error;
860
+ if (await recoverStaleCredentialHomeLock(lock))
861
+ continue;
862
+ await delay(CREDENTIAL_LOCK_POLL_MILLISECONDS, undefined, { signal });
863
+ continue;
864
+ }
865
+ try {
866
+ await writeFile(ownerPath, `${JSON.stringify({ pid: process.pid, token, protocol: "sqlite" })}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
784
867
  }
785
- await rm(lock, { recursive: true, force: true });
786
- released = true;
787
- };
868
+ catch (error) {
869
+ await rm(lock, { recursive: true, force: true }).catch(() => undefined);
870
+ throw error;
871
+ }
872
+ // Released clients use the directory heartbeat instead of the SQLite lock.
873
+ const heartbeat = setInterval(async () => {
874
+ try {
875
+ const now = new Date();
876
+ await utimes(lock, now, now);
877
+ }
878
+ catch { }
879
+ }, CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS);
880
+ heartbeat.unref();
881
+ let released = false;
882
+ return async () => {
883
+ if (released)
884
+ return;
885
+ released = true;
886
+ try {
887
+ await requireSecureCredentialHome(codexHome, {
888
+ ...securityOptions,
889
+ expectedDevice,
890
+ expectedInode,
891
+ });
892
+ const owner = JSON.parse(await readFile(ownerPath, "utf8"));
893
+ if (owner.token !== token) {
894
+ throw new PluginBootstrapError("The Codex Security credential-home lock is no longer owned by this scan.");
895
+ }
896
+ await rm(lock, { recursive: true, force: true });
897
+ }
898
+ finally {
899
+ clearInterval(heartbeat);
900
+ database.close();
901
+ }
902
+ };
903
+ }
904
+ }
905
+ catch (error) {
906
+ database.close();
907
+ throw error;
788
908
  }
789
909
  }
790
- async function recoverStaleCredentialHomeLock(lock, signal) {
910
+ function requireCredentialLockDatabaseFile(metadata, path) {
911
+ if (!metadata.isFile() || metadata.nlink !== 1) {
912
+ throw new OutputDirectoryError(`Codex Security credential-home lock must be a regular file, not a symlink or hard link: ${path}`);
913
+ }
914
+ }
915
+ async function recoverStaleCredentialHomeLock(lock) {
791
916
  const metadata = await lstat(lock).catch((error) => {
792
917
  if (nodeErrorCode(error) === "ENOENT")
793
918
  return null;
@@ -807,47 +932,31 @@ async function recoverStaleCredentialHomeLock(lock, signal) {
807
932
  throw error;
808
933
  }
809
934
  }
810
- // Only positive signed-32-bit PIDs identify an owner. Other values can name
811
- // process groups or fail argument validation, so use the stale-age check.
812
- const ownerPid = isRecord(owner) ? owner["pid"] : undefined;
813
- let ownerExited = false;
814
- let ownerIsAlive = false;
815
- if (typeof ownerPid === "number" &&
816
- Number.isInteger(ownerPid) &&
817
- ownerPid > 0 &&
818
- ownerPid <= MAX_PROCESS_ID) {
819
- try {
820
- process.kill(ownerPid, 0);
821
- ownerIsAlive = true;
822
- }
823
- catch (error) {
824
- if (nodeErrorCode(error) === "ESRCH")
825
- ownerExited = true;
826
- else if (nodeErrorCode(error) === "EPERM")
827
- ownerIsAlive = true;
828
- else
829
- throw error;
830
- }
831
- }
832
- if (!ownerExited &&
833
- Date.now() - metadata.mtimeMs < INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
834
- return false;
835
- }
836
- if (ownerIsAlive) {
837
- await delay(CREDENTIAL_LOCK_HEARTBEAT_MILLISECONDS, undefined, { signal });
838
- const refreshedMetadata = await lstat(lock).catch((error) => {
839
- if (nodeErrorCode(error) === "ENOENT")
840
- return null;
841
- throw error;
842
- });
843
- if (refreshedMetadata === null)
844
- return true;
845
- if (!refreshedMetadata.isDirectory() ||
846
- refreshedMetadata.isSymbolicLink()) {
847
- throw new OutputDirectoryError(`Codex Security credential-home lock is not a directory: ${lock}`);
935
+ // We hold the SQLite transaction, so a record from that protocol is orphaned.
936
+ // Older clients only record a PID: a live one must be respected at any age.
937
+ if (!isRecord(owner) || owner["protocol"] !== "sqlite") {
938
+ // Only positive signed-32-bit PIDs identify an owner. Other values can name
939
+ // process groups or fail argument validation, so use the stale-age check.
940
+ const ownerPid = isRecord(owner) ? owner["pid"] : undefined;
941
+ if (typeof ownerPid === "number" &&
942
+ Number.isInteger(ownerPid) &&
943
+ ownerPid > 0 &&
944
+ ownerPid <= MAX_PROCESS_ID) {
945
+ try {
946
+ process.kill(ownerPid, 0);
947
+ return false;
948
+ }
949
+ catch (error) {
950
+ if (nodeErrorCode(error) === "EPERM")
951
+ return false;
952
+ if (nodeErrorCode(error) !== "ESRCH")
953
+ throw error;
954
+ }
848
955
  }
849
- if (refreshedMetadata.mtimeMs > metadata.mtimeMs)
956
+ else if (Date.now() - metadata.mtimeMs <
957
+ INCOMPLETE_CREDENTIAL_LOCK_MILLISECONDS) {
850
958
  return false;
959
+ }
851
960
  }
852
961
  const quarantine = `${lock}.stale-${randomUUID()}`;
853
962
  try {
@@ -1001,10 +1110,6 @@ export async function preparePersistentOutputRoot(stateDirectory, category, repo
1001
1110
  export async function runWorkbench(options, args, input) {
1002
1111
  let stdout;
1003
1112
  try {
1004
- const environment = Object.fromEntries(Object.entries(options.environment).filter(([name]) => name.toUpperCase() !== "OPENAI_API_KEY" &&
1005
- name.toUpperCase() !== "CODEX_API_KEY" &&
1006
- name.toUpperCase() !== "OPENROUTER_API_KEY" &&
1007
- name.toUpperCase() !== "FIREWORKS_API_KEY"));
1008
1113
  const result = await runCodexCommand({ command: options.python }, [
1009
1114
  "-I",
1010
1115
  "-X",
@@ -1012,7 +1117,7 @@ export async function runWorkbench(options, args, input) {
1012
1117
  "-B",
1013
1118
  join(options.pluginRoot, "scripts", "workbench_db.py"),
1014
1119
  ...args,
1015
- ], pythonUtf8Environment(environment), input, options.signal);
1120
+ ], pluginHelperEnvironment(options.environment), input, options.signal);
1016
1121
  if (!result.success) {
1017
1122
  throw new Error(result.stderr.trim() ||
1018
1123
  result.stdout.trim() ||
@@ -1043,16 +1148,10 @@ export async function runWorkbench(options, args, input) {
1043
1148
  return result;
1044
1149
  }
1045
1150
  export function bundledPluginCandidates(moduleDirectory) {
1046
- const packageCandidates = [
1151
+ return [
1047
1152
  resolve(moduleDirectory, "_bundled_plugin"),
1048
1153
  resolve(moduleDirectory, "../_bundled_plugin"),
1049
1154
  ];
1050
- return basename(moduleDirectory) === "src"
1051
- ? [
1052
- resolve(moduleDirectory, "../../../plugins/codex-security"),
1053
- ...packageCandidates,
1054
- ]
1055
- : packageCandidates;
1056
1155
  }
1057
1156
  export async function bundledPluginRoot() {
1058
1157
  const moduleDirectory = dirname(fileURLToPath(import.meta.url));
@@ -1116,6 +1215,78 @@ export async function validateOutputDir(outputDirectory, archiveExisting = false
1116
1215
  throw new OutputDirectoryError(`Unable to inspect scan output directory: ${outputDirectory}`, { cause: error });
1117
1216
  }
1118
1217
  }
1218
+ export async function prepareScanArtifactRestorer(options, scanDirectory) {
1219
+ let helperPath;
1220
+ let canonicalPath;
1221
+ let dev;
1222
+ let ino;
1223
+ try {
1224
+ // Recovery uses the SDK-owned writer, even if the scan selected a custom plugin.
1225
+ helperPath = join(await bundledPluginRoot(), "scripts", "finalize_scan_contract.py");
1226
+ const result = await runCodexCommand({ command: options.python }, [
1227
+ "-I",
1228
+ "-X",
1229
+ "utf8",
1230
+ "-B",
1231
+ "-c",
1232
+ PREPARE_SCAN_ARTIFACT_RESTORER_PROGRAM,
1233
+ helperPath,
1234
+ scanDirectory,
1235
+ ], pluginHelperEnvironment(options.environment), undefined, options.signal);
1236
+ if (!result.success) {
1237
+ throw new Error(result.stderr.trim() ||
1238
+ result.stdout.trim() ||
1239
+ `Artifact restoration setup exited with status ${result.exitCode}.`);
1240
+ }
1241
+ const prepared = JSON.parse(result.stdout);
1242
+ if (!isRecord(prepared) ||
1243
+ typeof prepared["canonicalPath"] !== "string" ||
1244
+ prepared["canonicalPath"].length === 0 ||
1245
+ typeof prepared["dev"] !== "string" ||
1246
+ !/^(?:0|[1-9]\d*)$/u.test(prepared["dev"]) ||
1247
+ typeof prepared["ino"] !== "string" ||
1248
+ !/^(?:0|[1-9]\d*)$/u.test(prepared["ino"])) {
1249
+ throw new Error("Artifact restoration setup returned invalid output.");
1250
+ }
1251
+ canonicalPath = prepared["canonicalPath"];
1252
+ dev = prepared["dev"];
1253
+ ino = prepared["ino"];
1254
+ }
1255
+ catch (error) {
1256
+ if (options.signal?.aborted)
1257
+ throw error;
1258
+ throw new OutputDirectoryError("Could not securely prepare completed scan artifact restoration.", { cause: error });
1259
+ }
1260
+ return {
1261
+ async restore(relativePath, contents) {
1262
+ try {
1263
+ const result = await runCodexCommand({ command: options.python }, [
1264
+ "-I",
1265
+ "-X",
1266
+ "utf8",
1267
+ "-B",
1268
+ "-c",
1269
+ RESTORE_SCAN_ARTIFACT_PROGRAM,
1270
+ helperPath,
1271
+ canonicalPath,
1272
+ relativePath,
1273
+ dev,
1274
+ ino,
1275
+ ], pluginHelperEnvironment(options.environment), contents, options.signal);
1276
+ if (!result.success) {
1277
+ throw new Error(result.stderr.trim() ||
1278
+ result.stdout.trim() ||
1279
+ `Artifact restoration exited with status ${result.exitCode}.`);
1280
+ }
1281
+ }
1282
+ catch (error) {
1283
+ if (options.signal?.aborted)
1284
+ throw error;
1285
+ throw new OutputDirectoryError("Could not safely restore a completed scan artifact.", { cause: error });
1286
+ }
1287
+ },
1288
+ };
1289
+ }
1119
1290
  export async function planOutputArchive(outputDirectory) {
1120
1291
  if (outputDirectory === null)
1121
1292
  return null;
@@ -1720,6 +1891,9 @@ export function pythonUtf8Environment(environment) {
1720
1891
  normalized["PYTHONUTF8"] = "1";
1721
1892
  return normalized;
1722
1893
  }
1894
+ function pluginHelperEnvironment(environment) {
1895
+ return pythonUtf8Environment(Object.fromEntries(Object.entries(environment).filter(([name]) => !PLUGIN_HELPER_SECRET_ENVIRONMENT_VARIABLES.has(name.toUpperCase()))));
1896
+ }
1723
1897
  export async function cleanupSdkDirectory(path) {
1724
1898
  await rm(path, { recursive: true, force: true });
1725
1899
  }