@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,460 @@
1
+ import { CodexSecurityError } from "./errors.js";
2
+ import { repositoryUrlKey, validateExternalEvidence, } from "./external-import-contract.js";
3
+ import { parseJsonOrJsonl, readScannerText } from "./scanner-import.js";
4
+ import { readWizCsv, wizCsvFinding } from "./wiz-csv.js";
5
+ function object(value) {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value)
7
+ ? value
8
+ : undefined;
9
+ }
10
+ function text(value) {
11
+ return typeof value === "string" && value.trim() ? value : null;
12
+ }
13
+ function sourceFindingId(value) {
14
+ const id = text(value);
15
+ if (!id || id.includes("\0") || Buffer.byteLength(id) > 512)
16
+ throw new Error("Source finding id must contain 1–512 UTF-8 bytes and no NUL characters.");
17
+ return id;
18
+ }
19
+ /** Keep a Wiz vulnerability occurrence intact; advisory names are not identities. */
20
+ function wizFinding(record) {
21
+ if (record["detectionMethod"] === "EXTERNAL_NETWORK_SCAN")
22
+ throw new Error("Wiz external network findings are not supported by the package vulnerability mapping.");
23
+ const id = sourceFindingId(record["id"]);
24
+ const name = text(record["name"]);
25
+ const packageName = text(record["detailedName"]);
26
+ const version = text(record["version"]);
27
+ const severity = text(record["vendorSeverity"]) ?? text(record["severity"]);
28
+ const asset = object(record["vulnerableAsset"]);
29
+ const artifact = object(record["artifactType"]);
30
+ if (!name || !packageName || !text(asset?.["id"])) {
31
+ throw new Error("Expected a Wiz package vulnerability finding with name, detailedName, and vulnerableAsset.id. Other finding classes need a separate mapping.");
32
+ }
33
+ const assetType = text(asset?.["type"]);
34
+ const repositoryAsset = assetType === "REPOSITORY_BRANCH" ||
35
+ asset?.["nativeType"] === "github#repositoryBranch";
36
+ // Wiz repository reports prefix root-relative paths with '/'. Workload paths
37
+ // are not source locations and must remain only in the original evidence.
38
+ const locationPath = text(record["locationPath"]);
39
+ const repositoryPath = repositoryAsset && locationPath ? locationPath.replace(/^\/+/, "") : null;
40
+ const digest = text(asset?.["imageDigest"]) ??
41
+ text(record["imageDigest"]) ??
42
+ (assetType === null ||
43
+ assetType === "CONTAINER_IMAGE" ||
44
+ assetType === "CONTAINER"
45
+ ? (text(asset?.["imageId"]) ??
46
+ text(asset?.["containerImageId"]) ??
47
+ text(asset?.["ImageExternalId"]))
48
+ : null);
49
+ // lastDetectedAt is not proof that the entire vendor record was updated.
50
+ const evidence = {
51
+ title: text(record["title"]) ??
52
+ [packageName, version, name].filter(Boolean).join(" "),
53
+ description: text(record["description"]),
54
+ severity: severity?.toLowerCase(),
55
+ url: text(record["portalUrl"]),
56
+ advisory_ids: [text(record["vulnerabilityExternalId"]) ?? name],
57
+ packages: [
58
+ {
59
+ name: packageName,
60
+ ecosystem: text(record["packageManager"]) ??
61
+ text(artifact?.["osPackageManager"]) ??
62
+ text(artifact?.["codeLibraryLanguage"]) ??
63
+ text(record["codeLibraryLanguage"]),
64
+ installed_version: version,
65
+ manifest_path: repositoryPath,
66
+ fixed_versions: text(record["fixedVersion"])
67
+ ? [record["fixedVersion"]]
68
+ : [],
69
+ },
70
+ ],
71
+ locations: repositoryPath ? [{ path: repositoryPath }] : [],
72
+ branch: null,
73
+ code_revision: null,
74
+ source_scan_id: null,
75
+ image_digests: digest ? [digest] : [],
76
+ source_updated_at: updatedAt(record["updatedAt"], "updatedAt"),
77
+ source_data: record,
78
+ };
79
+ return {
80
+ source_finding_id: id,
81
+ evidence: validateExternalEvidence(evidence),
82
+ };
83
+ }
84
+ // Wiz's documented inventory platform establishes custom GitHub host semantics.
85
+ // Keep this context separate from the repository metadata published as evidence.
86
+ function inventoryRepositoryUrlKey(value, platform) {
87
+ const key = repositoryUrlKey(value);
88
+ return platform === "GITHUB" ? key.toLowerCase() : key;
89
+ }
90
+ function sourceRepository(repository, repositories) {
91
+ const id = text(repository?.["id"]);
92
+ const inventory = id ? repositories.get(id) : undefined;
93
+ const suppliedUrl = text(repository?.["url"]);
94
+ if (suppliedUrl &&
95
+ inventory &&
96
+ inventoryRepositoryUrlKey(suppliedUrl, inventory.platform) !==
97
+ inventoryRepositoryUrlKey(inventory.url, inventory.platform))
98
+ throw new Error("The finding and repository inventory have conflicting repository URLs.");
99
+ const url = suppliedUrl ?? inventory?.url;
100
+ if (!url)
101
+ throw new Error("A verified source repository URL is required. Include repository.url or the matching repository.id and repository.url from data.versionControlResources.nodes; names and Wiz IDs are not Cloud repository IDs.");
102
+ return {
103
+ id,
104
+ name: text(repository?.["name"]) ?? inventory?.name ?? null,
105
+ url,
106
+ };
107
+ }
108
+ function sourceBranch(branch, repository, legacy = false) {
109
+ const name = text(branch?.["name"]);
110
+ if (!name)
111
+ return null;
112
+ // Repository names and URL paths can both be literal branch prefixes. Keep
113
+ // the old mapping only for an already approved publication checkpoint.
114
+ if (!legacy)
115
+ return name;
116
+ const qualifiers = repository.name ? [repository.name] : [];
117
+ // Include the URL qualifier before selecting the longest repository prefix.
118
+ // Keep URL normalization and the branch suffix's original case and slashes.
119
+ const repositoryKey = repositoryUrlKey(repository.url).toLowerCase();
120
+ const url = /^(https?:\/\/[^/?#]+)\/([^?#]+)$/iu.exec(repositoryKey);
121
+ if (url) {
122
+ const prefixParts = url[2].split("/").length;
123
+ const parts = name.split("/");
124
+ const qualifier = parts.slice(0, prefixParts).join("/");
125
+ if (parts.length > prefixParts &&
126
+ repositoryUrlKey(url[1] + "/" + qualifier).toLowerCase() === repositoryKey)
127
+ qualifiers.push(qualifier);
128
+ }
129
+ for (const qualifier of qualifiers.sort((left, right) => right.length - left.length)) {
130
+ const prefix = qualifier + "/";
131
+ if (name.toLowerCase().startsWith(prefix.toLowerCase()))
132
+ return name.slice(prefix.length) || null;
133
+ }
134
+ return url || repository.name ? name : null;
135
+ }
136
+ function updatedAt(value, field) {
137
+ const timestamp = text(value);
138
+ if (!timestamp)
139
+ return null;
140
+ const seconds = Date.parse(timestamp) / 1000;
141
+ if (!Number.isFinite(seconds) || seconds < 0)
142
+ throw new Error(`Wiz ${field} is not a valid timestamp.`);
143
+ return Math.floor(seconds);
144
+ }
145
+ // Empty code and configuration strings are meaningful vendor evidence.
146
+ function content(value) {
147
+ return typeof value === "string" ? value : null;
148
+ }
149
+ /** Map only explicitly identified repository finding collections. */
150
+ function repositoryFinding(kind, record, repositories, legacy = false) {
151
+ const id = sourceFindingId(record["id"]);
152
+ const resource = object(record["resource"]);
153
+ if (kind === "secret" && resource?.["type"] !== "REPOSITORY_BRANCH")
154
+ throw new Error("Only repository-branch secret findings can be published to a repository. Workload secrets require a resource-scoped import and are not supported.");
155
+ const suppliedRepository = kind === "secret"
156
+ ? object(object(resource?.["typedProperties"])?.["repository"])
157
+ : object(record["repository"]);
158
+ const repository = sourceRepository(suppliedRepository, repositories);
159
+ const branch = kind === "secret"
160
+ ? resource
161
+ : object(record[kind === "sast" ? "repositoryBranch" : "branch"]);
162
+ const rule = object(record["rule"]);
163
+ const path = text(record[kind === "secret" ? "path" : "filePath"]);
164
+ const line = record[kind === "secret" ? "lineNumber" : "startLine"];
165
+ const details = {
166
+ kind,
167
+ repository,
168
+ source_status: text(record["status"]),
169
+ scanner_origin: kind === "sast" ? text(record["origin"]) : null,
170
+ scanner_verdict: kind === "sast" ? text(object(record["aiAnalysis"])?.["verdict"]) : null,
171
+ rule: rule
172
+ ? {
173
+ id: text(rule["id"]),
174
+ short_id: text(rule["shortId"]),
175
+ name: text(rule["name"]),
176
+ }
177
+ : null,
178
+ weakness_ids: kind === "sast" && Array.isArray(record["weaknesses"])
179
+ ? record["weaknesses"].map((weakness) => object(weakness)?.["id"])
180
+ : [],
181
+ remediation_instructions: text(record["remediationInstructions"]) ??
182
+ text(rule?.["remediationInstructions"]),
183
+ code: path && kind !== "secret"
184
+ ? {
185
+ end_line: record["endLine"] ?? null,
186
+ snippet: content(record[kind === "sast" ? "snippet" : "matchContent"]),
187
+ }
188
+ : null,
189
+ secret: kind === "secret"
190
+ ? {
191
+ type: text(record["type"]),
192
+ confidence: text(record["confidence"]),
193
+ validation_status: text(record["validationStatus"]),
194
+ is_encrypted: record["isEncrypted"] ?? null,
195
+ is_managed: record["isManaged"] ?? null,
196
+ introduced_commit: text(object(record["vcsDetails"])?.["initialCommitHash"]),
197
+ }
198
+ : null,
199
+ configuration: kind === "iac"
200
+ ? {
201
+ platform: text(record["platform"]),
202
+ cloud_platform: text(record["cloudPlatform"]),
203
+ expected: content(record["expectedContent"]),
204
+ actual: content(record["foundContent"]),
205
+ }
206
+ : null,
207
+ file_url: text(record["fileURL"]),
208
+ };
209
+ return {
210
+ // Existing package occurrence IDs remain unchanged. New families cannot
211
+ // collide with one another when the same tenant source key is used.
212
+ source_finding_id: sourceFindingId(`${kind}:${id}`),
213
+ evidence: validateExternalEvidence({
214
+ title: text(record["name"]) ?? text(rule?.["name"]),
215
+ severity: text(record["severity"])?.toLowerCase(),
216
+ description: text(record["description"]) ?? text(rule?.["description"]),
217
+ url: text(record["wizUrl"]) ?? text(record["portalUrl"]),
218
+ locations: path ? [{ path, line: line ?? null }] : [],
219
+ branch: sourceBranch(branch, repository, legacy),
220
+ code_revision: null,
221
+ source_scan_id: null,
222
+ source_updated_at: kind === "secret"
223
+ ? updatedAt(record["lastUpdatedAt"], "lastUpdatedAt")
224
+ : kind === "iac"
225
+ ? updatedAt(record["updatedAt"], "updatedAt")
226
+ : null,
227
+ source_data: record,
228
+ details,
229
+ }),
230
+ };
231
+ }
232
+ function records(payload) {
233
+ const repositories = new Map();
234
+ const legacyRepositories = new Map();
235
+ if (Array.isArray(payload))
236
+ return { records: payload.map((value) => ({ value })), repositories };
237
+ const envelope = object(payload);
238
+ if (!envelope)
239
+ throw new Error("Expected finding objects or a named Wiz finding collection.");
240
+ if (object(envelope["scannersRunStatuses"]) &&
241
+ object(envelope["codeAnalyzerDetails"]))
242
+ throw new Error("This is a Wiz Code & Build Scan event, which contains scan metadata rather than vulnerability records. In Vulnerability Findings, filter the repository and selection, then choose Save as → Report with JSON format and Detailed columns. Download that report instead of Raw Event.");
243
+ if (Array.isArray(envelope["errors"]) && envelope["errors"].length > 0)
244
+ throw new Error("Wiz returned GraphQL errors. Resolve them before publishing this response.");
245
+ if (envelope["source_finding_id"] !== undefined ||
246
+ envelope["id"] !== undefined)
247
+ return { records: [{ value: envelope }], repositories };
248
+ const data = object(envelope["data"]) ?? envelope;
249
+ const inventory = object(data["versionControlResources"]);
250
+ if (object(inventory?.["pageInfo"])?.["hasNextPage"] === true)
251
+ throw new Error("Wiz repository inventory has another page. Finish the selected inventory before publishing.");
252
+ if (Array.isArray(inventory?.["nodes"])) {
253
+ const entries = inventory["nodes"].flatMap((entry) => {
254
+ const node = object(entry);
255
+ const repository = object(node?.["repository"]);
256
+ const id = text(repository?.["id"]);
257
+ const url = text(repository?.["url"]);
258
+ return id && url
259
+ ? [
260
+ {
261
+ id,
262
+ name: text(repository?.["name"]),
263
+ url,
264
+ platform: text(node?.["platform"]),
265
+ },
266
+ ]
267
+ : [];
268
+ });
269
+ // Resolve provider hints before comparing URLs, so duplicate row order cannot
270
+ // discard a known platform or reject a case variant before its GITHUB hint.
271
+ for (const entry of entries) {
272
+ const previous = repositories.get(entry.id);
273
+ if (previous?.platform &&
274
+ entry.platform &&
275
+ previous.platform !== entry.platform)
276
+ throw new Error(`Repository inventory contains conflicting platforms for ${JSON.stringify(entry.id)}.`);
277
+ repositories.set(entry.id, {
278
+ ...entry,
279
+ // Equivalent inventory aliases must produce the same evidence when the
280
+ // export reorders its rows. Keep a stable supplied URL and nonempty name.
281
+ url: previous && previous.url < entry.url ? previous.url : entry.url,
282
+ name: previous?.name && (!entry.name || previous.name < entry.name)
283
+ ? previous.name
284
+ : entry.name,
285
+ platform: entry.platform ?? previous?.platform ?? null,
286
+ });
287
+ legacyRepositories.set(entry.id, {
288
+ ...entry,
289
+ platform: entry.platform ?? previous?.platform ?? null,
290
+ });
291
+ }
292
+ for (const entry of entries) {
293
+ const resolved = repositories.get(entry.id);
294
+ if (inventoryRepositoryUrlKey(entry.url, resolved.platform) !==
295
+ inventoryRepositoryUrlKey(resolved.url, resolved.platform))
296
+ throw new Error(`Repository inventory contains conflicting URLs for ${JSON.stringify(entry.id)}.`);
297
+ }
298
+ }
299
+ const collections = {
300
+ vulnerabilityFindings: "sca",
301
+ sastFindings: "sast",
302
+ secretInstances: "secret",
303
+ iacFindings: "iac",
304
+ configurationFindings: "cloud_configuration",
305
+ };
306
+ const selected = [];
307
+ let found = false;
308
+ for (const [root, kind] of Object.entries(collections)) {
309
+ const collection = object(data[root]);
310
+ if (!collection)
311
+ continue;
312
+ found = true;
313
+ if (!Array.isArray(collection["nodes"]))
314
+ throw new Error(`Wiz ${root}.nodes must be an array.`);
315
+ if (object(collection["pageInfo"])?.["hasNextPage"] === true)
316
+ throw new Error("Wiz response has another page. Complete the requested pages or save the explicitly selected records in their named collection before publishing.");
317
+ for (const value of collection["nodes"])
318
+ selected.push({ value, kind });
319
+ }
320
+ if (found)
321
+ return {
322
+ records: selected,
323
+ repositories,
324
+ legacyRepositories,
325
+ };
326
+ throw new Error("Unsupported Wiz export. Supply repository vulnerability CSV, vulnerability finding objects, named sastFindings/secretInstances/iacFindings collections, or normalized JSONL. Other CSV reports need an explicit normalized JSONL mapping.");
327
+ }
328
+ export async function readVendorFindings(path) {
329
+ return normalizeFindings(await readFindingInput(path));
330
+ }
331
+ /** @internal Preserve older inventory projections only for saved publication replay. */
332
+ export async function readVendorFindingsForPublication(path) {
333
+ const input = await readFindingInput(path);
334
+ const normalized = new WeakSet();
335
+ const current = normalizeFindings(input, normalized);
336
+ const legacy = normalizeFindings({ ...input, repositories: input.legacyRepositories ?? input.repositories }, normalized, true);
337
+ const identity = (parsed) => parsed.findings.map((finding) => {
338
+ if (normalized.has(finding))
339
+ return finding;
340
+ const repository = finding.evidence.details?.repository;
341
+ return {
342
+ source_finding_id: finding.source_finding_id,
343
+ evidence: {
344
+ // Raw vendor records retain every original branch/ref and source field.
345
+ // Inventory display aliases must not change an outstanding request's identity.
346
+ source_data: finding.evidence.source_data,
347
+ repository: repository
348
+ ? {
349
+ id: repository.id,
350
+ // Publication targets use Cloud's GitHub URL semantics. Input
351
+ // joins above still require provenance for custom-host folding.
352
+ url: repositoryUrlKey(repository.url).toLowerCase(),
353
+ }
354
+ : null,
355
+ },
356
+ };
357
+ });
358
+ return {
359
+ current,
360
+ legacy,
361
+ currentIdentity: identity(current),
362
+ legacyIdentity: identity(legacy),
363
+ sourceRepositories: current.findings.flatMap(({ evidence }) => {
364
+ const repository = evidence.details?.repository;
365
+ const inventory = input.repositories.get(repository?.id ?? "");
366
+ // Forward provenance only for selected findings that match the inventory.
367
+ // Use the emitted spelling so typed evidence and reader hints share it.
368
+ return repository &&
369
+ inventory?.platform === "GITHUB" &&
370
+ inventoryRepositoryUrlKey(repository.url, inventory.platform) ===
371
+ inventoryRepositoryUrlKey(inventory.url, inventory.platform)
372
+ ? [{ url: repository.url, platform: "github" }]
373
+ : [];
374
+ }),
375
+ };
376
+ }
377
+ async function readFindingInput(path) {
378
+ try {
379
+ const contents = await readScannerText(path);
380
+ let payload;
381
+ try {
382
+ payload = JSON.parse(contents);
383
+ }
384
+ catch {
385
+ const csv = readWizCsv(contents);
386
+ if (csv)
387
+ return {
388
+ records: csv.map((value) => ({ value, kind: "sca_csv" })),
389
+ repositories: new Map(),
390
+ };
391
+ payload = parseJsonOrJsonl(contents);
392
+ }
393
+ return records(payload);
394
+ }
395
+ catch (cause) {
396
+ throw new CodexSecurityError(`Could not read vendor findings as UTF-8 JSON, JSONL, or Wiz CSV: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
397
+ }
398
+ }
399
+ function normalizeFindings(input, normalized, legacy = false) {
400
+ const result = {
401
+ read: input.records.length,
402
+ findings: [],
403
+ excluded: [],
404
+ };
405
+ const identities = new Set();
406
+ for (const [index, item] of input.records.entries()) {
407
+ const record = object(item.value);
408
+ try {
409
+ if (!record)
410
+ throw new Error("Finding must be an object.");
411
+ let finding;
412
+ if (item.kind === "sca_csv") {
413
+ finding = wizCsvFinding(record, sourceFindingId(record["ID"]));
414
+ }
415
+ else if ("source_finding_id" in record) {
416
+ if (Object.keys(record).some((key) => !["source_finding_id", "evidence"].includes(key))) {
417
+ throw new Error("Normalized input permits only source_finding_id and evidence.");
418
+ }
419
+ finding = {
420
+ source_finding_id: sourceFindingId(record["source_finding_id"]),
421
+ evidence: validateExternalEvidence(record["evidence"]),
422
+ };
423
+ }
424
+ else if (item.kind === "cloud_configuration") {
425
+ throw new Error("Cloud configuration findings require a resource-scoped import and cannot be published to a repository.");
426
+ }
427
+ else if (item.kind && item.kind !== "sca") {
428
+ finding = repositoryFinding(item.kind, record, input.repositories, legacy);
429
+ }
430
+ else {
431
+ if (!item.kind &&
432
+ (object(record["repository"]) ||
433
+ object(record["repositoryBranch"]) ||
434
+ object(record["resource"])))
435
+ throw new Error("Raw SAST, secret, and IaC records require their named sastFindings, secretInstances, or iacFindings collection. Bare arrays do not identify the finding family; use normalized JSONL for an explicit mapping.");
436
+ finding = wizFinding(record);
437
+ }
438
+ if (identities.has(finding.source_finding_id)) {
439
+ throw new CodexSecurityError(`Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each vendor occurrence once.`);
440
+ }
441
+ identities.add(finding.source_finding_id);
442
+ result.findings.push(finding);
443
+ if (item.kind !== "sca_csv" && "source_finding_id" in record)
444
+ normalized?.add(finding);
445
+ }
446
+ catch (error) {
447
+ if (error instanceof CodexSecurityError)
448
+ throw error;
449
+ result.excluded.push({
450
+ position: index + 1,
451
+ source_finding_id: item.kind === "sca_csv"
452
+ ? text(record?.["ID"])
453
+ : (text(record?.["source_finding_id"]) ?? text(record?.["id"])),
454
+ reason: error instanceof Error ? error.message : String(error),
455
+ });
456
+ }
457
+ }
458
+ return result;
459
+ }
460
+ //# sourceMappingURL=wiz-findings.js.map
@@ -0,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CAAC,MAAM,CAAC,KAAK,CAAC;aAC/D,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { CodexSecurityError } from \"./errors.js\";\nimport {\n repositoryUrlKey,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport { parseJsonOrJsonl, readScannerText } from \"./scanner-import.js\";\nimport { readWizCsv, wizCsvFinding } from \"./wiz-csv.js\";\nimport type {\n ExternalFinding as VendorFinding,\n ExternalFindings as VendorFindings,\n ExternalSourceRepository,\n} from \"./external-findings.js\";\n\nexport type {\n ExternalFinding as VendorFinding,\n ExternalFindings as VendorFindings,\n} from \"./external-findings.js\";\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n}\n\nfunction text(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value : null;\n}\n\nfunction sourceFindingId(value: unknown): string {\n const id = text(value);\n if (!id || 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 return id;\n}\n\n/** Keep a Wiz vulnerability occurrence intact; advisory names are not identities. */\nfunction wizFinding(record: Record<string, unknown>): VendorFinding {\n if (record[\"detectionMethod\"] === \"EXTERNAL_NETWORK_SCAN\")\n throw new Error(\n \"Wiz external network findings are not supported by the package vulnerability mapping.\",\n );\n const id = sourceFindingId(record[\"id\"]);\n const name = text(record[\"name\"]);\n const packageName = text(record[\"detailedName\"]);\n const version = text(record[\"version\"]);\n const severity = text(record[\"vendorSeverity\"]) ?? text(record[\"severity\"]);\n const asset = object(record[\"vulnerableAsset\"]);\n const artifact = object(record[\"artifactType\"]);\n if (!name || !packageName || !text(asset?.[\"id\"])) {\n throw new Error(\n \"Expected a Wiz package vulnerability finding with name, detailedName, and vulnerableAsset.id. Other finding classes need a separate mapping.\",\n );\n }\n const assetType = text(asset?.[\"type\"]);\n const repositoryAsset =\n assetType === \"REPOSITORY_BRANCH\" ||\n asset?.[\"nativeType\"] === \"github#repositoryBranch\";\n // Wiz repository reports prefix root-relative paths with '/'. Workload paths\n // are not source locations and must remain only in the original evidence.\n const locationPath = text(record[\"locationPath\"]);\n const repositoryPath =\n repositoryAsset && locationPath ? locationPath.replace(/^\\/+/, \"\") : null;\n const digest =\n text(asset?.[\"imageDigest\"]) ??\n text(record[\"imageDigest\"]) ??\n (assetType === null ||\n assetType === \"CONTAINER_IMAGE\" ||\n assetType === \"CONTAINER\"\n ? (text(asset?.[\"imageId\"]) ??\n text(asset?.[\"containerImageId\"]) ??\n text(asset?.[\"ImageExternalId\"]))\n : null);\n // lastDetectedAt is not proof that the entire vendor record was updated.\n const evidence = {\n title:\n text(record[\"title\"]) ??\n [packageName, version, name].filter(Boolean).join(\" \"),\n description: text(record[\"description\"]),\n severity: severity?.toLowerCase(),\n url: text(record[\"portalUrl\"]),\n advisory_ids: [text(record[\"vulnerabilityExternalId\"]) ?? name],\n packages: [\n {\n name: packageName,\n ecosystem:\n text(record[\"packageManager\"]) ??\n text(artifact?.[\"osPackageManager\"]) ??\n text(artifact?.[\"codeLibraryLanguage\"]) ??\n text(record[\"codeLibraryLanguage\"]),\n installed_version: version,\n manifest_path: repositoryPath,\n fixed_versions: text(record[\"fixedVersion\"])\n ? [record[\"fixedVersion\"]]\n : [],\n },\n ],\n locations: repositoryPath ? [{ path: repositoryPath }] : [],\n branch: null,\n code_revision: null,\n source_scan_id: null,\n image_digests: digest ? [digest] : [],\n source_updated_at: updatedAt(record[\"updatedAt\"], \"updatedAt\"),\n source_data: record,\n };\n return {\n source_finding_id: id,\n evidence: validateExternalEvidence(evidence),\n };\n}\n\ntype RepositoryFindingKind = \"sast\" | \"secret\" | \"iac\";\n\ntype InputRecord = {\n value: unknown;\n kind?: \"sca\" | \"sca_csv\" | RepositoryFindingKind | \"cloud_configuration\";\n};\n\ntype RepositoryMetadata = {\n id: string | null;\n name: string | null;\n url: string;\n};\n\ntype FindingInput = {\n records: InputRecord[];\n repositories: Map<string, RepositoryMetadata & { platform: string | null }>;\n legacyRepositories?: FindingInput[\"repositories\"];\n};\n\n// Wiz's documented inventory platform establishes custom GitHub host semantics.\n// Keep this context separate from the repository metadata published as evidence.\nfunction inventoryRepositoryUrlKey(\n value: string,\n platform: string | null | undefined,\n): string {\n const key = repositoryUrlKey(value);\n return platform === \"GITHUB\" ? key.toLowerCase() : key;\n}\n\nfunction sourceRepository(\n repository: Record<string, unknown> | undefined,\n repositories: FindingInput[\"repositories\"],\n): RepositoryMetadata {\n const id = text(repository?.[\"id\"]);\n const inventory = id ? repositories.get(id) : undefined;\n const suppliedUrl = text(repository?.[\"url\"]);\n if (\n suppliedUrl &&\n inventory &&\n inventoryRepositoryUrlKey(suppliedUrl, inventory.platform) !==\n inventoryRepositoryUrlKey(inventory.url, inventory.platform)\n )\n throw new Error(\n \"The finding and repository inventory have conflicting repository URLs.\",\n );\n const url = suppliedUrl ?? inventory?.url;\n if (!url)\n throw new Error(\n \"A verified source repository URL is required. Include repository.url or the matching repository.id and repository.url from data.versionControlResources.nodes; names and Wiz IDs are not Cloud repository IDs.\",\n );\n return {\n id,\n name: text(repository?.[\"name\"]) ?? inventory?.name ?? null,\n url,\n };\n}\n\nfunction sourceBranch(\n branch: Record<string, unknown> | undefined,\n repository: RepositoryMetadata,\n legacy = false,\n): string | null {\n const name = text(branch?.[\"name\"]);\n if (!name) return null;\n // Repository names and URL paths can both be literal branch prefixes. Keep\n // the old mapping only for an already approved publication checkpoint.\n if (!legacy) return name;\n const qualifiers = repository.name ? [repository.name] : [];\n\n // Include the URL qualifier before selecting the longest repository prefix.\n // Keep URL normalization and the branch suffix's original case and slashes.\n const repositoryKey = repositoryUrlKey(repository.url).toLowerCase();\n const url = /^(https?:\\/\\/[^/?#]+)\\/([^?#]+)$/iu.exec(repositoryKey);\n if (url) {\n const prefixParts = url[2]!.split(\"/\").length;\n const parts = name.split(\"/\");\n const qualifier = parts.slice(0, prefixParts).join(\"/\");\n if (\n parts.length > prefixParts &&\n repositoryUrlKey(url[1] + \"/\" + qualifier).toLowerCase() === repositoryKey\n )\n qualifiers.push(qualifier);\n }\n for (const qualifier of qualifiers.sort(\n (left, right) => right.length - left.length,\n )) {\n const prefix = qualifier + \"/\";\n if (name.toLowerCase().startsWith(prefix.toLowerCase()))\n return name.slice(prefix.length) || null;\n }\n return url || repository.name ? name : null;\n}\n\nfunction updatedAt(value: unknown, field: string): number | null {\n const timestamp = text(value);\n if (!timestamp) return null;\n const seconds = Date.parse(timestamp) / 1000;\n if (!Number.isFinite(seconds) || seconds < 0)\n throw new Error(`Wiz ${field} is not a valid timestamp.`);\n return Math.floor(seconds);\n}\n\n// Empty code and configuration strings are meaningful vendor evidence.\nfunction content(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\n/** Map only explicitly identified repository finding collections. */\nfunction repositoryFinding(\n kind: RepositoryFindingKind,\n record: Record<string, unknown>,\n repositories: FindingInput[\"repositories\"],\n legacy = false,\n): VendorFinding {\n const id = sourceFindingId(record[\"id\"]);\n const resource = object(record[\"resource\"]);\n if (kind === \"secret\" && resource?.[\"type\"] !== \"REPOSITORY_BRANCH\")\n throw new Error(\n \"Only repository-branch secret findings can be published to a repository. Workload secrets require a resource-scoped import and are not supported.\",\n );\n const suppliedRepository =\n kind === \"secret\"\n ? object(object(resource?.[\"typedProperties\"])?.[\"repository\"])\n : object(record[\"repository\"]);\n const repository = sourceRepository(suppliedRepository, repositories);\n const branch =\n kind === \"secret\"\n ? resource\n : object(record[kind === \"sast\" ? \"repositoryBranch\" : \"branch\"]);\n const rule = object(record[\"rule\"]);\n const path = text(record[kind === \"secret\" ? \"path\" : \"filePath\"]);\n const line = record[kind === \"secret\" ? \"lineNumber\" : \"startLine\"];\n const details = {\n kind,\n repository,\n source_status: text(record[\"status\"]),\n scanner_origin: kind === \"sast\" ? text(record[\"origin\"]) : null,\n scanner_verdict:\n kind === \"sast\" ? text(object(record[\"aiAnalysis\"])?.[\"verdict\"]) : null,\n rule: rule\n ? {\n id: text(rule[\"id\"]),\n short_id: text(rule[\"shortId\"]),\n name: text(rule[\"name\"]),\n }\n : null,\n weakness_ids:\n kind === \"sast\" && Array.isArray(record[\"weaknesses\"])\n ? record[\"weaknesses\"].map((weakness) => object(weakness)?.[\"id\"])\n : [],\n remediation_instructions:\n text(record[\"remediationInstructions\"]) ??\n text(rule?.[\"remediationInstructions\"]),\n code:\n path && kind !== \"secret\"\n ? {\n end_line: record[\"endLine\"] ?? null,\n snippet: content(\n record[kind === \"sast\" ? \"snippet\" : \"matchContent\"],\n ),\n }\n : null,\n secret:\n kind === \"secret\"\n ? {\n type: text(record[\"type\"]),\n confidence: text(record[\"confidence\"]),\n validation_status: text(record[\"validationStatus\"]),\n is_encrypted: record[\"isEncrypted\"] ?? null,\n is_managed: record[\"isManaged\"] ?? null,\n introduced_commit: text(\n object(record[\"vcsDetails\"])?.[\"initialCommitHash\"],\n ),\n }\n : null,\n configuration:\n kind === \"iac\"\n ? {\n platform: text(record[\"platform\"]),\n cloud_platform: text(record[\"cloudPlatform\"]),\n expected: content(record[\"expectedContent\"]),\n actual: content(record[\"foundContent\"]),\n }\n : null,\n file_url: text(record[\"fileURL\"]),\n };\n return {\n // Existing package occurrence IDs remain unchanged. New families cannot\n // collide with one another when the same tenant source key is used.\n source_finding_id: sourceFindingId(`${kind}:${id}`),\n evidence: validateExternalEvidence({\n title: text(record[\"name\"]) ?? text(rule?.[\"name\"]),\n severity: text(record[\"severity\"])?.toLowerCase(),\n description: text(record[\"description\"]) ?? text(rule?.[\"description\"]),\n url: text(record[\"wizUrl\"]) ?? text(record[\"portalUrl\"]),\n locations: path ? [{ path, line: line ?? null }] : [],\n branch: sourceBranch(branch, repository, legacy),\n code_revision: null,\n source_scan_id: null,\n source_updated_at:\n kind === \"secret\"\n ? updatedAt(record[\"lastUpdatedAt\"], \"lastUpdatedAt\")\n : kind === \"iac\"\n ? updatedAt(record[\"updatedAt\"], \"updatedAt\")\n : null,\n source_data: record,\n details,\n }),\n };\n}\n\nfunction records(payload: unknown): FindingInput {\n const repositories: FindingInput[\"repositories\"] = new Map();\n const legacyRepositories: FindingInput[\"repositories\"] = new Map();\n if (Array.isArray(payload))\n return { records: payload.map((value) => ({ value })), repositories };\n const envelope = object(payload);\n if (!envelope)\n throw new Error(\n \"Expected finding objects or a named Wiz finding collection.\",\n );\n if (\n object(envelope[\"scannersRunStatuses\"]) &&\n object(envelope[\"codeAnalyzerDetails\"])\n )\n throw new Error(\n \"This is a Wiz Code & Build Scan event, which contains scan metadata rather than vulnerability records. In Vulnerability Findings, filter the repository and selection, then choose Save as → Report with JSON format and Detailed columns. Download that report instead of Raw Event.\",\n );\n if (Array.isArray(envelope[\"errors\"]) && envelope[\"errors\"].length > 0)\n throw new Error(\n \"Wiz returned GraphQL errors. Resolve them before publishing this response.\",\n );\n if (\n envelope[\"source_finding_id\"] !== undefined ||\n envelope[\"id\"] !== undefined\n )\n return { records: [{ value: envelope }], repositories };\n const data = object(envelope[\"data\"]) ?? envelope;\n const inventory = object(data[\"versionControlResources\"]);\n if (object(inventory?.[\"pageInfo\"])?.[\"hasNextPage\"] === true)\n throw new Error(\n \"Wiz repository inventory has another page. Finish the selected inventory before publishing.\",\n );\n if (Array.isArray(inventory?.[\"nodes\"])) {\n const entries = inventory[\"nodes\"].flatMap((entry) => {\n const node = object(entry);\n const repository = object(node?.[\"repository\"]);\n const id = text(repository?.[\"id\"]);\n const url = text(repository?.[\"url\"]);\n return id && url\n ? [\n {\n id,\n name: text(repository?.[\"name\"]),\n url,\n platform: text(node?.[\"platform\"]),\n },\n ]\n : [];\n });\n // Resolve provider hints before comparing URLs, so duplicate row order cannot\n // discard a known platform or reject a case variant before its GITHUB hint.\n for (const entry of entries) {\n const previous = repositories.get(entry.id);\n if (\n previous?.platform &&\n entry.platform &&\n previous.platform !== entry.platform\n )\n throw new Error(\n `Repository inventory contains conflicting platforms for ${JSON.stringify(entry.id)}.`,\n );\n repositories.set(entry.id, {\n ...entry,\n // Equivalent inventory aliases must produce the same evidence when the\n // export reorders its rows. Keep a stable supplied URL and nonempty name.\n url: previous && previous.url < entry.url ? previous.url : entry.url,\n name:\n previous?.name && (!entry.name || previous.name < entry.name)\n ? previous.name\n : entry.name,\n platform: entry.platform ?? previous?.platform ?? null,\n });\n legacyRepositories.set(entry.id, {\n ...entry,\n platform: entry.platform ?? previous?.platform ?? null,\n });\n }\n for (const entry of entries) {\n const resolved = repositories.get(entry.id)!;\n if (\n inventoryRepositoryUrlKey(entry.url, resolved.platform) !==\n inventoryRepositoryUrlKey(resolved.url, resolved.platform)\n )\n throw new Error(\n `Repository inventory contains conflicting URLs for ${JSON.stringify(entry.id)}.`,\n );\n }\n }\n const collections = {\n vulnerabilityFindings: \"sca\",\n sastFindings: \"sast\",\n secretInstances: \"secret\",\n iacFindings: \"iac\",\n configurationFindings: \"cloud_configuration\",\n } as const;\n const selected: InputRecord[] = [];\n let found = false;\n for (const [root, kind] of Object.entries(collections)) {\n const collection = object(data[root]);\n if (!collection) continue;\n found = true;\n if (!Array.isArray(collection[\"nodes\"]))\n throw new Error(`Wiz ${root}.nodes must be an array.`);\n if (object(collection[\"pageInfo\"])?.[\"hasNextPage\"] === true)\n throw new Error(\n \"Wiz response has another page. Complete the requested pages or save the explicitly selected records in their named collection before publishing.\",\n );\n for (const value of collection[\"nodes\"]) selected.push({ value, kind });\n }\n if (found)\n return {\n records: selected,\n repositories,\n legacyRepositories,\n };\n throw new Error(\n \"Unsupported Wiz export. Supply repository vulnerability CSV, vulnerability finding objects, named sastFindings/secretInstances/iacFindings collections, or normalized JSONL. Other CSV reports need an explicit normalized JSONL mapping.\",\n );\n}\n\nexport async function readVendorFindings(\n path: string,\n): Promise<VendorFindings> {\n return normalizeFindings(await readFindingInput(path));\n}\n\n/** @internal Preserve older inventory projections only for saved publication replay. */\nexport async function readVendorFindingsForPublication(path: string): Promise<{\n current: VendorFindings;\n legacy: VendorFindings;\n currentIdentity: unknown[];\n legacyIdentity: unknown[];\n sourceRepositories: ExternalSourceRepository[];\n}> {\n const input = await readFindingInput(path);\n const normalized = new WeakSet<VendorFinding>();\n const current = normalizeFindings(input, normalized);\n const legacy = normalizeFindings(\n { ...input, repositories: input.legacyRepositories ?? input.repositories },\n normalized,\n true,\n );\n const identity = (parsed: VendorFindings) =>\n parsed.findings.map((finding) => {\n if (normalized.has(finding)) return finding;\n const repository = finding.evidence.details?.repository;\n return {\n source_finding_id: finding.source_finding_id,\n evidence: {\n // Raw vendor records retain every original branch/ref and source field.\n // Inventory display aliases must not change an outstanding request's identity.\n source_data: finding.evidence.source_data,\n repository: repository\n ? {\n id: repository.id,\n // Publication targets use Cloud's GitHub URL semantics. Input\n // joins above still require provenance for custom-host folding.\n url: repositoryUrlKey(repository.url).toLowerCase(),\n }\n : null,\n },\n };\n });\n return {\n current,\n legacy,\n currentIdentity: identity(current),\n legacyIdentity: identity(legacy),\n sourceRepositories: current.findings.flatMap(({ evidence }) => {\n const repository = evidence.details?.repository;\n const inventory = input.repositories.get(repository?.id ?? \"\");\n // Forward provenance only for selected findings that match the inventory.\n // Use the emitted spelling so typed evidence and reader hints share it.\n return repository &&\n inventory?.platform === \"GITHUB\" &&\n inventoryRepositoryUrlKey(repository.url, inventory.platform) ===\n inventoryRepositoryUrlKey(inventory.url, inventory.platform)\n ? [{ url: repository.url, platform: \"github\" as const }]\n : [];\n }),\n };\n}\n\nasync function readFindingInput(path: string): Promise<FindingInput> {\n try {\n const contents = await readScannerText(path);\n let payload: unknown;\n try {\n payload = JSON.parse(contents);\n } catch {\n const csv = readWizCsv(contents);\n if (csv)\n return {\n records: csv.map((value) => ({ value, kind: \"sca_csv\" })),\n repositories: new Map(),\n };\n payload = parseJsonOrJsonl(contents);\n }\n return records(payload);\n } catch (cause) {\n throw new CodexSecurityError(\n `Could not read vendor findings as UTF-8 JSON, JSONL, or Wiz CSV: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n }\n}\n\nfunction normalizeFindings(\n input: FindingInput,\n normalized?: WeakSet<VendorFinding>,\n legacy = false,\n): VendorFindings {\n const result: VendorFindings = {\n read: input.records.length,\n findings: [],\n excluded: [],\n };\n const identities = new Set<string>();\n for (const [index, item] of input.records.entries()) {\n const record = object(item.value);\n try {\n if (!record) throw new Error(\"Finding must be an object.\");\n let finding: VendorFinding;\n if (item.kind === \"sca_csv\") {\n finding = wizCsvFinding(record, sourceFindingId(record[\"ID\"]));\n } else if (\"source_finding_id\" in record) {\n if (\n Object.keys(record).some(\n (key) => ![\"source_finding_id\", \"evidence\"].includes(key),\n )\n ) {\n throw new Error(\n \"Normalized input permits only source_finding_id and evidence.\",\n );\n }\n finding = {\n source_finding_id: sourceFindingId(record[\"source_finding_id\"]),\n evidence: validateExternalEvidence(record[\"evidence\"]),\n };\n } else if (item.kind === \"cloud_configuration\") {\n throw new Error(\n \"Cloud configuration findings require a resource-scoped import and cannot be published to a repository.\",\n );\n } else if (item.kind && item.kind !== \"sca\") {\n finding = repositoryFinding(\n item.kind,\n record,\n input.repositories,\n legacy,\n );\n } else {\n if (\n !item.kind &&\n (object(record[\"repository\"]) ||\n object(record[\"repositoryBranch\"]) ||\n object(record[\"resource\"]))\n )\n throw new Error(\n \"Raw SAST, secret, and IaC records require their named sastFindings, secretInstances, or iacFindings collection. Bare arrays do not identify the finding family; use normalized JSONL for an explicit mapping.\",\n );\n finding = wizFinding(record);\n }\n if (identities.has(finding.source_finding_id)) {\n throw new CodexSecurityError(\n `Duplicate source finding id ${JSON.stringify(finding.source_finding_id)}. Select each vendor occurrence once.`,\n );\n }\n identities.add(finding.source_finding_id);\n result.findings.push(finding);\n if (item.kind !== \"sca_csv\" && \"source_finding_id\" in record)\n normalized?.add(finding);\n } catch (error) {\n if (error instanceof CodexSecurityError) throw error;\n result.excluded.push({\n position: index + 1,\n source_finding_id:\n item.kind === \"sca_csv\"\n ? text(record?.[\"ID\"])\n : (text(record?.[\"source_finding_id\"]) ?? text(record?.[\"id\"])),\n reason: error instanceof Error ? error.message : String(error),\n });\n }\n }\n return result;\n}\n"]}
@@ -3,7 +3,7 @@
3
3
  `codex-security classify-severity --records` accepts canonical reports without a
4
4
  repository, saved scan, synthetic provenance, local Codex login, or filesystem
5
5
  state. It uses the same bidirectional JSON-RPC transport as [record deduplication](dedupe-records.md).
6
- Use `--records` alone; saved-scan classification remains unchanged.
6
+ Use `--records` alone or with `--runs N`; model execution remains host-provided.
7
7
 
8
8
  The SDK exports `classifySeverityRecords`, `classifySeverityRecordsInputSchema`,
9
9
  and their input, result, and review-request types. The protocol and input have
@@ -25,6 +25,15 @@ Send one newline-delimited JSON-RPC request with `method: "run"` and these param
25
25
  }
26
26
  ```
27
27
 
28
+ The `rubric` field is optional. Omit it to classify with the
29
+ [built-in severity rubric](../src/default-severity-rubric.ts), using the same configured
30
+ independent host reviews and usage accounting. The result echoes its built-in
31
+ revision (currently `1`) and exact Markdown SHA-256. Supplying a custom rubric
32
+ replaces the default completely and preserves the supplied revision/hash binding.
33
+ Do not reuse cached results across differing rubric hashes; preserve the default
34
+ snapshot from the review prompt alongside its returned binding. Default revisions
35
+ are local to the bundled policy, not workspace rubric revisions.
36
+
28
37
  `findingJson` is the exact JSON text of an object with nonblank `findingId`,
29
38
  `title`, and `summary`. `findingId` must equal the canonical `id`. Optional
30
39
  `severity.level` uses `critical`, `high`, `medium`, `low`, or `informational`.
@@ -36,7 +45,7 @@ normalizing newlines, whitespace, Unicode, object key order, or JSON numbers.
36
45
  Compute `inputSha256` from `findingJson`, not from its parsed/reserialized object.
37
46
  For example, Node uses `createHash("sha256").update(text, "utf8").digest("hex")`;
38
47
  Python uses `hashlib.sha256(text.encode("utf-8")).hexdigest()`.
39
- The CLI recomputes both hashes before requesting any review. Rubric revisions are
48
+ The CLI recomputes supplied hashes before requesting any review. Rubric revisions are
40
49
  positive safe integers; record revisions are nonnegative safe integers. Duplicate
41
50
  canonical IDs and invalid records reject the entire input before host work.
42
51
  The implementation snapshots caller input before awaiting model execution and
@@ -45,8 +54,10 @@ numeric evidence that JavaScript cannot represent exactly.
45
54
 
46
55
  ## Host execution contract
47
56
 
48
- For each record the CLI emits `method: "review.run"`, with a unique request ID
49
- and params containing `requestId`, `stage: "severity-classification"`, explicit
57
+ The `classificationRuns` SDK option or CLI `--runs N` flag accepts
58
+ an integer from 1 through 10 (default: 3), validated before any host work.
59
+ For each record the CLI emits that many sequential `method: "review.run"` requests,
60
+ each with a unique request ID and params containing `requestId`, `stage: "severity-classification"`, explicit
50
61
  `model` and `effort`, `trustedInstructions`, untrusted report/rubric `prompt`, and
51
62
  an output JSON `schema`. The host must authorize the requested model and effort,
52
63
  create a fresh independent review context, preserve the instruction/data boundary,
@@ -61,7 +72,14 @@ object. Do not wrap the assessment in a string or an array. An assessment contai
61
72
  `rubricLabel`, `rationale`, separate `confidence`, and nullable `reviewTrigger`.
62
73
  Excluded assessments require null level and label; assessed ones require both.
63
74
 
64
- The host owns model budgets, transport limits, timeouts, and session cancellation.
75
+ The reviews receive identical inputs and do not see earlier answers. The
76
+ most common normalized severity wins; the highest among tied top counts wins
77
+ (`critical` > `high` > `medium` > `low` > `informational`). Exclusion is a separate
78
+ vote: exclusions can win by count, but lose ties to assessed severities. The first answer matching the winner supplies all assessment fields.
79
+
80
+ The host owns model budgets, usage accounting, transport limits, timeouts, and
81
+ session cancellation. Account for every review request, including work preceding
82
+ a later failure; classification results do not aggregate or report token usage.
65
83
  Use the transport's `cancel` notification with the active run ID and also stop
66
84
  any remote execution. EOF or a broken pipe means disconnection, not successful
67
85
  completion. No review is retried automatically, including after an ambiguous
@@ -70,20 +88,20 @@ host execution error.
70
88
  ## Results and persistence
71
89
 
72
90
  A completed result contains `version: 1`, `status: "completed"`, the rubric's
73
- `revision` and `sha256`, and `assessments`. Each assessment replaces model-provided
91
+ `revision` and `sha256`, `classificationRuns`, and `assessments`. Each assessment replaces model-provided
74
92
  `findingId` with the verified canonical `id`, `revision`, and `inputSha256`.
75
93
  The original report and severity are never rewritten.
76
94
 
77
95
  Invalid or mismatched model output and host failures return `status: "unresolved"`,
78
96
  an empty `assessments` array, and an error with `recordId` and stable code
79
- `invalid_assessment` or `review_failed`. Earlier assessments in that invocation
80
- are discarded. Invalid input, protocol errors, and cancellation use JSON-RPC error
81
- responses. Exit codes are 0 for completion, 1 for unresolved review, and 2 for
97
+ `invalid_assessment` or `review_failed`. All requested reviews must succeed; partial
98
+ votes and earlier assessments in that invocation are discarded. Invalid input,
99
+ protocol errors, and cancellation use JSON-RPC error responses. Exit codes are 0 for completion, 1 for unresolved review, and 2 for
82
100
  input/protocol failure (130/143 for SIGINT/SIGTERM).
83
101
 
84
102
  Prefer one canonical record per workflow invocation when the host needs independent
85
103
  retries and partial success. The host should retain immutable rubric/report
86
- snapshots, compare every echoed binding, and conditionally persist only computed
104
+ snapshots, compare every echoed binding including `classificationRuns`, and conditionally persist only computed
87
105
  prioritization fields if the expected canonical version and rubric still apply.
88
106
  Keep manual edits and original severity intact. Repeating the same inputs binds
89
107
  results to the same hashes; it does not promise deterministic model answers.