cve-lite-cli 1.17.3 → 1.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -0
- package/dist/advisory/osv-sync.js +3 -2
- package/dist/cli/args.js +54 -3
- package/dist/cli/config-command.js +40 -0
- package/dist/cli/config.js +66 -0
- package/dist/cli/help.js +8 -0
- package/dist/cli/validate.js +31 -0
- package/dist/constants.js +2 -0
- package/dist/index.js +66 -311
- package/dist/output/formatters.js +13 -5
- package/dist/output/html-reporter.js +10 -4
- package/dist/output/printers.js +20 -12
- 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/parsers/yarn-lock.js +60 -0
- package/dist/remediation/fix-commands.js +145 -14
- package/dist/remediation/npm-transitive-resolution.js +63 -0
- package/dist/scanner.js +58 -6
- package/dist/usage/scanner.js +3 -2
- package/dist/utils/fix-runner.js +127 -0
- package/dist/utils/network.js +58 -8
- package/dist/utils/package-json.js +124 -0
- package/dist/utils/severity.js +14 -0
- package/dist/utils/string.js +3 -0
- package/dist/utils/time.js +31 -0
- package/dist/utils/update-check.js +102 -0
- package/package.json +1 -1
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createSpinner } from "../output/spinner.js";
|
|
3
|
+
import { chalk } from "./chalk.js";
|
|
4
|
+
import { pluralize } from "./string.js";
|
|
5
|
+
export function buildFixCommandParts(packageManager, targets) {
|
|
6
|
+
if (packageManager === "npm") {
|
|
7
|
+
return ["npm", "install", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
8
|
+
}
|
|
9
|
+
if (packageManager === "pnpm") {
|
|
10
|
+
return ["pnpm", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
11
|
+
}
|
|
12
|
+
if (packageManager === "bun") {
|
|
13
|
+
return ["bun", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
14
|
+
}
|
|
15
|
+
return ["yarn", "add", ...targets.map(target => `${target.package}@${target.targetVersion}`)];
|
|
16
|
+
}
|
|
17
|
+
export async function runInstallCommand(command, args, cwd) {
|
|
18
|
+
return await new Promise(resolve => {
|
|
19
|
+
const child = spawn(command, args, {
|
|
20
|
+
cwd,
|
|
21
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
22
|
+
});
|
|
23
|
+
child.stdout.on("data", () => { });
|
|
24
|
+
child.stderr.on("data", () => { });
|
|
25
|
+
child.on("error", error => {
|
|
26
|
+
resolve({ status: null, error });
|
|
27
|
+
});
|
|
28
|
+
child.on("close", code => {
|
|
29
|
+
resolve({ status: code, error: null });
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
export function commandLabelForPackageManager(packageManager) {
|
|
34
|
+
if (packageManager === "npm")
|
|
35
|
+
return "npm install";
|
|
36
|
+
if (packageManager === "pnpm")
|
|
37
|
+
return "pnpm add";
|
|
38
|
+
if (packageManager === "bun")
|
|
39
|
+
return "bun add";
|
|
40
|
+
return "yarn add";
|
|
41
|
+
}
|
|
42
|
+
export async function applyFixesIfRequested(params) {
|
|
43
|
+
console.log("");
|
|
44
|
+
console.log(chalk.bold.cyan("Applying fixes (--fix)"));
|
|
45
|
+
if (!params.plan) {
|
|
46
|
+
return {
|
|
47
|
+
appliedFixCount: 0,
|
|
48
|
+
skippedCount: params.totalFindings,
|
|
49
|
+
skippedTransitiveCount: 0,
|
|
50
|
+
skippedNoValidatedTargetCount: params.totalFindings,
|
|
51
|
+
applied: [],
|
|
52
|
+
note: "No package-manager-native fix command is available for this project.",
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const directTargets = params.plan.targets.filter(target => target.kind === "direct");
|
|
56
|
+
const transitiveTargets = params.plan.targets.filter(target => target.kind !== "direct");
|
|
57
|
+
const skippedDirect = params.plan.skipped.filter(skip => skip.relationship === "direct" || skip.relationship === "unknown");
|
|
58
|
+
if (directTargets.length === 0) {
|
|
59
|
+
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
60
|
+
return {
|
|
61
|
+
appliedFixCount: 0,
|
|
62
|
+
skippedCount,
|
|
63
|
+
skippedTransitiveCount: transitiveTargets.length,
|
|
64
|
+
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
65
|
+
applied: [],
|
|
66
|
+
note: "No validated direct dependency fixes were eligible for auto-apply.",
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
const commandLabel = commandLabelForPackageManager(params.plan.packageManager);
|
|
70
|
+
const total = directTargets.length;
|
|
71
|
+
const spinner = createSpinner(`Applying direct package fixes with ${commandLabel}... 0/${total}`, params.options);
|
|
72
|
+
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.`;
|
|
73
|
+
for (let i = 0; i < directTargets.length; i++) {
|
|
74
|
+
const target = directTargets[i];
|
|
75
|
+
const commandParts = buildFixCommandParts(params.plan.packageManager, [target]);
|
|
76
|
+
spinner.update(`Applying direct fix ${i + 1}/${total}: ${commandParts.join(" ")}`);
|
|
77
|
+
const run = await runInstallCommand(commandParts[0], commandParts.slice(1), params.projectPath);
|
|
78
|
+
if (run.error) {
|
|
79
|
+
spinner.fail("Failed to apply fixes");
|
|
80
|
+
throw new Error(`Failed to apply fixes: ${run.error.message}${fixHint}`);
|
|
81
|
+
}
|
|
82
|
+
if ((run.status ?? 1) !== 0) {
|
|
83
|
+
spinner.fail(`Fix command failed (${commandLabel})`);
|
|
84
|
+
throw new Error(`Fix command exited with status ${run.status ?? 1}${fixHint}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
spinner.succeed(`Applied ${directTargets.length} direct package ${pluralize(directTargets.length, "fix", "fixes")} with ${commandLabel}`);
|
|
88
|
+
const skippedCount = transitiveTargets.length + skippedDirect.length;
|
|
89
|
+
return {
|
|
90
|
+
appliedFixCount: directTargets.length,
|
|
91
|
+
skippedCount,
|
|
92
|
+
skippedTransitiveCount: transitiveTargets.length,
|
|
93
|
+
skippedNoValidatedTargetCount: skippedDirect.length,
|
|
94
|
+
applied: directTargets.map(target => ({
|
|
95
|
+
package: target.package,
|
|
96
|
+
from: target.currentVersion ?? "unknown",
|
|
97
|
+
to: target.targetVersion,
|
|
98
|
+
})),
|
|
99
|
+
note: null,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
export function printFixModeSummary(params) {
|
|
103
|
+
const result = params.fixResult;
|
|
104
|
+
if (!result)
|
|
105
|
+
return;
|
|
106
|
+
if (result.note) {
|
|
107
|
+
console.log(chalk.gray(result.note));
|
|
108
|
+
}
|
|
109
|
+
if (result.applied.length > 0) {
|
|
110
|
+
console.log("");
|
|
111
|
+
console.log(chalk.bold.cyan("Applied fixes"));
|
|
112
|
+
for (const item of result.applied) {
|
|
113
|
+
console.log(`- ${chalk.white(item.package)}: ${chalk.gray(item.from)} ${chalk.cyan("->")} ${chalk.green(item.to)}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
console.log("");
|
|
117
|
+
console.log(chalk.bold.cyan("Fix summary"));
|
|
118
|
+
console.log(`- Applied fixes: ${chalk.green(String(result.appliedFixCount))}`);
|
|
119
|
+
console.log(`- Skipped findings: ${chalk.yellow(String(result.skippedCount))}`);
|
|
120
|
+
if (result.skippedCount > 0) {
|
|
121
|
+
console.log(` - Transitive (v1 skip): ${chalk.yellow(String(result.skippedTransitiveCount))}`);
|
|
122
|
+
console.log(` - No validated direct target: ${chalk.yellow(String(result.skippedNoValidatedTargetCount))}`);
|
|
123
|
+
}
|
|
124
|
+
console.log(`- Findings before fix: ${chalk.white(String(params.findingsBeforeFix))}`);
|
|
125
|
+
console.log(`- Remaining findings after fix: ${chalk.white(String(params.findingsAfterFix))}`);
|
|
126
|
+
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))}`);
|
|
127
|
+
}
|
package/dist/utils/network.js
CHANGED
|
@@ -9,10 +9,10 @@ export function extractErrorMessage(error) {
|
|
|
9
9
|
export function sslCertificateErrorHint() {
|
|
10
10
|
return [
|
|
11
11
|
"Hint: SSL certificate error — your network may be using a corporate proxy that intercepts HTTPS traffic.",
|
|
12
|
-
"Fix
|
|
13
|
-
"
|
|
14
|
-
"
|
|
15
|
-
"
|
|
12
|
+
"Fix (recommended): save your corporate CA certificate path once:",
|
|
13
|
+
" cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
14
|
+
"Or pass it per-invocation:",
|
|
15
|
+
" cve-lite . --ca-cert /path/to/corporate-ca.crt",
|
|
16
16
|
];
|
|
17
17
|
}
|
|
18
18
|
export function blockedAdvisoryRequestHint() {
|
|
@@ -20,6 +20,29 @@ export function blockedAdvisoryRequestHint() {
|
|
|
20
20
|
"Hint: Outbound access to the OSV API may be blocked or restricted in this environment.",
|
|
21
21
|
"If that is expected, build the advisory DB on a machine with OSV access, then scan here with `--offline` or `--offline-db /path/to/advisories.db`.",
|
|
22
22
|
"Command to build the DB on a network-allowed machine: `cve-lite advisories sync --output /path/to/advisories.db`",
|
|
23
|
+
"If your network uses SSL inspection, try: cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
export function fetchErrorCaCertHint() {
|
|
27
|
+
return [
|
|
28
|
+
"Hint: If your network uses a corporate SSL proxy, a CA certificate may be required.",
|
|
29
|
+
"Run: cve-lite config set ca-cert /path/to/corporate-ca.crt",
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
const OFFLINE_FALLBACK_LINES = [
|
|
33
|
+
" cve-lite . --offline",
|
|
34
|
+
" (requires a local advisory DB - run `cve-lite advisories sync` to build one)",
|
|
35
|
+
];
|
|
36
|
+
export function rateLimitAdvisoryRequestHint() {
|
|
37
|
+
return [
|
|
38
|
+
"Hint: OSV API rate limit reached. Wait a moment and retry, or scan offline:",
|
|
39
|
+
...OFFLINE_FALLBACK_LINES,
|
|
40
|
+
];
|
|
41
|
+
}
|
|
42
|
+
export function serverAdvisoryRequestHint() {
|
|
43
|
+
return [
|
|
44
|
+
"Hint: OSV API may be temporarily unavailable. Wait a moment and retry, or scan offline:",
|
|
45
|
+
...OFFLINE_FALLBACK_LINES,
|
|
23
46
|
];
|
|
24
47
|
}
|
|
25
48
|
const SSL_ERROR_CODES = new Set([
|
|
@@ -38,6 +61,19 @@ const SSL_ERROR_MESSAGE_FRAGMENTS = [
|
|
|
38
61
|
"certificate has expired",
|
|
39
62
|
"unable to verify the first certificate",
|
|
40
63
|
];
|
|
64
|
+
function finalErrorCause(message) {
|
|
65
|
+
const normalized = message.toLowerCase();
|
|
66
|
+
return normalized.split(":").pop()?.trim() ?? normalized;
|
|
67
|
+
}
|
|
68
|
+
function isOsvError(message) {
|
|
69
|
+
return message.toLowerCase().includes("osv");
|
|
70
|
+
}
|
|
71
|
+
function isRateLimitCause(finalCause) {
|
|
72
|
+
return /^429\b/.test(finalCause);
|
|
73
|
+
}
|
|
74
|
+
function isServerCause(finalCause) {
|
|
75
|
+
return /^5\d\d\b/.test(finalCause);
|
|
76
|
+
}
|
|
41
77
|
export function isSslCertificateError(error) {
|
|
42
78
|
if (!(error instanceof Error))
|
|
43
79
|
return false;
|
|
@@ -50,12 +86,26 @@ export function isSslCertificateError(error) {
|
|
|
50
86
|
const normalized = error.message.toLowerCase();
|
|
51
87
|
return SSL_ERROR_MESSAGE_FRAGMENTS.some(f => normalized.includes(f));
|
|
52
88
|
}
|
|
89
|
+
export function isRateLimitError(message) {
|
|
90
|
+
if (!isOsvError(message)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
return isRateLimitCause(finalErrorCause(message));
|
|
94
|
+
}
|
|
95
|
+
export function isServerError(message) {
|
|
96
|
+
if (!isOsvError(message)) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
return isServerCause(finalErrorCause(message));
|
|
100
|
+
}
|
|
53
101
|
export function isLikelyBlockedAdvisoryRequestError(message) {
|
|
54
|
-
if (!message
|
|
102
|
+
if (!isOsvError(message)) {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
const finalCause = finalErrorCause(message);
|
|
106
|
+
if (isRateLimitCause(finalCause) || isServerCause(finalCause)) {
|
|
55
107
|
return false;
|
|
56
108
|
}
|
|
57
|
-
const normalized = message.toLowerCase();
|
|
58
|
-
const finalCause = normalized.split(":").pop()?.trim() ?? normalized;
|
|
59
109
|
const blockedIndicators = [
|
|
60
110
|
"access denied",
|
|
61
111
|
"blocked",
|
|
@@ -81,5 +131,5 @@ export function isLikelyBlockedAdvisoryRequestError(message) {
|
|
|
81
131
|
if (blockedIndicators.some(indicator => finalCause.includes(indicator))) {
|
|
82
132
|
return true;
|
|
83
133
|
}
|
|
84
|
-
return /^(401|403|407|408|
|
|
134
|
+
return /^(401|403|407|408|451)\b/.test(finalCause);
|
|
85
135
|
}
|
|
@@ -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,31 @@
|
|
|
1
|
+
import { chalk } from "./chalk.js";
|
|
2
|
+
import { pluralize } from "./string.js";
|
|
3
|
+
export function formatAdvisoryDbFreshness(lastSyncAt) {
|
|
4
|
+
if (!lastSyncAt) {
|
|
5
|
+
return chalk.yellow("unknown");
|
|
6
|
+
}
|
|
7
|
+
const timestamp = Date.parse(lastSyncAt);
|
|
8
|
+
if (Number.isNaN(timestamp)) {
|
|
9
|
+
return chalk.yellow("unknown");
|
|
10
|
+
}
|
|
11
|
+
return `${relativeAge(timestamp)} ${chalk.gray(`(${lastSyncAt})`)}`;
|
|
12
|
+
}
|
|
13
|
+
export function relativeAge(timestamp) {
|
|
14
|
+
const deltaMs = Math.max(0, Date.now() - timestamp);
|
|
15
|
+
const minute = 60 * 1000;
|
|
16
|
+
const hour = 60 * minute;
|
|
17
|
+
const day = 24 * hour;
|
|
18
|
+
if (deltaMs < minute) {
|
|
19
|
+
return "just synced";
|
|
20
|
+
}
|
|
21
|
+
if (deltaMs < hour) {
|
|
22
|
+
const minutes = Math.floor(deltaMs / minute);
|
|
23
|
+
return `synced ${minutes} ${pluralize(minutes, "minute")} ago`;
|
|
24
|
+
}
|
|
25
|
+
if (deltaMs < day) {
|
|
26
|
+
const hours = Math.floor(deltaMs / hour);
|
|
27
|
+
return `synced ${hours} ${pluralize(hours, "hour")} ago`;
|
|
28
|
+
}
|
|
29
|
+
const days = Math.floor(deltaMs / day);
|
|
30
|
+
return `synced ${days} ${pluralize(days, "day")} ago`;
|
|
31
|
+
}
|
|
@@ -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
|
+
}
|