@openai/codex-security 0.8.0 → 0.8.2

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 (160) hide show
  1. package/README.md +16 -10
  2. package/_bundled_plugin/.codex-plugin/plugin.json +1 -0
  3. package/_bundled_plugin/mcp/helpers.mjs.br.part-000 +0 -0
  4. package/_bundled_plugin/mcp/helpers.mjs.br.part-001 +0 -0
  5. package/_bundled_plugin/mcp/native/THIRD_PARTY_NOTICES.txt +4 -4
  6. package/_bundled_plugin/mcp/native/darwin-arm64/unix.node +0 -0
  7. package/_bundled_plugin/mcp/native/darwin-x64/unix.node +0 -0
  8. package/_bundled_plugin/mcp/native/linux-arm64-gnu/unix.node +0 -0
  9. package/_bundled_plugin/mcp/native/linux-arm64-musl/unix.node +0 -0
  10. package/_bundled_plugin/mcp/native/linux-x64-gnu/unix.node +0 -0
  11. package/_bundled_plugin/mcp/native/linux-x64-musl/unix.node +0 -0
  12. package/_bundled_plugin/mcp/native/win32-arm64/windows.node +0 -0
  13. package/_bundled_plugin/mcp/native/win32-x64/windows.node +0 -0
  14. package/_bundled_plugin/mcp/server.mjs.br.part-000 +0 -0
  15. package/_bundled_plugin/mcp/server.mjs.br.part-001 +0 -0
  16. package/_bundled_plugin/mcp/server.mjs.br.part-002 +0 -0
  17. package/_bundled_plugin/references/scan-artifacts.md +1 -1
  18. package/_bundled_plugin/scripts/finalize_scan_contract.py +37 -1
  19. package/_bundled_plugin/scripts/servicenow_avit.py +107 -0
  20. package/_bundled_plugin/scripts/workbench_coverage_receipts.py +0 -17
  21. package/_bundled_plugin/scripts/workbench_db.py +1 -3
  22. package/_bundled_plugin/scripts/workbench_saved_results.py +0 -66
  23. package/_bundled_plugin/scripts/workbench_scan_start.py +4 -1
  24. package/_bundled_plugin/scripts/workbench_target.py +0 -108
  25. package/_bundled_plugin/skills/publish-findings/SKILL.md +9 -3
  26. package/_bundled_plugin/skills/resolve-dependency-alert/SKILL.md +18 -0
  27. package/_bundled_plugin/skills/resolve-dependency-alert/agents/openai.yaml +4 -0
  28. package/_bundled_plugin/skills/security-scan/SKILL.md +1 -1
  29. package/_bundled_plugin/skills/threat-model-visualize/SKILL.md +83 -0
  30. package/_bundled_plugin/skills/threat-model-visualize/agents/openai.yaml +4 -0
  31. package/_bundled_plugin/skills/threat-model-visualize/assets/context-reference-overview.svg +366 -0
  32. package/_bundled_plugin/skills/threat-model-visualize/assets/context-reference-path.svg +558 -0
  33. package/_bundled_plugin/skills/threat-model-visualize/assets/control-effects.js +85 -0
  34. package/_bundled_plugin/skills/threat-model-visualize/assets/explorer.css +17 -0
  35. package/_bundled_plugin/skills/threat-model-visualize/assets/explorer.html +38 -0
  36. package/_bundled_plugin/skills/threat-model-visualize/assets/explorer.js +372 -0
  37. package/_bundled_plugin/skills/threat-model-visualize/assets/route-paths.js +71 -0
  38. package/_bundled_plugin/skills/threat-model-visualize/assets/source-roles.js +47 -0
  39. package/_bundled_plugin/skills/threat-model-visualize/assets/svg-layout.js +149 -0
  40. package/_bundled_plugin/skills/threat-model-visualize/references/context-explorer.md +21 -0
  41. package/_bundled_plugin/skills/threat-model-visualize/references/view-model.md +49 -0
  42. package/_bundled_plugin/skills/threat-model-visualize/scripts/build_explorer.py +563 -0
  43. package/dist/api.d.ts.map +1 -1
  44. package/dist/api.js +36 -15
  45. package/dist/api.js.map +1 -1
  46. package/dist/artifact-export.d.ts +12 -3
  47. package/dist/artifact-export.d.ts.map +1 -1
  48. package/dist/artifact-export.js +30 -10
  49. package/dist/artifact-export.js.map +1 -1
  50. package/dist/auth.js +1 -1
  51. package/dist/auth.js.map +1 -1
  52. package/dist/cli-help.d.ts.map +1 -1
  53. package/dist/cli-help.js +1 -0
  54. package/dist/cli-help.js.map +1 -1
  55. package/dist/cli.d.ts +1 -1
  56. package/dist/cli.d.ts.map +1 -1
  57. package/dist/cli.js +72 -50
  58. package/dist/cli.js.map +1 -1
  59. package/dist/contract.d.ts +1 -0
  60. package/dist/contract.d.ts.map +1 -1
  61. package/dist/contract.js +16 -12
  62. package/dist/contract.js.map +1 -1
  63. package/dist/custom-validation-prompt.d.ts.map +1 -1
  64. package/dist/custom-validation-prompt.js +12 -4
  65. package/dist/custom-validation-prompt.js.map +1 -1
  66. package/dist/custom-validation.js +2 -2
  67. package/dist/custom-validation.js.map +1 -1
  68. package/dist/deduplication/deduplication-reviewer.d.ts.map +1 -1
  69. package/dist/deduplication/deduplication-reviewer.js +1 -1
  70. package/dist/deduplication/deduplication-reviewer.js.map +1 -1
  71. package/dist/deduplication/records-protocol.d.ts.map +1 -1
  72. package/dist/deduplication/records-protocol.js +36 -22
  73. package/dist/deduplication/records-protocol.js.map +1 -1
  74. package/dist/deduplication/records.d.ts +3 -1
  75. package/dist/deduplication/records.d.ts.map +1 -1
  76. package/dist/deduplication/records.js +12 -8
  77. package/dist/deduplication/records.js.map +1 -1
  78. package/dist/endor-findings.d.ts.map +1 -1
  79. package/dist/endor-findings.js +46 -61
  80. package/dist/endor-findings.js.map +1 -1
  81. package/dist/external-findings-import.d.ts.map +1 -1
  82. package/dist/external-findings-import.js +8 -6
  83. package/dist/external-findings-import.js.map +1 -1
  84. package/dist/external-findings-local.d.ts +3 -1
  85. package/dist/external-findings-local.d.ts.map +1 -1
  86. package/dist/external-findings-local.js +136 -36
  87. package/dist/external-findings-local.js.map +1 -1
  88. package/dist/external-findings-publish.d.ts +3 -1
  89. package/dist/external-findings-publish.d.ts.map +1 -1
  90. package/dist/external-findings-publish.js +56 -31
  91. package/dist/external-findings-publish.js.map +1 -1
  92. package/dist/external-findings-read.d.ts +2 -0
  93. package/dist/external-findings-read.d.ts.map +1 -1
  94. package/dist/external-findings-read.js +9 -0
  95. package/dist/external-findings-read.js.map +1 -1
  96. package/dist/external-findings.d.ts +11 -0
  97. package/dist/external-findings.d.ts.map +1 -1
  98. package/dist/external-findings.js +13 -1
  99. package/dist/external-findings.js.map +1 -1
  100. package/dist/external-import-models.d.ts +1 -1
  101. package/dist/external-import-models.d.ts.map +1 -1
  102. package/dist/external-import-models.js.map +1 -1
  103. package/dist/github-advisories.d.ts.map +1 -1
  104. package/dist/github-advisories.js +5 -5
  105. package/dist/github-advisories.js.map +1 -1
  106. package/dist/github-dependabot-findings.d.ts +6 -0
  107. package/dist/github-dependabot-findings.d.ts.map +1 -0
  108. package/dist/github-dependabot-findings.js +247 -0
  109. package/dist/github-dependabot-findings.js.map +1 -0
  110. package/dist/github-findings.d.ts.map +1 -1
  111. package/dist/github-findings.js +11 -4
  112. package/dist/github-findings.js.map +1 -1
  113. package/dist/github-identifiers.d.ts +4 -0
  114. package/dist/github-identifiers.d.ts.map +1 -0
  115. package/dist/github-identifiers.js +9 -0
  116. package/dist/github-identifiers.js.map +1 -0
  117. package/dist/github.d.ts.map +1 -1
  118. package/dist/github.js +4 -6
  119. package/dist/github.js.map +1 -1
  120. package/dist/host-protocol.d.ts +5 -0
  121. package/dist/host-protocol.d.ts.map +1 -1
  122. package/dist/host-protocol.js +27 -3
  123. package/dist/host-protocol.js.map +1 -1
  124. package/dist/hosted-scan.d.ts.map +1 -1
  125. package/dist/hosted-scan.js +13 -5
  126. package/dist/hosted-scan.js.map +1 -1
  127. package/dist/index.d.ts +2 -0
  128. package/dist/index.d.ts.map +1 -1
  129. package/dist/index.js +2 -0
  130. package/dist/index.js.map +1 -1
  131. package/dist/inspector-findings.d.ts +9 -0
  132. package/dist/inspector-findings.d.ts.map +1 -0
  133. package/dist/inspector-findings.js +517 -0
  134. package/dist/inspector-findings.js.map +1 -0
  135. package/dist/patch-tui.d.ts +1 -1
  136. package/dist/patch-tui.d.ts.map +1 -1
  137. package/dist/patch-tui.js +4 -1
  138. package/dist/patch-tui.js.map +1 -1
  139. package/dist/runtime.d.ts +3 -2
  140. package/dist/runtime.d.ts.map +1 -1
  141. package/dist/runtime.js +15 -5
  142. package/dist/runtime.js.map +1 -1
  143. package/dist/scan-dashboard.d.ts.map +1 -1
  144. package/dist/scan-dashboard.js +25 -15
  145. package/dist/scan-dashboard.js.map +1 -1
  146. package/dist/scanner-import.d.ts +6 -2
  147. package/dist/scanner-import.d.ts.map +1 -1
  148. package/dist/scanner-import.js +23 -14
  149. package/dist/scanner-import.js.map +1 -1
  150. package/dist/semgrep-findings.d.ts.map +1 -1
  151. package/dist/semgrep-findings.js +39 -49
  152. package/dist/semgrep-findings.js.map +1 -1
  153. package/dist/snyk-findings.d.ts.map +1 -1
  154. package/dist/snyk-findings.js +78 -88
  155. package/dist/snyk-findings.js.map +1 -1
  156. package/docs/cli.md +52 -14
  157. package/docs/dedupe-records.md +17 -4
  158. package/docs/hosted-scans.md +14 -0
  159. package/package.json +5 -5
  160. package/schemas/external-findings.schema.json +1 -1
