cve-lite-cli 1.17.3 → 1.18.0
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 +2 -0
- package/dist/cli/args.js +6 -3
- package/dist/cli/help.js +2 -0
- package/dist/cli/validate.js +22 -0
- package/dist/constants.js +2 -0
- package/dist/index.js +25 -188
- package/dist/output/formatters.js +9 -2
- package/dist/output/html-reporter.js +7 -2
- package/dist/output/printers.js +8 -1
- package/dist/parsers/bun-lock.js +19 -0
- package/dist/parsers/package-lock.js +23 -0
- package/dist/parsers/pnpm-lock.js +20 -0
- package/dist/remediation/fix-commands.js +54 -12
- package/dist/remediation/npm-transitive-resolution.js +63 -0
- package/dist/scanner.js +52 -1
- package/dist/usage/scanner.js +3 -2
- package/dist/utils/network.js +47 -4
- package/dist/utils/package-json.js +124 -0
- package/dist/utils/severity.js +14 -0
- package/dist/utils/time.js +30 -0
- package/dist/utils/update-check.js +102 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -217,6 +217,8 @@ If you maintain an open-source JavaScript or TypeScript project and want CVE Lit
|
|
|
217
217
|
|
|
218
218
|
## Press
|
|
219
219
|
|
|
220
|
+
- **[As AI speeds coding, CVE Lite CLI keeps security deliberately AI-free](https://www.csoonline.com/article/4176701/as-ai-speeds-coding-cve-lite-cli-keeps-security-deliberately-ai-free.html)** — CSO Online (Shweta Sharma), May 2026
|
|
221
|
+
- **[AI Security Is Changing Fast — These 6 Open-Source Tools Prove It](https://medium.com/@techlatest.net/ai-security-is-changing-fast-these-6-open-source-tools-prove-it-5c5c9081cff7)** — Medium (TechLatest.Net), May 2026
|
|
220
222
|
- **[CVE Lite CLI: Open-source dependency vulnerability scanner](https://www.helpnetsecurity.com/2026/05/20/cve-lite-cli-open-source-dependency-vulnerability-scanner/)** — Help Net Security, May 2026
|
|
221
223
|
- **[Review of CVE Lite CLI](https://developmentcurated.com/testing-and-security/review-of-cve-lite-cli/)** — Development Curated (Sebastian Raiffen, IT Security Consultant), April 2026
|
|
222
224
|
|
package/dist/cli/args.js
CHANGED
|
@@ -24,8 +24,9 @@ export function parseArgs(argv) {
|
|
|
24
24
|
options.output = arg.slice("--output=".length);
|
|
25
25
|
continue;
|
|
26
26
|
}
|
|
27
|
-
if (arg.startsWith("-"))
|
|
27
|
+
if (arg.startsWith("-")) {
|
|
28
28
|
throw new Error(`Unknown option: ${arg}`);
|
|
29
|
+
}
|
|
29
30
|
throw new Error(`Unexpected argument: ${arg}`);
|
|
30
31
|
}
|
|
31
32
|
return { command: "advisories-sync", options };
|
|
@@ -37,8 +38,9 @@ export function parseArgs(argv) {
|
|
|
37
38
|
options.help = true;
|
|
38
39
|
continue;
|
|
39
40
|
}
|
|
40
|
-
if (arg.startsWith("-"))
|
|
41
|
+
if (arg.startsWith("-")) {
|
|
41
42
|
throw new Error(`Unknown option: ${arg}`);
|
|
43
|
+
}
|
|
42
44
|
throw new Error(`Unexpected argument: ${arg}`);
|
|
43
45
|
}
|
|
44
46
|
return { command: "install-skill", options };
|
|
@@ -182,8 +184,9 @@ export function parseArgs(argv) {
|
|
|
182
184
|
options.cdx = true;
|
|
183
185
|
continue;
|
|
184
186
|
}
|
|
185
|
-
if (arg.startsWith("-"))
|
|
187
|
+
if (arg.startsWith("-")) {
|
|
186
188
|
throw new Error(`Unknown option: ${arg}`);
|
|
189
|
+
}
|
|
187
190
|
if (!projectArg) {
|
|
188
191
|
projectArg = arg;
|
|
189
192
|
continue;
|
package/dist/cli/help.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { chalk } from "../utils/chalk.js";
|
|
2
2
|
import { getCliVersion } from "../utils/version-info.js";
|
|
3
|
+
import { checkForUpdate } from "../utils/update-check.js";
|
|
3
4
|
const CLI_VERSION = getCliVersion();
|
|
4
5
|
const CLI_BANNER = [
|
|
5
6
|
`${chalk.green(">_")} ${chalk.bold.whiteBright(`CVE Lite CLI (${CLI_VERSION})`)}`,
|
|
@@ -15,6 +16,7 @@ export function printBanner(options) {
|
|
|
15
16
|
return;
|
|
16
17
|
console.log(CLI_BANNER);
|
|
17
18
|
console.log("");
|
|
19
|
+
checkForUpdate(options);
|
|
18
20
|
}
|
|
19
21
|
export function printHelp() {
|
|
20
22
|
printBanner();
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export function validateOptions(options) {
|
|
2
|
+
if ((options.offline || options.offlineDb) && options.osvUrl) {
|
|
3
|
+
throw new Error("--offline/--offline-db cannot be used with --osv-url");
|
|
4
|
+
}
|
|
5
|
+
if (options.noCache && (options.offline || options.offlineDb)) {
|
|
6
|
+
throw new Error("--no-cache cannot be used with --offline or --offline-db");
|
|
7
|
+
}
|
|
8
|
+
if (options.osvUrl) {
|
|
9
|
+
try {
|
|
10
|
+
new URL(options.osvUrl);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (options.fix && options.json) {
|
|
17
|
+
throw new Error("--fix cannot be used with --json");
|
|
18
|
+
}
|
|
19
|
+
if (options.report && options.json) {
|
|
20
|
+
throw new Error("--report cannot be used with --json");
|
|
21
|
+
}
|
|
22
|
+
}
|
package/dist/constants.js
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,26 +1,29 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import fs from "node:fs";
|
|
4
3
|
import path from "node:path";
|
|
5
4
|
import process from "node:process";
|
|
6
5
|
import { parseArgs } from "./cli/args.js";
|
|
7
6
|
import { printBanner, printHelp } from "./cli/help.js";
|
|
7
|
+
import { validateOptions } from "./cli/validate.js";
|
|
8
8
|
import { loadPackages, buildNoPackagesMessage } from "./parsers/index.js";
|
|
9
9
|
import { scanPackages, buildCoverageNotes, createAdvisorySource } from "./scanner.js";
|
|
10
10
|
import { syncOsvAdvisories } from "./advisory/osv-sync.js";
|
|
11
11
|
import { normalizeSeverity } from "./osv/severity.js";
|
|
12
|
-
import { severityOrder } from "./constants.js";
|
|
12
|
+
import { DEFAULT_BATCH_SIZE, DEFAULT_SEARCH_DEPTH, severityOrder } from "./constants.js";
|
|
13
13
|
import { chalk } from "./utils/chalk.js";
|
|
14
14
|
import { createSpinner } from "./output/spinner.js";
|
|
15
15
|
import { buildSuggestedFixCommandPlan } from "./remediation/fix-commands.js";
|
|
16
16
|
import { scanProjectForPackageUsage } from "./usage/scanner.js";
|
|
17
17
|
import { getCliVersion } from "./utils/version-info.js";
|
|
18
|
-
import { isLikelyBlockedAdvisoryRequestError, isSslCertificateError, sslCertificateErrorHint,
|
|
19
|
-
import {
|
|
18
|
+
import { blockedAdvisoryRequestHint, isLikelyBlockedAdvisoryRequestError, isRateLimitError, isServerError, isSslCertificateError, rateLimitAdvisoryRequestHint, serverAdvisoryRequestHint, sslCertificateErrorHint, } from "./utils/network.js";
|
|
19
|
+
import { formatAdvisoryDbFreshness } from "./utils/time.js";
|
|
20
|
+
import { formatAdvisorySourceLine, logInfo, logWarn, printCacheSummary, sortFindingsForOutput } from "./output/formatters.js";
|
|
21
|
+
import { countBySeverity } from "./utils/severity.js";
|
|
20
22
|
import { buildReportData, writeHtmlReport } from "./output/html-reporter.js";
|
|
21
23
|
import { writeOutputs } from "./output/write-outputs.js";
|
|
22
24
|
import { printSummary, printActionSummary, printSuggestedFixCommands, printSuggestedFixCommandSkips, printCoverage, printSkippedDependencies, printTable, printFinalStatus, printCompactOutput } from "./output/printers.js";
|
|
23
25
|
import { installSkill } from "./skills/install.js";
|
|
26
|
+
import { readDirectDependencyNames } from "./utils/package-json.js";
|
|
24
27
|
let parsedArgs = null;
|
|
25
28
|
try {
|
|
26
29
|
parsedArgs = parseArgs(process.argv.slice(2));
|
|
@@ -39,15 +42,15 @@ if (parsedArgs) {
|
|
|
39
42
|
process.exit(0);
|
|
40
43
|
}
|
|
41
44
|
else if (options.version) {
|
|
42
|
-
printBanner();
|
|
45
|
+
printBanner(options);
|
|
43
46
|
process.exit(0);
|
|
44
47
|
}
|
|
45
48
|
else {
|
|
46
49
|
const projectPath = path.resolve(projectArg || ".");
|
|
47
|
-
const batchSize = Number(options.batchSize ||
|
|
48
|
-
const searchDepth = Math.max(0, Number(options.searchDepth ||
|
|
50
|
+
const batchSize = Number(options.batchSize || DEFAULT_BATCH_SIZE);
|
|
51
|
+
const searchDepth = Math.max(0, Number(options.searchDepth || DEFAULT_SEARCH_DEPTH));
|
|
49
52
|
async function main() {
|
|
50
|
-
printBanner();
|
|
53
|
+
printBanner(options);
|
|
51
54
|
if (command === "advisories-sync") {
|
|
52
55
|
const spinner = createSpinner("Preparing advisory sync...", options);
|
|
53
56
|
const usePlainProgressLogs = !process.stdout.isTTY || !!options.json;
|
|
@@ -79,26 +82,7 @@ if (parsedArgs) {
|
|
|
79
82
|
process.exit(0);
|
|
80
83
|
return;
|
|
81
84
|
}
|
|
82
|
-
|
|
83
|
-
throw new Error("--offline/--offline-db cannot be used with --osv-url");
|
|
84
|
-
}
|
|
85
|
-
if (options.noCache && (options.offline || options.offlineDb)) {
|
|
86
|
-
throw new Error("--no-cache cannot be used with --offline or --offline-db");
|
|
87
|
-
}
|
|
88
|
-
if (options.osvUrl) {
|
|
89
|
-
try {
|
|
90
|
-
new URL(options.osvUrl);
|
|
91
|
-
}
|
|
92
|
-
catch {
|
|
93
|
-
throw new Error(`Invalid value for --osv-url: ${options.osvUrl}`);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
if (options.fix && options.json) {
|
|
97
|
-
throw new Error("--fix cannot be used with --json");
|
|
98
|
-
}
|
|
99
|
-
if (options.report && options.json) {
|
|
100
|
-
throw new Error("--report cannot be used with --json");
|
|
101
|
-
}
|
|
85
|
+
validateOptions(options);
|
|
102
86
|
let advisorySourceLine;
|
|
103
87
|
let advisoryDbFreshnessLine = null;
|
|
104
88
|
let advisoryDbWarning = null;
|
|
@@ -260,6 +244,16 @@ if (parsedArgs) {
|
|
|
260
244
|
console.error(chalk.yellow(hint));
|
|
261
245
|
rest.forEach(line => console.error(chalk.gray(line)));
|
|
262
246
|
}
|
|
247
|
+
else if (isRateLimitError(errorMessage)) {
|
|
248
|
+
const [hint, ...rest] = rateLimitAdvisoryRequestHint();
|
|
249
|
+
console.error(chalk.yellow(hint));
|
|
250
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
251
|
+
}
|
|
252
|
+
else if (isServerError(errorMessage)) {
|
|
253
|
+
const [hint, ...rest] = serverAdvisoryRequestHint();
|
|
254
|
+
console.error(chalk.yellow(hint));
|
|
255
|
+
rest.forEach(line => console.error(chalk.gray(line)));
|
|
256
|
+
}
|
|
263
257
|
else if (isLikelyBlockedAdvisoryRequestError(errorMessage)) {
|
|
264
258
|
const [hint, ...rest] = blockedAdvisoryRequestHint();
|
|
265
259
|
console.error(chalk.yellow(hint));
|
|
@@ -269,13 +263,6 @@ if (parsedArgs) {
|
|
|
269
263
|
});
|
|
270
264
|
}
|
|
271
265
|
}
|
|
272
|
-
function formatAdvisorySourceLine(sourceLabel) {
|
|
273
|
-
const match = sourceLabel.match(/^(.*) \((.*)\)$/);
|
|
274
|
-
if (!match) {
|
|
275
|
-
return sourceLabel;
|
|
276
|
-
}
|
|
277
|
-
return `${match[1]} (${chalk.cyan(match[2])})`;
|
|
278
|
-
}
|
|
279
266
|
async function scanProject(params) {
|
|
280
267
|
const directDependencyNames = readDirectDependencyNames(params.projectPath, !!params.options.prodOnly);
|
|
281
268
|
const findings = await scanPackages(params.scanInput.packages, params.batchSize, params.options, {
|
|
@@ -348,6 +335,7 @@ async function applyFixesIfRequested(params) {
|
|
|
348
335
|
const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
|
|
349
336
|
const total = directTargets.length;
|
|
350
337
|
const spinner = createSpinner(`Applying direct package fixes with ${commandLabel}... 0/${total}`, params.options);
|
|
338
|
+
const fixHint = `\nHint: Check that \`${params.plan.packageManager}\` is available and you have write access to node_modules.\nIf running in CI, ensure the install step has already run before cve-lite --fix.`;
|
|
351
339
|
for (let i = 0; i < directTargets.length; i++) {
|
|
352
340
|
const target = directTargets[i];
|
|
353
341
|
const commandParts = buildFixCommandParts(params.plan.packageManager, [target]);
|
|
@@ -355,11 +343,11 @@ async function applyFixesIfRequested(params) {
|
|
|
355
343
|
const run = await runInstallCommand(commandParts[0], commandParts.slice(1), params.projectPath);
|
|
356
344
|
if (run.error) {
|
|
357
345
|
spinner.fail("Failed to apply fixes");
|
|
358
|
-
throw new Error(`Failed to apply fixes: ${run.error.message}`);
|
|
346
|
+
throw new Error(`Failed to apply fixes: ${run.error.message}${fixHint}`);
|
|
359
347
|
}
|
|
360
348
|
if ((run.status ?? 1) !== 0) {
|
|
361
349
|
spinner.fail(`Fix command failed (${commandLabel})`);
|
|
362
|
-
throw new Error(`Fix command exited with status ${run.status ?? 1}`);
|
|
350
|
+
throw new Error(`Fix command exited with status ${run.status ?? 1}${fixHint}`);
|
|
363
351
|
}
|
|
364
352
|
}
|
|
365
353
|
spinner.succeed(`Applied ${directTargets.length} direct package fix${directTargets.length === 1 ? "" : "es"} with ${commandLabel}`);
|
|
@@ -414,20 +402,6 @@ function commandLabelForPackageManager(packageManager) {
|
|
|
414
402
|
return "bun add";
|
|
415
403
|
return "yarn add";
|
|
416
404
|
}
|
|
417
|
-
function countBySeverity(findings) {
|
|
418
|
-
const counts = {
|
|
419
|
-
none: 0,
|
|
420
|
-
low: 0,
|
|
421
|
-
medium: 0,
|
|
422
|
-
high: 0,
|
|
423
|
-
critical: 0,
|
|
424
|
-
unknown: 0,
|
|
425
|
-
};
|
|
426
|
-
for (const finding of findings) {
|
|
427
|
-
counts[finding.severity] += 1;
|
|
428
|
-
}
|
|
429
|
-
return counts;
|
|
430
|
-
}
|
|
431
405
|
function printFixModeSummary(params) {
|
|
432
406
|
const result = params.fixResult;
|
|
433
407
|
if (!result)
|
|
@@ -454,140 +428,3 @@ function printFixModeSummary(params) {
|
|
|
454
428
|
console.log(`- Remaining findings after fix: ${chalk.white(String(params.findingsAfterFix))}`);
|
|
455
429
|
console.log(`- Remaining severity mix: critical ${chalk.redBright(String(params.remainingBySeverity.critical))}, high ${chalk.red(String(params.remainingBySeverity.high))}, medium ${chalk.yellow(String(params.remainingBySeverity.medium))}, low ${chalk.blueBright(String(params.remainingBySeverity.low))}, unknown ${chalk.magenta(String(params.remainingBySeverity.unknown))}`);
|
|
456
430
|
}
|
|
457
|
-
function readDirectDependencyNames(projectPath, prodOnly) {
|
|
458
|
-
const packageJsonPath = path.join(projectPath, "package.json");
|
|
459
|
-
if (!fs.existsSync(packageJsonPath)) {
|
|
460
|
-
return null;
|
|
461
|
-
}
|
|
462
|
-
try {
|
|
463
|
-
const directNames = new Set();
|
|
464
|
-
const rootManifest = readPackageJsonObject(packageJsonPath);
|
|
465
|
-
if (!rootManifest) {
|
|
466
|
-
return null;
|
|
467
|
-
}
|
|
468
|
-
addDependencyNamesFromManifest(directNames, rootManifest, prodOnly);
|
|
469
|
-
const workspacePatterns = readWorkspacePatterns(rootManifest);
|
|
470
|
-
for (const workspacePackageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, workspacePatterns)) {
|
|
471
|
-
const workspaceManifest = readPackageJsonObject(workspacePackageJsonPath);
|
|
472
|
-
if (!workspaceManifest)
|
|
473
|
-
continue;
|
|
474
|
-
addDependencyNamesFromManifest(directNames, workspaceManifest, prodOnly);
|
|
475
|
-
}
|
|
476
|
-
return directNames;
|
|
477
|
-
}
|
|
478
|
-
catch {
|
|
479
|
-
return null;
|
|
480
|
-
}
|
|
481
|
-
}
|
|
482
|
-
function readPackageJsonObject(filePath) {
|
|
483
|
-
try {
|
|
484
|
-
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
485
|
-
return raw && typeof raw === "object" ? raw : null;
|
|
486
|
-
}
|
|
487
|
-
catch {
|
|
488
|
-
return null;
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
function addDependencyNamesFromManifest(target, manifest, prodOnly) {
|
|
492
|
-
const sections = [
|
|
493
|
-
isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
|
|
494
|
-
isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
|
|
495
|
-
];
|
|
496
|
-
if (!prodOnly) {
|
|
497
|
-
sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
|
|
498
|
-
}
|
|
499
|
-
for (const section of sections) {
|
|
500
|
-
if (!section)
|
|
501
|
-
continue;
|
|
502
|
-
for (const name of Object.keys(section)) {
|
|
503
|
-
target.add(name);
|
|
504
|
-
}
|
|
505
|
-
}
|
|
506
|
-
}
|
|
507
|
-
function readWorkspacePatterns(manifest) {
|
|
508
|
-
const workspaces = manifest.workspaces;
|
|
509
|
-
if (Array.isArray(workspaces)) {
|
|
510
|
-
return workspaces.filter((value) => typeof value === "string");
|
|
511
|
-
}
|
|
512
|
-
if (isRecord(workspaces) && Array.isArray(workspaces.packages)) {
|
|
513
|
-
return workspaces.packages.filter((value) => typeof value === "string");
|
|
514
|
-
}
|
|
515
|
-
return [];
|
|
516
|
-
}
|
|
517
|
-
function resolveWorkspacePackageJsonPaths(projectPath, patterns) {
|
|
518
|
-
const matches = new Set();
|
|
519
|
-
for (const pattern of patterns) {
|
|
520
|
-
const normalized = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
521
|
-
if (!normalized)
|
|
522
|
-
continue;
|
|
523
|
-
for (const relativeDir of expandWorkspacePattern(projectPath, normalized.split("/").filter(Boolean), "")) {
|
|
524
|
-
const packageJsonPath = path.join(projectPath, relativeDir, "package.json");
|
|
525
|
-
if (fs.existsSync(packageJsonPath)) {
|
|
526
|
-
matches.add(packageJsonPath);
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
return [...matches];
|
|
531
|
-
}
|
|
532
|
-
function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
|
|
533
|
-
if (segments.length === 0) {
|
|
534
|
-
return currentRelativePath ? [currentRelativePath] : [];
|
|
535
|
-
}
|
|
536
|
-
const [segment, ...rest] = segments;
|
|
537
|
-
if (segment === "*") {
|
|
538
|
-
const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
|
|
539
|
-
let entries = [];
|
|
540
|
-
try {
|
|
541
|
-
entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
|
542
|
-
}
|
|
543
|
-
catch {
|
|
544
|
-
return [];
|
|
545
|
-
}
|
|
546
|
-
return entries
|
|
547
|
-
.filter(entry => entry.isDirectory())
|
|
548
|
-
.flatMap(entry => {
|
|
549
|
-
const nextRelativePath = currentRelativePath
|
|
550
|
-
? path.join(currentRelativePath, entry.name)
|
|
551
|
-
: entry.name;
|
|
552
|
-
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
553
|
-
});
|
|
554
|
-
}
|
|
555
|
-
const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, segment) : segment;
|
|
556
|
-
const nextAbsolutePath = path.join(projectPath, nextRelativePath);
|
|
557
|
-
if (!fs.existsSync(nextAbsolutePath) || !fs.statSync(nextAbsolutePath).isDirectory()) {
|
|
558
|
-
return [];
|
|
559
|
-
}
|
|
560
|
-
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
561
|
-
}
|
|
562
|
-
function isRecord(value) {
|
|
563
|
-
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
564
|
-
}
|
|
565
|
-
function formatAdvisoryDbFreshness(lastSyncAt) {
|
|
566
|
-
if (!lastSyncAt) {
|
|
567
|
-
return chalk.yellow("unknown");
|
|
568
|
-
}
|
|
569
|
-
const timestamp = Date.parse(lastSyncAt);
|
|
570
|
-
if (Number.isNaN(timestamp)) {
|
|
571
|
-
return chalk.yellow("unknown");
|
|
572
|
-
}
|
|
573
|
-
return `${relativeAge(timestamp)} ${chalk.gray(`(${lastSyncAt})`)}`;
|
|
574
|
-
}
|
|
575
|
-
function relativeAge(timestamp) {
|
|
576
|
-
const deltaMs = Math.max(0, Date.now() - timestamp);
|
|
577
|
-
const minute = 60 * 1000;
|
|
578
|
-
const hour = 60 * minute;
|
|
579
|
-
const day = 24 * hour;
|
|
580
|
-
if (deltaMs < minute) {
|
|
581
|
-
return "just synced";
|
|
582
|
-
}
|
|
583
|
-
if (deltaMs < hour) {
|
|
584
|
-
const minutes = Math.floor(deltaMs / minute);
|
|
585
|
-
return `synced ${minutes} minute${minutes === 1 ? "" : "s"} ago`;
|
|
586
|
-
}
|
|
587
|
-
if (deltaMs < day) {
|
|
588
|
-
const hours = Math.floor(deltaMs / hour);
|
|
589
|
-
return `synced ${hours} hour${hours === 1 ? "" : "s"} ago`;
|
|
590
|
-
}
|
|
591
|
-
const days = Math.floor(deltaMs / day);
|
|
592
|
-
return `synced ${days} day${days === 1 ? "" : "s"} ago`;
|
|
593
|
-
}
|
|
@@ -26,6 +26,13 @@ export function formatRelationshipLabel(value) {
|
|
|
26
26
|
return chalk.yellow(value);
|
|
27
27
|
return chalk.gray(value);
|
|
28
28
|
}
|
|
29
|
+
export function formatAdvisorySourceLine(sourceLabel) {
|
|
30
|
+
const match = sourceLabel.match(/^(.*) \((.*)\)$/);
|
|
31
|
+
if (!match) {
|
|
32
|
+
return sourceLabel;
|
|
33
|
+
}
|
|
34
|
+
return `${match[1]} (${chalk.cyan(match[2])})`;
|
|
35
|
+
}
|
|
29
36
|
// MAL-* is the OSV prefix for malicious code advisories
|
|
30
37
|
function isMaliciousAdvisory(finding) {
|
|
31
38
|
return finding.vulnerabilities.some(v => v.id.startsWith("MAL-"));
|
|
@@ -48,7 +55,7 @@ export function getRecommendedAction(finding) {
|
|
|
48
55
|
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
49
56
|
}
|
|
50
57
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
51
|
-
return
|
|
58
|
+
return `${finding.recommendedNpmTransitiveRemediation.package} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} — run the lockfile refresh command to pick it up.`;
|
|
52
59
|
}
|
|
53
60
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
54
61
|
finding.recommendedNpmTransitiveRemediation.targetVersion) {
|
|
@@ -149,7 +156,7 @@ export function summarizeNextAction(finding) {
|
|
|
149
156
|
return `No known fix exists for ${finding.pkg.name}. Consider replacing it with an actively maintained alternative.`;
|
|
150
157
|
}
|
|
151
158
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
152
|
-
return `
|
|
159
|
+
return `Lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version.`;
|
|
153
160
|
}
|
|
154
161
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "upgrade-parent-to-version" &&
|
|
155
162
|
finding.recommendedNpmTransitiveRemediation.targetVersion) {
|
|
@@ -490,11 +490,12 @@ function renderFixPlan(plan) {
|
|
|
490
490
|
const skippedCount = plan.skipped.length;
|
|
491
491
|
const commandRows = plan.sections.map(section => {
|
|
492
492
|
const targetRows = section.targets.map(t => {
|
|
493
|
+
const displayVersion = t.displayTargetVersion ?? t.targetVersion;
|
|
493
494
|
const isMajor = t.currentVersion ? isMajorVersionBump(t.currentVersion, t.targetVersion) : false;
|
|
494
495
|
const breakBadge = isMajor ? ` <span class="break-badge">⚠ breaking</span>` : "";
|
|
495
496
|
const versionHtml = t.currentVersion
|
|
496
|
-
? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(
|
|
497
|
-
: `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(
|
|
497
|
+
? `<span class="fix-target-pkg">${escapeHtml(t.package)}@${escapeHtml(t.currentVersion)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`
|
|
498
|
+
: `<span class="fix-target-pkg">${escapeHtml(t.package)}</span><span class="fix-target-arrow">→</span><span class="fix-target-to">${escapeHtml(displayVersion)}</span>`;
|
|
498
499
|
const statsHtml = t.scannedVersions != null
|
|
499
500
|
? ` <span class="fix-target-stats">${t.scannedVersions} scanned${t.knownVulnerableVersions != null ? ` · ${t.knownVulnerableVersions} still vulnerable` : ""}</span>`
|
|
500
501
|
: "";
|
|
@@ -530,6 +531,9 @@ function renderFixPlan(plan) {
|
|
|
530
531
|
const skippedBadgePart = skippedCount > 0
|
|
531
532
|
? ` · <button class="skipped-toggle" onclick="toggleSkipped()">↓ ${skippedCount} skipped</button>`
|
|
532
533
|
: "";
|
|
534
|
+
const coverageText = plan.coveredFindingCount === plan.totalFindingCount
|
|
535
|
+
? `Running all commands should fix all ${plan.totalFindingCount} findings.`
|
|
536
|
+
: `Running all commands should fix <strong>${plan.coveredFindingCount}</strong> of <strong>${plan.totalFindingCount}</strong> findings.`;
|
|
533
537
|
return `<div class="fix-plan">
|
|
534
538
|
<div class="fix-plan-header">
|
|
535
539
|
<h2><span class="icon">✦</span> Suggested Fix Plan</h2>
|
|
@@ -537,6 +541,7 @@ function renderFixPlan(plan) {
|
|
|
537
541
|
</div>
|
|
538
542
|
<div class="fix-commands">${commandRows}
|
|
539
543
|
</div>${skippedSection}
|
|
544
|
+
<div style="padding:10px 18px;border-top:1px solid #21262d;font-size:11px;color:#8b949e">${coverageText}</div>
|
|
540
545
|
</div>`;
|
|
541
546
|
}
|
|
542
547
|
export async function writeHtmlReport(params) {
|
package/dist/output/printers.js
CHANGED
|
@@ -89,6 +89,13 @@ export function printSuggestedFixCommands(findings, scanInput, options) {
|
|
|
89
89
|
}
|
|
90
90
|
console.log(renderCommandCallout(section.command));
|
|
91
91
|
}
|
|
92
|
+
if (plan.coveredFindingCount > 0) {
|
|
93
|
+
console.log("");
|
|
94
|
+
const coverage = plan.coveredFindingCount === plan.totalFindingCount
|
|
95
|
+
? chalk.gray(`Running all commands above should fix all ${plan.totalFindingCount} findings.`)
|
|
96
|
+
: chalk.gray(`Running all commands above should fix ${chalk.white(String(plan.coveredFindingCount))} of ${chalk.white(String(plan.totalFindingCount))} findings.`);
|
|
97
|
+
console.log(coverage);
|
|
98
|
+
}
|
|
92
99
|
}
|
|
93
100
|
export function printSuggestedFixCommandSkips(findings, scanInput, options) {
|
|
94
101
|
const plan = buildSuggestedFixCommandPlan(findings, scanInput, options);
|
|
@@ -305,7 +312,7 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
305
312
|
console.log(` ${chalk.red(`⚠ Malicious: ${action}`)}`);
|
|
306
313
|
}
|
|
307
314
|
else if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
308
|
-
console.log(` ${chalk.gray(`Fix:
|
|
315
|
+
console.log(` ${chalk.gray(`Fix: lockfile refresh — ${finding.recommendedNpmTransitiveRemediation.package} already permits a safe version`)}`);
|
|
309
316
|
}
|
|
310
317
|
else if (finding.recommendedParentUpgrade) {
|
|
311
318
|
console.log(` ${chalk.gray(`Fix: upgrade ${finding.recommendedParentUpgrade.package} to ${finding.recommendedParentUpgrade.targetVersion}`)}`);
|
package/dist/parsers/bun-lock.js
CHANGED
|
@@ -4,6 +4,25 @@ function parseJsonc(text) {
|
|
|
4
4
|
// bun.lock uses JSONC (trailing commas). Strip them before parsing.
|
|
5
5
|
return JSON.parse(text.replace(/,(\s*[}\]])/g, "$1"));
|
|
6
6
|
}
|
|
7
|
+
export function buildBunWorkspaceMap(filePath) {
|
|
8
|
+
const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
|
|
9
|
+
const workspaces = raw?.workspaces ?? {};
|
|
10
|
+
const map = new Map();
|
|
11
|
+
for (const [workspacePath, workspace] of Object.entries(workspaces)) {
|
|
12
|
+
for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
|
|
13
|
+
const depSection = workspace?.[depSectionName];
|
|
14
|
+
if (!depSection || typeof depSection !== "object")
|
|
15
|
+
continue;
|
|
16
|
+
for (const depName of Object.keys(depSection)) {
|
|
17
|
+
const existing = map.get(depName) ?? [];
|
|
18
|
+
if (!existing.includes(workspacePath)) {
|
|
19
|
+
map.set(depName, [...existing, workspacePath]);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return map;
|
|
25
|
+
}
|
|
7
26
|
export function loadFromBunLock(filePath, prodOnly) {
|
|
8
27
|
const raw = parseJsonc(fs.readFileSync(filePath, "utf8"));
|
|
9
28
|
const packages = raw?.packages ?? {};
|
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import { upsertPackage, normalizeNodeModulesPath } from "./utils.js";
|
|
3
3
|
import { loadNpmLockGraph } from "./npm-lock-graph.js";
|
|
4
|
+
export function buildNpmWorkspaceMap(filePath) {
|
|
5
|
+
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
6
|
+
const map = new Map();
|
|
7
|
+
if (!raw.packages || typeof raw.packages !== "object")
|
|
8
|
+
return map;
|
|
9
|
+
for (const [pkgPath, meta] of Object.entries(raw.packages)) {
|
|
10
|
+
if (pkgPath.includes("node_modules/"))
|
|
11
|
+
continue;
|
|
12
|
+
const workspacePath = pkgPath === "" ? "." : pkgPath;
|
|
13
|
+
for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
|
|
14
|
+
const depSection = meta?.[depSectionName];
|
|
15
|
+
if (!depSection || typeof depSection !== "object")
|
|
16
|
+
continue;
|
|
17
|
+
for (const depName of Object.keys(depSection)) {
|
|
18
|
+
const existing = map.get(depName) ?? [];
|
|
19
|
+
if (!existing.includes(workspacePath)) {
|
|
20
|
+
map.set(depName, [...existing, workspacePath]);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return map;
|
|
26
|
+
}
|
|
4
27
|
export function loadFromPackageLock(filePath, prodOnly) {
|
|
5
28
|
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
6
29
|
const map = new Map();
|
|
@@ -5,6 +5,26 @@ import { upsertPackage } from "./utils.js";
|
|
|
5
5
|
import { uniquePathArrays } from "../utils/array.js";
|
|
6
6
|
const MAX_PATHS_PER_PACKAGE = 5;
|
|
7
7
|
const MAX_PATH_DEPTH = 10;
|
|
8
|
+
export function buildPnpmWorkspaceMap(filePath) {
|
|
9
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
10
|
+
const parsed = YAML.parse(content);
|
|
11
|
+
const importers = parsed?.importers ?? {};
|
|
12
|
+
const map = new Map();
|
|
13
|
+
for (const [importerPath, importer] of Object.entries(importers)) {
|
|
14
|
+
for (const depSectionName of ["dependencies", "optionalDependencies", "devDependencies"]) {
|
|
15
|
+
const depSection = importer?.[depSectionName];
|
|
16
|
+
if (!depSection || typeof depSection !== "object")
|
|
17
|
+
continue;
|
|
18
|
+
for (const depName of Object.keys(depSection)) {
|
|
19
|
+
const existing = map.get(depName) ?? [];
|
|
20
|
+
if (!existing.includes(importerPath)) {
|
|
21
|
+
map.set(depName, [...existing, importerPath]);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
return map;
|
|
27
|
+
}
|
|
8
28
|
export function loadFromPnpmLock(filePath, prodOnly) {
|
|
9
29
|
const content = fs.readFileSync(filePath, "utf8");
|
|
10
30
|
const parsed = YAML.parse(content);
|
|
@@ -112,7 +112,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
112
112
|
package: finding.recommendedNpmTransitiveRemediation.package,
|
|
113
113
|
currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
|
|
114
114
|
targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
|
|
115
|
-
displayTargetVersion: "
|
|
115
|
+
displayTargetVersion: "lockfile refresh",
|
|
116
116
|
scannedVersions: null,
|
|
117
117
|
knownVulnerableVersions: null,
|
|
118
118
|
kind: "parent-update",
|
|
@@ -120,8 +120,8 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
120
120
|
severity: finding.severity,
|
|
121
121
|
adjusted: false,
|
|
122
122
|
adjustmentNote: null,
|
|
123
|
-
reason:
|
|
124
|
-
command:
|
|
123
|
+
reason: `${finding.recommendedNpmTransitiveRemediation.package}@${finding.recommendedNpmTransitiveRemediation.currentVersion} already permits ${finding.pkg.name}@${finding.recommendedNpmTransitiveRemediation.targetChildVersion} — refreshing the lockfile is enough.`,
|
|
124
|
+
command: buildNpmUpdateCommand(finding.recommendedNpmTransitiveRemediation.package, finding.recommendedNpmTransitiveRemediation.workspaces),
|
|
125
125
|
usage: finding.usage ?? null,
|
|
126
126
|
});
|
|
127
127
|
continue;
|
|
@@ -186,12 +186,26 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
186
186
|
if (packageManager !== "npm" &&
|
|
187
187
|
finding.relationship === "transitive" &&
|
|
188
188
|
finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
189
|
-
const
|
|
190
|
-
|
|
189
|
+
const lockfileRefreshCommand = packageManager === "pnpm"
|
|
190
|
+
? buildPnpmLockfileRefreshCommand(finding.pkg.name, finding.recommendedNpmTransitiveRemediation.workspaces)
|
|
191
|
+
: packageManager === "yarn"
|
|
192
|
+
? `yarn upgrade ${finding.pkg.name}`
|
|
193
|
+
: `bun update ${finding.pkg.name}`;
|
|
194
|
+
upsertTarget(targetsByPackage, {
|
|
191
195
|
package: finding.pkg.name,
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
196
|
+
currentVersion: finding.pkg.version,
|
|
197
|
+
targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
|
|
198
|
+
displayTargetVersion: "lockfile refresh",
|
|
199
|
+
scannedVersions: null,
|
|
200
|
+
knownVulnerableVersions: null,
|
|
201
|
+
kind: "parent-update",
|
|
202
|
+
urgent,
|
|
203
|
+
severity: finding.severity,
|
|
204
|
+
adjusted: false,
|
|
205
|
+
adjustmentNote: null,
|
|
206
|
+
reason: `${finding.pkg.name}@${finding.pkg.version} can be refreshed to ${finding.recommendedNpmTransitiveRemediation.targetChildVersion}+ — no parent upgrade needed.`,
|
|
207
|
+
command: lockfileRefreshCommand,
|
|
208
|
+
usage: finding.usage ?? null,
|
|
195
209
|
});
|
|
196
210
|
continue;
|
|
197
211
|
}
|
|
@@ -235,14 +249,18 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
235
249
|
const command = targets.length > 0
|
|
236
250
|
? buildCommandForTargets(targets, packageManager)
|
|
237
251
|
: null;
|
|
238
|
-
|
|
252
|
+
const plan = {
|
|
239
253
|
packageManager,
|
|
240
254
|
sourceLabel: packageManagerSourceLabel(scanInput),
|
|
241
255
|
command,
|
|
242
256
|
sections,
|
|
243
257
|
targets,
|
|
244
258
|
skipped,
|
|
259
|
+
coveredFindingCount: 0,
|
|
260
|
+
totalFindingCount: findings.length,
|
|
245
261
|
};
|
|
262
|
+
plan.coveredFindingCount = findings.filter(f => findSuggestedCommandForFinding(plan, f) !== null).length;
|
|
263
|
+
return plan;
|
|
246
264
|
}
|
|
247
265
|
function inferPackageManager(scanInput) {
|
|
248
266
|
if (scanInput.source === "package-lock")
|
|
@@ -255,6 +273,26 @@ function inferPackageManager(scanInput) {
|
|
|
255
273
|
return "bun";
|
|
256
274
|
return null;
|
|
257
275
|
}
|
|
276
|
+
function buildNpmUpdateCommand(pkg, workspaces) {
|
|
277
|
+
const nonRoot = (workspaces ?? []).filter(w => w !== ".");
|
|
278
|
+
if (nonRoot.length === 1) {
|
|
279
|
+
return `npm update --workspace=${nonRoot[0]} ${pkg}`;
|
|
280
|
+
}
|
|
281
|
+
if (nonRoot.length > 1) {
|
|
282
|
+
return `npm update --workspaces ${pkg}`;
|
|
283
|
+
}
|
|
284
|
+
return `npm update ${pkg}`;
|
|
285
|
+
}
|
|
286
|
+
function buildPnpmLockfileRefreshCommand(pkg, workspaces) {
|
|
287
|
+
if (!workspaces || workspaces.length === 0 || workspaces.length > 1) {
|
|
288
|
+
return `pnpm update --recursive --no-save ${pkg}`;
|
|
289
|
+
}
|
|
290
|
+
const workspace = workspaces[0];
|
|
291
|
+
if (workspace === ".") {
|
|
292
|
+
return `pnpm update --no-save ${pkg}`;
|
|
293
|
+
}
|
|
294
|
+
return `pnpm -C ${workspace} update --no-save ${pkg}`;
|
|
295
|
+
}
|
|
258
296
|
function commandPrefix(packageManager) {
|
|
259
297
|
if (packageManager === "npm")
|
|
260
298
|
return "npm install";
|
|
@@ -268,8 +306,8 @@ export function findSuggestedCommandForFinding(plan, finding) {
|
|
|
268
306
|
const target = plan.targets.find(item => {
|
|
269
307
|
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
270
308
|
return (item.kind === "parent-update" &&
|
|
271
|
-
item.
|
|
272
|
-
item.
|
|
309
|
+
item.targetVersion === finding.recommendedNpmTransitiveRemediation.targetChildVersion &&
|
|
310
|
+
(item.package === finding.recommendedNpmTransitiveRemediation.package || item.package === finding.pkg.name));
|
|
273
311
|
}
|
|
274
312
|
if (finding.recommendedParentUpgrade) {
|
|
275
313
|
return (item.package === finding.recommendedParentUpgrade.package &&
|
|
@@ -382,7 +420,9 @@ function buildSections(targets, packageManager) {
|
|
|
382
420
|
const groups = [];
|
|
383
421
|
const sectionOrder = [
|
|
384
422
|
{ kind: "urgent", severity: "critical" },
|
|
423
|
+
{ kind: "parent-update", severity: "critical" },
|
|
385
424
|
{ kind: "urgent", severity: "high" },
|
|
425
|
+
{ kind: "parent-update", severity: "high" },
|
|
386
426
|
{ kind: "direct", severity: "medium" },
|
|
387
427
|
{ kind: "direct", severity: "low" },
|
|
388
428
|
{ kind: "direct", severity: "unknown" },
|
|
@@ -398,7 +438,9 @@ function buildSections(targets, packageManager) {
|
|
|
398
438
|
];
|
|
399
439
|
for (const entry of sectionOrder) {
|
|
400
440
|
const sectionTargets = targets.filter(target => {
|
|
401
|
-
const targetKind = target.
|
|
441
|
+
const targetKind = target.kind === "parent-update"
|
|
442
|
+
? "parent-update"
|
|
443
|
+
: target.urgent ? "urgent" : target.adjusted ? "direct-adjusted" : target.kind;
|
|
402
444
|
return targetKind === entry.kind && target.severity === entry.severity;
|
|
403
445
|
});
|
|
404
446
|
if (sectionTargets.length === 0)
|
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
import { compareVersions, isPreReleaseVersion, looksLikeVersion } from "../utils/version.js";
|
|
2
2
|
import { fetchPackument } from "./npm-registry.js";
|
|
3
3
|
import { findSafeVersionWithinParentRange } from "./npm-transitive-graph.js";
|
|
4
|
+
export async function resolveTransitiveRemediationViaRegistry(args) {
|
|
5
|
+
if (args.finding.relationship !== "transitive")
|
|
6
|
+
return null;
|
|
7
|
+
const viaPath = getBestPath(args.finding);
|
|
8
|
+
if (!viaPath || viaPath.length < 3)
|
|
9
|
+
return null;
|
|
10
|
+
const directParentContext = resolveDirectParentContext(viaPath, args.packages, args.directDependencyNames);
|
|
11
|
+
if (!directParentContext)
|
|
12
|
+
return null;
|
|
13
|
+
const { directParentName, immediateParentName, directParent } = directParentContext;
|
|
14
|
+
if (directParentName !== immediateParentName)
|
|
15
|
+
return null;
|
|
16
|
+
if (!looksLikeVersion(directParent.version))
|
|
17
|
+
return null;
|
|
18
|
+
const vulnerableName = args.finding.pkg.name;
|
|
19
|
+
const fixHint = args.finding.validatedFirstFixedVersion ?? args.finding.firstFixedVersion;
|
|
20
|
+
const safeCandidates = await findSafeChildCandidates(vulnerableName, args.finding.pkg.version, fixHint);
|
|
21
|
+
if (safeCandidates.length === 0)
|
|
22
|
+
return null;
|
|
23
|
+
const packument = await fetchPackument(directParentName);
|
|
24
|
+
const parentManifest = packument?.versions?.[directParent.version];
|
|
25
|
+
const depRange = parentManifest?.dependencies?.[vulnerableName] ??
|
|
26
|
+
parentManifest?.optionalDependencies?.[vulnerableName];
|
|
27
|
+
if (!depRange)
|
|
28
|
+
return null;
|
|
29
|
+
const inRangeTarget = [...safeCandidates]
|
|
30
|
+
.sort(compareVersions)
|
|
31
|
+
.filter(v => versionSatisfiesRange(v, depRange))
|
|
32
|
+
.at(-1);
|
|
33
|
+
if (!inRangeTarget)
|
|
34
|
+
return null;
|
|
35
|
+
const workspaces = collectWorkspacesFromAllPaths(args.finding.dependencyPaths ?? [], args.workspaceMap);
|
|
36
|
+
return {
|
|
37
|
+
kind: "update-parent-within-range",
|
|
38
|
+
package: directParentName,
|
|
39
|
+
currentVersion: directParent.version,
|
|
40
|
+
targetChildVersion: inRangeTarget,
|
|
41
|
+
viaPath,
|
|
42
|
+
reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
|
|
43
|
+
workspaces,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
4
46
|
export async function resolveNpmTransitiveRemediation(args) {
|
|
5
47
|
if (args.finding.relationship !== "transitive")
|
|
6
48
|
return null;
|
|
@@ -38,6 +80,7 @@ export async function resolveNpmTransitiveRemediation(args) {
|
|
|
38
80
|
candidates: safeCandidates,
|
|
39
81
|
});
|
|
40
82
|
if (inRangeTarget) {
|
|
83
|
+
const workspaces = collectWorkspacesFromAllPaths(args.finding.dependencyPaths ?? [], args.workspaceMap);
|
|
41
84
|
return {
|
|
42
85
|
kind: "update-parent-within-range",
|
|
43
86
|
package: directParentName,
|
|
@@ -45,6 +88,7 @@ export async function resolveNpmTransitiveRemediation(args) {
|
|
|
45
88
|
targetChildVersion: inRangeTarget,
|
|
46
89
|
viaPath,
|
|
47
90
|
reason: `${directParentName}@${directParent.version} already allows ${vulnerableName}@${inRangeTarget} within the current dependency range`,
|
|
91
|
+
workspaces,
|
|
48
92
|
};
|
|
49
93
|
}
|
|
50
94
|
// The upgrade-parent-to-version path needs the parent's published manifests
|
|
@@ -236,3 +280,22 @@ function parseCoreVersion(version) {
|
|
|
236
280
|
const [major = "0", minor = "0", patch = "0"] = version.split(/[+-]/)[0].split(".");
|
|
237
281
|
return [Number(major), Number(minor), Number(patch)];
|
|
238
282
|
}
|
|
283
|
+
function collectWorkspacesFromAllPaths(dependencyPaths, workspaceMap) {
|
|
284
|
+
if (!workspaceMap)
|
|
285
|
+
return undefined;
|
|
286
|
+
const workspaceSet = new Set();
|
|
287
|
+
for (const path of dependencyPaths) {
|
|
288
|
+
if (path.length !== 3)
|
|
289
|
+
continue;
|
|
290
|
+
const parentName = path[1];
|
|
291
|
+
if (!parentName)
|
|
292
|
+
continue;
|
|
293
|
+
const wsForParent = workspaceMap.get(parentName);
|
|
294
|
+
if (wsForParent) {
|
|
295
|
+
for (const ws of wsForParent) {
|
|
296
|
+
workspaceSet.add(ws);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return workspaceSet.size > 0 ? [...workspaceSet] : undefined;
|
|
301
|
+
}
|
package/dist/scanner.js
CHANGED
|
@@ -9,8 +9,11 @@ import { LocalAdvisoryDatabase } from "./advisory/local-db.js";
|
|
|
9
9
|
import { ADVISORY_DB_STALE_AFTER_MS, getDefaultAdvisoryDbPath } from "./advisory/osv-sync.js";
|
|
10
10
|
import { resolveRecommendedParentUpgrade } from "./remediation/parent-upgrade.js";
|
|
11
11
|
import { resolveLowestKnownNonVulnerableVersion, resolvePublishedFixVersion } from "./remediation/npm-registry.js";
|
|
12
|
-
import { resolveNpmTransitiveRemediation } from "./remediation/npm-transitive-resolution.js";
|
|
12
|
+
import { resolveNpmTransitiveRemediation, resolveTransitiveRemediationViaRegistry } from "./remediation/npm-transitive-resolution.js";
|
|
13
13
|
import { loadNpmLockGraph } from "./parsers/npm-lock-graph.js";
|
|
14
|
+
import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
|
|
15
|
+
import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
|
|
16
|
+
import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
|
|
14
17
|
export function createAdvisorySource(options) {
|
|
15
18
|
const offline = !!options?.offline || !!options?.offlineDb;
|
|
16
19
|
if (offline) {
|
|
@@ -191,6 +194,34 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
191
194
|
const npmTransitiveGraph = context?.scanSource === "package-lock" && context.scanFilePath
|
|
192
195
|
? createNpmTransitiveGraphFromLockfile(context.scanFilePath)
|
|
193
196
|
: null;
|
|
197
|
+
const npmWorkspaceMap = (() => {
|
|
198
|
+
try {
|
|
199
|
+
return context?.scanSource === "package-lock" && context.scanFilePath
|
|
200
|
+
? buildNpmWorkspaceMap(context.scanFilePath) : null;
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
})();
|
|
206
|
+
const pnpmWorkspaceMap = (() => {
|
|
207
|
+
try {
|
|
208
|
+
return context?.scanSource === "pnpm-lock" && context.scanFilePath
|
|
209
|
+
? buildPnpmWorkspaceMap(context.scanFilePath) : null;
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
})();
|
|
215
|
+
const bunWorkspaceMap = (() => {
|
|
216
|
+
try {
|
|
217
|
+
return context?.scanSource === "bun-lock" && context.scanFilePath
|
|
218
|
+
? buildBunWorkspaceMap(context.scanFilePath) : null;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
})();
|
|
224
|
+
const lockfileWorkspaceMap = pnpmWorkspaceMap ?? bunWorkspaceMap ?? null;
|
|
194
225
|
const npmRemediationCache = new Map();
|
|
195
226
|
const parentUpgradeCache = new Map();
|
|
196
227
|
const directValidationCount = offline ? 0 : findings.length;
|
|
@@ -233,6 +264,7 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
233
264
|
packages,
|
|
234
265
|
directDependencyNames: context?.directDependencyNames,
|
|
235
266
|
offline,
|
|
267
|
+
workspaceMap: npmWorkspaceMap,
|
|
236
268
|
});
|
|
237
269
|
npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
|
|
238
270
|
}
|
|
@@ -253,6 +285,25 @@ export async function scanPackages(packages, batchSize, options, context) {
|
|
|
253
285
|
continue;
|
|
254
286
|
}
|
|
255
287
|
}
|
|
288
|
+
if (!offline && !npmTransitiveGraph) {
|
|
289
|
+
if (npmRemediationCache.has(remediationCacheKey)) {
|
|
290
|
+
finding.recommendedNpmTransitiveRemediation =
|
|
291
|
+
npmRemediationCache.get(remediationCacheKey) ?? undefined;
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
finding.recommendedNpmTransitiveRemediation = await resolveTransitiveRemediationViaRegistry({
|
|
295
|
+
finding,
|
|
296
|
+
packages,
|
|
297
|
+
directDependencyNames: context?.directDependencyNames,
|
|
298
|
+
workspaceMap: lockfileWorkspaceMap,
|
|
299
|
+
});
|
|
300
|
+
npmRemediationCache.set(remediationCacheKey, finding.recommendedNpmTransitiveRemediation ?? null);
|
|
301
|
+
}
|
|
302
|
+
if (finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
303
|
+
finding.recommendedParentUpgrade = undefined;
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
256
307
|
if (parentUpgradeCache.has(remediationCacheKey)) {
|
|
257
308
|
finding.recommendedParentUpgrade = parentUpgradeCache.get(remediationCacheKey) ?? undefined;
|
|
258
309
|
}
|
package/dist/usage/scanner.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
|
|
3
|
+
// Shared with lockfile scanning in utils/file.ts; additions affect both code paths.
|
|
4
|
+
import { EXCLUDED_DIRS } from "../constants.js";
|
|
4
5
|
const ALLOWED_EXTS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
|
|
5
6
|
// Matches:
|
|
6
7
|
// import { foo } from 'pkg'
|
|
@@ -46,7 +47,7 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
|
|
|
46
47
|
return;
|
|
47
48
|
const fullPath = path.join(dir, entry.name);
|
|
48
49
|
if (entry.isDirectory()) {
|
|
49
|
-
if (!
|
|
50
|
+
if (!EXCLUDED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
|
|
50
51
|
walk(fullPath);
|
|
51
52
|
}
|
|
52
53
|
}
|
package/dist/utils/network.js
CHANGED
|
@@ -22,6 +22,22 @@ export function blockedAdvisoryRequestHint() {
|
|
|
22
22
|
"Command to build the DB on a network-allowed machine: `cve-lite advisories sync --output /path/to/advisories.db`",
|
|
23
23
|
];
|
|
24
24
|
}
|
|
25
|
+
const OFFLINE_FALLBACK_LINES = [
|
|
26
|
+
" cve-lite . --offline",
|
|
27
|
+
" (requires a local advisory DB - run `cve-lite advisories sync` to build one)",
|
|
28
|
+
];
|
|
29
|
+
export function rateLimitAdvisoryRequestHint() {
|
|
30
|
+
return [
|
|
31
|
+
"Hint: OSV API rate limit reached. Wait a moment and retry, or scan offline:",
|
|
32
|
+
...OFFLINE_FALLBACK_LINES,
|
|
33
|
+
];
|
|
34
|
+
}
|
|
35
|
+
export function serverAdvisoryRequestHint() {
|
|
36
|
+
return [
|
|
37
|
+
"Hint: OSV API may be temporarily unavailable. Wait a moment and retry, or scan offline:",
|
|
38
|
+
...OFFLINE_FALLBACK_LINES,
|
|
39
|
+
];
|
|
40
|
+
}
|
|
25
41
|
const SSL_ERROR_CODES = new Set([
|
|
26
42
|
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
27
43
|
"CERT_UNTRUSTED",
|
|
@@ -38,6 +54,19 @@ const SSL_ERROR_MESSAGE_FRAGMENTS = [
|
|
|
38
54
|
"certificate has expired",
|
|
39
55
|
"unable to verify the first certificate",
|
|
40
56
|
];
|
|
57
|
+
function finalErrorCause(message) {
|
|
58
|
+
const normalized = message.toLowerCase();
|
|
59
|
+
return normalized.split(":").pop()?.trim() ?? normalized;
|
|
60
|
+
}
|
|
61
|
+
function isOsvError(message) {
|
|
62
|
+
return message.toLowerCase().includes("osv");
|
|
63
|
+
}
|
|
64
|
+
function isRateLimitCause(finalCause) {
|
|
65
|
+
return /^429\b/.test(finalCause);
|
|
66
|
+
}
|
|
67
|
+
function isServerCause(finalCause) {
|
|
68
|
+
return /^5\d\d\b/.test(finalCause);
|
|
69
|
+
}
|
|
41
70
|
export function isSslCertificateError(error) {
|
|
42
71
|
if (!(error instanceof Error))
|
|
43
72
|
return false;
|
|
@@ -50,12 +79,26 @@ export function isSslCertificateError(error) {
|
|
|
50
79
|
const normalized = error.message.toLowerCase();
|
|
51
80
|
return SSL_ERROR_MESSAGE_FRAGMENTS.some(f => normalized.includes(f));
|
|
52
81
|
}
|
|
82
|
+
export function isRateLimitError(message) {
|
|
83
|
+
if (!isOsvError(message)) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return isRateLimitCause(finalErrorCause(message));
|
|
87
|
+
}
|
|
88
|
+
export function isServerError(message) {
|
|
89
|
+
if (!isOsvError(message)) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
return isServerCause(finalErrorCause(message));
|
|
93
|
+
}
|
|
53
94
|
export function isLikelyBlockedAdvisoryRequestError(message) {
|
|
54
|
-
if (!message
|
|
95
|
+
if (!isOsvError(message)) {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
const finalCause = finalErrorCause(message);
|
|
99
|
+
if (isRateLimitCause(finalCause) || isServerCause(finalCause)) {
|
|
55
100
|
return false;
|
|
56
101
|
}
|
|
57
|
-
const normalized = message.toLowerCase();
|
|
58
|
-
const finalCause = normalized.split(":").pop()?.trim() ?? normalized;
|
|
59
102
|
const blockedIndicators = [
|
|
60
103
|
"access denied",
|
|
61
104
|
"blocked",
|
|
@@ -81,5 +124,5 @@ export function isLikelyBlockedAdvisoryRequestError(message) {
|
|
|
81
124
|
if (blockedIndicators.some(indicator => finalCause.includes(indicator))) {
|
|
82
125
|
return true;
|
|
83
126
|
}
|
|
84
|
-
return /^(401|403|407|408|
|
|
127
|
+
return /^(401|403|407|408|451)\b/.test(finalCause);
|
|
85
128
|
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import YAML from "yaml";
|
|
4
|
+
export function readDirectDependencyNames(projectPath, prodOnly) {
|
|
5
|
+
const packageJsonPath = path.join(projectPath, "package.json");
|
|
6
|
+
if (!fs.existsSync(packageJsonPath)) {
|
|
7
|
+
return null;
|
|
8
|
+
}
|
|
9
|
+
try {
|
|
10
|
+
const directNames = new Set();
|
|
11
|
+
const rootManifest = readPackageJsonObject(packageJsonPath);
|
|
12
|
+
if (!rootManifest) {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
addDependencyNamesFromManifest(directNames, rootManifest, prodOnly);
|
|
16
|
+
const workspacePatterns = readWorkspacePatterns(rootManifest, projectPath);
|
|
17
|
+
for (const workspacePackageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, workspacePatterns)) {
|
|
18
|
+
const workspaceManifest = readPackageJsonObject(workspacePackageJsonPath);
|
|
19
|
+
if (!workspaceManifest)
|
|
20
|
+
continue;
|
|
21
|
+
addDependencyNamesFromManifest(directNames, workspaceManifest, prodOnly);
|
|
22
|
+
}
|
|
23
|
+
return directNames;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function readPackageJsonObject(filePath) {
|
|
30
|
+
try {
|
|
31
|
+
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
32
|
+
return raw && typeof raw === "object" ? raw : null;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function addDependencyNamesFromManifest(target, manifest, prodOnly) {
|
|
39
|
+
const sections = [
|
|
40
|
+
isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
|
|
41
|
+
isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
|
|
42
|
+
];
|
|
43
|
+
if (!prodOnly) {
|
|
44
|
+
sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
|
|
45
|
+
}
|
|
46
|
+
for (const section of sections) {
|
|
47
|
+
if (!section)
|
|
48
|
+
continue;
|
|
49
|
+
for (const name of Object.keys(section)) {
|
|
50
|
+
target.add(name);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function readWorkspacePatterns(manifest, projectPath) {
|
|
55
|
+
const workspaces = manifest.workspaces;
|
|
56
|
+
if (Array.isArray(workspaces)) {
|
|
57
|
+
return workspaces.filter((value) => typeof value === "string");
|
|
58
|
+
}
|
|
59
|
+
if (isRecord(workspaces) && Array.isArray(workspaces.packages)) {
|
|
60
|
+
return workspaces.packages.filter((value) => typeof value === "string");
|
|
61
|
+
}
|
|
62
|
+
const pnpmWorkspaceYamlPath = path.join(projectPath, "pnpm-workspace.yaml");
|
|
63
|
+
if (fs.existsSync(pnpmWorkspaceYamlPath)) {
|
|
64
|
+
try {
|
|
65
|
+
const parsed = YAML.parse(fs.readFileSync(pnpmWorkspaceYamlPath, "utf8"));
|
|
66
|
+
const packages = parsed?.packages;
|
|
67
|
+
if (Array.isArray(packages)) {
|
|
68
|
+
return packages.filter((value) => typeof value === "string");
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
// ignore
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return [];
|
|
76
|
+
}
|
|
77
|
+
function resolveWorkspacePackageJsonPaths(projectPath, patterns) {
|
|
78
|
+
const matches = new Set();
|
|
79
|
+
for (const pattern of patterns) {
|
|
80
|
+
const normalized = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
|
|
81
|
+
if (!normalized)
|
|
82
|
+
continue;
|
|
83
|
+
for (const relativeDir of expandWorkspacePattern(projectPath, normalized.split("/").filter(Boolean), "")) {
|
|
84
|
+
const packageJsonPath = path.join(projectPath, relativeDir, "package.json");
|
|
85
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
86
|
+
matches.add(packageJsonPath);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return [...matches];
|
|
91
|
+
}
|
|
92
|
+
function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
|
|
93
|
+
if (segments.length === 0) {
|
|
94
|
+
return currentRelativePath ? [currentRelativePath] : [];
|
|
95
|
+
}
|
|
96
|
+
const [segment, ...rest] = segments;
|
|
97
|
+
if (segment === "*") {
|
|
98
|
+
const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
|
|
99
|
+
let entries = [];
|
|
100
|
+
try {
|
|
101
|
+
entries = fs.readdirSync(baseDir, { withFileTypes: true });
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return [];
|
|
105
|
+
}
|
|
106
|
+
return entries
|
|
107
|
+
.filter(entry => entry.isDirectory())
|
|
108
|
+
.flatMap(entry => {
|
|
109
|
+
const nextRelativePath = currentRelativePath
|
|
110
|
+
? path.join(currentRelativePath, entry.name)
|
|
111
|
+
: entry.name;
|
|
112
|
+
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, segment) : segment;
|
|
116
|
+
const nextAbsolutePath = path.join(projectPath, nextRelativePath);
|
|
117
|
+
if (!fs.existsSync(nextAbsolutePath) || !fs.statSync(nextAbsolutePath).isDirectory()) {
|
|
118
|
+
return [];
|
|
119
|
+
}
|
|
120
|
+
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
|
|
121
|
+
}
|
|
122
|
+
export function isRecord(value) {
|
|
123
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
124
|
+
}
|
package/dist/utils/severity.js
CHANGED
|
@@ -1,3 +1,17 @@
|
|
|
1
|
+
export function countBySeverity(findings) {
|
|
2
|
+
const counts = {
|
|
3
|
+
none: 0,
|
|
4
|
+
low: 0,
|
|
5
|
+
medium: 0,
|
|
6
|
+
high: 0,
|
|
7
|
+
critical: 0,
|
|
8
|
+
unknown: 0,
|
|
9
|
+
};
|
|
10
|
+
for (const finding of findings) {
|
|
11
|
+
counts[finding.severity] += 1;
|
|
12
|
+
}
|
|
13
|
+
return counts;
|
|
14
|
+
}
|
|
1
15
|
export function severityToSarifLevel(severity) {
|
|
2
16
|
if (severity === "critical" || severity === "high")
|
|
3
17
|
return "error";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { chalk } from "./chalk.js";
|
|
2
|
+
export function formatAdvisoryDbFreshness(lastSyncAt) {
|
|
3
|
+
if (!lastSyncAt) {
|
|
4
|
+
return chalk.yellow("unknown");
|
|
5
|
+
}
|
|
6
|
+
const timestamp = Date.parse(lastSyncAt);
|
|
7
|
+
if (Number.isNaN(timestamp)) {
|
|
8
|
+
return chalk.yellow("unknown");
|
|
9
|
+
}
|
|
10
|
+
return `${relativeAge(timestamp)} ${chalk.gray(`(${lastSyncAt})`)}`;
|
|
11
|
+
}
|
|
12
|
+
export function relativeAge(timestamp) {
|
|
13
|
+
const deltaMs = Math.max(0, Date.now() - timestamp);
|
|
14
|
+
const minute = 60 * 1000;
|
|
15
|
+
const hour = 60 * minute;
|
|
16
|
+
const day = 24 * hour;
|
|
17
|
+
if (deltaMs < minute) {
|
|
18
|
+
return "just synced";
|
|
19
|
+
}
|
|
20
|
+
if (deltaMs < hour) {
|
|
21
|
+
const minutes = Math.floor(deltaMs / minute);
|
|
22
|
+
return `synced ${minutes} minute${minutes === 1 ? "" : "s"} ago`;
|
|
23
|
+
}
|
|
24
|
+
if (deltaMs < day) {
|
|
25
|
+
const hours = Math.floor(deltaMs / hour);
|
|
26
|
+
return `synced ${hours} hour${hours === 1 ? "" : "s"} ago`;
|
|
27
|
+
}
|
|
28
|
+
const days = Math.floor(deltaMs / day);
|
|
29
|
+
return `synced ${days} day${days === 1 ? "" : "s"} ago`;
|
|
30
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import { chalk, stripAnsi } from "./chalk.js";
|
|
5
|
+
import { getCliVersion } from "./version-info.js";
|
|
6
|
+
const NPM_REGISTRY_URL = "https://registry.npmjs.org/cve-lite-cli/latest";
|
|
7
|
+
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
|
8
|
+
const BOX_INNER_WIDTH = 50;
|
|
9
|
+
export function isNewer(latest, current) {
|
|
10
|
+
const parse = (v) => {
|
|
11
|
+
const parts = v.replace(/^v/, "").split(".").map(Number);
|
|
12
|
+
return parts.length === 3 && parts.every(n => !isNaN(n)) ? parts : [];
|
|
13
|
+
};
|
|
14
|
+
const l = parse(latest);
|
|
15
|
+
const c = parse(current);
|
|
16
|
+
if (l.length === 0 || c.length === 0)
|
|
17
|
+
return false;
|
|
18
|
+
if (l[0] !== c[0])
|
|
19
|
+
return l[0] > c[0];
|
|
20
|
+
if (l[1] !== c[1])
|
|
21
|
+
return l[1] > c[1];
|
|
22
|
+
return l[2] > c[2];
|
|
23
|
+
}
|
|
24
|
+
function getCacheFilePath(cacheDir) {
|
|
25
|
+
const dir = cacheDir ? path.resolve(cacheDir) : path.join(os.homedir(), ".cache", "cve-lite");
|
|
26
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
27
|
+
return path.join(dir, "update-check.json");
|
|
28
|
+
}
|
|
29
|
+
export function readCache(cacheDir) {
|
|
30
|
+
try {
|
|
31
|
+
const raw = fs.readFileSync(getCacheFilePath(cacheDir), "utf8");
|
|
32
|
+
const parsed = JSON.parse(raw);
|
|
33
|
+
if (typeof parsed.latestVersion === "string" && typeof parsed.checkedAt === "string") {
|
|
34
|
+
return { latestVersion: parsed.latestVersion, checkedAt: parsed.checkedAt };
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export function writeCache(latestVersion, cacheDir) {
|
|
43
|
+
try {
|
|
44
|
+
fs.writeFileSync(getCacheFilePath(cacheDir), JSON.stringify({ latestVersion, checkedAt: new Date().toISOString() }), "utf8");
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
// silently ignore write failures
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
export function isCacheStale(cache) {
|
|
51
|
+
return Date.now() - new Date(cache.checkedAt).getTime() > CACHE_TTL_MS;
|
|
52
|
+
}
|
|
53
|
+
function fetchAndUpdateCache(cacheDir) {
|
|
54
|
+
void fetch(NPM_REGISTRY_URL)
|
|
55
|
+
.then(res => {
|
|
56
|
+
if (!res.ok)
|
|
57
|
+
return undefined;
|
|
58
|
+
return res.json();
|
|
59
|
+
})
|
|
60
|
+
.then((data) => {
|
|
61
|
+
if (data === undefined)
|
|
62
|
+
return;
|
|
63
|
+
if (data !== null &&
|
|
64
|
+
typeof data === "object" &&
|
|
65
|
+
"version" in data &&
|
|
66
|
+
typeof data.version === "string") {
|
|
67
|
+
writeCache(data.version, cacheDir);
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
.catch(() => { });
|
|
71
|
+
}
|
|
72
|
+
function renderBox(current, latest) {
|
|
73
|
+
const top = chalk.yellow("╭" + "─".repeat(BOX_INNER_WIDTH) + "╮");
|
|
74
|
+
const empty = chalk.yellow("│") + " ".repeat(BOX_INNER_WIDTH) + chalk.yellow("│");
|
|
75
|
+
const bottom = chalk.yellow("╰" + "─".repeat(BOX_INNER_WIDTH) + "╯");
|
|
76
|
+
const line1 = ` ${chalk.bold.yellow("Update available!")} ${chalk.gray(current)} ${chalk.yellow("→")} ${chalk.green(latest)}`;
|
|
77
|
+
const line2 = ` ${chalk.white("Run: npm install -g cve-lite-cli")}`;
|
|
78
|
+
const padLine = (content) => {
|
|
79
|
+
const visual = stripAnsi(content).length;
|
|
80
|
+
return chalk.yellow("│") + content + " ".repeat(Math.max(0, BOX_INNER_WIDTH - visual)) + chalk.yellow("│");
|
|
81
|
+
};
|
|
82
|
+
return [top, empty, padLine(line1), padLine(line2), empty, bottom].join("\n");
|
|
83
|
+
}
|
|
84
|
+
export function checkForUpdate(options) {
|
|
85
|
+
if (options?.json)
|
|
86
|
+
return;
|
|
87
|
+
if (options?.offline || options?.offlineDb)
|
|
88
|
+
return;
|
|
89
|
+
if (process.env["CI"])
|
|
90
|
+
return;
|
|
91
|
+
if (process.env["NO_UPDATE_NOTIFIER"])
|
|
92
|
+
return;
|
|
93
|
+
const cache = readCache(options?.cacheDir);
|
|
94
|
+
const current = getCliVersion();
|
|
95
|
+
if (cache !== null && isNewer(cache.latestVersion, current)) {
|
|
96
|
+
console.log(renderBox(current, cache.latestVersion));
|
|
97
|
+
console.log("");
|
|
98
|
+
}
|
|
99
|
+
if (cache === null || isCacheStale(cache)) {
|
|
100
|
+
fetchAndUpdateCache(options?.cacheDir);
|
|
101
|
+
}
|
|
102
|
+
}
|