@trustify-da/trustify-da-javascript-client 0.3.0-ea.62f6bc7 → 0.3.0-ea.6549d2a

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 (37) hide show
  1. package/README.md +13 -1
  2. package/dist/package.json +7 -3
  3. package/dist/src/analysis.js +21 -76
  4. package/dist/src/cli.js +72 -6
  5. package/dist/src/cyclone_dx_sbom.d.ts +3 -1
  6. package/dist/src/cyclone_dx_sbom.js +16 -4
  7. package/dist/src/index.d.ts +5 -3
  8. package/dist/src/index.js +5 -3
  9. package/dist/src/license/compatibility.d.ts +18 -0
  10. package/dist/src/license/compatibility.js +45 -0
  11. package/dist/src/license/index.d.ts +28 -0
  12. package/dist/src/license/index.js +100 -0
  13. package/dist/src/license/licenses_api.d.ts +34 -0
  14. package/dist/src/license/licenses_api.js +91 -0
  15. package/dist/src/license/project_license.d.ts +25 -0
  16. package/dist/src/license/project_license.js +139 -0
  17. package/dist/src/provider.d.ts +12 -3
  18. package/dist/src/provider.js +16 -1
  19. package/dist/src/providers/base_javascript.d.ts +10 -4
  20. package/dist/src/providers/base_javascript.js +28 -4
  21. package/dist/src/providers/golang_gomodules.d.ts +8 -1
  22. package/dist/src/providers/golang_gomodules.js +12 -4
  23. package/dist/src/providers/java_gradle.d.ts +6 -0
  24. package/dist/src/providers/java_gradle.js +11 -2
  25. package/dist/src/providers/java_maven.d.ts +8 -1
  26. package/dist/src/providers/java_maven.js +31 -4
  27. package/dist/src/providers/python_controller.d.ts +5 -2
  28. package/dist/src/providers/python_controller.js +56 -58
  29. package/dist/src/providers/python_pip.d.ts +11 -4
  30. package/dist/src/providers/python_pip.js +45 -53
  31. package/dist/src/providers/requirements_parser.d.ts +6 -0
  32. package/dist/src/providers/requirements_parser.js +23 -0
  33. package/dist/src/sbom.d.ts +3 -1
  34. package/dist/src/sbom.js +3 -2
  35. package/dist/src/tools.d.ts +18 -0
  36. package/dist/src/tools.js +56 -1
  37. package/package.json +8 -4
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Fetch license details by SPDX identifier from the backend GET /api/v5/licenses/{spdx}.
3
+ * Returns detailed information about a specific license including category, name, and text.
4
+ *
5
+ * @param {string} spdxId - SPDX identifier (e.g., "Apache-2.0", "MIT")
6
+ * @param {import('../index.js').Options} [opts={}] - options (proxy, token, TRUSTIFY_DA_BACKEND_URL, etc.)
7
+ * @returns {Promise<Object|null>} License details or null if not found
8
+ */
9
+ export function getLicenseDetails(spdxId: string, opts?: import("../index.js").Options): Promise<any | null>;
10
+ /**
11
+ * Normalize the LicensesResponse shape (array of LicenseProviderResult) into a map of purl -> license info.
12
+ * Each provider result has { status, summary, packages } where packages is { [purl]: { concluded, evidence } }.
13
+ * We merge the first successful provider's packages; concluded has identifiers[], category (PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN).
14
+ *
15
+ * @param {unknown} data - LicensesResponse (array) or analysis report's licenses field
16
+ * @param {string[]} [purls] - optional list of purls to restrict to (for consistency with getLicensesByPurl)
17
+ * @returns {Map<string, { licenses: string[], category?: string }>}
18
+ */
19
+ export function normalizeLicensesResponse(data: unknown, purls?: string[]): Map<string, {
20
+ licenses: string[];
21
+ category?: string;
22
+ }>;
23
+ /**
24
+ * Build license map from an analysis report that already includes license data (result.licenses).
25
+ * Use this when the dependency analysis response already contains the licenses array to avoid a second request.
26
+ *
27
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} analysisReport - full analysis JSON
28
+ * @param {string[]} [purls] - optional list of purls to restrict to
29
+ * @returns {Map<string, { licenses: string[], category?: string }>}
30
+ */
31
+ export function licensesFromReport(analysisReport: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport, purls?: string[]): Map<string, {
32
+ licenses: string[];
33
+ category?: string;
34
+ }>;
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Client for the Trustify DA backend License Analysis API (POST /api/v5/licenses).
3
+ * The same license data shape is returned in the dependency analysis JSON report (result.licenses).
4
+ * @see https://github.com/guacsec/trustify-dependency-analytics#license-analysis-apiv5licenses
5
+ * @see https://github.com/guacsec/trustify-da-api-spec/blob/main/api/v5/openapi.yaml
6
+ */
7
+ import { selectTrustifyDABackend } from '../index.js';
8
+ import { addProxyAgent, getTokenHeaders } from '../tools.js';
9
+ /**
10
+ * Fetch license details by SPDX identifier from the backend GET /api/v5/licenses/{spdx}.
11
+ * Returns detailed information about a specific license including category, name, and text.
12
+ *
13
+ * @param {string} spdxId - SPDX identifier (e.g., "Apache-2.0", "MIT")
14
+ * @param {import('../index.js').Options} [opts={}] - options (proxy, token, TRUSTIFY_DA_BACKEND_URL, etc.)
15
+ * @returns {Promise<Object|null>} License details or null if not found
16
+ */
17
+ export async function getLicenseDetails(spdxId, opts = {}) {
18
+ if (!spdxId) {
19
+ return null;
20
+ }
21
+ const url = selectTrustifyDABackend(opts);
22
+ const finalUrl = new URL(`${url}/api/v5/licenses/${encodeURIComponent(spdxId)}`);
23
+ const fetchOptions = addProxyAgent({
24
+ method: 'GET',
25
+ headers: {
26
+ 'Accept': 'application/json',
27
+ ...getTokenHeaders(opts)
28
+ },
29
+ }, opts);
30
+ try {
31
+ const resp = await fetch(finalUrl, fetchOptions);
32
+ if (!resp.ok) {
33
+ const errorText = await resp.text().catch(() => '');
34
+ throw new Error(`HTTP ${resp.status}: ${errorText || resp.statusText}`);
35
+ }
36
+ return await resp.json();
37
+ }
38
+ catch (err) {
39
+ throw new Error(`Failed to fetch license details: ${err.message}`);
40
+ }
41
+ }
42
+ /**
43
+ * Normalize the LicensesResponse shape (array of LicenseProviderResult) into a map of purl -> license info.
44
+ * Each provider result has { status, summary, packages } where packages is { [purl]: { concluded, evidence } }.
45
+ * We merge the first successful provider's packages; concluded has identifiers[], category (PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN).
46
+ *
47
+ * @param {unknown} data - LicensesResponse (array) or analysis report's licenses field
48
+ * @param {string[]} [purls] - optional list of purls to restrict to (for consistency with getLicensesByPurl)
49
+ * @returns {Map<string, { licenses: string[], category?: string }>}
50
+ */
51
+ export function normalizeLicensesResponse(data, purls = []) {
52
+ const map = new Map();
53
+ if (!data || !Array.isArray(data)) {
54
+ return map;
55
+ }
56
+ for (const providerResult of data) {
57
+ const packages = providerResult?.packages;
58
+ if (!packages || typeof packages !== 'object') {
59
+ continue;
60
+ }
61
+ for (const [purl, pkgLicense] of Object.entries(packages)) {
62
+ const concluded = pkgLicense?.concluded;
63
+ const identifiers = Array.isArray(concluded?.identifiers) ? concluded.identifiers : [];
64
+ const expression = concluded?.expression;
65
+ const licenses = identifiers.length > 0 ? identifiers : (expression ? [expression] : []);
66
+ const category = concluded?.category; // PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
67
+ if (purls.length === 0 || purls.includes(purl)) {
68
+ map.set(purl, { licenses: licenses.filter(Boolean), category });
69
+ }
70
+ }
71
+ // Use first provider that has packages; backend may return multiple (e.g. deps.dev)
72
+ if (map.size > 0) {
73
+ break;
74
+ }
75
+ }
76
+ return map;
77
+ }
78
+ /**
79
+ * Build license map from an analysis report that already includes license data (result.licenses).
80
+ * Use this when the dependency analysis response already contains the licenses array to avoid a second request.
81
+ *
82
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} analysisReport - full analysis JSON
83
+ * @param {string[]} [purls] - optional list of purls to restrict to
84
+ * @returns {Map<string, { licenses: string[], category?: string }>}
85
+ */
86
+ export function licensesFromReport(analysisReport, purls = []) {
87
+ if (!analysisReport?.licenses) {
88
+ return new Map();
89
+ }
90
+ return normalizeLicensesResponse(analysisReport.licenses, purls);
91
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Resolve project license from manifest and from LICENSE / LICENSE.md in manifest dir or git root.
3
+ * Uses local pattern matching for LICENSE file identification (synchronous).
4
+ * For more accurate backend-based identification, use identifyLicense() separately.
5
+ * @param {string} manifestPath - path to manifest
6
+ * @returns {{ fromManifest: string|null, fromFile: string|null, mismatch: boolean }}
7
+ */
8
+ export function getProjectLicense(manifestPath: string): {
9
+ fromManifest: string | null;
10
+ fromFile: string | null;
11
+ mismatch: boolean;
12
+ };
13
+ /**
14
+ * Find LICENSE file path in the same directory as the manifest.
15
+ * @param {string} manifestPath
16
+ * @returns {string|null} - path to LICENSE file or null if not found
17
+ */
18
+ export function findLicenseFilePath(manifestPath: string): string | null;
19
+ /**
20
+ * Call backend /licenses/identify endpoint to identify license from file.
21
+ * @param {string} licenseFilePath - path to LICENSE file
22
+ * @param {{}} [opts={}] - options (proxy, token, etc.)
23
+ * @returns {Promise<string|null>} - SPDX identifier or null
24
+ */
25
+ export function identifyLicense(licenseFilePath: string, opts?: {}): Promise<string | null>;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Resolves the project license from the manifest and from a LICENSE / LICENSE.md file.
3
+ * Used to report manifest-vs-file mismatch and as the baseline for dependency license compatibility.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { selectTrustifyDABackend } from '../index.js';
8
+ import { matchForLicense, availableProviders } from '../provider.js';
9
+ import { addProxyAgent, getTokenHeaders } from '../tools.js';
10
+ const LICENSE_FILES = ['LICENSE', 'LICENSE.md', 'LICENSE.txt'];
11
+ /**
12
+ * Resolve project license from manifest and from LICENSE / LICENSE.md in manifest dir or git root.
13
+ * Uses local pattern matching for LICENSE file identification (synchronous).
14
+ * For more accurate backend-based identification, use identifyLicense() separately.
15
+ * @param {string} manifestPath - path to manifest
16
+ * @returns {{ fromManifest: string|null, fromFile: string|null, mismatch: boolean }}
17
+ */
18
+ export function getProjectLicense(manifestPath) {
19
+ const resolved = path.resolve(manifestPath);
20
+ const provider = matchForLicense(resolved, availableProviders);
21
+ const fromManifest = provider.readLicenseFromManifest(resolved);
22
+ const fromFile = readLicenseFromFile(resolved);
23
+ const mismatch = Boolean(fromManifest && fromFile && normalizeSpdx(fromManifest) !== normalizeSpdx(fromFile));
24
+ return {
25
+ fromManifest: fromManifest || null,
26
+ fromFile: fromFile || null,
27
+ mismatch
28
+ };
29
+ }
30
+ /**
31
+ * Find LICENSE file path in the same directory as the manifest.
32
+ * @param {string} manifestPath
33
+ * @returns {string|null} - path to LICENSE file or null if not found
34
+ */
35
+ export function findLicenseFilePath(manifestPath) {
36
+ const manifestDir = path.dirname(path.resolve(manifestPath));
37
+ for (const name of LICENSE_FILES) {
38
+ const filePath = path.join(manifestDir, name);
39
+ try {
40
+ if (fs.statSync(filePath).isFile()) {
41
+ return filePath;
42
+ }
43
+ }
44
+ catch {
45
+ // skip
46
+ }
47
+ }
48
+ return null;
49
+ }
50
+ /**
51
+ * Call backend /licenses/identify endpoint to identify license from file.
52
+ * @param {string} licenseFilePath - path to LICENSE file
53
+ * @param {{}} [opts={}] - options (proxy, token, etc.)
54
+ * @returns {Promise<string|null>} - SPDX identifier or null
55
+ */
56
+ export async function identifyLicense(licenseFilePath, opts = {}) {
57
+ try {
58
+ const fileContent = fs.readFileSync(licenseFilePath);
59
+ const backendUrl = selectTrustifyDABackend(opts);
60
+ const url = new URL(`${backendUrl}/licenses/identify`);
61
+ const tokenHeaders = getTokenHeaders(opts);
62
+ const fetchOptions = addProxyAgent({
63
+ method: 'POST',
64
+ headers: {
65
+ 'Content-Type': 'application/octet-stream',
66
+ ...tokenHeaders,
67
+ },
68
+ body: fileContent,
69
+ }, opts);
70
+ const resp = await fetch(url, fetchOptions);
71
+ if (!resp.ok) {
72
+ return null; // Fallback to local detection on error
73
+ }
74
+ const data = await resp.json();
75
+ // Extract SPDX identifier from backend response
76
+ return data?.license?.id || data?.spdx_id || data?.identifier || null;
77
+ }
78
+ catch {
79
+ return null; // Fallback to local detection on error
80
+ }
81
+ }
82
+ /**
83
+ * Find and read LICENSE or LICENSE.md; use local pattern matching for identification.
84
+ * @param {string} manifestPath
85
+ * @returns {string|null}
86
+ */
87
+ function readLicenseFromFile(manifestPath) {
88
+ const licenseFilePath = findLicenseFilePath(manifestPath);
89
+ if (!licenseFilePath) {
90
+ return null;
91
+ }
92
+ try {
93
+ const content = fs.readFileSync(licenseFilePath, 'utf-8');
94
+ return detectSpdxFromText(content) || content.split('\n')[0]?.trim() || null;
95
+ }
96
+ catch {
97
+ return null;
98
+ }
99
+ }
100
+ /**
101
+ * Very simple SPDX detection from common license text (first ~500 chars).
102
+ * @param {string} text
103
+ * @returns {string|null}
104
+ */
105
+ function detectSpdxFromText(text) {
106
+ const head = text.slice(0, 500);
107
+ if (/Apache License,?\s*Version 2\.0/i.test(head)) {
108
+ return 'Apache-2.0';
109
+ }
110
+ if (/MIT License/i.test(head) && /Permission is hereby granted/i.test(head)) {
111
+ return 'MIT';
112
+ }
113
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 2/i.test(head)) {
114
+ return 'GPL-2.0-only';
115
+ }
116
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
117
+ return 'GPL-3.0-only';
118
+ }
119
+ if (/BSD 2-Clause/i.test(head)) {
120
+ return 'BSD-2-Clause';
121
+ }
122
+ if (/BSD 3-Clause/i.test(head)) {
123
+ return 'BSD-3-Clause';
124
+ }
125
+ return null;
126
+ }
127
+ /**
128
+ * Normalize for comparison (lowercase, strip common suffixes).
129
+ * @param {string} spdxOrName
130
+ * @returns {string}
131
+ */
132
+ function normalizeSpdx(spdxOrName) {
133
+ const s = String(spdxOrName).trim().toLowerCase();
134
+ // e.g. "MIT" vs "MIT License"
135
+ if (s.endsWith(' license')) {
136
+ return s.slice(0, -8);
137
+ }
138
+ return s;
139
+ }
@@ -1,3 +1,11 @@
1
+ /**
2
+ * Match a provider by manifest type only (no lock file check). Used for license reading.
3
+ * @param {string} manifestPath - path or name of the manifest
4
+ * @param {[Provider]} providers - list of providers to iterate over
5
+ * @returns {Provider}
6
+ * @throws {Error} when the manifest is not supported and no provider was matched
7
+ */
8
+ export function matchForLicense(manifestPath: string, providers: [Provider]): Provider;
1
9
  /**
2
10
  * Match a provider from a list or providers based on file type.
3
11
  * Each provider MUST export 'isSupported' taking a file name-type and returning true if supported.
@@ -10,7 +18,7 @@
10
18
  */
