@trustify-da/trustify-da-javascript-client 0.3.0-ea.de62188 → 0.3.0-ea.e348975

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -688,7 +688,7 @@ This increasing the chances and the probability that the automatic installation
688
688
  ###### Usage
689
689
  A New setting is introduced - `TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS` (as both env variable/key in `options` object)
690
690
  1. `TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS`="false" - install requirements.txt while respecting declared versions for all packages.
691
- 2. `TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS`="true" - install all packages from requirements.txt, not respecting the declared version, but trying to install a version tailored for the used python version. When using this setting, you must set setting `MATCH_MANIFEST_VERSIONS` to 'false'.
691
+ 2. `TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS`="true" - install all packages from requirements.txt, not respecting the declared version, but trying to install a version tailored for the used python version. When using this setting, you must set `TRUSTIFY_DA_PYTHON_VIRTUAL_ENV` to 'true' and `MATCH_MANIFEST_VERSIONS` to 'false'.
692
692
 
693
693
  ##### Using `pipdeptree`
694
694
  By default, The API algorithm will use native commands of PIP installer as data source to build the dependency tree.
package/dist/src/cli.js CHANGED
@@ -4,6 +4,7 @@ import * as path from "path";
4
4
  import yargs from 'yargs';
5
5
  import { hideBin } from 'yargs/helpers';
6
6
  import { getProjectLicense, getLicenseDetails } from './license/index.js';
7
+ import { runRemediation } from './remediate.js';
7
8
  import client, { selectTrustifyDABackend, generateSbom } from './index.js';
8
9
  // command for component analysis take manifest type and content
9
10
  const component = {
@@ -430,9 +431,54 @@ const sbom = {
430
431
  }
431
432
  }
432
433
  };
434
+ const remediate = {
435
+ command: 'remediate <path>',
436
+ desc: 'Scan and apply vulnerability remediations to manifest files',
437
+ builder: yargs => yargs.positional('path', {
438
+ desc: 'Path to manifest file or directory',
439
+ type: 'string',
440
+ normalize: true,
441
+ }).options({
442
+ 'dry-run': {
443
+ alias: 'd',
444
+ type: 'boolean',
445
+ desc: 'Preview changes without modifying files',
446
+ },
447
+ providers: {
448
+ desc: 'Comma-separated list of vulnerability providers (env: TRUSTIFY_DA_PROVIDERS)',
449
+ type: 'string',
450
+ },
451
+ sources: {
452
+ desc: 'Comma-separated list of vulnerability sources (env: TRUSTIFY_DA_SOURCES)',
453
+ type: 'string',
454
+ },
455
+ 'group-by': {
456
+ type: 'string',
457
+ choices: ['dependency', 'bundle'],
458
+ default: 'dependency',
459
+ desc: 'Report grouping strategy',
460
+ },
461
+ }),
462
+ handler: async (args) => {
463
+ try {
464
+ const result = await runRemediation(args.path, {
465
+ dryRun: args['dry-run'],
466
+ providers: args.providers,
467
+ sources: args.sources,
468
+ groupBy: args['group-by'],
469
+ });
470
+ console.log(result.output);
471
+ process.exit(result.exitCode);
472
+ }
473
+ catch (err) {
474
+ console.error(err.message);
475
+ process.exit(1);
476
+ }
477
+ }
478
+ };
433
479
  // parse and invoke the command
434
480
  yargs(hideBin(process.argv))
435
- .usage(`Usage: ${process.argv[0].includes("node") ? path.parse(process.argv[1]).base : path.parse(process.argv[0]).base} {component|stack|stack-batch|image|validate-token|license|sbom}`)
481
+ .usage(`Usage: ${process.argv[0].includes("node") ? path.parse(process.argv[1]).base : path.parse(process.argv[0]).base} {component|stack|stack-batch|image|validate-token|license|sbom|remediate}`)
436
482
  .command(stack)
437
483
  .command(stackBatch)
438
484
  .command(component)
@@ -440,6 +486,7 @@ yargs(hideBin(process.argv))
440
486
  .command(validateToken)
441
487
  .command(license)
442
488
  .command(sbom)
489
+ .command(remediate)
443
490
  .scriptName('')
444
491
  .version(false)
445
492
  .demandCommand(1)
