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

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 (73) hide show
  1. package/README.md +57 -3
  2. package/dist/package.json +26 -23
  3. package/dist/src/analysis.d.ts +14 -7
  4. package/dist/src/analysis.js +32 -15
  5. package/dist/src/cli.js +109 -3
  6. package/dist/src/cyclone_dx_sbom.d.ts +14 -1
  7. package/dist/src/cyclone_dx_sbom.js +43 -8
  8. package/dist/src/index.d.ts +84 -11
  9. package/dist/src/index.js +95 -8
  10. package/dist/src/license/index.d.ts +3 -3
  11. package/dist/src/license/index.js +4 -1
  12. package/dist/src/license/license_utils.js +4 -1
  13. package/dist/src/license/licenses_api.d.ts +2 -2
  14. package/dist/src/oci_image/images.d.ts +1 -1
  15. package/dist/src/oci_image/images.js +15 -1
  16. package/dist/src/oci_image/utils.d.ts +5 -5
  17. package/dist/src/oci_image/utils.js +11 -2
  18. package/dist/src/provider.d.ts +4 -3
  19. package/dist/src/provider.js +12 -2
  20. package/dist/src/providers/base_java.d.ts +14 -12
  21. package/dist/src/providers/base_java.js +18 -44
  22. package/dist/src/providers/base_javascript.d.ts +20 -9
  23. package/dist/src/providers/base_javascript.js +44 -6
  24. package/dist/src/providers/base_pyproject.d.ts +158 -0
  25. package/dist/src/providers/base_pyproject.js +322 -0
  26. package/dist/src/providers/containerfile_parser.d.ts +5 -0
  27. package/dist/src/providers/containerfile_parser.js +20 -0
  28. package/dist/src/providers/golang_gomodules.d.ts +11 -1
  29. package/dist/src/providers/golang_gomodules.js +65 -8
  30. package/dist/src/providers/java_gradle.d.ts +19 -0
  31. package/dist/src/providers/java_gradle.js +116 -2
  32. package/dist/src/providers/java_gradle_groovy.d.ts +1 -1
  33. package/dist/src/providers/java_gradle_kotlin.d.ts +1 -1
  34. package/dist/src/providers/java_maven.d.ts +10 -2
  35. package/dist/src/providers/java_maven.js +165 -1
  36. package/dist/src/providers/javascript_bun.d.ts +10 -0
  37. package/dist/src/providers/javascript_bun.js +100 -0
  38. package/dist/src/providers/javascript_npm.d.ts +6 -0
  39. package/dist/src/providers/javascript_npm.js +21 -0
  40. package/dist/src/providers/javascript_pnpm.js +6 -2
  41. package/dist/src/providers/manifest.d.ts +2 -0
  42. package/dist/src/providers/manifest.js +22 -4
  43. package/dist/src/providers/marker_evaluator.d.ts +14 -0
  44. package/dist/src/providers/marker_evaluator.js +191 -0
  45. package/dist/src/providers/oci_dockerfile.d.ts +51 -0
  46. package/dist/src/providers/oci_dockerfile.js +177 -0
  47. package/dist/src/providers/processors/yarn_berry_processor.d.ts +2 -2
  48. package/dist/src/providers/processors/yarn_berry_processor.js +88 -5
  49. package/dist/src/providers/processors/yarn_classic_processor.d.ts +2 -2
  50. package/dist/src/providers/python_controller.d.ts +5 -1
  51. package/dist/src/providers/python_controller.js +65 -7
  52. package/dist/src/providers/python_pip.d.ts +5 -0
  53. package/dist/src/providers/python_pip.js +5 -5
  54. package/dist/src/providers/python_pip_pyproject.d.ts +61 -0
  55. package/dist/src/providers/python_pip_pyproject.js +146 -0
  56. package/dist/src/providers/python_poetry.d.ts +98 -0
  57. package/dist/src/providers/python_poetry.js +286 -0
  58. package/dist/src/providers/python_uv.d.ts +46 -0
  59. package/dist/src/providers/python_uv.js +269 -0
  60. package/dist/src/providers/rust_cargo.d.ts +6 -2
  61. package/dist/src/providers/rust_cargo.js +31 -4
  62. package/dist/src/providers/tree-sitter-containerfile.wasm +0 -0
  63. package/dist/src/sbom.d.ts +14 -1
  64. package/dist/src/sbom.js +13 -2
  65. package/dist/src/tools.d.ts +28 -2
  66. package/dist/src/tools.js +58 -0
  67. package/dist/src/updaters/maven_updater.d.ts +26 -0
  68. package/dist/src/updaters/maven_updater.js +322 -0
  69. package/dist/src/updaters/toml_updater.d.ts +33 -0
  70. package/dist/src/updaters/toml_updater.js +244 -0
  71. package/dist/src/workspace.d.ts +9 -0
  72. package/dist/src/workspace.js +1 -1
  73. package/package.json +27 -24
