cve-lite-cli 1.0.2 → 1.0.4
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/README.md +206 -101
- package/dist/banner.js +10 -0
- package/dist/chalk.js +44 -0
- package/dist/cli/args.js +84 -0
- package/dist/cli/help.js +41 -0
- package/dist/constants.js +19 -0
- package/dist/index.js +24 -1259
- package/dist/osv/api.js +26 -0
- package/dist/osv/cache.js +31 -0
- package/dist/osv/severity.js +50 -0
- package/dist/output/formatters.js +113 -0
- package/dist/output/printers.js +319 -0
- package/dist/output/spinner.js +42 -0
- package/dist/parsers/index.js +142 -0
- package/dist/parsers/package-json.js +37 -0
- package/dist/parsers/package-lock.js +40 -0
- package/dist/parsers/pnpm-lock.js +109 -0
- package/dist/parsers/utils.js +32 -0
- package/dist/parsers/yarn-lock.js +25 -0
- package/dist/scanner.js +131 -0
- package/dist/types.js +1 -0
- package/dist/utils/array.js +22 -0
- package/dist/utils/chalk.js +48 -0
- package/dist/utils/file.js +74 -0
- package/dist/utils/version.js +39 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,156 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import fs from "node:fs";
|
|
3
2
|
import path from "node:path";
|
|
4
3
|
import process from "node:process";
|
|
5
|
-
import
|
|
6
|
-
import
|
|
7
|
-
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
greenBright: "\x1b[92m",
|
|
15
|
-
yellow: "\x1b[33m",
|
|
16
|
-
blue: "\x1b[34m",
|
|
17
|
-
blueBright: "\x1b[94m",
|
|
18
|
-
magenta: "\x1b[35m",
|
|
19
|
-
cyan: "\x1b[36m",
|
|
20
|
-
white: "\x1b[37m",
|
|
21
|
-
whiteBright: "\x1b[97m",
|
|
22
|
-
gray: "\x1b[90m"
|
|
23
|
-
};
|
|
24
|
-
const colorEnabled = Boolean(process.stdout.isTTY) && process.env.NO_COLOR !== "1";
|
|
25
|
-
function paint(code, text) {
|
|
26
|
-
if (!colorEnabled)
|
|
27
|
-
return text;
|
|
28
|
-
return `${code}${text}${ansi.reset}`;
|
|
29
|
-
}
|
|
30
|
-
const chalk = {
|
|
31
|
-
bold: Object.assign((text) => paint(ansi.bold, text), {
|
|
32
|
-
cyan: (text) => paint(ansi.bold + ansi.cyan, text),
|
|
33
|
-
green: (text) => paint(ansi.bold + ansi.green, text),
|
|
34
|
-
magenta: (text) => paint(ansi.bold + ansi.magenta, text),
|
|
35
|
-
blue: (text) => paint(ansi.bold + ansi.blue, text),
|
|
36
|
-
yellow: (text) => paint(ansi.bold + ansi.yellow, text)
|
|
37
|
-
}),
|
|
38
|
-
cyan: (text) => paint(ansi.cyan, text),
|
|
39
|
-
green: (text) => paint(ansi.green, text),
|
|
40
|
-
greenBright: (text) => paint(ansi.greenBright, text),
|
|
41
|
-
red: (text) => paint(ansi.red, text),
|
|
42
|
-
redBright: (text) => paint(ansi.redBright, text),
|
|
43
|
-
yellow: (text) => paint(ansi.yellow, text),
|
|
44
|
-
blue: (text) => paint(ansi.blue, text),
|
|
45
|
-
blueBright: (text) => paint(ansi.blueBright, text),
|
|
46
|
-
magenta: (text) => paint(ansi.magenta, text),
|
|
47
|
-
gray: (text) => paint(ansi.gray, text),
|
|
48
|
-
white: (text) => paint(ansi.white, text),
|
|
49
|
-
whiteBright: (text) => paint(ansi.whiteBright, text)
|
|
50
|
-
};
|
|
51
|
-
function printHelp() {
|
|
52
|
-
const lines = [
|
|
53
|
-
"cve-lite",
|
|
54
|
-
"",
|
|
55
|
-
"Fast local-first CVE scanner for JS/TS projects using lockfiles + OSV",
|
|
56
|
-
"",
|
|
57
|
-
"Usage:",
|
|
58
|
-
" cve-lite [projectPath] [options]",
|
|
59
|
-
"",
|
|
60
|
-
"Options:",
|
|
61
|
-
" --json Print JSON output",
|
|
62
|
-
" --prod-only Exclude dev dependencies where available",
|
|
63
|
-
" --fail-on <severity> Exit non-zero at or above severity (default: critical)",
|
|
64
|
-
" --batch-size <number> OSV batch size (default: 100)",
|
|
65
|
-
" --offline Use cached vulnerability details only",
|
|
66
|
-
" --cache-dir <path> Override cache directory",
|
|
67
|
-
" --search-depth <number> Recursive search depth (default: 4)",
|
|
68
|
-
" --all Show all findings in the main table",
|
|
69
|
-
" --min-severity <level> Minimum severity shown in table (default: medium)",
|
|
70
|
-
" -h, --help Show this help message"
|
|
71
|
-
];
|
|
72
|
-
console.log(lines.join("\n"));
|
|
73
|
-
}
|
|
74
|
-
function parseArgs(argv) {
|
|
75
|
-
const options = {
|
|
76
|
-
failOn: "critical",
|
|
77
|
-
batchSize: "100",
|
|
78
|
-
searchDepth: "4",
|
|
79
|
-
minSeverity: "medium"
|
|
80
|
-
};
|
|
81
|
-
let projectArg;
|
|
82
|
-
for (let i = 0; i < argv.length; i++) {
|
|
83
|
-
const arg = argv[i];
|
|
84
|
-
if (arg === "-h" || arg === "--help") {
|
|
85
|
-
options.help = true;
|
|
86
|
-
continue;
|
|
87
|
-
}
|
|
88
|
-
if (arg === "--json") {
|
|
89
|
-
options.json = true;
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
if (arg === "--prod-only") {
|
|
93
|
-
options.prodOnly = true;
|
|
94
|
-
continue;
|
|
95
|
-
}
|
|
96
|
-
if (arg === "--offline") {
|
|
97
|
-
options.offline = true;
|
|
98
|
-
continue;
|
|
99
|
-
}
|
|
100
|
-
if (arg === "--all") {
|
|
101
|
-
options.all = true;
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
|
-
if (arg === "--fail-on") {
|
|
105
|
-
options.failOn = argv[++i] ?? options.failOn;
|
|
106
|
-
continue;
|
|
107
|
-
}
|
|
108
|
-
if (arg.startsWith("--fail-on=")) {
|
|
109
|
-
options.failOn = arg.slice("--fail-on=".length);
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
if (arg === "--batch-size") {
|
|
113
|
-
options.batchSize = argv[++i] ?? options.batchSize;
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
if (arg.startsWith("--batch-size=")) {
|
|
117
|
-
options.batchSize = arg.slice("--batch-size=".length);
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
if (arg === "--cache-dir") {
|
|
121
|
-
options.cacheDir = argv[++i];
|
|
122
|
-
continue;
|
|
123
|
-
}
|
|
124
|
-
if (arg.startsWith("--cache-dir=")) {
|
|
125
|
-
options.cacheDir = arg.slice("--cache-dir=".length);
|
|
126
|
-
continue;
|
|
127
|
-
}
|
|
128
|
-
if (arg === "--search-depth") {
|
|
129
|
-
options.searchDepth = argv[++i] ?? options.searchDepth;
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
if (arg.startsWith("--search-depth=")) {
|
|
133
|
-
options.searchDepth = arg.slice("--search-depth=".length);
|
|
134
|
-
continue;
|
|
135
|
-
}
|
|
136
|
-
if (arg === "--min-severity") {
|
|
137
|
-
options.minSeverity = argv[++i] ?? options.minSeverity;
|
|
138
|
-
continue;
|
|
139
|
-
}
|
|
140
|
-
if (arg.startsWith("--min-severity=")) {
|
|
141
|
-
options.minSeverity = arg.slice("--min-severity=".length);
|
|
142
|
-
continue;
|
|
143
|
-
}
|
|
144
|
-
if (arg.startsWith("-"))
|
|
145
|
-
throw new Error(`Unknown option: ${arg}`);
|
|
146
|
-
if (!projectArg) {
|
|
147
|
-
projectArg = arg;
|
|
148
|
-
continue;
|
|
149
|
-
}
|
|
150
|
-
throw new Error(`Unexpected argument: ${arg}`);
|
|
151
|
-
}
|
|
152
|
-
return { options, projectArg };
|
|
153
|
-
}
|
|
4
|
+
import { parseArgs } from "./cli/args.js";
|
|
5
|
+
import { printBanner, printHelp } from "./cli/help.js";
|
|
6
|
+
import { loadPackages, buildNoPackagesMessage } from "./parsers/index.js";
|
|
7
|
+
import { scanPackages, buildCoverageNotes } from "./scanner.js";
|
|
8
|
+
import { normalizeSeverity } from "./osv/severity.js";
|
|
9
|
+
import { severityOrder } from "./constants.js";
|
|
10
|
+
import { chalk } from "./utils/chalk.js";
|
|
11
|
+
import { logInfo, logWarn, printCacheSummary, serializeFinding } from "./output/formatters.js";
|
|
12
|
+
import { printSummary, printActionSummary, printPriorityFixes, printFixPlan, printCoverage, printSkippedDependencies, printGroupSummary, printTable, printPathHints, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
154
13
|
const { options, projectArg } = parseArgs(process.argv.slice(2));
|
|
155
14
|
if (options.help) {
|
|
156
15
|
printHelp();
|
|
@@ -159,29 +18,24 @@ if (options.help) {
|
|
|
159
18
|
const projectPath = path.resolve(projectArg || ".");
|
|
160
19
|
const batchSize = Number(options.batchSize || 100);
|
|
161
20
|
const searchDepth = Math.max(0, Number(options.searchDepth || 4));
|
|
162
|
-
const severityOrder = {
|
|
163
|
-
none: 0,
|
|
164
|
-
low: 1,
|
|
165
|
-
medium: 2,
|
|
166
|
-
high: 3,
|
|
167
|
-
critical: 4,
|
|
168
|
-
unknown: 1
|
|
169
|
-
};
|
|
170
21
|
async function main() {
|
|
22
|
+
if (!options.json) {
|
|
23
|
+
printBanner();
|
|
24
|
+
}
|
|
171
25
|
const scanInput = loadPackages(projectPath, !!options.prodOnly, searchDepth);
|
|
172
26
|
const packages = scanInput.packages;
|
|
173
|
-
logInfo(`Parsed ${packages.length} package${packages.length === 1 ? "" : "s"} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}
|
|
174
|
-
printCacheSummary(options.cacheDir);
|
|
27
|
+
logInfo(`Parsed ${packages.length} package${packages.length === 1 ? "" : "s"} from ${scanInput.source}${scanInput.filePath ? ` (${path.relative(projectPath, scanInput.filePath) || path.basename(scanInput.filePath)})` : ""}`, options);
|
|
28
|
+
printCacheSummary(options.cacheDir, options);
|
|
175
29
|
if (scanInput.warnings.length > 0) {
|
|
176
30
|
for (const warning of scanInput.warnings) {
|
|
177
|
-
logWarn(warning);
|
|
31
|
+
logWarn(warning, options);
|
|
178
32
|
}
|
|
179
33
|
}
|
|
180
34
|
if (packages.length === 0) {
|
|
181
|
-
logWarn(buildNoPackagesMessage(projectPath));
|
|
35
|
+
logWarn(buildNoPackagesMessage(projectPath), options);
|
|
182
36
|
process.exit(0);
|
|
183
37
|
}
|
|
184
|
-
const findings = await scanPackages(packages, batchSize, !!options.offline, options.cacheDir);
|
|
38
|
+
const findings = await scanPackages(packages, batchSize, !!options.offline, options.cacheDir, options);
|
|
185
39
|
const sorted = findings.sort((a, b) => severityOrder[b.severity] - severityOrder[a.severity]);
|
|
186
40
|
const coverage = buildCoverageNotes(scanInput, !!options.offline);
|
|
187
41
|
const minSeverity = normalizeSeverity(options.minSeverity || "medium");
|
|
@@ -199,7 +53,8 @@ async function main() {
|
|
|
199
53
|
findings: sorted.map(serializeFinding)
|
|
200
54
|
}, null, 2));
|
|
201
55
|
}
|
|
202
|
-
else {
|
|
56
|
+
else if (options.verbose) {
|
|
57
|
+
// Verbose output - show all details
|
|
203
58
|
printSummary(sorted, packages.length, scanInput);
|
|
204
59
|
printActionSummary(sorted);
|
|
205
60
|
printPriorityFixes(sorted);
|
|
@@ -215,1109 +70,19 @@ async function main() {
|
|
|
215
70
|
printPathHints(tableFindings);
|
|
216
71
|
}
|
|
217
72
|
else {
|
|
218
|
-
logInfo(`No findings met the table threshold of ${minSeverity}. Re-run with --all to show everything
|
|
73
|
+
logInfo(`No findings met the table threshold of ${minSeverity}. Re-run with --all to show everything.`, options);
|
|
219
74
|
}
|
|
220
75
|
}
|
|
221
76
|
printFinalStatus(sorted);
|
|
222
77
|
}
|
|
78
|
+
else {
|
|
79
|
+
// Simplified output - cleaner, focused view
|
|
80
|
+
printCompactOutput(sorted);
|
|
81
|
+
}
|
|
223
82
|
const failLevel = normalizeSeverity(options.failOn);
|
|
224
83
|
const shouldFail = sorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
|
|
225
84
|
process.exit(shouldFail ? 1 : 0);
|
|
226
85
|
}
|
|
227
|
-
function createSpinner(initialMessage) {
|
|
228
|
-
const enabled = !options.json && Boolean(process.stdout.isTTY);
|
|
229
|
-
if (!enabled) {
|
|
230
|
-
return {
|
|
231
|
-
update: () => { },
|
|
232
|
-
succeed: () => { },
|
|
233
|
-
fail: () => { },
|
|
234
|
-
stop: () => { }
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
238
|
-
let frameIndex = 0;
|
|
239
|
-
let currentMessage = initialMessage;
|
|
240
|
-
const render = () => {
|
|
241
|
-
process.stdout.write(`\r\x1b[2K${chalk.cyan(frames[frameIndex])} ${currentMessage}`);
|
|
242
|
-
frameIndex = (frameIndex + 1) % frames.length;
|
|
243
|
-
};
|
|
244
|
-
render();
|
|
245
|
-
const timer = setInterval(render, 80);
|
|
246
|
-
const clearLine = () => {
|
|
247
|
-
clearInterval(timer);
|
|
248
|
-
process.stdout.write("\r\x1b[2K");
|
|
249
|
-
};
|
|
250
|
-
return {
|
|
251
|
-
update(message) {
|
|
252
|
-
currentMessage = message;
|
|
253
|
-
},
|
|
254
|
-
succeed(message) {
|
|
255
|
-
clearLine();
|
|
256
|
-
console.log(chalk.green(`✓ ${message}`));
|
|
257
|
-
},
|
|
258
|
-
fail(message) {
|
|
259
|
-
clearLine();
|
|
260
|
-
console.log(chalk.red(`✗ ${message}`));
|
|
261
|
-
},
|
|
262
|
-
stop() {
|
|
263
|
-
clearLine();
|
|
264
|
-
}
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
function loadPackages(projectRoot, prodOnly, maxDepth) {
|
|
268
|
-
const rootPackageLock = path.join(projectRoot, "package-lock.json");
|
|
269
|
-
const rootPnpmLock = path.join(projectRoot, "pnpm-lock.yaml");
|
|
270
|
-
const rootYarnLock = path.join(projectRoot, "yarn.lock");
|
|
271
|
-
if (fs.existsSync(rootPackageLock)) {
|
|
272
|
-
return {
|
|
273
|
-
mode: "resolved-lockfile",
|
|
274
|
-
source: "package-lock",
|
|
275
|
-
filePath: rootPackageLock,
|
|
276
|
-
packages: loadFromPackageLock(rootPackageLock, prodOnly),
|
|
277
|
-
notes: [
|
|
278
|
-
"Scanned resolved dependency versions from package-lock.json.",
|
|
279
|
-
"Dependency paths are derived from lockfile package locations."
|
|
280
|
-
],
|
|
281
|
-
warnings: [],
|
|
282
|
-
skippedDependencies: []
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
if (fs.existsSync(rootPnpmLock)) {
|
|
286
|
-
return {
|
|
287
|
-
mode: "resolved-lockfile",
|
|
288
|
-
source: "pnpm-lock",
|
|
289
|
-
filePath: rootPnpmLock,
|
|
290
|
-
packages: loadFromPnpmLock(rootPnpmLock, prodOnly),
|
|
291
|
-
notes: [
|
|
292
|
-
"Scanned resolved dependency versions from pnpm-lock.yaml.",
|
|
293
|
-
"Dependency paths are approximated from importer relationships and package snapshots."
|
|
294
|
-
],
|
|
295
|
-
warnings: [],
|
|
296
|
-
skippedDependencies: []
|
|
297
|
-
};
|
|
298
|
-
}
|
|
299
|
-
if (fs.existsSync(rootYarnLock)) {
|
|
300
|
-
return {
|
|
301
|
-
mode: "resolved-lockfile",
|
|
302
|
-
source: "yarn-lock",
|
|
303
|
-
filePath: rootYarnLock,
|
|
304
|
-
packages: loadFromYarnLock(rootYarnLock),
|
|
305
|
-
notes: [
|
|
306
|
-
"Scanned resolved dependency versions from yarn.lock.",
|
|
307
|
-
"Dependency path reconstruction is limited for Yarn Classic lockfiles in this MVP."
|
|
308
|
-
],
|
|
309
|
-
warnings: [],
|
|
310
|
-
skippedDependencies: []
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
const discoveredLockfiles = findFiles(projectRoot, ["package-lock.json", "pnpm-lock.yaml", "yarn.lock"], maxDepth);
|
|
314
|
-
if (discoveredLockfiles.length > 0) {
|
|
315
|
-
const selected = chooseBestLockfile(discoveredLockfiles);
|
|
316
|
-
const selectedName = path.basename(selected);
|
|
317
|
-
if (selectedName === "package-lock.json") {
|
|
318
|
-
return {
|
|
319
|
-
mode: "resolved-lockfile",
|
|
320
|
-
source: "package-lock",
|
|
321
|
-
filePath: selected,
|
|
322
|
-
packages: loadFromPackageLock(selected, prodOnly),
|
|
323
|
-
notes: [
|
|
324
|
-
`Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
|
|
325
|
-
"Dependency paths are derived from lockfile package locations."
|
|
326
|
-
],
|
|
327
|
-
warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
|
|
328
|
-
skippedDependencies: []
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
if (selectedName === "pnpm-lock.yaml") {
|
|
332
|
-
return {
|
|
333
|
-
mode: "resolved-lockfile",
|
|
334
|
-
source: "pnpm-lock",
|
|
335
|
-
filePath: selected,
|
|
336
|
-
packages: loadFromPnpmLock(selected, prodOnly),
|
|
337
|
-
notes: [
|
|
338
|
-
`Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
|
|
339
|
-
"Dependency paths are approximated from importer relationships and package snapshots."
|
|
340
|
-
],
|
|
341
|
-
warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
|
|
342
|
-
skippedDependencies: []
|
|
343
|
-
};
|
|
344
|
-
}
|
|
345
|
-
return {
|
|
346
|
-
mode: "resolved-lockfile",
|
|
347
|
-
source: "yarn-lock",
|
|
348
|
-
filePath: selected,
|
|
349
|
-
packages: loadFromYarnLock(selected),
|
|
350
|
-
notes: [
|
|
351
|
-
`Scanned resolved dependency versions from ${relativeOrName(projectRoot, selected)}.`,
|
|
352
|
-
"Dependency path reconstruction is limited for Yarn Classic lockfiles in this MVP."
|
|
353
|
-
],
|
|
354
|
-
warnings: ["No supported lockfile was found at the repo root, so a nested lockfile was used instead."],
|
|
355
|
-
skippedDependencies: []
|
|
356
|
-
};
|
|
357
|
-
}
|
|
358
|
-
const packageJsonPath = findNearestPackageJson(projectRoot, maxDepth);
|
|
359
|
-
if (packageJsonPath) {
|
|
360
|
-
const manifestResult = loadFromPackageJson(packageJsonPath, prodOnly);
|
|
361
|
-
const warnings = [
|
|
362
|
-
"No supported lockfile was found, so the scanner fell back to package.json.",
|
|
363
|
-
"Manifest fallback can only check direct dependencies pinned to exact versions."
|
|
364
|
-
];
|
|
365
|
-
const npmrcPath = path.join(path.dirname(packageJsonPath), ".npmrc");
|
|
366
|
-
if (fs.existsSync(npmrcPath)) {
|
|
367
|
-
const npmrc = safeReadText(npmrcPath);
|
|
368
|
-
if (/^\s*package-lock\s*=\s*false\s*$/m.test(npmrc)) {
|
|
369
|
-
warnings.push("This repo disables package-lock generation in .npmrc. For npm projects, try: npm install --package-lock-only --ignore-scripts --package-lock=true");
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
return {
|
|
373
|
-
mode: "manifest-fallback",
|
|
374
|
-
source: "package-json",
|
|
375
|
-
filePath: packageJsonPath,
|
|
376
|
-
packages: manifestResult.packages,
|
|
377
|
-
notes: [
|
|
378
|
-
`Scanned direct dependencies from ${relativeOrName(projectRoot, packageJsonPath)}.`,
|
|
379
|
-
"Manifest fallback does not resolve transitive dependencies unless they are pinned and present in a lockfile."
|
|
380
|
-
],
|
|
381
|
-
warnings,
|
|
382
|
-
skippedDependencies: manifestResult.skippedDependencies
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
return {
|
|
386
|
-
mode: "manifest-fallback",
|
|
387
|
-
source: "unknown",
|
|
388
|
-
filePath: null,
|
|
389
|
-
packages: [],
|
|
390
|
-
notes: [],
|
|
391
|
-
warnings: [],
|
|
392
|
-
skippedDependencies: []
|
|
393
|
-
};
|
|
394
|
-
}
|
|
395
|
-
function buildNoPackagesMessage(projectRoot) {
|
|
396
|
-
return [
|
|
397
|
-
"No scannable packages were found.",
|
|
398
|
-
"Supported inputs: package-lock.json, pnpm-lock.yaml, yarn.lock, or package.json with exact pinned versions.",
|
|
399
|
-
`Searched under: ${projectRoot}`
|
|
400
|
-
].join(" ");
|
|
401
|
-
}
|
|
402
|
-
function chooseBestLockfile(candidates) {
|
|
403
|
-
return [...candidates].sort((a, b) => {
|
|
404
|
-
const aDepth = a.split(path.sep).length;
|
|
405
|
-
const bDepth = b.split(path.sep).length;
|
|
406
|
-
if (aDepth !== bDepth)
|
|
407
|
-
return aDepth - bDepth;
|
|
408
|
-
const score = (file) => {
|
|
409
|
-
const name = path.basename(file);
|
|
410
|
-
if (name === "package-lock.json")
|
|
411
|
-
return 0;
|
|
412
|
-
if (name === "pnpm-lock.yaml")
|
|
413
|
-
return 1;
|
|
414
|
-
if (name === "yarn.lock")
|
|
415
|
-
return 2;
|
|
416
|
-
return 3;
|
|
417
|
-
};
|
|
418
|
-
return score(a) - score(b);
|
|
419
|
-
})[0];
|
|
420
|
-
}
|
|
421
|
-
function findNearestPackageJson(projectRoot, maxDepth) {
|
|
422
|
-
const rootCandidate = path.join(projectRoot, "package.json");
|
|
423
|
-
if (fs.existsSync(rootCandidate))
|
|
424
|
-
return rootCandidate;
|
|
425
|
-
const found = findFiles(projectRoot, ["package.json"], maxDepth);
|
|
426
|
-
return found[0] ?? null;
|
|
427
|
-
}
|
|
428
|
-
function findFiles(rootDir, names, maxDepth) {
|
|
429
|
-
const results = [];
|
|
430
|
-
const excluded = new Set([".git", "node_modules", "dist", "build", "coverage", ".next", ".turbo", ".angular", ".nx"]);
|
|
431
|
-
function walk(currentDir, depth) {
|
|
432
|
-
if (depth > maxDepth)
|
|
433
|
-
return;
|
|
434
|
-
let entries = [];
|
|
435
|
-
try {
|
|
436
|
-
entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
437
|
-
}
|
|
438
|
-
catch (_error) {
|
|
439
|
-
return;
|
|
440
|
-
}
|
|
441
|
-
for (const entry of entries) {
|
|
442
|
-
const fullPath = path.join(currentDir, entry.name);
|
|
443
|
-
if (entry.isFile() && names.includes(entry.name)) {
|
|
444
|
-
results.push(fullPath);
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
for (const entry of entries) {
|
|
448
|
-
if (!entry.isDirectory())
|
|
449
|
-
continue;
|
|
450
|
-
if (excluded.has(entry.name))
|
|
451
|
-
continue;
|
|
452
|
-
walk(path.join(currentDir, entry.name), depth + 1);
|
|
453
|
-
}
|
|
454
|
-
}
|
|
455
|
-
walk(rootDir, 0);
|
|
456
|
-
return results.sort((a, b) => {
|
|
457
|
-
const aDepth = a.split(path.sep).length;
|
|
458
|
-
const bDepth = b.split(path.sep).length;
|
|
459
|
-
return aDepth - bDepth || a.localeCompare(b);
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
function safeReadText(filePath) {
|
|
463
|
-
try {
|
|
464
|
-
return fs.readFileSync(filePath, "utf8");
|
|
465
|
-
}
|
|
466
|
-
catch (_error) {
|
|
467
|
-
return "";
|
|
468
|
-
}
|
|
469
|
-
}
|
|
470
|
-
function relativeOrName(rootDir, filePath) {
|
|
471
|
-
const relative = path.relative(rootDir, filePath);
|
|
472
|
-
return relative || path.basename(filePath);
|
|
473
|
-
}
|
|
474
|
-
function loadFromPackageJson(filePath, prodOnly) {
|
|
475
|
-
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
476
|
-
const map = new Map();
|
|
477
|
-
const skipped = [];
|
|
478
|
-
const sections = [
|
|
479
|
-
{ name: "dependencies", deps: raw.dependencies, dev: false },
|
|
480
|
-
{ name: "optionalDependencies", deps: raw.optionalDependencies, dev: false }
|
|
481
|
-
];
|
|
482
|
-
if (!prodOnly) {
|
|
483
|
-
sections.push({ name: "devDependencies", deps: raw.devDependencies, dev: true });
|
|
484
|
-
}
|
|
485
|
-
for (const section of sections) {
|
|
486
|
-
if (!section.deps || typeof section.deps !== "object")
|
|
487
|
-
continue;
|
|
488
|
-
for (const [name, spec] of Object.entries(section.deps)) {
|
|
489
|
-
const exactVersion = parseExactManifestVersion(String(spec));
|
|
490
|
-
if (!exactVersion) {
|
|
491
|
-
skipped.push(`${section.name}:${name}@${spec}`);
|
|
492
|
-
continue;
|
|
493
|
-
}
|
|
494
|
-
upsertPackage(map, {
|
|
495
|
-
name,
|
|
496
|
-
version: exactVersion,
|
|
497
|
-
ecosystem: "npm",
|
|
498
|
-
dev: section.dev,
|
|
499
|
-
paths: [["project", name]]
|
|
500
|
-
});
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
return {
|
|
504
|
-
packages: [...map.values()],
|
|
505
|
-
skippedDependencies: skipped.slice(0, 50)
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
function parseExactManifestVersion(spec) {
|
|
509
|
-
const cleaned = spec.trim().replace(/^npm:/, "");
|
|
510
|
-
if (looksLikeVersion(cleaned))
|
|
511
|
-
return cleaned;
|
|
512
|
-
return null;
|
|
513
|
-
}
|
|
514
|
-
function loadFromPackageLock(filePath, prodOnly) {
|
|
515
|
-
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
516
|
-
const map = new Map();
|
|
517
|
-
if (raw.packages && typeof raw.packages === "object") {
|
|
518
|
-
for (const [pkgPath, meta] of Object.entries(raw.packages)) {
|
|
519
|
-
if (!pkgPath || pkgPath === "")
|
|
520
|
-
continue;
|
|
521
|
-
if (!pkgPath.includes("node_modules/"))
|
|
522
|
-
continue;
|
|
523
|
-
const name = pkgPath.slice(pkgPath.lastIndexOf("node_modules/") + "node_modules/".length);
|
|
524
|
-
const version = meta?.version;
|
|
525
|
-
const dev = !!meta?.dev;
|
|
526
|
-
if (!name || !version)
|
|
527
|
-
continue;
|
|
528
|
-
if (prodOnly && dev)
|
|
529
|
-
continue;
|
|
530
|
-
const pathParts = normalizeNodeModulesPath(pkgPath);
|
|
531
|
-
upsertPackage(map, { name, version, ecosystem: "npm", dev, paths: [pathParts] });
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
if (map.size === 0 && raw.dependencies && typeof raw.dependencies === "object") {
|
|
535
|
-
walkLegacyDeps(raw.dependencies, map, prodOnly, ["project"]);
|
|
536
|
-
}
|
|
537
|
-
return [...map.values()];
|
|
538
|
-
}
|
|
539
|
-
function walkLegacyDeps(deps, map, prodOnly, currentPath) {
|
|
540
|
-
for (const [name, meta] of Object.entries(deps)) {
|
|
541
|
-
const version = meta?.version;
|
|
542
|
-
const dev = !!meta?.dev;
|
|
543
|
-
const nextPath = [...currentPath, name];
|
|
544
|
-
if (name && version && !(prodOnly && dev)) {
|
|
545
|
-
upsertPackage(map, { name, version, ecosystem: "npm", dev, paths: [nextPath] });
|
|
546
|
-
}
|
|
547
|
-
if (meta?.dependencies) {
|
|
548
|
-
walkLegacyDeps(meta.dependencies, map, prodOnly, nextPath);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
function loadFromYarnLock(filePath) {
|
|
553
|
-
const content = fs.readFileSync(filePath, "utf8");
|
|
554
|
-
const parsed = parseYarnLock(content);
|
|
555
|
-
if (parsed.type !== "success" || !parsed.object) {
|
|
556
|
-
throw new Error("Could not parse yarn.lock");
|
|
557
|
-
}
|
|
558
|
-
const map = new Map();
|
|
559
|
-
for (const [selector, meta] of Object.entries(parsed.object)) {
|
|
560
|
-
const version = meta?.version;
|
|
561
|
-
if (!version)
|
|
562
|
-
continue;
|
|
563
|
-
const firstSelector = String(selector).split(",")[0].trim();
|
|
564
|
-
const atIndex = firstSelector.lastIndexOf("@");
|
|
565
|
-
if (atIndex <= 0)
|
|
566
|
-
continue;
|
|
567
|
-
const name = firstSelector.slice(0, atIndex);
|
|
568
|
-
if (!name || !version)
|
|
569
|
-
continue;
|
|
570
|
-
upsertPackage(map, { name, version, ecosystem: "npm", paths: [["project", name]] });
|
|
571
|
-
}
|
|
572
|
-
return [...map.values()];
|
|
573
|
-
}
|
|
574
|
-
function loadFromPnpmLock(filePath, prodOnly) {
|
|
575
|
-
const content = fs.readFileSync(filePath, "utf8");
|
|
576
|
-
const parsed = YAML.parse(content);
|
|
577
|
-
const packagesSection = parsed?.packages ?? {};
|
|
578
|
-
const importers = parsed?.importers ?? {};
|
|
579
|
-
const graph = new Map();
|
|
580
|
-
const map = new Map();
|
|
581
|
-
for (const [key, meta] of Object.entries(packagesSection)) {
|
|
582
|
-
const ref = parsePnpmPackageKey(String(key));
|
|
583
|
-
if (!ref)
|
|
584
|
-
continue;
|
|
585
|
-
const depKeys = new Set();
|
|
586
|
-
for (const depMap of [meta?.dependencies, meta?.optionalDependencies]) {
|
|
587
|
-
if (!depMap || typeof depMap !== "object")
|
|
588
|
-
continue;
|
|
589
|
-
for (const [depName, depRef] of Object.entries(depMap)) {
|
|
590
|
-
const resolved = normalizePnpmDepRef(String(depName), depRef);
|
|
591
|
-
if (resolved)
|
|
592
|
-
depKeys.add(resolved);
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
graph.set(ref.key, [...depKeys]);
|
|
596
|
-
const dev = !!meta?.dev;
|
|
597
|
-
if (prodOnly && dev)
|
|
598
|
-
continue;
|
|
599
|
-
upsertPackage(map, { name: ref.name, version: ref.version, ecosystem: "npm", dev, paths: [] });
|
|
600
|
-
}
|
|
601
|
-
const rootDeps = [];
|
|
602
|
-
for (const importer of Object.values(importers)) {
|
|
603
|
-
for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
|
|
604
|
-
if (prodOnly && depSectionName == "devDependencies")
|
|
605
|
-
continue;
|
|
606
|
-
const depSection = importer?.[depSectionName];
|
|
607
|
-
if (!depSection || typeof depSection !== "object")
|
|
608
|
-
continue;
|
|
609
|
-
for (const [depName, depRef] of Object.entries(depSection)) {
|
|
610
|
-
const resolved = normalizePnpmDepRef(String(depName), depRef);
|
|
611
|
-
if (resolved) {
|
|
612
|
-
rootDeps.push(resolved);
|
|
613
|
-
}
|
|
614
|
-
else {
|
|
615
|
-
const fallbackVersion = normalizeRawVersion(depRef);
|
|
616
|
-
if (fallbackVersion) {
|
|
617
|
-
upsertPackage(map, {
|
|
618
|
-
name: String(depName),
|
|
619
|
-
version: fallbackVersion,
|
|
620
|
-
ecosystem: "npm",
|
|
621
|
-
paths: [["project", String(depName)]]
|
|
622
|
-
});
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
const queue = rootDeps.map(dep => ({ key: dep, path: ["project"] }));
|
|
629
|
-
const seenPaths = new Set();
|
|
630
|
-
while (queue.length > 0) {
|
|
631
|
-
const current = queue.shift();
|
|
632
|
-
const ref = parsePnpmPackageKey(current.key);
|
|
633
|
-
if (!ref)
|
|
634
|
-
continue;
|
|
635
|
-
const nextPath = [...current.path, ref.name];
|
|
636
|
-
const pathFingerprint = `${current.key}|${nextPath.join(">")}`;
|
|
637
|
-
if (seenPaths.has(pathFingerprint))
|
|
638
|
-
continue;
|
|
639
|
-
seenPaths.add(pathFingerprint);
|
|
640
|
-
const pkgKey = `${ref.name}@${ref.version}`;
|
|
641
|
-
const pkg = map.get(pkgKey);
|
|
642
|
-
if (pkg) {
|
|
643
|
-
pkg.paths = uniquePathArrays([...(pkg.paths ?? []), nextPath]).slice(0, 5);
|
|
644
|
-
}
|
|
645
|
-
const children = graph.get(current.key) ?? [];
|
|
646
|
-
for (const child of children) {
|
|
647
|
-
queue.push({ key: child, path: nextPath });
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
return [...map.values()];
|
|
651
|
-
}
|
|
652
|
-
function parsePnpmPackageKey(key) {
|
|
653
|
-
const cleaned = key.replace(/^\//, "").split("(")[0];
|
|
654
|
-
const match = cleaned.match(/^(@?[^/]+(?:\/[^/]+)?)\/([^/]+)$/);
|
|
655
|
-
if (!match)
|
|
656
|
-
return null;
|
|
657
|
-
const [, name, version] = match;
|
|
658
|
-
return { key, name, version };
|
|
659
|
-
}
|
|
660
|
-
function normalizePnpmDepRef(depName, depRef) {
|
|
661
|
-
if (typeof depRef === "string") {
|
|
662
|
-
const cleaned = depRef.replace(/^link:/, "").replace(/^workspace:/, "").split("(")[0];
|
|
663
|
-
if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
|
|
664
|
-
return null;
|
|
665
|
-
if (cleaned.startsWith("/"))
|
|
666
|
-
return cleaned;
|
|
667
|
-
if (cleaned.includes("/"))
|
|
668
|
-
return "/" + cleaned.replace(/^\//, "");
|
|
669
|
-
if (looksLikeVersion(cleaned))
|
|
670
|
-
return `/${depName}/${cleaned}`;
|
|
671
|
-
}
|
|
672
|
-
if (depRef && typeof depRef === "object") {
|
|
673
|
-
const version = depRef.version ?? depRef.specifier;
|
|
674
|
-
return normalizePnpmDepRef(depName, version);
|
|
675
|
-
}
|
|
676
|
-
return null;
|
|
677
|
-
}
|
|
678
|
-
function normalizeRawVersion(value) {
|
|
679
|
-
if (typeof value !== "string")
|
|
680
|
-
return null;
|
|
681
|
-
const cleaned = value.replace(/^workspace:/, "").replace(/^npm:/, "").trim();
|
|
682
|
-
if (!cleaned || cleaned.startsWith(".") || cleaned.startsWith(".."))
|
|
683
|
-
return null;
|
|
684
|
-
if (looksLikeVersion(cleaned))
|
|
685
|
-
return cleaned;
|
|
686
|
-
return null;
|
|
687
|
-
}
|
|
688
|
-
function looksLikeVersion(value) {
|
|
689
|
-
return /^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][^/]+)?$/.test(value);
|
|
690
|
-
}
|
|
691
|
-
function normalizeNodeModulesPath(pkgPath) {
|
|
692
|
-
const parts = pkgPath.split("/").filter(Boolean);
|
|
693
|
-
const names = ["project"];
|
|
694
|
-
for (let i = 0; i < parts.length; i++) {
|
|
695
|
-
if (parts[i] !== "node_modules")
|
|
696
|
-
continue;
|
|
697
|
-
const next = parts[i + 1];
|
|
698
|
-
const scopedNext = parts[i + 2];
|
|
699
|
-
if (!next)
|
|
700
|
-
continue;
|
|
701
|
-
if (next.startsWith("@") && scopedNext) {
|
|
702
|
-
names.push(`${next}/${scopedNext}`);
|
|
703
|
-
i += 2;
|
|
704
|
-
}
|
|
705
|
-
else {
|
|
706
|
-
names.push(next);
|
|
707
|
-
i += 1;
|
|
708
|
-
}
|
|
709
|
-
}
|
|
710
|
-
return names;
|
|
711
|
-
}
|
|
712
|
-
function upsertPackage(map, candidate) {
|
|
713
|
-
const key = `${candidate.name}@${candidate.version}`;
|
|
714
|
-
const existing = map.get(key);
|
|
715
|
-
if (!existing) {
|
|
716
|
-
map.set(key, { ...candidate, paths: uniquePathArrays(candidate.paths ?? []).slice(0, 5) });
|
|
717
|
-
return;
|
|
718
|
-
}
|
|
719
|
-
existing.dev = existing.dev && candidate.dev;
|
|
720
|
-
existing.paths = uniquePathArrays([...(existing.paths ?? []), ...(candidate.paths ?? [])]).slice(0, 5);
|
|
721
|
-
}
|
|
722
|
-
async function scanPackages(packages, batchSize, offline, cacheDirOverride) {
|
|
723
|
-
const spinner = createSpinner("Scanning dependencies against OSV...");
|
|
724
|
-
try {
|
|
725
|
-
const chunks = chunk(packages, batchSize);
|
|
726
|
-
const results = [];
|
|
727
|
-
if (!offline) {
|
|
728
|
-
for (let i = 0; i < chunks.length; i++) {
|
|
729
|
-
spinner.update(`Scanning OSV batch ${i + 1}/${chunks.length}...`);
|
|
730
|
-
const chunkItems = chunks[i];
|
|
731
|
-
const batchResponse = await osvQueryBatch(chunkItems);
|
|
732
|
-
const rows = batchResponse.results ?? [];
|
|
733
|
-
for (let j = 0; j < chunkItems.length; j++) {
|
|
734
|
-
const pkg = chunkItems[j];
|
|
735
|
-
const row = rows[j];
|
|
736
|
-
const vulnIds = (row?.vulns ?? []).map(v => v.id).filter(Boolean);
|
|
737
|
-
if (vulnIds.length > 0) {
|
|
738
|
-
results.push({ pkg, vulnIds });
|
|
739
|
-
}
|
|
740
|
-
}
|
|
741
|
-
}
|
|
742
|
-
spinner.succeed(`Queried OSV in ${chunks.length} batch${chunks.length === 1 ? "" : "es"}`);
|
|
743
|
-
}
|
|
744
|
-
else {
|
|
745
|
-
spinner.succeed("Offline mode enabled; package matching was skipped");
|
|
746
|
-
}
|
|
747
|
-
const cache = loadCache(cacheDirOverride);
|
|
748
|
-
const idSet = new Set(results.flatMap(r => r.vulnIds));
|
|
749
|
-
const vulnMap = new Map();
|
|
750
|
-
if (idSet.size > 0 && !offline) {
|
|
751
|
-
const ids = [...idSet];
|
|
752
|
-
const detailSpinner = createSpinner("Fetching vulnerability details...");
|
|
753
|
-
try {
|
|
754
|
-
for (let i = 0; i < ids.length; i++) {
|
|
755
|
-
const id = ids[i];
|
|
756
|
-
detailSpinner.update(`Fetching vulnerability details ${i + 1}/${ids.length}...`);
|
|
757
|
-
const cached = cache.entries[id];
|
|
758
|
-
if (cached) {
|
|
759
|
-
vulnMap.set(id, cached);
|
|
760
|
-
continue;
|
|
761
|
-
}
|
|
762
|
-
try {
|
|
763
|
-
const detail = await osvGetVuln(id);
|
|
764
|
-
vulnMap.set(id, detail);
|
|
765
|
-
cache.entries[id] = detail;
|
|
766
|
-
}
|
|
767
|
-
catch (_error) {
|
|
768
|
-
cache.entries[id] = null;
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
detailSpinner.succeed(`Loaded ${ids.length} vulnerability detail record${ids.length === 1 ? "" : "s"}`);
|
|
772
|
-
}
|
|
773
|
-
catch (error) {
|
|
774
|
-
detailSpinner.fail("Failed while fetching vulnerability details");
|
|
775
|
-
throw error;
|
|
776
|
-
}
|
|
777
|
-
}
|
|
778
|
-
if (!offline && idSet.size > 0) {
|
|
779
|
-
saveCache(cache, cacheDirOverride);
|
|
780
|
-
}
|
|
781
|
-
return results.map(result => {
|
|
782
|
-
const vulnerabilities = result.vulnIds
|
|
783
|
-
.map(id => vulnMap.get(id))
|
|
784
|
-
.filter((v) => Boolean(v));
|
|
785
|
-
const severity = maxSeverity(vulnerabilities);
|
|
786
|
-
const cveAliases = unique(vulnerabilities.flatMap(v => (v.aliases ?? []).filter(a => a.startsWith("CVE-"))));
|
|
787
|
-
const dependencyPaths = result.pkg.paths ?? [];
|
|
788
|
-
const relationship = classifyRelationship(dependencyPaths);
|
|
789
|
-
const firstFixedVersion = findFirstFixedVersion(vulnerabilities);
|
|
790
|
-
return {
|
|
791
|
-
pkg: result.pkg,
|
|
792
|
-
vulnerabilities,
|
|
793
|
-
severity,
|
|
794
|
-
cveAliases,
|
|
795
|
-
dependencyPaths,
|
|
796
|
-
relationship,
|
|
797
|
-
firstFixedVersion
|
|
798
|
-
};
|
|
799
|
-
});
|
|
800
|
-
}
|
|
801
|
-
catch (error) {
|
|
802
|
-
spinner.fail("Scan failed");
|
|
803
|
-
throw error;
|
|
804
|
-
}
|
|
805
|
-
}
|
|
806
|
-
function classifyRelationship(paths) {
|
|
807
|
-
if (paths.length === 0)
|
|
808
|
-
return "unknown";
|
|
809
|
-
const shortest = Math.min(...paths.map(p => p.length));
|
|
810
|
-
if (shortest <= 2)
|
|
811
|
-
return "direct";
|
|
812
|
-
return "transitive";
|
|
813
|
-
}
|
|
814
|
-
function findFirstFixedVersion(vulns) {
|
|
815
|
-
const fixedVersions = [];
|
|
816
|
-
for (const vuln of vulns) {
|
|
817
|
-
for (const affected of vuln.affected ?? []) {
|
|
818
|
-
for (const range of affected.ranges ?? []) {
|
|
819
|
-
for (const event of range.events ?? []) {
|
|
820
|
-
const fixed = event.fixed;
|
|
821
|
-
if (fixed && looksLikeVersion(fixed)) {
|
|
822
|
-
fixedVersions.push(fixed);
|
|
823
|
-
}
|
|
824
|
-
}
|
|
825
|
-
}
|
|
826
|
-
}
|
|
827
|
-
}
|
|
828
|
-
if (fixedVersions.length === 0)
|
|
829
|
-
return null;
|
|
830
|
-
return fixedVersions.sort(compareVersions)[0];
|
|
831
|
-
}
|
|
832
|
-
function compareVersions(a, b) {
|
|
833
|
-
const pa = a.split(/[.+-]/).map(n => Number.isFinite(Number(n)) ? Number(n) : n);
|
|
834
|
-
const pb = b.split(/[.+-]/).map(n => Number.isFinite(Number(n)) ? Number(n) : n);
|
|
835
|
-
const len = Math.max(pa.length, pb.length);
|
|
836
|
-
for (let i = 0; i < len; i++) {
|
|
837
|
-
const av = pa[i] ?? 0;
|
|
838
|
-
const bv = pb[i] ?? 0;
|
|
839
|
-
if (typeof av === "number" && typeof bv === "number") {
|
|
840
|
-
if (av !== bv)
|
|
841
|
-
return av - bv;
|
|
842
|
-
}
|
|
843
|
-
else {
|
|
844
|
-
const as = String(av);
|
|
845
|
-
const bs = String(bv);
|
|
846
|
-
if (as !== bs)
|
|
847
|
-
return as.localeCompare(bs);
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
return 0;
|
|
851
|
-
}
|
|
852
|
-
function printCacheSummary(cacheDirOverride) {
|
|
853
|
-
if (options.json)
|
|
854
|
-
return;
|
|
855
|
-
const cache = loadCache(cacheDirOverride);
|
|
856
|
-
const advisoryCount = Object.entries(cache.entries).filter(([, value]) => Boolean(value)).length;
|
|
857
|
-
const negativeCount = Object.entries(cache.entries).filter(([, value]) => value === null).length;
|
|
858
|
-
logInfo(`Cache summary: ${advisoryCount} advisory record${advisoryCount === 1 ? "" : "s"} cached, ${negativeCount} negative entr${negativeCount === 1 ? "y" : "ies"}`);
|
|
859
|
-
}
|
|
860
|
-
function getCacheFilePath(cacheDirOverride) {
|
|
861
|
-
const baseDir = cacheDirOverride
|
|
862
|
-
? path.resolve(cacheDirOverride)
|
|
863
|
-
: path.join(os.homedir(), ".cache", "cve-lite");
|
|
864
|
-
fs.mkdirSync(baseDir, { recursive: true });
|
|
865
|
-
return path.join(baseDir, "osv-vulns.json");
|
|
866
|
-
}
|
|
867
|
-
function loadCache(cacheDirOverride) {
|
|
868
|
-
const filePath = getCacheFilePath(cacheDirOverride);
|
|
869
|
-
if (!fs.existsSync(filePath)) {
|
|
870
|
-
return { version: 1, createdAt: new Date().toISOString(), entries: {} };
|
|
871
|
-
}
|
|
872
|
-
try {
|
|
873
|
-
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
874
|
-
if (parsed.version === 1 && parsed.entries) {
|
|
875
|
-
return parsed;
|
|
876
|
-
}
|
|
877
|
-
}
|
|
878
|
-
catch (_error) {
|
|
879
|
-
// ignore corrupt cache
|
|
880
|
-
}
|
|
881
|
-
return { version: 1, createdAt: new Date().toISOString(), entries: {} };
|
|
882
|
-
}
|
|
883
|
-
function saveCache(cache, cacheDirOverride) {
|
|
884
|
-
const filePath = getCacheFilePath(cacheDirOverride);
|
|
885
|
-
cache.createdAt = new Date().toISOString();
|
|
886
|
-
fs.writeFileSync(filePath, JSON.stringify(cache, null, 2), "utf8");
|
|
887
|
-
}
|
|
888
|
-
async function osvQueryBatch(packages) {
|
|
889
|
-
const response = await fetch("https://api.osv.dev/v1/querybatch", {
|
|
890
|
-
method: "POST",
|
|
891
|
-
headers: { "content-type": "application/json" },
|
|
892
|
-
body: JSON.stringify({
|
|
893
|
-
queries: packages.map(pkg => ({
|
|
894
|
-
package: {
|
|
895
|
-
ecosystem: pkg.ecosystem,
|
|
896
|
-
name: pkg.name
|
|
897
|
-
},
|
|
898
|
-
version: pkg.version
|
|
899
|
-
}))
|
|
900
|
-
})
|
|
901
|
-
});
|
|
902
|
-
if (!response.ok) {
|
|
903
|
-
throw new Error(`OSV batch query failed: ${response.status} ${response.statusText}`);
|
|
904
|
-
}
|
|
905
|
-
return response.json();
|
|
906
|
-
}
|
|
907
|
-
async function osvGetVuln(id) {
|
|
908
|
-
const response = await fetch(`https://api.osv.dev/v1/vulns/${encodeURIComponent(id)}`);
|
|
909
|
-
if (!response.ok) {
|
|
910
|
-
throw new Error(`OSV vuln fetch failed for ${id}`);
|
|
911
|
-
}
|
|
912
|
-
return response.json();
|
|
913
|
-
}
|
|
914
|
-
function maxSeverity(vulns) {
|
|
915
|
-
let current = "none";
|
|
916
|
-
for (const vuln of vulns) {
|
|
917
|
-
const sev = inferSeverity(vuln);
|
|
918
|
-
if (severityOrder[sev] > severityOrder[current]) {
|
|
919
|
-
current = sev;
|
|
920
|
-
}
|
|
921
|
-
}
|
|
922
|
-
return current;
|
|
923
|
-
}
|
|
924
|
-
function inferSeverity(vuln) {
|
|
925
|
-
const rawScores = vuln.severity ?? [];
|
|
926
|
-
for (const item of rawScores) {
|
|
927
|
-
const score = item?.score ?? "";
|
|
928
|
-
const label = severityFromScore(score);
|
|
929
|
-
if (label !== "unknown")
|
|
930
|
-
return label;
|
|
931
|
-
}
|
|
932
|
-
const db = vuln.database_specific;
|
|
933
|
-
const dbSeverity = String(db?.severity ?? "").toLowerCase();
|
|
934
|
-
if (["critical", "high", "medium", "low"].includes(dbSeverity)) {
|
|
935
|
-
return dbSeverity;
|
|
936
|
-
}
|
|
937
|
-
return "unknown";
|
|
938
|
-
}
|
|
939
|
-
function severityFromScore(score) {
|
|
940
|
-
const match = String(score).match(/([0-9]+(?:\.[0-9]+)?)/);
|
|
941
|
-
if (!match)
|
|
942
|
-
return "unknown";
|
|
943
|
-
const value = Number(match[1]);
|
|
944
|
-
if (Number.isNaN(value))
|
|
945
|
-
return "unknown";
|
|
946
|
-
if (value >= 9.0)
|
|
947
|
-
return "critical";
|
|
948
|
-
if (value >= 7.0)
|
|
949
|
-
return "high";
|
|
950
|
-
if (value >= 4.0)
|
|
951
|
-
return "medium";
|
|
952
|
-
if (value > 0)
|
|
953
|
-
return "low";
|
|
954
|
-
return "none";
|
|
955
|
-
}
|
|
956
|
-
function formatSeverityLabel(severity) {
|
|
957
|
-
if (severity === "critical")
|
|
958
|
-
return chalk.redBright(severity);
|
|
959
|
-
if (severity === "high")
|
|
960
|
-
return chalk.red(severity);
|
|
961
|
-
if (severity === "medium")
|
|
962
|
-
return chalk.yellow(severity);
|
|
963
|
-
if (severity === "low")
|
|
964
|
-
return chalk.blueBright(severity);
|
|
965
|
-
if (severity === "unknown")
|
|
966
|
-
return chalk.magenta(severity);
|
|
967
|
-
return severity;
|
|
968
|
-
}
|
|
969
|
-
function formatRelationshipLabel(value) {
|
|
970
|
-
if (value === "direct")
|
|
971
|
-
return chalk.green(value);
|
|
972
|
-
if (value === "transitive")
|
|
973
|
-
return chalk.yellow(value);
|
|
974
|
-
return chalk.gray(value);
|
|
975
|
-
}
|
|
976
|
-
function stripAnsi(text) {
|
|
977
|
-
return text.replace(/\x1b\[[0-9;]*m/g, "");
|
|
978
|
-
}
|
|
979
|
-
function summarizeRisk(finding) {
|
|
980
|
-
if (finding.severity === "critical" && finding.relationship === "direct") {
|
|
981
|
-
return "Critical direct dependency. Prioritize this first because the project controls it directly.";
|
|
982
|
-
}
|
|
983
|
-
if (finding.severity === "high" && finding.relationship === "direct") {
|
|
984
|
-
return "High-severity direct dependency. A direct upgrade is likely the fastest path.";
|
|
985
|
-
}
|
|
986
|
-
if (finding.relationship === "transitive" && finding.firstFixedVersion) {
|
|
987
|
-
return `Transitive issue. Look for a parent dependency upgrade that pulls in ${finding.firstFixedVersion}+`;
|
|
988
|
-
}
|
|
989
|
-
if (finding.relationship === "transitive") {
|
|
990
|
-
return "Transitive issue. Review the parent path and check whether an upstream package can be upgraded.";
|
|
991
|
-
}
|
|
992
|
-
if (finding.firstFixedVersion) {
|
|
993
|
-
return `A fixed-version hint exists. Aim for at least ${finding.firstFixedVersion}.`;
|
|
994
|
-
}
|
|
995
|
-
return "Review this finding and inspect the dependency path for the safest upgrade path.";
|
|
996
|
-
}
|
|
997
|
-
function summarizeNextAction(finding) {
|
|
998
|
-
if (finding.relationship === "direct" && finding.firstFixedVersion) {
|
|
999
|
-
return `Upgrade ${finding.pkg.name} toward ${finding.firstFixedVersion}.`;
|
|
1000
|
-
}
|
|
1001
|
-
if (finding.relationship === "direct") {
|
|
1002
|
-
return `Review and upgrade ${finding.pkg.name} directly in this project.`;
|
|
1003
|
-
}
|
|
1004
|
-
if (finding.firstFixedVersion) {
|
|
1005
|
-
return `Upgrade the parent dependency chain so it resolves ${finding.pkg.name} to ${finding.firstFixedVersion}+`;
|
|
1006
|
-
}
|
|
1007
|
-
return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
|
|
1008
|
-
}
|
|
1009
|
-
function printPriorityFixes(findings) {
|
|
1010
|
-
if (findings.length === 0)
|
|
1011
|
-
return;
|
|
1012
|
-
const scored = [...findings].sort((a, b) => {
|
|
1013
|
-
const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
|
|
1014
|
-
if (sevDelta !== 0)
|
|
1015
|
-
return sevDelta;
|
|
1016
|
-
const relScore = (f) => f.relationship === "direct" ? 2 : f.relationship === "transitive" ? 1 : 0;
|
|
1017
|
-
const relDelta = relScore(b) - relScore(a);
|
|
1018
|
-
if (relDelta !== 0)
|
|
1019
|
-
return relDelta;
|
|
1020
|
-
const fixedDelta = Number(Boolean(b.firstFixedVersion)) - Number(Boolean(a.firstFixedVersion));
|
|
1021
|
-
if (fixedDelta !== 0)
|
|
1022
|
-
return fixedDelta;
|
|
1023
|
-
return a.pkg.name.localeCompare(b.pkg.name);
|
|
1024
|
-
});
|
|
1025
|
-
const top = scored.slice(0, 5);
|
|
1026
|
-
console.log("");
|
|
1027
|
-
console.log(chalk.bold.magenta("Top priority fixes"));
|
|
1028
|
-
for (const finding of top) {
|
|
1029
|
-
console.log(`- ${chalk.whiteBright(finding.pkg.name)}@${chalk.white(finding.pkg.version)} (${formatSeverityLabel(finding.severity)}, ${formatRelationshipLabel(finding.relationship)})`);
|
|
1030
|
-
console.log(` Risk: ${summarizeRisk(finding)}`);
|
|
1031
|
-
const parent = getPrimaryParent(finding);
|
|
1032
|
-
if (parent)
|
|
1033
|
-
console.log(` Parent: ${parent}`);
|
|
1034
|
-
console.log(` Next: ${summarizeNextAction(finding)}`);
|
|
1035
|
-
}
|
|
1036
|
-
}
|
|
1037
|
-
function printSummary(findings, packageCount, scanInput) {
|
|
1038
|
-
if (findings.length === 0) {
|
|
1039
|
-
if (scanInput.mode === "manifest-fallback") {
|
|
1040
|
-
console.log(chalk.greenBright(`✓ No known OSV matches found for manifest fallback packages (${packageCount} exact direct dependencies checked)`));
|
|
1041
|
-
}
|
|
1042
|
-
else {
|
|
1043
|
-
console.log(chalk.greenBright(`✓ No known OSV vulnerability matches found in parsed lockfile packages (${packageCount} checked)`));
|
|
1044
|
-
}
|
|
1045
|
-
return;
|
|
1046
|
-
}
|
|
1047
|
-
const counts = {
|
|
1048
|
-
critical: findings.filter(f => f.severity === "critical").length,
|
|
1049
|
-
high: findings.filter(f => f.severity === "high").length,
|
|
1050
|
-
medium: findings.filter(f => f.severity === "medium").length,
|
|
1051
|
-
low: findings.filter(f => f.severity === "low").length,
|
|
1052
|
-
unknown: findings.filter(f => f.severity === "unknown").length
|
|
1053
|
-
};
|
|
1054
|
-
console.log(chalk.redBright(`✗ Found ${findings.length} package(s) with known OSV matches from ${scanInput.source}`));
|
|
1055
|
-
console.log(` ${formatSeverityLabel("critical")}: ${counts.critical} ${formatSeverityLabel("high")}: ${counts.high} ${formatSeverityLabel("medium")}: ${counts.medium} ${formatSeverityLabel("low")}: ${counts.low} ${formatSeverityLabel("unknown")}: ${counts.unknown}`);
|
|
1056
|
-
}
|
|
1057
|
-
function printActionSummary(findings) {
|
|
1058
|
-
if (findings.length === 0)
|
|
1059
|
-
return;
|
|
1060
|
-
const direct = findings.filter(f => f.relationship === "direct").length;
|
|
1061
|
-
const transitive = findings.filter(f => f.relationship === "transitive").length;
|
|
1062
|
-
const unknown = findings.filter(f => f.relationship === "unknown").length;
|
|
1063
|
-
const uniqueAdvisories = new Set(findings.flatMap(f => f.vulnerabilities.map(v => v.id))).size;
|
|
1064
|
-
const fixable = findings.filter(f => Boolean(f.firstFixedVersion)).length;
|
|
1065
|
-
console.log("");
|
|
1066
|
-
console.log(chalk.bold.cyan("Quick take"));
|
|
1067
|
-
console.log(`- ${chalk.green(String(direct))} vulnerable package${direct === 1 ? "" : "s"} look directly fixable in this project.`);
|
|
1068
|
-
console.log(`- ${chalk.yellow(String(transitive))} issue${transitive === 1 ? "" : "s"} come through other dependencies.`);
|
|
1069
|
-
if (unknown > 0) {
|
|
1070
|
-
console.log(`- ${chalk.magenta(String(unknown))} package${unknown === 1 ? "" : "s"} could not be clearly classified as direct or transitive.`);
|
|
1071
|
-
}
|
|
1072
|
-
console.log(`- ${chalk.blueBright(String(uniqueAdvisories))} unique advisories matched overall.`);
|
|
1073
|
-
console.log(`- ${chalk.blue(String(fixable))} package${fixable === 1 ? "" : "s"} include a fixed-version hint from OSV.`);
|
|
1074
|
-
}
|
|
1075
|
-
function getPrimaryParent(finding) {
|
|
1076
|
-
const firstPath = finding.dependencyPaths?.[0];
|
|
1077
|
-
if (!firstPath || firstPath.length < 3)
|
|
1078
|
-
return null;
|
|
1079
|
-
return firstPath[1] ?? null;
|
|
1080
|
-
}
|
|
1081
|
-
function getRecommendedAction(finding) {
|
|
1082
|
-
if (finding.relationship === "direct" && finding.firstFixedVersion) {
|
|
1083
|
-
return `Upgrade ${finding.pkg.name} to ${finding.firstFixedVersion}+ in this project.`;
|
|
1084
|
-
}
|
|
1085
|
-
if (finding.relationship === "direct") {
|
|
1086
|
-
return `Review and upgrade ${finding.pkg.name} directly in this project.`;
|
|
1087
|
-
}
|
|
1088
|
-
const parent = getPrimaryParent(finding);
|
|
1089
|
-
if (parent && finding.firstFixedVersion) {
|
|
1090
|
-
return `Review ${parent}; aim for a version that resolves ${finding.pkg.name} to ${finding.firstFixedVersion}+`;
|
|
1091
|
-
}
|
|
1092
|
-
if (parent) {
|
|
1093
|
-
return `Review ${parent}; it currently pulls in vulnerable ${finding.pkg.name}.`;
|
|
1094
|
-
}
|
|
1095
|
-
if (finding.firstFixedVersion) {
|
|
1096
|
-
return `Upgrade the parent dependency chain so ${finding.pkg.name} resolves to ${finding.firstFixedVersion}+`;
|
|
1097
|
-
}
|
|
1098
|
-
return `Inspect the dependency path for ${finding.pkg.name} and choose the safest upgrade path.`;
|
|
1099
|
-
}
|
|
1100
|
-
function printFixPlan(findings) {
|
|
1101
|
-
if (findings.length === 0)
|
|
1102
|
-
return;
|
|
1103
|
-
const directUrgent = findings.filter(f => f.relationship === "direct" && (f.severity === "critical" || f.severity === "high"));
|
|
1104
|
-
const transitiveUrgent = findings.filter(f => f.relationship === "transitive" && (f.severity === "critical" || f.severity === "high"));
|
|
1105
|
-
const directMedium = findings.filter(f => f.relationship === "direct" && f.severity === "medium");
|
|
1106
|
-
console.log("");
|
|
1107
|
-
console.log(chalk.bold.green("Suggested fix plan"));
|
|
1108
|
-
if (directUrgent.length > 0) {
|
|
1109
|
-
console.log(chalk.green("1) Upgrade these direct critical/high dependencies first:"));
|
|
1110
|
-
for (const finding of directUrgent.slice(0, 5)) {
|
|
1111
|
-
console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
if (transitiveUrgent.length > 0) {
|
|
1115
|
-
console.log(chalk.yellow("2) Review these urgent transitive issues next:"));
|
|
1116
|
-
for (const finding of transitiveUrgent.slice(0, 5)) {
|
|
1117
|
-
console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
|
|
1118
|
-
}
|
|
1119
|
-
}
|
|
1120
|
-
if (directMedium.length > 0) {
|
|
1121
|
-
console.log(chalk.blue("3) Clean up these medium direct dependencies after the urgent fixes:"));
|
|
1122
|
-
for (const finding of directMedium.slice(0, 5)) {
|
|
1123
|
-
console.log(` - ${finding.pkg.name}@${finding.pkg.version}: ${getRecommendedAction(finding)}`);
|
|
1124
|
-
}
|
|
1125
|
-
}
|
|
1126
|
-
const grouped = new Map();
|
|
1127
|
-
for (const finding of findings) {
|
|
1128
|
-
const existing = grouped.get(finding.pkg.name) ?? [];
|
|
1129
|
-
existing.push(finding);
|
|
1130
|
-
grouped.set(finding.pkg.name, existing);
|
|
1131
|
-
}
|
|
1132
|
-
const dupes = [...grouped.entries()]
|
|
1133
|
-
.filter(([, items]) => items.length > 1)
|
|
1134
|
-
.sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
|
|
1135
|
-
.slice(0, 5);
|
|
1136
|
-
if (dupes.length > 0) {
|
|
1137
|
-
console.log(chalk.magenta("4) Consolidate duplicated vulnerable packages where possible:"));
|
|
1138
|
-
for (const [name, items] of dupes) {
|
|
1139
|
-
const versions = [...new Set(items.map(item => item.pkg.version))].sort().join(", ");
|
|
1140
|
-
console.log(` - ${name}: vulnerable versions present -> ${versions}`);
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1144
|
-
function printCoverage(notes) {
|
|
1145
|
-
if (notes.length === 0)
|
|
1146
|
-
return;
|
|
1147
|
-
console.log("");
|
|
1148
|
-
console.log(chalk.bold.blue("Coverage notes"));
|
|
1149
|
-
for (const note of notes) {
|
|
1150
|
-
console.log(`${chalk.blue("•")} ${note}`);
|
|
1151
|
-
}
|
|
1152
|
-
}
|
|
1153
|
-
function printSkippedDependencies(skipped) {
|
|
1154
|
-
console.log("");
|
|
1155
|
-
console.log(chalk.bold.yellow("Skipped manifest dependencies"));
|
|
1156
|
-
for (const item of skipped.slice(0, 10)) {
|
|
1157
|
-
console.log(`${chalk.yellow("•")} ${item}`);
|
|
1158
|
-
}
|
|
1159
|
-
if (skipped.length > 10) {
|
|
1160
|
-
console.log(`${chalk.yellow("•")} ...and ${skipped.length - 10} more`);
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
function buildCoverageNotes(scanInput, offline) {
|
|
1164
|
-
const notes = [
|
|
1165
|
-
"This MVP checks package versions against OSV advisories. It does not prove exploitability or runtime reachability.",
|
|
1166
|
-
"Installed node_modules contents are not verified in this scan.",
|
|
1167
|
-
"Container images, binaries, secrets, and IaC files are not scanned.",
|
|
1168
|
-
"Monorepo workspace boundaries are only partially modeled in this version."
|
|
1169
|
-
];
|
|
1170
|
-
if (scanInput.mode === "manifest-fallback") {
|
|
1171
|
-
notes.push("Manifest fallback is limited to direct dependencies pinned to exact versions. It does not resolve transitive dependencies from package.json alone.");
|
|
1172
|
-
}
|
|
1173
|
-
if (offline) {
|
|
1174
|
-
notes.push("Offline mode only uses cached vulnerability details.");
|
|
1175
|
-
}
|
|
1176
|
-
return notes;
|
|
1177
|
-
}
|
|
1178
|
-
function printGroupSummary(findings) {
|
|
1179
|
-
const direct = findings.filter(f => f.relationship === "direct");
|
|
1180
|
-
const transitive = findings.filter(f => f.relationship === "transitive");
|
|
1181
|
-
const unknown = findings.filter(f => f.relationship === "unknown");
|
|
1182
|
-
console.log("");
|
|
1183
|
-
console.log(chalk.bold.green("Where the issues are"));
|
|
1184
|
-
console.log(`- Direct dependencies: ${chalk.green(String(direct.length))}`);
|
|
1185
|
-
console.log(`- Transitive dependencies: ${chalk.yellow(String(transitive.length))}`);
|
|
1186
|
-
if (unknown.length > 0) {
|
|
1187
|
-
console.log(`- Unclear relationship: ${chalk.magenta(String(unknown.length))}`);
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
function printTable(findings, threshold) {
|
|
1191
|
-
const headers = ["Package", "Version", "Severity", "Type", "Fixed", "IDs"];
|
|
1192
|
-
const rawRows = findings.map(f => [
|
|
1193
|
-
f.pkg.name,
|
|
1194
|
-
f.pkg.version,
|
|
1195
|
-
f.severity,
|
|
1196
|
-
f.relationship,
|
|
1197
|
-
f.firstFixedVersion ?? "-",
|
|
1198
|
-
f.vulnerabilities.map(v => v.id).join(", ")
|
|
1199
|
-
]);
|
|
1200
|
-
const widths = headers.map((header, index) => Math.min(40, Math.max(header.length, ...rawRows.map(r => String(r[index]).length))));
|
|
1201
|
-
console.log("");
|
|
1202
|
-
if (threshold) {
|
|
1203
|
-
console.log(chalk.bold(`Showing ${threshold}+ findings in the main table. Use --all to show everything.`));
|
|
1204
|
-
}
|
|
1205
|
-
const line = (left, mid, right) => left + widths.map(w => "─".repeat(w + 2)).join(mid) + right;
|
|
1206
|
-
console.log(line("┌", "┬", "┐"));
|
|
1207
|
-
console.log(renderRow(headers, widths));
|
|
1208
|
-
console.log(line("├", "┼", "┤"));
|
|
1209
|
-
for (const row of rawRows) {
|
|
1210
|
-
const decorated = [
|
|
1211
|
-
row[0],
|
|
1212
|
-
row[1],
|
|
1213
|
-
formatSeverityLabel(String(row[2])),
|
|
1214
|
-
formatRelationshipLabel(String(row[3])),
|
|
1215
|
-
row[4],
|
|
1216
|
-
row[5]
|
|
1217
|
-
];
|
|
1218
|
-
console.log(renderRow(decorated, widths));
|
|
1219
|
-
}
|
|
1220
|
-
console.log(line("└", "┴", "┘"));
|
|
1221
|
-
console.log(chalk.gray("Tip: use --all to include low/unknown findings, or --min-severity high to focus only on urgent issues."));
|
|
1222
|
-
}
|
|
1223
|
-
function printPathHints(findings) {
|
|
1224
|
-
const withPaths = findings.filter(f => (f.dependencyPaths ?? []).length > 0);
|
|
1225
|
-
if (withPaths.length === 0)
|
|
1226
|
-
return;
|
|
1227
|
-
console.log("");
|
|
1228
|
-
console.log(chalk.bold.cyan("Dependency paths to inspect"));
|
|
1229
|
-
for (const finding of withPaths.slice(0, 10)) {
|
|
1230
|
-
const examples = finding.dependencyPaths.slice(0, 3).map(p => p.join(" -> "));
|
|
1231
|
-
console.log(`- ${finding.pkg.name}@${finding.pkg.version}`);
|
|
1232
|
-
for (const example of examples) {
|
|
1233
|
-
console.log(` ${chalk.gray(example)}`);
|
|
1234
|
-
}
|
|
1235
|
-
}
|
|
1236
|
-
}
|
|
1237
|
-
function renderRow(cells, widths) {
|
|
1238
|
-
const formatted = cells.map((cell, i) => {
|
|
1239
|
-
const truncated = truncate(cell, widths[i]);
|
|
1240
|
-
const visible = stripAnsi(truncated);
|
|
1241
|
-
return ` ${truncated}${" ".repeat(Math.max(0, widths[i] - visible.length))} `;
|
|
1242
|
-
});
|
|
1243
|
-
return "│" + formatted.join("│") + "│";
|
|
1244
|
-
}
|
|
1245
|
-
function truncate(value, width) {
|
|
1246
|
-
const plain = stripAnsi(value);
|
|
1247
|
-
if (plain.length <= width)
|
|
1248
|
-
return value;
|
|
1249
|
-
return plain.slice(0, Math.max(0, width - 1)) + "…";
|
|
1250
|
-
}
|
|
1251
|
-
function chunk(items, size) {
|
|
1252
|
-
const output = [];
|
|
1253
|
-
for (let i = 0; i < items.length; i += size) {
|
|
1254
|
-
output.push(items.slice(i, i + size));
|
|
1255
|
-
}
|
|
1256
|
-
return output;
|
|
1257
|
-
}
|
|
1258
|
-
function unique(items) {
|
|
1259
|
-
return [...new Set(items)];
|
|
1260
|
-
}
|
|
1261
|
-
function uniquePathArrays(paths) {
|
|
1262
|
-
const seen = new Set();
|
|
1263
|
-
const output = [];
|
|
1264
|
-
for (const item of paths) {
|
|
1265
|
-
const key = item.join(">");
|
|
1266
|
-
if (seen.has(key))
|
|
1267
|
-
continue;
|
|
1268
|
-
seen.add(key);
|
|
1269
|
-
output.push(item);
|
|
1270
|
-
}
|
|
1271
|
-
return output;
|
|
1272
|
-
}
|
|
1273
|
-
function normalizeSeverity(input) {
|
|
1274
|
-
const normalized = String(input || "").toLowerCase();
|
|
1275
|
-
if (["none", "low", "medium", "high", "critical", "unknown"].includes(normalized)) {
|
|
1276
|
-
return normalized;
|
|
1277
|
-
}
|
|
1278
|
-
return "critical";
|
|
1279
|
-
}
|
|
1280
|
-
function serializeFinding(finding) {
|
|
1281
|
-
return {
|
|
1282
|
-
package: finding.pkg.name,
|
|
1283
|
-
version: finding.pkg.version,
|
|
1284
|
-
severity: finding.severity,
|
|
1285
|
-
relationship: finding.relationship,
|
|
1286
|
-
firstFixedVersion: finding.firstFixedVersion,
|
|
1287
|
-
recommendedAction: getRecommendedAction(finding),
|
|
1288
|
-
primaryParent: getPrimaryParent(finding),
|
|
1289
|
-
cves: finding.cveAliases,
|
|
1290
|
-
dependencyPaths: finding.dependencyPaths,
|
|
1291
|
-
vulnerabilities: finding.vulnerabilities.map(v => ({
|
|
1292
|
-
id: v.id,
|
|
1293
|
-
aliases: v.aliases ?? [],
|
|
1294
|
-
summary: v.summary ?? "",
|
|
1295
|
-
severity: inferSeverity(v)
|
|
1296
|
-
}))
|
|
1297
|
-
};
|
|
1298
|
-
}
|
|
1299
|
-
function printFinalStatus(findings) {
|
|
1300
|
-
console.log("");
|
|
1301
|
-
if (findings.length === 0) {
|
|
1302
|
-
console.log(chalk.greenBright("Done. No known vulnerabilities found."));
|
|
1303
|
-
return;
|
|
1304
|
-
}
|
|
1305
|
-
const hasCriticalOrHigh = findings.some(f => f.severity === "critical" || f.severity === "high");
|
|
1306
|
-
if (hasCriticalOrHigh) {
|
|
1307
|
-
console.log(chalk.redBright("Done. Vulnerabilities found. Start with the priority fixes above."));
|
|
1308
|
-
}
|
|
1309
|
-
else {
|
|
1310
|
-
console.log(chalk.yellow("Done. Vulnerabilities found. Review the suggested fix plan above."));
|
|
1311
|
-
}
|
|
1312
|
-
}
|
|
1313
|
-
function logInfo(message) {
|
|
1314
|
-
if (!options.json)
|
|
1315
|
-
console.log(chalk.cyan(`• ${message}`));
|
|
1316
|
-
}
|
|
1317
|
-
function logWarn(message) {
|
|
1318
|
-
if (!options.json)
|
|
1319
|
-
console.log(chalk.yellow(`! ${message}`));
|
|
1320
|
-
}
|
|
1321
86
|
main().catch((error) => {
|
|
1322
87
|
console.error(chalk.red(`Error: ${error instanceof Error ? error.message : String(error)}`));
|
|
1323
88
|
process.exit(1);
|