@trustify-da/trustify-da-javascript-client 0.3.0-ea.61444d4 → 0.3.0-ea.62b88e5

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 (59) hide show
  1. package/README.md +22 -8
  2. package/dist/package.json +6 -5
  3. package/dist/src/analysis.d.ts +40 -19
  4. package/dist/src/analysis.js +41 -5
  5. package/dist/src/cli.js +95 -17
  6. package/dist/src/config.d.ts +120 -0
  7. package/dist/src/config.js +260 -0
  8. package/dist/src/cyclone_dx_sbom.d.ts +13 -0
  9. package/dist/src/cyclone_dx_sbom.js +39 -1
  10. package/dist/src/index.d.ts +23 -23
  11. package/dist/src/index.js +23 -39
  12. package/dist/src/license/index.d.ts +2 -2
  13. package/dist/src/license/index.js +9 -6
  14. package/dist/src/license/licenses_api.d.ts +2 -2
  15. package/dist/src/license/licenses_api.js +1 -1
  16. package/dist/src/package_version.d.ts +8 -0
  17. package/dist/src/package_version.js +31 -0
  18. package/dist/src/providers/base_java.d.ts +53 -0
  19. package/dist/src/providers/base_java.js +64 -17
  20. package/dist/src/providers/base_javascript.d.ts +54 -0
  21. package/dist/src/providers/base_javascript.js +106 -4
  22. package/dist/src/providers/golang_gomodules.js +6 -5
  23. package/dist/src/providers/java_gradle.d.ts +48 -0
  24. package/dist/src/providers/java_gradle.js +204 -20
  25. package/dist/src/providers/java_maven.d.ts +28 -8
  26. package/dist/src/providers/java_maven.js +104 -10
  27. package/dist/src/providers/javascript_bun.d.ts +12 -0
  28. package/dist/src/providers/javascript_bun.js +42 -1
  29. package/dist/src/providers/javascript_npm.d.ts +13 -0
  30. package/dist/src/providers/javascript_npm.js +40 -1
  31. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  32. package/dist/src/providers/javascript_pnpm.js +47 -1
  33. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  34. package/dist/src/providers/javascript_yarn.js +75 -2
  35. package/dist/src/providers/manifest.js +6 -3
  36. package/dist/src/providers/processors/yarn_berry_processor.d.ts +5 -1
  37. package/dist/src/providers/processors/yarn_berry_processor.js +3 -2
  38. package/dist/src/providers/processors/yarn_classic_processor.d.ts +5 -1
  39. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  40. package/dist/src/providers/python_uv.js +6 -0
  41. package/dist/src/providers/requirements_parser.js +1 -1
  42. package/dist/src/providers/rust_cargo.js +34 -52
  43. package/dist/src/remediate.d.ts +90 -4
  44. package/dist/src/remediate.js +153 -58
  45. package/dist/src/remediation.d.ts +54 -30
  46. package/dist/src/remediation.js +92 -53
  47. package/dist/src/remediation_report.d.ts +3 -20
  48. package/dist/src/remediation_report.js +37 -16
  49. package/dist/src/sbom.d.ts +11 -0
  50. package/dist/src/sbom.js +10 -0
  51. package/dist/src/tools.d.ts +9 -11
  52. package/dist/src/tools.js +34 -13
  53. package/dist/src/updaters/maven_updater.d.ts +40 -8
  54. package/dist/src/updaters/maven_updater.js +26 -3
  55. package/dist/src/updaters/toml_updater.d.ts +42 -13
  56. package/dist/src/updaters/toml_updater.js +36 -4
  57. package/dist/src/workspace.d.ts +2 -1
  58. package/dist/src/workspace.js +2 -1
  59. package/package.json +7 -6
@@ -12,8 +12,8 @@ import Base_java, { ecosystem_gradle } from "./base_java.js";
12
12
  /** @typedef {import('../provider.js').Provider} */
13
13
  /** @typedef {import('../provider.js').Provided} Provided */
14
14
  const ROOT_PROJECT_KEY_NAME = "root-project";
15
- const TRUSTIFY_DA_IGNORE_REGEX_LINE = /.*\s?exhortignore\s*$/g;
16
- const TRUSTIFY_DA_IGNORE_REGEX = /\/\/\s?exhortignore/;
15
+ const TRUSTIFY_DA_IGNORE_REGEX_LINE = /.*\s?(exhortignore|trustify-da-ignore)\s*$/g;
16
+ const TRUSTIFY_DA_IGNORE_REGEX = /\/\/\s?(exhortignore|trustify-da-ignore)/;
17
17
  /**
18
18
  * Check if the dependency marked for exclusion has libs notation , so if it's true the rest of coordinates( GAV) should be fetched from TOML file.
19
19
  * @param {string} depToBeIgnored
@@ -59,7 +59,6 @@ export default class Java_gradle extends Base_java {
59
59
  * @param {string} manifestPath - path to manifest
60
60
  * @returns {null}
61
61
  */