@@ -0,0 +1,177 @@
1
+ import fs from 'node:fs';
2
+ import { generateImageSBOM, parseImageRef } from '../oci_image/utils.js';
3
+ import { getArgQuery, getFromQuery, getParser } from './containerfile_parser.js';
4
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'oci'; } };
5
+ /** @typedef {import('../provider').Provider} */
6
+ /** @typedef {import('../provider').Provided} Provided */
7
+ /**
8
+ * @type {string} ecosystem identifier for OCI image packages
9
+ * @private
10
+ */
11
+ const ecosystem = 'oci';
12
+ /**
13
+ * Check if the given manifest name is a Dockerfile or Containerfile.
14
+ * Supports dot-suffixed variants such as Dockerfile.dev or Containerfile.prod.
15
+ * @param {string} manifestName the manifest file name to check
16
+ * @returns {boolean} true if the manifest is a Dockerfile or Containerfile
17
+ */
18
+ function isSupported(manifestName) {
19
+ return /^(Dockerfile|Containerfile)(\..+)?$/.test(manifestName);
20
+ }
21
+ /**
22
+ * Dockerfiles have no lock file, so validation always passes.
23
+ * @returns {boolean} always true
24
+ */
25
+ function validateLockFile() { return true; }
26
+ /**
27
+ * Check whether a syntax node contains any expansion (variable substitution) children.
28
+ * @param {import('web-tree-sitter').SyntaxNode} node
29
+ * @returns {boolean}
30
+ * @private
31
+ */
32
+ function containsExpansion(node) {
33
+ if (node.type === 'expansion') {
34
+ return true;
35
+ }
36
+ for (let i = 0; i < node.childCount; i++) {
37
+ if (containsExpansion(node.child(i))) {
38
+ return true;
39
+ }
40
+ }
41
+ return false;
42
+ }
43
+ /**
44
+ * Strip surrounding single or double quotes from a string.
45
+ * @param {string} text
46
+ * @returns {string}
47
+ * @private
48
+ */
49
+ function stripQuotes(text) {
50
+ if ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) {
51
+ return text.slice(1, -1);
52
+ }
53
+ return text;
54
+ }
55
+ /**
56
+ * Collect ARG key-value pairs from the Dockerfile AST.
57
+ * Only ARGs with a default value are collected (ARGs without defaults cannot be resolved statically).
58
+ * @param {import('web-tree-sitter').Tree} tree the parsed Dockerfile tree
59
+ * @param {import('web-tree-sitter').Query} argQuery the tree-sitter query for arg_instruction nodes
60
+ * @returns {Map<string, string>} map of ARG names to their default values
61
+ * @private
62
+ */
63
+ function collectArgs(tree, argQuery) {
64
+ const args = new Map();
65
+ for (const match of argQuery.matches(tree.rootNode)) {
66
+ const name = match.captures.find(c => c.name === 'name')?.node.text;
67
+ const defaultValue = match.captures.find(c => c.name === 'default')?.node.text;
68
+ if (name && defaultValue) {
69
+ args.set(name, stripQuotes(defaultValue));
70
+ }
71
+ }
72
+ return args;
73
+ }
74
+ /**
75
+ * Resolve ARG substitutions in an image spec text using the collected ARG map.
76
+ * Replaces ${VAR} and $VAR patterns with their ARG default values.
77
+ * @param {string} text the image spec text potentially containing variable references
78
+ * @param {Map<string, string>} args map of ARG names to their default values
79
+ * @returns {string|null} the resolved text, or null if any variable could not be resolved
80
+ * @private
81
+ */
82
+ function resolveArgs(text, args) {
83
+ let resolved = text;
84
+ let hasUnresolved = false;
85
+ resolved = resolved.replace(/\$\{([^}]+)\}|\$([A-Za-z_]\w*)/g, (_match, braced, plain) => {
86
+ const key = braced || plain;
87
+ if (args.has(key)) {
88
+ return args.get(key);
89
+ }
90
+ hasUnresolved = true;
91
+ return _match;
92
+ });
93
+ return hasUnresolved ? null : resolved;
94
+ }
95
+ /**
96
+ * Parse all FROM instructions from a Dockerfile using tree-sitter to extract base image references.
97
+ * In multi-stage builds, every FROM line is returned so each image can be analyzed independently.
98
+ * ARG substitutions are resolved using declared default values. FROM lines with unresolvable
99
+ * variables (ARGs without defaults) are silently skipped.
100
+ * @param {string} manifestContent the content of the Dockerfile
101
+ * @returns {Promise<string[]>} array of image references from all resolvable FROM instructions
102
+ * @throws {Error} when no FROM instruction is found or when no FROM lines can be resolved
103
+ */
104
+ export async function parseAllFromImages(manifestContent) {
105
+ const [parser, fromQuery, argQuery] = await Promise.all([getParser(), getFromQuery(), getArgQuery()]);
106
+ const tree = parser.parse(manifestContent);
107
+ const matches = fromQuery.matches(tree.rootNode);
108
+ if (matches.length === 0) {
109
+ throw new Error('No FROM line found in Dockerfile');
110
+ }
111
+ const args = collectArgs(tree, argQuery);
112
+ const images = [];
113
+ for (const match of matches) {
114
+ const imageSpec = match.captures.find(c => c.name === 'image').node;
115
+ if (containsExpansion(imageSpec)) {
116
+ const resolved = resolveArgs(imageSpec.text, args);
117
+ if (resolved != null) {
118
+ images.push(resolved);
119
+ }
120
+ continue;
121
+ }
122
+ images.push(imageSpec.text);
123
+ }
124
+ if (images.length === 0) {
125
+ throw new Error('Dockerfile uses ARG substitution in all FROM lines — cannot resolve variable references');
126
+ }
127
+ return images;
128
+ }
129
+ /**
130
+ * Generate image SBOMs for all FROM instructions in a Dockerfile manifest using syft.
131
+ * Returns a batch result with a purl-to-SBOM map suitable for the batch-analysis endpoint.
132
+ * @param {string} manifest path to the Dockerfile
133
+ * @param {{}} [opts={}] optional various options to pass along the application
134
+ * @returns {Promise<{ecosystem: string, content: string, contentType: string, batch: boolean}>}
135
+ * @private
136
+ */
137
+ async function getImageSBOM(manifest, opts = {}) {
138
+ const manifestContent = fs.readFileSync(manifest, 'utf-8');
139
+ const images = await parseAllFromImages(manifestContent);
140
+ const sbomByPurl = {};
141
+ for (const image of images) {
142
+ const imageRef = parseImageRef(image, opts);
143
+ const purl = imageRef.getPackageURL().toString();
144
+ if (purl in sbomByPurl)
145
+ continue;
146
+ sbomByPurl[purl] = generateImageSBOM(imageRef, opts);
147
+ }
148
+ return {
149
+ ecosystem,
150
+ content: JSON.stringify(sbomByPurl),
151
+ contentType: 'application/vnd.cyclonedx+json',
152
+ batch: true
153
+ };
154
+ }
155
+ /**
156
+ * Provide content and content type for Dockerfile component analysis.
157
+ * @param {string} manifest path to the Dockerfile
158
+ * @param {{}} [opts={}] optional various options to pass along the application
159
+ * @returns {Promise<Provided>}
160
+ */
161
+ async function provideComponent(manifest, opts = {}) {
162
+ return getImageSBOM(manifest, opts);
163
+ }
164
+ /**
165
+ * Provide content and content type for Dockerfile stack analysis.
166
+ * @param {string} manifest path to the Dockerfile
167
+ * @param {{}} [opts={}] optional various options to pass along the application
168
+ * @returns {Promise<Provided>}
169
+ */
170
+ async function provideStack(manifest, opts = {}) {
171
+ return getImageSBOM(manifest, opts);
172
+ }
173
+ /**
174
+ * Dockerfiles contain no license information.
175
+ * @returns {null} always null
176
+ */
177
+ function readLicenseFromManifest() { return null; }
@@ -29,13 +29,13 @@ export default class Yarn_berry_processor extends Yarn_processor {
29
29
  * @param {Object} depTree - The dependency tree object
30
30
  * @returns {Map<string, PackageURL>} Map of dependency names to their PackageURL objects
31
31
  */
32
- getRootDependencies(depTree: any): Map<string, PackageURL>;
32
+ getRootDependencies(depTree: Object): Map<string, PackageURL>;
33
33
  /**
34
34
  * Adds dependencies to the SBOM
35
35
  * @param {Sbom} sbom - The SBOM object to add dependencies to
36
36
  * @param {Object} depTree - The dependency tree object
37
37
  */
38
- addDependenciesToSbom(sbom: Sbom, depTree: any): void;
38
+ addDependenciesToSbom(sbom: Sbom, depTree: Object): void;
39
39
  #private;
40
40
  }
