cve-lite-cli 1.35.0 → 1.36.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 +34 -0
- package/dist/osv/cache.js +19 -12
- package/dist/output/printers.js +33 -18
- package/dist/parsers/index.js +69 -10
- package/dist/remediation/fix-commands.js +28 -13
- package/dist/scanner.js +29 -8
- package/dist/utils/network.js +4 -0
- package/package.json +2 -1
- package/scripts/pr-scan-delta.mjs +315 -0
package/README.md
CHANGED
|
@@ -39,6 +39,40 @@
|
|
|
39
39
|
|
|
40
40
|
<br/>
|
|
41
41
|
|
|
42
|
+
<p>
|
|
43
|
+
🏆 <strong>Ranked #5</strong> in <a href="https://www.helpnetsecurity.com/2026/07/08/20-latest-open-source-cybersecurity-tools/">Help Net Security's 20 open-source security tools</a> ·
|
|
44
|
+
<strong><a href="https://www.bestpractices.dev/projects/12731">OpenSSF Best Practices</a></strong>
|
|
45
|
+
</p>
|
|
46
|
+
|
|
47
|
+
<p>
|
|
48
|
+
Covered by
|
|
49
|
+
<a href="https://www.theregister.com/security/2026/06/23/sniff-out-stale-ai-override-advice-with-this-open-source-cli/5259853"><strong>The Register</strong></a> ·
|
|
50
|
+
<a href="https://www.csoonline.com/article/4176701/as-ai-speeds-coding-cve-lite-cli-keeps-security-deliberately-ai-free.html"><strong>CSO Online</strong></a> ·
|
|
51
|
+
<a href="https://www.securityweek.com/owasp-incubator-project-helps-developers-find-and-fix-vulnerable-dependencies-in-seconds/"><strong>SecurityWeek</strong></a> ·
|
|
52
|
+
<a href="https://sdtimes.com/security/shift-left-how-cve-lite-cli-is-transforming-developer-security/"><strong>SD Times</strong></a> ·
|
|
53
|
+
<a href="https://devops.com/owasp-adopts-cve-lite-cli-to-boost-dependency-scanning/"><strong>DevOps.com</strong></a> ·
|
|
54
|
+
<a href="https://www.reversinglabs.com/blog/cve-lite-cli"><strong>ReversingLabs</strong></a>
|
|
55
|
+
</p>
|
|
56
|
+
|
|
57
|
+
<p>
|
|
58
|
+
<sub>Running in CI at
|
|
59
|
+
<a href="https://github.com/solidjs/solid/blob/main/.github/workflows/cve-lite.yml"><strong>SolidJS</strong></a>,
|
|
60
|
+
<a href="https://github.com/bcgov/nr-waste-plus/blob/main/.github/workflows/analysis.yml"><strong>the Government of British Columbia</strong></a> as a required merge gate,
|
|
61
|
+
<a href="https://github.com/etalab-ia/parcours-rag/blob/main/package.json">French government digital services (<strong>DINUM</strong>)</a>, and
|
|
62
|
+
<a href="https://github.com/fabian-hiller/valibot"><strong>Valibot</strong></a>.<br/>
|
|
63
|
+
In production use in France, Canada, Germany, Thailand and China.</sub>
|
|
64
|
+
</p>
|
|
65
|
+
|
|
66
|
+
<br/>
|
|
67
|
+
|
|
68
|
+
<p>
|
|
69
|
+
⚡ <strong>One command. No account, no API key, nothing leaves your machine.</strong>
|
|
70
|
+
<code>npx cve-lite-cli .</code>
|
|
71
|
+
<a href="#quick-start"><strong>→ Quick Start</strong></a>
|
|
72
|
+
</p>
|
|
73
|
+
|
|
74
|
+
<br/>
|
|
75
|
+
|
|
42
76
|
<p>
|
|
43
77
|
<a href="#quick-start">Quick Start</a> •
|
|
44
78
|
<a href="#usage">Usage</a> •
|
package/dist/osv/cache.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import { CACHE_TTL_MS } from "../constants.js";
|
|
5
5
|
function createEmptyCache() {
|
|
6
|
-
return { version:
|
|
6
|
+
return { version: 6, createdAt: new Date().toISOString(), entries: {}, queryEntries: {}, npmVersionEntries: {}, npmAdvisoryEntries: {} };
|
|
7
7
|
}
|
|
8
8
|
// v4 stores detail records as { vuln, cachedAt }. v1-v3 stored the OsvVuln (or
|
|
9
9
|
// null for a known-empty lookup) directly, with no timestamp. Legacy records are
|
|
@@ -53,12 +53,15 @@ export function loadCache(cacheDirOverride, debugLog) {
|
|
|
53
53
|
debugLog?.("Cache load failed", { path: filePath, reason: "invalid root object" });
|
|
54
54
|
return createEmptyCache();
|
|
55
55
|
}
|
|
56
|
-
|
|
56
|
+
// Compare cumulatively rather than listing each version. An explicit list has to
|
|
57
|
+
// be extended at every bump, and missing one silently discards that whole section
|
|
58
|
+
// of the cache instead of failing.
|
|
59
|
+
const version = typeof parsed.version === "number" ? parsed.version : 0;
|
|
57
60
|
const rawEntries = parsed.entries;
|
|
58
|
-
// Detail records: v4
|
|
61
|
+
// Detail records: v4 onward already carry { vuln, cachedAt }; v1-v3 stored the record
|
|
59
62
|
// directly and are wrapped (and backdated) so the TTL applies uniformly.
|
|
60
|
-
const entries = version
|
|
61
|
-
// Query records: v2 stored string[]; v3
|
|
63
|
+
const entries = version >= 4 ? readDetailEntries(rawEntries) : wrapLegacyDetailEntries(rawEntries);
|
|
64
|
+
// Query records: v2 stored string[]; v3 onward store { vulnIds, cachedAt }; v1/unknown had none.
|
|
62
65
|
const queryEntries = {};
|
|
63
66
|
if (version === 2) {
|
|
64
67
|
const rawQuery = parsed.queryEntries;
|
|
@@ -67,7 +70,7 @@ export function loadCache(cacheDirOverride, debugLog) {
|
|
|
67
70
|
queryEntries[key] = { vulnIds: Array.isArray(vulnIds) ? vulnIds : [], cachedAt: epoch };
|
|
68
71
|
}
|
|
69
72
|
}
|
|
70
|
-
else if (version
|
|
73
|
+
else if (version >= 3) {
|
|
71
74
|
const rawQuery = parsed.queryEntries;
|
|
72
75
|
for (const [key, value] of Object.entries(rawQuery ?? {})) {
|
|
73
76
|
if (value && typeof value === "object" && "vulnIds" in value && "cachedAt" in value) {
|
|
@@ -77,7 +80,7 @@ export function loadCache(cacheDirOverride, debugLog) {
|
|
|
77
80
|
}
|
|
78
81
|
// npm publish-date records exist from v3 onward.
|
|
79
82
|
const npmVersionEntries = {};
|
|
80
|
-
if (version
|
|
83
|
+
if (version >= 3) {
|
|
81
84
|
const rawNpmVersions = parsed.npmVersionEntries;
|
|
82
85
|
for (const [key, value] of Object.entries(rawNpmVersions ?? {})) {
|
|
83
86
|
if (value && typeof value === "object" && "publishedAt" in value && "cachedAt" in value) {
|
|
@@ -85,18 +88,22 @@ export function loadCache(cacheDirOverride, debugLog) {
|
|
|
85
88
|
}
|
|
86
89
|
}
|
|
87
90
|
}
|
|
88
|
-
// npm advisory entries exist from v5 onward.
|
|
91
|
+
// npm advisory entries exist from v5 onward, but v5 stored ids only. Those
|
|
92
|
+
// records cannot be reused: the advisory detail they refer to lives in the npm
|
|
93
|
+
// registry namespace, so a later scan reading a v5 record had ids it could not
|
|
94
|
+
// resolve and silently dropped them from the findings. v6 stores the advisories
|
|
95
|
+
// themselves; v5 records are discarded so the next scan refetches them.
|
|
89
96
|
const npmAdvisoryEntries = {};
|
|
90
|
-
if (version
|
|
97
|
+
if (version >= 6) {
|
|
91
98
|
const raw = parsed.npmAdvisoryEntries;
|
|
92
99
|
for (const [key, value] of Object.entries(raw ?? {})) {
|
|
93
|
-
if (value && typeof value === "object" && "
|
|
100
|
+
if (value && typeof value === "object" && "vulns" in value && "cachedAt" in value) {
|
|
94
101
|
npmAdvisoryEntries[key] = value;
|
|
95
102
|
}
|
|
96
103
|
}
|
|
97
104
|
}
|
|
98
105
|
const loaded = {
|
|
99
|
-
version:
|
|
106
|
+
version: 6,
|
|
100
107
|
createdAt: String(parsed.createdAt ?? new Date().toISOString()),
|
|
101
108
|
entries,
|
|
102
109
|
queryEntries,
|
|
@@ -107,7 +114,7 @@ export function loadCache(cacheDirOverride, debugLog) {
|
|
|
107
114
|
path: filePath,
|
|
108
115
|
queryEntries: Object.keys(loaded.queryEntries).length,
|
|
109
116
|
detailEntries: Object.keys(loaded.entries).length,
|
|
110
|
-
...(version ===
|
|
117
|
+
...(version === 6 ? {} : { migratedFrom: version || "unknown" }),
|
|
111
118
|
});
|
|
112
119
|
return loaded;
|
|
113
120
|
}
|
package/dist/output/printers.js
CHANGED
|
@@ -497,6 +497,26 @@ export function printTable(findings, threshold, skippedKeys, plan) {
|
|
|
497
497
|
console.log(chalk.gray("Tip: use --all to include low findings, or --min-severity high to focus only on urgent issues."));
|
|
498
498
|
}
|
|
499
499
|
}
|
|
500
|
+
/**
|
|
501
|
+
* Builds the one-sentence verdict both output modes close with.
|
|
502
|
+
*
|
|
503
|
+
* Compact and verbose used to construct this separately, 350 lines apart, and had
|
|
504
|
+
* drifted: compact reported critical+high while verbose reported every finding, so
|
|
505
|
+
* the same scan closed with "7 urgent issues" or "11 vulnerabilities" depending on
|
|
506
|
+
* the flag. Verbose's noun was wrong too - findings are vulnerable packages, and
|
|
507
|
+
* that scan carried 94 advisories across its 11 packages (#1168).
|
|
508
|
+
*/
|
|
509
|
+
function buildScanVerdict(findingCount, critical, high) {
|
|
510
|
+
const urgentCount = critical + high;
|
|
511
|
+
const packages = `${findingCount} vulnerable ${pluralize(findingCount, "package")}`;
|
|
512
|
+
// Only name the severities actually present. "(0 critical, 1 high)" reads as noise.
|
|
513
|
+
const breakdown = [
|
|
514
|
+
critical > 0 ? `${critical} critical` : null,
|
|
515
|
+
high > 0 ? `${high} high` : null,
|
|
516
|
+
].filter(Boolean).join(", ");
|
|
517
|
+
const urgentNote = urgentCount > 0 ? `, ${urgentCount} urgent (${breakdown})` : "";
|
|
518
|
+
return { text: `${packages}${urgentNote}`, urgent: urgentCount > 0 };
|
|
519
|
+
}
|
|
500
520
|
export function printFinalStatus(findings, overrideCount = 0, completeness) {
|
|
501
521
|
console.log("");
|
|
502
522
|
console.log(chalk.gray("────────────────────────────────"));
|
|
@@ -521,19 +541,17 @@ export function printFinalStatus(findings, overrideCount = 0, completeness) {
|
|
|
521
541
|
else {
|
|
522
542
|
const criticalCount = findings.filter(f => f.severity === "critical").length;
|
|
523
543
|
const highCount = findings.filter(f => f.severity === "high").length;
|
|
524
|
-
const
|
|
525
|
-
const
|
|
544
|
+
const verdict = buildScanVerdict(findings.length, criticalCount, highCount);
|
|
545
|
+
const action = verdict.urgent ? "Start with the priority fixes above." : "Review the suggested fix plan above.";
|
|
546
|
+
const renderStatus = verdict.urgent ? chalk.redBright : chalk.yellow;
|
|
526
547
|
if (hasDetectionGap) {
|
|
527
|
-
|
|
528
|
-
const action = urgent ? "Start with the priority fixes above." : "Review the suggested fix plan above.";
|
|
529
|
-
const renderStatus = urgent ? chalk.redBright : chalk.yellow;
|
|
530
|
-
console.log(renderStatus(`⚠ Partial scan: ${label} found${overrideSuffix}${severityNote}. Vulnerability findings may be incomplete. ${action}`));
|
|
548
|
+
console.log(renderStatus(`⚠ Partial scan: ${verdict.text}${overrideSuffix}. Vulnerability findings may be incomplete. ${action}`));
|
|
531
549
|
}
|
|
532
|
-
else if (urgent) {
|
|
533
|
-
console.log(chalk.redBright(`✖ Scan complete. ${
|
|
550
|
+
else if (verdict.urgent) {
|
|
551
|
+
console.log(chalk.redBright(`✖ Scan complete. ${verdict.text}${overrideSuffix}. ${action}`));
|
|
534
552
|
}
|
|
535
553
|
else {
|
|
536
|
-
console.log(chalk.yellow(`▲ Scan complete. ${
|
|
554
|
+
console.log(chalk.yellow(`▲ Scan complete. ${verdict.text}${overrideSuffix}. ${action}`));
|
|
537
555
|
}
|
|
538
556
|
}
|
|
539
557
|
if (hasRemediationGap) {
|
|
@@ -833,19 +851,16 @@ export function printCompactOutput(findings, scanInput, options) {
|
|
|
833
851
|
console.log("");
|
|
834
852
|
}
|
|
835
853
|
// Footer
|
|
836
|
-
const
|
|
854
|
+
const verdict = buildScanVerdict(findings.length, counts.critical, counts.high);
|
|
855
|
+
const renderStatus = verdict.urgent ? chalk.redBright : chalk.yellow;
|
|
837
856
|
if (hasDetectionGap) {
|
|
838
|
-
|
|
839
|
-
? `${urgentCount} urgent ${pluralize(urgentCount, "issue")} found`
|
|
840
|
-
: `${findings.length} ${pluralize(findings.length, "issue")} found`;
|
|
841
|
-
const renderStatus = urgentCount > 0 ? chalk.redBright : chalk.yellow;
|
|
842
|
-
console.log(renderStatus(`⚠ Partial scan: ${label}. Vulnerability findings may be incomplete.`));
|
|
857
|
+
console.log(renderStatus(`⚠ Partial scan: ${verdict.text}. Vulnerability findings may be incomplete.`));
|
|
843
858
|
}
|
|
844
|
-
else if (
|
|
845
|
-
console.log(chalk.redBright(`✖ Scan complete. ${
|
|
859
|
+
else if (verdict.urgent) {
|
|
860
|
+
console.log(chalk.redBright(`✖ Scan complete. ${verdict.text}.`));
|
|
846
861
|
}
|
|
847
862
|
else {
|
|
848
|
-
console.log(chalk.yellow(`▲ Scan complete. ${
|
|
863
|
+
console.log(chalk.yellow(`▲ Scan complete. ${verdict.text}.`));
|
|
849
864
|
}
|
|
850
865
|
printIncompleteDiagnostics(options?.completeness);
|
|
851
866
|
if (hasRemediationGap) {
|
package/dist/parsers/index.js
CHANGED
|
@@ -47,15 +47,74 @@ function toLockfileName(filePath) {
|
|
|
47
47
|
const name = path.basename(filePath);
|
|
48
48
|
return LOCKFILE_NAMES.find(candidate => candidate === name) ?? null;
|
|
49
49
|
}
|
|
50
|
-
/**
|
|
50
|
+
/** The lockfile each package manager writes, for reading `packageManager`. */
|
|
51
|
+
const PACKAGE_MANAGER_LOCKFILES = {
|
|
52
|
+
npm: "package-lock.json",
|
|
53
|
+
pnpm: "pnpm-lock.yaml",
|
|
54
|
+
yarn: "yarn.lock",
|
|
55
|
+
bun: "bun.lock",
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The package manager a project declares for itself, from the `packageManager`
|
|
59
|
+
* field npm and Corepack already standardise on. Returns the bare name, so
|
|
60
|
+
* "pnpm@10.14.0" gives "pnpm".
|
|
61
|
+
*/
|
|
62
|
+
function readDeclaredPackageManager(projectRoot) {
|
|
63
|
+
const manifest = safeReadText(path.join(projectRoot, "package.json"));
|
|
64
|
+
if (manifest === null)
|
|
65
|
+
return null;
|
|
66
|
+
try {
|
|
67
|
+
const declared = JSON.parse(manifest).packageManager;
|
|
68
|
+
if (typeof declared !== "string")
|
|
69
|
+
return null;
|
|
70
|
+
const name = declared.split("@")[0]?.trim().toLowerCase();
|
|
71
|
+
return name && name in PACKAGE_MANAGER_LOCKFILES ? name : null;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
// A manifest we cannot parse tells us nothing about the package manager.
|
|
75
|
+
// Lockfile selection falls back to precedence rather than failing here.
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Picks the lockfile at the repo root.
|
|
81
|
+
*
|
|
82
|
+
* A project that declares `packageManager` has already answered this, so that
|
|
83
|
+
* wins. Filename precedence is only a guess for when it has not, and guessing
|
|
84
|
+
* went badly: a stale `package-lock.json` left behind by a migration outranked
|
|
85
|
+
* the `pnpm-lock.yaml` actually describing the project, so a 504-package tree
|
|
86
|
+
* scanned as one package and reported no known vulnerabilities (#1159).
|
|
87
|
+
*/
|
|
51
88
|
function findRootLockfile(projectRoot) {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
89
|
+
const present = LOCKFILE_PRIORITY_ROOT.filter(name => fs.existsSync(path.join(projectRoot, name)));
|
|
90
|
+
if (present.length === 0)
|
|
91
|
+
return null;
|
|
92
|
+
const declared = readDeclaredPackageManager(projectRoot);
|
|
93
|
+
const declaredLockfile = declared ? PACKAGE_MANAGER_LOCKFILES[declared] : undefined;
|
|
94
|
+
const chosen = declaredLockfile && present.includes(declaredLockfile) ? declaredLockfile : present[0];
|
|
95
|
+
return {
|
|
96
|
+
filePath: path.join(projectRoot, chosen),
|
|
97
|
+
name: chosen,
|
|
98
|
+
skipped: present.filter(name => name !== chosen),
|
|
99
|
+
declaredBy: chosen === declaredLockfile ? declared : undefined,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/** Says which lockfile was used and why, whenever the root held more than one. */
|
|
103
|
+
function describeLockfileChoice(found) {
|
|
104
|
+
if (found.skipped.length === 0)
|
|
105
|
+
return [];
|
|
106
|
+
const others = found.skipped.join(", ");
|
|
107
|
+
return found.declaredBy
|
|
108
|
+
? [`Root also contains ${others}. Used ${found.name} because package.json declares packageManager "${found.declaredBy}".`]
|
|
109
|
+
: [`Root also contains ${others}. Used ${found.name} by precedence; no packageManager field declared.`];
|
|
110
|
+
}
|
|
111
|
+
function readInput(filePath, load) {
|
|
112
|
+
try {
|
|
113
|
+
return load();
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
throw new Error(`Failed to read ${filePath}: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
|
|
57
117
|
}
|
|
58
|
-
return null;
|
|
59
118
|
}
|
|
60
119
|
function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
|
|
61
120
|
const handler = LOCKFILE_HANDLERS[name];
|
|
@@ -63,7 +122,7 @@ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
|
|
|
63
122
|
mode: "resolved-lockfile",
|
|
64
123
|
source: handler.source,
|
|
65
124
|
filePath,
|
|
66
|
-
packages: handler.load(filePath, prodOnly),
|
|
125
|
+
packages: readInput(filePath, () => handler.load(filePath, prodOnly)),
|
|
67
126
|
notes: [
|
|
68
127
|
`Scanned resolved dependency versions from ${label}.`,
|
|
69
128
|
handler.pathNote,
|
|
@@ -76,7 +135,7 @@ function buildLockfileScan(filePath, name, prodOnly, label, extraNotes) {
|
|
|
76
135
|
export function loadPackages(projectRoot, prodOnly, maxDepth) {
|
|
77
136
|
const rootLockfile = findRootLockfile(projectRoot);
|
|
78
137
|
if (rootLockfile !== null) {
|
|
79
|
-
return buildLockfileScan(rootLockfile.filePath, rootLockfile.name, prodOnly, rootLockfile.name,
|
|
138
|
+
return buildLockfileScan(rootLockfile.filePath, rootLockfile.name, prodOnly, rootLockfile.name, describeLockfileChoice(rootLockfile));
|
|
80
139
|
}
|
|
81
140
|
const discoveredLockfiles = findFiles(projectRoot, [...LOCKFILE_NAMES], maxDepth);
|
|
82
141
|
if (discoveredLockfiles.length > 0) {
|
|
@@ -88,7 +147,7 @@ export function loadPackages(projectRoot, prodOnly, maxDepth) {
|
|
|
88
147
|
}
|
|
89
148
|
const packageJsonPath = findNearestPackageJson(projectRoot, maxDepth);
|
|
90
149
|
if (packageJsonPath) {
|
|
91
|
-
const manifestResult = loadFromPackageJson(packageJsonPath, prodOnly);
|
|
150
|
+
const manifestResult = readInput(packageJsonPath, () => loadFromPackageJson(packageJsonPath, prodOnly));
|
|
92
151
|
const warnings = [
|
|
93
152
|
"No supported lockfile was found, so the scanner fell back to package.json.",
|
|
94
153
|
"Manifest fallback can only check direct dependencies pinned to exact versions."
|
|
@@ -59,7 +59,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
59
59
|
return relDelta;
|
|
60
60
|
return a.pkg.name.localeCompare(b.pkg.name);
|
|
61
61
|
});
|
|
62
|
-
const
|
|
62
|
+
const targetsByKey = new Map();
|
|
63
63
|
const skippedByKey = new Map();
|
|
64
64
|
const orderedFindings = [
|
|
65
65
|
...prioritizedFindings,
|
|
@@ -106,7 +106,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
106
106
|
isUpgradeTarget(finding.pkg.version, directTarget) &&
|
|
107
107
|
validatedFieldOk) {
|
|
108
108
|
const pkgWorkspaces = workspaceMap.get(finding.pkg.name)?.filter(w => w !== ".") ?? [];
|
|
109
|
-
upsertTarget(
|
|
109
|
+
upsertTarget(targetsByKey, finding, {
|
|
110
110
|
package: finding.pkg.name,
|
|
111
111
|
currentVersion: finding.pkg.version,
|
|
112
112
|
targetVersion: directTarget,
|
|
@@ -171,7 +171,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
171
171
|
if (packageManager === "npm" &&
|
|
172
172
|
finding.relationship === "transitive" &&
|
|
173
173
|
finding.recommendedNpmTransitiveRemediation?.kind === "update-parent-within-range") {
|
|
174
|
-
upsertTarget(
|
|
174
|
+
upsertTarget(targetsByKey, finding, {
|
|
175
175
|
package: finding.recommendedNpmTransitiveRemediation.package,
|
|
176
176
|
currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
|
|
177
177
|
targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
|
|
@@ -199,7 +199,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
199
199
|
? finding.chainResolution
|
|
200
200
|
: null;
|
|
201
201
|
const npmParentUpgradeWorkspaces = workspaceMap.get(finding.recommendedNpmTransitiveRemediation.package)?.filter(w => w !== ".") ?? [];
|
|
202
|
-
upsertTarget(
|
|
202
|
+
upsertTarget(targetsByKey, finding, {
|
|
203
203
|
package: finding.recommendedNpmTransitiveRemediation.package,
|
|
204
204
|
currentVersion: finding.recommendedNpmTransitiveRemediation.currentVersion,
|
|
205
205
|
targetVersion: finding.recommendedNpmTransitiveRemediation.targetVersion,
|
|
@@ -231,7 +231,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
231
231
|
? finding.chainResolution
|
|
232
232
|
: null;
|
|
233
233
|
const parentUpgradeWorkspaces = workspaceMap.get(finding.recommendedParentUpgrade.package)?.filter(w => w !== ".") ?? [];
|
|
234
|
-
upsertTarget(
|
|
234
|
+
upsertTarget(targetsByKey, finding, {
|
|
235
235
|
package: finding.recommendedParentUpgrade.package,
|
|
236
236
|
currentVersion: finding.recommendedParentUpgrade.currentVersion,
|
|
237
237
|
targetVersion: finding.recommendedParentUpgrade.targetVersion,
|
|
@@ -273,7 +273,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
273
273
|
: packageManager === "yarn"
|
|
274
274
|
? `yarn upgrade ${finding.pkg.name}`
|
|
275
275
|
: `bun update ${finding.pkg.name}`;
|
|
276
|
-
upsertTarget(
|
|
276
|
+
upsertTarget(targetsByKey, finding, {
|
|
277
277
|
package: finding.pkg.name,
|
|
278
278
|
currentVersion: finding.pkg.version,
|
|
279
279
|
targetVersion: finding.recommendedNpmTransitiveRemediation.targetChildVersion,
|
|
@@ -296,7 +296,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
296
296
|
const isDev = devLookup.get(`${finding.chainResolution.directDep}@${finding.chainResolution.directDepCurrentVersion}`) ?? false;
|
|
297
297
|
const coverage = calculatePathCoverage(finding.dependencyPaths, [finding.chainResolution.directDep]);
|
|
298
298
|
const chainWorkspaces = workspaceMap.get(finding.chainResolution.directDep)?.filter(w => w !== ".") ?? [];
|
|
299
|
-
upsertTarget(
|
|
299
|
+
upsertTarget(targetsByKey, finding, {
|
|
300
300
|
package: finding.chainResolution.directDep,
|
|
301
301
|
currentVersion: finding.chainResolution.directDepCurrentVersion,
|
|
302
302
|
targetVersion: finding.chainResolution.targetVersion,
|
|
@@ -337,7 +337,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
|
|
|
337
337
|
: "No confident automatic fix command could be generated for this issue.",
|
|
338
338
|
});
|
|
339
339
|
}
|
|
340
|
-
const targets = [...
|
|
340
|
+
const targets = [...targetsByKey.values()].sort((a, b) => {
|
|
341
341
|
const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
|
|
342
342
|
if (sevDelta !== 0)
|
|
343
343
|
return sevDelta;
|
|
@@ -532,10 +532,25 @@ function packageManagerSourceLabel(scanInput) {
|
|
|
532
532
|
return "bun.lock";
|
|
533
533
|
return scanInput.source;
|
|
534
534
|
}
|
|
535
|
-
|
|
536
|
-
|
|
535
|
+
// Install targets (direct / parent-upgrade) all mean "install <package>@<targetVersion>",
|
|
536
|
+
// so findings that land on the same package merge into one target and the higher
|
|
537
|
+
// version wins. A parent-update target means something else: "refresh <vulnerable
|
|
538
|
+
// child> within <package>'s declared range", and its targetVersion is the CHILD's
|
|
539
|
+
// version, not <package>'s. Merging it with an install target for the same package
|
|
540
|
+
// compares versions of two different packages, and the child's version can end up
|
|
541
|
+
// pinned onto the parent (`npm install axios@4.0.6`, where 4.0.6 is form-data's
|
|
542
|
+
// version - #1007). Keep parent-update targets in their own keyspace, per child, so
|
|
543
|
+
// they only ever merge with a refresh of the same child through the same package.
|
|
544
|
+
function targetKey(finding, target) {
|
|
545
|
+
return target.kind === "parent-update"
|
|
546
|
+
? `parent-update:${target.package}>${finding.pkg.name}`
|
|
547
|
+
: `install:${target.package}`;
|
|
548
|
+
}
|
|
549
|
+
function upsertTarget(targetsByKey, finding, next) {
|
|
550
|
+
const key = targetKey(finding, next);
|
|
551
|
+
const existing = targetsByKey.get(key);
|
|
537
552
|
if (!existing) {
|
|
538
|
-
|
|
553
|
+
targetsByKey.set(key, next);
|
|
539
554
|
return;
|
|
540
555
|
}
|
|
541
556
|
const merged = {
|
|
@@ -600,7 +615,7 @@ function upsertTarget(targetsByPackage, next) {
|
|
|
600
615
|
merged.adjustmentNote = existing.adjustmentNote ?? null;
|
|
601
616
|
merged.advisoryVersion = existing.advisoryVersion ?? next.advisoryVersion ?? null;
|
|
602
617
|
}
|
|
603
|
-
|
|
618
|
+
targetsByKey.set(key, merged);
|
|
604
619
|
return;
|
|
605
620
|
}
|
|
606
621
|
if (next.kind === "direct" && existing.kind !== "direct") {
|
|
@@ -612,7 +627,7 @@ function upsertTarget(targetsByPackage, next) {
|
|
|
612
627
|
merged.knownVulnerableVersions = next.knownVulnerableVersions ?? merged.knownVulnerableVersions ?? null;
|
|
613
628
|
merged.fixVersionPublishedAt = next.fixVersionPublishedAt ?? merged.fixVersionPublishedAt ?? null;
|
|
614
629
|
}
|
|
615
|
-
|
|
630
|
+
targetsByKey.set(key, merged);
|
|
616
631
|
}
|
|
617
632
|
function buildParentUpgradeReason(finding, coverage) {
|
|
618
633
|
const coveredPath = coverage.coveredPaths[0];
|
package/dist/scanner.js
CHANGED
|
@@ -24,6 +24,12 @@ import { pluralize } from "./utils/string.js";
|
|
|
24
24
|
import { extractErrorMessage } from "./utils/network.js";
|
|
25
25
|
import { logWarn } from "./output/formatters.js";
|
|
26
26
|
import { formatDiagnosticMessage } from "./scan/completeness.js";
|
|
27
|
+
/**
|
|
28
|
+
* Advisory id namespaces OSV does not serve. Ids with these prefixes come from
|
|
29
|
+
* a different source, so OSV failing to resolve them is expected and must not
|
|
30
|
+
* be reported as missing detail.
|
|
31
|
+
*/
|
|
32
|
+
const OSV_FOREIGN_ID_PREFIXES = ["NPM-"];
|
|
27
33
|
export function createAdvisorySource(options) {
|
|
28
34
|
const offline = !!options?.offline || !!options?.offlineDb;
|
|
29
35
|
if (offline) {
|
|
@@ -197,9 +203,17 @@ export async function scanPackages(packages, batchSize, options, context, debugL
|
|
|
197
203
|
const key = getPackageCacheKey(pkg);
|
|
198
204
|
const cached = cache.npmAdvisoryEntries[key];
|
|
199
205
|
if (cached && !isEntryStale(cached, nowMs)) {
|
|
200
|
-
const
|
|
201
|
-
if (
|
|
202
|
-
results.push({ pkg, vulnIds:
|
|
206
|
+
const newCachedVulns = cached.vulns.filter(v => !existingVulnIds.has(v.id));
|
|
207
|
+
if (newCachedVulns.length > 0) {
|
|
208
|
+
results.push({ pkg, vulnIds: newCachedVulns.map(v => v.id) });
|
|
209
|
+
// Seed the detail map from the cache. These advisories come from the npm
|
|
210
|
+
// registry namespace, so nothing downstream can resolve them: OSV returns
|
|
211
|
+
// 404 for an NPM-prefixed id by definition. Restoring only the ids left
|
|
212
|
+
// them unresolvable, which dropped them from the CVE tally on every scan
|
|
213
|
+
// after the first and reported them as detail confirmed missing.
|
|
214
|
+
for (const vuln of newCachedVulns) {
|
|
215
|
+
vulnMap.set(vuln.id, vuln);
|
|
216
|
+
}
|
|
203
217
|
}
|
|
204
218
|
}
|
|
205
219
|
else {
|
|
@@ -215,10 +229,11 @@ export async function scanPackages(packages, batchSize, options, context, debugL
|
|
|
215
229
|
for (const pkg of uncachedForNpm) {
|
|
216
230
|
const found = npmResults.find(r => r.pkg.name === pkg.name && r.pkg.version === pkg.version);
|
|
217
231
|
const vulns = found?.vulns ?? [];
|
|
218
|
-
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
232
|
+
// Store the full advisories in cache, not just their ids, so a later scan
|
|
233
|
+
// can restore the detail rather than going looking for it in OSV, which
|
|
234
|
+
// does not hold this namespace. Only genuinely new vulns go into results -
|
|
235
|
+
// ones OSV did not already surface.
|
|
236
|
+
cache.npmAdvisoryEntries[getPackageCacheKey(pkg)] = { vulns, cachedAt };
|
|
222
237
|
const newVulns = vulns.filter(v => !existingVulnIds.has(v.id));
|
|
223
238
|
const newVulnIds = newVulns.map(v => v.id);
|
|
224
239
|
if (newVulns.length > 0) {
|
|
@@ -238,7 +253,13 @@ export async function scanPackages(packages, batchSize, options, context, debugL
|
|
|
238
253
|
const offlineMissingDetailIds = new Set();
|
|
239
254
|
const confirmedMissingDetailIds = new Set();
|
|
240
255
|
if (idSet.size > 0 && !offline) {
|
|
241
|
-
|
|
256
|
+
// Only ask OSV for ids OSV can own. The npm registry advisory source
|
|
257
|
+
// (#1056) contributes NPM-prefixed ids from its own namespace, and
|
|
258
|
+
// api.osv.dev/v1/vulns/NPM-... is a 404 by definition. Sending them
|
|
259
|
+
// anyway made every online scan of a project carrying npm-sourced
|
|
260
|
+
// advisories report `partial` with "findings may be incomplete", when
|
|
261
|
+
// nothing was missing: the detail was looked for in the wrong database.
|
|
262
|
+
const ids = [...idSet].filter((id) => !OSV_FOREIGN_ID_PREFIXES.some((prefix) => id.startsWith(prefix)));
|
|
242
263
|
const detailSpinner = createSpinner("Fetching vulnerability details...", options);
|
|
243
264
|
try {
|
|
244
265
|
const nowMs = Date.now();
|
package/dist/utils/network.js
CHANGED
|
@@ -152,6 +152,10 @@ export function getNetworkErrorHint(error, errorMessage) {
|
|
|
152
152
|
return serverAdvisoryRequestHint();
|
|
153
153
|
if (isLikelyBlockedAdvisoryRequestError(errorMessage))
|
|
154
154
|
return blockedAdvisoryRequestHint();
|
|
155
|
+
// Local read/parse failures are stamped with this prefix by readInput() in
|
|
156
|
+
// src/parsers/index.ts. They are not network failures, so no CA hint.
|
|
157
|
+
if (errorMessage.startsWith("Failed to read "))
|
|
158
|
+
return [];
|
|
155
159
|
return fetchErrorCaCertHint();
|
|
156
160
|
}
|
|
157
161
|
export function createCertAwareFetch(caCertPath) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cve-lite-cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.36.0",
|
|
4
4
|
"description": "Developer-friendly CLI for scanning JS/TS projects for dependency vulnerabilities using local lockfiles and OSV",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -59,6 +59,7 @@
|
|
|
59
59
|
"homepage": "https://github.com/OWASP/cve-lite-cli#readme",
|
|
60
60
|
"files": [
|
|
61
61
|
"dist",
|
|
62
|
+
"scripts/pr-scan-delta.mjs",
|
|
62
63
|
"README.md",
|
|
63
64
|
"LICENSE",
|
|
64
65
|
"assets/logo-with-title-removebg-preview.png",
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Turn two scan JSON files (base and head of a PR) into a PR comment describing
|
|
4
|
+
* only what THIS PR changed.
|
|
5
|
+
*
|
|
6
|
+
* The scoping is the whole point. A comment that republishes every pre-existing
|
|
7
|
+
* finding on an unrelated PR is the reason people disable tools like this, so
|
|
8
|
+
* this reports the delta and stays silent when the finding set did not move.
|
|
9
|
+
*
|
|
10
|
+
* node scripts/pr-scan-delta.mjs base.json head.json
|
|
11
|
+
*
|
|
12
|
+
* Prints the comment body, or nothing at all when there is no delta.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const MARKER = "<!-- cve-lite-cli:pr-delta -->";
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The wordmark on its own line, linked to the repository.
|
|
19
|
+
*
|
|
20
|
+
* Inline it cannot win: at a legible width the image is taller than the line
|
|
21
|
+
* box, so it either overhangs or has to shrink to about 24px. On its own line
|
|
22
|
+
* there is nothing to align against.
|
|
23
|
+
*
|
|
24
|
+
* The link is not decoration. Without an explicit href GitHub wraps the image
|
|
25
|
+
* in a link to the raw PNG, so clicking the logo opens a 217KB file, which is
|
|
26
|
+
* worse than no link at all.
|
|
27
|
+
*/
|
|
28
|
+
const LOGO_URL =
|
|
29
|
+
"https://raw.githubusercontent.com/OWASP/cve-lite-cli/main/assets/logo-with-title-transparent.png";
|
|
30
|
+
const PROJECT_URL = "https://github.com/OWASP/cve-lite-cli";
|
|
31
|
+
const TITLE =
|
|
32
|
+
`<a href="${PROJECT_URL}"><img src="${LOGO_URL}" width="120" alt="CVE Lite CLI"></a>`;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Collapsed by default, so it costs one line until someone opens it. The badge
|
|
36
|
+
* is fenced rather than inlined: an inline badge renders as an image, and the
|
|
37
|
+
* point is to give people something they can copy into a README.
|
|
38
|
+
*/
|
|
39
|
+
const SHARE = [
|
|
40
|
+
"<details>",
|
|
41
|
+
"<summary>\u2764\ufe0f Share</summary>",
|
|
42
|
+
"",
|
|
43
|
+
"If this caught something before it merged, a mention helps other maintainers find it.",
|
|
44
|
+
"",
|
|
45
|
+
`- [Post on X](https://twitter.com/intent/tweet?text=CVE%20Lite%20CLI%20caught%20a%20vulnerable%20transitive%20dependency%20in%20my%20PR%20before%20it%20merged.&url=${PROJECT_URL})`,
|
|
46
|
+
`- [Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=${PROJECT_URL})`,
|
|
47
|
+
"- Add the badge to your README:",
|
|
48
|
+
"",
|
|
49
|
+
" ```markdown",
|
|
50
|
+
` [](${PROJECT_URL})`,
|
|
51
|
+
" ```",
|
|
52
|
+
"",
|
|
53
|
+
"</details>",
|
|
54
|
+
];
|
|
55
|
+
|
|
56
|
+
const SEVERITY_RANK = { critical: 4, high: 3, medium: 2, low: 1, unknown: 0, none: 0 };
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Every string in the comment originates in a lockfile the PR author controls,
|
|
60
|
+
* and with fork PRs supported that author is untrusted. GitHub strips raw HTML
|
|
61
|
+
* in comments so this is not an XSS surface, but a crafted package name can
|
|
62
|
+
* still inject links, headings, or prose that reads as if a maintainer wrote it.
|
|
63
|
+
*
|
|
64
|
+
* Allowlist rather than escape: these fields have known, narrow shapes, so
|
|
65
|
+
* anything outside them is dropped rather than encoded. npm names allow
|
|
66
|
+
* `@scope/name`, semver allows dots, hyphens and plus, advisory ids are
|
|
67
|
+
* alphanumeric with separators.
|
|
68
|
+
*/
|
|
69
|
+
const SAFE_CHARS = /[^A-Za-z0-9._@/+-]/g;
|
|
70
|
+
const MAX_FIELD = 120;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Commands are rendered inside a fenced block, so spaces must survive while
|
|
74
|
+
* anything that could close the fence or start a new directive must not.
|
|
75
|
+
*/
|
|
76
|
+
function safeCommand(value) {
|
|
77
|
+
const raw = String(value ?? "");
|
|
78
|
+
return raw.replace(/[^A-Za-z0-9._@/+ -]/g, "").trim().slice(0, 200);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Post a command only when sanitising it changes nothing.
|
|
83
|
+
*
|
|
84
|
+
* safeCommand's allowlist is a trust boundary, not cosmetics: stage 1 built this
|
|
85
|
+
* JSON on a machine the PR author controls (see pr-delta-scan.yml), so the string
|
|
86
|
+
* is attacker-influenced. But the allowlist also rewrites legitimate commands. It
|
|
87
|
+
* excludes `&`, and runnableFixCommand genuinely contains `&&` because
|
|
88
|
+
* fix-commands.ts chains with " && " in three places, so a real
|
|
89
|
+
* `pnpm add a@1 && pnpm add -D b@2` was being posted as
|
|
90
|
+
* `pnpm add a@1 pnpm add -D b@2`, which does not work.
|
|
91
|
+
*
|
|
92
|
+
* Rather than loosen the boundary or rebuild the command here (a second
|
|
93
|
+
* implementation of the CLI's own logic, which is what mergeCommands was and why
|
|
94
|
+
* it corrupted pnpm workspace filters), only show commands that survive
|
|
95
|
+
* sanitisation byte for byte. Anything else degrades to no command, which is
|
|
96
|
+
* honest, rather than a wrong one, which is not.
|
|
97
|
+
*
|
|
98
|
+
* Returns the command, or null when one exists but cannot be shown safely, or
|
|
99
|
+
* undefined when the finding carries none (#1172).
|
|
100
|
+
*/
|
|
101
|
+
function acceptCommand(value) {
|
|
102
|
+
if (!value) return undefined;
|
|
103
|
+
const raw = String(value);
|
|
104
|
+
return safeCommand(raw) === raw ? raw : null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function safe(value) {
|
|
108
|
+
const raw = String(value ?? "");
|
|
109
|
+
const cleaned = raw.replace(SAFE_CHARS, "").slice(0, MAX_FIELD);
|
|
110
|
+
return cleaned.length > 0 ? cleaned : "(unnamed)";
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function findingsOf(scan) {
|
|
114
|
+
if (!scan || typeof scan !== "object") return [];
|
|
115
|
+
return Array.isArray(scan.findings) ? scan.findings : [];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* One row per (package, version), carrying every advisory id on it. A single
|
|
120
|
+
* finding routinely covers several ids (js-yaml 3.15.1 carries both
|
|
121
|
+
* GHSA-2883-xcg3-v3hh and NPM-1193726) and listing them as separate rows reads
|
|
122
|
+
* as two problems rather than one.
|
|
123
|
+
*/
|
|
124
|
+
function index(scan) {
|
|
125
|
+
const rows = new Map();
|
|
126
|
+
for (const f of findingsOf(scan)) {
|
|
127
|
+
const pkg = f.package ?? f.pkg?.name;
|
|
128
|
+
const version = f.version ?? f.pkg?.version;
|
|
129
|
+
if (!pkg || !version) continue;
|
|
130
|
+
|
|
131
|
+
const key = `${pkg}@${version}`;
|
|
132
|
+
const row = rows.get(key) ?? {
|
|
133
|
+
package: safe(pkg),
|
|
134
|
+
version: safe(version),
|
|
135
|
+
severity: safe(f.severity ?? "unknown"),
|
|
136
|
+
relationship: safe(f.relationship ?? ""),
|
|
137
|
+
fixVersion: f.validatedFirstFixedVersion ?? f.firstFixedVersion
|
|
138
|
+
? safe(f.validatedFirstFixedVersion ?? f.firstFixedVersion)
|
|
139
|
+
: undefined,
|
|
140
|
+
advisories: [],
|
|
141
|
+
cves: [],
|
|
142
|
+
fixCommand: acceptCommand(f.runnableFixCommand),
|
|
143
|
+
};
|
|
144
|
+
for (const v of f.vulnerabilities ?? []) {
|
|
145
|
+
if (v?.id && !row.advisories.includes(safe(v.id))) row.advisories.push(safe(v.id));
|
|
146
|
+
}
|
|
147
|
+
// Advisories whose detail could not be fetched still count as findings, and
|
|
148
|
+
// dropping them silently would understate the delta.
|
|
149
|
+
for (const id of f.unresolvedAdvisoryIds ?? []) {
|
|
150
|
+
if (id && !row.advisories.includes(safe(id))) row.advisories.push(safe(id));
|
|
151
|
+
}
|
|
152
|
+
// A CVE number is what a reader recognises; the GHSA id is what we key on.
|
|
153
|
+
for (const c of f.cves ?? []) {
|
|
154
|
+
if (c && !row.cves.includes(safe(c))) row.cves.push(safe(c));
|
|
155
|
+
}
|
|
156
|
+
rows.set(key, row);
|
|
157
|
+
}
|
|
158
|
+
return rows;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function buildDelta(baseScan, headScan) {
|
|
162
|
+
const base = index(baseScan);
|
|
163
|
+
const head = index(headScan);
|
|
164
|
+
|
|
165
|
+
const bySeverity = (a, b) =>
|
|
166
|
+
(SEVERITY_RANK[b.severity] ?? 0) - (SEVERITY_RANK[a.severity] ?? 0) ||
|
|
167
|
+
a.package.localeCompare(b.package);
|
|
168
|
+
|
|
169
|
+
const introduced = [...head.entries()]
|
|
170
|
+
.filter(([k]) => !base.has(k))
|
|
171
|
+
.map(([, v]) => v)
|
|
172
|
+
.sort(bySeverity);
|
|
173
|
+
const resolved = [...base.entries()]
|
|
174
|
+
.filter(([k]) => !head.has(k))
|
|
175
|
+
.map(([, v]) => v)
|
|
176
|
+
.sort(bySeverity);
|
|
177
|
+
|
|
178
|
+
return { introduced, resolved, hasChanges: introduced.length > 0 || resolved.length > 0 };
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* "1 new high finding" when they are all one severity, otherwise
|
|
183
|
+
* "6 new findings (2 critical, 4 high)". Naming only the worst severity across
|
|
184
|
+
* a mixed set reads as though every finding were that severe, which is a
|
|
185
|
+
* material overstatement on a security comment.
|
|
186
|
+
*/
|
|
187
|
+
function countPhrase(rows, { adjective } = {}) {
|
|
188
|
+
const n = rows.length;
|
|
189
|
+
const counts = new Map();
|
|
190
|
+
for (const r of rows) counts.set(r.severity, (counts.get(r.severity) ?? 0) + 1);
|
|
191
|
+
|
|
192
|
+
const parts = [String(n)];
|
|
193
|
+
if (adjective) parts.push(adjective);
|
|
194
|
+
|
|
195
|
+
if (counts.size === 1) {
|
|
196
|
+
const only = [...counts.keys()][0];
|
|
197
|
+
if (only !== "unknown") parts.push(only);
|
|
198
|
+
parts.push(`finding${n === 1 ? "" : "s"}`);
|
|
199
|
+
return parts.join(" ");
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
parts.push(`finding${n === 1 ? "" : "s"}`);
|
|
203
|
+
const breakdown = [...counts.entries()]
|
|
204
|
+
.sort((a, b) => (SEVERITY_RANK[b[0]] ?? 0) - (SEVERITY_RANK[a[0]] ?? 0))
|
|
205
|
+
.map(([sev, c]) => `${c} ${sev}`)
|
|
206
|
+
.join(", ");
|
|
207
|
+
return `${parts.join(" ")} (${breakdown})`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* "GHSA-xxx (CVE-2026-84375)", capped. A single package can carry dozens of
|
|
212
|
+
* advisories (tar@6.1.0 has 36), and listing them all produces a line nobody
|
|
213
|
+
* can read. CVEs are shown in preference to GHSA ids because they are what a
|
|
214
|
+
* reviewer recognises.
|
|
215
|
+
*/
|
|
216
|
+
const MAX_IDS = 3;
|
|
217
|
+
|
|
218
|
+
function advisoryLabel(r) {
|
|
219
|
+
const cves = r.cves ?? [];
|
|
220
|
+
const primary = cves.length > 0 ? cves : r.advisories;
|
|
221
|
+
const shown = primary.slice(0, MAX_IDS).join(", ");
|
|
222
|
+
const hidden = primary.length - Math.min(primary.length, MAX_IDS);
|
|
223
|
+
return hidden > 0 ? `${shown} and ${hidden} more` : shown;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
export function renderComment(delta) {
|
|
228
|
+
if (!delta.hasChanges) return null;
|
|
229
|
+
|
|
230
|
+
const lines = [MARKER, ""];
|
|
231
|
+
const { introduced, resolved } = delta;
|
|
232
|
+
|
|
233
|
+
if (introduced.length > 0) {
|
|
234
|
+
lines.push(TITLE);
|
|
235
|
+
lines.push("");
|
|
236
|
+
lines.push(`${countPhrase(introduced, { adjective: "new" })} introduced by this PR`);
|
|
237
|
+
lines.push("");
|
|
238
|
+
for (const r of introduced) {
|
|
239
|
+
const via = r.relationship === "transitive" ? " (transitive)" : "";
|
|
240
|
+
lines.push(`- \`${r.package}@${r.version}\`${via} · ${advisoryLabel(r)} · **${r.severity}**`);
|
|
241
|
+
if (r.fixVersion) lines.push(` Fixed in \`${r.fixVersion}\``);
|
|
242
|
+
}
|
|
243
|
+
// Verbatim and complete, or nothing. A partial set reads as the whole fix,
|
|
244
|
+
// and the CLI has already merged these into its plan, so re-merging them here
|
|
245
|
+
// is what corrupted pnpm workspace filters (#1172).
|
|
246
|
+
const raw = introduced.map((r) => r.fixCommand).filter((c) => c !== undefined);
|
|
247
|
+
const withheld = raw.some((c) => c === null);
|
|
248
|
+
const commands = [...new Set(raw.filter(Boolean))];
|
|
249
|
+
if (!withheld && commands.length > 0) {
|
|
250
|
+
lines.push("");
|
|
251
|
+
lines.push("```bash");
|
|
252
|
+
lines.push(...commands);
|
|
253
|
+
lines.push("```");
|
|
254
|
+
} else if (withheld) {
|
|
255
|
+
lines.push("");
|
|
256
|
+
lines.push("Run `cve-lite .` for the fix commands.");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (resolved.length > 0) {
|
|
260
|
+
lines.push("");
|
|
261
|
+
lines.push(`Also resolves ${resolved.length} existing finding${resolved.length === 1 ? "" : "s"}.`);
|
|
262
|
+
}
|
|
263
|
+
} else {
|
|
264
|
+
lines.push(TITLE);
|
|
265
|
+
lines.push("");
|
|
266
|
+
lines.push(`${countPhrase(resolved)} resolved by this PR`);
|
|
267
|
+
lines.push("");
|
|
268
|
+
for (const r of resolved) {
|
|
269
|
+
lines.push(`- \`${r.package}@${r.version}\` · ${advisoryLabel(r)}`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
lines.push("");
|
|
274
|
+
lines.push("<sub>Only findings this PR changed are listed. Nothing is posted when the set is unchanged.</sub>");
|
|
275
|
+
lines.push("");
|
|
276
|
+
lines.push(
|
|
277
|
+
`<sub>Scanned by <a href="${PROJECT_URL}">CVE Lite CLI</a>, a free and open source OWASP project.</sub>`,
|
|
278
|
+
);
|
|
279
|
+
lines.push("");
|
|
280
|
+
lines.push(...SHARE);
|
|
281
|
+
return lines.join("\n");
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export { MARKER };
|
|
285
|
+
|
|
286
|
+
// CLI entrypoint. Kept side-effect free on import so the tests can call the
|
|
287
|
+
// functions directly.
|
|
288
|
+
if (process.argv[1] && import.meta.url.endsWith(process.argv[1].split("/").pop())) {
|
|
289
|
+
const [basePath, headPath] = process.argv.slice(2);
|
|
290
|
+
if (!basePath || !headPath) {
|
|
291
|
+
console.error("usage: pr-scan-delta.mjs <base.json> <head.json>");
|
|
292
|
+
process.exit(2);
|
|
293
|
+
}
|
|
294
|
+
const { readFileSync } = await import("node:fs");
|
|
295
|
+
// Fail loudly. Treating an unreadable scan as "no findings" would print
|
|
296
|
+
// nothing, which is indistinguishable from "this PR changed nothing" and
|
|
297
|
+
// would quietly stop the check from ever reporting.
|
|
298
|
+
const read = (p) => {
|
|
299
|
+
let raw;
|
|
300
|
+
try {
|
|
301
|
+
raw = readFileSync(p, "utf8");
|
|
302
|
+
} catch (err) {
|
|
303
|
+
console.error(`pr-scan-delta: cannot read ${p}: ${err.message}`);
|
|
304
|
+
process.exit(1);
|
|
305
|
+
}
|
|
306
|
+
try {
|
|
307
|
+
return JSON.parse(raw);
|
|
308
|
+
} catch (err) {
|
|
309
|
+
console.error(`pr-scan-delta: ${p} is not valid JSON: ${err.message}`);
|
|
310
|
+
process.exit(1);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
const body = renderComment(buildDelta(read(basePath), read(headPath)));
|
|
314
|
+
if (body) console.log(body);
|
|
315
|
+
}
|