11
19
  export function match(manifest: string, providers: [Provider]): Provider;
12
20
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
13
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided, provideStack: function(string, {}): Provided}} Provider */
21
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
14
22
  /**
15
23
  * MUST include all providers here.
16
24
  * @type {[Provider]}
@@ -24,6 +32,7 @@ export type Provided = {
24
32
  export type Provider = {
25
33
  isSupported: (arg0: string) => boolean;
26
34
  validateLockFile: (arg0: string) => void;
27
- provideComponent: (arg0: string, arg1: {}) => Provided;
28
- provideStack: (arg0: string, arg1: {}) => Provided;
35
+ provideComponent: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
36
+ provideStack: (arg0: string, arg1: {}) => Provided | Promise<Provided>;
37
+ readLicenseFromManifest: (arg0: string) => string | null;
29
38
  };
@@ -8,7 +8,7 @@ import Javascript_pnpm from './providers/javascript_pnpm.js';
8
8
  import Javascript_yarn from './providers/javascript_yarn.js';
9
9
  import pythonPipProvider from './providers/python_pip.js';
10
10
  /** @typedef {{ecosystem: string, contentType: string, content: string}} Provided */
11
- /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided, provideStack: function(string, {}): Provided}} Provider */
11
+ /** @typedef {{isSupported: function(string): boolean, validateLockFile: function(string): void, provideComponent: function(string, {}): Provided | Promise<Provided>, provideStack: function(string, {}): Provided | Promise<Provided>, readLicenseFromManifest: function(string): string | null}} Provider */
12
12
  /**
13
13
  * MUST include all providers here.
14
14
  * @type {[Provider]}
@@ -23,6 +23,21 @@ export const availableProviders = [
23
23
  golangGomodulesProvider,
24
24
  pythonPipProvider
25
25
  ];
26
+ /**
27
+ * Match a provider by manifest type only (no lock file check). Used for license reading.
28
+ * @param {string} manifestPath - path or name of the manifest
29
+ * @param {[Provider]} providers - list of providers to iterate over
30
+ * @returns {Provider}
31
+ * @throws {Error} when the manifest is not supported and no provider was matched
32
+ */
33
+ export function matchForLicense(manifestPath, providers) {
34
+ const base = path.parse(manifestPath).base;
35
+ const provider = providers.find(prov => prov.isSupported(base));
36
+ if (!provider) {
37
+ throw new Error(`${base} is not supported`);
38
+ }
39
+ return provider;
40
+ }
26
41
  /**
27
42
  * Match a provider from a list or providers based on file type.
28
43
  * Each provider MUST export 'isSupported' taking a file name-type and returning true if supported.
@@ -1,5 +1,6 @@
1
- /** @typedef {import('../provider.js').Provider} Provider */
2
- /** @typedef {import('../provider.js').Provided} Provided */
1
+ export type purlType = import("../provider").Provider;
2
+ /** @typedef {import('../provider').Provider} */
3
+ /** @typedef {import('../provider').Provided} Provided */
3
4
  /**
4
5
  * The ecosystem identifier for JavaScript/npm packages
5
6
  * @type {string}
@@ -85,6 +86,12 @@ export default class Base_javascript {
85
86
  * @returns {Provided} The provided data for component analysis
86
87
  */