41
41
  import Yarn_processor from "./yarn_processor.js";
@@ -15,7 +15,10 @@ export default class Yarn_berry_processor extends Yarn_processor {
15
15
  * @returns {string[]} Command arguments for listing dependencies
16
16
  */
17
17
  listCmdArgs(includeTransitive) {
18
- return ['info', includeTransitive ? '--recursive' : '--all', '--json'];
18
+ // --all is needed to include workspace members in the output
19
+ return includeTransitive
20
+ ? ['info', '--recursive', '--all', '--json']
21
+ : ['info', '--all', '--json'];
19
22
  }
20
23
  /**
21
24
  * Returns the command arguments for updating the lock file
@@ -48,13 +51,15 @@ export default class Yarn_berry_processor extends Yarn_processor {
48
51
  if (!depTree) {
49
52
  return new Map();
50
53
  }
51
- return new Map(depTree.filter(dep => !this.#isRoot(dep.value)).map(dep => {
54
+ return new Map(depTree.filter(dep => !this.#isRoot(dep.value))
55
+ .map(dep => {
52
56
  const depName = dep.value;
53
57
  const idx = depName.lastIndexOf('@');
54
58
  const name = depName.substring(0, idx);
55
59
  const version = dep.children.Version;
56
60
  return [name, toPurl(purlType, name, version)];
57
- }));
61
+ })
62
+ .filter(([name]) => this._manifest.dependencies.includes(name)));
58
63
  }
59
64
  /**
60
65
  * Checks if a dependency is the root package
@@ -66,7 +71,8 @@ export default class Yarn_berry_processor extends Yarn_processor {
66
71
  if (!name) {
67
72
  return false;
68
73
  }
69
- return name.endsWith("@workspace:.");
74
+ // Workspace members use paths like "member-a@workspace:packages/member-a", not just "@workspace:."
75
+ return name.startsWith(`${this._manifest.name}@workspace:`);
70
76
  }
71
77
  /**
72
78
  * Adds dependencies to the SBOM
@@ -77,14 +83,58 @@ export default class Yarn_berry_processor extends Yarn_processor {
77
83
  if (!depTree) {
78
84
  return;
79
85
  }
86
+ // Build index of nodes by their value for quick lookup
87
+ const nodeIndex = new Map();
88
+ depTree.forEach(n => nodeIndex.set(n.value, n));
89
+ // Determine the set of node values reachable from root via production deps
90
+ const prodDeps = new Set(this._manifest.dependencies);
91
+ const reachable = new Set();
92
+ const queue = [];
93
+ // Seed with root's production dependencies
94
+ const rootNode = depTree.find(n => this.#isRoot(n.value));
95
+ if (rootNode?.children?.Dependencies) {
96
+ for (const d of rootNode.children.Dependencies) {
97
+ const to = this.#purlFromLocator(d.locator);
98
+ if (to) {
99
+ const fullName = to.namespace ? `${to.namespace}/${to.name}` : to.name;
100
+ if (prodDeps.has(fullName)) {
101
+ queue.push(d.locator);
102
+ }
103
+ }
104
+ }
105
+ }
106
+ // BFS to find all transitively reachable packages
107
+ while (queue.length > 0) {
108
+ const locator = queue.shift();
109
+ if (reachable.has(locator)) {
110
+ continue;
111
+ }
112
+ reachable.add(locator);
113
+ const node = nodeIndex.get(this.#nodeValueFromLocator(locator));
114
+ if (node?.children?.Dependencies) {
115
+ for (const d of node.children.Dependencies) {
116
+ if (!reachable.has(d.locator)) {
117
+ queue.push(d.locator);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ // Only emit edges for root and reachable nodes
80
123
  depTree.forEach(n => {
81
124
  const depName = n.value;
82
- const from = this.#isRoot(depName) ? toPurlFromString(sbom.getRoot().purl) : this.#purlFromNode(depName, n);
125
+ const isRoot = this.#isRoot(depName);
126
+ if (!isRoot && !this.#isReachableNode(depName, reachable)) {
127
+ return;
128
+ }
129
+ const from = isRoot ? toPurlFromString(sbom.getRoot().purl) : this.#purlFromNode(depName, n);
83
130
  const deps = n.children?.Dependencies;
84
131
  if (!deps) {
85
132
  return;
86
133
  }
87
134
  deps.forEach(d => {
135
+ if (!reachable.has(d.locator)) {
136
+ return;
137
+ }
88
138
  const to = this.#purlFromLocator(d.locator);
89
139
  if (to) {
90
140
  sbom.addDependency(from, to);
@@ -92,6 +142,39 @@ export default class Yarn_berry_processor extends Yarn_processor {
92
142
  });
93
143
  });
94
144
  }
145
+ /**
146
+ * Converts a locator to the node value format used in yarn info output
147
+ * @param {string} locator - e.g. "express@npm:4.17.1"
148
+ * @returns {string} The node value, same as locator for non-virtual
149
+ * @private
150
+ */
151
+ #nodeValueFromLocator(locator) {
152
+ // Virtual locators: "@scope/name@virtual:hash#npm:version" → "@scope/name@npm:version"
153
+ const virtualMatch = Yarn_berry_processor.VIRTUAL_LOCATOR_PATTERN.exec(locator);
154
+ if (virtualMatch) {
155
+ return `${virtualMatch[1]}@npm:${virtualMatch[2]}`;
156
+ }
157
+ return locator;
158
+ }
159
+ /**
160
+ * Checks if a node is in the reachable set by matching its value against reachable locators
161
+ * @param {string} depName - The node value (e.g. "express@npm:4.17.1")
162
+ * @param {Set<string>} reachable - Set of reachable locators
163
+ * @returns {boolean}
164
+ * @private
165
+ */
166
+ #isReachableNode(depName, reachable) {
167
+ if (reachable.has(depName)) {
168
+ return true;
169
+ }
170
+ // Check if any reachable locator resolves to this node value
171
+ for (const locator of reachable) {
172
+ if (this.#nodeValueFromLocator(locator) === depName) {
173
+ return true;
174
+ }
175
+ }
176
+ return false;
177
+ }
95
178
  /**
96
179
  * Creates a PackageURL from a dependency locator
97
180
  * @param {string} locator - The dependency locator
@@ -25,13 +25,13 @@ export default class Yarn_classic_processor extends Yarn_processor {
25
25
  * @param {Object} depTree - The dependency tree object
26
26
  * @returns {Map<string, PackageURL>} Map of dependency names to their PackageURL objects
27
27
  */