62
- // eslint-disable-next-line no-unused-vars
63
62
  readLicenseFromManifest(manifestPath) { return readLicenseFile(manifestPath); }
64
63
  /**
65
64
  * Provide content and content type for stack analysis.
@@ -67,10 +66,10 @@ export default class Java_gradle extends Base_java {
67
66
  * @param {{}} [opts={}] - optional various options to pass along the application
68
67
  * @returns {Provided}
69
68
  */
70
- provideStack(manifest, opts = {}) {
69
+ async provideStack(manifest, opts = {}) {
71
70
  return {
72
71
  ecosystem: ecosystem_gradle,
73
- content: this.#createSbomStackAnalysis(manifest, opts),
72
+ content: await this.#createSbomStackAnalysis(manifest, opts),
74
73
  contentType: 'application/vnd.cyclonedx+json'
75
74
  };
76
75
  }
@@ -80,10 +79,10 @@ export default class Java_gradle extends Base_java {
80
79
  * @param {{}} [opts={}] - optional various options to pass along the application
81
80
  * @returns {Provided}
82
81
  */
83
- provideComponent(manifest, opts = {}) {
82
+ async provideComponent(manifest, opts = {}) {
84
83
  return {
85
84
  ecosystem: ecosystem_gradle,
86
- content: this.#getSbomForComponentAnalysis(manifest, opts),
85
+ content: await this.#getSbomForComponentAnalysis(manifest, opts),
87
86
  contentType: 'application/vnd.cyclonedx+json'
88
87
  };
89
88
  }
@@ -133,9 +132,10 @@ export default class Java_gradle extends Base_java {
133
132
  * @param {Sbom} sbom - the SBOM object to add dependencies to
134
133
  * @param {Set} processedDeps - set of already processed dependencies
135
134
  * @param {string} scope - the dependency scope
135
+ * @param {Map<string, Array<{alg: string, content: string}>>} [hashMap] - map of "group:name@version" to CycloneDX hashes
136
136
  * @private
137
137
  */
138
- #processDependencyTree(config, parentPurl, sbom, processedDeps, scope) {
138
+ #processDependencyTree(config, parentPurl, sbom, processedDeps, scope, hashMap) {
139
139
  const processedLines = this.#prepareLinesForParsingDependencyTree(config);
140
140
  let parentStack = [parentPurl];
141
141
  for (const { line, depth } of processedLines) {
@@ -153,12 +153,18 @@ export default class Java_gradle extends Base_java {
153
153
  // Add dependency to SBOM if not already processed
154
154
  if (!processedDeps.has(depKey)) {
155
155
  processedDeps.add(depKey);
156
- sbom.addDependency(currentParent, purl, scope);
156
+ sbom.addDependency(currentParent, purl, scope, hashMap?.get(purl.toString()));
157
157
  }
158
158
  parentStack.push(purl);
159
159
  }
160
160
  }
161
161
  }
162
+ #buildRootCoordinate(properties) {
163
+ const group = properties.group || 'unknown';
164
+ const version = properties.version || '0.0.0';
165
+ const rootName = properties[ROOT_PROJECT_KEY_NAME]?.match(/Root project '(.+)'/)?.[1] || 'unknown';
166
+ return `${group}:${rootName}:jar:${version}`;
167
+ }
162
168
  /**
163
169
  * Create a Dot Graph dependency tree for a manifest path.
164
170
  * @param {string} manifest - path for pom.xml
@@ -166,17 +172,17 @@ export default class Java_gradle extends Base_java {
166
172
  * @returns {string} the Dot Graph content
167
173
  * @private
168
174
  */
169
- #buildSbom(content, properties, manifestPath, opts = {}) {
175
+ #buildSbom(content, properties, manifestPath, opts = {}, hashMap) {
170
176
  let sbom = new Sbom();
171
- let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
177
+ let root = this.#buildRootCoordinate(properties);
172
178
  let rootPurl = this.parseDep(root);
173
179
  const license = this.readLicenseFromManifest(manifestPath);
174
180
  sbom.addRoot(rootPurl, license);
175
181
  let ignoredDeps = this.#getIgnoredDeps(manifestPath);
176
182
  const [runtimeConfig, compileConfig] = this.#extractConfigurations(content);
177
183
  const processedDeps = new Set();
178
- this.#processDependencyTree(runtimeConfig, rootPurl, sbom, processedDeps, 'required');
179
- this.#processDependencyTree(compileConfig, rootPurl, sbom, processedDeps, 'optional');
184
+ this.#processDependencyTree(runtimeConfig, rootPurl, sbom, processedDeps, 'required', hashMap);
185
+ this.#processDependencyTree(compileConfig, rootPurl, sbom, processedDeps, 'optional', hashMap);
180
186
  return sbom.filterIgnoredDepsIncludingVersion(ignoredDeps).getAsJsonString(opts);
181
187
  }
182
188
  /**
@@ -186,14 +192,15 @@ export default class Java_gradle extends Base_java {
186
192
  * @returns {string} the Dot Graph content
187
193
  * @private
188
194
  */
189
- #createSbomStackAnalysis(manifest, opts = {}) {
195
+ async #createSbomStackAnalysis(manifest, opts = {}) {
190
196
  let content = this.#getDependencies(manifest, opts);
191
197
  let properties = this.#extractProperties(manifest, opts);
198
+ let hashMap = await this.parseGradleHashes(manifest, opts);
192
199
  // read dependency tree from temp file
193
200
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
194
201
  console.log("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content);
195
202
  }
196
- let sbom = this.#buildSbom(content, properties, manifest, opts);
203
+ let sbom = this.#buildSbom(content, properties, manifest, opts, hashMap);
197
204
  return sbom;
198
205
  }