@@ -42,12 +42,14 @@ export function relativePath(value) {
42
42
  export function stableId(prefix, fields) {
43
43
  return `${prefix}:${hash("sha256", JSON.stringify(fields))}`;
44
44
  }
45
- /** Detect gzip from the report bytes and preserve identities with strict UTF-8. */
45
+ const strictUtf8 = new TextDecoder("utf-8", { fatal: true });
46
+ const gunzipAsync = promisify(gunzip);
47
+ async function readScannerBytes(path) {
48
+ const bytes = await readFile(path);
49
+ return bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipAsync(bytes) : bytes;
50
+ }
46
51
  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);
52
+ return strictUtf8.decode(await readScannerBytes(path));
51
53
  }
52
54
  export function parseJsonOrJsonl(contents) {
53
55
  try {
@@ -61,12 +63,10 @@ export function parseJsonOrJsonl(contents) {
61
63
  }
62
64
  }
63
65
  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);
66
+ const bytes = await readScannerBytes(path);
67
67
  let decoded;
68
68
  try {
69
- decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
69
+ decoded = strictUtf8.decode(bytes);
70
70
  }
71
71
  catch (error) {
72
72
  throw new CodexSecurityError(`Scanner report is not valid UTF-8. ${errorMessage(error)}`, { cause: error });
@@ -150,8 +150,17 @@ export function sarifRunContextForResult(runContext, ...selectedEvidence) {
150
150
  }
151
151
  return context;
152
152
  }
153
+ /** Duplicate IDs cannot identify a single rule in this run. */
154
+ export function indexSarifRules(rules) {
155
+ const byId = new Map();
156
+ for (const [index, rule] of rules.entries()) {
157
+ const id = rule["id"];
158
+ byId.set(id, byId.has(id) ? null : { rule, index });
159
+ }
160
+ return byId;
161
+ }
153
162
  /** Exclude every colliding record: choosing the first could overwrite another occurrence. */
