@trustify-da/trustify-da-javascript-client 0.3.0-ea.ec6824b → 0.3.0-ea.efdc87d

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 (66) hide show
  1. package/README.md +199 -11
  2. package/dist/package.json +15 -10
  3. package/dist/src/analysis.d.ts +47 -19
  4. package/dist/src/analysis.js +70 -18
  5. package/dist/src/cli.js +188 -6
  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 +27 -22
  11. package/dist/src/index.js +27 -38
  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/oci_image/images.js +15 -1
  17. package/dist/src/package_version.d.ts +8 -0
  18. package/dist/src/package_version.js +31 -0
  19. package/dist/src/provider.js +3 -1
  20. package/dist/src/providers/base_java.d.ts +53 -0
  21. package/dist/src/providers/base_java.js +64 -17
  22. package/dist/src/providers/base_javascript.d.ts +54 -0
  23. package/dist/src/providers/base_javascript.js +106 -4
  24. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  25. package/dist/src/providers/containerfile_parser.js +20 -0
  26. package/dist/src/providers/golang_gomodules.js +49 -7
  27. package/dist/src/providers/java_gradle.d.ts +48 -0
  28. package/dist/src/providers/java_gradle.js +196 -18
  29. package/dist/src/providers/java_maven.d.ts +28 -8
  30. package/dist/src/providers/java_maven.js +104 -10
  31. package/dist/src/providers/javascript_bun.d.ts +12 -0
  32. package/dist/src/providers/javascript_bun.js +42 -1
  33. package/dist/src/providers/javascript_npm.d.ts +13 -0
  34. package/dist/src/providers/javascript_npm.js +40 -1
  35. package/dist/src/providers/javascript_pnpm.d.ts +13 -0
  36. package/dist/src/providers/javascript_pnpm.js +47 -1
  37. package/dist/src/providers/javascript_yarn.d.ts +12 -0
  38. package/dist/src/providers/javascript_yarn.js +75 -2
  39. package/dist/src/providers/manifest.js +6 -3
  40. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  41. package/dist/src/providers/oci_dockerfile.js +177 -0
  42. package/dist/src/providers/processors/yarn_berry_processor.d.ts +5 -1
  43. package/dist/src/providers/processors/yarn_berry_processor.js +3 -2
  44. package/dist/src/providers/processors/yarn_classic_processor.d.ts +5 -1
  45. package/dist/src/providers/processors/yarn_classic_processor.js +8 -6
  46. package/dist/src/providers/python_controller.js +4 -1
  47. package/dist/src/providers/requirements_parser.js +1 -1
  48. package/dist/src/providers/rust_cargo.js +70 -29
  49. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  50. package/dist/src/remediate.d.ts +120 -0
  51. package/dist/src/remediate.js +253 -0
  52. package/dist/src/remediation.d.ts +58 -0
  53. package/dist/src/remediation.js +425 -0
  54. package/dist/src/remediation_report.d.ts +40 -0
  55. package/dist/src/remediation_report.js +159 -0
  56. package/dist/src/sbom.d.ts +11 -0
  57. package/dist/src/sbom.js +10 -0
  58. package/dist/src/tools.d.ts +9 -11
  59. package/dist/src/tools.js +34 -13
  60. package/dist/src/updaters/maven_updater.d.ts +58 -0
  61. package/dist/src/updaters/maven_updater.js +345 -0
  62. package/dist/src/updaters/toml_updater.d.ts +62 -0
  63. package/dist/src/updaters/toml_updater.js +276 -0
  64. package/dist/src/workspace.d.ts +2 -1
  65. package/dist/src/workspace.js +2 -1
  66. package/package.json +16 -11
@@ -12,6 +12,49 @@ import Manifest from './manifest.js';
12
12
  * @type {string}
13
13
  */
14
14
  export const purlType = 'npm';