87
88
  provideComponent(manifestPath: string, opts?: any): Provided;
89
+ /**
90
+ * Read license from manifest (package.json). Reused by npm, pnpm, yarn.
91
+ * @param {string} manifestPath - path to package.json
92
+ * @returns {string|null}
93
+ */
94
+ readLicenseFromManifest(manifestPath: string): string | null;
88
95
  /**
89
96
  * Builds the dependency tree for the project
90
97
  * @param {boolean} includeTransitive - Whether to include transitive dependencies
@@ -121,7 +128,6 @@ export default class Base_javascript {
121
128
  protected _parseDepTreeOutput(output: string): string;
122
129
  #private;
123
130
  }
124
- export type Provider = import("../provider.js").Provider;
125
- export type Provided = import("../provider.js").Provided;
131
+ export type Provided = import("../provider").Provided;
126
132
  import Manifest from './manifest.js';
127
133
  import Sbom from '../sbom.js';
@@ -4,8 +4,8 @@ import path from 'node:path';
4
4
  import Sbom from '../sbom.js';
5
5
  import { getCustom, getCustomPath, invokeCommand, toPurl, toPurlFromString } from "../tools.js";
6
6
  import Manifest from './manifest.js';
7
- /** @typedef {import('../provider.js').Provider} Provider */
8
- /** @typedef {import('../provider.js').Provided} Provided */
7
+ /** @typedef {import('../provider').Provider} */
8
+ /** @typedef {import('../provider').Provided} Provided */
9
9
  /**
10
10
  * The ecosystem identifier for JavaScript/npm packages
11
11
  * @type {string}
@@ -132,6 +132,28 @@ export default class Base_javascript {
132
132
  contentType: 'application/vnd.cyclonedx+json'
133
133
  };
134
134
  }
135
+ /**
136
+ * Read license from manifest (package.json). Reused by npm, pnpm, yarn.
137
+ * @param {string} manifestPath - path to package.json
138
+ * @returns {string|null}
139
+ */
140
+ readLicenseFromManifest(manifestPath) {
141
+ try {
142
+ const content = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
143
+ if (typeof content.license === 'string') {
144
+ return content.license.trim() || null;
145
+ }
146
+ if (Array.isArray(content.licenses) && content.licenses.length > 0) {
147
+ const first = content.licenses[0];
148
+ const name = first.type || first.name;
149
+ return typeof name === 'string' ? name.trim() : null;
150
+ }
151
+ return null;
152
+ }
153
+ catch {
154
+ return null;
155
+ }
156
+ }
135
157
  /**
136
158
  * Builds the dependency tree for the project
137
159
  * @param {boolean} includeTransitive - Whether to include transitive dependencies
@@ -155,8 +177,9 @@ export default class Base_javascript {
155
177
  #getSBOM(opts = {}) {
156
178
  const depsObject = this._buildDependencyTree(true);
157
179
  let mainComponent = toPurl(purlType, this.#manifest.name, this.#manifest.version);
180
+ const license = this.readLicenseFromManifest(this.#manifest.manifestPath);
158
181
  let sbom = new Sbom();
159
- sbom.addRoot(mainComponent);
182
+ sbom.addRoot(mainComponent, license);
160
183
  this._addDependenciesToSbom(sbom, depsObject);
161
184
  sbom.filterIgnoredDeps(this.#manifest.ignored);
162
185
  return sbom.getAsJsonString(opts);
@@ -206,8 +229,9 @@ export default class Base_javascript {
206
229
  #getDirectDependencySbom(opts = {}) {
207
230
  const depTree = this._buildDependencyTree(false);
208
231
  let mainComponent = toPurl(purlType, this.#manifest.name, this.#manifest.version);
232
+ const license = this.readLicenseFromManifest(this.#manifest.manifestPath);
209
233
  let sbom = new Sbom();
210
- sbom.addRoot(mainComponent);
234
+ sbom.addRoot(mainComponent, license);
211
235
  const rootDeps = this._getRootDependencies(depTree);
212
236
  const sortedDepsKeys = Array
213
237
  .from(rootDeps.keys())
@@ -3,6 +3,7 @@ declare namespace _default {
3
3
  export { validateLockFile };
4
4
  export { provideComponent };
5
5
  export { provideStack };
6
+ export { readLicenseFromManifest };
6
7
  }
7
8
  export default _default;
8
9
  export type Provided = import("../provider").Provided;
@@ -20,7 +21,7 @@ export type Dependency = {
20
21
  /**
21
22
  * @param {string} manifestName - the subject manifest name-type
22
23
  * @returns {boolean} - return true if `pom.xml` is the manifest name-type
23
- */
24
+ */
24
25
  declare function isSupported(manifestName: string): boolean;
