@openai/codex-security 0.5.1 → 0.6.0

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 (173) hide show
  1. package/README.md +86 -2
  2. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  3. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  4. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  5. package/_bundled_plugin/scripts/workbench_finding_workflows.py +2 -0
  6. package/_bundled_plugin/shared/workbench-migrations.json +16 -0
  7. package/_bundled_plugin/skills/fix-finding/SKILL.md +16 -8
  8. package/_bundled_plugin/skills/publish-findings/SKILL.md +130 -0
  9. package/_bundled_plugin/skills/publish-findings/agents/openai.yaml +6 -0
  10. package/_bundled_plugin/skills/verify-fix/SKILL.md +4 -2
  11. package/dist/api.d.ts +3 -0
  12. package/dist/api.d.ts.map +1 -1
  13. package/dist/api.js +76 -38
  14. package/dist/api.js.map +1 -1
  15. package/dist/classify-severity-records.d.ts +5 -2
  16. package/dist/classify-severity-records.d.ts.map +1 -1
  17. package/dist/classify-severity-records.js +40 -34
  18. package/dist/classify-severity-records.js.map +1 -1
  19. package/dist/classify-severity.d.ts +5 -1
  20. package/dist/classify-severity.d.ts.map +1 -1
  21. package/dist/classify-severity.js +20 -30
  22. package/dist/classify-severity.js.map +1 -1
  23. package/dist/cli-help.d.ts.map +1 -1
  24. package/dist/cli-help.js +1 -0
  25. package/dist/cli-help.js.map +1 -1
  26. package/dist/cli.d.ts +7 -0
  27. package/dist/cli.d.ts.map +1 -1
  28. package/dist/cli.js +412 -14
  29. package/dist/cli.js.map +1 -1
  30. package/dist/cloud-endpoint.d.ts +6 -0
  31. package/dist/cloud-endpoint.d.ts.map +1 -0
  32. package/dist/cloud-endpoint.js +51 -0
  33. package/dist/cloud-endpoint.js.map +1 -0
  34. package/dist/cloud-publish.d.ts.map +1 -1
  35. package/dist/cloud-publish.js +7 -5
  36. package/dist/cloud-publish.js.map +1 -1
  37. package/dist/default-severity-rubric.d.ts +3 -0
  38. package/dist/default-severity-rubric.d.ts.map +1 -0
  39. package/dist/default-severity-rubric.js +67 -0
  40. package/dist/default-severity-rubric.js.map +1 -0
  41. package/dist/endor-findings.d.ts +7 -0
  42. package/dist/endor-findings.d.ts.map +1 -0
  43. package/dist/endor-findings.js +233 -0
  44. package/dist/endor-findings.js.map +1 -0
  45. package/dist/external-findings-import.d.ts +5 -0
  46. package/dist/external-findings-import.d.ts.map +1 -0
  47. package/dist/external-findings-import.js +38 -0
  48. package/dist/external-findings-import.js.map +1 -0
  49. package/dist/external-findings-local.d.ts +63 -0
  50. package/dist/external-findings-local.d.ts.map +1 -0
  51. package/dist/external-findings-local.js +337 -0
  52. package/dist/external-findings-local.js.map +1 -0
  53. package/dist/external-findings-publish.d.ts +73 -0
  54. package/dist/external-findings-publish.d.ts.map +1 -0
  55. package/dist/external-findings-publish.js +713 -0
  56. package/dist/external-findings-publish.js.map +1 -0
  57. package/dist/external-findings-read.d.ts +6 -0
  58. package/dist/external-findings-read.d.ts.map +1 -0
  59. package/dist/external-findings-read.js +88 -0
  60. package/dist/external-findings-read.js.map +1 -0
  61. package/dist/external-findings.d.ts +21 -0
  62. package/dist/external-findings.d.ts.map +1 -0
  63. package/dist/external-findings.js +2 -0
  64. package/dist/external-findings.js.map +1 -0
  65. package/dist/external-import-contract.d.ts +13 -0
  66. package/dist/external-import-contract.d.ts.map +1 -0
  67. package/dist/external-import-contract.js +254 -0
  68. package/dist/external-import-contract.js.map +1 -0
  69. package/dist/external-import-models.d.ts +362 -0
  70. package/dist/external-import-models.d.ts.map +1 -0
  71. package/dist/external-import-models.js +3 -0
  72. package/dist/external-import-models.js.map +1 -0
  73. package/dist/finding-workflow.d.ts +1 -1
  74. package/dist/finding-workflow.d.ts.map +1 -1
  75. package/dist/finding-workflow.js +2 -1
  76. package/dist/finding-workflow.js.map +1 -1
  77. package/dist/github-advisories.d.ts +386 -0
  78. package/dist/github-advisories.d.ts.map +1 -0
  79. package/dist/github-advisories.js +131 -0
  80. package/dist/github-advisories.js.map +1 -0
  81. package/dist/github-findings.d.ts +10 -0
  82. package/dist/github-findings.d.ts.map +1 -0
  83. package/dist/github-findings.js +256 -0
  84. package/dist/github-findings.js.map +1 -0
  85. package/dist/hosted-remediation-protocol.d.ts +2 -1
  86. package/dist/hosted-remediation-protocol.d.ts.map +1 -1
  87. package/dist/hosted-remediation-protocol.js +17 -11
  88. package/dist/hosted-remediation-protocol.js.map +1 -1
  89. package/dist/hosted-remediation.d.ts +4 -0
  90. package/dist/hosted-remediation.d.ts.map +1 -1
  91. package/dist/hosted-remediation.js +3 -1
  92. package/dist/hosted-remediation.js.map +1 -1
  93. package/dist/hosted-scan.d.ts +16 -0
  94. package/dist/hosted-scan.d.ts.map +1 -1
  95. package/dist/hosted-scan.js +14 -2
  96. package/dist/hosted-scan.js.map +1 -1
  97. package/dist/index.d.ts +13 -0
  98. package/dist/index.d.ts.map +1 -1
  99. package/dist/index.js +8 -0
  100. package/dist/index.js.map +1 -1
  101. package/dist/project-config-schema.d.ts +2 -0
  102. package/dist/project-config-schema.d.ts.map +1 -1
  103. package/dist/project-config-schema.js +1 -0
  104. package/dist/project-config-schema.js.map +1 -1
  105. package/dist/project-config.d.ts +1 -0
  106. package/dist/project-config.d.ts.map +1 -1
  107. package/dist/project-config.js +2 -0
  108. package/dist/project-config.js.map +1 -1
  109. package/dist/remediation.d.ts +6 -0
  110. package/dist/remediation.d.ts.map +1 -1
  111. package/dist/remediation.js +16 -5
  112. package/dist/remediation.js.map +1 -1
  113. package/dist/result.d.ts +4 -0
  114. package/dist/result.d.ts.map +1 -1
  115. package/dist/result.js +10 -0
  116. package/dist/result.js.map +1 -1
  117. package/dist/runtime.d.ts +1 -0
  118. package/dist/runtime.d.ts.map +1 -1
  119. package/dist/runtime.js +3 -1
  120. package/dist/runtime.js.map +1 -1
  121. package/dist/scan-owner-suggestions.d.ts +8 -0
  122. package/dist/scan-owner-suggestions.d.ts.map +1 -0
  123. package/dist/scan-owner-suggestions.js +33 -0
  124. package/dist/scan-owner-suggestions.js.map +1 -0
  125. package/dist/scan-settings.d.ts +1 -0
  126. package/dist/scan-settings.d.ts.map +1 -1
  127. package/dist/scan-settings.js +4 -0
  128. package/dist/scan-settings.js.map +1 -1
  129. package/dist/scanner-import.d.ts +20 -0
  130. package/dist/scanner-import.d.ts.map +1 -0
  131. package/dist/scanner-import.js +204 -0
  132. package/dist/scanner-import.js.map +1 -0
  133. package/dist/security-policy-diff.d.ts +2 -0
  134. package/dist/security-policy-diff.d.ts.map +1 -0
  135. package/dist/security-policy-diff.js +197 -0
  136. package/dist/security-policy-diff.js.map +1 -0
  137. package/dist/security-policy.d.ts +7 -3
  138. package/dist/security-policy.d.ts.map +1 -1
  139. package/dist/security-policy.js +10 -56
  140. package/dist/security-policy.js.map +1 -1
  141. package/dist/semgrep-findings.d.ts +9 -0
  142. package/dist/semgrep-findings.d.ts.map +1 -0
  143. package/dist/semgrep-findings.js +293 -0
  144. package/dist/semgrep-findings.js.map +1 -0
  145. package/dist/severity-review.d.ts +3 -0
  146. package/dist/severity-review.d.ts.map +1 -1
  147. package/dist/severity-review.js +19 -0
  148. package/dist/severity-review.js.map +1 -1
  149. package/dist/severity-store.js +7 -2
  150. package/dist/severity-store.js.map +1 -1
  151. package/dist/snyk-findings.d.ts +9 -0
  152. package/dist/snyk-findings.d.ts.map +1 -0
  153. package/dist/snyk-findings.js +349 -0
  154. package/dist/snyk-findings.js.map +1 -0
  155. package/dist/targets.d.ts +2 -2
  156. package/dist/targets.d.ts.map +1 -1
  157. package/dist/targets.js +12 -2
  158. package/dist/targets.js.map +1 -1
  159. package/dist/wiz-csv.d.ts +8 -0
  160. package/dist/wiz-csv.d.ts.map +1 -0
  161. package/dist/wiz-csv.js +116 -0
  162. package/dist/wiz-csv.js.map +1 -0
  163. package/dist/wiz-findings.d.ts +4 -0
  164. package/dist/wiz-findings.d.ts.map +1 -0
  165. package/dist/wiz-findings.js +460 -0
  166. package/dist/wiz-findings.js.map +1 -0
  167. package/docs/classify-severity-records.md +28 -10
  168. package/docs/cli.md +702 -31
  169. package/docs/hosted-remediation.md +24 -7
  170. package/docs/hosted-scans.md +12 -0
  171. package/package.json +6 -4
  172. package/schemas/external-findings.schema.json +1421 -0
  173. package/schemas/project-config.schema.json +4 -0