15
+ /**
16
+ * Maps a Subresource Integrity (SRI) algorithm token to its CycloneDX label.
17
+ * @type {Object<string, string>}
18
+ */
19
+ const SRI_ALG_LABELS = {
20
+ sha1: 'SHA-1',
21
+ sha256: 'SHA-256',
22
+ sha384: 'SHA-384',
23
+ sha512: 'SHA-512',
24
+ };
25
+ /**
26
+ * Converts a Subresource Integrity (SRI) string to a CycloneDX hash object.
27
+ * SRI is formatted as `<alg>-<base64>` (e.g. `sha512-Ab3d...`). CycloneDX
28
+ * expects an uppercased algorithm label (e.g. `SHA-512`) and a hex-encoded
29
+ * digest. When the SRI string contains multiple space-separated hashes, only
30
+ * the first is used.
31
+ * @param {string} integrity - SRI string from a lock file
32
+ * @returns {{alg: string, content: string}|null} CycloneDX hash, or null when unparseable
33
+ */
34
+ export function sriToHash(integrity) {
35
+ if (typeof integrity !== 'string') {
36
+ return null;
37
+ }
38
+ const first = integrity.trim().split(/\s+/)[0];
39
+ if (!first) {
40
+ return null;
41
+ }
42
+ const dash = first.indexOf('-');
43
+ if (dash < 0) {
44
+ return null;
45
+ }
46
+ const alg = SRI_ALG_LABELS[first.slice(0, dash).toLowerCase()];
47
+ // Strip any SRI options (e.g. "?foo") that may follow the base64 payload
48
+ const base64 = first.slice(dash + 1).split('?')[0];
49
+ if (!alg || !base64) {
50
+ return null;
51
+ }
52
+ const content = Buffer.from(base64, 'base64').toString('hex');
53
+ if (!content) {
54
+ return null;
55
+ }
56
+ return { alg, content };
57
+ }
15
58
  /**
16
59
  * Base class for JavaScript package manager providers.
17
60
  * This class provides common functionality for different JavaScript package managers
@@ -25,6 +68,11 @@ export default class Base_javascript {
25
68
  #cmd;
26
69
  /** @type {string} */
27
70
  #ecosystem;