25
26
  /**
26
27
  * @param {string} manifestDir - the directory where the manifest lies
@@ -40,3 +41,9 @@ declare function provideComponent(manifest: string, opts?: {}): Provided;
40
41
  * @returns {Provided}
41
42
  */
42
43
  declare function provideStack(manifest: string, opts?: {}): Provided;
44
+ /**
45
+ * Go modules have no standard license field in go.mod
46
+ * @param {string} manifestPath - path to go.mod
47
+ * @returns {string|null}
48
+ */
49
+ declare function readLicenseFromManifest(manifestPath: string): string | null;
@@ -4,7 +4,7 @@ import { EOL } from "os";
4
4
  import { PackageURL } from 'packageurl-js';
5
5
  import Sbom from '../sbom.js';
6
6
  import { getCustom, getCustomPath, invokeCommand } from "../tools.js";
7
- export default { isSupported, validateLockFile, provideComponent, provideStack };
7
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
8
8
  /** @typedef {import('../provider').Provider} */
9
9
  /** @typedef {import('../provider').Provided} Provided */
10
10
  /** @typedef {{name: string, version: string}} Package */
@@ -12,16 +12,23 @@ export default { isSupported, validateLockFile, provideComponent, provideStack }
12
12
  /**
13
13
  * @type {string} ecosystem for npm-npm is 'maven'
14
14
  * @private
15
- */
15
+ */
16
16
  const ecosystem = 'golang';