199
206
  /**
@@ -238,10 +245,11 @@ export default class Java_gradle extends Base_java {
238
245
  * @returns {string} - sbom string of the direct dependencies of build.gradle
239
246
  * @private
240
247
  */
241
- #getSbomForComponentAnalysis(manifestPath, opts = {}) {
248
+ async #getSbomForComponentAnalysis(manifestPath, opts = {}) {
242
249
  let content = this.#getDependencies(manifestPath, opts);
243
250
  let properties = this.#extractProperties(manifestPath, opts);
244
- let sbom = this.#buildDirectDependenciesSbom(content, properties, manifestPath, opts);
251
+ let hashMap = await this.parseGradleHashes(manifestPath, opts);
252
+ let sbom = this.#buildDirectDependenciesSbom(content, properties, manifestPath, opts, hashMap);
245
253
  return sbom;
246
254
  }
247
255
  /**
@@ -260,6 +268,112 @@ export default class Java_gradle extends Base_java {
260
268
  throw new Error(`Couldn't run gradle dependencies command, error message returned from gradle binary => ${EOL} ${error.message}`);
261
269
  }
262
270
  }
271
+ /**
272
+ * Hash a file using SHA-256 with streaming to handle large files efficiently.
273
+ * @param {string} filePath - path to the file to hash
274
+ * @returns {Promise<string>} hex-encoded SHA-256 digest
275
+ * @private
276
+ */
277
+ #hashFileStream(filePath) {
278
+ return new Promise((resolve, reject) => {
279
+ const hash = crypto.createHash('sha256');
280
+ const stream = fs.createReadStream(filePath);
281
+ stream.on('data', chunk => hash.update(chunk));
282
+ stream.on('end', () => resolve(hash.digest('hex')));
283
+ stream.on('error', reject);
284
+ });
285
+ }
286
+ /**
287
+ * Compute SHA-256 hashes for the resolved artifacts of a Gradle manifest.
288
+ *
289
+ * Rather than scanning the local Gradle cache, this asks Gradle itself for
290
+ * the resolved artifact files via an init script (mirroring the pattern used
291
+ * by {@link discoverGradleSubprojects}), then hashes each file with the
292
+ * Node.js `crypto` module. The result is keyed by the canonical PURL string
293
+ * built via {@link Base_java#toPurl} — the same builder {@link parseDep} uses
294
+ * for the lookup — so the stored key and the lookup key cannot drift.
295
+ *
296
+ * Degrades gracefully: if Gradle cannot be invoked, the init script fails, or
297
+ * an artifact has no readable file (e.g. BOM/`platform()` dependencies), the
298
+ * hash for that component is omitted rather than throwing. A warning is emitted
299
+ * on every degradation path so incomplete hash coverage is visible even without
300
+ * `TRUSTIFY_DA_DEBUG` (mirroring the pip/cargo providers).
301
+ *
302
+ * @param {string} manifest - path to build.gradle[.kts]
303
+ * @param {{}} [opts={}] - optional various options to pass along the application
304
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>} map of canonical PURL string to CycloneDX hashes
305
+ */
306
+ async parseGradleHashes(manifest, opts = {}) {
307
+ const hashMap = new Map();
308
+ const debug = process.env["TRUSTIFY_DA_DEBUG"] === "true";
309
+ let gradle;
310
+ try {
311
+ gradle = this.selectToolBinary(manifest, opts);
312
+ }
313
+ catch (error) {
314
+ console.warn(`Gradle could not be invoked to compute artifact hashes, SBOM will be generated without hashes: ${error.stack || error.message}`);
315
+ return hashMap;
316
+ }
317
+ const initScriptPath = path.join(os.tmpdir(), `da-list-hashes-${crypto.randomUUID()}.gradle`);
318
+ try {
319
+ fs.writeFileSync(initScriptPath, GRADLE_HASH_INIT_SCRIPT);
320
+ let output;
321
+ try {
322
+ output = this._invokeCommand(gradle, [
323
+ '-q', '--no-daemon',
324
+ '--init-script', initScriptPath,
325
+ 'daListHashes',
326
+ ], { cwd: path.dirname(manifest) });
327
+ }
328
+ catch (error) {
329
+ console.warn(`Gradle hash init script failed, SBOM will be generated without hashes: ${error.stack || error.message}`);
330
+ return hashMap;
331
+ }
332
+ let attempted = 0;
333
+ let missed = 0;
334
+ for (const { id, file } of parseGradleHashScriptOutput(output.toString())) {
335
+ const coord = parseComponentId(id);
336
+ if (!coord) {
337
+ continue;
338
+ }
339
+ // Build the key with the same canonical PURL builder parseDep uses for
340
+ // the lookup, so the stored key and the lookup key cannot drift.
341
+ const key = this.toPurl(coord.group, coord.name, coord.version).toString();
342
+ if (hashMap.has(key)) {
343
+ continue;
344
+ }
345
+ attempted++;
346
+ try {
347
+ const digest = await this.#hashFileStream(file);
348
+ hashMap.set(key, [{ alg: 'SHA-256', content: digest }]);
349
+ }
350
+ catch (error) {
351
+ // artifact file missing/unreadable — omit the hash for this component
352
+ missed++;
353
+ if (debug) {
354
+ console.error(`Gradle hash: could not read artifact ${file} => ${error.message}`);
355
+ }
356
+ }
357
+ }
358
+ if (missed > 0) {
359
+ console.warn(`Gradle hash: ${missed} of ${attempted} resolved artifacts could not be read, SBOM will be generated without hashes for those components`);
360
+ }
361
+ }
362
+ catch (error) {
363
+ // Unexpected failure (e.g. a programming error) is degraded to keep SBOM
364
+ // generation working, but the error is surfaced so it is not mistaken
365
+ // for ordinary graceful degradation.
366
+ console.warn(`Gradle artifact hashing failed, SBOM will be generated without hashes: ${error.stack || error.message}`);
367
+ return hashMap;
368
+ }
369
+ finally {
370
+ try {
371
+ fs.unlinkSync(initScriptPath);
372
+ }
373
+ catch { /* ignore */ }
374
+ }
375
+ return hashMap;
376
+ }
263
377
  /**
264
378
  * Extracts runtime and compile configurations from the dependency tree
265
379
  * @param {string} content - the dependency tree content
@@ -307,9 +421,9 @@ export default class Java_gradle extends Base_java {
307
421
  * @param properties {Object} - properties of the gradle project.
308
422
  * @return {string} return sbom json string of the build.gradle manifest file
309
423
  */