28
- getRootDependencies(depTree: any): Map<string, PackageURL>;
28
+ getRootDependencies(depTree: Object): Map<string, PackageURL>;
29
29
  /**
30
30
  * Adds dependencies to the SBOM
31
31
  * @param {Sbom} sbom - The SBOM object to add dependencies to
32
32
  * @param {Object} depTree - The dependency tree object
33
33
  */
34
- addDependenciesToSbom(sbom: Sbom, depTree: any): void;
34
+ addDependenciesToSbom(sbom: Sbom, depTree: Object): void;
35
35
  #private;
36
36
  }
37
37
  import Yarn_processor from "./yarn_processor.js";
@@ -1,4 +1,4 @@
1
- /** @typedef {{name: string, version: string, dependencies: DependencyEntry[]}} DependencyEntry */
1
+ /** @typedef {{name: string, version: string, dependencies: DependencyEntry[], hashes?: Array<{alg: string, content: string}>}} DependencyEntry */
2
2
  export default class Python_controller {
3
3
  /**
4
4
  * Constructor to create new python controller instance to interact with pip package manager
@@ -31,4 +31,8 @@ export type DependencyEntry = {
31
31
  name: string;
32
32
  version: string;
33
33
  dependencies: DependencyEntry[];
34
+ hashes?: Array<{
35
+ alg: string;
36
+ content: string;
37
+ }>;
34
38
  };
@@ -19,7 +19,54 @@ function getPipShowOutput(depNames) {
19
19
  throw new Error('fail invoking \'pip show\' to fetch metadata for all installed packages in environment', { cause: error });
20
20
  }
21
21
  }
22
- /** @typedef {{name: string, version: string, dependencies: DependencyEntry[]}} DependencyEntry */
22
+ /**
23
+ * Get pip inspect output from env var override or by invoking pip inspect.
24
+ * Returns null if pip inspect is unavailable (pip < 22.2) or if freeze/show
25
+ * env vars are set without an inspect override (to avoid inconsistent data).
26
+ * @return {string|null} pip inspect JSON output, or null on failure
27
+ */
28
+ function getPipInspectOutput() {
29
+ if (environmentVariableIsPopulated("TRUSTIFY_DA_PIP_INSPECT")) {
30
+ return new Buffer.from(process.env["TRUSTIFY_DA_PIP_INSPECT"], 'base64').toString('ascii');
31
+ }
32
+ if (environmentVariableIsPopulated("TRUSTIFY_DA_PIP_FREEZE") || environmentVariableIsPopulated("TRUSTIFY_DA_PIP_SHOW")) {
33
+ return null;
34
+ }
35
+ try {
36
+ return invokeCommand(this.pathToPipBin, ['inspect']).toString();
37
+ }
38
+ catch (error) {
39
+ console.warn('pip inspect is not available (requires pip 22.2+), SBOM will be generated without hashes');
40
+ return null;
41
+ }
42
+ }
43
+ /**
44
+ * Parse pip inspect JSON output and build a hash lookup map.
45
+ * @param {string|null} inspectOutput - raw pip inspect JSON string
46
+ * @return {Map<string, Array<{alg: string, content: string}>>} map of lowercase package name to hashes
47
+ */
48
+ function parsePipInspectHashes(inspectOutput) {
49
+ if (!inspectOutput) {
50
+ return new Map();
51
+ }
52
+ try {
53
+ let inspectData = JSON.parse(inspectOutput);
54
+ let hashMap = new Map();
55
+ for (let pkg of (inspectData.installed || [])) {
56
+ let name = pkg.metadata?.name;
57
+ let sha256 = pkg.download_info?.archive_info?.hashes?.sha256;
58
+ if (name && sha256) {
59
+ hashMap.set(name.toLowerCase(), [{ alg: "SHA-256", content: sha256 }]);
60
+ }
61
+ }
62
+ return hashMap;
63
+ }
64
+ catch (error) {
65
+ console.warn('Failed to parse pip inspect output, SBOM will be generated without hashes');
66
+ return new Map();
67
+ }
68
+ }
69
+ /** @typedef {{name: string, version: string, dependencies: DependencyEntry[], hashes?: Array<{alg: string, content: string}>}} DependencyEntry */
23
70
  export default class Python_controller {
24
71
  pythonEnvDir;
25
72
  pathToPipBin;
@@ -95,7 +142,7 @@ export default class Python_controller {
95
142
  }
96
143
  /**
97
144
  * Parse the requirements.txt file using tree-sitter and return structured requirement data.
98
- * @return {Promise<{name: string, version: string|null}[]>}
145
+ * @return {Promise<{name: string, version: string|null, hasMarker: boolean}[]>}
99
146
  */
100
147
  async #parseRequirements() {
101
148
  const content = fs.readFileSync(this.pathToRequirements).toString();
@@ -107,7 +154,8 @@ export default class Python_controller {
107
154
  const version = versionMatches.length > 0
108
155
  ? versionMatches[0].captures.find(c => c.name === 'version').node.text
109
156
  : null;
110
- return { name, version };
157
+ const hasMarker = reqNode.children.some(c => c.type === 'marker_spec');
158
+ return { name, version, hasMarker };
111
159
  }));