17
17
  const defaultMainModuleVersion = "v0.0.0";
18
18
  /**
19
19
  * @param {string} manifestName - the subject manifest name-type
20
20
  * @returns {boolean} - return true if `pom.xml` is the manifest name-type
21
- */
21
+ */
22
22
  function isSupported(manifestName) {
23
23
  return 'go.mod' === manifestName;
24
24
  }
25
+ /**
26
+ * Go modules have no standard license field in go.mod
27
+ * @param {string} manifestPath - path to go.mod
28
+ * @returns {string|null}
29
+ */
30
+ // eslint-disable-next-line no-unused-vars
31
+ function readLicenseFromManifest(manifestPath) { return null; }
25
32
  /**
26
33
  * @param {string} manifestDir - the directory where the manifest lies
27
34
  */
@@ -250,7 +257,8 @@ function getSBOM(manifest, opts = {}, includeTransitive) {
250
257
  performManifestVersionsCheck(root, rows, manifest);
251
258
  }
252
259
  const mainModule = toPurl(root, "@");
253
- sbom.addRoot(mainModule);
260
+ const license = readLicenseFromManifest(manifest);
261
+ sbom.addRoot(mainModule, license);
254
262
  const exhortGoMvsLogicEnabled = getCustom("TRUSTIFY_DA_GO_MVS_LOGIC_ENABLED", "true", opts);