310
- #buildDirectDependenciesSbom(content, properties, manifestPath, opts = {}) {
424
+ #buildDirectDependenciesSbom(content, properties, manifestPath, opts = {}, hashMap) {
311
425
  let sbom = new Sbom();
312
- let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
426
+ let root = this.#buildRootCoordinate(properties);
313
427
  let rootPurl = this.parseDep(root);
314
428
  const license = this.readLicenseFromManifest(manifestPath);
315
429
  sbom.addRoot(rootPurl, license);
@@ -321,7 +435,7 @@ export default class Java_gradle extends Base_java {
321
435
  directDependencies.forEach((scope, dep) => {
322
436
  const purl = this.parseDep(dep);
323
437
  purl.scope = scope;
324
- sbom.addDependency(rootPurl, purl, scope);
438
+ sbom.addDependency(rootPurl, purl, scope, hashMap?.get(purl.toString()));
325
439
  });
326
440
  return sbom.filterIgnoredDepsIncludingVersion(ignoredDeps).getAsJsonString(opts);
327
441
  }
@@ -424,6 +538,29 @@ const GRADLE_INIT_SCRIPT = `allprojects {
424
538
  }
425
539
  }
426
540
  `;
541
+ /**
542
+ * Gradle init script that emits, per resolved module artifact, a structured line
543
+ * of the form `::DA_HASH::group:name:version::/absolute/file/path`. It obtains
544
+ * files from Gradle's resolution API (the same approach as the CycloneDX Gradle
545
+ * plugin) so it is robust to cache-layout changes and correctly reports
546
+ * classifiers and non-jar artifacts. Uses a lenient artifact view so
547
+ * unresolved/fileless artifacts are skipped rather than failing the build.
548
+ */
549
+ const GRADLE_HASH_INIT_SCRIPT = `allprojects {
550
+ task daListHashes {
551
+ doLast {
552
+ configurations.findAll { it.canBeResolved }.each { cfg ->
553
+ cfg.incoming.artifactView { lenient = true }.artifacts.each { artifact ->
554
+ def cid = artifact.id.componentIdentifier
555
+ if (cid instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier) {
556
+ println "::DA_HASH::\${cid.group}:\${cid.module}:\${cid.version}::\${artifact.file.absolutePath}"
557
+ }
558
+ }
559
+ }
560
+ }
561
+ }
562
+ }
563
+ `;
427
564
  /**
428
565
  * Discover all build.gradle[.kts] manifest paths in a Gradle multi-project build.
429
566
  * Uses a custom init script to get structured project listing.
@@ -521,3 +658,50 @@ export function parseGradleInitScriptOutput(raw) {
521
658
  }
522
659
  return projects;
523
660
  }
661
+ /**
662
+ * Parse the structured output from the Gradle hash init script.
663
+ * Each recognised line has the form `::DA_HASH::group:name:version::<file-path>`.
664
+ *
665
+ * @param {string} raw - Raw stdout from gradle
666
+ * @returns {{ id: string, file: string }[]} component id (`group:name:version`) and absolute artifact file path
667
+ */
668
+ export function parseGradleHashScriptOutput(raw) {
669
+ const artifacts = [];
670
+ for (const rawLine of raw.split('\n')) {
671
+ const line = rawLine.trimEnd();
672
+ if (!line.startsWith('::DA_HASH::')) {
673
+ continue;
674
+ }
675
+ const prefix = '::DA_HASH::';
676
+ const remainder = line.substring(prefix.length);
677
+ const lastSep = remainder.lastIndexOf('::');
678
+ if (lastSep < 0) {
679
+ continue;
680
+ }
681
+ const id = remainder.substring(0, lastSep);
682
+ const file = remainder.substring(lastSep + 2);
683
+ if (id && file) {
684
+ artifacts.push({ id, file });
685
+ }
686
+ }
687
+ return artifacts;
688
+ }
689
+ /**
690
+ * Parse a Gradle module component id (`group:name:version`) into its coordinate
691
+ * parts. The caller builds the canonical PURL key from these parts using the same
692
+ * builder {@link parseDep} uses, so the stored key and the lookup key cannot drift.
693
+ *
694
+ * @param {string} id - the Gradle component id
695
+ * @returns {{group: string, name: string, version: string}|null} the parsed coordinate, or null when the id is malformed
696
+ */
697
+ export function parseComponentId(id) {
698
+ const parts = id.split(':');
699
+ if (parts.length < 3) {
700
+ return null;
701
+ }
702
+ const [group, name, version] = parts;
703
+ if (!group || !name || !version) {
704
+ return null;
705
+ }
706
+ return { group, name, version };
707
+ }
@@ -6,11 +6,11 @@
6
6
  * @returns {Promise<string[]>} Paths to pom.xml files (absolute)