71
+ /**
72
+ * Lock-file hashes keyed by `name@version`.
73
+ * @type {Map<string, Array<{alg: string, content: string}>>}
74
+ */
75
+ #hashes = new Map();
28
76
  /**
29
77
  * Sets up the provider with the manifest path and options
30
78
  * @param {string} manifestPath - Path to the package.json manifest file
@@ -95,6 +143,58 @@ export default class Base_javascript {
95
143
  _updateLockFileCmdArgs() {
96
144
  throw new TypeError("_updateLockFileCmdArgs must be implemented");
97
145
  }
146
+ /**
147
+ * Parses the provider's lock file into a hash map keyed by `name@version`.
148
+ * Subclasses override this (accepting the lock directory) to support their
149
+ * lock file format. The default implementation returns an empty map so
150
+ * providers without lock parsing (or without a lock file present) gracefully
151
+ * omit hashes.
152
+ * @returns {Map<string, Array<{alg: string, content: string}>>} Hash map
153
+ * @protected
154
+ */
155
+ _parseLockFileHashes() {
156
+ return new Map();
157
+ }
158
+ /**
159
+ * Loads lock-file hashes for the given directory into internal state.
160
+ * Parsing failures degrade gracefully to an empty map (no hashes emitted).
161
+ * @param {string} lockDir - Directory containing the lock file
162
+ * @protected
163
+ */
164
+ _loadHashes(lockDir) {
165
+ try {
166
+ this.#hashes = this._parseLockFileHashes(lockDir) || new Map();
167
+ }
168
+ catch (_) {
169
+ this.#hashes = new Map();
170
+ }
171
+ }
172
+ /**
173
+ * Looks up CycloneDX hashes for a package by name and resolved version.
174
+ * @param {string} name - The package name (including scope, e.g. `@hapi/joi`)
175
+ * @param {string} version - The resolved package version
176
+ * @returns {Array<{alg: string, content: string}>|undefined} Hashes, or undefined
177
+ * @protected
178
+ */
179
+ _hashesFor(name, version) {
180
+ if (!name || !version) {
181
+ return undefined;
182
+ }
183
+ return this.#hashes.get(`${name}@${version}`);
184
+ }
185
+ /**
186
+ * Looks up CycloneDX hashes for a package described by a PackageURL.
187
+ * @param {PackageURL} purl - The package URL
188
+ * @returns {Array<{alg: string, content: string}>|undefined} Hashes, or undefined
189
+ * @protected
190
+ */
191
+ _hashesForPurl(purl) {
192
+ if (!purl) {
193
+ return undefined;
194
+ }
195
+ const name = purl.namespace ? `${purl.namespace}/${purl.name}` : purl.name;
196
+ return this._hashesFor(name, purl.version);
197
+ }
98
198
  /**
99
199
  * Checks if the provider supports the given manifest name
100
200
  * @param {string} manifestName - The manifest name to check
@@ -225,6 +325,7 @@ export default class Base_javascript {
225
325
  const manifestDir = path.dirname(this.#manifest.manifestPath);
226
326
  const cmdDir = this._findLockFileDir(manifestDir, opts) || manifestDir;
227
327
  this._createLockFile(cmdDir);
328
+ this._loadHashes(cmdDir);
228
329
  let output = this.#executeListCmd(includeTransitive, cmdDir);
229
330
  output = this._parseDepTreeOutput(output);
230
331
  return JSON.parse(output);
@@ -284,7 +385,7 @@ export default class Base_javascript {
284
385
  const [name, artifact] = entry;
285
386
  const target = toPurl(purlType, name, artifact.version);
286
387
  const rootPurl = toPurl(purlType, this.#manifest.name, this.#manifest.version);
287
- sbom.addDependency(rootPurl, target);
388
+ sbom.addDependency(rootPurl, target, undefined, this._hashesFor(name, artifact.version));
288
389
  this.#addDependenciesOf(sbom, target, artifact);
289
390
  });
290
391
  }
@@ -302,7 +403,7 @@ export default class Base_javascript {
302
403
  const [name, depArtifact] = entry;
303
404
  if (depArtifact.version !== undefined) {
304
405
  const target = toPurl(purlType, name, depArtifact.version);
305
- sbom.addDependency(from, target);
406
+ sbom.addDependency(from, target, undefined, this._hashesFor(name, depArtifact.version));
306
407
  this.#addDependenciesOf(sbom, target, depArtifact);
307
408
  }
308
409
  });
@@ -326,7 +427,8 @@ export default class Base_javascript {
326
427
  .sort();
327
428
  for (const key of sortedDepsKeys) {
328
429
  const rootPurl = toPurlFromString(sbom.getRoot().purl);
329
- sbom.addDependency(rootPurl, rootDeps.get(key));
430
+ const targetPurl = rootDeps.get(key);
431
+ sbom.addDependency(rootPurl, targetPurl, undefined, this._hashesForPurl(targetPurl));
330
432
  }
331
433
  this.#ensurePeerAndOptionalDeps(sbom);
332
434
  sbom.filterIgnoredDeps(this.#manifest.ignored);
@@ -430,7 +532,7 @@ export default class Base_javascript {
430
532
  }
431
533
  }
432
534
  // Try to find the command in the following order:
433
- // 1. Custom path from environment/opts (via getCustomPath)
535
+ // 1. Custom path from opts/environment (via getCustomPath)
434
536
  // 2. Local node_modules/.bin
435
537
  // 3. Global installation
436
538
  let cmd = this.#cmd;
@@ -0,0 +1,5 @@
1
+ export function getParser(): Promise<Parser>;
2
+ export function getFromQuery(): Promise<Query>;
3
+ export function getArgQuery(): Promise<Query>;
4
+ import { Parser } from 'web-tree-sitter';
5
+ import { Query } from 'web-tree-sitter';
@@ -0,0 +1,20 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { Language, Parser, Query } from 'web-tree-sitter';
3
+ const wasmUrl = new URL('./tree-sitter-containerfile.wasm', import.meta.url);
4
+ async function init() {
5
+ await Parser.init();
6
+ const wasmBytes = new Uint8Array(await readFile(wasmUrl));
7
+ return await Language.load(wasmBytes);
8
+ }
9
+ export async function getParser() {
10
+ const language = await init();
11
+ return new Parser().setLanguage(language);
12
+ }
13
+ export async function getFromQuery() {
14
+ const language = await init();
15
+ return new Query(language, '(from_instruction (image_spec) @image)');
16
+ }
17
+ export async function getArgQuery() {
18
+ const language = await init();
19
+ return new Query(language, '(arg_instruction (arg_pair name: (_) @name default: (_) @default))');
20
+ }
@@ -78,9 +78,10 @@ function getChildVertexFromEdge(edge) {
78
78
  return edge.split(" ")[1];
79
79
  }
80
80
  /**
81
- * Check whether a require_spec has a valid exhortignore marker.
82
- * For direct dependencies: `//exhortignore` or `// exhortignore`
83
- * For indirect dependencies: `// indirect; exhortignore` (semicolon-separated)
81
+ * Check whether a require_spec has a valid ignore marker.
82
+ * Supports both the legacy `exhortignore` marker and the new `trustify-da-ignore` marker.
83
+ * For direct dependencies: `//exhortignore` or `// trustify-da-ignore`
84
+ * For indirect dependencies: `// indirect; exhortignore` or `// indirect; trustify-da-ignore` (semicolon-separated)
84
85
  * @param {import('web-tree-sitter').SyntaxNode} specNode
85
86
  * @return {boolean}
86
87
  */
