forked from CycloneDX/cdxgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
8037 lines (7845 loc) · 229 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 { homedir, platform, tmpdir } from "node:os";
import {
basename,
delimiter as _delimiter,
dirname,
extname,
join,
resolve,
sep as _sep
} from "node:path";
import {
chmodSync,
constants,
copyFileSync,
existsSync,
lstatSync,
mkdtempSync,
readFileSync,
rmSync,
unlinkSync,
writeFileSync
} from "node:fs";
import got from "got";
import Arborist from "@npmcli/arborist";
import path from "node:path";
import { xml2js } from "xml-js";
import { fileURLToPath } from "node:url";
import { load } from "cheerio";
import { load as _load } from "js-yaml";
import { spawnSync } from "node:child_process";
import propertiesReader from "properties-reader";
import {
clean,
coerce,
compare,
maxSatisfying,
satisfies,
valid,
parse
} from "semver";
import StreamZip from "node-stream-zip";
import { parseEDNString } from "edn-data";
import { PackageURL } from "packageurl-js";
import { getTreeWithPlugin } from "./piptree.js";
import iconv from "iconv-lite";
let url = import.meta.url;
if (!url.startsWith("file://")) {
url = new URL(`file://${import.meta.url}`).toString();
}
const dirNameStr = import.meta ? dirname(fileURLToPath(url)) : __dirname;
const isWin = platform() === "win32";
const licenseMapping = JSON.parse(
readFileSync(join(dirNameStr, "data", "lic-mapping.json"))
);
const vendorAliases = JSON.parse(
readFileSync(join(dirNameStr, "data", "vendor-alias.json"))
);
const spdxLicenses = JSON.parse(
readFileSync(join(dirNameStr, "data", "spdx-licenses.json"))
);
const knownLicenses = JSON.parse(
readFileSync(join(dirNameStr, "data", "known-licenses.json"))
);
const mesonWrapDB = JSON.parse(
readFileSync(join(dirNameStr, "data", "wrapdb-releases.json"))
);
export const frameworksList = JSON.parse(
readFileSync(join(dirNameStr, "data", "frameworks-list.json"))
);
const selfPJson = JSON.parse(readFileSync(join(dirNameStr, "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(dirNameStr, "data", "python-stdlib.json"))
);
// Mapping between modules and package names
const PYPI_MODULE_PACKAGE_MAPPING = JSON.parse(
readFileSync(join(dirNameStr, "data", "pypi-pkg-aliases.json"))
);
// Debug mode flag
export const DEBUG_MODE =
process.env.CDXGEN_DEBUG_MODE === "debug" ||
process.env.SCAN_DEBUG_MODE === "debug" ||
process.env.SHIFTLEFT_LOGGING_LEVEL === "debug" ||
process.env.NODE_ENV === "development";
// Timeout milliseconds. Default 20 mins
export const TIMEOUT_MS =
parseInt(process.env.CDXGEN_TIMEOUT_MS) || 20 * 60 * 1000;
// Max buffer for stdout and stderr. Defaults to 100MB
export const MAX_BUFFER =
parseInt(process.env.CDXGEN_MAX_BUFFER) || 100 * 1024 * 1024;
// Metadata cache
export 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
export const FETCH_LICENSE =
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
export 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";
} else {
const possibleId = l
.replace("http://www.opensource.org/licenses/", "")
.toUpperCase();
spdxLicenses.forEach((v) => {
if (v.toUpperCase() === possibleId) {
licenseContent.id = v;
}
});
}
if (l.includes("mit-license")) {
licenseContent.id = "MIT";
}
// We always need a name to avoid validation errors
// Issue: #469
if (!licenseContent.name && !licenseContent.id) {
licenseContent.name = "CUSTOM";
}
licenseContent.url = l;
} else {
licenseContent.name = l;
}
} else if (Object.keys(l).length) {
licenseContent = l;
} else {
return undefined;
}
if (!licenseContent.id) {
addLicenseText(pkg, l, licenseContent, format);
}
return licenseContent;
})
.map((l) => ({ license: l }));
}
return undefined;
}
/**
* 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") {
const licenseFilenames = [
"LICENSE",
"License",
"license",
"LICENCE",
"Licence",
"licence",
"NOTICE",
"Notice",
"notice"
];
const 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
)) {
const 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"
) {
const licenseText = readFileSync(licenseFilepath, "utf8");
if (licenseText) {
if (format === "xml") {
const licenseContentText = { "#cdata": licenseText };
if (licenseContentType !== "text/plain") {
licenseContentText["@content-type"] = licenseContentType;
}
return licenseContentText;
} else {
const 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(p, "was not found on npm");
}
}
}
return cdepList;
};
/**
* Parse nodejs package json file
*
* @param {string} pkgJsonFile package.json file
* @param {boolean} simple Return a simpler representation of the component by skipping extended attributes and license fetch.
*/
export const parsePkgJson = async (pkgJsonFile, simple = false) => {
const pkgList = [];
if (existsSync(pkgJsonFile)) {
try {
const pkgData = JSON.parse(readFileSync(pkgJsonFile, "utf8"));
const pkgIdentifier = parsePackageJsonName(pkgData.name);
const name = pkgIdentifier.fullName || pkgData.name;
if (!name && !pkgJsonFile.includes("node_modules")) {
console.log(
`${pkgJsonFile} doesn't contain the package name. Consider using the 'npm init' command to create a valid package.json file for this project.`
);
return pkgList;
}
const group = pkgIdentifier.scope || "";
const purl = new PackageURL(
"npm",
group,
name,
pkgData.version,
null,
null
).toString();
const apkg = {
name,
group,
version: pkgData.version,
purl: purl,
"bom-ref": decodeURIComponent(purl)
};
if (!simple) {
apkg.properties = [
{
name: "SrcFile",
value: pkgJsonFile
}
];
apkg.evidence = {
identity: {
field: "purl",
confidence: 0.7,
methods: [
{
technique: "manifest-analysis",
confidence: 1,
value: pkgJsonFile
}
]
}
};
}
pkgList.push(apkg);
} catch (err) {
// continue regardless of error
}
}
if (!simple && FETCH_LICENSE && 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
* @param {object} options Command line options
*/
export const parsePkgLock = async (pkgLockFile, options = {}) => {
let pkgList = [];
let dependenciesList = [];
if (!options) {
options = {};
}
if (!existsSync(pkgLockFile)) {
return {
pkgList,
dependenciesList
};
}
const parseArboristNode = (
node,
rootNode,
parentRef = null,
visited = new Set(),
options = {}
) => {
if (visited.has(node)) {
return { pkgList: [], dependenciesList: [] };
}
visited.add(node);
let pkgList = [];
let dependenciesList = [];
// Create the package entry
const srcFilePath = node.path.includes(`${_sep}node_modules`)
? node.path.split(`${_sep}node_modules`)[0]
: node.path;
const scope = node.dev === true ? "optional" : undefined;
const integrity = node.integrity ? node.integrity : undefined;
let pkg = {};
let purlString = "";
const author = node.package.author;
const authorString =
author instanceof Object
? `${author.name}${author.email ? ` <${author.email}>` : ""}${
author.url ? ` (${author.url})` : ""
}`
: author;
if (node == rootNode) {
purlString = new PackageURL(
"npm",
options.projectGroup || "",
options.projectName || node.packageName,
options.projectVersion || node.version,
null,
null
).toString();
pkg = {
author: authorString,
group: options.projectGroup || "",
name: options.projectName || node.packageName,
version: options.projectVersion || node.version,
type: "application",
purl: purlString,
"bom-ref": decodeURIComponent(purlString)
};
} else {
purlString = new PackageURL(
"npm",
"",
node.packageName,
node.version,
null,
null
).toString();
const pkgLockFile = join(
srcFilePath.replace("/", _sep),
"package-lock.json"
);
pkg = {
group: "",
name: node.packageName,
version: node.version,
author: authorString,
scope: scope,
_integrity: integrity,
properties: [
{
name: "SrcFile",
value: pkgLockFile
}
],
evidence: {
identity: {
field: "purl",
confidence: 1,
methods: [
{
technique: "manifest-analysis",
confidence: 1,
value: pkgLockFile
}
]
}
},
type: parentRef ? "npm" : "application",
purl: purlString,
"bom-ref": decodeURIComponent(purlString)
};
}
const packageLicense = node.package.license;
if (packageLicense) {
// License will be overridden if FETCH_LICENSE is enabled
pkg.license = packageLicense;
}
pkgList.push(pkg);
// retrieve workspace node pkglists
let workspaceDependsOn = [];
if (node.fsChildren && node.fsChildren.size > 0) {
for (let workspaceNode of node.fsChildren) {
const {
pkgList: childPkgList,
dependenciesList: childDependenciesList
} = parseArboristNode(workspaceNode, rootNode, purlString, visited);
pkgList = pkgList.concat(childPkgList);
dependenciesList = dependenciesList.concat(childDependenciesList);
const depWorkspacePurlString = decodeURIComponent(
new PackageURL(
"npm",
"",
workspaceNode.name,
workspaceNode.version,
null,
null
).toString()
);
workspaceDependsOn.push(depWorkspacePurlString);
}
}
// this handles the case when a node has ["dependencies"] key in a package-lock.json
// for a node. We exclude the root node because it's already been handled
let childrenDependsOn = [];
if (node != rootNode) {
for (const child of node.children) {
let childNode = child[1];
const {
pkgList: childPkgList,
dependenciesList: childDependenciesList
} = parseArboristNode(
childNode,
rootNode,
decodeURIComponent(purlString),
visited
);
pkgList = pkgList.concat(childPkgList);
dependenciesList = dependenciesList.concat(childDependenciesList);
const depChildString = decodeURIComponent(
new PackageURL(
"npm",
"",
childNode.name,
childNode.version,
null,
null
).toString()
);
childrenDependsOn.push(depChildString);
}
}
// this handles the case when a node has a ["requires"] key
const pkgDependsOn = [];
for (const edge of node.edgesOut.values()) {
let targetVersion;
let targetName;
// if the edge doesn't have an integrity, it's likely a peer dependency
// which isn't installed
let edgeToIntegrity = edge.to ? edge.to.integrity : null;
// let packageName = node.packageName;
// let edgeName = edge.name;
if (!edgeToIntegrity) {
continue;
}
// the edges don't actually contain a version, so we need to search the root node
// children to find the correct version. we check the node children first, then
// we check the root node children
let foundMatch = false;
for (const child of node.children) {
if (child[1].integrity == edgeToIntegrity) {
targetName = child[0].replace(/node_modules\//g, "");
// The package name could be different from the targetName retrieved
// Eg: "string-width-cjs": "npm:string-width@^4.2.0",
if (child[1].packageName && child[1].packageName !== targetName) {
targetName = child[1].packageName;
}
targetVersion = child[1].version;
foundMatch = true;
break;
}
}
if (!foundMatch) {
for (const child of rootNode.children) {
if (child[1].integrity == edgeToIntegrity) {
targetName = child[0].replace(/node_modules\//g, "");
targetVersion = child[1].version;
// The package name could be different from the targetName retrieved
// "string-width-cjs": "npm:string-width@^4.2.0",
if (child[1].packageName && child[1].packageName !== targetName) {
targetName = child[1].packageName;
}
break;
}
}
}
// if we can't find the version of the edge, continue
// it may be an optional peer dependency
if (!targetVersion || !targetName) {
continue;
}
const depPurlString = decodeURIComponent(
new PackageURL(
"npm",
"",
targetName,
targetVersion,
null,
null
).toString()
);
pkgDependsOn.push(depPurlString);
if (edge.to == null) continue;
const { pkgList: childPkgList, dependenciesList: childDependenciesList } =
parseArboristNode(
edge.to,
rootNode,
decodeURIComponent(purlString),
visited
);
pkgList = pkgList.concat(childPkgList);
dependenciesList = dependenciesList.concat(childDependenciesList);
}
dependenciesList.push({
ref: decodeURIComponent(purlString),
dependsOn: workspaceDependsOn
.concat(childrenDependsOn)
.concat(pkgDependsOn)
});
return { pkgList, dependenciesList };
};
let arb = new Arborist({
path: path.dirname(pkgLockFile),
// legacyPeerDeps=false enables npm >v3 package dependency resolution
legacyPeerDeps: false
});
let tree = undefined;
try {
tree = await arb.loadVirtual();
} catch (e) {
console.log(
`Unable to parse ${pkgLockFile} without legacy peer dependencies. Retrying ...`
);
try {
arb = new Arborist({
path: path.dirname(pkgLockFile),
legacyPeerDeps: true
});
tree = await arb.loadVirtual();
} catch (e) {
console.log(
`Unable to parse ${pkgLockFile} in legacy and non-legacy mode. The resulting SBOM would be incomplete.`
);
return { pkgList, dependenciesList };
}
}
if (!tree) {
return { pkgList, dependenciesList };
}
({ pkgList, dependenciesList } = parseArboristNode(
tree,
tree,
null,
new Set(),
options
));
if (FETCH_LICENSE && 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) => {
l = l.replace("\r", "");
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}/`;
}
// "lru-cache@npm:^6.0.0":
// "string-width-cjs@npm:string-width@^4.2.0":
// Here range can be
// - npm:^6.0.0
// - npm:@types/ioredis@^4.28.10
// - npm:strip-ansi@^6.0.1
// See test cases with yarn3.lock and yarn6.lock
if (range && range.startsWith("npm:")) {
if (range.includes("@")) {
range = range.split("@").slice(-1)[0];
} else {
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;
};
const _parseYarnLine = (l) => {
let name = "";
let group = "";
const 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;
}
}
return { group, name };
};
/**
* 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 name_aliases = [];
let group = "";
let version = "";
let integrity = "";
let depsMode = false;
let purlString = "";
let deplist = [];
const pkgAddedMap = {};
// This would have the keys and the resolved version required to solve the dependency tree
const identMap = yarnLockToIdentMap(lockData);
lockData.split("\n").forEach((l) => {
l = l.replace("\r", "");
if (l.startsWith("#")) {
return;
}
if (!l.startsWith(" ") || l.trim() === "") {
// Create an entry for the package and reset variables
if (
name !== "" &&
version !== "" &&
(integrity !== "" ||
version.includes("local") ||
(integrity === "" && (depsMode || l.trim() === "")))
) {
name_aliases.push({ group, name });
// FIXME: What should we do about the dependencies for such aliases
for (const ang of name_aliases) {
group = ang.group;
name = ang.name;
// Create a purl ref for the current package
purlString = new PackageURL(
"npm",
group,
name,
version,
null,
null
).toString();
// Trim duplicates
if (!pkgAddedMap[purlString]) {
pkgAddedMap[purlString] = true;
pkgList.push({
group: group || "",
name: name,
version: version,
_integrity: integrity,
purl: purlString,
"bom-ref": decodeURIComponent(purlString),
properties: [
{
name: "SrcFile",
value: yarnLockFile
}
],
evidence: {
identity: {
field: "purl",
confidence: 1,
methods: [
{
technique: "manifest-analysis",
confidence: 1,
value: yarnLockFile
}
]
}
}
});
}
}
// Reset all the variables
group = "";
name = "";
name_aliases = [];
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, "");
// Deals with lines including aliases
// Eg: string-width-cjs@npm:string-width@^4.2.0, string-width@npm:^1.0.2 || 2 || 3 || 4, string-width@npm:^4.1.0, string-width@npm:^4.2.0, string-width@npm:^4.2.3
const fragments = l.split(", ");
for (let i = 0; i < fragments.length; i++) {
const parsedline = _parseYarnLine(fragments[i]);
if (i === 0) {
group = parsedline.group;
name = parsedline.name;
} else {
let fullName = parsedline.name;
if (parsedline.group && parsedline.group.length) {
fullName = `${parsedline.group}/${parsedline.name}`;
}
if (
fullName !== name &&
fullName !== `${group}/${name}` &&
!name_aliases.includes(fullName)
) {
name_aliases.push({
group: parsedline.group,
name: parsedline.name
});
}
}
}
} 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);
}
let range = tmpA[1];
// Deal with range with npm: prefix such as npm:string-width@^4.2.0, npm:@types/ioredis@^4.28.10
if (range.startsWith("npm:")) {
range = range.split("@").splice(-1)[0];
}
const resolvedVersion = identMap[`${dgroupname}|${range}`];
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;
}
}
}
});