-
Notifications
You must be signed in to change notification settings - Fork 201
/
Copy pathsnyk-test.js
71 lines (56 loc) · 1.74 KB
/
snyk-test.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
'use strict';
const { promises: fs } = require('fs');
const path = require('path');
const fetch = require('make-fetch-happen');
const MAKE_FETCH_HAPPEN_OPTIONS = {
timeout: 10000,
retry: {
retries: 3,
factor: 1,
minTimeout: 1000,
maxTimeout: 3000,
randomize: true,
},
};
async function snykTest(dependency) {
const { name, version } = dependency;
process.stdout.write(`Testing ${name}@${version} ... `);
const response = await fetch(
`https://api.snyk.io/v1/test/npm/${encodeURIComponent(name)}/${version}`,
{
...MAKE_FETCH_HAPPEN_OPTIONS,
headers: {
Authorization: `token ${process.env.SNYK_TOKEN}`,
},
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const vulnerabilities = (await response.json()).issues?.vulnerabilities ?? [];
process.stdout.write(`Done\n`);
return vulnerabilities.map((v) => {
// for some reason the api doesn't add these properties unlike `snyk test`
return { ...v, name: v.package, fixedIn: v.upgradePath ?? [] };
});
}
async function main() {
if (!process.env.SNYK_TOKEN) {
throw new Error('process.env.SNYK_TOKEN is missing.');
}
const rootPath = path.resolve(__dirname, '..');
const dependenciesFile = path.join(rootPath, '.sbom', 'dependencies.json');
const dependencies = JSON.parse(await fs.readFile(dependenciesFile, 'utf-8'));
const results = [];
for (const dependency of dependencies) {
const vulnerabilities = await snykTest(dependency);
if (vulnerabilities && vulnerabilities.length) {
results.push({ vulnerabilities });
}
}
await fs.writeFile(
path.join(rootPath, `.sbom/snyk-test-result.json`),
JSON.stringify(results, null, 2)
);
}
main();