@@ -92,10 +93,10 @@ function hasExhortIgnore(specNode) {
92
93
  let comments = specNode.children.filter(c => c.type === 'comment');
93
94
  for (let comment of comments) {
94
95
  let text = comment.text;
95
- if (/^\/\/\s*indirect;\s*exhortignore/.test(text)) {
96
+ if (/^\/\/\s*indirect;\s*(exhortignore|trustify-da-ignore)(?![\w-])/.test(text)) {
96
97
  return true;
97
98
  }
98
- if (/^\/\/\s*exhortignore/.test(text)) {
99
+ if (/^\/\/\s*(exhortignore|trustify-da-ignore)(?![\w-])/.test(text)) {
99
100
  return true;
100
101
  }
101
102
  }
@@ -187,6 +188,36 @@ function performManifestVersionsCheck(rootElementName, goModGraphOutputRows, man
187
188
  throw error;
188
189
  }
189
190
  }
191
+ /** Parses go.sum to build a hash map of module@version to CycloneDX hashes. */
192
+ function parseGoSumHashes(manifestDir) {
193
+ let goSumPath = path.join(manifestDir, 'go.sum');
194
+ if (!fs.existsSync(goSumPath)) {
195
+ return new Map();
196
+ }
197
+ let hashMap = new Map();
198
+ let content = fs.readFileSync(goSumPath, 'utf-8');
199
+ for (let line of content.split('\n')) {
200
+ line = line.trim();
201
+ if (!line) {
202
+ continue;
203
+ }
204
+ let parts = line.split(/\s+/);
205
+ if (parts.length < 3) {
206
+ continue;
207
+ }
208
+ let [mod, version, hash] = parts;
209
+ if (version.endsWith('/go.mod')) {
210
+ continue;
211
+ }
212
+ if (!hash.startsWith('h1:')) {
213
+ continue;
214
+ }
215
+ let base64Part = hash.slice(3);
216
+ let hexDigest = Buffer.from(base64Part, 'base64').toString('hex');
217
+ hashMap.set(`${mod}@${version}`, [{ alg: "SHA-256", content: hexDigest }]);
218
+ }
219
+ return hashMap;
220
+ }
190
221
  /**
191
222
  * Create SBOM json string for go Module.
192
223
  * @param {string} manifest - path for go.mod
@@ -241,6 +272,7 @@ async function getSBOM(manifest, opts = {}, includeTransitive) {
241
272
  if (matchManifestVersions === "true") {
242
273
  performManifestVersionsCheck(root, rows, manifestContent, parser, requireQuery);
243
274
  }
275
+ let goSumHashes = parseGoSumHashes(manifestDir);
244
276
  const mainModule = toPurl(root, "@");
245
277
  const license = readLicenseFromManifest(manifest);
246
278
  sbom.addRoot(mainModule, license);
@@ -262,7 +294,7 @@ async function getSBOM(manifest, opts = {}, includeTransitive) {
262
294
  if (getParentVertexFromEdge(row) === root && !directDepPaths.has(getPackageName(child))) {
263
295
  return;
264
296
  }
265
- sbom.addDependency(source, target);
297
+ sbom.addDependency(source, target, undefined, goSumHashes.get(child));
266
298
  });
267
299
  // at the end, filter out all ignored dependencies including versions.
268
300
  sbom.filterIgnoredDepsIncludingVersion(allIgnoredDeps);
@@ -275,12 +307,22 @@ async function getSBOM(manifest, opts = {}, includeTransitive) {
275
307
  let target = toPurl(child, "@");
276
308
  if (dependencyNotIgnored(ignoredDeps, target)) {
277
309
  if (directDepPaths.has(getPackageName(child))) {
278
- sbom.addDependency(mainModule, target);
310
+ sbom.addDependency(mainModule, target, undefined, goSumHashes.get(child));
279
311
  }
280
312
  }
281
313
  });
282
314
  enforceRemovingIgnoredDepsInCaseOfAutomaticVersionUpdate(ignoredDeps, sbom);
283
315
  }
316
+ // Backfill hashes for components that were only seen as dependency sources
317
+ for (const comp of sbom.sbomModel.components) {
318
+ if (!comp.hashes && comp.purl) {
319
+ let key = decodeURIComponent(comp.purl.replace('pkg:golang/', ''));
320
+ let hashes = goSumHashes.get(key);
321
+ if (hashes) {
322
+ comp.hashes = hashes;
323
+ }
324
+ }
325
+ }
284
326
  return sbom.getAsJsonString(opts);
285
327
  }
286
328
  /**
@@ -17,6 +17,30 @@ export function parseGradleInitScriptOutput(raw: string): {
17
17
  path: string;
18
18
  dir: string;
19
19
  }[];
20
+ /**
21
+ * Parse the structured output from the Gradle hash init script.
22
+ * Each recognised line has the form `::DA_HASH::group:name:version::<file-path>`.
23
+ *
24
+ * @param {string} raw - Raw stdout from gradle
25
+ * @returns {{ id: string, file: string }[]} component id (`group:name:version`) and absolute artifact file path
26
+ */
27
+ export function parseGradleHashScriptOutput(raw: string): {
28
+ id: string;
29
+ file: string;
30
+ }[];
31
+ /**
32
+ * Parse a Gradle module component id (`group:name:version`) into its coordinate
33
+ * parts. The caller builds the canonical PURL key from these parts using the same
34
+ * builder {@link parseDep} uses, so the stored key and the lookup key cannot drift.
35
+ *
36
+ * @param {string} id - the Gradle component id
37
+ * @returns {{group: string, name: string, version: string}|null} the parsed coordinate, or null when the id is malformed
38
+ */
39
+ export function parseComponentId(id: string): {
40
+ group: string;
41
+ name: string;
42
+ version: string;
43
+ } | null;
20
44
  /**
21
45
  * This class provides common functionality for Groovy and Kotlin DSL files.
22
46
  */
@@ -54,6 +78,30 @@ export default class Java_gradle extends Base_java {
54
78
  * @returns {Provided}
55
79
  */
56
80
  provideComponent(manifest: string, opts?: {}): Provided;
81
+ /**
82
+ * Compute SHA-256 hashes for the resolved artifacts of a Gradle manifest.
83
+ *
84
+ * Rather than scanning the local Gradle cache, this asks Gradle itself for
85
+ * the resolved artifact files via an init script (mirroring the pattern used
86
+ * by {@link discoverGradleSubprojects}), then hashes each file with the
87
+ * Node.js `crypto` module. The result is keyed by the canonical PURL string
88
+ * built via {@link Base_java#toPurl} — the same builder {@link parseDep} uses
89
+ * for the lookup — so the stored key and the lookup key cannot drift.
90
+ *
91
+ * Degrades gracefully: if Gradle cannot be invoked, the init script fails, or
92
+ * an artifact has no readable file (e.g. BOM/`platform()` dependencies), the
93
+ * hash for that component is omitted rather than throwing. A warning is emitted
94
+ * on every degradation path so incomplete hash coverage is visible even without
95
+ * `TRUSTIFY_DA_DEBUG` (mirroring the pip/cargo providers).
96
+ *
97
+ * @param {string} manifest - path to build.gradle[.kts]
98
+ * @param {{}} [opts={}] - optional various options to pass along the application
99
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>} map of canonical PURL string to CycloneDX hashes
100
+ */
101
+ parseGradleHashes(manifest: string, opts?: {}): Promise<Map<string, Array<{
102
+ alg: string;
103
+ content: string;
104
+ }>>>;
57
105
  #private;
58
106
  }
59
107
  export type Provided = import("../provider.js").Provided;
@@ -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,7 +153,7 @@ 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
  }
@@ -166,7 +166,7 @@ export default class Java_gradle extends Base_java {
166
166
  * @returns {string} the Dot Graph content
167
167
  * @private
168
168
  */
169
- #buildSbom(content, properties, manifestPath, opts = {}) {
169
+ #buildSbom(content, properties, manifestPath, opts = {}, hashMap) {
170
170
  let sbom = new Sbom();
171
171
  let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
172
172
  let rootPurl = this.parseDep(root);
@@ -175,8 +175,8 @@ export default class Java_gradle extends Base_java {
175
175
  let ignoredDeps = this.#getIgnoredDeps(manifestPath);
176
176
  const [runtimeConfig, compileConfig] = this.#extractConfigurations(content);
177
177
  const processedDeps = new Set();
178
- this.#processDependencyTree(runtimeConfig, rootPurl, sbom, processedDeps, 'required');
179
- this.#processDependencyTree(compileConfig, rootPurl, sbom, processedDeps, 'optional');
178
+ this.#processDependencyTree(runtimeConfig, rootPurl, sbom, processedDeps, 'required', hashMap);
179
+ this.#processDependencyTree(compileConfig, rootPurl, sbom, processedDeps, 'optional', hashMap);
180
180
  return sbom.filterIgnoredDepsIncludingVersion(ignoredDeps).getAsJsonString(opts);
181
181
  }
182
182
  /**
@@ -186,14 +186,15 @@ export default class Java_gradle extends Base_java {
186
186
  * @returns {string} the Dot Graph content
187
187
  * @private
188
188
  */
189
- #createSbomStackAnalysis(manifest, opts = {}) {
189
+ async #createSbomStackAnalysis(manifest, opts = {}) {
190
190
  let content = this.#getDependencies(manifest, opts);
191
191
  let properties = this.#extractProperties(manifest, opts);
192
+ let hashMap = await this.parseGradleHashes(manifest, opts);
192
193
  // read dependency tree from temp file
193
194
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
194
195
  console.log("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content);
195
196
  }
196
- let sbom = this.#buildSbom(content, properties, manifest, opts);
197
+ let sbom = this.#buildSbom(content, properties, manifest, opts, hashMap);
197
198
  return sbom;
198
199
  }
199
200
  /**
@@ -238,10 +239,11 @@ export default class Java_gradle extends Base_java {
238
239
  * @returns {string} - sbom string of the direct dependencies of build.gradle
239
240
  * @private
240
241
  */
241
- #getSbomForComponentAnalysis(manifestPath, opts = {}) {
242
+ async #getSbomForComponentAnalysis(manifestPath, opts = {}) {
242
243
  let content = this.#getDependencies(manifestPath, opts);
243
244
  let properties = this.#extractProperties(manifestPath, opts);
244
- let sbom = this.#buildDirectDependenciesSbom(content, properties, manifestPath, opts);
245
+ let hashMap = await this.parseGradleHashes(manifestPath, opts);
246
+ let sbom = this.#buildDirectDependenciesSbom(content, properties, manifestPath, opts, hashMap);
245
247
  return sbom;
246
248
  }