112
160
  }
113
161
  #decideIfWindowsOrLinuxPath(fileName) {
@@ -224,7 +272,12 @@ export default class Python_controller {
224
272
  CachedEnvironmentDeps[packageName.replace("_", "-")] = pipDepTreeEntryForCache;
225
273
  });
226
274
  }
227
- parsedRequirements.forEach(({ name: depName, version: manifestVersion }) => {
275
+ const inspectOutput = getPipInspectOutput.call(this);
276
+ const hashMap = parsePipInspectHashes(inspectOutput);
277
+ parsedRequirements.forEach(({ name: depName, version: manifestVersion, hasMarker }) => {
278
+ if (hasMarker && CachedEnvironmentDeps[depName.toLowerCase()] === undefined) {
279
+ return;
280
+ }
228
281
  if (matchManifestVersions === "true" && manifestVersion != null) {
229
282
  let installedVersion;
230
283
  if (CachedEnvironmentDeps[depName.toLowerCase()] !== undefined) {
@@ -243,7 +296,7 @@ export default class Python_controller {
243
296
  }
244
297
  let path = [];
245
298
  path.push(depName.toLowerCase());
246
- bringAllDependencies(dependencies, depName, CachedEnvironmentDeps, includeTransitive, path, usePipDepTree);
299
+ bringAllDependencies(dependencies, depName, CachedEnvironmentDeps, includeTransitive, path, usePipDepTree, hashMap);
247
300
  });
248
301
  dependencies.sort((dep1, dep2) => {
249
302
  const DEP1 = dep1.name.toLowerCase();
@@ -323,8 +376,9 @@ function getDepsList(record) {
323
376
  * @param includeTransitive
324
377
  * @param usePipDepTree
325
378
  * @param {[string]}path array representing the path of the current branch in dependency tree, starting with a root dependency - that is - a given dependency in requirements.txt
379
+ * @param {Map<string, Array<{alg: string, content: string}>>} hashMap - map of lowercase package name to hashes
326
380
  */
327
- function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDeps, includeTransitive, path, usePipDepTree) {
381
+ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDeps, includeTransitive, path, usePipDepTree, hashMap) {
328
382
  if (dependencyName?.trim() === "") {
329
383
  return;
330
384
  }
@@ -346,7 +400,11 @@ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDep
346
400
  directDeps = record.dependencies;
347
401
  }
348
402
  let targetDeps = [];
403
+ let hashes = hashMap?.get(depName.toLowerCase());
349
404
  let entry = { "name": depName, "version": version, "dependencies": [] };
405
+ if (hashes) {
406
+ entry.hashes = hashes;
407
+ }
350
408
  dependencies.push(entry);
351
409
  directDeps.forEach((dep) => {
352
410
  let depArray = [];
@@ -356,7 +414,7 @@ function bringAllDependencies(dependencies, dependencyName, cachedEnvironmentDep
356
414
  depArray.push(dep.toLowerCase());
357
415
  if (includeTransitive) {
358
416
  // send to recurrsion the array of all deps in path + the current dependency name which is not on the path.
359
- bringAllDependencies(targetDeps, dep, cachedEnvironmentDeps, includeTransitive, path.concat(depArray), usePipDepTree);
417
+ bringAllDependencies(targetDeps, dep, cachedEnvironmentDeps, includeTransitive, path.concat(depArray), usePipDepTree, hashMap);
360
418
  }
361
419
  }
362
420
  // sort ra
@@ -4,12 +4,17 @@ declare namespace _default {
4
4
  export { provideComponent };
5
5
  export { provideStack };
6
6
  export { readLicenseFromManifest };
7
+ export function packageManagerName(): string;
7
8
  }
8
9
  export default _default;
9
10
  export type DependencyEntry = {
10
11
  name: string;
11
12
  version: string;
12
13
  dependencies: DependencyEntry[];
14
+ hashes?: Array<{
15
+ alg: string;
16
+ content: string;
17
+ }>;
13
18
  };
14
19
  /**
15
20
  * @param {string} manifestName - the subject manifest name-type
@@ -5,13 +5,14 @@ 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
7
  import { getParser, getIgnoreQuery, getPinnedVersionQuery } from './requirements_parser.js';
8
- export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest };
9
- /** @typedef {{name: string, version: string, dependencies: DependencyEntry[]}} DependencyEntry */
8
+ export default { isSupported, validateLockFile, provideComponent, provideStack, readLicenseFromManifest, packageManagerName() { return 'pip'; } };
9
+ /** @typedef {{name: string, version: string, dependencies: DependencyEntry[], hashes?: Array<{alg: string, content: string}>}} DependencyEntry */
10
10
  /**
11
11
  * @type {string} ecosystem for python-pip is 'pip'
12
12
  * @private
13
13
  */
14
14
  const ecosystem = 'pip';
15
+ const NO_SCOPE = undefined;
15
16
  /**
16
17
  * @param {string} manifestName - the subject manifest name-type
17
18
  * @returns {boolean} - return true if `requirements.txt` is the manifest name-type
@@ -56,7 +57,6 @@ async function provideComponent(manifest, opts = {}) {
56
57
  contentType: 'application/vnd.cyclonedx+json'
57
58
  };
58
59
  }
59
- /** @typedef {{name: string, , version: string, dependencies: DependencyEntry[]}} DependencyEntry */
60
60
  /**
61
61
  *
62
62
  * @param {PackageURL}source
@@ -66,7 +66,7 @@ async function provideComponent(manifest, opts = {}) {
66
66
  */
67
67
  function addAllDependencies(source, dep, sbom) {
68
68
  let targetPurl = toPurl(dep["name"], dep["version"]);
69
- sbom.addDependency(source, targetPurl);
69
+ sbom.addDependency(source, targetPurl, NO_SCOPE, dep["hashes"]);
70
70
  let directDeps = dep["dependencies"];
71
71
  if (directDeps !== undefined && directDeps.length > 0) {
72
72
  directDeps.forEach((dependency) => { addAllDependencies(toPurl(dep["name"], dep["version"]), dependency, sbom); });
@@ -202,7 +202,7 @@ async function getSbomForComponentAnalysis(manifest, opts = {}) {
202
202
  const license = readLicenseFromManifest(manifest);
203
203
  sbom.addRoot(rootPurl, license);
204
204
  dependencies.forEach(dep => {
205
- sbom.addDependency(rootPurl, toPurl(dep.name, dep.version));
205
+ sbom.addDependency(rootPurl, toPurl(dep.name, dep.version), NO_SCOPE, dep.hashes);
206
206
  });
207
207
  await handleIgnoredDependencies(manifest, sbom, opts);
208
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
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Python provider for pyproject.toml files using PEP 621 format without a lock file.
3
+ * Uses `pip install --dry-run --ignore-installed --report` to resolve the full dependency tree.
4
+ * Acts as the fallback provider when no lock file (uv.lock/poetry.lock) is found.
5
+ */
6
+ export default class Python_pip_pyproject extends Base_pyproject {
7
+ /**
8
+ * Always returns true — pip provider is the fallback when no lock file is found.
9
+ * @param {string} manifestDir
10
+ * @param {{}} [opts={}]
11
+ * @returns {boolean}
12
+ */
13
+ validateLockFile(manifestDir: string, opts?: {}): boolean;
14
+ /**
15
+ * Get pip report output from env var override or by running pip.
16
+ * @param {string} manifestDir - directory containing pyproject.toml
17
+ * @param {{}} [opts={}]
18
+ * @returns {string} pip report JSON string
19
+ */
20
+ _getPipReportOutput(manifestDir: string, opts?: {}): string;
21
+ /**
22
+ * Parse pip report JSON and build dependency graph.
23
+ * @param {string} reportJson - pip report JSON string
24
+ * @returns {{directDeps: string[], graph: Map<string, {name: string, version: string, children: string[]}>}}
25
+ */
26
+ _parsePipReport(reportJson: string): {
27
+ directDeps: string[];
28
+ graph: Map<string, {
29
+ name: string;
30
+ version: string;
31
+ children: string[];
32
+ }>;
33
+ };
34
+ /**
35
+ * Check if a requires_dist entry is an extras-only dependency.
36
+ * @param {string} req - e.g. "PySocks!=1.5.7,>=1.5.6; extra == \"socks\""
37
+ * @returns {boolean}
38
+ */
39
+ _hasExtraMarker(req: string): boolean;
40
+ /**
41
+ * Extract package name from a requires_dist entry.
42
+ * @param {string} req - e.g. "charset_normalizer<4,>=2"
43
+ * @returns {string|null}
44
+ */
45
+ _extractDepName(req: string): string | null;
46
+ /**
47
+ * Resolve dependencies using pip install --dry-run --report.
48
+ * @param {string} manifestDir
49
+ * @param {string} _workspaceDir - unused (pip resolves from manifest directory)
50
+ * @param {object} parsed - parsed pyproject.toml
51
+ * @param {{}} [opts={}]
52
+ * @returns {Promise<{directDeps: string[], graph: Map}>}
53
+ */
54
+ _getDependencyData(manifestDir: string, _workspaceDir: string, parsed: object, opts?: {}): Promise<{
55
+ directDeps: string[];
56
+ graph: Map<any, any>;
57
+ }>;
58
+ _findEggInfoDirs(dir: any): string[];
59
+ _cleanupEggInfo(dir: any, existing: any): void;
60
+ }
61
+ import Base_pyproject from './base_pyproject.js';