255
263
  if (includeTransitive && exhortGoMvsLogicEnabled === "true") {
256
264
  rows = getFinalPackagesVersionsForModule(rows, manifest, goBin);
@@ -15,6 +15,12 @@ export default class Java_gradle extends Base_java {
15
15
  * @param {string} manifestDir - the directory where the manifest lies
16
16
  */
17
17
  validateLockFile(): boolean;
18
+ /**
19
+ * Gradle manifests (build.gradle, build.gradle.kts) have no standard license field.
20
+ * @param {string} manifestPath - path to manifest
21
+ * @returns {null}
22
+ */
23
+ readLicenseFromManifest(manifestPath: string): null;
18
24
  /**
19
25
  * Provide content and content type for stack analysis.
20
26
  * @param {string} manifest - the manifest path or name
@@ -49,6 +49,13 @@ export default class Java_gradle extends Base_java {
49
49
  * @param {string} manifestDir - the directory where the manifest lies
50
50
  */
51
51
  validateLockFile() { return true; }
52
+ /**
53
+ * Gradle manifests (build.gradle, build.gradle.kts) have no standard license field.
54
+ * @param {string} manifestPath - path to manifest
55
+ * @returns {null}
56
+ */
57
+ // eslint-disable-next-line no-unused-vars
58
+ readLicenseFromManifest(manifestPath) { return null; }
52
59
  /**
53
60
  * Provide content and content type for stack analysis.
54
61
  * @param {string} manifest - the manifest path or name
@@ -158,7 +165,8 @@ export default class Java_gradle extends Base_java {
158
165
  let sbom = new Sbom();
159
166
  let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
160
167
  let rootPurl = this.parseDep(root);
161
- sbom.addRoot(rootPurl);
168
+ const license = this.readLicenseFromManifest(manifestPath);
169
+ sbom.addRoot(rootPurl, license);
162
170
  let ignoredDeps = this.#getIgnoredDeps(manifestPath);
163
171
  const [runtimeConfig, compileConfig] = this.#extractConfigurations(content);
164
172
  const processedDeps = new Set();
@@ -298,7 +306,8 @@ export default class Java_gradle extends Base_java {
298
306
  let sbom = new Sbom();
299
307
  let root = `${properties.group}:${properties[ROOT_PROJECT_KEY_NAME].match(/Root project '(.+)'/)[1]}:jar:${properties.version}`;
300
308
  let rootPurl = this.parseDep(root);
301
- sbom.addRoot(rootPurl);
309
+ const license = this.readLicenseFromManifest(manifestPath);
310
+ sbom.addRoot(rootPurl, license);
302
311
  let ignoredDeps = this.#getIgnoredDeps(manifestPath);
303
312
  const [runtimeConfig, compileConfig] = this.#extractConfigurations(content);
304
313
  let directDependencies = new Map();
@@ -27,13 +27,20 @@ export default class Java_maven extends Base_java {
27
27
  * @returns {Provided}
28
28
  */
29
29
  provideComponent(manifest: string, opts?: {}): Provided;
30
+ /**
31
+ * Read license from pom.xml manifest
32
+ * @param {string} manifestPath - path to pom.xml
33
+ * @returns {string|null}
34
+ */
35
+ readLicenseFromManifest(manifestPath: string): string | null;
30
36
  /**
31
37
  *
32
38
  * @param {String} textGraphList Text graph String of the manifest
33
39
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
40
+ * @param {String} manifestPath Path to the pom.xml manifest
34
41
  * @return {String} formatted sbom Json String with all dependencies
35
42
  */
36
- createSbomFileFromTextFormat(textGraphList: string, ignoredDeps: [string], opts: any): string;
43
+ createSbomFileFromTextFormat(textGraphList: string, ignoredDeps: [string], opts: any, manifestPath: string): string;
37
44
  #private;
38
45
  }
39
46
  export type Java_maven = import("../provider").Provider;
@@ -51,6 +51,30 @@ export default class Java_maven extends Base_java {
51
51
  contentType: 'application/vnd.cyclonedx+json'
52
52
  };
53
53
  }
