@trustify-da/trustify-da-javascript-client 0.3.0-ea.c9a9877 → 0.3.0-ea.cb4ae28

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 (44) hide show
  1. package/README.md +43 -1
  2. package/dist/package.json +16 -9
  3. package/dist/src/analysis.d.ts +5 -5
  4. package/dist/src/analysis.js +21 -76
  5. package/dist/src/cli.js +72 -6
  6. package/dist/src/cyclone_dx_sbom.d.ts +3 -2
  7. package/dist/src/cyclone_dx_sbom.js +16 -4
  8. package/dist/src/index.d.ts +65 -11
  9. package/dist/src/index.js +5 -3
  10. package/dist/src/license/index.d.ts +28 -0
  11. package/dist/src/license/index.js +100 -0
  12. package/dist/src/license/license_utils.d.ts +40 -0
  13. package/dist/src/license/license_utils.js +134 -0
  14. package/dist/src/license/licenses_api.d.ts +34 -0
  15. package/dist/src/license/licenses_api.js +98 -0
  16. package/dist/src/license/project_license.d.ts +20 -0
  17. package/dist/src/license/project_license.js +62 -0
  18. package/dist/src/oci_image/images.d.ts +4 -5
  19. package/dist/src/oci_image/utils.d.ts +4 -4
  20. package/dist/src/provider.d.ts +12 -3
  21. package/dist/src/provider.js +16 -1
  22. package/dist/src/providers/base_java.d.ts +3 -5
  23. package/dist/src/providers/base_javascript.d.ts +10 -4
  24. package/dist/src/providers/base_javascript.js +30 -4
  25. package/dist/src/providers/golang_gomodules.d.ts +11 -4
  26. package/dist/src/providers/golang_gomodules.js +13 -4
  27. package/dist/src/providers/java_gradle.d.ts +9 -3
  28. package/dist/src/providers/java_gradle.js +12 -2
  29. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  30. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  31. package/dist/src/providers/java_maven.d.ts +12 -5
  32. package/dist/src/providers/java_maven.js +33 -5
  33. package/dist/src/providers/python_controller.d.ts +5 -2
  34. package/dist/src/providers/python_controller.js +56 -58
  35. package/dist/src/providers/python_pip.d.ts +11 -4
  36. package/dist/src/providers/python_pip.js +46 -53
  37. package/dist/src/providers/requirements_parser.d.ts +6 -0
  38. package/dist/src/providers/requirements_parser.js +24 -0
  39. package/dist/src/providers/tree-sitter-requirements.wasm +0 -0
  40. package/dist/src/sbom.d.ts +3 -1
  41. package/dist/src/sbom.js +3 -2
  42. package/dist/src/tools.d.ts +22 -6
  43. package/dist/src/tools.js +56 -1
  44. package/package.json +17 -10
package/dist/src/index.js CHANGED
@@ -8,6 +8,7 @@ import.meta.dirname;
8
8
  import * as url from 'url';
9
9
  export { parseImageRef } from "./oci_image/utils.js";
10
10
  export { ImageRef } from "./oci_image/images.js";
11
+ export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
11
12
  export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken };
