@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
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from 'node:path';
3
3
  import os, { EOL } from "os";
4
4
  import { environmentVariableIsPopulated, getCustom, invokeCommand } from "../tools.js";
5
+ import { getParser, getRequirementQuery, getPinnedVersionQuery } from './requirements_parser.js';
5
6
  function getPipFreezeOutput() {
6
7
  try {
7
8
  return environmentVariableIsPopulated("TRUSTIFY_DA_PIP_FREEZE") ? new Buffer.from(process.env["TRUSTIFY_DA_PIP_FREEZE"], 'base64').toString('ascii') : invokeCommand(this.pathToPipBin, ['freeze', '--all']).toString();
@@ -26,6 +27,9 @@ export default class Python_controller {
26
27
  realEnvironment;
27
28
  pathToRequirements;
28
29
  options;
30
+ parser;
31
+ requirementsQuery;
32
+ pinnedVersionQuery;
29
33
  /**
30
34
  * Constructor to create new python controller instance to interact with pip package manager
31
35
  * @param {boolean} realEnvironment - whether to use real environment supplied by client or to create virtual environment
@@ -41,6 +45,9 @@ export default class Python_controller {
41
45
  this.prepareEnvironment();
42
46
  this.pathToRequirements = pathToRequirements;
43
47
  this.options = options;
48
+ this.parser = getParser();
49
+ this.requirementsQuery = getRequirementQuery();
50
+ this.pinnedVersionQuery = getPinnedVersionQuery();
44
51
  }
45
52
  prepareEnvironment() {
46
53
  if (!this.realEnvironment) {
@@ -86,6 +93,23 @@ export default class Python_controller {
86
93
  }
87
94
  }
88
95
  }
96
+ /**
97
+ * Parse the requirements.txt file using tree-sitter and return structured requirement data.
98
+ * @return {Promise<{name: string, version: string|null}[]>}
99
+ */
100
+ async #parseRequirements() {
101
+ const content = fs.readFileSync(this.pathToRequirements).toString();
102
+ const tree = (await this.parser).parse(content);
103
+ return Promise.all((await this.requirementsQuery).matches(tree.rootNode).map(async (match) => {
104
+ const reqNode = match.captures.find(c => c.name === 'req').node;
105
+ const name = match.captures.find(c => c.name === 'name').node.text;
106
+ const versionMatches = (await this.pinnedVersionQuery).matches(reqNode);
107
+ const version = versionMatches.length > 0
108
+ ? versionMatches[0].captures.find(c => c.name === 'version').node.text
109
+ : null;
110
+ return { name, version };
111
+ }));
112
+ }
89
113
  #decideIfWindowsOrLinuxPath(fileName) {
90
114
  if (os.platform() === "win32") {
91
115
  return fileName + ".exe";
@@ -97,9 +121,9 @@ export default class Python_controller {
97
121
  /**
98
122
  *
99
123
  * @param {boolean} includeTransitive - whether to return include in returned object transitive dependencies or not
100
- * @return {[DependencyEntry]}
124
+ * @return {Promise<[DependencyEntry]>}
101
125
  */
102
- getDependencies(includeTransitive) {
126
+ async getDependencies(includeTransitive) {
103
127
  let startingTime;
104
128
  let endingTime;
105
129
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
@@ -124,10 +148,10 @@ export default class Python_controller {
124
148
  if (matchManifestVersions === "true") {
125
149
  throw new Error("Conflicting settings, TRUSTIFY_DA_PYTHON_INSTALL_BEST_EFFORTS=true can only work with MATCH_MANIFEST_VERSIONS=false");
126
150
  }
127
- this.#installingRequirementsOneByOne();
151
+ await this.#installingRequirementsOneByOne();
128
152
  }
129
153
  }
130
- let dependencies = this.#getDependenciesImpl(includeTransitive);
154
+ let dependencies = await this.#getDependenciesImpl(includeTransitive);
131
155
  this.#cleanEnvironment();
132
156
  if (process.env["TRUSTIFY_DA_DEBUG"] === "true") {
133
157
  endingTime = new Date();
@@ -137,16 +161,14 @@ export default class Python_controller {
137
161
  }
138
162
  return dependencies;
139
163
  }
140
- #installingRequirementsOneByOne() {
141
- let requirementsContent = fs.readFileSync(this.pathToRequirements);
142
- let requirementsRows = requirementsContent.toString().split(EOL);
143
- requirementsRows.filter((line) => !line.trim().startsWith("#")).filter((line) => line.trim() !== "").forEach((dependency) => {
144
- let dependencyName = getDependencyName(dependency);
164
+ async #installingRequirementsOneByOne() {
165
+ const requirements = await this.#parseRequirements();
166
+ requirements.forEach(({ name }) => {
145
167
  try {
146
- invokeCommand(this.pathToPipBin, ['install', dependencyName]);
168
+ invokeCommand(this.pathToPipBin, ['install', name]);
147
169
  }
148
170
  catch (error) {
149
- throw new Error(`Failed in best-effort installing ${dependencyName} in virtual python environment`, { cause: error });
171
+ throw new Error(`Failed in best-effort installing ${name} in virtual python environment`, { cause: error });
150
172
  }
151
173
  });
152
174
  }
@@ -163,34 +185,26 @@ export default class Python_controller {
163
185
  }
164
186
  }
165
187
  }
166
- #getDependenciesImpl(includeTransitive) {
167
- let dependencies = new Array();
188
+ async #getDependenciesImpl(includeTransitive) {
189
+ let dependencies = [];
168
190
  let usePipDepTree = getCustom("TRUSTIFY_DA_PIP_USE_DEP_TREE", "false", this.options);
169
- let freezeOutput;
170
- let lines;
171
- let depNames;
172
- let pipShowOutput;
173
191
  let allPipShowDeps;
174
192
  let pipDepTreeJsonArrayOutput;
175
193
  if (usePipDepTree !== "true") {
176
- freezeOutput = getPipFreezeOutput.call(this);
177
- lines = freezeOutput.split(EOL);
178
- depNames = lines.map(line => getDependencyName(line));
194
+ const freezeOutput = getPipFreezeOutput.call(this);
195
+ const lines = freezeOutput.split(EOL);
196
+ const depNames = lines.map(line => getDependencyName(line));
197
+ const pipShowOutput = getPipShowOutput.call(this, depNames);
198
+ allPipShowDeps = pipShowOutput.split(EOL + "---" + EOL);
179
199
  }
180
200
  else {
181
201
  pipDepTreeJsonArrayOutput = getDependencyTreeJsonFromPipDepTree(this.pathToPipBin, this.pathToPythonBin);
182
202
  }
183
- if (usePipDepTree !== "true") {
184
- pipShowOutput = getPipShowOutput.call(this, depNames);
185
- allPipShowDeps = pipShowOutput.split(EOL + "---" + EOL);
186
- }
187
- //debug
188
- // pipShowOutput = "alternative pip show output goes here for debugging"
189
203
  let matchManifestVersions = getCustom("MATCH_MANIFEST_VERSIONS", "true", this.options);
190
- let linesOfRequirements = fs.readFileSync(this.pathToRequirements).toString().split(EOL).filter((line) => !line.trim().startsWith("#")).map(line => line.trim());
204
+ let parsedRequirements = await this.#parseRequirements();
191
205
  let CachedEnvironmentDeps = {};
192
206
  if (usePipDepTree !== "true") {
193
- allPipShowDeps.forEach((record) => {
207
+ allPipShowDeps.forEach(record => {
194
208
  let dependencyName = getDependencyNameShow(record).toLowerCase();
195
209
  CachedEnvironmentDeps[dependencyName] = record;
196
210
  CachedEnvironmentDeps[dependencyName.replace("-", "_")] = record;
@@ -210,40 +224,24 @@ export default class Python_controller {
210
224
  CachedEnvironmentDeps[packageName.replace("_", "-")] = pipDepTreeEntryForCache;
211
225
  });
212
226
  }
213
- linesOfRequirements.forEach((dep) => {
214
- // if matchManifestVersions setting is turned on , then
215
- if (matchManifestVersions === "true") {
216
- let dependencyName;
217
- let manifestVersion;
227
+ parsedRequirements.forEach(({ name: depName, version: manifestVersion }) => {
228
+ if (matchManifestVersions === "true" && manifestVersion != null) {
218
229
  let installedVersion;
219
- let doubleEqualSignPosition;
220
- if (dep.includes("==")) {
221
- doubleEqualSignPosition = dep.indexOf("==");
222
- manifestVersion = dep.substring(doubleEqualSignPosition + 2).trim();
223
- if (manifestVersion.includes("#")) {
224
- let hashCharIndex = manifestVersion.indexOf("#");
225
- manifestVersion = manifestVersion.substring(0, hashCharIndex);
230
+ if (CachedEnvironmentDeps[depName.toLowerCase()] !== undefined) {
231
+ if (usePipDepTree !== "true") {
232
+ installedVersion = getDependencyVersion(CachedEnvironmentDeps[depName.toLowerCase()]);
226
233
  }
227
- dependencyName = getDependencyName(dep);
228
- // only compare between declared version in manifest to installed version , if the package is installed.
229
- if (CachedEnvironmentDeps[dependencyName.toLowerCase()] !== undefined) {
230
- if (usePipDepTree !== "true") {
231
- installedVersion = getDependencyVersion(CachedEnvironmentDeps[dependencyName.toLowerCase()]);
232
- }
233
- else {
234
- installedVersion = CachedEnvironmentDeps[dependencyName.toLowerCase()].version;
235
- }
234
+ else {
235
+ installedVersion = CachedEnvironmentDeps[depName.toLowerCase()].version;
236
236
  }
237
- if (installedVersion) {
238
- if (manifestVersion.trim() !== installedVersion.trim()) {
239
- throw new Error(`Can't continue with analysis - versions mismatch for dependency name ${dependencyName} (manifest version=${manifestVersion}, installed version=${installedVersion}).If you want to allow version mismatch for analysis between installed and requested packages, set environment variable/setting MATCH_MANIFEST_VERSIONS=false`);
240
- }
237
+ }
238
+ if (installedVersion) {
239
+ if (manifestVersion.trim() !== installedVersion.trim()) {
240
+ throw new Error(`Can't continue with analysis - versions mismatch for dependency name ${depName} (manifest version=${manifestVersion}, installed version=${installedVersion}).If you want to allow version mismatch for analysis between installed and requested packages, set environment variable/setting MATCH_MANIFEST_VERSIONS=false`);
241
241
  }
242
242
  }
243
243
  }
244
- let path = new Array();
245
- let depName = getDependencyName(dep);
246
- //array to track a path for each branch in the dependency tree
244
+ let path = [];
247
245
  path.push(depName.toLowerCase());
248
246
  bringAllDependencies(dependencies, depName, CachedEnvironmentDeps, includeTransitive, path, usePipDepTree);
249
247
  });
@@ -347,11 +345,11 @@ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDep
347
345
  version = record.version;
348
346
  directDeps = record.dependencies;
349
347
  }
350
- let targetDeps = new Array();
348
+ let targetDeps = [];
351
349
  let entry = { "name": depName, "version": version, "dependencies": [] };
352
350
  dependencies.push(entry);
353
351
  directDeps.forEach((dep) => {
354
- let depArray = new Array();
352
+ let depArray = [];
355
353
  // to avoid infinite loop, check if the dependency not already on current path, before going recursively resolving its dependencies.
356
354
  if (!path.includes(dep.toLowerCase())) {
357
355
  // send to recurrsion the path + the current dep
@@ -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 DependencyEntry = {
@@ -23,13 +24,19 @@ declare function validateLockFile(): boolean;
23
24
  * Provide content and content type for python-pip component analysis.
24
25
  * @param {string} manifest - path to requirements.txt for component report
25
26
  * @param {{}} [opts={}] - optional various options to pass along the application
26
- * @returns {Provided}
27
+ * @returns {Promise<Provided>}
27
28
  */
28
- declare function provideComponent(manifest: string, opts?: {} | undefined): Provided;
29
+ declare function provideComponent(manifest: string, opts?: {}): Promise<Provided>;
29
30
  /**
30
31
  * Provide content and content type for python-pip stack analysis.
31
32
  * @param {string} manifest - the manifest path or name
32
33
  * @param {{}} [opts={}] - optional various options to pass along the application
33
- * @returns {Provided}
34
+ * @returns {Promise<Provided>}
34
35
  */
35
- declare function provideStack(manifest: string, opts?: {} | undefined): Provided;
36
+ declare function provideStack(manifest: string, opts?: {}): Promise<Provided>;
37
+ /**
38
+ * Python requirements.txt has no standard license field
39
+ * @param {string} manifestPath - path to requirements.txt
40
+ * @returns {string|null}
41
+ */
42
+ declare function readLicenseFromManifest(manifestPath: string): string | null;
@@ -1,10 +1,11 @@
1
1
  import fs from 'node:fs';
2
- import { EOL } from 'os';
3
2
  import { PackageURL } from 'packageurl-js';
3
+ import { readLicenseFile } from '../license/license_utils.js';
4
4
  import Sbom from '../sbom.js';
5
5
  import { environmentVariableIsPopulated, getCustom, getCustomPath, invokeCommand } from "../tools.js";
6
6
  import Python_controller from './python_controller.js';
7
- export default { isSupported, validateLockFile, provideComponent, provideStack };
7
+ import { getParser, getIgnoreQuery, getPinnedVersionQuery } from './requirements_parser.js';
8
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
8
9
  /** @typedef {{name: string, version: string, dependencies: DependencyEntry[]}} DependencyEntry */
9
10
  /**
10
11
  * @type {string} ecosystem for python-pip is 'pip'
@@ -18,6 +19,13 @@ const ecosystem = 'pip';
18
19
  function isSupported(manifestName) {
19
20
  return 'requirements.txt' === manifestName;
20
21
  }
22
+ /**
23
+ * Python requirements.txt has no standard license field
24
+ * @param {string} manifestPath - path to requirements.txt
25
+ * @returns {string|null}
26
+ */
27
+ // eslint-disable-next-line no-unused-vars
28
+ function readLicenseFromManifest(manifestPath) { return readLicenseFile(manifestPath); }
21
29
  /**
22
30
  * @param {string} manifestDir - the directory where the manifest lies
23
31
  */
@@ -26,12 +34,12 @@ function validateLockFile() { return true; }
26
34
  * Provide content and content type for python-pip stack analysis.
27
35
  * @param {string} manifest - the manifest path or name
28
36
  * @param {{}} [opts={}] - optional various options to pass along the application
29
- * @returns {Provided}
37
+ * @returns {Promise<Provided>}
30
38
  */
31
- function provideStack(manifest, opts = {}) {
39
+ async function provideStack(manifest, opts = {}) {
32
40
  return {
33
41
  ecosystem,
34
- content: createSbomStackAnalysis(manifest, opts),
42
+ content: await createSbomStackAnalysis(manifest, opts),
35
43
  contentType: 'application/vnd.cyclonedx+json'
36
44
  };
37
45
  }
@@ -39,12 +47,12 @@ function provideStack(manifest, opts = {}) {
39
47
  * Provide content and content type for python-pip component analysis.
40
48
  * @param {string} manifest - path to requirements.txt for component report
41
49
  * @param {{}} [opts={}] - optional various options to pass along the application
42
- * @returns {Provided}
50
+ * @returns {Promise<Provided>}
43
51
  */
44
- function provideComponent(manifest, opts = {}) {
52
+ async function provideComponent(manifest, opts = {}) {
45
53
  return {
46
54
  ecosystem,
47
- content: getSbomForComponentAnalysis(manifest, opts),
55
+ content: await getSbomForComponentAnalysis(manifest, opts),
48
56
  contentType: 'application/vnd.cyclonedx+json'
49
57
  };
50
58
  }
@@ -66,49 +74,34 @@ function addAllDependencies(source, dep, sbom) {
66
74
  }
67
75
  /**
68
76
  *
69
- * @param nameVersion
70
- * @return {string}
71
- */
72
- function splitToNameVersion(nameVersion) {
73
- let result = [];
74
- if (nameVersion.includes("==")) {
75
- return nameVersion.split("==");
76
- }
77
- const regex = /[^\w\s-_]/g;
78
- let endIndex = nameVersion.search(regex);
79
- if (endIndex === -1) {
80
- return [nameVersion.trim()];
81
- }
82
- result.push(nameVersion.substring(0, endIndex).trim());
83
- return result;
84
- }
85
- /**
86
- *
87
- * @param {string} requirementTxtContent
77
+ * @param {string} manifest - path to requirements.txt
88
78
  * @return {PackageURL []}
89
79
  */
90
- function getIgnoredDependencies(requirementTxtContent) {
91
- let requirementsLines = requirementTxtContent.split(EOL);
92
- return requirementsLines
93
- .filter(line => line.includes("#exhortignore") || line.includes("# exhortignore"))
94
- .map((line) => line.substring(0, line.indexOf("#")).trim())
95
- .map((name) => {
96
- let nameVersion = splitToNameVersion(name);
97
- if (nameVersion.length === 2) {
98
- return toPurl(nameVersion[0], nameVersion[1]);
99
- }
100
- return toPurl(nameVersion[0], undefined);
80
+ async function getIgnoredDependencies(manifest) {
81
+ const [parser, ignoreQuery, pinnedVersionQuery] = await Promise.all([
82
+ getParser(), getIgnoreQuery(), getPinnedVersionQuery()
83
+ ]);
84
+ const content = fs.readFileSync(manifest).toString();
85
+ const tree = parser.parse(content);
86
+ return ignoreQuery.matches(tree.rootNode).map(match => {
87
+ const reqNode = match.captures.find(c => c.name === 'req').node;
88
+ const name = match.captures.find(c => c.name === 'name').node.text;
89
+ const versionMatches = pinnedVersionQuery.matches(reqNode);
90
+ const version = versionMatches.length > 0
91
+ ? versionMatches[0].captures.find(c => c.name === 'version').node.text
92
+ : undefined;
93
+ return toPurl(name, version);
101
94
  });
102
95
  }
103
96
  /**
104
97
  *
105
- * @param {string} requirementTxtContent content of requirments.txt in string
98
+ * @param {string} manifest - path to requirements.txt
106
99
  * @param {Sbom} sbom object to filter out from it exhortignore dependencies.
107
100
  * @param {{Object}} opts - various options and settings for the application
108
101
  * @private
109
102
  */
110
- function handleIgnoredDependencies(requirementTxtContent, sbom, opts = {}) {
111
- let ignoredDeps = getIgnoredDependencies(requirementTxtContent);
103
+ async function handleIgnoredDependencies(manifest, sbom, opts = {}) {
104
+ let ignoredDeps = await getIgnoredDependencies(manifest);
112
105
  let matchManifestVersions = getCustom("MATCH_MANIFEST_VERSIONS", "true", opts);
113
106
  if (matchManifestVersions === "true") {
114
107
  const ignoredDepsVersion = ignoredDeps.filter(dep => dep.version !== undefined);
@@ -172,22 +165,22 @@ const DEFAULT_PIP_ROOT_COMPONENT_VERSION = "0.0.0";
172
165
  * Create sbom json string out of a manifest path for stack analysis.
173
166
  * @param {string} manifest - path for requirements.txt
174
167
  * @param {{}} [opts={}] - optional various options to pass along the application
175
- * @returns {string} the sbom json string content
168
+ * @returns {Promise<string>} the sbom json string content
176
169
  * @private
177
170
  */
178
- function createSbomStackAnalysis(manifest, opts = {}) {
171
+ async function createSbomStackAnalysis(manifest, opts = {}) {
179
172
  let binaries = {};
180
173
  let createVirtualPythonEnv = handlePythonEnvironment(binaries, opts);
181
174
  let pythonController = new Python_controller(createVirtualPythonEnv === "false", binaries.pip, binaries.python, manifest, opts);
182
- let dependencies = pythonController.getDependencies(true);
175
+ let dependencies = await pythonController.getDependencies(true);
183
176
  let sbom = new Sbom();
184
177
  const rootPurl = toPurl(DEFAULT_PIP_ROOT_COMPONENT_NAME, DEFAULT_PIP_ROOT_COMPONENT_VERSION);
185
- sbom.addRoot(rootPurl);
178
+ const license = readLicenseFromManifest(manifest);
179
+ sbom.addRoot(rootPurl, license);
186
180
  dependencies.forEach(dep => {
187
181
  addAllDependencies(rootPurl, dep, sbom);
188
182
  });
189
- let requirementTxtContent = fs.readFileSync(manifest).toString();
190
- handleIgnoredDependencies(requirementTxtContent, sbom, opts);
183
+ await handleIgnoredDependencies(manifest, sbom, opts);
191
184
  // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by the DA backend
192
185
  // sbom.removeRootComponent()
193
186
  return sbom.getAsJsonString(opts);
@@ -196,22 +189,22 @@ function createSbomStackAnalysis(manifest, opts = {}) {
196
189
  * Create a sbom json string out of a manifest content for component analysis
197
190
  * @param {string} manifest - path to requirements.txt
198
191
  * @param {{}} [opts={}] - optional various options to pass along the application
199
- * @returns {string} the sbom json string content
192
+ * @returns {Promise<string>} the sbom json string content
200
193
  * @private
201
194
  */
202
- function getSbomForComponentAnalysis(manifest, opts = {}) {
195
+ async function getSbomForComponentAnalysis(manifest, opts = {}) {
203
196
  let binaries = {};
204
197
  let createVirtualPythonEnv = handlePythonEnvironment(binaries, opts);
205
198
  let pythonController = new Python_controller(createVirtualPythonEnv === "false", binaries.pip, binaries.python, manifest, opts);
206
- let dependencies = pythonController.getDependencies(false);
199
+ let dependencies = await pythonController.getDependencies(false);
207
200
  let sbom = new Sbom();
208
201
  const rootPurl = toPurl(DEFAULT_PIP_ROOT_COMPONENT_NAME, DEFAULT_PIP_ROOT_COMPONENT_VERSION);
209
- sbom.addRoot(rootPurl);
202
+ const license = readLicenseFromManifest(manifest);
203
+ sbom.addRoot(rootPurl, license);
210
204
  dependencies.forEach(dep => {
211
205
  sbom.addDependency(rootPurl, toPurl(dep.name, dep.version));
212
206
  });
213
- let requirementTxtContent = fs.readFileSync(manifest).toString();
214
- handleIgnoredDependencies(requirementTxtContent, sbom, opts);
207
+ await handleIgnoredDependencies(manifest, sbom, opts);
215
208
  // In python there is no root component, then we must remove the dummy root we added, so the sbom json will be accepted by the DA backend
216
209
  // sbom.removeRootComponent()
217
210
  return sbom.getAsJsonString(opts);
@@ -0,0 +1,6 @@
1
+ export function getParser(): Promise<Parser>;
2
+ export function getRequirementQuery(): Promise<Query>;
3
+ export function getIgnoreQuery(): Promise<Query>;
4
+ export function getPinnedVersionQuery(): Promise<Query>;
5
+ import { Parser } from 'web-tree-sitter';
6
+ import { Query } from 'web-tree-sitter';
@@ -0,0 +1,24 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { Language, Parser, Query } from 'web-tree-sitter';
3
+ const wasmUrl = new URL('./tree-sitter-requirements.wasm', import.meta.url);
4
+ async function init() {
5
+ await Parser.init();
6
+ const wasmBytes = new Uint8Array(await readFile(wasmUrl));
7
+ return await Language.load(wasmBytes);
8
+ }
9
+ export async function getParser() {
10
+ const language = await init();
11
+ return new Parser().setLanguage(language);
12
+ }
13
+ export async function getRequirementQuery() {
14
+ const language = await init();
15
+ return new Query(language, '(requirement (package) @name) @req');
16
+ }
17
+ export async function getIgnoreQuery() {
18
+ const language = await init();
19
+ return new Query(language, '((requirement (package) @name) @req . (comment) @comment (#match? @comment "^#[\\t ]*exhortignore"))');
20
+ }
21
+ export async function getPinnedVersionQuery() {
22
+ const language = await init();
23
+ return new Query(language, '(version_spec (version_cmp) @cmp (version) @version (#eq? @cmp "=="))');
24
+ }
@@ -2,9 +2,10 @@ export default class Sbom {
2
2
  sbomModel: CycloneDxSbom;
3
3
  /**
4
4
  * @param {PackageURL} root - add main/root component for sbom
5
+ * @param {string|Array} [licenses] - optional license(s) for the root component
5
6
  * @return Sbom
6
7
  */
7
- addRoot(root: PackageURL): CycloneDxSbom;
8
+ addRoot(root: PackageURL, licenses?: string | any[]): CycloneDxSbom;
8
9
  /**
9
10
  * @return {{{"bom-ref": string, name, purl: string, type, version}}} root component of sbom.
10
11
  */
@@ -43,6 +44,7 @@ export default class Sbom {
43
44
  type: any;
44
45
  version: any;
45
46
  scope: any;
47
+ licenses?: any;
46
48
  };
47
49
  /** This method gets a component object, and a string name, and checks if the name is a substring of the component' purl.
48
50
  * @param {} component to search in its dependencies
package/dist/src/sbom.js CHANGED
@@ -12,10 +12,11 @@ export default class Sbom {
12
12
  }
13
13
  /**
14
14
  * @param {PackageURL} root - add main/root component for sbom
15
+ * @param {string|Array} [licenses] - optional license(s) for the root component
15
16
  * @return Sbom
16
17
  */
17
- addRoot(root) {
18
- return this.sbomModel.addRoot(root);
18
+ addRoot(root, licenses) {
19
+ return this.sbomModel.addRoot(root, licenses);
19
20
  }
20
21
  /**
21
22
  * @return {{{"bom-ref": string, name, purl: string, type, version}}} root component of sbom.
@@ -1,12 +1,10 @@
1
- /// <reference types="node" />
2
- /// <reference types="packageurl-js/src/package-url" />
3
1
  /**
4
2
  *
5
3
  * @param {string} key to log its value from environment variables and from opts, if it exists
6
4
  * @param {{}} [opts={}] different options of application, if key in it, log it.
7
5
  * @param {string }defValue default value of key in case there is no option and environment variable values for key
8
6
  */
9
- export function logValueFromObjects(key: string, opts?: {} | undefined, defValue: string): void;
7
+ export function logValueFromObjects(key: string, opts?: {}, defValue: string): void;
10
8
  /**
11
9
  * Utility function will return the value for key from the environment variables,
12
10
  * if not present will return the value for key from the opts objects only if it's a string,
@@ -17,7 +15,7 @@ export function logValueFromObjects(key: string, opts?: {} | undefined, defValue
17
15
  * @returns {string|null} the value of the key found in the environment, options object, or the
18
16
  * default supplied
19
17
  */
20
- export function getCustom(key: string, def?: string | null | undefined, opts?: {} | undefined): string | null;
18
+ export function getCustom(key: string, def?: string | null, opts?: {}): string | null;
21
19
  /**
22
20
  * Utility function for looking up custom variable for a binary path.
23
21
  * Will look in the environment variables (1) or in opts (2) for a key with TRUSTIFY_DA_x_PATH, x is an
@@ -28,7 +26,7 @@ export function getCustom(key: string, def?: string | null | undefined, opts?: {
28
26
  * @returns {string|null} the value of the key found in the environment, options object, or the
29
27
  * original name supplied
30
28
  */
31
- export function getCustomPath(name: any, opts?: {} | undefined): string | null;
29
+ export function getCustomPath(name: any, opts?: {}): string | null;
32
30
  /**
33
31
  * Utility function for determining whether wrappers for build tools such as gradlew/mvnw should be
34
32
  * preferred over invoking the binary directly.
@@ -69,6 +67,24 @@ export function getGitRootDir(cwd: string): string | undefined;
69
67
  * @param {import('child_process').ExecFileOptionsWithStringEncoding} [opts={}]
70
68
  * @returns {string}
71
69
  */
72
- export function invokeCommand(bin: string, args: Array<string>, opts?: import("child_process").ExecFileOptionsWithStringEncoding | undefined): string;
70
+ export function invokeCommand(bin: string, args: Array<string>, opts?: import("child_process").ExecFileOptionsWithStringEncoding): string;
71
+ /**
72
+ * Adds proxy agent configuration to fetch options if a proxy URL is specified
73
+ * @param {RequestInit} options - The base fetch options
74
+ * @param {import("index.js").Options} opts - The trustify DA options that may contain proxy configuration
75
+ * @returns {RequestInit} The fetch options with proxy agent if applicable
76
+ */
77
+ export function addProxyAgent(options: RequestInit, opts: import("index.js").Options): RequestInit;
78
+ /**
79
+ * Utility function for fetching vendor tokens
80
+ * @param {import("index.js").Options} [opts={}] - optional various options to pass along the application
81
+ * @returns {{}}
82
+ */
83
+ export function getTokenHeaders(opts?: import("index.js").Options): {};
73
84
  export const RegexNotToBeLogged: RegExp;
85
+ export const TRUSTIFY_DA_TOKEN_HEADER: "trust-da-token";
86
+ export const TRUSTIFY_DA_TELEMETRY_ID_HEADER: "telemetry-anonymous-id";
87
+ export const TRUSTIFY_DA_SOURCE_HEADER: "trust-da-source";
88
+ export const TRUSTIFY_DA_OPERATION_TYPE_HEADER: "trust-da-operation-type";
89
+ export const TRUSTIFY_DA_PACKAGE_MANAGER_HEADER: "trust-da-pkg-manager";
74
90
  import { PackageURL } from "packageurl-js";
package/dist/src/tools.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { execFileSync } from "child_process";
2
2
  import { EOL } from "os";
3
+ import { HttpsProxyAgent } from "https-proxy-agent";
3
4
  import { PackageURL } from "packageurl-js";
4
- export const RegexNotToBeLogged = /TRUSTIFY_DA_.*_TOKEN|ex-.*-token/;
5
+ export const RegexNotToBeLogged = /TRUSTIFY_DA_(.*_)?TOKEN|ex-.*-token|trust-.*-token/;
5
6
  /**
6
7
  *
7
8
  * @param {string} key to log its value from environment variables and from opts, if it exists
@@ -157,3 +158,57 @@ export function invokeCommand(bin, args, opts = {}) {
157
158
  };
158
159
  return execFileSync(bin, args, { ...{ stdio: 'pipe', encoding: 'utf-8' }, ...opts });
159
160
  }
161
+ export const TRUSTIFY_DA_TOKEN_HEADER = "trust-da-token";
162
+ export const TRUSTIFY_DA_TELEMETRY_ID_HEADER = "telemetry-anonymous-id";
163
+ export const TRUSTIFY_DA_SOURCE_HEADER = "trust-da-source";
164
+ export const TRUSTIFY_DA_OPERATION_TYPE_HEADER = "trust-da-operation-type";
165
+ export const TRUSTIFY_DA_PACKAGE_MANAGER_HEADER = "trust-da-pkg-manager";
166
+ /**
167
+ * Adds proxy agent configuration to fetch options if a proxy URL is specified
168
+ * @param {RequestInit} options - The base fetch options
169
+ * @param {import("index.js").Options} opts - The trustify DA options that may contain proxy configuration
170
+ * @returns {RequestInit} The fetch options with proxy agent if applicable
171
+ */
172
+ export function addProxyAgent(options, opts) {
173
+ const proxyUrl = getCustom('TRUSTIFY_DA_PROXY_URL', null, opts);
174
+ if (proxyUrl) {
175
+ options.agent = new HttpsProxyAgent(proxyUrl);
176
+ }
177
+ return options;
178
+ }
179
+ /**
180
+ * Utility function for fetching vendor tokens
181
+ * @param {import("index.js").Options} [opts={}] - optional various options to pass along the application
182
+ * @returns {{}}
183
+ */
184
+ export function getTokenHeaders(opts = {}) {
185
+ let headers = {};
186
+ setCustomHeader(TRUSTIFY_DA_TOKEN_HEADER, headers, 'TRUSTIFY_DA_TOKEN', opts);
187
+ setCustomHeader(TRUSTIFY_DA_SOURCE_HEADER, headers, 'TRUSTIFY_DA_SOURCE', opts);
188
+ setCustomHeader(TRUSTIFY_DA_OPERATION_TYPE_HEADER, headers, TRUSTIFY_DA_OPERATION_TYPE_HEADER.toUpperCase().replaceAll("-", "_"), opts);
189
+ setCustomHeader(TRUSTIFY_DA_PACKAGE_MANAGER_HEADER, headers, TRUSTIFY_DA_PACKAGE_MANAGER_HEADER.toUpperCase().replaceAll("-", "_"), opts);
190
+ setCustomHeader(TRUSTIFY_DA_TELEMETRY_ID_HEADER, headers, 'TRUSTIFY_DA_TELEMETRY_ID', opts);
191
+ if (getCustom("TRUSTIFY_DA_DEBUG", null, opts) === "true") {
192
+ console.log("Headers Values to be sent to Trustify DA backend:" + EOL);
193
+ for (const headerKey in headers) {
194
+ if (!headerKey.match(RegexNotToBeLogged)) {
195
+ console.log(`${headerKey}: ${headers[headerKey]}`);
196
+ }
197
+ }
198
+ }
199
+ return headers;
200
+ }
201
+ /**
202
+ *
203
+ * @param {string} headerName - the header name to populate in request
204
+ * @param headers
205
+ * @param {string} optsKey - key in the options object to use the value for
206
+ * @param {import("index.js").Options} [opts={}] - options input object to fetch header values from
207
+ * @private
208
+ */
209
+ function setCustomHeader(headerName, headers, optsKey, opts) {
210
+ let customHeaderValue = getCustom(optsKey, null, opts);
211
+ if (customHeaderValue) {
212
+ headers[headerName] = customHeaderValue;
213
+ }
214
+ }