7
7
  */
8
8
  export function discoverMavenModules(workspaceRoot: string, opts?: object): Promise<string[]>;
9
- /** @typedef {import('../provider').Provider} */
10
- /** @typedef {import('../provider').Provided} Provided */
11
- /** @typedef {{name: string, version: string}} Package */
12
- /** @typedef {{groupId: string, artifactId: string, version: string, scope: string, ignore: boolean}} Dependency */
13
9
  export default class Java_maven extends Base_java {
10
+ /** @type {Object<string, string>} Packaging types that produce .jar files despite non-jar packaging names. */
11
+ static PACKAGING_TO_JAR: {
12
+ [x: string]: string;
13
+ };
14
14
  constructor();
15
15
  /**
16
16
  * @param {string} manifestName - the subject manifest name-type
@@ -25,9 +25,9 @@ export default class Java_maven extends Base_java {
25
25
  * Provide content and content type for maven-maven stack analysis.
26
26
  * @param {string} manifest - the manifest path or name
27
27
  * @param {{}} [opts={}] - optional various options to pass along the application
28
- * @returns {Provided}
28
+ * @returns {Promise<Provided>}
29
29
  */
30
- provideStack(manifest: string, opts?: {}): Provided;
30
+ provideStack(manifest: string, opts?: {}): Promise<Provided>;
31
31
  /**
32
32
  * Provide content and content type for maven-maven component analysis.
33
33
  * @param {string} manifest - path to the manifest file
@@ -42,16 +42,36 @@ export default class Java_maven extends Base_java {
42
42
  */
43
43
  readLicenseFromManifest(manifestPath: string): string | null;
44
44
  /**
45
+ * Build a Map of PURL string → CycloneDX hash entries by reading artifact files from the local Maven repository.
46
+ *
47
+ * Both the artifact file path and the hash-map key are derived from the
48
+ * shared {@link Base_java#parseCoordinate} parser: the file path uses the
49
+ * resolved version and raw classifier, while the key uses the same canonical
50
+ * PURL builder as {@link Base_java#parseDep}. This guarantees the key always
51
+ * matches the PURL that {@link Base_java#parseDependencyTree} looks up.
45
52
  *
53
+ * @param {string} depTreeText Raw dependency tree text from mvn dependency:tree
54
+ * @param {{}} [opts={}] Options bag (may contain TRUSTIFY_DA_MVN_REPO)
55
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>}
56
+ */
57
+ _buildMavenHashMap(depTreeText: string, opts?: {}): Promise<Map<string, Array<{
58
+ alg: string;
59
+ content: string;
60
+ }>>>;
61
+ /**
46
62
  * @param {String} textGraphList Text graph String of the manifest
47
63
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
64
+ * @param {{}} opts Options
48
65
  * @param {String} manifestPath Path to the pom.xml manifest
66
+ * @param {Map<string, Array<{alg: string, content: string}>>} [hashMap] PURL→hashes map
49
67
  * @return {String} formatted sbom Json String with all dependencies
50
68
  */
51
- createSbomFileFromTextFormat(textGraphList: string, ignoredDeps: [string], opts: any, manifestPath: string): string;
69
+ createSbomFileFromTextFormat(textGraphList: string, ignoredDeps: [string], opts: {}, manifestPath: string, hashMap?: Map<string, Array<{
70
+ alg: string;
71
+ content: string;
72
+ }>>): string;
52
73
  #private;
53
74
  }
