vuln-scan 0.1.1
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.
- package/LICENSE +21 -0
- package/README.md +61 -0
- package/cli.js +112 -0
- package/package.json +46 -0
- package/src/core.js +480 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 DEBASIS
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# vuln-scan
|
|
2
|
+
|
|
3
|
+
A Node.js CLI that scans a project’s **lockfile** (npm / pnpm / yarn) to find known vulnerabilities using the **OSV.dev** API.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- Detects package manager by lockfile:
|
|
8
|
+
- npm: `package-lock.json`
|
|
9
|
+
- pnpm: `pnpm-lock.yaml`
|
|
10
|
+
- yarn: `yarn.lock`
|
|
11
|
+
- Reads **exact installed versions** from the lockfile
|
|
12
|
+
- Queries OSV (`https://api.osv.dev/v1/query`) per dependency
|
|
13
|
+
- Colored, human-readable table output (chalk + cli-table3)
|
|
14
|
+
- Spinner while scanning (ora)
|
|
15
|
+
- Optional `--json` output for automation
|
|
16
|
+
- Includes fix version when OSV provides one
|
|
17
|
+
|
|
18
|
+
## Install / Run
|
|
19
|
+
|
|
20
|
+
### Run with npx
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npx vuln-scan
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
### Install globally
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm i -g vuln-scan
|
|
30
|
+
vuln-scan
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
This package also exposes `vuln-scan-cli` as an alias:
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
npx vuln-scan -- --json
|
|
37
|
+
npx vuln-scan-cli
|
|
38
|
+
vuln-scan-cli --json
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
vuln-scan
|
|
45
|
+
vuln-scan --json
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Notes
|
|
49
|
+
|
|
50
|
+
- Requires Node.js `>= 18` (uses built-in `fetch`).
|
|
51
|
+
- Scans both dependencies and devDependencies as recorded in the lockfile.
|
|
52
|
+
|
|
53
|
+
## Development
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pnpm install
|
|
57
|
+
node ./cli.js
|
|
58
|
+
node ./cli.js --json
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
|
package/cli.js
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import chalk from 'chalk';
|
|
4
|
+
import ora from 'ora';
|
|
5
|
+
import Table from 'cli-table3';
|
|
6
|
+
|
|
7
|
+
import { scanProject } from './src/core.js';
|
|
8
|
+
|
|
9
|
+
function printHelp() {
|
|
10
|
+
const text = `
|
|
11
|
+
${chalk.bold('vuln-scan')}
|
|
12
|
+
|
|
13
|
+
Scans a project's lockfile (npm/pnpm/yarn) for known vulnerabilities using the OSV.dev API.
|
|
14
|
+
|
|
15
|
+
Usage:
|
|
16
|
+
npx vuln-scan
|
|
17
|
+
vuln-scan
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--json Output machine-readable JSON
|
|
21
|
+
--help Show this help
|
|
22
|
+
`;
|
|
23
|
+
// eslint-disable-next-line no-console
|
|
24
|
+
console.log(text.trim());
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function severityColor(sev) {
|
|
28
|
+
switch (sev) {
|
|
29
|
+
case 'CRITICAL':
|
|
30
|
+
return chalk.redBright(sev);
|
|
31
|
+
case 'HIGH':
|
|
32
|
+
return chalk.red(sev);
|
|
33
|
+
case 'MEDIUM':
|
|
34
|
+
return chalk.yellow(sev);
|
|
35
|
+
case 'LOW':
|
|
36
|
+
return chalk.green(sev);
|
|
37
|
+
default:
|
|
38
|
+
return chalk.gray(sev || 'UNKNOWN');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function main() {
|
|
43
|
+
const args = new Set(process.argv.slice(2));
|
|
44
|
+
if (args.has('--help') || args.has('-h')) {
|
|
45
|
+
printHelp();
|
|
46
|
+
process.exit(0);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const jsonOutput = args.has('--json');
|
|
50
|
+
|
|
51
|
+
const spinner = ora({ text: 'Scanning dependencies…', spinner: 'dots' }).start();
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const result = await scanProject({
|
|
55
|
+
cwd: process.cwd(),
|
|
56
|
+
onProgress: ({ processed, total }) => {
|
|
57
|
+
spinner.text = `Scanning dependencies… ${processed}/${total}`;
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
spinner.stop();
|
|
62
|
+
|
|
63
|
+
if (jsonOutput) {
|
|
64
|
+
// Keep stdout clean for piping/automation.
|
|
65
|
+
// eslint-disable-next-line no-console
|
|
66
|
+
console.log(JSON.stringify(result, null, 2));
|
|
67
|
+
// eslint-disable-next-line no-console
|
|
68
|
+
console.error(chalk.green('Scan complete!'));
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (result.vulnerabilities.length === 0) {
|
|
73
|
+
// eslint-disable-next-line no-console
|
|
74
|
+
console.log(chalk.green(`No known vulnerabilities found in ${result.dependencyCount} dependencies.`));
|
|
75
|
+
// eslint-disable-next-line no-console
|
|
76
|
+
console.log(chalk.green('Scan complete!'));
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const table = new Table({
|
|
81
|
+
head: ['Package', 'CVE ID', 'Severity', 'Summary'],
|
|
82
|
+
wordWrap: true,
|
|
83
|
+
colWidths: [
|
|
84
|
+
28,
|
|
85
|
+
18,
|
|
86
|
+
10,
|
|
87
|
+
70
|
|
88
|
+
]
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
for (const v of result.vulnerabilities) {
|
|
92
|
+
const pkg = `${v.package}@${v.version}`;
|
|
93
|
+
const cve = v.cve || v.id;
|
|
94
|
+
const summary = v.summary + (v.fixed ? ` (Fix: ${v.fixed})` : '');
|
|
95
|
+
|
|
96
|
+
table.push([pkg, cve, severityColor(v.severity), summary]);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// eslint-disable-next-line no-console
|
|
100
|
+
console.log(table.toString());
|
|
101
|
+
// eslint-disable-next-line no-console
|
|
102
|
+
console.log(chalk.green('Scan complete!'));
|
|
103
|
+
} catch (err) {
|
|
104
|
+
spinner.stop();
|
|
105
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
106
|
+
// eslint-disable-next-line no-console
|
|
107
|
+
console.error(chalk.red(`Error: ${message}`));
|
|
108
|
+
process.exitCode = 1;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
await main();
|
package/package.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "vuln-scan",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Node.js CLI to scan dependency lockfiles for vulnerabilities using OSV.dev",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"vuln-scan": "./cli.js",
|
|
8
|
+
"vuln-scan-cli": "./cli.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"cli.js",
|
|
12
|
+
"src"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"start": "node ./cli.js",
|
|
16
|
+
"scan": "node ./cli.js"
|
|
17
|
+
},
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=18"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@yarnpkg/lockfile": "^1.1.0",
|
|
23
|
+
"chalk": "^5.4.1",
|
|
24
|
+
"cli-table3": "^0.6.5",
|
|
25
|
+
"js-yaml": "^4.1.0",
|
|
26
|
+
"ora": "^8.1.1"
|
|
27
|
+
},
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"keywords": [
|
|
30
|
+
"security",
|
|
31
|
+
"vulnerability",
|
|
32
|
+
"osv",
|
|
33
|
+
"cli",
|
|
34
|
+
"npm",
|
|
35
|
+
"pnpm",
|
|
36
|
+
"yarn"
|
|
37
|
+
],
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/DebaA17/vuln-scan.git"
|
|
41
|
+
},
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/DebaA17/vuln-scan/issues"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://github.com/DebaA17/vuln-scan#readme"
|
|
46
|
+
}
|
package/src/core.js
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
import yaml from 'js-yaml';
|
|
5
|
+
import yarnLockfile from '@yarnpkg/lockfile';
|
|
6
|
+
|
|
7
|
+
const OSV_QUERY_URL = 'https://api.osv.dev/v1/query';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Scan the current project by detecting its lockfile, extracting exact installed versions,
|
|
11
|
+
* and querying OSV.dev for vulnerabilities.
|
|
12
|
+
*
|
|
13
|
+
* @param {object} params
|
|
14
|
+
* @param {string} params.cwd - Working directory to scan.
|
|
15
|
+
* @param {(progress: {processed: number, total: number}) => void} [params.onProgress]
|
|
16
|
+
* @returns {Promise<{packageManager: string, dependencyCount: number, vulnerabilities: Array<object>}>}
|
|
17
|
+
*/
|
|
18
|
+
export async function scanProject({ cwd, onProgress }) {
|
|
19
|
+
const projectPackageJsonPath = path.join(cwd, 'package.json');
|
|
20
|
+
const hasPackageJson = await exists(projectPackageJsonPath);
|
|
21
|
+
if (!hasPackageJson) {
|
|
22
|
+
throw new Error('Missing package.json in the current directory.');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const { packageManager, lockfilePath } = await detectPackageManager(cwd);
|
|
26
|
+
|
|
27
|
+
const dependencies = await readDependenciesFromLockfile({
|
|
28
|
+
packageManager,
|
|
29
|
+
lockfilePath
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const unique = uniqBy(dependencies, (d) => `${d.name}@${d.version}`);
|
|
33
|
+
|
|
34
|
+
const vulns = await queryVulnerabilities({
|
|
35
|
+
dependencies: unique,
|
|
36
|
+
onProgress
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// Flatten to one row per (package@version, vulnerability)
|
|
40
|
+
const flattened = [];
|
|
41
|
+
for (const item of vulns) {
|
|
42
|
+
for (const vuln of item.vulns) {
|
|
43
|
+
flattened.push({
|
|
44
|
+
package: item.dependency.name,
|
|
45
|
+
version: item.dependency.version,
|
|
46
|
+
id: vuln.id,
|
|
47
|
+
cve: vuln.cve,
|
|
48
|
+
severity: vuln.severity,
|
|
49
|
+
summary: vuln.summary,
|
|
50
|
+
fixed: vuln.fixed
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Sort: most severe first, then package name
|
|
56
|
+
flattened.sort((a, b) => {
|
|
57
|
+
const s = severityRank(b.severity) - severityRank(a.severity);
|
|
58
|
+
if (s !== 0) return s;
|
|
59
|
+
const p = a.package.localeCompare(b.package);
|
|
60
|
+
if (p !== 0) return p;
|
|
61
|
+
return a.version.localeCompare(b.version);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
return {
|
|
65
|
+
packageManager,
|
|
66
|
+
dependencyCount: unique.length,
|
|
67
|
+
vulnerabilities: flattened
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function detectPackageManager(cwd) {
|
|
72
|
+
const candidates = [
|
|
73
|
+
{ packageManager: 'npm', file: 'package-lock.json' },
|
|
74
|
+
{ packageManager: 'pnpm', file: 'pnpm-lock.yaml' },
|
|
75
|
+
{ packageManager: 'yarn', file: 'yarn.lock' }
|
|
76
|
+
];
|
|
77
|
+
|
|
78
|
+
for (const c of candidates) {
|
|
79
|
+
const p = path.join(cwd, c.file);
|
|
80
|
+
if (await exists(p)) {
|
|
81
|
+
return { packageManager: c.packageManager, lockfilePath: p };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
throw new Error('No supported lockfile found (package-lock.json, pnpm-lock.yaml, yarn.lock).');
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function readDependenciesFromLockfile({ packageManager, lockfilePath }) {
|
|
89
|
+
switch (packageManager) {
|
|
90
|
+
case 'npm':
|
|
91
|
+
return readFromNpmLockfile(lockfilePath);
|
|
92
|
+
case 'pnpm':
|
|
93
|
+
return readFromPnpmLockfile(lockfilePath);
|
|
94
|
+
case 'yarn':
|
|
95
|
+
return readFromYarnLockfile(lockfilePath);
|
|
96
|
+
default:
|
|
97
|
+
throw new Error(`Unsupported package manager: ${packageManager}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Parse npm's package-lock.json (v1/v2/v3).
|
|
103
|
+
*
|
|
104
|
+
* We prefer the "packages" section (npm v7+), because it includes exact installed versions.
|
|
105
|
+
*/
|
|
106
|
+
async function readFromNpmLockfile(lockfilePath) {
|
|
107
|
+
const raw = await fs.readFile(lockfilePath, 'utf8');
|
|
108
|
+
const data = JSON.parse(raw);
|
|
109
|
+
|
|
110
|
+
const deps = [];
|
|
111
|
+
|
|
112
|
+
if (data && data.packages && typeof data.packages === 'object') {
|
|
113
|
+
for (const [key, value] of Object.entries(data.packages)) {
|
|
114
|
+
if (!key || key === '') continue; // root
|
|
115
|
+
if (!key.includes('node_modules/')) continue;
|
|
116
|
+
if (!value || typeof value !== 'object') continue;
|
|
117
|
+
if (!value.version) continue;
|
|
118
|
+
|
|
119
|
+
const name = packageNameFromNpmPackagesKey(key);
|
|
120
|
+
if (!name) continue;
|
|
121
|
+
|
|
122
|
+
deps.push({ name, version: String(value.version) });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return deps;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Fallback for older lockfiles: top-level "dependencies".
|
|
129
|
+
if (data && data.dependencies && typeof data.dependencies === 'object') {
|
|
130
|
+
collectNpmDepsRecursive(data.dependencies, deps);
|
|
131
|
+
return deps;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
throw new Error('Unsupported or invalid package-lock.json format.');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function packageNameFromNpmPackagesKey(key) {
|
|
138
|
+
// Examples:
|
|
139
|
+
// - node_modules/react
|
|
140
|
+
// - node_modules/@types/node
|
|
141
|
+
// - node_modules/a/node_modules/b
|
|
142
|
+
const idx = key.lastIndexOf('node_modules/');
|
|
143
|
+
if (idx === -1) return null;
|
|
144
|
+
return key.slice(idx + 'node_modules/'.length);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function collectNpmDepsRecursive(node, out) {
|
|
148
|
+
for (const [name, info] of Object.entries(node)) {
|
|
149
|
+
if (!info || typeof info !== 'object') continue;
|
|
150
|
+
if (info.version) out.push({ name, version: String(info.version) });
|
|
151
|
+
if (info.dependencies && typeof info.dependencies === 'object') {
|
|
152
|
+
collectNpmDepsRecursive(info.dependencies, out);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Parse pnpm-lock.yaml.
|
|
159
|
+
*
|
|
160
|
+
* pnpm stores installed packages under the "packages" map with keys like:
|
|
161
|
+
* /react/18.2.0
|
|
162
|
+
* /@types/node/20.11.17
|
|
163
|
+
*/
|
|
164
|
+
async function readFromPnpmLockfile(lockfilePath) {
|
|
165
|
+
const raw = await fs.readFile(lockfilePath, 'utf8');
|
|
166
|
+
const data = yaml.load(raw);
|
|
167
|
+
if (!data || typeof data !== 'object') {
|
|
168
|
+
throw new Error('Invalid pnpm-lock.yaml');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const packages = /** @type {any} */ (data).packages;
|
|
172
|
+
if (!packages || typeof packages !== 'object') {
|
|
173
|
+
throw new Error('pnpm-lock.yaml does not contain a "packages" section.');
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const deps = [];
|
|
177
|
+
for (const key of Object.keys(packages)) {
|
|
178
|
+
// Ignore non-package keys.
|
|
179
|
+
if (typeof key !== 'string') continue;
|
|
180
|
+
|
|
181
|
+
const parsed = parsePnpmPackageKey(key);
|
|
182
|
+
if (!parsed) continue;
|
|
183
|
+
|
|
184
|
+
deps.push(parsed);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
return deps;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function parsePnpmPackageKey(key) {
|
|
191
|
+
// pnpm lockfile keys vary across versions.
|
|
192
|
+
// Examples:
|
|
193
|
+
// - /react/18.2.0
|
|
194
|
+
// - /@types/node/20.11.17
|
|
195
|
+
// - chalk@5.6.2
|
|
196
|
+
// - @yarnpkg/lockfile@1.1.0
|
|
197
|
+
// Keys may include peers in parentheses, e.g. foo@1.0.0(bar@2.0.0)
|
|
198
|
+
|
|
199
|
+
const noPeers = key.split('(')[0].trim();
|
|
200
|
+
if (!noPeers) return null;
|
|
201
|
+
|
|
202
|
+
if (noPeers.startsWith('/')) {
|
|
203
|
+
const parts = noPeers.split('/').filter(Boolean);
|
|
204
|
+
if (parts.length < 2) return null;
|
|
205
|
+
|
|
206
|
+
const version = parts[parts.length - 1];
|
|
207
|
+
const name = parts.slice(0, parts.length - 1).join('/');
|
|
208
|
+
if (!name || !version) return null;
|
|
209
|
+
|
|
210
|
+
return { name, version };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// name@version (scoped or unscoped). Split on last '@'.
|
|
214
|
+
const at = noPeers.lastIndexOf('@');
|
|
215
|
+
if (at <= 0) return null;
|
|
216
|
+
|
|
217
|
+
const name = noPeers.slice(0, at);
|
|
218
|
+
const version = noPeers.slice(at + 1);
|
|
219
|
+
if (!name || !version) return null;
|
|
220
|
+
|
|
221
|
+
return { name, version };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Parse yarn.lock.
|
|
226
|
+
*
|
|
227
|
+
* Uses @yarnpkg/lockfile to support Yarn v1-style lockfiles.
|
|
228
|
+
*/
|
|
229
|
+
async function readFromYarnLockfile(lockfilePath) {
|
|
230
|
+
const raw = await fs.readFile(lockfilePath, 'utf8');
|
|
231
|
+
const parsed = yarnLockfile.parse(raw);
|
|
232
|
+
|
|
233
|
+
if (!parsed || parsed.type !== 'success' || !parsed.object) {
|
|
234
|
+
throw new Error('Failed to parse yarn.lock');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const deps = [];
|
|
238
|
+
|
|
239
|
+
// `parsed.object` keys look like: "react@^18.2.0, react@~18.2.0".
|
|
240
|
+
// The value contains the resolved version.
|
|
241
|
+
for (const [selector, value] of Object.entries(parsed.object)) {
|
|
242
|
+
if (!value || typeof value !== 'object') continue;
|
|
243
|
+
const version = /** @type {any} */ (value).version;
|
|
244
|
+
if (!version) continue;
|
|
245
|
+
|
|
246
|
+
// Selectors can be multiple entries separated by ",".
|
|
247
|
+
const first = selector.split(',')[0].trim();
|
|
248
|
+
const name = yarnSelectorToName(first);
|
|
249
|
+
if (!name) continue;
|
|
250
|
+
|
|
251
|
+
deps.push({ name, version: String(version) });
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return deps;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function yarnSelectorToName(selector) {
|
|
258
|
+
// Examples:
|
|
259
|
+
// react@^18.2.0
|
|
260
|
+
// @types/node@^20.0.0
|
|
261
|
+
// "@scope/name@npm:^1.2.3" (rare) => we strip quotes and protocols
|
|
262
|
+
|
|
263
|
+
const s = selector.replace(/^"|"$/g, '');
|
|
264
|
+
|
|
265
|
+
// Strip possible protocol prefixes (yarn berry selectors):
|
|
266
|
+
// pkg@npm:1.2.3
|
|
267
|
+
// pkg@workspace:*
|
|
268
|
+
const npmPrefix = '@npm:';
|
|
269
|
+
const protocolIndex = s.indexOf(npmPrefix);
|
|
270
|
+
if (protocolIndex !== -1) {
|
|
271
|
+
// "name@npm:range" -> keep "name@range" for parsing
|
|
272
|
+
const before = s.slice(0, protocolIndex);
|
|
273
|
+
const after = s.slice(protocolIndex + npmPrefix.length);
|
|
274
|
+
return yarnSelectorToName(`${before}@${after}`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
if (s.startsWith('@')) {
|
|
278
|
+
// Scoped package: @scope/name@range => split on last '@'
|
|
279
|
+
const idx = s.lastIndexOf('@');
|
|
280
|
+
if (idx <= 0) return null;
|
|
281
|
+
return s.slice(0, idx);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Unscoped: name@range
|
|
285
|
+
const idx = s.indexOf('@');
|
|
286
|
+
if (idx === -1) return null;
|
|
287
|
+
return s.slice(0, idx);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function queryVulnerabilities({ dependencies, onProgress }) {
|
|
291
|
+
const concurrency = 12;
|
|
292
|
+
let processed = 0;
|
|
293
|
+
const total = dependencies.length;
|
|
294
|
+
|
|
295
|
+
const results = [];
|
|
296
|
+
|
|
297
|
+
await promisePool({
|
|
298
|
+
items: dependencies,
|
|
299
|
+
concurrency,
|
|
300
|
+
worker: async (dependency) => {
|
|
301
|
+
const response = await queryOsv({ name: dependency.name, version: dependency.version });
|
|
302
|
+
const normalized = normalizeOsvResponse({ dependency, response });
|
|
303
|
+
results.push({ dependency, vulns: normalized });
|
|
304
|
+
|
|
305
|
+
processed += 1;
|
|
306
|
+
if (onProgress) onProgress({ processed, total });
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
// Keep only dependencies with vulnerabilities
|
|
311
|
+
return results.filter((r) => r.vulns.length > 0);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function queryOsv({ name, version }) {
|
|
315
|
+
const body = {
|
|
316
|
+
version,
|
|
317
|
+
package: {
|
|
318
|
+
name,
|
|
319
|
+
ecosystem: 'npm'
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
const res = await fetch(OSV_QUERY_URL, {
|
|
324
|
+
method: 'POST',
|
|
325
|
+
headers: {
|
|
326
|
+
'content-type': 'application/json'
|
|
327
|
+
},
|
|
328
|
+
body: JSON.stringify(body)
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
if (!res.ok) {
|
|
332
|
+
const text = await safeReadText(res);
|
|
333
|
+
throw new Error(`OSV query failed for ${name}@${version} (${res.status}): ${text}`);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return res.json();
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function normalizeOsvResponse({ dependency, response }) {
|
|
340
|
+
const vulns = Array.isArray(response?.vulns) ? response.vulns : [];
|
|
341
|
+
|
|
342
|
+
return vulns.map((v) => {
|
|
343
|
+
const id = String(v.id || '');
|
|
344
|
+
const cve = findCveAlias(v);
|
|
345
|
+
const summary = String(v.summary || v.details || '');
|
|
346
|
+
const severity = computeSeverity(v);
|
|
347
|
+
const fixed = extractFixedVersion({ vuln: v, packageName: dependency.name });
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
id,
|
|
351
|
+
cve,
|
|
352
|
+
summary: summary.trim().replace(/\s+/g, ' '),
|
|
353
|
+
severity,
|
|
354
|
+
fixed
|
|
355
|
+
};
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function findCveAlias(vuln) {
|
|
360
|
+
const aliases = Array.isArray(vuln?.aliases) ? vuln.aliases : [];
|
|
361
|
+
const cve = aliases.find((a) => typeof a === 'string' && a.startsWith('CVE-'));
|
|
362
|
+
return cve || null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function computeSeverity(vuln) {
|
|
366
|
+
// OSV uses `severity` entries like: { type: "CVSS_V3", score: "9.8" }
|
|
367
|
+
const sev = Array.isArray(vuln?.severity) ? vuln.severity : [];
|
|
368
|
+
|
|
369
|
+
const scores = sev
|
|
370
|
+
.map((s) => {
|
|
371
|
+
const score = typeof s?.score === 'string' ? parseFloat(s.score) : NaN;
|
|
372
|
+
return Number.isFinite(score) ? score : null;
|
|
373
|
+
})
|
|
374
|
+
.filter((x) => x !== null);
|
|
375
|
+
|
|
376
|
+
const maxScore = scores.length ? Math.max(...scores) : null;
|
|
377
|
+
|
|
378
|
+
// Some records have a database-specific severity label.
|
|
379
|
+
const dbSev = vuln?.database_specific?.severity;
|
|
380
|
+
if (typeof dbSev === 'string') {
|
|
381
|
+
const normalized = dbSev.toUpperCase();
|
|
382
|
+
if (['LOW', 'MEDIUM', 'HIGH', 'CRITICAL'].includes(normalized)) return normalized;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
if (maxScore === null) return 'UNKNOWN';
|
|
386
|
+
if (maxScore >= 9) return 'CRITICAL';
|
|
387
|
+
if (maxScore >= 7) return 'HIGH';
|
|
388
|
+
if (maxScore >= 4) return 'MEDIUM';
|
|
389
|
+
if (maxScore > 0) return 'LOW';
|
|
390
|
+
return 'UNKNOWN';
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function severityRank(sev) {
|
|
394
|
+
switch (sev) {
|
|
395
|
+
case 'CRITICAL':
|
|
396
|
+
return 4;
|
|
397
|
+
case 'HIGH':
|
|
398
|
+
return 3;
|
|
399
|
+
case 'MEDIUM':
|
|
400
|
+
return 2;
|
|
401
|
+
case 'LOW':
|
|
402
|
+
return 1;
|
|
403
|
+
default:
|
|
404
|
+
return 0;
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function extractFixedVersion({ vuln, packageName }) {
|
|
409
|
+
// Try to find any `fixed` event in affected ranges for this package.
|
|
410
|
+
const affected = Array.isArray(vuln?.affected) ? vuln.affected : [];
|
|
411
|
+
|
|
412
|
+
for (const a of affected) {
|
|
413
|
+
const pName = a?.package?.name;
|
|
414
|
+
if (pName && pName !== packageName) continue;
|
|
415
|
+
|
|
416
|
+
const ranges = Array.isArray(a?.ranges) ? a.ranges : [];
|
|
417
|
+
for (const r of ranges) {
|
|
418
|
+
const events = Array.isArray(r?.events) ? r.events : [];
|
|
419
|
+
for (const e of events) {
|
|
420
|
+
if (typeof e?.fixed === 'string' && e.fixed.trim()) {
|
|
421
|
+
return e.fixed.trim();
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Some ecosystems store it elsewhere.
|
|
428
|
+
const dbFixed = vuln?.database_specific?.fixed;
|
|
429
|
+
if (typeof dbFixed === 'string' && dbFixed.trim()) return dbFixed.trim();
|
|
430
|
+
|
|
431
|
+
return null;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
async function safeReadText(res) {
|
|
435
|
+
try {
|
|
436
|
+
return await res.text();
|
|
437
|
+
} catch {
|
|
438
|
+
return '';
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
async function exists(filePath) {
|
|
443
|
+
try {
|
|
444
|
+
await fs.access(filePath);
|
|
445
|
+
return true;
|
|
446
|
+
} catch {
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function uniqBy(items, keyFn) {
|
|
452
|
+
const seen = new Set();
|
|
453
|
+
const out = [];
|
|
454
|
+
for (const item of items) {
|
|
455
|
+
const key = keyFn(item);
|
|
456
|
+
if (seen.has(key)) continue;
|
|
457
|
+
seen.add(key);
|
|
458
|
+
out.push(item);
|
|
459
|
+
}
|
|
460
|
+
return out;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
async function promisePool({ items, concurrency, worker }) {
|
|
464
|
+
const queue = items.slice();
|
|
465
|
+
const workers = [];
|
|
466
|
+
|
|
467
|
+
const runOne = async () => {
|
|
468
|
+
while (queue.length) {
|
|
469
|
+
const item = queue.shift();
|
|
470
|
+
if (item === undefined) return;
|
|
471
|
+
await worker(item);
|
|
472
|
+
}
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
for (let i = 0; i < Math.max(1, concurrency); i += 1) {
|
|
476
|
+
workers.push(runOne());
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
await Promise.all(workers);
|
|
480
|
+
}
|