54
+ /**
55
+ * Read license from pom.xml manifest
56
+ * @param {string} manifestPath - path to pom.xml
57
+ * @returns {string|null}
58
+ */
59
+ readLicenseFromManifest(manifestPath) {
60
+ try {
61
+ const xml = fs.readFileSync(manifestPath, 'utf-8');
62
+ const parser = new XMLParser({ ignoreAttributes: false });
63
+ const obj = parser.parse(xml);
64
+ const project = obj?.project;
65
+ if (!project?.licenses?.license) {
66
+ return null;
67
+ }
68
+ const license = Array.isArray(project.licenses.license)
69
+ ? project.licenses.license[0]
70
+ : project.licenses.license;
71
+ const name = (license?.name && license.name.trim()) || null;
72
+ return name || null;
73
+ }
74
+ catch {
75
+ return null;
76
+ }
77
+ }
54
78
  /**
55
79
  * Create a Dot Graph dependency tree for a manifest path.
56
80
  * @param {string} manifest - path for pom.xml
@@ -105,7 +129,7 @@ export default class Java_maven extends Base_java {
105
129
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
106
130
  console.error("Dependency tree that will be used as input for creating the BOM =>" + EOL + EOL + content.toString());
107
131
  }
108
- let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts);
132
+ let sbom = this.createSbomFileFromTextFormat(content.toString(), ignoredDeps, opts, manifest);
109
133
  // delete temp file and directory
110
134
  fs.rmSync(tmpDir, { recursive: true, force: true });
111
135
  // return dependency graph as string
@@ -115,15 +139,17 @@ export default class Java_maven extends Base_java {
115
139
  *
116
140
  * @param {String} textGraphList Text graph String of the manifest
117
141
  * @param {[String]} ignoredDeps List of ignored dependencies to be omitted from sbom
142
+ * @param {String} manifestPath Path to the pom.xml manifest
118
143
  * @return {String} formatted sbom Json String with all dependencies
119
144
  */