247
249
  /**
@@ -260,6 +262,112 @@ export default class Java_gradle extends Base_java {
260
262
  throw new Error(`Couldn't run gradle dependencies command, error message returned from gradle binary => ${EOL} ${error.message}`);
261
263
  }
262
264
  }
265
+ /**
266
+ * Hash a file using SHA-256 with streaming to handle large files efficiently.
267
+ * @param {string} filePath - path to the file to hash
268
+ * @returns {Promise<string>} hex-encoded SHA-256 digest
269
+ * @private
270
+ */
271
+ #hashFileStream(filePath) {
272
+ return new Promise((resolve, reject) => {
273
+ const hash = crypto.createHash('sha256');
274
+ const stream = fs.createReadStream(filePath);
275
+ stream.on('data', chunk => hash.update(chunk));
276
+ stream.on('end', () => resolve(hash.digest('hex')));
277
+ stream.on('error', reject);
278
+ });
279
+ }
280
+ /**
281
+ * Compute SHA-256 hashes for the resolved artifacts of a Gradle manifest.
282
+ *
283
+ * Rather than scanning the local Gradle cache, this asks Gradle itself for
284
+ * the resolved artifact files via an init script (mirroring the pattern used
285
+ * by {@link discoverGradleSubprojects}), then hashes each file with the
286
+ * Node.js `crypto` module. The result is keyed by the canonical PURL string
287
+ * built via {@link Base_java#toPurl} — the same builder {@link parseDep} uses
288
+ * for the lookup — so the stored key and the lookup key cannot drift.
289
+ *
290
+ * Degrades gracefully: if Gradle cannot be invoked, the init script fails, or
291
+ * an artifact has no readable file (e.g. BOM/`platform()` dependencies), the
292
+ * hash for that component is omitted rather than throwing. A warning is emitted
293
+ * on every degradation path so incomplete hash coverage is visible even without
294
+ * `TRUSTIFY_DA_DEBUG` (mirroring the pip/cargo providers).
295
+ *
296
+ * @param {string} manifest - path to build.gradle[.kts]
297
+ * @param {{}} [opts={}] - optional various options to pass along the application
298
+ * @returns {Promise<Map<string, Array<{alg: string, content: string}>>>} map of canonical PURL string to CycloneDX hashes
299
+ */
300
+ async parseGradleHashes(manifest, opts = {}) {
301
+ const hashMap = new Map();
302
+ const debug = process.env["TRUSTIFY_DA_DEBUG"] === "true";
303
+ let gradle;
304
+ try {
305
+ gradle = this.selectToolBinary(manifest, opts);
306
+ }
307
+ catch (error) {
308
+ console.warn(`Gradle could not be invoked to compute artifact hashes, SBOM will be generated without hashes: ${error.stack || error.message}`);
309
+ return hashMap;
310
+ }
311
+ const initScriptPath = path.join(os.tmpdir(), `da-list-hashes-${crypto.randomUUID()}.gradle`);
312
+ try {
313
+ fs.writeFileSync(initScriptPath, GRADLE_HASH_INIT_SCRIPT);
314
+ let output;
315
+ try {
316
+ output = this._invokeCommand(gradle, [
317
+ '-q', '--no-daemon',
318
+ '--init-script', initScriptPath,
319
+ 'daListHashes',
320
+ ], { cwd: path.dirname(manifest) });
321
+ }
322
+ catch (error) {
323
+ console.warn(`Gradle hash init script failed, SBOM will be generated without hashes: ${error.stack || error.message}`);
324
+ return hashMap;
325
+ }
326
+ let attempted = 0;
327
+ let missed = 0;
328
+ for (const { id, file } of parseGradleHashScriptOutput(output.toString())) {
329
+ const coord = parseComponentId(id);
330
+ if (!coord) {
331
+ continue;
332
+ }
333
+ // Build the key with the same canonical PURL builder parseDep uses for
334
+ // the lookup, so the stored key and the lookup key cannot drift.
335
+ const key = this.toPurl(coord.group, coord.name, coord.version).toString();
336
+ if (hashMap.has(key)) {
337
+ continue;
338
+ }
339
+ attempted++;
340
+ try {
341
+ const digest = await this.#hashFileStream(file);
342
+ hashMap.set(key, [{ alg: 'SHA-256', content: digest }]);
343
+ }
344
+ catch (error) {
345
+ // artifact file missing/unreadable — omit the hash for this component
346
+ missed++;
347
+ if (debug) {
348
+ console.error(`Gradle hash: could not read artifact ${file} => ${error.message}`);
349
+ }
350
+ }
351
+ }
352
+ if (missed > 0) {
353
+ console.warn(`Gradle hash: ${missed} of ${attempted} resolved artifacts could not be read, SBOM will be generated without hashes for those components`);
354
+ }
355
+ }
356
+ catch (error) {
357
+ // Unexpected failure (e.g. a programming error) is degraded to keep SBOM
358
+ // generation working, but the error is surfaced so it is not mistaken
359
+ // for ordinary graceful degradation.
360
+ console.warn(`Gradle artifact hashing failed, SBOM will be generated without hashes: ${error.stack || error.message}`);
361
+ return hashMap;
362
+ }
363
+ finally {
364
+ try {
365
+ fs.unlinkSync(initScriptPath);
366
+ }
367
+ catch { /* ignore */ }
368
+ }
369
+ return hashMap;
370
+ }
263
371
  /**
264
372
  * Extracts runtime and compile configurations from the dependency tree
265
373
  * @param {string} content - the dependency tree content
@@ -307,7 +415,7 @@ export default class Java_gradle extends Base_java {
307
415
  * @param properties {Object} - properties of the gradle project.
308
416
  * @return {string} return sbom json string of the build.gradle manifest file
309
417
  */