12
13
  /**
13
14
  * @typedef {{
@@ -35,10 +36,11 @@ export default { componentAnalysis, stackAnalysis, imageAnalysis, validateToken
35
36
  * TRUSTIFY_DA_SYFT_CONFIG_PATH?: string | undefined,
36
37
  * TRUSTIFY_DA_SYFT_PATH?: string | undefined,
37
38
  * TRUSTIFY_DA_YARN_PATH?: string | undefined,
39
+ * TRUSTIFY_DA_LICENSE_CHECK?: string | undefined,
38
40
  * MATCH_MANIFEST_VERSIONS?: string | undefined,
39
- * RHDA_SOURCE?: string | undefined,
40
- * RHDA_TOKEN?: string | undefined,
41
- * RHDA_TELEMETRY_ID?: string | undefined,
41
+ * TRUSTIFY_DA_SOURCE?: string | undefined,
42
+ * TRUSTIFY_DA_TOKEN?: string | undefined,
43
+ * TRUSTIFY_DA_TELEMETRY_ID?: string | undefined,
42
44
  * [key: string]: string | undefined,
43
45
  * }} Options
44
46
  */
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Run full license check: resolve project license (with backend identification and details),
3
+ * get dependency licenses from analysis report, and compute incompatibilities.
4
+ *
5
+ * @param {string} sbomContent - CycloneDX SBOM JSON string (the one sent for component analysis)
6
+ * @param {string} manifestPath - path to manifest
7
+ * @param {string} url - the backend url to send the request to
8
+ * @param {import('../index.js').Options} [opts={}]
9
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
10
+ * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
11
+ */
12
+ export function runLicenseCheck(sbomContent: string, manifestPath: string, url: string, opts?: import("../index.js").Options, analysisResult?: import("@trustify-da/trustify-da-api-model/model/v5/AnalysisReport").AnalysisReport): Promise<{
13
+ projectLicense: {
14
+ manifest: any | null;
15
+ file: any | null;
16
+ mismatch: boolean;
17
+ };
18
+ incompatibleDependencies: Array<{
19
+ purl: string;
20
+ licenses: string[];
21
+ category?: string;
22
+ reason: string;
23
+ }>;
24
+ error?: string;
25
+ }>;
26
+ export { getCompatibility } from "./license_utils.js";
27
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from "./project_license.js";
28
+ export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from "./licenses_api.js";
@@ -0,0 +1,100 @@
1
+ /**
2
+ * License resolution and dependency license compatibility for component analysis.
3
+ */
4
+ import { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
5
+ import { licensesFromReport, getLicenseDetails } from './licenses_api.js';
6
+ import { getCompatibility } from './license_utils.js';
7
+ export { getProjectLicense, findLicenseFilePath, identifyLicense } from './project_license.js';
8
+ export { licensesFromReport, normalizeLicensesResponse, getLicenseDetails } from './licenses_api.js';
9
+ export { getCompatibility } from './license_utils.js';
10
+ /**
11
+ * Run full license check: resolve project license (with backend identification and details),
12
+ * get dependency licenses from analysis report, and compute incompatibilities.
13
+ *
14
+ * @param {string} sbomContent - CycloneDX SBOM JSON string (the one sent for component analysis)
15
+ * @param {string} manifestPath - path to manifest
16
+ * @param {string} url - the backend url to send the request to
17
+ * @param {import('../index.js').Options} [opts={}]
18
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} [analysisResult] - analysis result that includes licenses array from backend
19
+ * @returns {Promise<{ projectLicense: { manifest: Object|null, file: Object|null, mismatch: boolean }, incompatibleDependencies: Array<{ purl: string, licenses: string[], category?: string, reason: string }>, error?: string }>}
20
+ */
21
+ export async function runLicenseCheck(sbomContent, manifestPath, url, opts = {}, analysisResult = null) {
22
+ // Resolve project license from manifest and LICENSE file
23
+ const projectLicense = getProjectLicense(manifestPath);
24
+ // Try backend identification for LICENSE file (more accurate than local pattern matching)
25
+ const licenseFilePath = findLicenseFilePath(manifestPath);
26
+ let backendFileId = null;
27
+ if (licenseFilePath) {
28
+ try {
29
+ backendFileId = await identifyLicense(licenseFilePath, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
30
+ }
31
+ catch {
32
+ // Fall back to local detection
33
+ }
34
+ }
35
+ // Determine final license identifiers
36
+ const manifestSpdx = projectLicense.fromManifest;
37
+ const fileSpdx = backendFileId || projectLicense.fromFile;
38
+ const mismatch = Boolean(manifestSpdx && fileSpdx && manifestSpdx.toLowerCase() !== fileSpdx.toLowerCase());
39
+ // Fetch detailed license info from backend (avoid duplicate calls if same license)
40
+ const licenseDetailsCache = new Map();
41
+ async function getDetails(spdxId) {
42
+ if (!spdxId || !url)
43
+ return null;
44
+ if (licenseDetailsCache.has(spdxId))
45
+ return licenseDetailsCache.get(spdxId);
46
+ try {
47
+ const details = await getLicenseDetails(spdxId, { ...opts, TRUSTIFY_DA_BACKEND_URL: url });
48
+ licenseDetailsCache.set(spdxId, details);
49
+ return details;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ const manifestLicenseInfo = await getDetails(manifestSpdx);
56
+ const fileLicenseInfo = await getDetails(fileSpdx);
57
+ // Extract dependency purls from SBOM (exclude root component)
58
+ const sbomObj = typeof sbomContent === 'string' ? JSON.parse(sbomContent) : sbomContent;
59
+ const rootRef = sbomObj?.metadata?.component?.["bom-ref"] || sbomObj?.metadata?.component?.purl;
60
+ const purls = (sbomObj?.components || [])
61
+ .map(c => c.purl || c["bom-ref"])
62
+ .filter(Boolean)
63
+ .filter(purl => !rootRef || purl !== rootRef);
64
+ if (purls.length === 0) {
65
+ return {
66
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
67
+ incompatibleDependencies: []
68
+ };
69
+ }
70
+ // Get dependency licenses from analysis report
71
+ const licenseByPurl = licensesFromReport(analysisResult, purls);
72
+ if (licenseByPurl.size === 0 && analysisResult) {
73
+ return {
74
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
75
+ incompatibleDependencies: [],
76
+ error: 'No license data available in analysis report'
77
+ };
78
+ }
79
+ // Check compatibility for each dependency
80
+ const projectCategory = manifestLicenseInfo?.category || fileLicenseInfo?.category;
81
+ const incompatibleDependencies = [];
82
+ for (const purl of purls) {
83
+ const entry = licenseByPurl.get(purl);
84
+ if (!entry)
85
+ continue;
86
+ const status = getCompatibility(projectCategory, entry.category);
87
+ if (status === 'incompatible') {
88
+ incompatibleDependencies.push({
89
+ purl,
90
+ licenses: entry.licenses,
91
+ category: entry.category,
92
+ reason: 'Dependency license(s) are incompatible with the project license.'
93
+ });
94
+ }
95
+ }
96
+ return {
97
+ projectLicense: { manifest: manifestLicenseInfo, file: fileLicenseInfo, mismatch },
98
+ incompatibleDependencies
99
+ };
100
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Find LICENSE file path in the same directory as the manifest.
3
+ * @param {string} manifestPath
4
+ * @returns {string|null} - path to LICENSE file or null if not found
5
+ */
6
+ export function findLicenseFilePath(manifestPath: string): string | null;
7
+ /**
8
+ * Very simple SPDX detection from common license text (first ~500 chars).
9
+ * @param {string} text
10
+ * @returns {string|null}
11
+ */
12
+ export function detectSpdxFromText(text: string): string | null;
13
+ /**
14
+ * Read LICENSE file and detect SPDX identifier.
15
+ * @param {string} manifestPath - path to manifest
16
+ * @returns {string|null} - SPDX identifier from LICENSE file or null
17
+ */
18
+ export function readLicenseFile(manifestPath: string): string | null;
19
+ /**
20
+ * Get project license from manifest or LICENSE file.
21
+ * Returns manifestLicense if provided, otherwise tries LICENSE file.
22
+ * @param {string|null} manifestLicense - license from manifest (or null)
23
+ * @param {string} manifestPath - path to manifest
24
+ * @returns {string|null} - SPDX identifier or null
25
+ */
26
+ export function getLicense(manifestLicense: string | null, manifestPath: string): string | null;
27
+ /**
28
+ * Normalize SPDX identifier for comparison (lowercase, strip common suffixes).
29
+ * @param {string} spdxOrName
30
+ * @returns {string}
31
+ */
32
+ export function normalizeSpdx(spdxOrName: string): string;
33
+ /**
34
+ * Check if a dependency's license is compatible with the project license based on backend categories.
35
+ *
36
+ * @param {string} [projectCategory] - backend category for project license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
37
+ * @param {string} [dependencyCategory] - backend category for dependency license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
38
+ * @returns {'compatible'|'incompatible'|'unknown'}
39
+ */
40
+ export function getCompatibility(projectCategory?: string, dependencyCategory?: string): "compatible" | "incompatible" | "unknown";
@@ -0,0 +1,134 @@
1
+ /**
2
+ * License utilities: file reading, SPDX detection, normalization, compatibility.
3
+ * This module has NO dependencies on providers or backend to avoid circular dependencies.
4
+ */
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ const LICENSE_FILES = ['LICENSE', 'LICENSE.md', 'LICENSE.txt'];
8
+ /**
9
+ * Find LICENSE file path in the same directory as the manifest.
10
+ * @param {string} manifestPath
11
+ * @returns {string|null} - path to LICENSE file or null if not found
12
+ */
13
+ export function findLicenseFilePath(manifestPath) {
14
+ const manifestDir = path.dirname(path.resolve(manifestPath));
15
+ for (const name of LICENSE_FILES) {
16
+ const filePath = path.join(manifestDir, name);
17
+ try {
18
+ if (fs.statSync(filePath).isFile()) {
19
+ return filePath;
20
+ }
21
+ }
22
+ catch {
23
+ // skip
24
+ }
25
+ }
26
+ return null;
27
+ }
28
+ /**
29
+ * Very simple SPDX detection from common license text (first ~500 chars).
30
+ * @param {string} text
31
+ * @returns {string|null}
32
+ */
33
+ export function detectSpdxFromText(text) {
34
+ const head = text.slice(0, 500);
35
+ if (/Apache License,?\s*Version 2\.0/i.test(head)) {
36
+ return 'Apache-2.0';
37
+ }
38
+ if (/MIT License/i.test(head) && /Permission is hereby granted/i.test(head)) {
39
+ return 'MIT';
40
+ }
41
+ if (/GNU AFFERO GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
42
+ return 'AGPL-3.0-only';
43
+ }
44
+ if (/GNU LESSER GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
45
+ return 'LGPL-3.0-only';
46
+ }
47
+ if (/GNU LESSER GENERAL PUBLIC LICENSE\s+Version 2\.1/i.test(head)) {
48
+ return 'LGPL-2.1-only';
49
+ }
50
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 2/i.test(head)) {
51
+ return 'GPL-2.0-only';
52
+ }
53
+ if (/GNU GENERAL PUBLIC LICENSE\s+Version 3/i.test(head)) {
54
+ return 'GPL-3.0-only';
55
+ }
56
+ if (/BSD 2-Clause/i.test(head)) {
57
+ return 'BSD-2-Clause';
58
+ }
59
+ if (/BSD 3-Clause/i.test(head)) {
60
+ return 'BSD-3-Clause';
61
+ }
62
+ return null;
63
+ }
64
+ /**
65
+ * Read LICENSE file and detect SPDX identifier.
66
+ * @param {string} manifestPath - path to manifest
67
+ * @returns {string|null} - SPDX identifier from LICENSE file or null
68
+ */
69
+ export function readLicenseFile(manifestPath) {
70
+ const licenseFilePath = findLicenseFilePath(manifestPath);
71
+ if (!licenseFilePath) {
72
+ return null;
73
+ }
74
+ try {
75
+ const content = fs.readFileSync(licenseFilePath, 'utf-8');
76
+ return detectSpdxFromText(content) || content.split('\n')[0]?.trim() || null;
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ }
82
+ /**
83
+ * Get project license from manifest or LICENSE file.
84
+ * Returns manifestLicense if provided, otherwise tries LICENSE file.
85
+ * @param {string|null} manifestLicense - license from manifest (or null)
86
+ * @param {string} manifestPath - path to manifest
87
+ * @returns {string|null} - SPDX identifier or null
88
+ */
89
+ export function getLicense(manifestLicense, manifestPath) {
90
+ return manifestLicense || readLicenseFile(manifestPath) || null;
91
+ }
92
+ /**
93
+ * Normalize SPDX identifier for comparison (lowercase, strip common suffixes).
94
+ * @param {string} spdxOrName
95
+ * @returns {string}
96
+ */
97
+ export function normalizeSpdx(spdxOrName) {
98
+ const s = String(spdxOrName).trim().toLowerCase();
99
+ if (s.endsWith(' license')) {
100
+ return s.slice(0, -8);
101
+ }
102
+ return s;
103
+ }
104
+ /**
105
+ * Check if a dependency's license is compatible with the project license based on backend categories.
106
+ *
107
+ * @param {string} [projectCategory] - backend category for project license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
108
+ * @param {string} [dependencyCategory] - backend category for dependency license: PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
109
+ * @returns {'compatible'|'incompatible'|'unknown'}
110
+ */
111
+ export function getCompatibility(projectCategory, dependencyCategory) {
112
+ if (!projectCategory || !dependencyCategory) {
113
+ return 'unknown';
114
+ }
115
+ const proj = projectCategory.toUpperCase();
116
+ const dep = dependencyCategory.toUpperCase();
117
+ if (proj === 'UNKNOWN' || dep === 'UNKNOWN') {
118
+ return 'unknown';
119
+ }
120
+ const restrictiveness = {
121
+ 'PERMISSIVE': 1,
122
+ 'WEAK_COPYLEFT': 2,
123
+ 'STRONG_COPYLEFT': 3
124
+ };
125
+ const projLevel = restrictiveness[proj];
126
+ const depLevel = restrictiveness[dep];
127
+ if (projLevel === undefined || depLevel === undefined) {
128
+ return 'unknown';
129
+ }
130
+ if (depLevel > projLevel) {
131
+ return 'incompatible';
132
+ }
133
+ return 'compatible';
134
+ }
@@ -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,98 @@
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 { PackageURL } from 'packageurl-js';
8
+ import { selectTrustifyDABackend } from '../index.js';
9
+ import { addProxyAgent, getTokenHeaders } from '../tools.js';
10
+ /**
11
+ * Fetch license details by SPDX identifier from the backend GET /api/v5/licenses/{spdx}.
12
+ * Returns detailed information about a specific license including category, name, and text.
13
+ *
14
+ * @param {string} spdxId - SPDX identifier (e.g., "Apache-2.0", "MIT")
15
+ * @param {import('../index.js').Options} [opts={}] - options (proxy, token, TRUSTIFY_DA_BACKEND_URL, etc.)
16
+ * @returns {Promise<Object|null>} License details or null if not found
17
+ */
18
+ export async function getLicenseDetails(spdxId, opts = {}) {
19
+ if (!spdxId) {
20
+ return null;
21
+ }
22
+ const url = selectTrustifyDABackend(opts);
23
+ const finalUrl = new URL(`${url}/api/v5/licenses/${encodeURIComponent(spdxId)}`);
24
+ const fetchOptions = addProxyAgent({
25
+ method: 'GET',
26
+ headers: {
27
+ 'Accept': 'application/json',
28
+ ...getTokenHeaders(opts)
29
+ },
30
+ }, opts);
31
+ try {
32
+ const resp = await fetch(finalUrl, fetchOptions);
33
+ if (!resp.ok) {
34
+ const errorText = await resp.text().catch(() => '');
35
+ throw new Error(`HTTP ${resp.status}: ${errorText || resp.statusText}`);
36
+ }
37
+ return await resp.json();
38
+ }
39
+ catch (err) {
40
+ throw new Error(`Failed to fetch license details: ${err.message}`);
41
+ }
42
+ }
43
+ function normalizePurlString(purl) {
44
+ const parsed = PackageURL.fromString(purl);
45
+ return new PackageURL(parsed.type, parsed.namespace, parsed.name, parsed.version, null, null).toString();
46
+ }
47
+ /**
48
+ * Normalize the LicensesResponse shape (array of LicenseProviderResult) into a map of purl -> license info.
49
+ * Each provider result has { status, summary, packages } where packages is { [purl]: { concluded, evidence } }.
50
+ * We merge the first successful provider's packages; concluded has identifiers[], category (PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN).
51
+ *
52
+ * @param {unknown} data - LicensesResponse (array) or analysis report's licenses field
53
+ * @param {string[]} [purls] - optional list of purls to restrict to (for consistency with getLicensesByPurl)
54
+ * @returns {Map<string, { licenses: string[], category?: string }>}
55
+ */
56
+ export function normalizeLicensesResponse(data, purls = []) {
57
+ const map = new Map();
58
+ if (!data || !Array.isArray(data)) {
59
+ return map;
60
+ }
61
+ const normalizedPurlsSet = purls.length > 0 ? new Set(purls.map(normalizePurlString)) : null;
62
+ for (const providerResult of data) {
63
+ const packages = providerResult?.packages;
64
+ if (!packages || typeof packages !== 'object') {
65
+ continue;
66
+ }
67
+ for (const [purl, pkgLicense] of Object.entries(packages)) {
68
+ const concluded = pkgLicense?.concluded;
69
+ const identifiers = Array.isArray(concluded?.identifiers) ? concluded.identifiers : [];
70
+ const expression = concluded?.expression;
71
+ const licenses = identifiers.length > 0 ? identifiers : (expression ? [expression] : []);
72
+ const category = concluded?.category; // PERMISSIVE | WEAK_COPYLEFT | STRONG_COPYLEFT | UNKNOWN
73
+ const normalizedPurl = normalizePurlString(purl);
74
+ if (normalizedPurlsSet === null || normalizedPurlsSet.has(normalizedPurl)) {
75
+ map.set(normalizedPurl, { licenses: licenses.filter(Boolean), category });
76
+ }
77
+ }
78
+ // Use first provider that has packages; backend may return multiple (e.g. deps.dev)
79
+ if (map.size > 0) {
80
+ break;
81
+ }
82
+ }
83
+ return map;
84
+ }
85
+ /**
86
+ * Build license map from an analysis report that already includes license data (result.licenses).
87
+ * Use this when the dependency analysis response already contains the licenses array to avoid a second request.
88
+ *
89
+ * @param {import('@trustify-da/trustify-da-api-model/model/v5/AnalysisReport').AnalysisReport} analysisReport - full analysis JSON
90
+ * @param {string[]} [purls] - optional list of purls to restrict to
91
+ * @returns {Map<string, { licenses: string[], category?: string }>}
92
+ */
93
+ export function licensesFromReport(analysisReport, purls = []) {
94
+ if (!analysisReport?.licenses) {
95
+ return new Map();
96
+ }
97
+ return normalizeLicensesResponse(analysisReport.licenses, purls);
98
+ }
@@ -0,0 +1,20 @@
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
+ * Call backend /licenses/identify endpoint to identify license from file.
15
+ * @param {string} licenseFilePath - path to LICENSE file
16
+ * @param {{}} [opts={}] - options (proxy, token, etc.)
17
+ * @returns {Promise<string|null>} - SPDX identifier or null
18
+ */
19
+ export function identifyLicense(licenseFilePath: string, opts?: {}): Promise<string | null>;
20
+ export { findLicenseFilePath, readLicenseFile } from "./license_utils.js";
@@ -0,0 +1,62 @@
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
+ import { normalizeSpdx, readLicenseFile } from './license_utils.js';
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 = readLicenseFile(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
+ export { findLicenseFilePath, readLicenseFile } from './license_utils.js';
31
+ /**
32
+ * Call backend /licenses/identify endpoint to identify license from file.
33
+ * @param {string} licenseFilePath - path to LICENSE file
34
+ * @param {{}} [opts={}] - options (proxy, token, etc.)
35
+ * @returns {Promise<string|null>} - SPDX identifier or null
36
+ */
37
+ export async function identifyLicense(licenseFilePath, opts = {}) {
38
+ try {
39
+ const fileContent = fs.readFileSync(licenseFilePath);
40
+ const backendUrl = selectTrustifyDABackend(opts);
41
+ const url = new URL(`${backendUrl}/api/v5/licenses/identify`);
42
+ const tokenHeaders = getTokenHeaders(opts);
43
+ const fetchOptions = addProxyAgent({
44
+ method: 'POST',
45
+ headers: {
46
+ 'Content-Type': 'application/octet-stream',
47
+ ...tokenHeaders,
48
+ },
49
+ body: fileContent,
50
+ }, opts);
51
+ const resp = await fetch(url, fetchOptions);
52
+ if (!resp.ok) {
53
+ return null; // Fallback to local detection on error
54
+ }
55
+ const data = await resp.json();
56
+ // Extract SPDX identifier from backend response
57
+ return data?.license?.id || data?.spdx_id || data?.identifier || null;
58
+ }
59
+ catch {
60
+ return null; // Fallback to local detection on error
61
+ }
62
+ }
@@ -1,4 +1,3 @@
1
- /// <reference types="packageurl-js/src/package-url.js" />
2
1
  /**
3
2
  * Helper class for parsing docker repository/image names:
4
3
  *
@@ -26,7 +25,7 @@ export class Image {
26
25
  * @param {string} fullName
27
26
  * @param {string} [givenTag]
28
27
  */
29
- constructor(fullName: string, givenTag?: string | undefined);
28
+ constructor(fullName: string, givenTag?: string);
30
29
  repository: string;
31
30
  registry: string;
32
31
  tag: string;
@@ -46,12 +45,12 @@ export class Image {
46
45
  * @param {string} [optionalRegistry]
47
46
  * @returns {string}
48
47
  */
49
- getNameWithoutTag(optionalRegistry?: string | undefined): string;
48
+ getNameWithoutTag(optionalRegistry?: string): string;
50
49
  /**
51
50
  * @param {string} [optionalRegistry]
52
51
  * @returns {string}
53
52
  */
54
- getFullName(optionalRegistry?: string | undefined): string;
53
+ getFullName(optionalRegistry?: string): string;
55
54
  /**
56
55
  * @returns {string}
57
56
  */
@@ -79,7 +78,7 @@ export class ImageRef {
79
78
  * @param {string} [platform]
80
79
  * @param {import("index.js").Options} [opts={}]
81
80
  */
82
- constructor(image: string, platform?: string | undefined, opts?: import("index.js").Options | undefined);
81
+ constructor(image: string, platform?: string, opts?: import("index.js").Options);
83
82
  /** @type {Image} */
84
83
  image: Image;
85
84
  /** @type {Platform} */
@@ -4,20 +4,20 @@
4
4
  * @param {import("../index.js").Options} [opts={}] - optional various options to pass along the application
5
5
  * @returns {{}}
6
6
  */
7
- export function generateImageSBOM(imageRef: import('./images').ImageRef, opts?: import("../index.js").Options | undefined): {};
7
+ export function generateImageSBOM(imageRef: import("./images").ImageRef, opts?: import("../index.js").Options): {};
8
8
  /**
9
9
  *
10
10
  * @param {string} image
11
11
  * @param {import("../index.js").Options} [opts={}] - optional various options to pass along the application
12
12
  * @returns {ImageRef}
13
13
  */
14
- export function parseImageRef(image: string, opts?: import("../index.js").Options | undefined): ImageRef;
14
+ export function parseImageRef(image: string, opts?: import("../index.js").Options): ImageRef;
15
15
  /**
16
16
  * Gets the platform information for an image
17
17
  * @param {import("../index.js").Options} [opts={}] - optional various options to pass along the application
18
18
  * @returns {Platform|null} - The platform information or null
19
19
  */
20
- export function getImagePlatform(opts?: import("../index.js").Options | undefined): Platform | null;
20
+ export function getImagePlatform(opts?: import("../index.js").Options): Platform | null;
21
21
  /**
22
22
  * Gets the digests for an image
23
23
  * @param {import('./images').ImageRef} imageRef - The image reference
@@ -25,7 +25,7 @@ export function getImagePlatform(opts?: import("../index.js").Options | undefine
25
25
  * @returns {Object.<string, string>} - The image digests
26
26
  * @throws {Error} If the image info is invalid
27
27
  */
28
- export function getImageDigests(imageRef: import('./images').ImageRef, opts?: import("../index.js").Options | undefined): {
28
+ export function getImageDigests(imageRef: import("./images").ImageRef, opts?: import("../index.js").Options): {
29
29
  [x: string]: string;
30
30
  };
31
31
  export type SyftImageSource = {
@@ -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
  };