120
- createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts) {
145
+ createSbomFileFromTextFormat(textGraphList, ignoredDeps, opts, manifestPath) {
121
146
  let lines = textGraphList.split(EOL);
122
147
  // get root component
123
148
  let root = lines[0];
124
149
  let rootPurl = this.parseDep(root);
150
+ const license = this.readLicenseFromManifest(manifestPath);
125
151
  let sbom = new Sbom();
126
- sbom.addRoot(rootPurl);
152
+ sbom.addRoot(rootPurl, license);
127
153
  this.parseDependencyTree(root, 0, lines.slice(1), sbom);
128
154
  return sbom.filterIgnoredDeps(ignoredDeps).getAsJsonString(opts);
129
155
  }
@@ -156,7 +182,8 @@ export default class Java_maven extends Base_java {
156
182
  let sbom = new Sbom();
157
183
  let rootDependency = this.#getRootFromPom(tmpEffectivePom, manifestPath);
158
184
  let purlRoot = this.toPurl(rootDependency.groupId, rootDependency.artifactId, rootDependency.version);
159
- sbom.addRoot(purlRoot);
185
+ const license = this.readLicenseFromManifest(manifestPath);
186
+ sbom.addRoot(purlRoot, license);
160
187
  dependencies.forEach(dep => {
161
188
  let currentPurl = this.toPurl(dep.groupId, dep.artifactId, dep.version);
162
189
  sbom.addDependency(purlRoot, currentPurl);