310
- #buildDirectDependenciesSbom(content, properties, manifestPath, opts = {}) {
418
+ #buildDirectDependenciesSbom(content, properties, manifestPath, opts = {}, hashMap) {
311
419
  let sbom = new Sbom();
312
420
  let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
313
421
  let rootPurl = this.parseDep(root);
@@ -321,7 +429,7 @@ export default class Java_gradle extends Base_java {
321
429
  directDependencies.forEach((scope, dep) => {
322
430
  const purl = this.parseDep(dep);
323
431
  purl.scope = scope;
324
- sbom.addDependency(rootPurl, purl, scope);
432
+ sbom.addDependency(rootPurl, purl, scope, hashMap?.get(purl.toString()));
325
433
  });
326
434
  return sbom.filterIgnoredDepsIncludingVersion(ignoredDeps).getAsJsonString(opts);
327
435
  }
@@ -424,6 +532,29 @@ const GRADLE_INIT_SCRIPT = `allprojects {
424
532
  }
425
533
  }
426
534
  `;
535
+ /**
536
+ * Gradle init script that emits, per resolved module artifact, a structured line
537
+ * of the form `::DA_HASH::group:name:version::/absolute/file/path`. It obtains
538
+ * files from Gradle's resolution API (the same approach as the CycloneDX Gradle
539
+ * plugin) so it is robust to cache-layout changes and correctly reports
540
+ * classifiers and non-jar artifacts. Uses a lenient artifact view so
541
+ * unresolved/fileless artifacts are skipped rather than failing the build.
542
+ */
543
+ const GRADLE_HASH_INIT_SCRIPT = `allprojects {
544
+ task daListHashes {
545
+ doLast {
546
+ configurations.findAll { it.canBeResolved }.each { cfg ->
547
+ cfg.incoming.artifactView { lenient = true }.artifacts.each { artifact ->
548
+ def cid = artifact.id.componentIdentifier
549
+ if (cid instanceof org.gradle.api.artifacts.component.ModuleComponentIdentifier) {
550
+ println "::DA_HASH::\${cid.group}:\${cid.module}:\${cid.version}::\${artifact.file.absolutePath}"
551
+ }
552
+ }
553
+ }
554
+ }
555
+ }
556
+ }
557
+ `;
427
558
  /**
428
559
  * Discover all build.gradle[.kts] manifest paths in a Gradle multi-project build.
429
560
  * Uses a custom init script to get structured project listing.
@@ -521,3 +652,50 @@ export function parseGradleInitScriptOutput(raw) {
521
652
  }
522
653
  return projects;
523
654
  }
655
+ /**
656
+ * Parse the structured output from the Gradle hash init script.
657
+ * Each recognised line has the form `::DA_HASH::group:name:version::<file-path>`.
658
+ *
659
+ * @param {string} raw - Raw stdout from gradle
660
+ * @returns {{ id: string, file: string }[]} component id (`group:name:version`) and absolute artifact file path
661
+ */
662
+ export function parseGradleHashScriptOutput(raw) {
663
+ const artifacts = [];
664
+ for (const rawLine of raw.split('\n')) {
665
+ const line = rawLine.trimEnd();
666
+ if (!line.startsWith('::DA_HASH::')) {
667
+ continue;
668
+ }
669
+ const prefix = '::DA_HASH::';
670
+ const remainder = line.substring(prefix.length);
671
+ const lastSep = remainder.lastIndexOf('::');
672
+ if (lastSep < 0) {
673
+ continue;
674
+ }
675
+ const id = remainder.substring(0, lastSep);
676
+ const file = remainder.substring(lastSep + 2);
677
+ if (id && file) {
678
+ artifacts.push({ id, file });
679
+ }
680
+ }
681
+ return artifacts;
682
+ }
683
+ /**
684
+ * Parse a Gradle module component id (`group:name:version`) into its coordinate
685
+ * parts. The caller builds the canonical PURL key from these parts using the same
686
+ * builder {@link parseDep} uses, so the stored key and the lookup key cannot drift.
687
+ *
688
+ * @param {string} id - the Gradle component id
689
+ * @returns {{group: string, name: string, version: string}|null} the parsed coordinate, or null when the id is malformed
690
+ */
691
+ export function parseComponentId(id) {
692
+ const parts = id.split(':');
693
+ if (parts.length < 3) {
694
+ return null;
695
+ }
696
+ const [group, name, version] = parts;
697
+ if (!group || !name || !version) {
698
+ return null;
699
+ }
700
+ return { group, name, version };
701
+ }