@bevorai/sdk 0.2.0 → 0.2.2-rc1

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.
package/README.md CHANGED
@@ -63,7 +63,6 @@ Responses are the API's JSON, typed. Timestamps are ISO 8601 strings.
63
63
 
64
64
  ```ts
65
65
  const analysis = client.analyses.with(analysisId);
66
- await analysis.commit();
67
66
  await analysis.listFindings({ version_id: versionId });
68
67
 
69
68
  const nodes = client.codes.with(codeId).nodes;
@@ -107,7 +106,7 @@ for await (const message of client.chats.stream(chatId, token, {
107
106
 
108
107
  ```ts
109
108
  import { fingerprintSource } from "@bevorai/sdk";
110
- import { directoryFiles } from "@bevorai/sdk/node";
109
+ import { directoryFiles } from "@bevorai/sdk/helpers";
111
110
 
112
111
  const { zip, nFiles, versionFingerprint } = await fingerprintSource(
113
112
  await directoryFiles("./contracts"),
@@ -152,7 +151,7 @@ Error responses with a known code throw a typed subclass of `BevorError` (`NotFo
152
151
  Any other non-2xx response throws `BevorError` with the `status` and raw `body`.
153
152
 
154
153
  ```ts
155
- import { NotFoundError } from "@bevorai/sdk";
154
+ import { NotFoundError } from "@bevorai/sdk/errors";
156
155
 
157
156
  try {
158
157
  await client.findings.get(findingId);
@@ -165,7 +164,7 @@ try {
165
164
  ### SARIF
166
165
 
167
166
  ```ts
168
- import { bevorToSarif, sarifToBevor } from "@bevorai/sdk";
167
+ import { bevorToSarif, sarifToBevor } from "@bevorai/sdk/helpers";
169
168
 
170
169
  const sarif = await bevorToSarif(graph, findings.results);
171
170
  await client.analyses.addFindings(analysisId, {
package/dist/errors.d.ts CHANGED
@@ -89,7 +89,7 @@ export declare class NotFoundError extends BevorError {
89
89
  }
90
90
  /**
91
91
  * The resource's current state forbids the action. e.g. a pipeline is running,
92
- * changes are staged, or it already exists.
92
+ * finding cannot be changed, or it already exists.
93
93
  */
94
94
  export declare class InvalidStateError extends BevorError {
95
95
  readonly code = "error.invalid_state";
package/dist/errors.js CHANGED
@@ -96,7 +96,7 @@ export class NotFoundError extends BevorError {
96
96
  }
97
97
  /**
98
98
  * The resource's current state forbids the action. e.g. a pipeline is running,
99
- * changes are staged, or it already exists.
99
+ * finding cannot be changed, or it already exists.
100
100
  */
101
101
  export class InvalidStateError extends BevorError {
102
102
  code = "error.invalid_state";
@@ -1,11 +1,11 @@
1
1
  import type { Log, Region } from "sarif";
2
2
  import type { Graph } from "../graph/graph.js";
3
- import type { FindingCreateBody } from "../types/requests.js";
4
- import type { Finding } from "../types/responses.js";
5
- /** Line/column (1-indexed), byte and code-point offsets for a byte range of a UTF-8 file. */
3
+ import type { FindingAddManyBody } from "../types/requests.js";
4
+ import type { Analysis, Finding } from "../types/responses.js";
5
+ /** Line/column (1-indexed, columns in code points, endColumn exclusive), byte and code-point offsets. */
6
6
  export declare const computeRegion: (content: Uint8Array, byteStart: number, byteEnd: number) => Region;
7
7
  /** Converts findings to a SARIF 2.1.0 log, one run per tool. The graph must be built. */
8
- export declare const bevorToSarif: (graph: Graph, findings: readonly Finding[]) => Promise<Log>;
9
- /** Converts a SARIF log into finding bodies for `analyses.addFindings`. */
10
- export declare const sarifToBevor: (sarif: Log) => FindingCreateBody[];
8
+ export declare const bevorToSarif: (graph: Graph, analysis: Analysis, findings: readonly Finding[]) => Promise<Log>;
9
+ /** Converts a SARIF log into a request body for `analyses.addFindings`. */
10
+ export declare const sarifToBevor: (sarif: Log) => FindingAddManyBody;
11
11
  //# sourceMappingURL=sarif.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"sarif.d.ts","sourceRoot":"","sources":["../../src/helpers/sarif.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EAEH,MAAM,EAIN,MAAM,OAAO,CAAC;AACf,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE/C,OAAO,KAAK,EACX,iBAAiB,EAGjB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAwFrD,6FAA6F;AAC7F,eAAO,MAAM,aAAa,YAChB,UAAU,aACR,MAAM,WACR,MAAM,KACb,MAwBF,CAAC;AAoDF,yFAAyF;AACzF,eAAO,MAAM,YAAY,UACjB,KAAK,YACF,SAAS,OAAO,EAAE,KAC1B,OAAO,CAAC,GAAG,CAyCb,CAAC;AAEF,2EAA2E;AAC3E,eAAO,MAAM,YAAY,UAAW,GAAG,KAAG,iBAAiB,EA+B1D,CAAC"}
1
+ {"version":3,"file":"sarif.d.ts","sourceRoot":"","sources":["../../src/helpers/sarif.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,GAAG,EAIH,MAAM,EAKN,MAAM,OAAO,CAAC;AACf,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAG/C,OAAO,KAAK,EACX,kBAAkB,EAKlB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AA0G/D,yGAAyG;AACzG,eAAO,MAAM,aAAa,YAChB,UAAU,aACR,MAAM,WACR,MAAM,KACb,MA8BF,CAAC;AA2FF,yFAAyF;AACzF,eAAO,MAAM,YAAY,UACjB,KAAK,YACF,QAAQ,YACR,SAAS,OAAO,EAAE,KAC1B,OAAO,CAAC,GAAG,CAoGb,CAAC;AAsMF,2EAA2E;AAC3E,eAAO,MAAM,YAAY,UAAW,GAAG,KAAG,kBAuCzC,CAAC"}
@@ -1,9 +1,11 @@
1
1
  const BEVOR_TOOL_VERSION = "0.0.1";
2
+ const BEVOR_INFORMATION_URI = "https://bevor.io/docs";
3
+ const SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json";
2
4
  const BEVOR_TO_SARIF_LEVEL = {
3
5
  critical: "error",
4
6
  high: "warning",
5
7
  medium: "note",
6
- low: "none",
8
+ low: "note",
7
9
  };
8
10
  const SARIF_TO_BEVOR_LEVEL = {
9
11
  error: "critical",
@@ -11,6 +13,8 @@ const SARIF_TO_BEVOR_LEVEL = {
11
13
  note: "medium",
12
14
  none: "low",
13
15
  };
16
+ const FINDING_LEVELS = Object.keys(BEVOR_TO_SARIF_LEVEL);
17
+ const SKIPPED_KINDS = new Set(["pass", "notApplicable", "informational"]);
14
18
  const PHYSICAL_REGION_KEYS = [
15
19
  "startLine",
16
20
  "startColumn",
@@ -28,20 +32,25 @@ const utf8Encoder = new TextEncoder();
28
32
  const titleCase = (value) => value.replace(/[A-Za-z]+/g, (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase());
29
33
  const countNewlines = (bytes) => bytes.reduce((n, b) => (b === NEWLINE ? n + 1 : n), 0);
30
34
  const codePointLength = (bytes) => [...strictUtf8.decode(bytes)].length;
31
- const ruleForFinding = (finding) => ({
32
- id: finding.type,
33
- shortDescription: {
34
- text: `${titleCase(finding.type.replaceAll("_", " "))} Vulnerability`,
35
- },
36
- });
35
+ // ---------------------------------------------------------------------------------------------- export
36
+ const ruleForFinding = (finding) => {
37
+ const description = `${titleCase(finding.type.replaceAll("_", " "))} Vulnerability`;
38
+ return {
39
+ id: finding.type,
40
+ name: description.replaceAll(" ", ""),
41
+ shortDescription: { text: description },
42
+ properties: { tags: ["security"] },
43
+ };
44
+ };
37
45
  /** Bevor-specific properties; SARIF property bags here carry strings only. */
38
46
  const bevorProperties = (finding) => {
39
47
  const properties = {
40
48
  findingId: finding.id,
41
- nodeId: finding.node_id,
49
+ nodeId: finding.location_id,
42
50
  is_acknowledged: finding.is_acknowledged,
43
51
  recommendation: finding.recommendation,
44
52
  poc: finding.poc,
53
+ level: finding.level,
45
54
  };
46
55
  const pruned = {};
47
56
  for (const [key, value] of Object.entries(properties)) {
@@ -51,27 +60,36 @@ const bevorProperties = (finding) => {
51
60
  }
52
61
  return { bevor: pruned };
53
62
  };
54
- const resultFromFinding = (finding, location) => ({
55
- ruleId: finding.type,
56
- level: BEVOR_TO_SARIF_LEVEL[finding.level],
57
- message: {
58
- text: finding.name,
59
- properties: { description: finding.explanation },
60
- },
61
- locations: [{ physicalLocation: location }],
62
- properties: bevorProperties(finding),
63
- });
64
- /** Line/column (1-indexed), byte and code-point offsets for a byte range of a UTF-8 file. */
63
+ const resultFromFinding = (finding, locations, related, ruleIndex) => {
64
+ const result = {
65
+ ruleId: finding.type,
66
+ ruleIndex,
67
+ level: BEVOR_TO_SARIF_LEVEL[finding.level],
68
+ message: { text: finding.name, markdown: finding.explanation },
69
+ locations,
70
+ properties: bevorProperties(finding),
71
+ };
72
+ if (related.length > 0)
73
+ result.relatedLocations = related;
74
+ return result;
75
+ };
76
+ /** Line/column (1-indexed, columns in code points, endColumn exclusive), byte and code-point offsets. */
65
77
  export const computeRegion = (content, byteStart, byteEnd) => {
66
78
  const before = content.subarray(0, byteStart);
67
79
  const snippet = content.subarray(byteStart, byteEnd);
68
80
  const startLine = countNewlines(before) + 1;
69
- const startColumn = byteStart - before.lastIndexOf(NEWLINE);
70
- const snippetNewlines = countNewlines(snippet);
71
- const endLine = startLine + snippetNewlines;
72
- const endColumn = snippetNewlines > 0
73
- ? byteEnd - (byteStart + snippet.lastIndexOf(NEWLINE))
74
- : startColumn + snippet.length;
81
+ const endLine = startLine + countNewlines(snippet);
82
+ const startLineStart = before.lastIndexOf(NEWLINE) + 1;
83
+ const startColumn = codePointLength(content.subarray(startLineStart, byteStart)) + 1;
84
+ const snippetLastNewline = snippet.lastIndexOf(NEWLINE);
85
+ let endColumn;
86
+ if (snippetLastNewline >= 0) {
87
+ const endLineStart = byteStart + snippetLastNewline + 1;
88
+ endColumn = codePointLength(content.subarray(endLineStart, byteEnd)) + 1;
89
+ }
90
+ else {
91
+ endColumn = startColumn + codePointLength(snippet);
92
+ }
75
93
  return {
76
94
  byteOffset: byteStart,
77
95
  byteLength: byteEnd - byteStart,
@@ -83,109 +101,373 @@ export const computeRegion = (content, byteStart, byteEnd) => {
83
101
  endColumn,
84
102
  };
85
103
  };
86
- const locationFromResult = (result) => {
87
- const location = result.locations?.[0];
88
- if (!location)
89
- throw new Error("result has no resolvable location");
90
- const physical = location.physicalLocation;
91
- const uri = physical?.artifactLocation?.uri;
92
- if (uri && physical?.region) {
93
- // SARIF defaults both offsets to -1 ("not provided"); the Python SDK sends them filled in
94
- const region = {
95
- charOffset: -1,
96
- byteOffset: -1,
97
- ...physical.region,
98
- };
99
- const found = { strategy: "physical", uri };
100
- for (const key of PHYSICAL_REGION_KEYS) {
101
- const value = region[key];
102
- if (value !== null && value !== undefined)
103
- found[key] = value;
104
- }
105
- return found;
104
+ const computeLogical = (graph, node) => {
105
+ const location = { name: node.name };
106
+ if (node.is_callable)
107
+ location.kind = "function";
108
+ else if (node.is_declaration)
109
+ location.kind = "variable";
110
+ else if (node.is_container)
111
+ location.kind = "type";
112
+ const file = graph.getFile(node.file_id);
113
+ // Solidity overloads, so functions keep their signature; Python names are already unique
114
+ let fqn = file.language === "solidity" && node.signature ? node.signature : node.name;
115
+ let nodeId = node.id;
116
+ const visited = new Set([nodeId]);
117
+ while (true) {
118
+ const edge = graph.getEdgesForNode(nodeId, {
119
+ direction: "in",
120
+ edgeType: "defines",
121
+ })[0];
122
+ if (!edge)
123
+ break;
124
+ const parent = graph.getNode(edge.src_id);
125
+ if (visited.has(parent.id))
126
+ break;
127
+ visited.add(parent.id);
128
+ fqn = `${parent.name}.${fqn}`;
129
+ nodeId = parent.id;
106
130
  }
107
- const fullyQualifiedName = location.logicalLocations?.[0]?.fullyQualifiedName;
108
- if (fullyQualifiedName)
109
- return { strategy: "logical", fully_qualified_name: fullyQualifiedName };
110
- throw new Error("result has no resolvable location");
131
+ if (file.language === "solidity") {
132
+ location.fullyQualifiedName = fqn;
133
+ }
134
+ else {
135
+ const module = file.path
136
+ .replace(/\.py$/, "")
137
+ .replace(/\/__init__$/, "")
138
+ .replaceAll("/", ".");
139
+ location.fullyQualifiedName = `${module}.${fqn}`;
140
+ }
141
+ location.properties = { bevor: { nodeId: node.id } };
142
+ return location;
143
+ };
144
+ const locationForNode = (graph, node, contents) => {
145
+ const file = graph.getFile(node.file_id);
146
+ const content = contents.get(file.id);
147
+ if (!content)
148
+ throw new Error(`missing content for file ${file.id}`);
149
+ return {
150
+ physicalLocation: {
151
+ artifactLocation: { uri: file.path },
152
+ region: computeRegion(content, node.src_start_pos, node.src_end_pos),
153
+ },
154
+ logicalLocations: [computeLogical(graph, node)],
155
+ };
156
+ };
157
+ /** Both the entrypoint and the location are exported, and they can live in different files. */
158
+ const fileIds = (graph, findings) => {
159
+ const ids = new Set();
160
+ for (const finding of findings) {
161
+ ids.add(graph.getNode(finding.node_id).file_id);
162
+ ids.add(graph.getNode(finding.location_id).file_id);
163
+ }
164
+ return ids;
111
165
  };
112
166
  /** Fetches (once per file) the UTF-8 bytes of every file a finding points at. */
113
167
  const getContents = async (graph, findings) => {
114
- const fileIds = new Set(findings.map((finding) => graph.getNode(finding.node_id).file_id));
115
- const contents = await Promise.all([...fileIds].map(async (fileId) => [
168
+ const contents = await Promise.all([...fileIds(graph, findings)].map(async (fileId) => [
116
169
  fileId,
117
170
  utf8Encoder.encode(await graph.getFileContent(fileId)),
118
171
  ]));
119
172
  return new Map(contents);
120
173
  };
121
174
  /** Converts findings to a SARIF 2.1.0 log, one run per tool. The graph must be built. */
122
- export const bevorToSarif = async (graph, findings) => {
175
+ export const bevorToSarif = async (graph, analysis, findings) => {
123
176
  const contents = await getContents(graph, findings);
177
+ // per tool: its rules, its rule id -> index into those rules, and its results
124
178
  const rules = new Map();
179
+ const ruleIndex = new Map();
125
180
  const results = new Map();
126
- const append = (map, key, value) => {
127
- const list = map.get(key);
128
- if (list)
129
- list.push(value);
130
- else
131
- map.set(key, [value]);
132
- };
133
181
  for (const finding of findings) {
134
- const node = graph.getNode(finding.node_id);
135
- const file = graph.getFile(node.file_id);
136
- const content = contents.get(file.id);
137
- const toolName = finding.tool.startsWith("bevor") ? "Bevor" : finding.tool;
138
- const location = {
139
- artifactLocation: { uri: file.path },
140
- region: computeRegion(content, node.src_start_pos, node.src_end_pos),
182
+ // where the problem is
183
+ const primary = locationForNode(graph, graph.getNode(finding.location_id), contents);
184
+ // how it's reached; only when that's a different node
185
+ const related = [];
186
+ if (finding.node_id !== finding.location_id) {
187
+ const entrypoint = locationForNode(graph, graph.getNode(finding.node_id), contents);
188
+ entrypoint.id = 1;
189
+ entrypoint.message = { text: "entrypoint" };
190
+ entrypoint.properties = { bevor: { role: "entrypoint" } };
191
+ related.push(entrypoint);
192
+ }
193
+ let toolRules = rules.get(finding.tool);
194
+ if (!toolRules) {
195
+ toolRules = [];
196
+ rules.set(finding.tool, toolRules);
197
+ }
198
+ let toolIndex = ruleIndex.get(finding.tool);
199
+ if (!toolIndex) {
200
+ toolIndex = new Map();
201
+ ruleIndex.set(finding.tool, toolIndex);
202
+ }
203
+ let index = toolIndex.get(finding.type);
204
+ if (index === undefined) {
205
+ index = toolRules.length;
206
+ toolIndex.set(finding.type, index);
207
+ toolRules.push(ruleForFinding(finding));
208
+ }
209
+ let toolResults = results.get(finding.tool);
210
+ if (!toolResults) {
211
+ toolResults = [];
212
+ results.set(finding.tool, toolResults);
213
+ }
214
+ toolResults.push(resultFromFinding(finding, [primary], related, index));
215
+ }
216
+ const bevorTool = {
217
+ name: "Bevor",
218
+ semanticVersion: BEVOR_TOOL_VERSION,
219
+ informationUri: BEVOR_INFORMATION_URI,
220
+ };
221
+ const codeVersion = analysis.version.code_version;
222
+ const runs = [];
223
+ for (const [toolName, toolResults] of results) {
224
+ const driver = {
225
+ name: toolName,
226
+ rules: rules.get(toolName),
141
227
  };
142
- append(rules, toolName, ruleForFinding(finding));
143
- append(results, toolName, resultFromFinding(finding, location));
144
- }
145
- const runs = [...rules.keys()].map((toolName) => ({
146
- tool: {
147
- driver: {
148
- name: toolName,
149
- rules: rules.get(toolName),
150
- ...(toolName === "Bevor"
151
- ? {
152
- semanticVersion: BEVOR_TOOL_VERSION,
153
- informationUri: "https://bevor.io/docs",
154
- }
155
- : {}),
228
+ if (toolName.toLowerCase().startsWith("bevor")) {
229
+ driver.semanticVersion = BEVOR_TOOL_VERSION;
230
+ driver.informationUri = BEVOR_INFORMATION_URI;
231
+ }
232
+ const run = {
233
+ tool: { driver },
234
+ conversion: { tool: { driver: bevorTool } },
235
+ automationDetails: { id: `bevor/${analysis.id}/${analysis.version.id}` },
236
+ properties: {
237
+ bevor: {
238
+ codeId: codeVersion.id,
239
+ fingerprint: codeVersion.version_fingerprint,
240
+ },
156
241
  },
157
- },
158
- results: results.get(toolName),
159
- }));
160
- return { version: "2.1.0", runs };
242
+ results: toolResults,
243
+ };
244
+ if (codeVersion.repository && codeVersion.commit) {
245
+ run.versionControlProvenance = [
246
+ {
247
+ repositoryUri: codeVersion.repository.url,
248
+ revisionId: codeVersion.commit.sha,
249
+ branch: codeVersion.branch ?? undefined,
250
+ },
251
+ ];
252
+ }
253
+ runs.push(run);
254
+ }
255
+ return { $schema: SARIF_SCHEMA, version: "2.1.0", runs };
256
+ };
257
+ // ---------------------------------------------------------------------------------------------- import
258
+ /** Only present when Bevor-aware tooling wrote the SARIF; other tools never set it. */
259
+ const bevorProps = (bag) => {
260
+ const bevor = bag?.bevor;
261
+ if (typeof bevor !== "object" || bevor === null)
262
+ return {};
263
+ const props = {};
264
+ for (const [key, value] of Object.entries(bevor)) {
265
+ if (typeof value === "string")
266
+ props[key] = value;
267
+ }
268
+ return props;
269
+ };
270
+ const securitySeverityLevel = (rule) => {
271
+ const raw = rule?.properties?.["security-severity"];
272
+ if (typeof raw !== "string" && typeof raw !== "number")
273
+ return undefined;
274
+ const score = Number(raw);
275
+ if (Number.isNaN(score))
276
+ return undefined;
277
+ if (score >= 9.0)
278
+ return "critical";
279
+ if (score >= 7.0)
280
+ return "high";
281
+ if (score >= 4.0)
282
+ return "medium";
283
+ return "low";
284
+ };
285
+ const levelFromResult = (result, rule) => {
286
+ const bevorLevel = bevorProps(result.properties).level;
287
+ for (const level of FINDING_LEVELS) {
288
+ if (level === bevorLevel)
289
+ return level;
290
+ }
291
+ // the numeric score security tools publish is more precise than SARIF's coarse level
292
+ const fromScore = securitySeverityLevel(rule);
293
+ if (fromScore !== undefined)
294
+ return fromScore;
295
+ if (result.level)
296
+ return SARIF_TO_BEVOR_LEVEL[result.level];
297
+ if (rule?.defaultConfiguration?.level)
298
+ return SARIF_TO_BEVOR_LEVEL[rule.defaultConfiguration.level];
299
+ return SARIF_TO_BEVOR_LEVEL.warning;
300
+ };
301
+ const ruleForResult = (run, result) => {
302
+ const reference = result.rule;
303
+ // rules live on the driver, or on an extension when result.rule names one (CodeQL does this)
304
+ const extensionIndex = reference?.toolComponent?.index;
305
+ const extension = extensionIndex !== undefined
306
+ ? run.tool.extensions?.[extensionIndex]
307
+ : undefined;
308
+ const rules = (extension ?? run.tool.driver).rules ?? [];
309
+ const ruleId = result.ruleId ?? reference?.id;
310
+ if (ruleId !== undefined) {
311
+ const byId = rules.find((rule) => rule.id === ruleId);
312
+ if (byId)
313
+ return byId;
314
+ }
315
+ const index = result.ruleIndex !== undefined && result.ruleIndex >= 0
316
+ ? result.ruleIndex
317
+ : reference?.index;
318
+ if (index === undefined)
319
+ return undefined;
320
+ return rules[index];
321
+ };
322
+ const messageText = (result, rule) => {
323
+ const message = result.message;
324
+ if (message.markdown)
325
+ return message.markdown;
326
+ if (message.text)
327
+ return message.text;
328
+ // templated messages: the text lives on the rule, with {0}, {1}… filled from arguments
329
+ if (message.id && rule?.messageStrings) {
330
+ const template = rule.messageStrings[message.id];
331
+ if (template) {
332
+ let text = template.markdown || template.text;
333
+ (message.arguments ?? []).forEach((argument, i) => {
334
+ text = text.replaceAll(`{${i}}`, argument);
335
+ });
336
+ return text;
337
+ }
338
+ }
339
+ return undefined;
340
+ };
341
+ const recommendationFor = (result, rule) => {
342
+ const bevorRecommendation = bevorProps(result.properties).recommendation;
343
+ if (bevorRecommendation)
344
+ return bevorRecommendation;
345
+ // a fix's own description is specific to this result; the rule's help is generic guidance for its type
346
+ const fixDescription = result.fixes?.[0]?.description;
347
+ if (fixDescription) {
348
+ if (fixDescription.markdown)
349
+ return fixDescription.markdown;
350
+ if (fixDescription.text)
351
+ return fixDescription.text;
352
+ }
353
+ if (rule?.help)
354
+ return rule.help.markdown || rule.help.text;
355
+ return undefined;
356
+ };
357
+ const artifactUri = (run, physical) => {
358
+ const artifact = physical.artifactLocation;
359
+ if (!artifact)
360
+ return undefined;
361
+ let uri = artifact.uri;
362
+ if (uri === undefined && artifact.index !== undefined) {
363
+ uri = run.artifacts?.[artifact.index]?.location?.uri;
364
+ }
365
+ if (uri === undefined)
366
+ return undefined;
367
+ // tools write absolute file URIs, %SRCROOT%-relative paths, or ./-prefixed paths; keep it repo-relative
368
+ uri = uri.replace(/^file:\/\//, "");
369
+ const base = artifact.uriBaseId
370
+ ? run.originalUriBaseIds?.[artifact.uriBaseId]
371
+ : undefined;
372
+ if (base?.uri) {
373
+ const basePath = `${base.uri.replace(/^file:\/\//, "").replace(/\/+$/, "")}/`;
374
+ if (uri.startsWith(basePath))
375
+ uri = uri.slice(basePath.length);
376
+ }
377
+ return uri.replace(/^\.\//, "");
378
+ };
379
+ const locationFromResult = (run, result) => {
380
+ const location = result.locations?.[0];
381
+ if (!location)
382
+ throw new Error("result has no resolvable location");
383
+ const logical = location.logicalLocations?.[0];
384
+ // most specific first: a node id from Bevor-aware tooling, then the file region, then the qualified name
385
+ const nodeId = bevorProps(logical?.properties).nodeId ??
386
+ bevorProps(result.properties).nodeId;
387
+ if (nodeId)
388
+ return { strategy: "node_id", node_id: nodeId };
389
+ const physical = location.physicalLocation;
390
+ if (physical?.region) {
391
+ const uri = artifactUri(run, physical);
392
+ if (uri) {
393
+ // SARIF defaults both offsets to -1 ("not provided"); the Python SDK sends them filled in
394
+ const region = {
395
+ charOffset: -1,
396
+ byteOffset: -1,
397
+ ...physical.region,
398
+ };
399
+ const found = { strategy: "physical", uri };
400
+ for (const key of PHYSICAL_REGION_KEYS) {
401
+ const value = region[key];
402
+ if (value !== null && value !== undefined)
403
+ found[key] = value;
404
+ }
405
+ // many tools report only a start line; a one-line region is what they mean
406
+ if (found.startLine !== undefined && found.endLine === undefined) {
407
+ found.endLine = found.startLine;
408
+ }
409
+ return found;
410
+ }
411
+ }
412
+ if (logical) {
413
+ let fullyQualifiedName = logical.fullyQualifiedName;
414
+ if (fullyQualifiedName === undefined && logical.index !== undefined) {
415
+ fullyQualifiedName =
416
+ run.logicalLocations?.[logical.index]?.fullyQualifiedName;
417
+ }
418
+ if (fullyQualifiedName)
419
+ return { strategy: "logical", fully_qualified_name: fullyQualifiedName };
420
+ }
421
+ throw new Error("result has no resolvable location");
161
422
  };
162
- /** Converts a SARIF log into finding bodies for `analyses.addFindings`. */
423
+ const isActive = (result) => {
424
+ if (result.kind !== undefined && SKIPPED_KINDS.has(result.kind))
425
+ return false;
426
+ // the tool already knows this one is fixed
427
+ if (result.baselineState === "absent")
428
+ return false;
429
+ // dismissed in the source tool; a suppression with no status counts as accepted
430
+ for (const suppression of result.suppressions ?? []) {
431
+ if (suppression.status === undefined || suppression.status === "accepted")
432
+ return false;
433
+ }
434
+ return true;
435
+ };
436
+ /** Converts a SARIF log into a request body for `analyses.addFindings`. */
163
437
  export const sarifToBevor = (sarif) => {
164
438
  const bodies = [];
439
+ let tool;
165
440
  for (const run of sarif.runs ?? []) {
166
- const tool = run.tool.driver.name;
167
- const rules = new Map((run.tool.driver.rules ?? []).map((rule) => [rule.id, rule]));
441
+ tool = run.tool.driver.name;
168
442
  for (const result of run.results ?? []) {
169
- const rule = rules.get(result.ruleId ?? "");
170
- const findingType = result.ruleId || rule?.id || rule?.name;
443
+ if (!isActive(result))
444
+ continue;
445
+ const rule = ruleForResult(run, result);
446
+ const findingType = result.ruleId || rule?.id;
171
447
  if (!findingType)
172
448
  throw new Error("result is missing a resolvable type");
173
- const name = rule?.name || rule?.shortDescription?.text || findingType;
174
- const explanation = result.message.text || result.message.markdown;
449
+ const name = rule?.shortDescription?.text || rule?.name || findingType;
450
+ const explanation = messageText(result, rule);
175
451
  if (!explanation)
176
452
  throw new Error("result is missing a resolvable explanation");
177
- bodies.push({
178
- metadata: {
179
- type: findingType,
180
- level: SARIF_TO_BEVOR_LEVEL[result.level ?? "warning"],
181
- name,
182
- explanation,
183
- },
184
- tool,
185
- location: locationFromResult(result),
186
- });
453
+ const body = {
454
+ location: locationFromResult(run, result),
455
+ type: findingType,
456
+ level: levelFromResult(result, rule),
457
+ name,
458
+ explanation,
459
+ };
460
+ const recommendation = recommendationFor(result, rule);
461
+ if (recommendation)
462
+ body.recommendation = recommendation;
463
+ const poc = bevorProps(result.properties).poc;
464
+ if (poc)
465
+ body.poc = poc;
466
+ bodies.push(body);
187
467
  }
188
468
  }
189
- return bodies;
469
+ if (tool === undefined)
470
+ throw new Error("SARIF log has no runs");
471
+ return { tool, findings: bodies };
190
472
  };
191
473
  //# sourceMappingURL=sarif.js.map