forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
5289 lines (5161 loc) · 148 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { globSync } from "glob";
import { tmpdir, platform, freemem } from "node:os";
import {
dirname,
sep as _sep,
basename,
join,
resolve,
delimiter as _delimiter
} from "node:path";
import {
existsSync,
readFileSync,
mkdtempSync,
rmSync,
copyFileSync,
constants,
writeFileSync,
unlinkSync,
chmodSync
} from "node:fs";
import got from "got";
import { xml2js } from "xml-js";
import { fileURLToPath } from "node:url";
let url = import.meta.url;
if (!url.startsWith("file://")) {
url = new URL(`file://${import.meta.url}`).toString();
}
const dirName = import.meta ? dirname(fileURLToPath(url)) : __dirname;
const licenseMapping = JSON.parse(
readFileSync(join(dirName, "data", "lic-mapping.json"))
);
const vendorAliases = JSON.parse(
readFileSync(join(dirName, "data", "vendor-alias.json"))
);
const spdxLicenses = JSON.parse(
readFileSync(join(dirName, "data", "spdx-licenses.json"))
);
const knownLicenses = JSON.parse(
readFileSync(join(dirName, "data", "known-licenses.json"))
);
import { load } from "cheerio";
import { load as _load } from "js-yaml";
import { spawnSync } from "node:child_process";
import propertiesReader from "properties-reader";
import { satisfies, coerce, maxSatisfying, clean, valid } from "semver";
import StreamZip from "node-stream-zip";
import { parseEDNString } from "edn-data";
import { PackageURL } from "packageurl-js";
const selfPJson = JSON.parse(readFileSync(join(dirName, "package.json")));
const _version = selfPJson.version;
// Refer to contrib/py-modules.py for a script to generate this list
// The script needs to be used once every few months to update this list
const PYTHON_STD_MODULES = JSON.parse(
readFileSync(join(dirName, "data", "python-stdlib.json"))
);
// Mapping between modules and package names
const PYPI_MODULE_PACKAGE_MAPPING = JSON.parse(
readFileSync(join(dirName, "data", "pypi-pkg-aliases.json"))
);
// Debug mode flag
const DEBUG_MODE =
process.env.CDXGEN_DEBUG_MODE === "debug" ||
process.env.SCAN_DEBUG_MODE === "debug" ||
process.env.SHIFTLEFT_LOGGING_LEVEL === "debug";
// Timeout milliseconds. Default 10 mins
const TIMEOUT_MS = parseInt(process.env.CDXGEN_TIMEOUT_MS) || 10 * 60 * 1000;
// Metadata cache
let metadata_cache = {};
// Whether test scope shall be included for java/maven projects; default, if unset shall be 'true'
export const includeMavenTestScope =
!process.env.CDX_MAVEN_INCLUDE_TEST_SCOPE ||
["true", "1"].includes(process.env.CDX_MAVEN_INCLUDE_TEST_SCOPE);
// Whether license information should be fetched
const fetchLicenses =
process.env.FETCH_LICENSE &&
["true", "1"].includes(process.env.FETCH_LICENSE);
const MAX_LICENSE_ID_LENGTH = 100;
let PYTHON_CMD = "python";
if (process.env.PYTHON_CMD) {
PYTHON_CMD = process.env.PYTHON_CMD;
}
// Custom user-agent for cdxgen
const cdxgenAgent = got.extend({
headers: {
"user-agent": `@CycloneDX/cdxgen ${_version}`
}
});
/**
* Method to get files matching a pattern
*
* @param {string} dirPath Root directory for search
* @param {string} pattern Glob pattern (eg: *.gradle)
*/
export const getAllFiles = function (dirPath, pattern) {
try {
const ignoreList = [
"**/.hg/**",
"**/.git/**",
"**/venv/**",
"**/docs/**",
"**/examples/**",
"**/site-packages/**"
];
// Only ignore node_modules if the caller is not looking for package.json
if (!pattern.includes("package.json")) {
ignoreList.push("**/node_modules/**");
}
return globSync(pattern, {
cwd: dirPath,
absolute: true,
nocase: true,
nodir: true,
strict: true,
dot: pattern.startsWith(".") ? true : false,
follow: false,
ignore: ignoreList
});
} catch (err) {
if (DEBUG_MODE) {
console.error(err);
}
return [];
}
};
const toBase64 = (hexString) => {
return Buffer.from(hexString, "hex").toString("base64");
};
/**
* Performs a lookup + validation of the license specified in the
* package. If the license is a valid SPDX license ID, set the 'id'
* and url of the license object, otherwise, set the 'name' of the license
* object.
*/
export function getLicenses(pkg, format = "xml") {
let license = pkg.license && (pkg.license.type || pkg.license);
if (license) {
if (!Array.isArray(license)) {
license = [license];
}
return license
.map((l) => {
let licenseContent = {};
if (typeof l === "string" || l instanceof String) {
if (
spdxLicenses.some((v) => {
return l === v;
})
) {
licenseContent.id = l;
licenseContent.url = "https://opensource.org/licenses/" + l;
} else if (l.startsWith("http")) {
if (!l.includes("opensource.org")) {
licenseContent.name = "CUSTOM";
}
if (l.includes("mit-license")) {
licenseContent.id = "MIT";
}
licenseContent.url = l;
} else {
licenseContent.name = l;
}
} else if (Object.keys(l).length) {
licenseContent = l;
} else {
return [];
}
if (!licenseContent.id) {
addLicenseText(pkg, l, licenseContent, format);
}
return licenseContent;
})
.map((l) => ({ license: l }));
}
return [];
}
/**
* Tries to find a file containing the license text based on commonly
* used naming and content types. If a candidate file is found, add
* the text to the license text object and stop.
*/
export function addLicenseText(pkg, l, licenseContent, format = "xml") {
let licenseFilenames = [
"LICENSE",
"License",
"license",
"LICENCE",
"Licence",
"licence",
"NOTICE",
"Notice",
"notice"
];
let licenseContentTypes = {
"text/plain": "",
"text/txt": ".txt",
"text/markdown": ".md",
"text/xml": ".xml"
};
/* Loops over different name combinations starting from the license specified
naming (e.g., 'LICENSE.Apache-2.0') and proceeding towards more generic names. */
for (const licenseName of [`.${l}`, ""]) {
for (const licenseFilename of licenseFilenames) {
for (const [licenseContentType, fileExtension] of Object.entries(
licenseContentTypes
)) {
let licenseFilepath = `${pkg.realPath}/${licenseFilename}${licenseName}${fileExtension}`;
if (existsSync(licenseFilepath)) {
licenseContent.text = readLicenseText(
licenseFilepath,
licenseContentType,
format
);
return;
}
}
}
}
}
/**
* Read the file from the given path to the license text object and includes
* content-type attribute, if not default. Returns the license text object.
*/
export function readLicenseText(
licenseFilepath,
licenseContentType,
format = "xml"
) {
let licenseText = readFileSync(licenseFilepath, "utf8");
if (licenseText) {
if (format === "xml") {
let licenseContentText = { "#cdata": licenseText };
if (licenseContentType !== "text/plain") {
licenseContentText["@content-type"] = licenseContentType;
}
return licenseContentText;
} else {
let licenseContentText = { content: licenseText };
if (licenseContentType !== "text/plain") {
licenseContentText["contentType"] = licenseContentType;
}
return licenseContentText;
}
}
return null;
}
/**
* Method to retrieve metadata for npm packages by querying npmjs
*
* @param {Array} pkgList Package list
*/
export const getNpmMetadata = async function (pkgList) {
const NPM_URL = "https://registry.npmjs.org/";
const cdepList = [];
for (const p of pkgList) {
try {
let key = p.name;
if (p.group && p.group !== "") {
let group = p.group;
if (!group.startsWith("@")) {
group = "@" + group;
}
key = group + "/" + p.name;
}
let body = {};
if (metadata_cache[key]) {
body = metadata_cache[key];
} else {
const res = await cdxgenAgent.get(NPM_URL + key, {
responseType: "json"
});
body = res.body;
metadata_cache[key] = body;
}
p.description = body.description;
p.license = body.license;
if (body.repository && body.repository.url) {
p.repository = { url: body.repository.url };
}
if (body.homepage) {
p.homepage = { url: body.homepage };
}
cdepList.push(p);
} catch (err) {
cdepList.push(p);
if (DEBUG_MODE) {
console.error(err, p);
}
}
}
return cdepList;
};
const _getDepPkgList = async function (
pkgLockFile,
pkgList,
dependenciesList,
depKeys,
pkg
) {
let pkgDependencies =
pkg.lockfileVersion && pkg.lockfileVersion >= 3
? pkg.packages
: pkg.dependencies;
if (pkg && pkgDependencies) {
const pkgKeys = Object.keys(pkgDependencies);
for (const k of pkgKeys) {
// Skip the root package in lockFileVersion 3 and above
if (k === "") {
continue;
}
let name = k;
const version = pkgDependencies[name].version;
const purl = new PackageURL(
"npm",
"",
name.replace("node_modules/", ""),
version,
null,
null
);
const purlString = decodeURIComponent(purl.toString());
let scope = pkgDependencies[name].dev === true ? "optional" : undefined;
const apkg = {
name: name.replace("node_modules/", ""),
version,
_integrity: pkgDependencies[name].integrity,
scope,
properties: [
{
name: "SrcFile",
value: pkgLockFile
}
]
};
pkgList.push(apkg);
if (pkgDependencies[name].dependencies) {
// Include child dependencies
const dependencies = pkgDependencies[name].dependencies;
const pkgDepKeys = Object.keys(dependencies);
const deplist = [];
for (const j in pkgDepKeys) {
const depName = pkgDepKeys[j];
const depVersion = dependencies[depName].version;
const deppurl = new PackageURL(
"npm",
"",
depName.replace("node_modules/", ""),
depVersion,
null,
null
);
const deppurlString = decodeURIComponent(deppurl.toString());
deplist.push(deppurlString);
}
if (!depKeys[purlString]) {
dependenciesList.push({
ref: purlString,
dependsOn: deplist
});
depKeys[purlString] = true;
}
if (pkg.lockfileVersion && pkg.lockfileVersion >= 3) {
// Do not recurse for lock file v3 and above
} else {
await _getDepPkgList(
pkgLockFile,
pkgList,
dependenciesList,
depKeys,
pkgDependencies[name]
);
}
} else {
if (!depKeys[purlString]) {
dependenciesList.push({
ref: purlString,
dependsOn: []
});
depKeys[purlString] = true;
}
}
}
}
return pkgList;
};
/**
* Parse nodejs package json file
*
* @param {string} pkgJsonFile package.json file
*/
export const parsePkgJson = async (pkgJsonFile) => {
const pkgList = [];
if (existsSync(pkgJsonFile)) {
try {
const pkgData = JSON.parse(readFileSync(pkgJsonFile, "utf8"));
const pkgIdentifier = parsePackageJsonName(pkgData.name);
pkgList.push({
name: pkgIdentifier.fullName || pkgData.name,
group: pkgIdentifier.scope || "",
version: pkgData.version,
properties: [
{
name: "SrcFile",
value: pkgJsonFile
}
]
});
} catch (err) {
// continue regardless of error
}
}
if (fetchLicenses && pkgList && pkgList.length) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages in parsePkgJson`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
/**
* Parse nodejs package lock file
*
* @param {string} pkgLockFile package-lock.json file
*/
export const parsePkgLock = async (pkgLockFile) => {
let pkgList = [];
let dependenciesList = [];
let depKeys = {};
let rootPkg = {};
if (existsSync(pkgLockFile)) {
const lockData = JSON.parse(readFileSync(pkgLockFile, "utf8"));
rootPkg.name = lockData.name || "";
// lockfile v2 onwards
if (lockData.name && lockData.packages && lockData.packages[""]) {
// Build the initial dependency tree for the root package
rootPkg = {
group: "",
name: lockData.name,
version: lockData.version,
type: "application"
};
} else if (lockData.lockfileVersion === 1) {
let dirName = dirname(pkgLockFile);
const tmpA = dirName.split(_sep);
dirName = tmpA[tmpA.length - 1];
// v1 lock file
rootPkg = {
group: "",
name: lockData.name || dirName,
version: lockData.version || "",
type: "application"
};
}
if (rootPkg && rootPkg.name) {
const purl = new PackageURL(
"application",
"",
rootPkg.name,
rootPkg.version,
null,
null
);
const purlString = decodeURIComponent(purl.toString());
rootPkg["bom-ref"] = purlString;
pkgList.push(rootPkg);
// npm ls command seems to include both dependencies and devDependencies
// For tree purposes, including only the dependencies should be enough
let rootPkgDeps = [];
if (
lockData.packages &&
lockData.packages[""] &&
lockData.packages[""].dependencies
) {
rootPkgDeps =
Object.keys(lockData.packages[""].dependencies || {}) || [];
} else if (lockData.dependencies) {
rootPkgDeps = Object.keys(lockData.dependencies || {}) || [];
}
const deplist = [];
for (const rd of rootPkgDeps) {
let resolvedVersion = undefined;
if (lockData.packages) {
resolvedVersion = (lockData.packages[`node_modules/${rd}`] || {})
.version;
} else if (lockData.dependencies) {
resolvedVersion = lockData.dependencies[rd].version;
}
if (resolvedVersion) {
const dpurl = decodeURIComponent(
new PackageURL(
"npm",
"",
rd,
resolvedVersion,
null,
null
).toString()
);
deplist.push(dpurl);
}
}
dependenciesList.push({
ref: purlString,
dependsOn: deplist
});
}
pkgList = await _getDepPkgList(
pkgLockFile,
pkgList,
dependenciesList,
depKeys,
lockData
);
}
if (fetchLicenses && pkgList && pkgList.length) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages in parsePkgLock`
);
}
pkgList = await getNpmMetadata(pkgList);
return { pkgList, dependenciesList };
}
return {
pkgList,
dependenciesList
};
};
/**
* Given a lock file this method would return an Object with the identiy as the key and parsed name and value
* eg: "@actions/core@^1.2.6", "@actions/core@^1.6.0":
* version "1.6.0"
* would result in two entries
*
* @param {string} lockData Yarn Lockfile data
*/
export const yarnLockToIdentMap = function (lockData) {
const identMap = {};
let currentIdents = [];
lockData.split("\n").forEach((l) => {
if (l === "\n" || l.startsWith("#")) {
return;
}
// "@actions/core@^1.2.6", "@actions/core@^1.6.0":
if (!l.startsWith(" ") && l.trim().length > 0) {
const tmpA = l.replace(/["']/g, "").split(", ");
if (tmpA && tmpA.length) {
for (let s of tmpA) {
if (!s.startsWith("__")) {
if (s.endsWith(":")) {
s = s.substring(0, s.length - 1);
}
// Non-strict mode parsing
const match = s.match(/^(?:(@[^/]+?)\/)?([^/]+?)(?:@(.+))?$/);
if (!match) {
continue;
}
let [, group, name, range] = match;
if (group) {
group = `${group}/`;
}
if (range && range.startsWith("npm:")) {
range = range.replace("npm:", "");
}
currentIdents.push(`${group || ""}${name}|${range}`);
}
}
}
} else if (l.startsWith(" version") && currentIdents.length) {
const tmpA = l.replace(/["']/g, "").split(" ");
const version = tmpA[tmpA.length - 1].trim();
for (const id of currentIdents) {
identMap[id] = version;
}
currentIdents = [];
}
});
return identMap;
};
/**
* Parse nodejs yarn lock file
*
* @param {string} yarnLockFile yarn.lock file
*/
export const parseYarnLock = async function (yarnLockFile) {
let pkgList = [];
const dependenciesList = [];
const depKeys = {};
if (existsSync(yarnLockFile)) {
const lockData = readFileSync(yarnLockFile, "utf8");
let name = "";
let group = "";
let version = "";
let integrity = "";
let depsMode = false;
let purlString = "";
let deplist = [];
// This would have the keys and the resolved version required to solve the dependency tree
const identMap = yarnLockToIdentMap(lockData);
let prefixAtSymbol = false;
lockData.split("\n").forEach((l) => {
if (l === "\n" || l.startsWith("#")) {
return;
}
if (!l.startsWith(" ")) {
// Create an entry for the package and reset variables
if (
name !== "" &&
version !== "" &&
(integrity !== "" || version.includes("local"))
) {
// Create a purl ref for the current package
purlString = new PackageURL(
"npm",
group,
name,
version,
null,
null
).toString();
pkgList.push({
group: group || "",
name: name,
version: version,
_integrity: integrity,
properties: [
{
name: "SrcFile",
value: yarnLockFile
}
]
});
// Reset all the variables
group = "";
name = "";
version = "";
integrity = "";
}
if (purlString && purlString !== "" && !depKeys[purlString]) {
// Create an entry for dependencies
dependenciesList.push({
ref: decodeURIComponent(purlString),
dependsOn: deplist
});
depKeys[purlString] = true;
deplist = [];
purlString = "";
depsMode = false;
}
// Collect the group and the name
l = l.replace(/["']/g, "");
prefixAtSymbol = l.startsWith("@");
const tmpA = l.split("@");
// ignore possible leading empty strings
if (tmpA[0] === "") {
tmpA.shift();
}
if (tmpA.length >= 2) {
const fullName = tmpA[0];
if (fullName.indexOf("/") > -1) {
const parts = fullName.split("/");
group = (prefixAtSymbol ? "@" : "") + parts[0];
name = parts[1];
} else {
name = fullName;
}
}
} else if (name !== "" && l.startsWith(" dependencies:")) {
depsMode = true;
} else if (depsMode && l.startsWith(" ")) {
// Given "@actions/http-client" "^1.0.11"
// We need the resolved version from identMap
const tmpA = l.trim().replace(/["']/g, "").split(" ");
if (tmpA && tmpA.length === 2) {
let dgroupname = tmpA[0];
if (dgroupname.endsWith(":")) {
dgroupname = dgroupname.substring(0, dgroupname.length - 1);
}
const resolvedVersion = identMap[`${dgroupname}|${tmpA[1]}`];
const depPurlString = new PackageURL(
"npm",
null,
dgroupname,
resolvedVersion,
null,
null
).toString();
deplist.push(decodeURIComponent(depPurlString));
}
} else if (name !== "") {
if (!l.startsWith(" ")) {
depsMode = false;
}
l = l.trim();
const parts = l.split(" ");
if (l.startsWith("version")) {
version = parts[1].replace(/"/g, "");
}
if (l.startsWith("integrity")) {
integrity = parts[1];
}
// checksum used by yarn 2/3 is hex encoded
if (l.startsWith("checksum")) {
integrity =
"sha512-" + Buffer.from(parts[1], "hex").toString("base64");
}
if (l.startsWith("resolved")) {
const tmpB = parts[1].split("#");
if (tmpB.length > 1) {
const digest = tmpB[1].replace(/"/g, "");
integrity = "sha256-" + digest;
}
}
}
});
}
if (fetchLicenses && pkgList && pkgList.length) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages in parseYarnLock`
);
}
pkgList = await getNpmMetadata(pkgList);
return {
pkgList,
dependenciesList
};
}
return {
pkgList,
dependenciesList
};
};
/**
* Parse nodejs shrinkwrap deps file
*
* @param {string} swFile shrinkwrap-deps.json file
*/
export const parseNodeShrinkwrap = async function (swFile) {
const pkgList = [];
if (existsSync(swFile)) {
const lockData = JSON.parse(readFileSync(swFile, "utf8"));
const pkgKeys = Object.keys(lockData);
for (var k in pkgKeys) {
const fullName = pkgKeys[k];
const integrity = lockData[fullName];
const parts = fullName.split("@");
if (parts && parts.length) {
let name = "";
let version = "";
let group = "";
if (parts.length === 2) {
name = parts[0];
version = parts[1];
} else if (parts.length === 3) {
if (parts[0] === "") {
let gnameparts = parts[1].split("/");
group = gnameparts[0];
name = gnameparts[1];
} else {
name = parts[0];
}
version = parts[2];
}
if (group !== "@types") {
pkgList.push({
group: group,
name: name,
version: version,
_integrity: integrity,
properties: [
{
name: "SrcFile",
value: swFile
}
]
});
}
}
}
}
if (fetchLicenses && pkgList && pkgList.length) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages in parseNodeShrinkwrap`
);
}
return await getNpmMetadata(pkgList);
}
return pkgList;
};
/**
* Parse nodejs pnpm lock file
*
* @param {string} pnpmLock pnpm-lock.yaml file
*/
export const parsePnpmLock = async function (pnpmLock, parentComponent = null) {
let pkgList = [];
const dependenciesList = [];
let ppurl = "";
if (parentComponent && parentComponent.name) {
ppurl =
parentComponent.purl ||
new PackageURL(
"application",
parentComponent.group,
parentComponent.name,
parentComponent.version,
null,
null
).toString();
}
if (existsSync(pnpmLock)) {
const lockData = readFileSync(pnpmLock, "utf8");
const yamlObj = _load(lockData);
if (!yamlObj) {
return {};
}
// This logic matches the pnpm list command to include only direct dependencies
if (ppurl !== "") {
const ddeps = yamlObj.dependencies || {};
const ddeplist = [];
for (const dk of Object.keys(ddeps)) {
let version = ddeps[dk];
if (typeof version === "object" && version.version) {
version = version.version;
}
const dpurl = new PackageURL(
"npm",
"",
dk,
version,
null,
null
).toString();
ddeplist.push(decodeURIComponent(dpurl));
}
dependenciesList.push({
ref: decodeURIComponent(ppurl),
dependsOn: ddeplist
});
}
let lockfileVersion = yamlObj.lockfileVersion;
try {
lockfileVersion = parseInt(lockfileVersion, 10);
} catch (e) {
// ignore parse errors
}
const packages = yamlObj.packages;
const pkgKeys = Object.keys(packages);
for (var k in pkgKeys) {
// Eg: @babel/code-frame/7.10.1
// In lockfileVersion 6, /@babel/[email protected]
let fullName = pkgKeys[k].replace("/@", "@");
// Handle /[email protected](@types/[email protected]) in lockfileVersion 6
if (lockfileVersion >= 6 && fullName.includes("(")) {
fullName = fullName.split("(")[0];
}
const parts = fullName.split("/");
const integrity = packages[pkgKeys[k]].resolution.integrity;
const deps = packages[pkgKeys[k]].dependencies || [];
let scope = packages[pkgKeys[k]].dev === true ? "optional" : undefined;
if (parts && parts.length) {
let name = "";
let version = "";
let group = "";
if (lockfileVersion >= 6 && fullName.includes("@")) {
const tmpA = parts[parts.length - 1].split("@");
group = parts[0];
if (parts.length === 2 && tmpA.length > 1) {
name = tmpA[0];
version = tmpA[1];
} else {
console.log(parts, fullName);
}
} else {
if (parts.length === 2) {
name = parts[0];
version = parts[1];
} else if (parts.length === 3) {
group = parts[0];
name = parts[1];
version = parts[2];
}
}
// Let's have some warnings till we fully support pnpm 8
if (!name) {
console.warn(
`Unable to extract name and version for string ${pkgKeys[k]}`
);
continue;
}
if (group !== "@types" && name.indexOf("file:") !== 0) {
const purlString = new PackageURL(
"npm",
group,
name,
version,
null,
null
).toString();
const deplist = [];
for (const dpkgName of Object.keys(deps)) {
const dpurlString = new PackageURL(
"npm",
"",
dpkgName,
deps[dpkgName],
null,
null
).toString();
deplist.push(decodeURIComponent(dpurlString));
}
dependenciesList.push({
ref: decodeURIComponent(purlString),
dependsOn: deplist
});
pkgList.push({
group: group,
name: name,
version: version,
scope,
_integrity: integrity,
properties: [
{
name: "SrcFile",
value: pnpmLock
}
]
});
}
}
}
}
if (fetchLicenses && pkgList && pkgList.length) {
if (DEBUG_MODE) {
console.log(
`About to fetch license information for ${pkgList.length} packages in parsePnpmLock`
);
}
pkgList = await getNpmMetadata(pkgList);
return {
pkgList,
dependenciesList
};
}
return {
pkgList,
dependenciesList
};
};
/**
* Parse bower json file
*
* @param {string} bowerJsonFile bower.json file
*/
export const parseBowerJson = async (bowerJsonFile) => {
const pkgList = [];
if (existsSync(bowerJsonFile)) {
try {
const pkgData = JSON.parse(readFileSync(bowerJsonFile, "utf8"));
const pkgIdentifier = parsePackageJsonName(pkgData.name);
pkgList.push({
name: pkgIdentifier.fullName || pkgData.name,
group: pkgIdentifier.scope || "",
version: pkgData.version || "",
description: pkgData.description || "",
license: pkgData.license || "",
properties: [
{
name: "SrcFile",
value: bowerJsonFile
}