@@ -0,0 +1,8 @@
1
+ import type { ScanResult } from "./result.js";
2
+ import type { ScanArtifactRestorer } from "./runtime.js";
3
+ import type { ReadOnlyCodexOptions } from "./scan-comparison.js";
4
+ import { type SuggestOwnersOptions } from "./suggest-owners.js";
5
+ export declare const OWNER_SUGGESTIONS_ARTIFACT = "owner-suggestions.json";
6
+ /** Write enrichment beside the sealed scan, without changing its manifest or findings. */
7
+ export declare function writeScanOwnerSuggestions(repository: string, result: ScanResult, writer: ScanArtifactRestorer, options: SuggestOwnersOptions & Pick<ReadOnlyCodexOptions, "auth">, surface?: "sdk" | "cli"): Promise<string>;
8
+ //# sourceMappingURL=scan-owner-suggestions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan-owner-suggestions.d.ts","sourceRoot":"","sources":["../src/scan-owner-suggestions.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAMjE,OAAO,EAEL,KAAK,oBAAoB,EAC1B,MAAM,qBAAqB,CAAC;AAE7B,eAAO,MAAM,0BAA0B,2BAA2B,CAAC;AAEnE,0FAA0F;AAC1F,wBAAsB,yBAAyB,CAC7C,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,UAAU,EAClB,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,oBAAoB,GAAG,IAAI,CAAC,oBAAoB,EAAE,MAAM,CAAC,EAClE,OAAO,GAAE,KAAK,GAAG,KAAa,GAC7B,OAAO,CAAC,MAAM,CAAC,CAyCjB"}
@@ -0,0 +1,33 @@
1
+ import { join, relative, sep } from "node:path";
2
+ import { enclosingGitWorktreeRoot, normalizeRepository, repositoryRevision, } from "./targets.js";
3
+ import { suggestOwnersInternal, } from "./suggest-owners.js";
4
+ export const OWNER_SUGGESTIONS_ARTIFACT = "owner-suggestions.json";
5
+ /** Write enrichment beside the sealed scan, without changing its manifest or findings. */
6
+ export async function writeScanOwnerSuggestions(repository, result, writer, options, surface = "sdk") {
7
+ const target = result.manifest.scan.target;
8
+ const revision = target.revision ?? target.headRevision;
9
+ if (result.manifest.scan.status !== "completed" ||
10
+ !revision ||
11
+ !["git_revision", "git_diff"].includes(target.kind))
12
+ throw new Error("Owner suggestions require a completed scan of committed Git content.");
13
+ if ((await repositoryRevision(repository, options.signal)) !== revision)
14
+ throw new Error("Owner checkout does not match the completed scan revision.");
15
+ const scanRoot = await normalizeRepository(repository, options.signal);
16
+ const gitRoot = (await enclosingGitWorktreeRoot(scanRoot, options.signal, {
17
+ requireIfPresent: true,
18
+ })) ?? scanRoot;
19
+ const prefix = relative(gitRoot, scanRoot).split(sep).join("/");
20
+ const report = await suggestOwnersInternal(repository, result.findings.findings.map((finding) => ({
21
+ ...finding,
22
+ sourceRevision: revision,
23
+ locations: finding.locations.map((location) => ({
24
+ ...location,
25
+ path: prefix ? `${prefix}/${location.path}` : location.path,
26
+ })),
27
+ })), options, surface);
28
+ if (report.revision !== revision)
29
+ throw new Error("Owner report revision does not match the completed scan.");
30
+ await writer.restore(OWNER_SUGGESTIONS_ARTIFACT, Buffer.from(`${JSON.stringify(report)}\n`));
31
+ return join(result.scanDir, OWNER_SUGGESTIONS_ARTIFACT);
32
+ }
33
+ //# sourceMappingURL=scan-owner-suggestions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scan-owner-suggestions.js","sourceRoot":"","sources":["../src/scan-owner-suggestions.ts"],"names":[],"mappings":"AAAA,OAAO,E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AC,IAAI,CAAC,GAAG,CAAC,CAAC;IAChE,MAAM,MAAM,GAAG,MAAM,qBAAqB,CACxC,UAAU,EACV,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;QACzC,GAAG,OAAO;QACV,cAAc,EAAE,QAAQ;QACxB,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;YAC9C,GAAG,QAAQ;YACX,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,IAAI,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI;SAC5D,CAAC,CAAC;KACJ,CAAC,CAAC,EACH,OAAO,EACP,OAAO,CACR,CAAC;IACF,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ;QAC9B,MAAM,IAAI,KAAK,CAAC,0DAA0D,CAAC,CAAC;IAC9E,MAAM,MAAM,CAAC,OAAO,CAClB,0BAA0B,EAC1B,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAC3C,CAAC;IACF,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,0BAA0B,CAAC,CAAC;AAC1D,CAAC","sourcesContent":["import { join, relative, sep } from \"node:path\";\nimport type { ScanResult } from \"./result.js\";\nimport type { ScanArtifactRestorer } from \"./runtime.js\";\nimport type { ReadOnlyCodexOptions } from \"./scan-comparison.js\";\nimport {\n enclosingGitWorktreeRoot,\n normalizeRepository,\n repositoryRevision,\n} from \"./targets.js\";\nimport {\n suggestOwnersInternal,\n type SuggestOwnersOptions,\n} from \"./suggest-owners.js\";\n\nexport const OWNER_SUGGESTIONS_ARTIFACT = \"owner-suggestions.json\";\n\n/** Write enrichment beside the sealed scan, without changing its manifest or findings. */\nexport async function writeScanOwnerSuggestions(\n repository: string,\n result: ScanResult,\n writer: ScanArtifactRestorer,\n options: SuggestOwnersOptions & Pick<ReadOnlyCodexOptions, \"auth\">,\n surface: \"sdk\" | \"cli\" = \"sdk\",\n): Promise<string> {\n const target = result.manifest.scan.target;\n const revision = target.revision ?? target.headRevision;\n if (\n result.manifest.scan.status !== \"completed\" ||\n !revision ||\n ![\"git_revision\", \"git_diff\"].includes(target.kind)\n )\n throw new Error(\n \"Owner suggestions require a completed scan of committed Git content.\",\n );\n if ((await repositoryRevision(repository, options.signal)) !== revision)\n throw new Error(\n \"Owner checkout does not match the completed scan revision.\",\n );\n const scanRoot = await normalizeRepository(repository, options.signal);\n const gitRoot =\n (await enclosingGitWorktreeRoot(scanRoot, options.signal, {\n requireIfPresent: true,\n })) ?? scanRoot;\n const prefix = relative(gitRoot, scanRoot).split(sep).join(\"/\");\n const report = await suggestOwnersInternal(\n repository,\n result.findings.findings.map((finding) => ({\n ...finding,\n sourceRevision: revision,\n locations: finding.locations.map((location) => ({\n ...location,\n path: prefix ? `${prefix}/${location.path}` : location.path,\n })),\n })),\n options,\n surface,\n );\n if (report.revision !== revision)\n throw new Error(\"Owner report revision does not match the completed scan.\");\n await writer.restore(\n OWNER_SUGGESTIONS_ARTIFACT,\n Buffer.from(`${JSON.stringify(report)}\\n`),\n );\n return join(result.scanDir, OWNER_SUGGESTIONS_ARTIFACT);\n}\n"]}
@@ -64,6 +64,7 @@ export declare const ScanSettingsSchema: z.ZodObject<{
64
64
  medium: "medium";
65
65
  }>>;