154
- export function normalizeRecords(records, normalize, identify, target = "cloud") {
163
+ export function normalizeRecords(records, projectEvidence, identify, target = "cloud") {
155
164
  const result = {
156
165
  read: records.length,
157
166
  findings: [],
@@ -189,10 +198,10 @@ export function normalizeRecords(records, normalize, identify, target = "cloud")
189
198
  continue;
190
199
  }
191
200
  try {
192
- const finding = normalize(value, id);
193
- if (finding.source_finding_id !== id)
194
- throw new Error("Finding identity changed during normalization.");
195
- result.findings.push(finding);
201
+ result.findings.push({
202
+ source_finding_id: id,
203
+ evidence: projectEvidence(value, id),
204
+ });
196
205
  }
197
206
  catch (error) {
198
207
  result.excluded.push({
@@ -1 +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,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,UAAU,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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 target: \"local\" | \"cloud\" = \"cloud\",\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 (\n !id.trim() ||\n id.includes(\"\\0\") ||\n (target === \"cloud\" && Buffer.byteLength(id) > 512)\n )\n throw new Error(\n target === \"cloud\"\n ? \"Source finding ID must contain 1–512 UTF-8 bytes and no NUL characters.\"\n : \"Source finding ID must be nonempty and contain 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"]}
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,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AACnC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE/D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,UAAU,MAAM,CAAC,KAAc,EAAE,KAAa;IAClD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAC7D,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,qBAAqB,CAAC,CAAC;IACjD,OAAO,KAAgC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,KAAK,CAAC,KAAc,EAAE,KAAa;IACjD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,oBAAoB,CAAC,CAAC;IACzE,OAAO,KAAK,CAAC;AACf,CAAC;AAED,MAAM,UAAU,IAAI,CAAC,KAAc;IACjC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAA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,EAAE,YAAY,CAAC,KAAK,CAAC;aAC5B,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,KAAK,MAAM,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,EAAE,IAAI,UAAU,EAAE,CAAC;QACjD,IAAI,MAAM,CAAC,GAAG,CAAC,EAAE,CAAE,GAAG,CAAC,EAAE,CAAC;YACxB,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,QAAQ;gBACR,iBAAiB,EAAE,EAAE;gBACrB,MAAM,EACJ,+FAA+F;aAClG,CAAC,CAAC;YACH,SAAS;QACX,CAAC;QACD,IAAI,CAAC;YACH,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,iBAAiB,EAAE,EAAE;gBACrB,QAAQ,EAAE,eAAe,CAAC,KAAK,EAAE,EAAE,CAAC;aACrC,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC;gBACnB,QAAQ;gBACR,iBAAiB,EAAE,EAAE;gBACrB,MAAM,EAAE,YAAY,CAAC,KAAK,CAAC;aAC5B,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,QAAQ,CAAC,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\nconst strictUtf8 = new TextDecoder(\"utf-8\", { fatal: true });\nconst gunzipAsync = promisify(gunzip);\n\nasync function readScannerBytes(path: string): Promise<Buffer> {\n const bytes = await readFile(path);\n return bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipAsync(bytes) : bytes;\n}\n\nexport async function readScannerText(path: string): Promise<string> {\n return strictUtf8.decode(await readScannerBytes(path));\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 const bytes = await readScannerBytes(path);\n let decoded: string;\n try {\n decoded = strictUtf8.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/** Duplicate IDs cannot identify a single rule in this run. */\nexport function indexSarifRules(rules: Record<string, unknown>[]) {\n const byId = new Map<\n unknown,\n { rule: Record<string, unknown>; index: number } | null\n >();\n for (const [index, rule] of rules.entries()) {\n const id = rule[\"id\"];\n byId.set(id, byId.has(id) ? null : { rule, index });\n }\n return byId;\n}\n\n/** Exclude every colliding record: choosing the first could overwrite another occurrence. */\nexport function normalizeRecords<T>(\n records: T[],\n projectEvidence: (record: T, id: string) => ExternalFinding[\"evidence\"],\n identify: (record: T) => string,\n target: \"local\" | \"cloud\" = \"cloud\",\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 (\n !id.trim() ||\n id.includes(\"\\0\") ||\n (target === \"cloud\" && Buffer.byteLength(id) > 512)\n )\n throw new Error(\n target === \"cloud\"\n ? \"Source finding ID must contain 1–512 UTF-8 bytes and no NUL characters.\"\n : \"Source finding ID must be nonempty and contain 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 result.findings.push({\n source_finding_id: id,\n evidence: projectEvidence(value, id),\n });\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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"semgrep-findings.d.ts","sourceRoot":"","sources":["../src/semgrep-findings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAK1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAuB/D,MAAM,WAAW,oBAAoB;IACnC,qFAAqF;IACrF,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAkHD,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CA6BlB;AAED,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CA+MlB;AAED,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,OAAO,CAAC,gBAAgB,CAAC,CAE3B"}
1
+ {"version":3,"file":"semgrep-findings.d.ts","sourceRoot":"","sources":["../src/semgrep-findings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAK1E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAwB/D,MAAM,WAAW,oBAAoB;IACnC,qFAAqF;IACrF,mBAAmB,EAAE,MAAM,CAAC;CAC7B;AAkHD,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAwBlB;AAED,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,OAAO,EACd,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,gBAAgB,CAqMlB;AAED,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,oBAAoB,EAC7B,MAAM,GAAE,oBAA8B,GACrC,OAAO,CAAC,gBAAgB,CAAC,CAE3B"}
@@ -1,6 +1,6 @@
1
1
  import { cloudRepositoryUrlKey, validateExternalEvidence, } from "./external-import-contract.js";
2
2
  import { messageText, parseNativeJsonResult, position, projectNativeJsonResult, sourceRepositoryUrl, ungatedText, weaknessIds, } from "./native-json-findings.js";
3
- import { array, hasSarifExternalPropertyReferences, normalizeRecords, readScannerJson, record, relativePath, requiredText, sarifRunContextForResult, stableId, text, } from "./scanner-import.js";
3
+ import { array, hasSarifExternalPropertyReferences, indexSarifRules, normalizeRecords, readScannerJson, record, relativePath, requiredText, sarifRunContextForResult, stableId, text, } from "./scanner-import.js";
4
4
  function sourceRepository(options) {
5
5
  return sourceRepositoryUrl(options?.sourceRepositoryUrl, "Semgrep");
6
6
  }
@@ -75,15 +75,12 @@ export function normalizeSemgrepFindings(input, options, target = "cloud") {
75
75
  if (array(document["errors"] ?? [], "Semgrep errors").length)
76
76
  throw new Error("The Semgrep report contains scan errors; supply a successful report before importing findings.");
77
77
  const { results, paths: _paths, time: _time, ...context } = document;
78
- return normalizeRecords(array(results, "Semgrep results"), (value, sourceFindingId) => ({
79
- source_finding_id: sourceFindingId,
80
- evidence: projectNativeJsonResult(parseNativeJsonResult(value, "Semgrep"), {
81
- origin: "Semgrep",
82
- repositoryUrl,
83
- severity,
84
- reportContext: context,
85
- target,
86
- }),
78
+ return normalizeRecords(array(results, "Semgrep results"), (value) => projectNativeJsonResult(parseNativeJsonResult(value, "Semgrep"), {
79
+ origin: "Semgrep",
80
+ repositoryUrl,
81
+ severity,
82
+ reportContext: context,
83
+ target,
87
84
  }), jsonIdentity, target);
88
85
  }
89
86
  export function normalizeSemgrepSarif(input, options, target = "cloud") {
@@ -113,11 +110,7 @@ export function normalizeSemgrepSarif(input, options, target = "cloud") {
113
110
  throw new Error("Semgrep SARIF contains scan error notifications.");
114
111
  }
115
112
  const rules = array(driver["rules"] ?? [], "Semgrep rules").map((r) => record(r, "Semgrep rule"));
116
- const rulesById = new Map();
117
- for (const [index, rule] of rules.entries()) {
118
- const id = rule["id"];
119
- rulesById.set(id, rulesById.has(id) ? null : { rule, index });
120
- }
113
+ const rulesById = indexSarifRules(rules);
121
114
  const { runs: _runs, ...documentContext } = document;
122
115
  const { results: _results, tool: _tool, ...runContext } = run;
123
116
  const { rules: _rules, ...driverContext } = driver;
@@ -132,7 +125,7 @@ export function normalizeSemgrepSarif(input, options, target = "cloud") {
132
125
  toolContext,
133
126
  }));
134
127
  });
135
- return normalizeRecords(entries, ({ result: value, rulesById, hasRules, ...context }, sourceFindingId) => {
128
+ return normalizeRecords(entries, ({ result: value, rulesById, hasRules, ...context }) => {
136
129
  const result = record(value, "Semgrep result");
137
130
  const properties = record(result["properties"] ?? {}, "Semgrep result properties");
138
131
  if (properties["exposure"] != null ||
@@ -184,40 +177,37 @@ export function normalizeSemgrepSarif(input, options, target = "cloud") {
184
177
  typeof artifact["uri"] === "string" &&
185
178
  /^[a-z][a-z\d+.-]*:/iu.test(artifact["uri"]);
186
179
  const path = rawPath === null || absoluteUri ? null : relativePath(rawPath);
187
- return {
188
- source_finding_id: sourceFindingId,
189
- evidence: validateExternalEvidence({
190
- title: ruleId,
191
- description: text(message["markdown"]) ??
192
- messageText(message["text"], "Semgrep"),
193
- severity: mappedSeverity,
194
- locations: path ? [{ path, line }] : [],
195
- details: {
196
- kind: "sast",
197
- repository: { url: repositoryUrl },
198
- scanner_origin: "Semgrep",
199
- rule: { id: ruleId },
200
- weakness_ids: weaknessIds(record(rule?.["properties"] ?? {}, "Rule properties")["tags"]),
201
- code: {
202
- end_line: path ? endLine : null,
203
- snippet: ungatedText(record(region["snippet"] ?? {}, "Snippet")["text"]),
204
- },
205
- source_status: Array.isArray(result["suppressions"]) &&
206
- result["suppressions"].some((value) => {
207
- const status = record(value, "Suppression")["status"];
208
- return status === undefined || status === "accepted";
209
- })
210
- ? "suppressed"
211
- : null,
180
+ return validateExternalEvidence({
181
+ title: ruleId,
182
+ description: text(message["markdown"]) ??
183
+ messageText(message["text"], "Semgrep"),
184
+ severity: mappedSeverity,
185
+ locations: path ? [{ path, line }] : [],
186
+ details: {
187
+ kind: "sast",
188
+ repository: { url: repositoryUrl },
189
+ scanner_origin: "Semgrep",
190
+ rule: { id: ruleId },
191
+ weakness_ids: weaknessIds(record(rule?.["properties"] ?? {}, "Rule properties")["tags"]),
192
+ code: {
193
+ end_line: path ? endLine : null,
194
+ snippet: ungatedText(record(region["snippet"] ?? {}, "Snippet")["text"]),
212
195
  },
213
- source_data: structuredClone({
214
- ...context,
215
- runContext: sarifRunContextForResult(context.runContext, result, rule, context.driverContext, context.toolContext, context.documentContext),
216
- ...(rule ? { rule } : {}),
217
- result,
218
- }),
219
- }, target),
220
- };
196
+ source_status: Array.isArray(result["suppressions"]) &&
197
+ result["suppressions"].some((value) => {
198
+ const status = record(value, "Suppression")["status"];
199
+ return status === undefined || status === "accepted";
200
+ })
201
+ ? "suppressed"
202
+ : null,
203
+ },
204
+ source_data: structuredClone({
205
+ ...context,
206
+ runContext: sarifRunContextForResult(context.runContext, result, rule, context.driverContext, context.toolContext, context.documentContext),
207
+ ...(rule ? { rule } : {}),
208
+ result,
209
+ }),
210
+ }, target);
221
211
  }, ({ result, runContext }) => sarifIdentity(result, runContext), target);
222
212
  }
223
213
  export async function readSemgrepFindings(path, options, target = "cloud") {
@@ -1 +1 @@
1
- {"version":3,"file":"semgrep-findings.js","sourceRoot":"","sources":["../src/semgrep-findings.ts"],"names":[],"mappings":"AACA,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AAEvC,OA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M,CAAC,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,SAAS,CAAC,CAAC,MAAM,CAAC,CACnD;qBACF;oBACD,aAAa,EACX,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;wBACrC,MAAM,CAAC,cAAc,CAAC,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;4BACpC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,CAAC;4BACtD,OAAO,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,UAAU,CAAC;wBACvD,CAAC,CAAC;wBACA,CAAC,CAAC,YAAY;wBACd,CAAC,CAAC,IAAI;iBACX;gBACD,WAAW,EAAE,eAAe,CAAC;oBAC3B,GAAG,OAAO;oBACV,UAAU,EAAE,wBAAwB,CAClC,OAAO,CAAC,UAAU,EAClB,MAAM,EACN,IAAI,EACJ,OAAO,CAAC,aAAa,EACrB,OAAO,CAAC,WAAW,EACnB,OAAO,CAAC,eAAe,CACxB;oBACD,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;oBACzB,MAAM;iBACP,CAAC;aACH,EACD,MAAM,CACP;SACF,CAAC;IACJ,CAAC,EACD,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7D,MAAM,CACP,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,IAAY,EACZ,OAA6B,EAC7B,MAAM,GAAyB,OAAO;IAEtC,OAAO,wBAAwB,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import type { ExternalImportTarget } from \"./external-import-contract.js\";\nimport {\n cloudRepositoryUrlKey,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport type { ExternalFindings } from \"./external-findings.js\";\nimport {\n messageText,\n parseNativeJsonResult,\n position,\n projectNativeJsonResult,\n sourceRepositoryUrl,\n ungatedText,\n weaknessIds,\n} from \"./native-json-findings.js\";\nimport {\n array,\n hasSarifExternalPropertyReferences,\n normalizeRecords,\n readScannerJson,\n record,\n relativePath,\n requiredText,\n sarifRunContextForResult,\n stableId,\n text,\n} from \"./scanner-import.js\";\n\nexport interface SemgrepImportOptions {\n /** Source repository declared by the caller; never inferred from the destination. */\n sourceRepositoryUrl: string;\n}\n\nfunction sourceRepository(options: SemgrepImportOptions): string {\n return sourceRepositoryUrl(options?.sourceRepositoryUrl, \"Semgrep\");\n}\n\nfunction severity(value: unknown): string {\n const levels: Record<string, string> = {\n CRITICAL: \"critical\",\n HIGH: \"high\",\n MEDIUM: \"medium\",\n LOW: \"low\",\n ERROR: \"high\",\n WARNING: \"medium\",\n INFO: \"low\",\n };\n return typeof value === \"string\" ? (levels[value] ?? \"unknown\") : \"unknown\";\n}\n\nfunction identity(\n rule: string,\n path: string,\n line: number,\n column: number,\n endLine: number,\n endColumn: number,\n): string {\n // CE omits fingerprints and source snippets. Its fallback is stable only while the range is stable.\n return stableId(\"semgrep-location\", [\n rule,\n path,\n line,\n column,\n endLine,\n endColumn,\n ]);\n}\n\nfunction jsonIdentity(value: unknown): string {\n const result = record(value, \"Semgrep result\");\n const extra = record(result[\"extra\"], \"Semgrep extra\");\n const supplied = ungatedText(extra[\"fingerprint\"]);\n if (supplied) return stableId(\"semgrep\", [supplied]);\n const start = record(result[\"start\"], \"Semgrep start\");\n const end = record(result[\"end\"], \"Semgrep end\");\n return identity(\n requiredText(result[\"check_id\"], \"Semgrep check_id\"),\n requiredText(result[\"path\"], \"Semgrep path\"),\n position(start[\"line\"], \"Start line\"),\n position(start[\"col\"], \"Start column\"),\n position(end[\"line\"], \"End line\"),\n position(end[\"col\"], \"End column\"),\n );\n}\n\nfunction sarifArtifactUri(\n artifact: Record<string, unknown>,\n runContext: Record<string, unknown>,\n): string | null {\n const base = artifact[\"uriBaseId\"];\n // Native Semgrep uses %SRCROOT% without defining a base. Keep other references raw.\n if (\n artifact[\"index\"] !== undefined ||\n (base !== undefined &&\n (base !== \"%SRCROOT%\" ||\n record(runContext[\"originalUriBaseIds\"] ?? {}, \"SARIF URI bases\")[\n base\n ] !== undefined))\n )\n return null;\n const uri = requiredText(artifact[\"uri\"], \"Semgrep artifact URI\");\n // Semgrep's native formatter copies filesystem paths without URI encoding.\n return base === \"%SRCROOT%\" ? uri : decodeURIComponent(uri);\n}\n\nfunction sarifIdentity(\n value: unknown,\n runContext: Record<string, unknown>,\n): string {\n const result = record(value, \"Semgrep result\");\n const supplied = ungatedText(\n record(result[\"fingerprints\"] ?? {}, \"Semgrep fingerprints\")[\n \"matchBasedId/v1\"\n ],\n );\n if (supplied) return stableId(\"semgrep\", [supplied]);\n const locations = array(result[\"locations\"] ?? [], \"Semgrep locations\");\n if (locations.length !== 1)\n throw new Error(\"Expected Semgrep's single primary result location.\");\n const physical = record(\n record(locations[0], \"Location\")[\"physicalLocation\"],\n \"Physical location\",\n );\n const uri = sarifArtifactUri(\n record(physical[\"artifactLocation\"], \"Artifact location\"),\n runContext,\n );\n if (uri === null)\n throw new Error(\n \"Cannot derive a Semgrep CE identity from an indexed or unresolved base-relative artifact URI.\",\n );\n const region = record(physical[\"region\"], \"Semgrep region\");\n const line = position(region[\"startLine\"], \"Start line\");\n const column = position(region[\"startColumn\"] ?? 1, \"Start column\");\n return identity(\n requiredText(result[\"ruleId\"], \"Semgrep ruleId\"),\n uri,\n line,\n column,\n position(region[\"endLine\"] ?? line, \"End line\"),\n position(region[\"endColumn\"] ?? column, \"End column\"),\n );\n}\n\nexport function normalizeSemgrepFindings(\n input: unknown,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const document = record(input, \"Semgrep report\");\n if (document[\"version\"] === \"2.1.0\" && document[\"runs\"] !== undefined)\n return normalizeSemgrepSarif(document, options, target);\n const repositoryUrl = sourceRepository(options);\n requiredText(document[\"version\"], \"Semgrep version\");\n if (array(document[\"errors\"] ?? [], \"Semgrep errors\").length)\n throw new Error(\n \"The Semgrep report contains scan errors; supply a successful report before importing findings.\",\n );\n const { results, paths: _paths, time: _time, ...context } = document;\n return normalizeRecords(\n array(results, \"Semgrep results\"),\n (value, sourceFindingId) => ({\n source_finding_id: sourceFindingId,\n evidence: projectNativeJsonResult(\n parseNativeJsonResult(value, \"Semgrep\"),\n {\n origin: \"Semgrep\",\n repositoryUrl,\n severity,\n reportContext: context,\n target,\n },\n ),\n }),\n jsonIdentity,\n target,\n );\n}\n\nexport function normalizeSemgrepSarif(\n input: unknown,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const repositoryUrl = sourceRepository(options);\n const document = record(input, \"Semgrep SARIF\");\n if (document[\"version\"] !== \"2.1.0\")\n throw new Error(\"Expected Semgrep SARIF 2.1.0.\");\n const entries = array(document[\"runs\"], \"SARIF runs\").flatMap((value) => {\n const run = record(value, \"SARIF run\");\n for (const entry of array(\n run[\"versionControlProvenance\"] ?? [],\n \"Version control provenance\",\n )) {\n const declared = text(\n record(entry, \"Repository provenance\")[\"repositoryUri\"],\n );\n if (\n declared &&\n cloudRepositoryUrlKey(declared) !== cloudRepositoryUrlKey(repositoryUrl)\n )\n throw new Error(\n \"SARIF source repository does not match the declared source repository URL.\",\n );\n }\n const tool = record(run[\"tool\"], \"SARIF tool\");\n const driver = record(tool[\"driver\"], \"SARIF driver\");\n if (\n ![\"semgrep\", \"semgrep oss\", \"semgrep pro\"].includes(\n requiredText(driver[\"name\"], \"SARIF producer\").toLowerCase(),\n )\n )\n throw new Error(\"Expected a Semgrep SARIF producer.\");\n if (\n hasSarifExternalPropertyReferences(run[\"externalPropertyFileReferences\"])\n )\n throw new Error(\"Use a self-contained Semgrep SARIF report.\");\n for (const invocation of array(\n run[\"invocations\"] ?? [],\n \"Semgrep invocations\",\n )) {\n const details = record(invocation, \"Semgrep invocation\");\n if (details[\"executionSuccessful\"] === false)\n throw new Error(\"Semgrep SARIF contains an unsuccessful invocation.\");\n if (\n array(\n details[\"toolExecutionNotifications\"] ?? [],\n \"Semgrep scan notifications\",\n ).length\n )\n throw new Error(\"Semgrep SARIF contains scan error notifications.\");\n }\n const rules = array(driver[\"rules\"] ?? [], \"Semgrep rules\").map((r) =>\n record(r, \"Semgrep rule\"),\n );\n const rulesById = new Map<\n unknown,\n { rule: Record<string, unknown>; index: number } | null\n >();\n for (const [index, rule] of rules.entries()) {\n const id = rule[\"id\"];\n rulesById.set(id, rulesById.has(id) ? null : { rule, index });\n }\n const { runs: _runs, ...documentContext } = document;\n const { results: _results, tool: _tool, ...runContext } = run;\n const { rules: _rules, ...driverContext } = driver;\n const { driver: _driver, ...toolContext } = tool;\n return array(run[\"results\"] ?? [], \"Semgrep results\").map((result) => ({\n result,\n rulesById,\n hasRules: rules.length > 0,\n documentContext,\n runContext,\n driverContext,\n toolContext,\n }));\n });\n return normalizeRecords(\n entries,\n ({ result: value, rulesById, hasRules, ...context }, sourceFindingId) => {\n const result = record(value, \"Semgrep result\");\n const properties = record(\n result[\"properties\"] ?? {},\n \"Semgrep result properties\",\n );\n if (\n properties[\"exposure\"] != null ||\n properties[\"dependencyPaths\"] != null\n )\n throw new Error(\n \"This adapter supports Semgrep SAST; Supply Chain reports need separate qualification.\",\n );\n const ruleId = requiredText(result[\"ruleId\"], \"Semgrep ruleId\");\n const selectedRule = rulesById.get(ruleId);\n if (selectedRule === null || (hasRules && selectedRule === undefined))\n throw new Error(\n \"Semgrep result must reference exactly one rule in its run.\",\n );\n const rule = selectedRule?.rule;\n const ruleIndex = selectedRule?.index;\n if (\n result[\"ruleIndex\"] !== undefined &&\n result[\"ruleIndex\"] !== ruleIndex\n )\n throw new Error(\"Semgrep ruleIndex and ruleId disagree.\");\n if (result[\"rule\"] !== undefined) {\n const ref = record(result[\"rule\"], \"Semgrep rule reference\");\n if (\n ref[\"toolComponent\"] !== undefined ||\n (ref[\"id\"] !== undefined && ref[\"id\"] !== ruleId) ||\n (ref[\"index\"] !== undefined && ref[\"index\"] !== ruleIndex) ||\n (ref[\"guid\"] !== undefined && ref[\"guid\"] !== rule?.[\"guid\"])\n )\n throw new Error(\"Inconsistent or external Semgrep rule reference.\");\n }\n const locations = array(result[\"locations\"] ?? [], \"Semgrep locations\");\n if (locations.length !== 1)\n throw new Error(\"Expected Semgrep's single primary result location.\");\n const physical = record(\n record(locations[0], \"Location\")[\"physicalLocation\"],\n \"Physical location\",\n );\n const artifact = record(\n physical[\"artifactLocation\"],\n \"Artifact location\",\n );\n const rawPath = sarifArtifactUri(artifact, context.runContext);\n const region = record(physical[\"region\"], \"Semgrep region\");\n const line = position(region[\"startLine\"], \"Start line\");\n const column = position(region[\"startColumn\"] ?? 1, \"Start column\");\n const endLine = position(region[\"endLine\"] ?? line, \"End line\");\n const endColumn = position(region[\"endColumn\"] ?? column, \"End column\");\n if (endLine < line || (endLine === line && endColumn < column))\n throw new Error(\"Semgrep source range ends before it starts.\");\n const message = record(result[\"message\"], \"Semgrep message\");\n const configuration = record(\n rule?.[\"defaultConfiguration\"] ?? {},\n \"Rule configuration\",\n );\n const level = text(result[\"level\"]) ?? text(configuration[\"level\"]);\n // SARIF collapses severity categories; retain its diagnostic level and all original metadata.\n const mappedSeverity =\n level === \"error\"\n ? \"high\"\n : level === \"warning\"\n ? \"medium\"\n : level === \"note\"\n ? \"low\"\n : \"unknown\";\n // Native %SRCROOT% values are filesystem paths; direct URIs can name other targets.\n const absoluteUri =\n artifact[\"uriBaseId\"] !== \"%SRCROOT%\" &&\n typeof artifact[\"uri\"] === \"string\" &&\n /^[a-z][a-z\\d+.-]*:/iu.test(artifact[\"uri\"]);\n const path =\n rawPath === null || absoluteUri ? null : relativePath(rawPath);\n return {\n source_finding_id: sourceFindingId,\n evidence: validateExternalEvidence(\n {\n title: ruleId,\n description:\n text(message[\"markdown\"]) ??\n messageText(message[\"text\"], \"Semgrep\"),\n severity: mappedSeverity,\n locations: path ? [{ path, line }] : [],\n details: {\n kind: \"sast\",\n repository: { url: repositoryUrl },\n scanner_origin: \"Semgrep\",\n rule: { id: ruleId },\n weakness_ids: weaknessIds(\n record(rule?.[\"properties\"] ?? {}, \"Rule properties\")[\"tags\"],\n ),\n code: {\n end_line: path ? endLine : null,\n snippet: ungatedText(\n record(region[\"snippet\"] ?? {}, \"Snippet\")[\"text\"],\n ),\n },\n source_status:\n Array.isArray(result[\"suppressions\"]) &&\n result[\"suppressions\"].some((value) => {\n const status = record(value, \"Suppression\")[\"status\"];\n return status === undefined || status === \"accepted\";\n })\n ? \"suppressed\"\n : null,\n },\n source_data: structuredClone({\n ...context,\n runContext: sarifRunContextForResult(\n context.runContext,\n result,\n rule,\n context.driverContext,\n context.toolContext,\n context.documentContext,\n ),\n ...(rule ? { rule } : {}),\n result,\n }),\n },\n target,\n ),\n };\n },\n ({ result, runContext }) => sarifIdentity(result, runContext),\n target,\n );\n}\n\nexport async function readSemgrepFindings(\n path: string,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): Promise<ExternalFindings> {\n return normalizeSemgrepFindings(await readScannerJson(path), options, target);\n}\n"]}
1
+ {"version":3,"file":"semgrep-findings.js","sourceRoot":"","sources":["../src/semgrep-findings.ts"],"names":[],"mappings":"AACA,OAAO,EACL,qBAAqB,EACrB,wBAAwB,GACzB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EACL,WAAW,EACX,qBAAqB,EACrB,QAAQ,EACR,uBAAuB,EACvB,mBAAmB,EACnB,WAAW,EACX,WAAW,GACZ,MAAM,2BAA2B,CAAC;AACnC,OAAO,EACL,KAAK,EACL,kCAAkC,EAClC,eAAe,EACf,gBAAgB,EAChB,eAAe,EACf,MAAM,EACN,YAAY,EACZ,YAAY,EACZ,wBAAwB,EACxB,QAAQ,EACR,IAAI,GACL,MAAM,qBAAqB,CAAC;AAO7B,SAAS,gBAAgB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;gBACzB,MAAM;aACP,CAAC;SACH,EACD,MAAM,CACP,CAAC;IACJ,CAAC,EACD,CAAC,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7D,MAAM,CACP,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,mBAAmB,CACvC,IAAY,EACZ,OAA6B,EAC7B,MAAM,GAAyB,OAAO;IAEtC,OAAO,wBAAwB,CAAC,MAAM,eAAe,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import type { ExternalImportTarget } from \"./external-import-contract.js\";\nimport {\n cloudRepositoryUrlKey,\n validateExternalEvidence,\n} from \"./external-import-contract.js\";\nimport type { ExternalFindings } from \"./external-findings.js\";\nimport {\n messageText,\n parseNativeJsonResult,\n position,\n projectNativeJsonResult,\n sourceRepositoryUrl,\n ungatedText,\n weaknessIds,\n} from \"./native-json-findings.js\";\nimport {\n array,\n hasSarifExternalPropertyReferences,\n indexSarifRules,\n normalizeRecords,\n readScannerJson,\n record,\n relativePath,\n requiredText,\n sarifRunContextForResult,\n stableId,\n text,\n} from \"./scanner-import.js\";\n\nexport interface SemgrepImportOptions {\n /** Source repository declared by the caller; never inferred from the destination. */\n sourceRepositoryUrl: string;\n}\n\nfunction sourceRepository(options: SemgrepImportOptions): string {\n return sourceRepositoryUrl(options?.sourceRepositoryUrl, \"Semgrep\");\n}\n\nfunction severity(value: unknown): string {\n const levels: Record<string, string> = {\n CRITICAL: \"critical\",\n HIGH: \"high\",\n MEDIUM: \"medium\",\n LOW: \"low\",\n ERROR: \"high\",\n WARNING: \"medium\",\n INFO: \"low\",\n };\n return typeof value === \"string\" ? (levels[value] ?? \"unknown\") : \"unknown\";\n}\n\nfunction identity(\n rule: string,\n path: string,\n line: number,\n column: number,\n endLine: number,\n endColumn: number,\n): string {\n // CE omits fingerprints and source snippets. Its fallback is stable only while the range is stable.\n return stableId(\"semgrep-location\", [\n rule,\n path,\n line,\n column,\n endLine,\n endColumn,\n ]);\n}\n\nfunction jsonIdentity(value: unknown): string {\n const result = record(value, \"Semgrep result\");\n const extra = record(result[\"extra\"], \"Semgrep extra\");\n const supplied = ungatedText(extra[\"fingerprint\"]);\n if (supplied) return stableId(\"semgrep\", [supplied]);\n const start = record(result[\"start\"], \"Semgrep start\");\n const end = record(result[\"end\"], \"Semgrep end\");\n return identity(\n requiredText(result[\"check_id\"], \"Semgrep check_id\"),\n requiredText(result[\"path\"], \"Semgrep path\"),\n position(start[\"line\"], \"Start line\"),\n position(start[\"col\"], \"Start column\"),\n position(end[\"line\"], \"End line\"),\n position(end[\"col\"], \"End column\"),\n );\n}\n\nfunction sarifArtifactUri(\n artifact: Record<string, unknown>,\n runContext: Record<string, unknown>,\n): string | null {\n const base = artifact[\"uriBaseId\"];\n // Native Semgrep uses %SRCROOT% without defining a base. Keep other references raw.\n if (\n artifact[\"index\"] !== undefined ||\n (base !== undefined &&\n (base !== \"%SRCROOT%\" ||\n record(runContext[\"originalUriBaseIds\"] ?? {}, \"SARIF URI bases\")[\n base\n ] !== undefined))\n )\n return null;\n const uri = requiredText(artifact[\"uri\"], \"Semgrep artifact URI\");\n // Semgrep's native formatter copies filesystem paths without URI encoding.\n return base === \"%SRCROOT%\" ? uri : decodeURIComponent(uri);\n}\n\nfunction sarifIdentity(\n value: unknown,\n runContext: Record<string, unknown>,\n): string {\n const result = record(value, \"Semgrep result\");\n const supplied = ungatedText(\n record(result[\"fingerprints\"] ?? {}, \"Semgrep fingerprints\")[\n \"matchBasedId/v1\"\n ],\n );\n if (supplied) return stableId(\"semgrep\", [supplied]);\n const locations = array(result[\"locations\"] ?? [], \"Semgrep locations\");\n if (locations.length !== 1)\n throw new Error(\"Expected Semgrep's single primary result location.\");\n const physical = record(\n record(locations[0], \"Location\")[\"physicalLocation\"],\n \"Physical location\",\n );\n const uri = sarifArtifactUri(\n record(physical[\"artifactLocation\"], \"Artifact location\"),\n runContext,\n );\n if (uri === null)\n throw new Error(\n \"Cannot derive a Semgrep CE identity from an indexed or unresolved base-relative artifact URI.\",\n );\n const region = record(physical[\"region\"], \"Semgrep region\");\n const line = position(region[\"startLine\"], \"Start line\");\n const column = position(region[\"startColumn\"] ?? 1, \"Start column\");\n return identity(\n requiredText(result[\"ruleId\"], \"Semgrep ruleId\"),\n uri,\n line,\n column,\n position(region[\"endLine\"] ?? line, \"End line\"),\n position(region[\"endColumn\"] ?? column, \"End column\"),\n );\n}\n\nexport function normalizeSemgrepFindings(\n input: unknown,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const document = record(input, \"Semgrep report\");\n if (document[\"version\"] === \"2.1.0\" && document[\"runs\"] !== undefined)\n return normalizeSemgrepSarif(document, options, target);\n const repositoryUrl = sourceRepository(options);\n requiredText(document[\"version\"], \"Semgrep version\");\n if (array(document[\"errors\"] ?? [], \"Semgrep errors\").length)\n throw new Error(\n \"The Semgrep report contains scan errors; supply a successful report before importing findings.\",\n );\n const { results, paths: _paths, time: _time, ...context } = document;\n return normalizeRecords(\n array(results, \"Semgrep results\"),\n (value) =>\n projectNativeJsonResult(parseNativeJsonResult(value, \"Semgrep\"), {\n origin: \"Semgrep\",\n repositoryUrl,\n severity,\n reportContext: context,\n target,\n }),\n jsonIdentity,\n target,\n );\n}\n\nexport function normalizeSemgrepSarif(\n input: unknown,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): ExternalFindings {\n const repositoryUrl = sourceRepository(options);\n const document = record(input, \"Semgrep SARIF\");\n if (document[\"version\"] !== \"2.1.0\")\n throw new Error(\"Expected Semgrep SARIF 2.1.0.\");\n const entries = array(document[\"runs\"], \"SARIF runs\").flatMap((value) => {\n const run = record(value, \"SARIF run\");\n for (const entry of array(\n run[\"versionControlProvenance\"] ?? [],\n \"Version control provenance\",\n )) {\n const declared = text(\n record(entry, \"Repository provenance\")[\"repositoryUri\"],\n );\n if (\n declared &&\n cloudRepositoryUrlKey(declared) !== cloudRepositoryUrlKey(repositoryUrl)\n )\n throw new Error(\n \"SARIF source repository does not match the declared source repository URL.\",\n );\n }\n const tool = record(run[\"tool\"], \"SARIF tool\");\n const driver = record(tool[\"driver\"], \"SARIF driver\");\n if (\n ![\"semgrep\", \"semgrep oss\", \"semgrep pro\"].includes(\n requiredText(driver[\"name\"], \"SARIF producer\").toLowerCase(),\n )\n )\n throw new Error(\"Expected a Semgrep SARIF producer.\");\n if (\n hasSarifExternalPropertyReferences(run[\"externalPropertyFileReferences\"])\n )\n throw new Error(\"Use a self-contained Semgrep SARIF report.\");\n for (const invocation of array(\n run[\"invocations\"] ?? [],\n \"Semgrep invocations\",\n )) {\n const details = record(invocation, \"Semgrep invocation\");\n if (details[\"executionSuccessful\"] === false)\n throw new Error(\"Semgrep SARIF contains an unsuccessful invocation.\");\n if (\n array(\n details[\"toolExecutionNotifications\"] ?? [],\n \"Semgrep scan notifications\",\n ).length\n )\n throw new Error(\"Semgrep SARIF contains scan error notifications.\");\n }\n const rules = array(driver[\"rules\"] ?? [], \"Semgrep rules\").map((r) =>\n record(r, \"Semgrep rule\"),\n );\n const rulesById = indexSarifRules(rules);\n const { runs: _runs, ...documentContext } = document;\n const { results: _results, tool: _tool, ...runContext } = run;\n const { rules: _rules, ...driverContext } = driver;\n const { driver: _driver, ...toolContext } = tool;\n return array(run[\"results\"] ?? [], \"Semgrep results\").map((result) => ({\n result,\n rulesById,\n hasRules: rules.length > 0,\n documentContext,\n runContext,\n driverContext,\n toolContext,\n }));\n });\n return normalizeRecords(\n entries,\n ({ result: value, rulesById, hasRules, ...context }) => {\n const result = record(value, \"Semgrep result\");\n const properties = record(\n result[\"properties\"] ?? {},\n \"Semgrep result properties\",\n );\n if (\n properties[\"exposure\"] != null ||\n properties[\"dependencyPaths\"] != null\n )\n throw new Error(\n \"This adapter supports Semgrep SAST; Supply Chain reports need separate qualification.\",\n );\n const ruleId = requiredText(result[\"ruleId\"], \"Semgrep ruleId\");\n const selectedRule = rulesById.get(ruleId);\n if (selectedRule === null || (hasRules && selectedRule === undefined))\n throw new Error(\n \"Semgrep result must reference exactly one rule in its run.\",\n );\n const rule = selectedRule?.rule;\n const ruleIndex = selectedRule?.index;\n if (\n result[\"ruleIndex\"] !== undefined &&\n result[\"ruleIndex\"] !== ruleIndex\n )\n throw new Error(\"Semgrep ruleIndex and ruleId disagree.\");\n if (result[\"rule\"] !== undefined) {\n const ref = record(result[\"rule\"], \"Semgrep rule reference\");\n if (\n ref[\"toolComponent\"] !== undefined ||\n (ref[\"id\"] !== undefined && ref[\"id\"] !== ruleId) ||\n (ref[\"index\"] !== undefined && ref[\"index\"] !== ruleIndex) ||\n (ref[\"guid\"] !== undefined && ref[\"guid\"] !== rule?.[\"guid\"])\n )\n throw new Error(\"Inconsistent or external Semgrep rule reference.\");\n }\n const locations = array(result[\"locations\"] ?? [], \"Semgrep locations\");\n if (locations.length !== 1)\n throw new Error(\"Expected Semgrep's single primary result location.\");\n const physical = record(\n record(locations[0], \"Location\")[\"physicalLocation\"],\n \"Physical location\",\n );\n const artifact = record(\n physical[\"artifactLocation\"],\n \"Artifact location\",\n );\n const rawPath = sarifArtifactUri(artifact, context.runContext);\n const region = record(physical[\"region\"], \"Semgrep region\");\n const line = position(region[\"startLine\"], \"Start line\");\n const column = position(region[\"startColumn\"] ?? 1, \"Start column\");\n const endLine = position(region[\"endLine\"] ?? line, \"End line\");\n const endColumn = position(region[\"endColumn\"] ?? column, \"End column\");\n if (endLine < line || (endLine === line && endColumn < column))\n throw new Error(\"Semgrep source range ends before it starts.\");\n const message = record(result[\"message\"], \"Semgrep message\");\n const configuration = record(\n rule?.[\"defaultConfiguration\"] ?? {},\n \"Rule configuration\",\n );\n const level = text(result[\"level\"]) ?? text(configuration[\"level\"]);\n // SARIF collapses severity categories; retain its diagnostic level and all original metadata.\n const mappedSeverity =\n level === \"error\"\n ? \"high\"\n : level === \"warning\"\n ? \"medium\"\n : level === \"note\"\n ? \"low\"\n : \"unknown\";\n // Native %SRCROOT% values are filesystem paths; direct URIs can name other targets.\n const absoluteUri =\n artifact[\"uriBaseId\"] !== \"%SRCROOT%\" &&\n typeof artifact[\"uri\"] === \"string\" &&\n /^[a-z][a-z\\d+.-]*:/iu.test(artifact[\"uri\"]);\n const path =\n rawPath === null || absoluteUri ? null : relativePath(rawPath);\n return validateExternalEvidence(\n {\n title: ruleId,\n description:\n text(message[\"markdown\"]) ??\n messageText(message[\"text\"], \"Semgrep\"),\n severity: mappedSeverity,\n locations: path ? [{ path, line }] : [],\n details: {\n kind: \"sast\",\n repository: { url: repositoryUrl },\n scanner_origin: \"Semgrep\",\n rule: { id: ruleId },\n weakness_ids: weaknessIds(\n record(rule?.[\"properties\"] ?? {}, \"Rule properties\")[\"tags\"],\n ),\n code: {\n end_line: path ? endLine : null,\n snippet: ungatedText(\n record(region[\"snippet\"] ?? {}, \"Snippet\")[\"text\"],\n ),\n },\n source_status:\n Array.isArray(result[\"suppressions\"]) &&\n result[\"suppressions\"].some((value) => {\n const status = record(value, \"Suppression\")[\"status\"];\n return status === undefined || status === \"accepted\";\n })\n ? \"suppressed\"\n : null,\n },\n source_data: structuredClone({\n ...context,\n runContext: sarifRunContextForResult(\n context.runContext,\n result,\n rule,\n context.driverContext,\n context.toolContext,\n context.documentContext,\n ),\n ...(rule ? { rule } : {}),\n result,\n }),\n },\n target,\n );\n },\n ({ result, runContext }) => sarifIdentity(result, runContext),\n target,\n );\n}\n\nexport async function readSemgrepFindings(\n path: string,\n options: SemgrepImportOptions,\n target: ExternalImportTarget = \"cloud\",\n): Promise<ExternalFindings> {\n return normalizeSemgrepFindings(await readScannerJson(path), options, target);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"snyk-findings.d.ts","sourceRoot":"","sources":["../src/snyk-findings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,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