54
- export type Java_maven = any;
55
75
  export type Provided = any;
56
76
  export type Package = {
57
77
  name: string;
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
@@ -12,6 +13,10 @@ import Base_java, { ecosystem_maven } from "./base_java.js";
12
13
  /** @typedef {import('../provider').Provided} Provided */
13
14
  /** @typedef {{name: string, version: string}} Package */
14
15
  /** @typedef {{groupId: string, artifactId: string, version: string, scope: string, ignore: boolean}} Dependency */
16
+ // Matches the legacy `exhortignore` and new `trustify-da-ignore` markers as whole
17
+ // tokens. The trailing `(?![\w-])` boundary prevents lookalikes such as
18
+ // `trustify-da-ignore-disabled` from being treated as ignore directives.
19
+ const IGNORE_MARKER_REGEX = /(exhortignore|trustify-da-ignore)(?![\w-])/;
15
20
  export default class Java_maven extends Base_java {
16
21
  constructor() {
17
22
  super('mvn', 'mvnw' + (process.platform === 'win32' ? '.cmd' : ''));
@@ -31,12 +36,12 @@ export default class Java_maven extends Base_java {
31
36
  * Provide content and content type for maven-maven stack analysis.
32
37
  * @param {string} manifest - the manifest path or name
33
38
  * @param {{}} [opts={}] - optional various options to pass along the application
34
- * @returns {Provided}
39
+ * @returns {Promise<Provided>}
35
40
  */
36
- provideStack(manifest, opts = {}) {
41
+ async provideStack(manifest, opts = {}) {
37
42
  return {
38
43
  ecosystem: ecosystem_maven,
39
- content: this.#createSbomStackAnalysis(manifest, opts),
44
+ content: await this.#createSbomStackAnalysis(manifest, opts),
40
45
  contentType: 'application/vnd.cyclonedx+json'
41
46
  };
42
47
  }
@@ -81,10 +86,10 @@ export default class Java_maven extends Base_java {
81
86
  * Create a Dot Graph dependency tree for a manifest path.
82
87
  * @param {string} manifest - path for pom.xml
83
88
  * @param {{}} [opts={}] - optional various options to pass along the application
84
- * @returns {string} the Dot Graph content
89
+ * @returns {Promise<string>} the Dot Graph content
85
90
  * @private
86
91
  */
87
- #createSbomStackAnalysis(manifest, opts = {}) {
92
+ async #createSbomStackAnalysis(manifest, opts = {}) {
88
93
  const manifestDir = path.dirname(manifest);
89
94
  const mvn = this.selectToolBinary(manifest, opts);
90
95
  const mvnArgs = JSON.parse(getCustom('TRUSTIFY_DA_MVN_ARGS', '[]', opts));
@@ -131,20 +136,105 @@ export default class Java_maven extends Base_java {
131
136
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
132
137
  console.error("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content.toString());
133
138
  }
134
- let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts, manifest);
139
+ const depTreeContent = content.toString();
140
+ const hashMap = await this._buildMavenHashMap(depTreeContent, opts);
141
+ let sbom = this.createSbomFileFromTextFormat(depTreeContent, ignoredDeps, opts, manifest, hashMap);
135
142
  // delete temp file and directory
136
143
  fs.rmSync(tmpDir, { recursive: true, force: true });
137
144
  // return dependency graph as string
138
145
  return sbom;
139
146
  }
147
+ /** @type {Object<string, string>} Packaging types that produce .jar files despite non-jar packaging names. */
148
+ static PACKAGING_TO_JAR = { 'bundle': 'jar', 'eclipse-plugin': 'jar' };
140
149
  /**
150
+ * Build a Map of PURL string → CycloneDX hash entries by reading artifact files from the local Maven repository.
151
+ *
152
+ * Both the artifact file path and the hash-map key are derived from the
153
+ * shared {@link Base_java#parseCoordinate} parser: the file path uses the
154
+ * resolved version and raw classifier, while the key uses the same canonical
155
+ * PURL builder as {@link Base_java#parseDep}. This guarantees the key always
156
+ * matches the PURL that {@link Base_java#parseDependencyTree} looks up.
141
157
  *
158
+ * @param {string} depTreeText Raw dependency tree text from mvn dependency:tree
159
+ * @param {{}} [opts={}] Options bag (may contain TRUSTIFY_DA_MVN_REPO)
160
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>}
161
+ */
162
+ async _buildMavenHashMap(depTreeText, opts = {}) {
163
+ const m2Repo = getCustom('TRUSTIFY_DA_MVN_REPO', path.join(os.homedir(), '.m2', 'repository'), opts);
164
+ const hashMap = new Map();
165
+ const lines = depTreeText.split(EOL);
166
+ // Track hash coverage so an incomplete .m2 cache (e.g. ephemeral CI
167
+ // containers or resolve-only phases) surfaces a summary warning instead
168
+ // of silently producing an SBOM with missing hashes.
169
+ let attempted = 0;
170
+ let missed = 0;
171
+ for (const rawLine of lines) {
172
+ const trimmed = rawLine.trim();
173
+ // Strip leading tree-drawing characters (e.g. "\-", "+-", "|") so the
174
+ // parenthesized-line check sees the coordinate itself. Omitted
175
+ // duplicate/conflict lines start with these characters after trim(),
176
+ // then an opening "(" — without stripping, the "(" check never fires.
177
+ const cleaned = trimmed.replace(/^[|+\\\- ]+/, '');
178
+ if (!cleaned || cleaned.startsWith('(')) {
179
+ continue;
180
+ }
181
+ const coord = this.parseCoordinate(rawLine);
182
+ if (!coord.groupId || !coord.artifactId || !coord.packaging) {
183
+ continue;
184
+ }
185
+ if (coord.packaging === 'pom') {
186
+ continue;
187
+ }
188
+ // Key by the exact PURL parseDep() produces, so the lookup in
189
+ // parseDependencyTree (hashMap.get(to.toString())) always hits.
190
+ const purl = this._coordinateToPurl(coord).toString();
191
+ // The same artifact recurs across dependency-tree branches — notably in
192
+ // multi-module reactor builds, where every module re-lists shared deps.
193
+ // The digest is deterministic per PURL, so skip the redundant file read
194
+ // and SHA-256 computation once this PURL is already hashed.
195
+ if (hashMap.has(purl)) {
196
+ continue;
197
+ }
198
+ const ext = Java_maven.PACKAGING_TO_JAR[coord.packaging] || coord.packaging;
199
+ const groupPath = coord.groupId.replaceAll('.', path.sep);
200
+ const fileName = coord.classifier
201
+ ? `${coord.artifactId}-${coord.version}-${coord.classifier}.${ext}`
202
+ : `${coord.artifactId}-${coord.version}.${ext}`;
203
+ const artifactPath = path.join(m2Repo, groupPath, coord.artifactId, coord.version, fileName);
204
+ attempted++;
205
+ try {
206
+ const stream = fs.createReadStream(artifactPath);
207
+ const hash = crypto.createHash('sha256');
208
+ for await (const chunk of stream) {
209
+ hash.update(chunk);
210
+ }
211
+ const digest = hash.digest('hex');
212
+ hashMap.set(purl, [{ alg: 'SHA-256', content: digest }]);
213
+ }
214
+ catch {
215
+ missed++;
216
+ if (process.env['TRUSTIFY_DA_DEBUG'] === 'true') {
217
+ console.error(`Maven hash: artifact not found at ${artifactPath}, omitting hash`);
218
+ }
219
+ }
220
+ }
221
+ // Mirror the pip provider's convention (python_controller.js): surface an
222
+ // unconditional warning when hashes could not be computed, so incomplete
223
+ // hash coverage is visible even without TRUSTIFY_DA_DEBUG.
224
+ if (missed > 0) {
225
+ console.warn(`Maven hash: ${missed} of ${attempted} artifacts could not be read from the local .m2 cache; SBOM will be generated without hashes for those components.`);
226
+ }
227
+ return hashMap;
228
+ }
229
+ /**
142
230
  * @param {String} textGraphList Text graph String of the manifest
143
231
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
232
+ * @param {{}} opts Options
144
233
  * @param {String} manifestPath Path to the pom.xml manifest
234
+ * @param {Map<string, Array<{alg: string, content: string}>>} [hashMap] PURL→hashes map
145
235
  * @return {String} formatted sbom Json String with all dependencies
146
236
  */
147
- createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath) {
237
+ createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath, hashMap) {
148
238
  let lines = textGraphList.split(EOL);
149
239
  // get root component
150
240
  let root = lines[0];
@@ -153,6 +243,9 @@ export default class Java_maven extends Base_java {
153
243
  let sbom = new Sbom();
154
244
  sbom.addRoot(rootPurl, license);
155
245
  this.parseDependencyTree(root, 0, lines.slice(1), sbom);
246
+ // Attach Maven artifact hashes as a post-processing step, keeping this
247
+ // Maven-specific concern out of the shared dependency-tree parser.
248
+ sbom.attachHashes(hashMap);
156
249
  return sbom.filterIgnoredDeps(ignoredDeps).getAsJsonString(opts);
157
250
  }
158
251
  /**
@@ -229,7 +322,8 @@ export default class Java_maven extends Base_java {
229
322
  return rootDependency;
230
323
  }
231
324
  /**
232
- * Get a list of dependencies with marking of dependencies commented with <!--exhortignore-->.
325
+ * Get a list of dependencies with marking of dependencies commented with
326
+ * <!--exhortignore--> or <!--trustify-da-ignore-->.
233
327
  * @param {string} manifest - path for pom.xml
234
328
  * @returns {[Dependency]} an array of dependencies
235
329
  * @private
@@ -247,7 +341,7 @@ export default class Java_maven extends Base_java {
247
341
  let buf = fs.readFileSync(manifest);
248
342
  // parse manifest pom.xml to json
249
343
  let pomJson = parser.parse(buf.toString());
250
- // iterate over all dependencies and chery pick dependencies with a exhortignore comment
344
+ // iterate over all dependencies and chery pick dependencies with an ignore comment
251
345
  let pomXml;
252
346
  // project without modules
253
347
  if (pomJson['project']) {
@@ -263,7 +357,7 @@ export default class Java_maven extends Base_java {
263
357
  }
264
358
  pomXml.forEach(dep => {
265
359
  let ignore = false;
266
- if (dep['#comment'] && dep['#comment'].includes('exhortignore')) { // #comment is an array or a string
360
+ if (dep['#comment'] && [].concat(dep['#comment']).some(comment => IGNORE_MARKER_REGEX.test(comment))) { // #comment is an array or a string
267
361
  ignore = true;
268
362
  }
269
363
  if (dep['scope'] !== 'test') {
@@ -1,4 +1,16 @@
1
1
  export default class Javascript_bun extends Base_javascript {
2
+ /**
3
+ * Parses `bun.lock` into a hash map keyed by `name@version`. Each entry in
4
+ * the `packages` section is an array whose first element is the resolved id
5
+ * (`name@version`) and whose fourth element is the SRI integrity string.
6
+ * @param {string} lockDir - Directory containing bun.lock
7
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
8
+ * @protected
9
+ */
10
+ protected _parseLockFileHashes(lockDir: string): Map<string, Array<{
11
+ alg: string;
12
+ content: string;
13
+ }>>;
2
14
  _listCmdArgs(): void;
3
15
  _buildDependencyTree(includeTransitive: any, opts?: {}): {
4
16
  name: any;