@@ -24,6 +24,7 @@ export function selectTrustifyDABackend(opts?: {
24
24
  export function generateSbom(manifestPath: string, opts?: Options): Promise<object>;
25
25
  export { parseImageRef } from "./oci_image/utils.js";
26
26
  export { ImageRef } from "./oci_image/images.js";
27
+ export { extractRemediations } from "./remediation.js";
27
28
  declare namespace _default {
28
29
  export { componentAnalysis };
29
30
  export { stackAnalysis };
@@ -266,3 +267,4 @@ import { resolveContinueOnError } from './batch_opts.js';
266
267
  import { resolveBatchMetadata } from './batch_opts.js';
267
268
  export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata };
268
269
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
270
+ export { generateReport, generateDeduplicationKey } from "./remediation_report.js";
package/dist/src/index.js CHANGED
@@ -16,6 +16,8 @@ import * as url from 'url';
16
16
  export { parseImageRef } from "./oci_image/utils.js";
17
17
  export { ImageRef } from "./oci_image/images.js";
18
18
  export { getProjectLicense, findLicenseFilePath, identifyLicense, getLicenseDetails, licensesFromReport, normalizeLicensesResponse, runLicenseCheck, getCompatibility } from "./license/index.js";
19
+ export { extractRemediations } from "./remediation.js";
20
+ export { generateReport, generateDeduplicationKey } from './remediation_report.js';
19
21
  export default { componentAnalysis, stackAnalysis, stackAnalysisBatch, imageAnalysis, validateToken, generateSbom };
20
22
  export { discoverMavenModules, discoverGradleSubprojects, discoverGoWorkspaceModules, discoverUvWorkspaceMembers, discoverWorkspacePackages, discoverWorkspaceCrates, validatePackageJson, resolveWorkspaceDiscoveryIgnore, filterManifestPathsByDiscoveryIgnore, resolveContinueOnError, resolveBatchMetadata, };
21
23
  /**
@@ -178,8 +178,11 @@ export default class Python_controller {
178
178
  startingTime = new Date();
179
179
  console.log("Starting time to get requirements.txt dependency tree = " + startingTime);
180
180
  }
181
+ let installBestEfforts = getCustom("TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS", "false", this.options);
182
+ if (installBestEfforts === "true" && this.realEnvironment) {
183
+ throw new Error("Conflicting settings, TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS=true requires TRUSTIFY_DA_PYTHON_VIRTUAL_ENV=true");
184
+ }
181
185
  if (!this.realEnvironment) {
182
- let installBestEfforts = getCustom("TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS", "false", this.options);
183
186
  if (installBestEfforts === "false") {
184
187
  try {
185
188
  invokeCommand(this.pathToPipBin, ['install', '-r', this.pathToRequirements]);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Orchestrates the full remediation pipeline for a single manifest or directory:
3
+ * discover manifests → scan via DA backend → extract remediations → apply or preview.
4
+ *
5
+ * @param {string} targetPath - path to a manifest file or directory
6
+ * @param {object} [options]
7
+ * @param {boolean} [options.dryRun=false] - preview changes without modifying files (applies by default)
8
+ * @param {string} [options.providers] - comma-separated provider list
9
+ * @param {string} [options.sources] - comma-separated source list
10
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - report grouping strategy
11
+ * @returns {Promise<{exitCode: number, output: string}>}
12
+ */
13
+ export function runRemediation(targetPath: string, options?: {
14
+ dryRun?: boolean | undefined;
15
+ providers?: string | undefined;
16
+ sources?: string | undefined;
17
+ groupBy?: "dependency" | "bundle" | undefined;
18
+ }): Promise<{
19
+ exitCode: number;
20
+ output: string;
21
+ }>;
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import analysis from './analysis.js';
4
+ import { availableProviders, match } from './provider.js';
5
+ import { extractRemediations } from './remediation.js';
6
+ import { generateReport } from './remediation_report.js';
7
+ import { updateMavenVersions } from './updaters/maven_updater.js';
8
+ import { updateTomlVersions } from './updaters/toml_updater.js';
9
+ import { selectTrustifyDABackend } from './index.js';
10
+ // Mirrors DEFAULT_WORKSPACE_DISCOVERY_IGNORE in workspace.js
11
+ const SKIP_DIRS = new Set(['node_modules', '.git']);
12
+ const MANIFEST_TYPES = [
13
+ {
14
+ test: (basename) => basename === 'pom.xml',
15
+ updater: updateMavenVersions,
16
+ label: 'maven',
17
+ },
18
+ {
19
+ test: (basename) => basename.endsWith('.versions.toml') || basename === 'libs.versions.toml',
20
+ updater: updateTomlVersions,
21
+ label: 'toml',
22
+ },
23
+ ];
24
+ /**
25
+ * Discovers supported manifest files recursively within a directory.
26
+ * @param {string} dirPath - absolute path to the directory
27
+ * @returns {string[]} array of absolute paths to supported manifest files
28
+ */
29
+ function discoverManifests(dirPath) {
30
+ const manifests = [];
31
+ function walk(dir) {
32
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
33
+ for (const entry of entries) {
34
+ if (SKIP_DIRS.has(entry.name)) {
35
+ continue;
36
+ }
37
+ const fullPath = path.join(dir, entry.name);
38
+ if (entry.isDirectory()) {
39
+ walk(fullPath);
40
+ }
41
+ else if (getManifestType(entry.name)) {
42
+ manifests.push(fullPath);
43
+ }
44
+ }
45
+ }
46
+ walk(dirPath);
47
+ return manifests;
48
+ }
49
+ /**
50
+ * Returns the manifest type descriptor for a given filename, or null if unsupported.
51
+ * @param {string} basename - the file name to check
52
+ * @returns {{test: function, updater: function, label: string}|null}
53
+ */
54
+ function getManifestType(basename) {
55
+ return MANIFEST_TYPES.find(t => t.test(basename)) || null;
56
+ }
57
+ /**
58
+ * Orchestrates the full remediation pipeline for a single manifest or directory:
59
+ * discover manifests → scan via DA backend → extract remediations → apply or preview.
60
+ *
61
+ * @param {string} targetPath - path to a manifest file or directory
62
+ * @param {object} [options]
63
+ * @param {boolean} [options.dryRun=false] - preview changes without modifying files (applies by default)
64
+ * @param {string} [options.providers] - comma-separated provider list
65
+ * @param {string} [options.sources] - comma-separated source list
66
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - report grouping strategy
67
+ * @returns {Promise<{exitCode: number, output: string}>}
68
+ */
69
+ export async function runRemediation(targetPath, options = {}) {
70
+ const { dryRun = false, providers, sources, groupBy = 'dependency' } = options;
71
+ const resolvedPath = path.resolve(targetPath);
72
+ let manifestPaths;
73
+ let stat;
74
+ try {
75
+ stat = fs.statSync(resolvedPath);
76
+ }
77
+ catch {
78
+ throw new Error(`Path not found: ${resolvedPath}`);
79
+ }
80
+ if (stat.isDirectory()) {
81
+ manifestPaths = discoverManifests(resolvedPath);
82
+ if (manifestPaths.length === 0) {
83
+ return { exitCode: 0, output: 'No supported manifest files found.' };
84
+ }
85
+ }
86
+ else {
87
+ const basename = path.basename(resolvedPath);
88
+ if (!getManifestType(basename)) {
89
+ throw new Error(`Unsupported manifest type: ${basename}`);
90
+ }
91
+ manifestPaths = [resolvedPath];
92
+ }
93
+ const opts = {};
94
+ if (providers) {
95
+ opts.TRUSTIFY_DA_PROVIDERS = providers;
96
+ }
97
+ if (sources) {
98
+ opts.TRUSTIFY_DA_SOURCES = sources;
99
+ }
100
+ const url = selectTrustifyDABackend(opts);
101
+ const allRemediations = [];
102
+ const appliedFiles = [];
103
+ for (const manifestPath of manifestPaths) {
104
+ const basename = path.basename(manifestPath);
105
+ const manifestType = getManifestType(basename);
106
+ if (!manifestType) {
107
+ continue;
108
+ }
109
+ let provider;
110
+ try {
111
+ provider = match(manifestPath, availableProviders, opts);
112
+ }
113
+ catch {
114
+ continue;
115
+ }
116
+ const analysisReport = await analysis.requestStack(provider, manifestPath, url, false, opts);
117
+ const remediations = extractRemediations(analysisReport, {
118
+ providerPriority: providers ? providers.split(',').map(p => p.trim()).filter(Boolean) : undefined,
119
+ });
120
+ if (remediations.length === 0) {
121
+ continue;
122
+ }
123
+ allRemediations.push(...remediations);
124
+ if (!dryRun) {
125
+ const content = fs.readFileSync(manifestPath, 'utf-8');
126
+ const versionChanges = remediations.map(r => ({
127
+ groupId: r.groupId,
128
+ artifactId: r.artifactId,
129
+ newVersion: r.fixedInVersion,
130
+ }));
131
+ const result = manifestType.updater(content, versionChanges);
132
+ if (result.applied.length > 0) {
133
+ fs.writeFileSync(manifestPath, result.content, 'utf-8');
134
+ appliedFiles.push(manifestPath);
135
+ }
136
+ }
137
+ }
138
+ if (allRemediations.length === 0) {
139
+ return { exitCode: 0, output: 'No remediations found.' };
140
+ }
141
+ const report = generateReport(allRemediations, { groupBy });
142
+ if (dryRun) {
143
+ return { exitCode: 2, output: report };
144
+ }
145
+ const summary = appliedFiles.length > 0
146
+ ? `Updated ${appliedFiles.length} file(s):\n${appliedFiles.map(f => ` ${f}`).join('\n')}\n\n${report}`
147
+ : report;
148
+ return { exitCode: 0, output: summary };
149
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Extracts actionable remediation instructions from a DA AnalysisReport response.
3
+ *
4
+ * Walks the provider/source/dependency/issue tree, collects fixedIn and trustedContent
5
+ * remediation data, applies provider priority resolution, and uses the configured
6
+ * version selection strategy to resolve conflicts. Dependencies with no remediation
7
+ * data are skipped.
8
+ *
9
+ * @param {object} analysisReport - raw DA AnalysisReport JSON response
10
+ * @param {object} [options] - extraction options
11
+ * @param {string[]} [options.providerPriority] - provider names in descending priority order.
12
+ * The first entry has the highest priority. Providers not listed share the lowest priority.
13
+ * When omitted or empty, all providers are treated equally and the highest fix version wins.
14
+ * @param {object} [options.versionStrategy] - version selection strategy with selectVersion
15
+ * and resolveConflict methods. Defaults to closestCoverageStrategy.
16
+ * @returns {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string, fixedInVersion: string, fixedInPurl: string, provider: string, source: string, advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>}
17
+ */
18
+ export function extractRemediations(analysisReport: object, options?: {
19
+ providerPriority?: string[] | undefined;
20
+ versionStrategy?: object | undefined;
21
+ }): Array<{
22
+ purl: string;
23
+ groupId: string;
24
+ artifactId: string;
25
+ currentVersion: string;
26
+ fixedInVersion: string;
27
+ fixedInPurl: string;
28
+ provider: string;
29
+ source: string;
30
+ advisories: Array<{
31
+ id: string;
32
+ url: string;
33
+ }>;
34
+ severity: string;
35
+ cves: string[];
36
+ }>;
37
+ /**
38
+ * Version selection strategy that prefers the closest compatible version
39
+ * within the same major version stream. Falls back to the lowest cross-major
40
+ * version when no same-major option exists.
41
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
42
+ */
43
+ export const closestCoverageStrategy: {
44
+ selectVersion: (arg0: string[], arg1: string) => string;
45
+ resolveConflict: (arg0: object, arg1: object) => string;
46
+ };
47
+ /**
48
+ * Version selection strategy that always picks the highest version regardless
49
+ * of major version distance. Guarantees maximum CVE coverage but may produce
50
+ * large version jumps. This is the original behavior before pluggable strategies.
51
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
52
+ */
53
+ export const highestStrategy: {
54
+ selectVersion: (arg0: string[], arg1: string) => string;
55
+ resolveConflict: (arg0: object, arg1: object) => string;
56
+ };
57
+ export const SEVERITY_ORDER: string[];
@@ -0,0 +1,436 @@
1
+ import { PackageURL } from 'packageurl-js';
2
+ /**
3
+ * Extracts the major version segment from a version string.
4
+ * @param {string} version
5
+ * @returns {string} the first dot-separated segment
6
+ */
7
+ function getMajorVersion(version) {
8
+ return version.split('.')[0] || '';
9
+ }
10
+ /**
11
+ * Version selection strategy that prefers the closest compatible version
12
+ * within the same major version stream. Falls back to the lowest cross-major
13
+ * version when no same-major option exists.
14
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
15
+ */
16
+ export const closestCoverageStrategy = {
17
+ selectVersion(fixedInVersions, currentVersion) {
18
+ const currentMajor = getMajorVersion(currentVersion);
19
+ const sameMajor = fixedInVersions.filter(v => getMajorVersion(v) === currentMajor);
20
+ if (sameMajor.length > 0) {
21
+ return sameMajor.sort((a, b) => compareVersions(b, a))[0];
22
+ }
23
+ return fixedInVersions.sort((a, b) => compareVersions(a, b))[0];
24
+ },
25
+ resolveConflict(existing, candidate) {
26
+ if (existing._fromTrustedContent && !candidate._fromTrustedContent) {
27
+ return 'existing';
28
+ }
29
+ if (!existing._fromTrustedContent && candidate._fromTrustedContent) {
30
+ return 'candidate';
31
+ }
32
+ const currentMajor = getMajorVersion(existing.currentVersion);
33
+ const existingSameMajor = getMajorVersion(existing.fixedInVersion) === currentMajor;
34
+ const candidateSameMajor = getMajorVersion(candidate.fixedInVersion) === currentMajor;
35
+ if (existingSameMajor && !candidateSameMajor) {
36
+ return 'existing';
37
+ }
38
+ if (!existingSameMajor && candidateSameMajor) {
39
+ return 'candidate';
40
+ }
41
+ return compareVersions(candidate.fixedInVersion, existing.fixedInVersion) > 0
42
+ ? 'candidate'
43
+ : 'existing';
44
+ },
45
+ };
46
+ /**
47
+ * Version selection strategy that always picks the highest version regardless
48
+ * of major version distance. Guarantees maximum CVE coverage but may produce
49
+ * large version jumps. This is the original behavior before pluggable strategies.
50
+ * @type {{selectVersion: function(string[], string): string, resolveConflict: function(object, object): string}}
51
+ */
52
+ export const highestStrategy = {
53
+ selectVersion(fixedInVersions) {
54
+ return fixedInVersions.sort((a, b) => compareVersions(b, a))[0];
55
+ },
56
+ resolveConflict(existing, candidate) {
57
+ if (existing._fromTrustedContent && !candidate._fromTrustedContent) {
58
+ return 'existing';
59
+ }
60
+ if (!existing._fromTrustedContent && candidate._fromTrustedContent) {
61
+ return 'candidate';
62
+ }
63
+ return compareVersions(candidate.fixedInVersion, existing.fixedInVersion) > 0
64
+ ? 'candidate'
65
+ : 'existing';
66
+ },
67
+ };
68
+ /**
69
+ * Extracts actionable remediation instructions from a DA AnalysisReport response.
70
+ *
71
+ * Walks the provider/source/dependency/issue tree, collects fixedIn and trustedContent
72
+ * remediation data, applies provider priority resolution, and uses the configured
73
+ * version selection strategy to resolve conflicts. Dependencies with no remediation
74
+ * data are skipped.
75
+ *
76
+ * @param {object} analysisReport - raw DA AnalysisReport JSON response
77
+ * @param {object} [options] - extraction options
78
+ * @param {string[]} [options.providerPriority] - provider names in descending priority order.
79
+ * The first entry has the highest priority. Providers not listed share the lowest priority.
80
+ * When omitted or empty, all providers are treated equally and the highest fix version wins.
81
+ * @param {object} [options.versionStrategy] - version selection strategy with selectVersion
82
+ * and resolveConflict methods. Defaults to closestCoverageStrategy.
83
+ * @returns {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string, fixedInVersion: string, fixedInPurl: string, provider: string, source: string, advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>}
84
+ */
85
+ export function extractRemediations(analysisReport, options = {}) {
86
+ if (!analysisReport || !analysisReport.providers) {
87
+ return [];
88
+ }
89
+ const priorityMap = buildPriorityMap(options.providerPriority);
90
+ const strategy = options.versionStrategy || closestCoverageStrategy;
91
+ const remediationsByDep = new Map();
92
+ const rankByDep = new Map();
93
+ for (const [providerName, providerReport] of Object.entries(analysisReport.providers)) {
94
+ const providerRank = priorityMap.get(providerName) ?? 0;
95
+ extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep, strategy);
96
+ extractFromRecommendations(providerReport, providerName, providerRank, remediationsByDep, rankByDep);
97
+ }
98
+ return Array.from(remediationsByDep.values())
99
+ .map((entry) => {
100
+ delete entry._fromTrustedContent;
101
+ return entry;
102
+ })
103
+ .sort((a, b) => a.purl.localeCompare(b.purl));
104
+ }
105
+ /**
106
+ * Builds a priority lookup map from a provider priority array.
107
+ * First entry gets the highest numeric priority.
108
+ * @param {string[]} [providerPriority]
109
+ * @returns {Map<string, number>}
110
+ */
111
+ function buildPriorityMap(providerPriority) {
112
+ const map = new Map();
113
+ if (!providerPriority || providerPriority.length === 0) {
114
+ return map;
115
+ }
116
+ for (let i = 0; i < providerPriority.length; i++) {
117
+ map.set(providerPriority[i], providerPriority.length - i);
118
+ }
119
+ return map;
120
+ }
121
+ /**
122
+ * Extracts remediations from the sources/dependencies/issues tree of a provider report.
123
+ * @param {object} providerReport
124
+ * @param {string} providerName
125
+ * @param {number} providerRank - numeric priority rank for this provider
126
+ * @param {Map<string, object>} remediationsByDep - accumulator keyed by dependency PURL
127
+ * @param {Map<string, number>} rankByDep - tracks current winning rank per dependency
128
+ * @param {object} strategy - version selection strategy
129
+ */
130
+ function extractFromSources(providerReport, providerName, providerRank, remediationsByDep, rankByDep, strategy) {
131
+ if (!providerReport.sources) {
132
+ return;
133
+ }
134
+ for (const [sourceName, sourceReport] of Object.entries(providerReport.sources)) {
135
+ if (!sourceReport.dependencies) {
136
+ continue;
137
+ }
138
+ for (const dep of sourceReport.dependencies) {
139
+ if (!dep.issues) {
140
+ continue;
141
+ }
142
+ for (const issue of dep.issues) {
143
+ processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep, strategy);
144
+ }
145
+ }
146
+ }
147
+ }
148
+ /**
149
+ * Processes a single issue's remediation data and merges it into the accumulator.
150
+ * @param {object} issue - issue object containing remediation and CVE data
151
+ * @param {object} dep - dependency object containing the ref PURL
152
+ * @param {string} providerName
153
+ * @param {string} sourceName
154
+ * @param {number} providerRank
155
+ * @param {Map<string, object>} remediationsByDep
156
+ * @param {Map<string, number>} rankByDep
157
+ * @param {object} strategy - version selection strategy
158
+ */
159
+ function processIssueRemediation(issue, dep, providerName, sourceName, providerRank, remediationsByDep, rankByDep, strategy) {
160
+ const depPurl = dep.ref;
161
+ if (!depPurl) {
162
+ return;
163
+ }
164
+ let parsedDep;
165
+ try {
166
+ parsedDep = PackageURL.fromString(depPurl);
167
+ }
168
+ catch {
169
+ return;
170
+ }
171
+ const currentVersion = parsedDep.version || '';
172
+ const fixedInPurl = getFixedInPurl(issue, depPurl, strategy, currentVersion);
173
+ if (!fixedInPurl) {
174
+ return;
175
+ }
176
+ const isTrustedContent = !!(issue.remediation && issue.remediation.trustedContent && issue.remediation.trustedContent.ref);
177
+ let parsedFix;
178
+ try {
179
+ parsedFix = PackageURL.fromString(fixedInPurl);
180
+ }
181
+ catch {
182
+ return;
183
+ }
184
+ const fixedInVersion = parsedFix.version;
185
+ if (!fixedInVersion) {
186
+ return;
187
+ }
188
+ const cveId = issue.id || issue.cve;
189
+ const severity = issue.severity || 'UNKNOWN';
190
+ const advisories = extractAdvisories(issue);
191
+ const existing = remediationsByDep.get(depPurl);
192
+ if (!existing) {
193
+ remediationsByDep.set(depPurl, {
194
+ purl: depPurl,
195
+ groupId: parsedDep.namespace || '',
196
+ artifactId: parsedDep.name,
197
+ currentVersion,
198
+ fixedInVersion,
199
+ fixedInPurl,
200
+ provider: providerName,
201
+ source: sourceName,
202
+ advisories,
203
+ severity: severity.toUpperCase(),
204
+ cves: cveId ? [cveId] : [],
205
+ _fromTrustedContent: isTrustedContent,
206
+ });
207
+ rankByDep.set(depPurl, providerRank);
208
+ return;
209
+ }
210
+ if (cveId && !existing.cves.includes(cveId)) {
211
+ existing.cves.push(cveId);
212
+ }
213
+ mergeAdvisories(existing.advisories, advisories);
214
+ const existingRank = rankByDep.get(depPurl);
215
+ if (providerRank > existingRank) {
216
+ existing.fixedInVersion = fixedInVersion;
217
+ existing.fixedInPurl = fixedInPurl;
218
+ existing.provider = providerName;
219
+ existing.source = sourceName;
220
+ existing.severity = higherSeverity(existing.severity, severity);
221
+ existing._fromTrustedContent = isTrustedContent;
222
+ rankByDep.set(depPurl, providerRank);
223
+ }
224
+ else if (providerRank === existingRank) {
225
+ const winner = strategy.resolveConflict({ fixedInVersion: existing.fixedInVersion, _fromTrustedContent: existing._fromTrustedContent, currentVersion }, { fixedInVersion, _fromTrustedContent: isTrustedContent, currentVersion });
226
+ if (winner === 'candidate') {
227
+ existing.fixedInVersion = fixedInVersion;
228
+ existing.fixedInPurl = fixedInPurl;
229
+ existing.provider = providerName;
230
+ existing.source = sourceName;
231
+ existing._fromTrustedContent = isTrustedContent;
232
+ }
233
+ existing.severity = higherSeverity(existing.severity, severity);
234
+ }
235
+ }
236
+ /**
237
+ * Extracts remediations from the recommendations section of a provider report.
238
+ * Merges CVEs and advisories into existing entries when present.
239
+ * @param {object} providerReport
240
+ * @param {string} providerName
241
+ * @param {number} providerRank
242
+ * @param {Map<string, object>} remediationsByDep
243
+ * @param {Map<string, number>} rankByDep
244
+ */
245
+ function extractFromRecommendations(providerReport, providerName, providerRank, remediationsByDep, rankByDep) {
246
+ if (!providerReport.recommendations || !providerReport.recommendations.dependencies) {
247
+ return;
248
+ }
249
+ for (const dep of providerReport.recommendations.dependencies) {
250
+ if (!dep.recommendation || !dep.ref) {
251
+ continue;
252
+ }
253
+ const recommendedPurl = dep.recommendation.ref || dep.recommendation;
254
+ if (typeof recommendedPurl !== 'string') {
255
+ continue;
256
+ }
257
+ let parsedDep;
258
+ let parsedRec;
259
+ try {
260
+ parsedDep = PackageURL.fromString(dep.ref);
261
+ parsedRec = PackageURL.fromString(recommendedPurl);
262
+ }
263
+ catch {
264
+ continue;
265
+ }
266
+ const fixedInVersion = parsedRec.version;
267
+ if (!fixedInVersion) {
268
+ continue;
269
+ }
270
+ const depPurl = dep.ref;
271
+ const existing = remediationsByDep.get(depPurl);
272
+ if (!existing) {
273
+ remediationsByDep.set(depPurl, {
274
+ purl: depPurl,
275
+ groupId: parsedDep.namespace || '',
276
+ artifactId: parsedDep.name,
277
+ currentVersion: parsedDep.version || '',
278
+ fixedInVersion,
279
+ fixedInPurl: recommendedPurl,
280
+ provider: providerName,
281
+ source: 'recommendation',
282
+ advisories: [],
283
+ severity: 'UNKNOWN',
284
+ cves: [],
285
+ });
286
+ rankByDep.set(depPurl, providerRank);
287
+ continue;
288
+ }
289
+ const existingRank = rankByDep.get(depPurl);
290
+ if (providerRank > existingRank) {
291
+ existing.fixedInVersion = fixedInVersion;
292
+ existing.fixedInPurl = recommendedPurl;
293
+ existing.provider = providerName;
294
+ existing.source = 'recommendation';
295
+ rankByDep.set(depPurl, providerRank);
296
+ }
297
+ else if (providerRank === existingRank) {
298
+ if (compareVersions(fixedInVersion, existing.fixedInVersion) > 0) {
299
+ existing.fixedInVersion = fixedInVersion;
300
+ existing.fixedInPurl = recommendedPurl;
301
+ existing.provider = providerName;
302
+ existing.source = 'recommendation';
303
+ }
304
+ }
305
+ }
306
+ }
307
+ /**
308
+ * Gets the fixedIn PURL from an issue's remediation, preferring trustedContent.
309
+ * When fixedIn is an array of version strings (not PURLs), uses the strategy's
310
+ * selectVersion to pick the best candidate and constructs a PURL from the dependency ref.
311
+ * @param {object} issue
312
+ * @param {string} depPurl - the dependency PURL, used to construct fixedIn PURLs from version strings
313
+ * @param {object} strategy - version selection strategy
314
+ * @param {string} currentVersion - the dependency's current version
315
+ * @returns {string|undefined}
316
+ */
317
+ function getFixedInPurl(issue, depPurl, strategy, currentVersion) {
318
+ if (!issue.remediation) {
319
+ return undefined;
320
+ }
321
+ if (issue.remediation.trustedContent && issue.remediation.trustedContent.ref) {
322
+ return issue.remediation.trustedContent.ref;
323
+ }
324
+ const fixedIn = issue.remediation.fixedIn;
325
+ if (!fixedIn) {
326
+ return undefined;
327
+ }
328
+ if (typeof fixedIn === 'string') {
329
+ return fixedIn;
330
+ }
331
+ if (Array.isArray(fixedIn) && fixedIn.length > 0) {
332
+ const version = fixedIn.length > 1
333
+ ? strategy.selectVersion(fixedIn, currentVersion)
334
+ : fixedIn[0];
335
+ if (typeof version === 'string' && version.startsWith('pkg:')) {
336
+ return version;
337
+ }
338
+ if (typeof version === 'string' && depPurl) {
339
+ try {
340
+ const parsed = PackageURL.fromString(depPurl);
341
+ parsed.version = version;
342
+ return parsed.toString();
343
+ }
344
+ catch {
345
+ return undefined;
346
+ }
347
+ }
348
+ }
349
+ return undefined;
350
+ }
351
+ /**
352
+ * Extracts advisory objects from an issue.
353
+ * @param {object} issue
354
+ * @returns {Array<{id: string, url: string}>}
355
+ */
356
+ function extractAdvisories(issue) {
357
+ const advisories = [];
358
+ if (issue.remediation && issue.remediation.trustedContent) {
359
+ const tc = issue.remediation.trustedContent;
360
+ if (tc.advisory) {
361
+ advisories.push({
362
+ id: tc.advisory.id || tc.advisory,
363
+ url: tc.advisory.url || '',
364
+ });
365
+ }
366
+ }
367
+ if (issue.advisories) {
368
+ for (const adv of issue.advisories) {
369
+ advisories.push({
370
+ id: adv.id || adv,
371
+ url: adv.url || '',
372
+ });
373
+ }
374
+ }
375
+ return advisories;
376
+ }
377
+ /**
378
+ * Merges new advisories into existing list, avoiding duplicates by id.
379
+ * @param {Array<{id: string, url: string}>} existing
380
+ * @param {Array<{id: string, url: string}>} incoming
381
+ */
382
+ function mergeAdvisories(existing, incoming) {
383
+ const seen = new Set(existing.map(a => a.id));
384
+ for (const adv of incoming) {
385
+ if (!seen.has(adv.id)) {
386
+ existing.push(adv);
387
+ seen.add(adv.id);
388
+ }
389
+ }
390
+ }
391
+ /**
392
+ * Compares two version strings segment by segment.
393
+ * Returns positive if a > b, negative if a < b, zero if equal.
394
+ * Falls back to lexicographic comparison for non-numeric segments.
395
+ * @param {string} a
396
+ * @param {string} b
397
+ * @returns {number}
398
+ */
399
+ function compareVersions(a, b) {
400
+ const partsA = a.split('.');
401
+ const partsB = b.split('.');
402
+ const len = Math.max(partsA.length, partsB.length);
403
+ for (let i = 0; i < len; i++) {
404
+ const segA = partsA[i] || '';
405
+ const segB = partsB[i] || '';
406
+ const numA = Number(segA);
407
+ const numB = Number(segB);
408
+ if (Number.isFinite(numA) && Number.isFinite(numB)) {
409
+ const diff = numA - numB;
410
+ if (diff !== 0) {
411
+ return diff;
412
+ }
413
+ }
414
+ else {
415
+ const cmp = segA.localeCompare(segB);
416
+ if (cmp !== 0) {
417
+ return cmp;
418
+ }
419
+ }
420
+ }
421
+ return 0;
422
+ }
423
+ export const SEVERITY_ORDER = ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
424
+ /**
425
+ * Returns the higher of two severity strings, normalized to uppercase.
426
+ * @param {string} a
427
+ * @param {string} b
428
+ * @returns {string}
429
+ */
430
+ function higherSeverity(a, b) {
431
+ const upperA = a.toUpperCase();
432
+ const upperB = b.toUpperCase();
433
+ const indexA = SEVERITY_ORDER.indexOf(upperA);
434
+ const indexB = SEVERITY_ORDER.indexOf(upperB);
435
+ return indexA >= indexB ? upperA : upperB;
436
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Generates a formatted report from an array of remediation entries.
3
+ *
4
+ * @param {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string,
5
+ * fixedInVersion: string, fixedInPurl: string, provider: string, source: string,
6
+ * advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>} remediations
7
+ * @param {object} [options]
8
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - grouping strategy
9
+ * @param {'markdown'|'json'} [options.format='markdown'] - output format
10
+ * @param {boolean} [options.dryRun=false] - when true, produces tabular summary
11
+ * @returns {string}
12
+ */
13
+ export function generateReport(remediations: Array<{
14
+ purl: string;
15
+ groupId: string;
16
+ artifactId: string;
17
+ currentVersion: string;
18
+ fixedInVersion: string;
19
+ fixedInPurl: string;
20
+ provider: string;
21
+ source: string;
22
+ advisories: Array<{
23
+ id: string;
24
+ url: string;
25
+ }>;
26
+ severity: string;
27
+ cves: string[];
28
+ }>, options?: {
29
+ groupBy?: "dependency" | "bundle" | undefined;
30
+ format?: "markdown" | "json" | undefined;
31
+ dryRun?: boolean | undefined;
32
+ }): string;
33
+ /**
34
+ * Generates a deterministic deduplication key for a remediation entry.
35
+ * Suitable for checking existing PR titles or branch names.
36
+ *
37
+ * @param {object} remediation - a single remediation entry
38
+ * @returns {string} stable key in the form `groupId:artifactId:newVersion`
39
+ */
40
+ export function generateDeduplicationKey(remediation: object): string;
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Report generator that transforms remediation extractor output into structured
3
+ * markdown for PR bodies, CLI dry-run output, and JSON.
4
+ */
5
+ import { SEVERITY_ORDER } from './remediation.js';
6
+ /**
7
+ * Generates a formatted report from an array of remediation entries.
8
+ *
9
+ * @param {Array<{purl: string, groupId: string, artifactId: string, currentVersion: string,
10
+ * fixedInVersion: string, fixedInPurl: string, provider: string, source: string,
11
+ * advisories: Array<{id: string, url: string}>, severity: string, cves: string[]}>} remediations
12
+ * @param {object} [options]
13
+ * @param {'dependency'|'bundle'} [options.groupBy='dependency'] - grouping strategy
14
+ * @param {'markdown'|'json'} [options.format='markdown'] - output format
15
+ * @param {boolean} [options.dryRun=false] - when true, produces tabular summary
16
+ * @returns {string}
17
+ */
18
+ export function generateReport(remediations, options = {}) {
19
+ const { groupBy = 'dependency', format = 'markdown', dryRun = false } = options;
20
+ if (!remediations || remediations.length === 0) {
21
+ return format === 'json' ? '[]' : 'No remediations found.';
22
+ }
23
+ if (format === 'json') {
24
+ return JSON.stringify(remediations, null, '\t');
25
+ }
26
+ if (dryRun) {
27
+ return generateDryRunReport(remediations);
28
+ }
29
+ if (groupBy === 'bundle') {
30
+ return generateBundledReport(remediations);
31
+ }
32
+ return generatePerDependencyReport(remediations);
33
+ }
34
+ /**
35
+ * Generates a per-dependency markdown report with one section per remediation entry.
36
+ * @param {Array<object>} remediations
37
+ * @returns {string}
38
+ */
39
+ function generatePerDependencyReport(remediations) {
40
+ const sections = remediations.map(rem => {
41
+ const depName = rem.groupId
42
+ ? `${rem.groupId}:${rem.artifactId}`
43
+ : rem.artifactId;
44
+ const lines = [
45
+ `## Security Update: ${depName} ${rem.currentVersion} → ${rem.fixedInVersion}`,
46
+ '',
47
+ `**Provider:** ${rem.provider} | **Source:** ${rem.source}`,
48
+ '',
49
+ ];
50
+ if (rem.cves && rem.cves.length > 0) {
51
+ lines.push('### Vulnerabilities resolved');
52
+ lines.push('');
53
+ lines.push('| CVE | Severity | Advisory |');
54
+ lines.push('| --- | --- | --- |');
55
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
56
+ for (const cve of rem.cves) {
57
+ lines.push(`| ${cve} | ${rem.severity} | ${advisoryLinks} |`);
58
+ }
59
+ }
60
+ return lines.join('\n');
61
+ });
62
+ return sections.join('\n\n');
63
+ }
64
+ /**
65
+ * Generates a bundled markdown report grouping all remediations by severity.
66
+ * @param {Array<object>} remediations
67
+ * @returns {string}
68
+ */
69
+ function generateBundledReport(remediations) {
70
+ const lines = ['# Security Update Summary', ''];
71
+ const bySeverity = groupBySeverity(remediations);
72
+ for (const severity of [...SEVERITY_ORDER].reverse()) {
73
+ const group = bySeverity.get(severity);
74
+ if (!group || group.length === 0) {
75
+ continue;
76
+ }
77
+ lines.push(`## ${severity}`);
78
+ lines.push('');
79
+ lines.push('| Dependency | Current | Fixed | Provider | CVEs | Advisory |');
80
+ lines.push('| --- | --- | --- | --- | --- | --- |');
81
+ for (const rem of group) {
82
+ const depName = rem.groupId
83
+ ? `${rem.groupId}:${rem.artifactId}`
84
+ : rem.artifactId;
85
+ const cves = (rem.cves || []).join(', ');
86
+ const advisoryLinks = formatAdvisoryLinks(rem.advisories);
87
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
88
+ + ` | ${rem.provider} | ${cves} | ${advisoryLinks} |`);
89
+ }
90
+ lines.push('');
91
+ }
92
+ return lines.join('\n').trimEnd();
93
+ }
94
+ /**
95
+ * Generates a tabular dry-run summary of proposed changes.
96
+ * @param {Array<object>} remediations
97
+ * @returns {string}
98
+ */
99
+ function generateDryRunReport(remediations) {
100
+ const lines = [
101
+ 'Proposed dependency updates:',
102
+ '',
103
+ '| Dependency | Current | Fixed | Severity | Provider |',
104
+ '| --- | --- | --- | --- | --- |',
105
+ ];
106
+ for (const rem of remediations) {
107
+ const depName = rem.groupId
108
+ ? `${rem.groupId}:${rem.artifactId}`
109
+ : rem.artifactId;
110
+ lines.push(`| ${depName} | ${rem.currentVersion} | ${rem.fixedInVersion}`
111
+ + ` | ${rem.severity} | ${rem.provider} |`);
112
+ }
113
+ return lines.join('\n');
114
+ }
115
+ /**
116
+ * Groups remediations by their severity.
117
+ * @param {Array<object>} remediations
118
+ * @returns {Map<string, Array<object>>}
119
+ */
120
+ function groupBySeverity(remediations) {
121
+ const map = new Map();
122
+ for (const severity of SEVERITY_ORDER) {
123
+ map.set(severity, []);
124
+ }
125
+ for (const rem of remediations) {
126
+ const sev = rem.severity || 'UNKNOWN';
127
+ if (!map.has(sev)) {
128
+ map.set(sev, []);
129
+ }
130
+ map.get(sev).push(rem);
131
+ }
132
+ return map;
133
+ }
134
+ /**
135
+ * Formats advisory entries into markdown links or plain text.
136
+ * @param {Array<{id: string, url: string}>} advisories
137
+ * @returns {string}
138
+ */
139
+ function formatAdvisoryLinks(advisories) {
140
+ if (!advisories || advisories.length === 0) {
141
+ return '-';
142
+ }
143
+ return advisories
144
+ .map(adv => adv.url ? `[${adv.id}](${adv.url})` : adv.id)
145
+ .join(', ');
146
+ }
147
+ /**
148
+ * Generates a deterministic deduplication key for a remediation entry.
149
+ * Suitable for checking existing PR titles or branch names.
150
+ *
151
+ * @param {object} remediation - a single remediation entry
152
+ * @returns {string} stable key in the form `groupId:artifactId:newVersion`
153
+ */
154
+ export function generateDeduplicationKey(remediation) {
155
+ const group = remediation.groupId || '';
156
+ const artifact = remediation.artifactId || '';
157
+ const version = remediation.fixedInVersion || '';
158
+ return `${group}:${artifact}:${version}`;
159
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trustify-da/trustify-da-javascript-client",
3
- "version": "0.3.0-ea.de62188",
3
+ "version": "0.3.0-ea.e348975",
4
4
  "description": "Code-Ready Dependency Analytics JavaScript API.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/guacsec/trustify-da-javascript-client#README.md",