66
66
  maxCostUsd: z.ZodOptional<z.ZodNumber>;
67
+ ownerSuggestions: z.ZodOptional<z.ZodBoolean>;
67
68
  }, z.core.$strict>;
68
69
  /** Scan settings shared by SDK calls, CLI flags, and project files. */
69
70
  export interface ScanSettings extends z.infer<typeof ScanSettingsSchema> {
@@ -1 +1 @@
1
- {"version":3,"file":"scan-settings.d.ts","sourceRoot":"","sources":["../src/scan-settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KA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,CAAC,EAAE,UAAU,CAAC;CACrB;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACxD,IAAI,EAAE,YAAY,CAAC;IACnB,IAAI,EAAE,QAAQ,CAAC;IACf,MAAM,EAAE,UAAU,CAAC;IACnB,kBAAkB,EAAE,YAAY,EAAE,CAAC;IACnC,cAAc,CAAC,EAAE,YAAY,CAAC;IAC9B,oBAAoB,CAAC,EAAE,YAAY,CAAC;IACpC,kBAAkB,CAAC,EAAE,YAAY,CAAC;IAClC,SAAS,CAAC,EAAE,YAAY,CAAC;CAC1B;AAED,MAAM,MAAM,kBAAkB,GAAG,IAAI,CACnC,YAAY,EACV,YAAY,GACZ,gBAAgB,GAChB,kBAAkB,GAClB,sBAAsB,GACtB,gBAAgB,GAChB,oBAAoB,CACvB,CAAC;AAEF,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,YAAY,GAAG,YAAY,CAUrE;AAED,wBAAgB,aAAa,CAC3B,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,UAAU,CAAC,EAClC,SAAS,EAAE,aAAa,GACvB,OAAO,CAIT;AAED,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,aAAa,GAAG,MAAM,CAQtE"}
@@ -107,6 +107,10 @@ export const ScanSettingsSchema = DeepScanSettingsSchema.extend({
107
107
  outputDir: inputPath.optional(),
108
108
  failureSeverity: z.enum(SCAN_SEVERITIES).optional(),
109
109
  maxCostUsd: z.number().positive().optional(),
110
+ ownerSuggestions: z
111
+ .boolean()
112
+ .optional()
113
+ .describe("Generate optional owner-suggestions.json after a committed scan (default: false)."),
110
114
  });
111
115
  /** Pick defined scan settings without copying callbacks or workflow controls. */
112
116
  export function pickScanSettings(settings) {
@@ -1 +1 @@
1
- {"version":3,"file":"scan-settings.js","sourceRoot":"","sources":["../src/scan-settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,0BAA0B,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C,SAAS,CAAC,GAAG,CACpD,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { DEFAULT_DEEP_SCAN_SETTINGS } from \"./deep-scan-defaults.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Finding, SeverityLevel } from \"./models.js\";\nimport type { AbsolutePath } from \"./config-path.js\";\nimport { SCAN_MODES, type ScanMode } from \"./scan-modes.js\";\nimport type { ScanTarget } from \"./targets.js\";\n\nexport const SCAN_AUTH_MODES = [\"auto\", \"chatgpt\", \"api-key\"] as const;\nexport type ScanAuthMode = (typeof SCAN_AUTH_MODES)[number];\nexport const DEFAULT_SCAN_AUTH = \"auto\";\nexport const DEFAULT_SCAN_MODE = \"standard\";\nexport const REPORTABLE_SEVERITIES = [\n \"critical\",\n \"high\",\n \"medium\",\n \"low\",\n] as const;\nexport const SCAN_SEVERITIES = [\n ...REPORTABLE_SEVERITIES,\n \"informational\",\n] as const;\nexport const FailureSeveritySchema = z.enum(REPORTABLE_SEVERITIES);\nexport type FailureSeverity = z.infer<typeof FailureSeveritySchema>;\n\n// SDK name, legacy TOML key, project key, and CLI flag (when exposed).\nexport const DEEP_SCAN_SETTINGS = [\n [\"workers\", \"workers\", \"workers\", \"--workers\"],\n [\"subagents\", \"subagents\", \"subagents_per_worker\", \"--subagents\"],\n [\n \"stopAfterNoNew\",\n \"stop_after_no_new\",\n \"stop_after_no_new\",\n \"--stop-after-no-new\",\n ],\n [\n \"stopAfterConsecutiveErrors\",\n \"stop_after_consecutive_errors\",\n \"stop_after_consecutive_errors\",\n null,\n ],\n [\n \"maxDiscoveryRuns\",\n \"max_discovery_runs\",\n \"max_discovery_runs\",\n \"--max-discovery-runs\",\n ],\n [\"maxTimeHours\", \"max_time_hours\", \"max_time_hours\", \"--max-time-hours\"],\n] as const;\n\nconst positiveIntegerError = \"must be a positive integer\";\nconst positiveInteger = z\n .number({ error: positiveIntegerError })\n .int({ error: positiveIntegerError })\n .positive({ error: positiveIntegerError });\nconst nonnegativeIntegerError = \"must be a non-negative integer\";\nconst nonnegativeInteger = z\n .number({ error: nonnegativeIntegerError })\n .int({ error: nonnegativeIntegerError })\n .nonnegative({ error: nonnegativeIntegerError });\nconst maximumHours = 96;\nconst hoursError = `must be a positive number no greater than ${maximumHours}`;\n\nexport const DeepScanSettingsSchema = z.strictObject({\n workers: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.workers,\n description: \"Maximum concurrent deep-scan discovery workers.\",\n }),\n subagents: nonnegativeInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.subagents,\n description: \"Subagents available to each deep-scan worker. Zero is valid.\",\n }),\n stopAfterNoNew: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.stopAfterNoNew,\n description: \"Stop after this many runs find no new issues.\",\n }),\n stopAfterConsecutiveErrors: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.stopAfterConsecutiveErrors,\n description: \"Stop after this many consecutive discovery errors.\",\n }),\n maxDiscoveryRuns: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.maxDiscoveryRuns,\n description: \"Maximum deep-scan discovery runs.\",\n }),\n maxTimeHours: z\n .number({ error: hoursError })\n .positive({ error: hoursError })\n .max(maximumHours, { error: hoursError })\n .optional()\n .meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.maxTimeHours,\n deprecated: true,\n description:\n \"Deprecated Deep-only alias for maxTimeMinutes / --max-time, in hours (default: 96; maximum: 96).\",\n }),\n});\n\nexport type DeepScanOptions = z.infer<typeof DeepScanSettingsSchema>;\n\nconst inputPath = z.string().min(1);\n\nexport const ScanSettingsSchema = DeepScanSettingsSchema.extend({\n auth: z.enum(SCAN_AUTH_MODES).optional().meta({ default: DEFAULT_SCAN_AUTH }),\n cyberAccessProgram: z\n .enum([\"standard\", \"daybreak_blue\", \"daybreak_red\"])\n .optional()\n .describe(\n \"Experimental Cyber access program for scan turns (OpenAI provider only). Omit to preserve Codex defaults.\",\n ),\n mode: z.enum(SCAN_MODES).optional().meta({ default: DEFAULT_SCAN_MODE }),\n maxTimeMinutes: z\n .number()\n .positive()\n .optional()\n .describe(\n \"Investigation minutes: advisory in Standard (default: unset); enforced Deep discovery limit (default and maximum: 5760). Scans may finish early; reporting may run longer.\",\n ),\n knowledgeBasePaths: z.array(inputPath).optional(),\n scanPrompt: z.string().optional(),\n scanPromptFile: inputPath.optional(),\n validationPrompt: z.string().optional(),\n validationPromptFile: inputPath.optional(),\n postScanPrompt: z.string().optional(),\n postScanPromptFile: inputPath.optional(),\n outputDir: inputPath.optional(),\n failureSeverity: z.enum(SCAN_SEVERITIES).optional(),\n maxCostUsd: z.number().positive().optional(),\n});\n\n/** Scan settings shared by SDK calls, CLI flags, and project files. */\nexport interface ScanSettings extends z.infer<typeof ScanSettingsSchema> {\n target?: ScanTarget;\n}\n\nexport interface ResolvedScanSettings extends ScanSettings {\n auth: ScanAuthMode;\n mode: ScanMode;\n target: ScanTarget;\n knowledgeBasePaths: AbsolutePath[];\n scanPromptFile?: AbsolutePath;\n validationPromptFile?: AbsolutePath;\n postScanPromptFile?: AbsolutePath;\n outputDir?: AbsolutePath;\n}\n\nexport type ScanPromptSettings = Pick<\n ScanSettings,\n | \"scanPrompt\"\n | \"scanPromptFile\"\n | \"validationPrompt\"\n | \"validationPromptFile\"\n | \"postScanPrompt\"\n | \"postScanPromptFile\"\n>;\n\n/** Pick defined scan settings without copying callbacks or workflow controls. */\nexport function pickScanSettings(settings: ScanSettings): ScanSettings {\n const keys = [\n \"target\",\n ...Object.keys(ScanSettingsSchema.shape),\n ] as (keyof ScanSettings)[];\n return Object.fromEntries(\n keys\n .filter((key) => settings[key] !== undefined)\n .map((key) => [key, settings[key]]),\n ) as ScanSettings;\n}\n\nexport function meetsSeverity(\n finding: Pick<Finding, \"severity\">,\n threshold: SeverityLevel,\n): boolean {\n const thresholdRank = severityThresholdRank(threshold);\n const severity = SCAN_SEVERITIES.indexOf(finding.severity.level);\n return severity >= 0 && severity <= thresholdRank;\n}\n\nexport function severityThresholdRank(threshold: SeverityLevel): number {\n const rank = SCAN_SEVERITIES.indexOf(threshold);\n if (rank < 0) {\n throw new ConfigurationError(\n `Unknown severity threshold: ${String(threshold)}.`,\n );\n }\n return rank;\n}\n"]}
1
+ {"version":3,"file":"scan-settings.js","sourceRoot":"","sources":["../src/scan-settings.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD,OAAO,EAAE,UAAU,EAAiB,MAAM,iBAAiB,CAAC;AAG5D,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAU,CAAC;AAEvE,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACxC,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC;AAC5C,MAAM,CAAC,MAAM,qBAAqB,GAAG;IACnC,UAAU;IACV,MAAM;IACN,QAAQ;IACR,KAAK;CACG,CAAC;AACX,MAAM,CAAC,MAAM,eAAe,GAAG;IAC7B,GAAG,qBAAqB;IACxB,eAAe;CACP,CAAC;AACX,MAAM,CAAC,MAAM,qBAAqB,GAAG,CAAC,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;AAGnE,uEAAuE;AACvE,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,CAAC;IAC9C,CAAC,WAAW,EAAE,WAAW,EAAE,sBAAsB,EAAE,aAAa,CAAC;IACjE;QACE,gBAAgB;QAChB,mBAAmB;QACnB,mBAAmB;QACnB,qBAAqB;KACtB;IACD;QACE,4BAA4B;QAC5B,+BAA+B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AED,MAAM,UAAU,aAAa,CAC3B,OAAkC,EAClC,SAAwB;IAExB,MAAM,aAAa,GAAG,qBAAqB,CAAC,SAAS,CAAC,CAAC;IACvD,MAAM,QAAQ,GAAG,eAAe,CAAC,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACjE,OAAO,QAAQ,IAAI,CAAC,IAAI,QAAQ,IAAI,aAAa,CAAC;AACpD,CAAC;AAED,MAAM,UAAU,qBAAqB,CAAC,SAAwB;IAC5D,MAAM,IAAI,GAAG,eAAe,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChD,IAAI,IAAI,GAAG,CAAC,EAAE,CAAC;QACb,MAAM,IAAI,kBAAkB,CAC1B,+BAA+B,MAAM,CAAC,SAAS,CAAC,GAAG,CACpD,CAAC;IACJ,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { z } from \"zod\";\nimport { DEFAULT_DEEP_SCAN_SETTINGS } from \"./deep-scan-defaults.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Finding, SeverityLevel } from \"./models.js\";\nimport type { AbsolutePath } from \"./config-path.js\";\nimport { SCAN_MODES, type ScanMode } from \"./scan-modes.js\";\nimport type { ScanTarget } from \"./targets.js\";\n\nexport const SCAN_AUTH_MODES = [\"auto\", \"chatgpt\", \"api-key\"] as const;\nexport type ScanAuthMode = (typeof SCAN_AUTH_MODES)[number];\nexport const DEFAULT_SCAN_AUTH = \"auto\";\nexport const DEFAULT_SCAN_MODE = \"standard\";\nexport const REPORTABLE_SEVERITIES = [\n \"critical\",\n \"high\",\n \"medium\",\n \"low\",\n] as const;\nexport const SCAN_SEVERITIES = [\n ...REPORTABLE_SEVERITIES,\n \"informational\",\n] as const;\nexport const FailureSeveritySchema = z.enum(REPORTABLE_SEVERITIES);\nexport type FailureSeverity = z.infer<typeof FailureSeveritySchema>;\n\n// SDK name, legacy TOML key, project key, and CLI flag (when exposed).\nexport const DEEP_SCAN_SETTINGS = [\n [\"workers\", \"workers\", \"workers\", \"--workers\"],\n [\"subagents\", \"subagents\", \"subagents_per_worker\", \"--subagents\"],\n [\n \"stopAfterNoNew\",\n \"stop_after_no_new\",\n \"stop_after_no_new\",\n \"--stop-after-no-new\",\n ],\n [\n \"stopAfterConsecutiveErrors\",\n \"stop_after_consecutive_errors\",\n \"stop_after_consecutive_errors\",\n null,\n ],\n [\n \"maxDiscoveryRuns\",\n \"max_discovery_runs\",\n \"max_discovery_runs\",\n \"--max-discovery-runs\",\n ],\n [\"maxTimeHours\", \"max_time_hours\", \"max_time_hours\", \"--max-time-hours\"],\n] as const;\n\nconst positiveIntegerError = \"must be a positive integer\";\nconst positiveInteger = z\n .number({ error: positiveIntegerError })\n .int({ error: positiveIntegerError })\n .positive({ error: positiveIntegerError });\nconst nonnegativeIntegerError = \"must be a non-negative integer\";\nconst nonnegativeInteger = z\n .number({ error: nonnegativeIntegerError })\n .int({ error: nonnegativeIntegerError })\n .nonnegative({ error: nonnegativeIntegerError });\nconst maximumHours = 96;\nconst hoursError = `must be a positive number no greater than ${maximumHours}`;\n\nexport const DeepScanSettingsSchema = z.strictObject({\n workers: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.workers,\n description: \"Maximum concurrent deep-scan discovery workers.\",\n }),\n subagents: nonnegativeInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.subagents,\n description: \"Subagents available to each deep-scan worker. Zero is valid.\",\n }),\n stopAfterNoNew: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.stopAfterNoNew,\n description: \"Stop after this many runs find no new issues.\",\n }),\n stopAfterConsecutiveErrors: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.stopAfterConsecutiveErrors,\n description: \"Stop after this many consecutive discovery errors.\",\n }),\n maxDiscoveryRuns: positiveInteger.optional().meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.maxDiscoveryRuns,\n description: \"Maximum deep-scan discovery runs.\",\n }),\n maxTimeHours: z\n .number({ error: hoursError })\n .positive({ error: hoursError })\n .max(maximumHours, { error: hoursError })\n .optional()\n .meta({\n default: DEFAULT_DEEP_SCAN_SETTINGS.maxTimeHours,\n deprecated: true,\n description:\n \"Deprecated Deep-only alias for maxTimeMinutes / --max-time, in hours (default: 96; maximum: 96).\",\n }),\n});\n\nexport type DeepScanOptions = z.infer<typeof DeepScanSettingsSchema>;\n\nconst inputPath = z.string().min(1);\n\nexport const ScanSettingsSchema = DeepScanSettingsSchema.extend({\n auth: z.enum(SCAN_AUTH_MODES).optional().meta({ default: DEFAULT_SCAN_AUTH }),\n cyberAccessProgram: z\n .enum([\"standard\", \"daybreak_blue\", \"daybreak_red\"])\n .optional()\n .describe(\n \"Experimental Cyber access program for scan turns (OpenAI provider only). Omit to preserve Codex defaults.\",\n ),\n mode: z.enum(SCAN_MODES).optional().meta({ default: DEFAULT_SCAN_MODE }),\n maxTimeMinutes: z\n .number()\n .positive()\n .optional()\n .describe(\n \"Investigation minutes: advisory in Standard (default: unset); enforced Deep discovery limit (default and maximum: 5760). Scans may finish early; reporting may run longer.\",\n ),\n knowledgeBasePaths: z.array(inputPath).optional(),\n scanPrompt: z.string().optional(),\n scanPromptFile: inputPath.optional(),\n validationPrompt: z.string().optional(),\n validationPromptFile: inputPath.optional(),\n postScanPrompt: z.string().optional(),\n postScanPromptFile: inputPath.optional(),\n outputDir: inputPath.optional(),\n failureSeverity: z.enum(SCAN_SEVERITIES).optional(),\n maxCostUsd: z.number().positive().optional(),\n ownerSuggestions: z\n .boolean()\n .optional()\n .describe(\n \"Generate optional owner-suggestions.json after a committed scan (default: false).\",\n ),\n});\n\n/** Scan settings shared by SDK calls, CLI flags, and project files. */\nexport interface ScanSettings extends z.infer<typeof ScanSettingsSchema> {\n target?: ScanTarget;\n}\n\nexport interface ResolvedScanSettings extends ScanSettings {\n auth: ScanAuthMode;\n mode: ScanMode;\n target: ScanTarget;\n knowledgeBasePaths: AbsolutePath[];\n scanPromptFile?: AbsolutePath;\n validationPromptFile?: AbsolutePath;\n postScanPromptFile?: AbsolutePath;\n outputDir?: AbsolutePath;\n}\n\nexport type ScanPromptSettings = Pick<\n ScanSettings,\n | \"scanPrompt\"\n | \"scanPromptFile\"\n | \"validationPrompt\"\n | \"validationPromptFile\"\n | \"postScanPrompt\"\n | \"postScanPromptFile\"\n>;\n\n/** Pick defined scan settings without copying callbacks or workflow controls. */\nexport function pickScanSettings(settings: ScanSettings): ScanSettings {\n const keys = [\n \"target\",\n ...Object.keys(ScanSettingsSchema.shape),\n ] as (keyof ScanSettings)[];\n return Object.fromEntries(\n keys\n .filter((key) => settings[key] !== undefined)\n .map((key) => [key, settings[key]]),\n ) as ScanSettings;\n}\n\nexport function meetsSeverity(\n finding: Pick<Finding, \"severity\">,\n threshold: SeverityLevel,\n): boolean {\n const thresholdRank = severityThresholdRank(threshold);\n const severity = SCAN_SEVERITIES.indexOf(finding.severity.level);\n return severity >= 0 && severity <= thresholdRank;\n}\n\nexport function severityThresholdRank(threshold: SeverityLevel): number {\n const rank = SCAN_SEVERITIES.indexOf(threshold);\n if (rank < 0) {\n throw new ConfigurationError(\n `Unknown severity threshold: ${String(threshold)}.`,\n );\n }\n return rank;\n}\n"]}
@@ -0,0 +1,20 @@
1
+ import type { ExternalFinding, ExternalFindings } from "./external-findings.js";
2
+ export declare function record(value: unknown, label: string): Record<string, unknown>;
3
+ export declare function array(value: unknown, label: string): unknown[];
4
+ export declare function text(value: unknown): string | null;
5
+ export declare function requiredText(value: unknown, label: string): string;
6
+ export declare function strings(value: unknown): string[];
7
+ /** Paths that cannot be attributed to a repository stay in original evidence. */
8
+ export declare function relativePath(value: unknown): string | null;
9
+ export declare function stableId(prefix: string, fields: unknown[]): string;
10
+ /** Detect gzip from the report bytes and preserve identities with strict UTF-8. */
11
+ export declare function readScannerText(path: string): Promise<string>;
12
+ export declare function parseJsonOrJsonl(contents: string): unknown;
13
+ export declare function readScannerJson(path: string): Promise<unknown>;
14
+ /** Empty reference containers and property-bag metadata do not externalize data. */
15
+ export declare function hasSarifExternalPropertyReferences(value: unknown): boolean;
16
+ /** Keep original artifact indexes; omit only inventory unrelated to this finding. */
17
+ export declare function sarifRunContextForResult(runContext: Record<string, unknown>, ...selectedEvidence: unknown[]): Record<string, unknown>;
18
+ /** Exclude every colliding record: choosing the first could overwrite another occurrence. */
19
+ export declare function normalizeRecords<T>(records: T[], normalize: (record: T, id: string) => ExternalFinding, identify: (record: T) => string): ExternalFindings;
20
+ //# sourceMappingURL=scanner-import.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner-import.d.ts","sourceRoot":"","sources":["../src/scanner-import.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAGhF,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAI7E;AAED,wBAAgB,KAAK,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,EAAE,CAG9D;AAED,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAElD;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAIlE;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,CAIhD;AAED,iFAAiF;AACjF,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAS1D;AAED,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,MAAM,CAElE;AAED,mFAAmF;AACnF,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAKnE;AAED,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAS1D;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBpE;AAED,oFAAoF;AACpF,wBAAgB,kCAAkC,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAS1E;AAeD,qFAAqF;AACrF,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACnC,GAAG,gBAAgB,EAAE,OAAO,EAAE,GAC7B,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAiDzB;AAED,6FAA6F;AAC7F,wBAAgB,gBAAgB,CAAC,CAAC,EAChC,OAAO,EAAE,CAAC,EAAE,EACZ,SAAS,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,KAAK,eAAe,EACrD,QAAQ,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,MAAM,GAC9B,gBAAgB,CAkDlB"}
@@ -0,0 +1,204 @@
1
+ import { hash } from "node:crypto";
2
+ import { readFile } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+ import { gunzip } from "node:zlib";
5
+ import { CodexSecurityError, errorMessage } from "./errors.js";
6
+ import { isRecord } from "./record.js";
7
+ export function record(value, label) {
8
+ if (!value || typeof value !== "object" || Array.isArray(value))
9
+ throw new Error(`${label} must be an object.`);
10
+ return value;
11
+ }
12
+ export function array(value, label) {
13
+ if (!Array.isArray(value))
14
+ throw new Error(`${label} must be an array.`);
15
+ return value;
16
+ }
17
+ export function text(value) {
18
+ return typeof value === "string" && value.trim() ? value : null;
19
+ }
20
+ export function requiredText(value, label) {
21
+ const result = text(value);
22
+ if (!result)
23
+ throw new Error(`${label} must be nonempty text.`);
24
+ return result;
25
+ }
26
+ export function strings(value) {
27
+ return Array.isArray(value)
28
+ ? value.filter((v) => text(v) !== null)
29
+ : [];
30
+ }
31
+ /** Paths that cannot be attributed to a repository stay in original evidence. */
32
+ export function relativePath(value) {
33
+ const path = text(value)?.replaceAll("\\", "/");
34
+ return path &&
35
+ !path.startsWith("/") &&
36
+ !path.includes("\0") &&
37
+ !/^[A-Za-z]:/.test(path) &&
38
+ !path.split("/").includes("..")
39
+ ? path
40
+ : null;
41
+ }
42
+ export function stableId(prefix, fields) {
43
+ return `${prefix}:${hash("sha256", JSON.stringify(fields))}`;
44
+ }
45
+ /** Detect gzip from the report bytes and preserve identities with strict UTF-8. */
46
+ export async function readScannerText(path) {
47
+ let bytes = await readFile(path);
48
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b)
49
+ bytes = await promisify(gunzip)(bytes);
50
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
51
+ }
52
+ export function parseJsonOrJsonl(contents) {
53
+ try {
54
+ return JSON.parse(contents);
55
+ }
56
+ catch {
57
+ return contents
58
+ .split(/\r?\n/u)
59
+ .filter((line) => line.trim())
60
+ .map((line) => JSON.parse(line));
61
+ }
62
+ }
63
+ export async function readScannerJson(path) {
64
+ let bytes = await readFile(path);
65
+ if (bytes[0] === 0x1f && bytes[1] === 0x8b)
66
+ bytes = await promisify(gunzip)(bytes);
67
+ let decoded;
68
+ try {
69
+ decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
70
+ }
71
+ catch (error) {
72
+ throw new CodexSecurityError(`Scanner report is not valid UTF-8. ${errorMessage(error)}`, { cause: error });
73
+ }
74
+ try {
75
+ return JSON.parse(decoded.replace(/^\uFEFF/u, ""));
76
+ }
77
+ catch (error) {
78
+ throw new CodexSecurityError(`Scanner JSON could not be parsed. ${errorMessage(error)}`, { cause: error });
79
+ }
80
+ }
81
+ /** Empty reference containers and property-bag metadata do not externalize data. */
82
+ export function hasSarifExternalPropertyReferences(value) {
83
+ if (value == null)
84
+ return false;
85
+ return Object.entries(record(value, "SARIF external property references")).some(([key, references]) => key !== "properties" &&
86
+ (!Array.isArray(references) || references.length > 0));
87
+ }
88
+ const sarifArtifactLocationFields = new Set([
89
+ "artifactLocation",
90
+ "analysisTarget",
91
+ "executableLocation",
92
+ "workingDirectory",
93
+ "stdin",
94
+ "stdout",
95
+ "stderr",
96
+ "stdoutStderr",
97
+ "mappedTo",
98
+ "displayBase",
99
+ ]);
100
+ /** Keep original artifact indexes; omit only inventory unrelated to this finding. */
101
+ export function sarifRunContextForResult(runContext, ...selectedEvidence) {
102
+ const { artifacts, ...context } = runContext;
103
+ if (!Array.isArray(artifacts) || artifacts.length === 0)
104
+ return runContext;
105
+ const locations = [];
106
+ let hasArtifactLink = false;
107
+ function visit(value) {
108
+ if (typeof value === "string") {
109
+ // SARIF message links can refer to an artifact without an artifactLocation.
110
+ if (/sarif:/iu.test(value))
111
+ hasArtifactLink = true;
112
+ }
113
+ else if (Array.isArray(value))
114
+ value.forEach(visit);
115
+ else if (isRecord(value))
116
+ for (const [key, child] of Object.entries(value)) {
117
+ if (key === "properties")
118
+ continue;
119
+ if (sarifArtifactLocationFields.has(key) && isRecord(child))
120
+ locations.push(child);
121
+ if (["locations", "responseFiles", "analysisToolLogFiles"].includes(key) &&
122
+ Array.isArray(child))
123
+ locations.push(...child.filter(isRecord));
124
+ if (key === "originalUriBaseIds" && isRecord(child))
125
+ locations.push(...Object.values(child).filter(isRecord));
126
+ visit(child);
127
+ }
128
+ }
129
+ visit([context, ...selectedEvidence]);
130
+ if (hasArtifactLink)
131
+ return runContext;
132
+ const unresolvedUri = /[%:\\]|(?:^|\/)\.\.?(?:\/|$)/u;
133
+ for (const location of locations) {
134
+ if (typeof location["index"] === "number" && location["index"] >= 0)
135
+ return runContext;
136
+ if (typeof location["uri"] !== "string")
137
+ continue;
138
+ for (const artifact of artifacts) {
139
+ if (!isRecord(artifact) || !isRecord(artifact["location"]))
140
+ continue;
141
+ const candidate = artifact["location"];
142
+ // Keep URI spellings that need resolution; evidence is never rewritten.
143
+ if (location["uriBaseId"] !== candidate["uriBaseId"] ||
144
+ unresolvedUri.test(location["uri"]) ||
145
+ (typeof candidate["uri"] === "string" &&
146
+ unresolvedUri.test(candidate["uri"])) ||
147
+ location["uri"] === candidate["uri"])
148
+ return runContext;
149
+ }
150
+ }
151
+ return context;
152
+ }
153
+ /** Exclude every colliding record: choosing the first could overwrite another occurrence. */
154
+ export function normalizeRecords(records, normalize, identify) {
155
+ const result = {
156
+ read: records.length,
157
+ findings: [],
158
+ excluded: [],
159
+ };
160
+ const identified = [];
161
+ const counts = new Map();
162
+ for (const [index, value] of records.entries()) {
163
+ try {
164
+ const id = identify(value);
165
+ if (!id.trim() || id.includes("\0") || Buffer.byteLength(id) > 512)
166
+ throw new Error("Source finding ID must contain 1–512 UTF-8 bytes and no NUL characters.");
167
+ identified.push({ position: index + 1, value, id });
168
+ counts.set(id, (counts.get(id) ?? 0) + 1);
169
+ }
170
+ catch (error) {
171
+ result.excluded.push({
172
+ position: index + 1,
173
+ source_finding_id: null,
174
+ reason: errorMessage(error),
175
+ });
176
+ }
177
+ }
178
+ for (const { position, value, id } of identified) {
179
+ if (counts.get(id) > 1) {
180
+ result.excluded.push({
181
+ position,
182
+ source_finding_id: id,
183
+ reason: "Ambiguous duplicate source identity; select one complete finding or separate source projects.",
184
+ });
185
+ continue;
186
+ }
187
+ try {
188
+ const finding = normalize(value, id);
189
+ if (finding.source_finding_id !== id)
190
+ throw new Error("Finding identity changed during normalization.");
191
+ result.findings.push(finding);
192
+ }
193
+ catch (error) {
194
+ result.excluded.push({
195
+ position,
196
+ source_finding_id: id,
197
+ reason: errorMessage(error),
198
+ });
199
+ }
200
+ }
201
+ result.excluded.sort((a, b) => a.position - b.position);
202
+ return result;
203
+ }
204
+ //# sourceMappingURL=scanner-import.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scanner-import.js","sourceRoot":"","sources":["../src/scanner-import.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AACnC,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,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AC,CAAC;IACxD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { hash } from \"node:crypto\";\nimport { readFile } from \"node:fs/promises\";\nimport { promisify } from \"node:util\";\nimport { gunzip } from \"node:zlib\";\nimport { CodexSecurityError, errorMessage } from \"./errors.js\";\nimport type { ExternalFinding, ExternalFindings } from \"./external-findings.js\";\nimport { isRecord } from \"./record.js\";\n\nexport function record(value: unknown, label: string): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new Error(`${label} must be an object.`);\n return value as Record<string, unknown>;\n}\n\nexport function array(value: unknown, label: string): unknown[] {\n if (!Array.isArray(value)) throw new Error(`${label} must be an array.`);\n return value;\n}\n\nexport function text(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nexport function requiredText(value: unknown, label: string): string {\n const result = text(value);\n if (!result) throw new Error(`${label} must be nonempty text.`);\n return result;\n}\n\nexport function strings(value: unknown): string[] {\n return Array.isArray(value)\n ? value.filter((v): v is string => text(v) !== null)\n : [];\n}\n\n/** Paths that cannot be attributed to a repository stay in original evidence. */\nexport function relativePath(value: unknown): string | null {\n const path = text(value)?.replaceAll(\"\\\\\", \"/\");\n return path &&\n !path.startsWith(\"/\") &&\n !path.includes(\"\\0\") &&\n !/^[A-Za-z]:/.test(path) &&\n !path.split(\"/\").includes(\"..\")\n ? path\n : null;\n}\n\nexport function stableId(prefix: string, fields: unknown[]): string {\n return `${prefix}:${hash(\"sha256\", JSON.stringify(fields))}`;\n}\n\n/** Detect gzip from the report bytes and preserve identities with strict UTF-8. */\nexport async function readScannerText(path: string): Promise<string> {\n let bytes = await readFile(path);\n if (bytes[0] === 0x1f && bytes[1] === 0x8b)\n bytes = await promisify(gunzip)(bytes);\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n}\n\nexport function parseJsonOrJsonl(contents: string): unknown {\n try {\n return JSON.parse(contents);\n } catch {\n return contents\n .split(/\\r?\\n/u)\n .filter((line) => line.trim())\n .map((line) => JSON.parse(line));\n }\n}\n\nexport async function readScannerJson(path: string): Promise<unknown> {\n let bytes = await readFile(path);\n if (bytes[0] === 0x1f && bytes[1] === 0x8b)\n bytes = await promisify(gunzip)(bytes);\n let decoded: string;\n try {\n decoded = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n } catch (error) {\n throw new CodexSecurityError(\n `Scanner report is not valid UTF-8. ${errorMessage(error)}`,\n { cause: error },\n );\n }\n try {\n return JSON.parse(decoded.replace(/^\\uFEFF/u, \"\"));\n } catch (error) {\n throw new CodexSecurityError(\n `Scanner JSON could not be parsed. ${errorMessage(error)}`,\n { cause: error },\n );\n }\n}\n\n/** Empty reference containers and property-bag metadata do not externalize data. */\nexport function hasSarifExternalPropertyReferences(value: unknown): boolean {\n if (value == null) return false;\n return Object.entries(\n record(value, \"SARIF external property references\"),\n ).some(\n ([key, references]) =>\n key !== \"properties\" &&\n (!Array.isArray(references) || references.length > 0),\n );\n}\n\nconst sarifArtifactLocationFields = new Set([\n \"artifactLocation\",\n \"analysisTarget\",\n \"executableLocation\",\n \"workingDirectory\",\n \"stdin\",\n \"stdout\",\n \"stderr\",\n \"stdoutStderr\",\n \"mappedTo\",\n \"displayBase\",\n]);\n\n/** Keep original artifact indexes; omit only inventory unrelated to this finding. */\nexport function sarifRunContextForResult(\n runContext: Record<string, unknown>,\n ...selectedEvidence: unknown[]\n): Record<string, unknown> {\n const { artifacts, ...context } = runContext;\n if (!Array.isArray(artifacts) || artifacts.length === 0) return runContext;\n const locations: Record<string, unknown>[] = [];\n let hasArtifactLink = false;\n function visit(value: unknown): void {\n if (typeof value === \"string\") {\n // SARIF message links can refer to an artifact without an artifactLocation.\n if (/sarif:/iu.test(value)) hasArtifactLink = true;\n } else if (Array.isArray(value)) value.forEach(visit);\n else if (isRecord(value))\n for (const [key, child] of Object.entries(value)) {\n if (key === \"properties\") continue;\n if (sarifArtifactLocationFields.has(key) && isRecord(child))\n locations.push(child);\n if (\n [\"locations\", \"responseFiles\", \"analysisToolLogFiles\"].includes(\n key,\n ) &&\n Array.isArray(child)\n )\n locations.push(...child.filter(isRecord));\n if (key === \"originalUriBaseIds\" && isRecord(child))\n locations.push(...Object.values(child).filter(isRecord));\n visit(child);\n }\n }\n visit([context, ...selectedEvidence]);\n if (hasArtifactLink) return runContext;\n const unresolvedUri = /[%:\\\\]|(?:^|\\/)\\.\\.?(?:\\/|$)/u;\n for (const location of locations) {\n if (typeof location[\"index\"] === \"number\" && location[\"index\"] >= 0)\n return runContext;\n if (typeof location[\"uri\"] !== \"string\") continue;\n for (const artifact of artifacts) {\n if (!isRecord(artifact) || !isRecord(artifact[\"location\"])) continue;\n const candidate = artifact[\"location\"];\n // Keep URI spellings that need resolution; evidence is never rewritten.\n if (\n location[\"uriBaseId\"] !== candidate[\"uriBaseId\"] ||\n unresolvedUri.test(location[\"uri\"]) ||\n (typeof candidate[\"uri\"] === \"string\" &&\n unresolvedUri.test(candidate[\"uri\"])) ||\n location[\"uri\"] === candidate[\"uri\"]\n )\n return runContext;\n }\n }\n return context;\n}\n\n/** Exclude every colliding record: choosing the first could overwrite another occurrence. */\nexport function normalizeRecords<T>(\n records: T[],\n normalize: (record: T, id: string) => ExternalFinding,\n identify: (record: T) => string,\n): ExternalFindings {\n const result: ExternalFindings = {\n read: records.length,\n findings: [],\n excluded: [],\n };\n const identified: { position: number; value: T; id: string }[] = [];\n const counts = new Map<string, number>();\n for (const [index, value] of records.entries()) {\n try {\n const id = identify(value);\n if (!id.trim() || id.includes(\"\\0\") || Buffer.byteLength(id) > 512)\n throw new Error(\n \"Source finding ID must contain 1–512 UTF-8 bytes and no NUL characters.\",\n );\n identified.push({ position: index + 1, value, id });\n counts.set(id, (counts.get(id) ?? 0) + 1);\n } catch (error) {\n result.excluded.push({\n position: index + 1,\n source_finding_id: null,\n reason: errorMessage(error),\n });\n }\n }\n for (const { position, value, id } of identified) {\n if (counts.get(id)! > 1) {\n result.excluded.push({\n position,\n source_finding_id: id,\n reason:\n \"Ambiguous duplicate source identity; select one complete finding or separate source projects.\",\n });\n continue;\n }\n try {\n const finding = normalize(value, id);\n if (finding.source_finding_id !== id)\n throw new Error(\"Finding identity changed during normalization.\");\n result.findings.push(finding);\n } catch (error) {\n result.excluded.push({\n position,\n source_finding_id: id,\n reason: errorMessage(error),\n });\n }\n }\n result.excluded.sort((a, b) => a.position - b.position);\n return result;\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function securityPolicyUnifiedDiff(before: string, after: string, fromfile: string, tofile: string, signal?: AbortSignal): Promise<string>;
2
+ //# sourceMappingURL=security-policy-diff.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"security-policy-diff.d.ts","sourceRoot":"","sources":["../src/security-policy-diff.ts"],"names":[],"mappings":"AAoMA,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,EACd,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,MAAM,CAAC,CAWjB"}
@@ -0,0 +1,197 @@
1
+ import { setImmediate } from "node:timers/promises";
2
+ function* lines(text) {
3
+ const result = [];
4
+ let start = 0;
5
+ for (let end = 0; end < text.length; end++) {
6
+ if (text.charCodeAt(end) === 10) {
7
+ result.push(text.slice(start, end + 1));
8
+ start = end + 1;
9
+ }
10
+ yield;
11
+ }
12
+ if (start < text.length)
13
+ result.push(text.slice(start));
14
+ return result;
15
+ }
16
+ // Match Python's SequenceMatcher(None, a, b), including its default autojunk
17
+ // heuristic. A different longest-common-subsequence algorithm changes the diff.
18
+ function* matchingBlocks(a, b) {
19
+ const positions = new Map();
20
+ for (let j = 0; j < b.length; j++) {
21
+ const line = b[j];
22
+ const indices = positions.get(line);
23
+ if (indices)
24
+ indices.push(j);
25
+ else
26
+ positions.set(line, [j]);
27
+ yield;
28
+ }
29
+ if (b.length >= 200) {
30
+ const threshold = Math.floor(b.length / 100) + 1;
31
+ for (const [line, indices] of positions) {
32
+ if (indices.length > threshold)
33
+ positions.delete(line);
34
+ yield;
35
+ }
36
+ }
37
+ const pending = [[0, a.length, 0, b.length]];
38
+ const matches = [];
39
+ while (pending.length) {
40
+ const range = pending.pop();
41
+ if (range.length === 3) {
42
+ const previous = matches.at(-1);
43
+ if (previous &&
44
+ previous[0] + previous[2] === range[0] &&
45
+ previous[1] + previous[2] === range[1]) {
46
+ previous[2] += range[2];
47
+ }
48
+ else {
49
+ matches.push(range);
50
+ }
51
+ yield;
52
+ continue;
53
+ }
54
+ const [alo, ahi, blo, bhi] = range;
55
+ let bestA = alo;
56
+ let bestB = blo;
57
+ let size = 0;
58
+ let lengths = new Map();
59
+ for (let i = alo; i < ahi; i++) {
60
+ const next = new Map();
61
+ for (const j of positions.get(a[i]) ?? []) {
62
+ yield;
63
+ if (j < blo)
64
+ continue;
65
+ if (j >= bhi)
66
+ break;
67
+ const length = (lengths.get(j - 1) ?? 0) + 1;
68
+ next.set(j, length);
69
+ if (length > size) {
70
+ bestA = i - length + 1;
71
+ bestB = j - length + 1;
72
+ size = length;
73
+ }
74
+ }
75
+ lengths = next;
76
+ yield;
77
+ }
78
+ // Popular lines may extend a match, even though they cannot anchor one.
79
+ while (bestA > alo && bestB > blo && a[bestA - 1] === b[bestB - 1]) {
80
+ bestA--;
81
+ bestB--;
82
+ size++;
83
+ yield;
84
+ }
85
+ while (bestA + size < ahi &&
86
+ bestB + size < bhi &&
87
+ a[bestA + size] === b[bestB + size]) {
88
+ size++;
89
+ yield;
90
+ }
91
+ if (size) {
92
+ // Visit matches in order, avoiding a blocking sort of the result.
93
+ if (bestA + size < ahi && bestB + size < bhi) {
94
+ pending.push([bestA + size, ahi, bestB + size, bhi]);
95
+ }
96
+ pending.push([bestA, bestB, size]);
97
+ if (alo < bestA && blo < bestB) {
98
+ pending.push([alo, bestA, blo, bestB]);
99
+ }
100
+ }
101
+ yield;
102
+ }
103
+ matches.push([a.length, b.length, 0]);
104
+ return matches;
105
+ }
106
+ function formatRange(start, end) {
107
+ const length = end - start;
108
+ return length === 1
109
+ ? String(start + 1)
110
+ : `${length ? start + 1 : start},${length}`;
111
+ }
112
+ function* unifiedDiff(before, after, fromfile, tofile) {
113
+ const a = yield* lines(before);
114
+ const b = yield* lines(after);
115
+ const matches = yield* matchingBlocks(a, b);
116
+ const codes = [];
117
+ let i = 0;
118
+ let j = 0;
119
+ for (const [ai, bj, size] of matches) {
120
+ if (i < ai || j < bj)
121
+ codes.push([false, i, ai, j, bj]);
122
+ i = ai + size;
123
+ j = bj + size;
124
+ if (size)
125
+ codes.push([true, ai, i, bj, j]);
126
+ yield;
127
+ }
128
+ const first = codes[0];
129
+ const last = codes.at(-1);
130
+ if (first?.[0]) {
131
+ first[1] = Math.max(first[1], first[2] - 3);
132
+ first[3] = Math.max(first[3], first[4] - 3);
133
+ }
134
+ if (last?.[0]) {
135
+ last[2] = Math.min(last[2], last[1] + 3);
136
+ last[4] = Math.min(last[4], last[3] + 3);
137
+ }
138
+ const output = [];
139
+ function* emit(group) {
140
+ if (!group.length || (group.length === 1 && group[0][0]))
141
+ return;
142
+ if (!output.length)
143
+ output.push(`--- ${fromfile}\n+++ ${tofile}\n`);
144
+ const first = group[0];
145
+ const last = group.at(-1);
146
+ output.push(`@@ -${formatRange(first[1], last[2])} +${formatRange(first[3], last[4])} @@\n`);
147
+ for (const [equal, aStart, aEnd, bStart, bEnd] of group) {
148
+ for (let index = aStart; index < aEnd; index++) {
149
+ const line = a[index];
150
+ output.push((equal ? " " : "-") + line);
151
+ if (!line.endsWith("\n")) {
152
+ output.push("\n\\n");
153
+ }
154
+ yield;
155
+ }
156
+ if (!equal) {
157
+ for (let index = bStart; index < bEnd; index++) {
158
+ const line = b[index];
159
+ output.push("+" + line);
160
+ if (!line.endsWith("\n")) {
161
+ output.push("\n\\n");
162
+ }
163
+ yield;
164
+ }
165
+ }
166
+ yield;
167
+ }
168
+ }
169
+ let group = [];
170
+ for (const [equal, aStart, aEnd, bStart, bEnd] of codes) {
171
+ if (equal && aEnd - aStart > 6) {
172
+ group.push([true, aStart, aStart + 3, bStart, bStart + 3]);
173
+ yield* emit(group);
174
+ group = [[true, aEnd - 3, aEnd, bEnd - 3, bEnd]];
175
+ }
176
+ else {
177
+ group.push([equal, aStart, aEnd, bStart, bEnd]);
178
+ }
179
+ yield;
180
+ }
181
+ yield* emit(group);
182
+ return output.join("");
183
+ }
184
+ export async function securityPolicyUnifiedDiff(before, after, fromfile, tofile, signal) {
185
+ const work = unifiedDiff(before, after, fromfile, tofile);
186
+ for (;;) {
187
+ signal?.throwIfAborted();
188
+ // Bound synchronous work, including the quadratic inner matching loop.
189
+ for (let operation = 0; operation < 4096; operation++) {
190
+ const result = work.next();
191
+ if (result.done)
192
+ return result.value;
193
+ }
194
+ await setImmediate();
195
+ }
196
+ }
197
+ //# sourceMappingURL=security-policy-diff.js.map