cve-lite-cli 1.41.1 → 1.41.3

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.
@@ -6,6 +6,7 @@ import { inferSeverity } from "../osv/severity.js";
6
6
  import { getPrimaryParent, getRootDependencies, isUnconfirmedFix } from "../utils/finding.js";
7
7
  import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
8
8
  import { pluralize, isOutputStdout } from "../utils/string.js";
9
+ import { npmLsCommand, UNSAFE_LS_INSTRUCTION } from "../utils/shell-quote.js";
9
10
  import { hasMaliciousAdvisory } from "../utils/vuln.js";
10
11
  import { computePrioritySignal } from "../utils/priority-signal.js";
11
12
  import { computeContextualSignals } from "../utils/contextual-signals.js";
@@ -113,10 +114,13 @@ export function getRecommendedAction(finding) {
113
114
  // a degenerate length-2 chain (project -> vulnerable, common when the
114
115
  // package is hoisted to top-level node_modules). The advice is the same
115
116
  // either way - inspect the lockfile or run `<pm> ls` to find the parent.
117
+ const lsCommand = npmLsCommand(finding.pkg.name);
118
+ const lookup = lsCommand ? `Run \`${lsCommand}\` (or your package manager equivalent)` : UNSAFE_LS_INSTRUCTION;
119
+ const inspectMessage = `No parent dependency was identified for ${finding.pkg.name} in the lockfile. ${lookup} to find which package pulls it in`;
116
120
  if (directTarget) {
117
- return `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${finding.pkg.name}\` (or your package manager equivalent) to find which package pulls it in, then upgrade toward ${directTarget}+.`;
121
+ return `${inspectMessage}, then upgrade toward ${directTarget}+.`;
118
122
  }
119
- return `No parent dependency was identified for ${finding.pkg.name} in the lockfile. Run \`npm ls ${finding.pkg.name}\` (or your package manager equivalent) to find which package pulls it in.`;
123
+ return `${inspectMessage}.`;
120
124
  }
121
125
  export function summarizeRisk(finding) {
122
126
  if (finding.maliciousUnverifiable) {
@@ -228,7 +232,9 @@ export function summarizeNextAction(finding) {
228
232
  return `Upgrade ${parent} - no safe version identified. Find a release resolving ${finding.pkg.name} to ${directTarget}+.`;
229
233
  }
230
234
  if (directTarget) {
231
- return `No parent identified in the lockfile. Run \`npm ls ${finding.pkg.name}\` to find the parent, then upgrade toward ${directTarget}+.`;
235
+ const lsCommand = npmLsCommand(finding.pkg.name);
236
+ const lookup = lsCommand ? `Run \`${lsCommand}\`` : UNSAFE_LS_INSTRUCTION;
237
+ return `No parent identified in the lockfile. ${lookup} to find the parent, then upgrade toward ${directTarget}+.`;
232
238
  }
233
239
  return `Inspect the parent dependency chain for ${finding.pkg.name} and choose the safest available upgrade.`;
234
240
  }
@@ -6,6 +6,7 @@ import { serializeFinding, summarizeNextAction, summarizeRisk, formatCooldownWar
6
6
  import { loadLogoDataUri } from "./logos.js";
7
7
  import { isBreakingUpgrade } from "../utils/version.js";
8
8
  import { pluralize } from "../utils/string.js";
9
+ import { npmLsCommand, UNSAFE_LS_INSTRUCTION } from "../utils/shell-quote.js";
9
10
  import { MAL_GIT_SOURCE_PINNED_DISPLAY, MAL_GIT_SOURCE_FLOATING_DISPLAY, severityOrder } from "../constants.js";
10
11
  import { hasMaliciousAdvisory } from "../utils/vuln.js";
11
12
  import { renderOverrideFindingsHtml } from "./override-findings-html.js";
@@ -739,7 +740,7 @@ function renderTransitiveContextCol(finding) {
739
740
  return `<div class="detail-col" style="max-width:200px">
740
741
  <h4>Context</h4>
741
742
  <span class="tier-err">✕ No parent identified</span>
742
- <p style="font-size:12px;color:var(--text-2);margin-top:4px">Run <code>npm ls ${escapeHtml(finding.package)}</code> to find which package pulls it in.</p>
743
+ <p style="font-size:12px;color:var(--text-2);margin-top:4px">${lsLookupHtml(finding.package)} to find which package pulls it in.</p>
743
744
  </div>`;
744
745
  }
745
746
  export function renderCompletenessBanner(completeness) {
@@ -1035,3 +1036,7 @@ export function openInBrowser(filePath) {
1035
1036
  // Best-effort only: report creation should not fail if the OS open command is unavailable.
1036
1037
  }
1037
1038
  }
1039
+ function lsLookupHtml(packageName) {
1040
+ const lsCommand = npmLsCommand(packageName);
1041
+ return lsCommand ? `Run <code>${escapeHtml(lsCommand)}</code>` : escapeHtml(UNSAFE_LS_INSTRUCTION);
1042
+ }
@@ -3,7 +3,7 @@ import { groupSkippedByReason, skippedHeadline, skippedRuleCount } from "./skipp
3
3
  import { chalk, stripAnsi } from "../utils/chalk.js";
4
4
  import { formatSeverityLabel, SEVERITY_ORDER } from "../utils/severity.js";
5
5
  import { pluralize } from "../utils/string.js";
6
- import { buildOverrideFixCommand, overrideCommandTargetSuffix } from "./override-fix-command.js";
6
+ import { buildOverrideFixCommand, isPasteableOverrideTarget, overrideCommandTargetSuffix } from "./override-fix-command.js";
7
7
  const COL_RULE_MAX = 8;
8
8
  const COL_PKG_MAX = 30;
9
9
  const COL_MSG_MAX = 50;
@@ -69,14 +69,15 @@ export function renderOverrideFindings(findings, options) {
69
69
  if (f.fix?.runnableCommand && !seenRules.has(f.ruleId)) {
70
70
  seenRules.add(f.ruleId);
71
71
  const cmd = buildOverrideFixCommand(f.fix.runnableCommand, commandTarget);
72
- lines.push(chalk.bold.cyan(`> ${cmd}`));
72
+ if (cmd)
73
+ lines.push(chalk.bold.cyan(`> ${cmd}`));
73
74
  }
74
75
  }
75
76
  lines.push("");
76
77
  }
77
78
  const projectInfix = overrideCommandTargetSuffix(commandTarget);
78
79
  const allFixableRules = new Set(findings.filter(f => f.fix?.runnableCommand).map(f => f.ruleId));
79
- if (allFixableRules.size >= 2) {
80
+ if (allFixableRules.size >= 2 && isPasteableOverrideTarget(commandTarget)) {
80
81
  const fixAllCmd = `cve-lite${projectInfix} overrides --fix`;
81
82
  lines.push("💡 " + chalk.gray(`Tip: run ${fixAllCmd} to apply all auto-fixable fixes in one shot.`));
82
83
  lines.push("");
@@ -1,11 +1,17 @@
1
1
  import { OVERRIDES_COMMAND } from "../constants.js";
2
- import { quoteShellPath } from "../utils/shell-quote.js";
2
+ import { isSafeInEveryShell, quoteShellPath } from "../utils/shell-quote.js";
3
3
  // HTML callers pass a project-relative path, and terminal callers pass a
4
4
  // cwd-relative path. An empty target or "." needs no positional argument.
5
5
  export function overrideCommandTargetSuffix(commandTarget) {
6
6
  return commandTarget && commandTarget !== "." ? ` ${quoteShellPath(commandTarget)}` : "";
7
7
  }
8
+ /** False when the folder name is not safe to paste into every shell, so no command should be printed for it. */
9
+ export function isPasteableOverrideTarget(commandTarget) {
10
+ return !commandTarget || isSafeInEveryShell(commandTarget);
11
+ }
8
12
  export function buildOverrideFixCommand(runnableCommand, commandTarget) {
13
+ if (!isPasteableOverrideTarget(commandTarget))
14
+ return null;
9
15
  const suffix = overrideCommandTargetSuffix(commandTarget);
10
16
  return runnableCommand.replace(OVERRIDES_COMMAND, () => `cve-lite${suffix} overrides`);
11
17
  }
@@ -1,4 +1,4 @@
1
- import { getDeclaredPackages, installCmd, undeclaredImportFiles } from "./phantom-utils.js";
1
+ import { getDeclaredPackages, phantomInstallInstruction, undeclaredImportFiles } from "./phantom-utils.js";
2
2
  const RULE_ID = "PD001";
3
3
  export function detect(ctx) {
4
4
  if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
@@ -7,7 +7,6 @@ export function detect(ctx) {
7
7
  return [];
8
8
  const declared = getDeclaredPackages(ctx.packageJson);
9
9
  const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
- const cmd = installCmd(ctx.packageManager);
11
10
  const findings = [];
12
11
  for (const [pkgName, importedIn] of ctx.importedPackageNames) {
13
12
  if (!overrideNames.has(pkgName))
@@ -25,7 +24,7 @@ export function detect(ctx) {
25
24
  message: `${pkgName} is imported in source but only present via an override pin - declare it as a dependency`,
26
25
  details: `Imported in: ${shown.join(", ")}${extra}. ` +
27
26
  `In pnpm strict mode (default on Vercel), override-only packages are not importable and will cause a deploy failure. ` +
28
- `Run: ${cmd} ${pkgName}`,
27
+ phantomInstallInstruction(ctx.packageManager, pkgName),
29
28
  references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md"],
30
29
  });
31
30
  }
@@ -1,4 +1,4 @@
1
- import { getDeclaredPackages, installCmd, undeclaredImportFiles } from "./phantom-utils.js";
1
+ import { getDeclaredPackages, phantomInstallInstruction, undeclaredImportFiles } from "./phantom-utils.js";
2
2
  const RULE_ID = "PD002";
3
3
  export function detect(ctx) {
4
4
  if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
@@ -7,7 +7,6 @@ export function detect(ctx) {
7
7
  return [];
8
8
  const declared = getDeclaredPackages(ctx.packageJson);
9
9
  const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
- const cmd = installCmd(ctx.packageManager);
11
10
  const findings = [];
12
11
  for (const [pkgName, importedIn] of ctx.importedPackageNames) {
13
12
  if (overrideNames.has(pkgName))
@@ -27,7 +26,7 @@ export function detect(ctx) {
27
26
  message: `${pkgName} is imported in source but only present as a transitive dependency - declare it explicitly`,
28
27
  details: `Imported in: ${shown.join(", ")}${extra}. ` +
29
28
  `If the parent package drops or changes this dependency, your code will break without warning. ` +
30
- `Run: ${cmd} ${pkgName}`,
29
+ phantomInstallInstruction(ctx.packageManager, pkgName),
31
30
  references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md"],
32
31
  });
33
32
  }
@@ -1,3 +1,4 @@
1
+ import { isSafeInEveryShell, shellQuote } from "../../utils/shell-quote.js";
1
2
  export function getDeclaredPackages(packageJson) {
2
3
  const declared = new Set();
3
4
  for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
@@ -48,3 +49,10 @@ export function installCmd(pm) {
48
49
  return "bun add";
49
50
  return "npm install";
50
51
  }
52
+ /** The closing instruction for a phantom-dependency finding: a copyable install command, or a plain step when the name is not safe in every shell. */
53
+ export function phantomInstallInstruction(pm, pkgName) {
54
+ if (!isSafeInEveryShell(pkgName)) {
55
+ return "Declare it in package.json (no command is shown because the name is not safe to paste into every shell).";
56
+ }
57
+ return `Run: ${installCmd(pm)} ${shellQuote(pkgName)}`;
58
+ }
@@ -49,7 +49,7 @@ export function bareName(overrideKey) {
49
49
  * or -1 if there is none. For scoped names the leading `@` (index 0) is the
50
50
  * scope, not a specifier, so we look past it.
51
51
  */
52
- function specifierAt(selector) {
52
+ export function specifierAt(selector) {
53
53
  if (selector.startsWith('@')) {
54
54
  return selector.indexOf('@', 1);
55
55
  }
@@ -0,0 +1,248 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { bareName, specifierAt } from "../overrides/parsing/package-json.js";
4
+ import { isGitSource } from "../utils/advisory.js";
5
+ import { isRecord } from "../utils/package-json.js";
6
+ import { npmAliasRegistryName } from "../utils/package-identity.js";
7
+ import { isValidRange, satisfiesRange } from "../utils/version.js";
8
+ /**
9
+ * Resolve true npm registry identities onto lockfile graph nodes without
10
+ * re-attributing non-registry git/tarball packages or un-installed peers.
11
+ */
12
+ export function resolveNpmLockAliasIdentities(ctx) {
13
+ const overrideRules = loadOverrideAliasRules(ctx.filePath, ctx.rootMeta);
14
+ const legacyAliasByPath = collectLegacyAliasRegistryNames(ctx.rawLegacyDependencies);
15
+ for (const node of ctx.nodesById.values()) {
16
+ const registryName = resolveNodeRegistryName(node, ctx, overrideRules, legacyAliasByPath);
17
+ if (registryName) {
18
+ node.registryName = registryName;
19
+ }
20
+ }
21
+ }
22
+ /** Format the canonical key tracking a fallback edge added from `peerDependencies`. */
23
+ export function peerFallbackEdgeKey(parentNodeId, childNodeId) {
24
+ return `${parentNodeId}\u0000${childNodeId}`;
25
+ }
26
+ function collectRegularDeclaredRanges(node, ctx) {
27
+ const ranges = [];
28
+ if (ctx.rootEntryNodeIds.has(node.id)) {
29
+ const rootRange = ctx.rootRanges[node.name];
30
+ if (rootRange)
31
+ ranges.push(rootRange);
32
+ }
33
+ for (const parentId of ctx.parentNodeIdsByChildNodeId.get(node.id) ?? []) {
34
+ if (ctx.peerFallbackEdgeKeys.has(peerFallbackEdgeKey(parentId, node.id)))
35
+ continue;
36
+ const range = ctx.rangeByParentNodeId.get(parentId)?.get(node.name);
37
+ if (range)
38
+ ranges.push(range);
39
+ }
40
+ return ranges;
41
+ }
42
+ function resolveNodeRegistryName(node, ctx, overrideRules, legacyAliasByPath) {
43
+ const regularDeclaredRanges = collectRegularDeclaredRanges(node, ctx);
44
+ const manifestName = ctx.manifestNameByNodeId.get(node.id);
45
+ const resolvedUrl = ctx.resolvedUrlByNodeId.get(node.id);
46
+ // 1. Explicit `npm:` spec on root or regular parent dependencies.
47
+ const explicitAlias = regularDeclaredRanges
48
+ .map(npmAliasRegistryName)
49
+ .find((name) => name && name !== node.name);
50
+ if (explicitAlias)
51
+ return explicitAlias;
52
+ // 2. Lockfile v2 legacy `dependencies` entry.
53
+ const legacyAlias = legacyAliasByPath.get(node.packagePath);
54
+ if (legacyAlias && legacyAlias !== node.name && (!manifestName || manifestName === legacyAlias)) {
55
+ return legacyAlias;
56
+ }
57
+ // Remaining paths rely on a differing installed manifest `name`.
58
+ if (!manifestName || manifestName === node.name)
59
+ return null;
60
+ // 3. Peer-derived `npm:` alias: only trust when the node's lockfile manifest `name`
61
+ // matches the alias target, so `--legacy-peer-deps` or optional peers cannot
62
+ // substitute an alias identity onto a different real package installed in that slot.
63
+ if (!isGitSource({ resolvedUrl }) &&
64
+ (regularDeclaredRanges.length === 0 || regularDeclaredRanges.every(looksLikeRegistryVersionSpec))) {
65
+ const peerRanges = ctx.peerRangesByChildNodeId.get(node.id) ?? [];
66
+ const peerAlias = peerRanges
67
+ .map(npmAliasRegistryName)
68
+ .find((name) => name === manifestName);
69
+ if (peerAlias)
70
+ return peerAlias;
71
+ }
72
+ // 4. Configured `overrides` (package.json or root lockfile metadata).
73
+ if (!isGitSource({ resolvedUrl })) {
74
+ const matchedRule = overrideRules.find((rule) => rule.target.name === node.name &&
75
+ rule.registryName === manifestName &&
76
+ matchesAncestorChain(node.id, rule.parentChain, ctx));
77
+ if (matchedRule)
78
+ return matchedRule.registryName;
79
+ }
80
+ // 5. Standalone v3 lockfiles omit `overrides` and replace the child spec only in
81
+ // node metadata; accept standard registry tarball layouts (including private
82
+ // mirrors) when every regular parent spec is a registry range/tag (#1450).
83
+ if (!isGitSource({ resolvedUrl }) &&
84
+ regularDeclaredRanges.length > 0 &&
85
+ regularDeclaredRanges.every(looksLikeRegistryVersionSpec) &&
86
+ isRegistryTarballForPackage(resolvedUrl, manifestName, node.version)) {
87
+ return manifestName;
88
+ }
89
+ return null;
90
+ }
91
+ function loadOverrideAliasRules(lockfilePath, rootMeta) {
92
+ const pkgJson = readJsonObject(path.join(path.dirname(lockfilePath), "package.json"));
93
+ const rootManifestDeps = collectRootManifestDeps(rootMeta, pkgJson);
94
+ const rules = [];
95
+ walkOverrideAliasRules(pkgJson?.overrides, [], rootManifestDeps, rules);
96
+ walkOverrideAliasRules(rootMeta?.overrides, [], rootManifestDeps, rules);
97
+ return rules;
98
+ }
99
+ function readJsonObject(filePath) {
100
+ try {
101
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
102
+ return isRecord(parsed) ? parsed : null;
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ }
108
+ function collectRootManifestDeps(rootMeta, pkgJson) {
109
+ const deps = {};
110
+ const sections = ["peerDependencies", "devDependencies", "optionalDependencies", "dependencies"];
111
+ for (const source of [rootMeta, pkgJson]) {
112
+ if (!source)
113
+ continue;
114
+ for (const sectionName of sections) {
115
+ const section = source[sectionName];
116
+ if (!isRecord(section))
117
+ continue;
118
+ for (const [name, spec] of Object.entries(section)) {
119
+ if (typeof spec === "string" && spec)
120
+ deps[name] = spec;
121
+ }
122
+ }
123
+ }
124
+ return deps;
125
+ }
126
+ function walkOverrideAliasRules(node, ancestors, rootManifestDeps, rules) {
127
+ if (!isRecord(node))
128
+ return;
129
+ for (const [key, value] of Object.entries(node)) {
130
+ if (key === ".") {
131
+ if (typeof value === "string" && ancestors.length > 0) {
132
+ const registryName = resolveOverrideAliasRegistryName(value, rootManifestDeps);
133
+ const target = ancestors[ancestors.length - 1];
134
+ if (registryName && target.name) {
135
+ rules.push({
136
+ parentChain: ancestors.slice(0, -1),
137
+ target,
138
+ registryName,
139
+ });
140
+ }
141
+ }
142
+ continue;
143
+ }
144
+ const selector = splitOverrideSelector(key);
145
+ if (!selector.name)
146
+ continue;
147
+ if (typeof value === "string") {
148
+ const registryName = resolveOverrideAliasRegistryName(value, rootManifestDeps);
149
+ if (registryName) {
150
+ rules.push({ parentChain: ancestors, target: selector, registryName });
151
+ }
152
+ }
153
+ else if (isRecord(value)) {
154
+ walkOverrideAliasRules(value, [...ancestors, selector], rootManifestDeps, rules);
155
+ }
156
+ }
157
+ }
158
+ function splitOverrideSelector(key) {
159
+ const trimmed = key.trim();
160
+ const at = specifierAt(trimmed);
161
+ if (at === -1)
162
+ return { name: trimmed };
163
+ const name = bareName(trimmed);
164
+ const range = trimmed.slice(at + 1).trim();
165
+ return range ? { name, range } : { name };
166
+ }
167
+ function resolveOverrideAliasRegistryName(rawSpec, rootManifestDeps) {
168
+ const trimmed = rawSpec.trim();
169
+ const resolved = trimmed.startsWith("$") ? rootManifestDeps[trimmed.slice(1)] : trimmed;
170
+ return npmAliasRegistryName(resolved);
171
+ }
172
+ function matchesAncestorChain(childNodeId, parentChain, ctx) {
173
+ if (parentChain.length === 0)
174
+ return true;
175
+ const visited = new Set();
176
+ const stack = [];
177
+ for (const parentId of ctx.parentNodeIdsByChildNodeId.get(childNodeId) ?? []) {
178
+ stack.push({ currentId: parentId, chainIndex: parentChain.length - 1 });
179
+ }
180
+ while (stack.length > 0) {
181
+ const { currentId, chainIndex } = stack.pop();
182
+ const visitKey = `${currentId}\u0000${chainIndex}`;
183
+ if (visited.has(visitKey))
184
+ continue;
185
+ visited.add(visitKey);
186
+ const parentNode = ctx.nodesById.get(currentId);
187
+ if (!parentNode)
188
+ continue;
189
+ const selector = parentChain[chainIndex];
190
+ const parentVersion = parentNode.version ?? ctx.ancestorVersionByNodeId.get(currentId) ?? null;
191
+ const selectorMatches = parentNode.name === selector.name &&
192
+ (!selector.range ||
193
+ !isValidRange(selector.range) ||
194
+ (parentVersion !== null && satisfiesRange(parentVersion, selector.range)));
195
+ if (selectorMatches) {
196
+ if (chainIndex === 0)
197
+ return true;
198
+ for (const grandParentId of ctx.parentNodeIdsByChildNodeId.get(currentId) ?? []) {
199
+ stack.push({ currentId: grandParentId, chainIndex: chainIndex - 1 });
200
+ }
201
+ }
202
+ // Nested npm overrides apply through intermediate transitive dependencies.
203
+ for (const grandParentId of ctx.parentNodeIdsByChildNodeId.get(currentId) ?? []) {
204
+ stack.push({ currentId: grandParentId, chainIndex });
205
+ }
206
+ }
207
+ return false;
208
+ }
209
+ function collectLegacyAliasRegistryNames(deps) {
210
+ const byPath = new Map();
211
+ const walk = (entries, prefix) => {
212
+ if (!isRecord(entries))
213
+ return;
214
+ for (const [name, meta] of Object.entries(entries)) {
215
+ if (!isRecord(meta))
216
+ continue;
217
+ const packagePath = prefix ? `${prefix}/node_modules/${name}` : `node_modules/${name}`;
218
+ const registryName = npmAliasRegistryName(meta.version);
219
+ if (registryName)
220
+ byPath.set(packagePath, registryName);
221
+ if (meta.dependencies)
222
+ walk(meta.dependencies, packagePath);
223
+ }
224
+ };
225
+ walk(deps, "");
226
+ return byPath;
227
+ }
228
+ function looksLikeRegistryVersionSpec(spec) {
229
+ const trimmed = spec.trim();
230
+ if (!trimmed)
231
+ return false;
232
+ if (trimmed.startsWith("npm:"))
233
+ return true;
234
+ if (trimmed.includes(":") || trimmed.includes("/"))
235
+ return false;
236
+ return isValidRange(trimmed) || /^[A-Za-z0-9._-]+$/.test(trimmed);
237
+ }
238
+ function isRegistryTarballForPackage(resolvedUrl, manifestName, version) {
239
+ if (!resolvedUrl || !version)
240
+ return false;
241
+ const cleanUrl = resolvedUrl.split(/[?#]/, 1)[0];
242
+ const unscoped = manifestName.startsWith("@")
243
+ ? manifestName.slice(manifestName.indexOf("/") + 1)
244
+ : manifestName;
245
+ if (!unscoped)
246
+ return false;
247
+ return cleanUrl.endsWith(`/${manifestName}/-/${unscoped}-${version}.tgz`);
248
+ }
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import { unique } from "../utils/array.js";
3
- import { npmAliasRegistryName } from "../utils/package-identity.js";
3
+ import { isRecord } from "../utils/package-json.js";
4
+ import { peerFallbackEdgeKey, resolveNpmLockAliasIdentities, } from "./npm-alias-resolution.js";
4
5
  export function loadNpmLockGraph(filePath, options) {
5
6
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
6
7
  const packages = raw?.packages;
@@ -11,6 +12,9 @@ export function loadNpmLockGraph(filePath, options) {
11
12
  const dependencyRangesByNodeId = new Map();
12
13
  const resolutionBasePathsByNodeId = new Map();
13
14
  const peerRangesByNodeId = new Map();
15
+ const manifestNameByNodeId = new Map();
16
+ const resolvedUrlByNodeId = new Map();
17
+ const ancestorVersionByNodeId = new Map();
14
18
  const parentNodeIdsByChildNodeId = new Map();
15
19
  const childNodeIdsByParentNodeId = new Map();
16
20
  const rangeByParentNodeId = new Map();
@@ -49,19 +53,30 @@ export function loadNpmLockGraph(filePath, options) {
49
53
  dev: !!meta?.dev,
50
54
  });
51
55
  nodeIdByPackagePath.set(packagePath, id);
56
+ if (typeof meta?.name === "string" && meta.name) {
57
+ manifestNameByNodeId.set(id, meta.name);
58
+ }
59
+ if (typeof meta?.resolved === "string" && meta.resolved) {
60
+ resolvedUrlByNodeId.set(id, meta.resolved);
61
+ }
52
62
  const keySet = nodeIdsByPackageKey.get(packageKey) ?? new Set();
53
63
  keySet.add(id);
54
64
  nodeIdsByPackageKey.set(packageKey, keySet);
65
+ const depSource = resolveDependencySource(meta, rawPackages);
66
+ const effectiveVersion = version ?? (typeof depSource?.version === "string" ? depSource.version : undefined);
67
+ if (effectiveVersion) {
68
+ ancestorVersionByNodeId.set(id, effectiveVersion);
69
+ }
55
70
  // Workspace / linked packages (link:true, resolved -> a workspace dir) are
56
71
  // installed with their devDependencies, like the root, and are the true roots
57
72
  // of their own dependency subtrees. Collect their full deps (incl. devDeps) and
58
73
  // treat them as entry points; otherwise every transitive that lives only under a
59
74
  // workspace is orphaned from "project" and reports "no parent identified".
60
75
  dependencyRangesByNodeId.set(id, isLinkNode
61
- ? collectRootDependencyRanges(resolveDependencySource(meta, rawPackages))
62
- : collectDependencyRanges(resolveDependencySource(meta, rawPackages)));
76
+ ? collectRootDependencyRanges(depSource)
77
+ : collectDependencyRanges(depSource));
63
78
  resolutionBasePathsByNodeId.set(id, resolveBasePaths(packagePath, meta));
64
- const peerRanges = collectPeerRanges(resolveDependencySource(meta, rawPackages));
79
+ const peerRanges = collectPeerRanges(depSource);
65
80
  if (Object.keys(peerRanges).length > 0)
66
81
  peerRangesByNodeId.set(id, peerRanges);
67
82
  if (isLinkNode)
@@ -69,12 +84,19 @@ export function loadNpmLockGraph(filePath, options) {
69
84
  }
70
85
  const rootMeta = isRecord(rawPackages[""]) ? rawPackages[""] : null;
71
86
  const rootRanges = collectRootDependencyRanges(rootMeta);
87
+ const rootPeerRanges = collectPeerRanges(rootMeta);
72
88
  const entryPackages = resolveEdgesForParent("", rootRanges, [""], nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId);
73
89
  for (const node of nodesById.values()) {
74
90
  resolveEdgesForParent(node.packagePath, dependencyRangesByNodeId.get(node.id) ?? {}, resolutionBasePathsByNodeId.get(node.id) ?? [node.packagePath], nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId);
75
91
  }
76
92
  const entryNodeIds = unique([...entryPackages, ...workspaceEntryNodeIds]);
77
- applyPeerDependencyFallback({
93
+ applyRootPeerFallback({
94
+ rootPeerRanges,
95
+ entryNodeIds,
96
+ nodeIdByPackagePath,
97
+ parentNodeIdsByChildNodeId,
98
+ });
99
+ const peerFallbackEdgeKeys = applyPeerDependencyFallback({
78
100
  nodesById,
79
101
  entryNodeIds,
80
102
  peerRangesByNodeId,
@@ -84,21 +106,22 @@ export function loadNpmLockGraph(filePath, options) {
84
106
  childNodeIdsByParentNodeId,
85
107
  rangeByParentNodeId,
86
108
  });
87
- // A different manifest name also occurs for git/tarball installs. Only an
88
- // npm: declaration establishes a registry alias for the resolved graph slot.
89
- const rootEntryNodeIds = new Set(entryPackages);
90
- for (const node of nodesById.values()) {
91
- const declaredRanges = [
92
- rootEntryNodeIds.has(node.id) ? rootRanges[node.name] : undefined,
93
- ...[...(parentNodeIdsByChildNodeId.get(node.id) ?? [])]
94
- .map(parentId => rangeByParentNodeId.get(parentId)?.get(node.name)),
95
- ];
96
- const registryName = declaredRanges.map(npmAliasRegistryName)
97
- .find(name => name && name !== node.name);
98
- if (registryName) {
99
- node.registryName = registryName;
100
- }
101
- }
109
+ const peerRangesByChildNodeId = collectPeerRangesByChild(nodesById, rootPeerRanges, peerRangesByNodeId, resolutionBasePathsByNodeId, nodeIdByPackagePath);
110
+ resolveNpmLockAliasIdentities({
111
+ filePath,
112
+ rootMeta,
113
+ rawLegacyDependencies: raw?.dependencies,
114
+ rootEntryNodeIds: new Set(entryPackages),
115
+ rootRanges,
116
+ peerRangesByChildNodeId,
117
+ manifestNameByNodeId,
118
+ resolvedUrlByNodeId,
119
+ ancestorVersionByNodeId,
120
+ nodesById,
121
+ parentNodeIdsByChildNodeId,
122
+ rangeByParentNodeId,
123
+ peerFallbackEdgeKeys,
124
+ });
102
125
  if (options?.includePaths !== false) {
103
126
  const MAX_PATHS_PER_NODE = 5;
104
127
  const MAX_PATH_DEPTH = 10;
@@ -136,7 +159,7 @@ export function loadNpmLockGraph(filePath, options) {
136
159
  childNodeIdsByParentNodeId: setsToArrays(childNodeIdsByParentNodeId),
137
160
  rangeByParentNodeId,
138
161
  pathSetByNodeId,
139
- peerRangesByChildNodeId: collectPeerRangesByChild(nodesById, peerRangesByNodeId, resolutionBasePathsByNodeId, nodeIdByPackagePath),
162
+ peerRangesByChildNodeId,
140
163
  });
141
164
  }
142
165
  function createGraph(args) {
@@ -188,23 +211,44 @@ function createGraph(args) {
188
211
  },
189
212
  };
190
213
  }
214
+ function appendPeerRangesForBasePaths(peerRanges, basePaths, nodeIdByPackagePath, rangesByChild) {
215
+ for (const [peerName, range] of Object.entries(peerRanges)) {
216
+ const childPackagePath = resolveDependencyPackagePath(basePaths, peerName, nodeIdByPackagePath);
217
+ const childNodeId = childPackagePath ? nodeIdByPackagePath.get(childPackagePath) : undefined;
218
+ if (!childNodeId)
219
+ continue;
220
+ rangesByChild.set(childNodeId, [...(rangesByChild.get(childNodeId) ?? []), range]);
221
+ }
222
+ }
191
223
  // npm refuses an install whose version breaks a peer requirement, so every
192
224
  // peer range on an installed copy limits what it can be moved to, whether or
193
225
  // not the peer fallback below turned that requirement into an edge.
194
- function collectPeerRangesByChild(nodesById, peerRangesByNodeId, resolutionBasePathsByNodeId, nodeIdByPackagePath) {
226
+ function collectPeerRangesByChild(nodesById, rootPeerRanges, peerRangesByNodeId, resolutionBasePathsByNodeId, nodeIdByPackagePath) {
195
227
  const rangesByChild = new Map();
228
+ appendPeerRangesForBasePaths(rootPeerRanges, [""], nodeIdByPackagePath, rangesByChild);
196
229
  for (const [nodeId, peerRanges] of peerRangesByNodeId) {
197
230
  const basePaths = resolutionBasePathsByNodeId.get(nodeId) ?? [nodesById.get(nodeId)?.packagePath ?? nodeId];
198
- for (const [peerName, range] of Object.entries(peerRanges)) {
199
- const childPackagePath = resolveDependencyPackagePath(basePaths, peerName, nodeIdByPackagePath);
200
- const childNodeId = childPackagePath ? nodeIdByPackagePath.get(childPackagePath) : undefined;
201
- if (!childNodeId)
202
- continue;
203
- rangesByChild.set(childNodeId, [...(rangesByChild.get(childNodeId) ?? []), range]);
204
- }
231
+ appendPeerRangesForBasePaths(peerRanges, basePaths, nodeIdByPackagePath, rangesByChild);
205
232
  }
206
233
  return rangesByChild;
207
234
  }
235
+ // npm 7+ auto-installs root peerDependencies unless suppressed; keep otherwise-orphaned
236
+ // root peer targets anchored at "project" so paths and aliases remain intact.
237
+ function applyRootPeerFallback(args) {
238
+ const entrySet = new Set(args.entryNodeIds);
239
+ for (const peerName of Object.keys(args.rootPeerRanges)) {
240
+ const childPackagePath = resolveDependencyPackagePath([""], peerName, args.nodeIdByPackagePath);
241
+ if (!childPackagePath)
242
+ continue;
243
+ const childNodeId = args.nodeIdByPackagePath.get(childPackagePath);
244
+ if (!childNodeId || entrySet.has(childNodeId))
245
+ continue;
246
+ if ((args.parentNodeIdsByChildNodeId.get(childNodeId)?.size ?? 0) > 0)
247
+ continue;
248
+ args.entryNodeIds.push(childNodeId);
249
+ entrySet.add(childNodeId);
250
+ }
251
+ }
208
252
  function resolveEdgesForParent(parentPackagePath, dependencyRanges, resolutionBasePaths, nodeIdByPackagePath, childNodeIdsByParentNodeId, parentNodeIdsByChildNodeId, rangeByParentNodeId) {
209
253
  const resolvedChildNodeIds = [];
210
254
  for (const [dependencyName, range] of Object.entries(dependencyRanges)) {
@@ -235,6 +279,7 @@ function resolveEdgesForParent(parentPackagePath, dependencyRanges, resolutionBa
235
279
  // is also a direct dependency).
236
280
  function applyPeerDependencyFallback(args) {
237
281
  const { nodesById, entryNodeIds, peerRangesByNodeId, resolutionBasePathsByNodeId, nodeIdByPackagePath, parentNodeIdsByChildNodeId, } = args;
282
+ const fallbackEdgeKeys = new Set();
238
283
  const entryNodeIdSet = new Set(entryNodeIds);
239
284
  const orphanNodeIds = new Set();
240
285
  for (const nodeId of nodesById.keys()) {
@@ -243,7 +288,7 @@ function applyPeerDependencyFallback(args) {
243
288
  orphanNodeIds.add(nodeId);
244
289
  }
245
290
  if (orphanNodeIds.size === 0)
246
- return;
291
+ return fallbackEdgeKeys;
247
292
  for (const node of nodesById.values()) {
248
293
  const peerRanges = peerRangesByNodeId.get(node.id);
249
294
  if (!peerRanges)
@@ -257,8 +302,10 @@ function applyPeerDependencyFallback(args) {
257
302
  if (!childNodeId || !orphanNodeIds.has(childNodeId))
258
303
  continue;
259
304
  addParentChildEdge(node.id, childNodeId, peerName, range, args);
305
+ fallbackEdgeKeys.add(peerFallbackEdgeKey(node.id, childNodeId));
260
306
  }
261
307
  }
308
+ return fallbackEdgeKeys;
262
309
  }
263
310
  function addParentChildEdge(parentNodeId, childNodeId, dependencyName, range, edges) {
264
311
  const childSet = edges.childNodeIdsByParentNodeId.get(parentNodeId) ?? new Set();
@@ -362,9 +409,6 @@ function setsToArrays(map) {
362
409
  }
363
410
  return result;
364
411
  }
365
- function isRecord(value) {
366
- return !!value && typeof value === "object";
367
- }
368
412
  function buildPackageKey(name, version) {
369
413
  return `${name}@${version ?? "<link>"}`;
370
414
  }
@@ -5,7 +5,7 @@ import { getPrimaryParent } from "../utils/finding.js";
5
5
  import { isNpmLockSource, packageManagerForSource } from "../utils/package-manager-source.js";
6
6
  import { calculatePathCoverage, formatDependencyPath } from "../utils/path-coverage.js";
7
7
  import { pluralize } from "../utils/string.js";
8
- import { quoteShellPath, shellQuote } from "../utils/shell-quote.js";
8
+ import { isSafeInEveryShell, quoteShellPath, shellQuote } from "../utils/shell-quote.js";
9
9
  import { buildNpmWorkspaceMap } from "../parsers/package-lock.js";
10
10
  import { buildPnpmWorkspaceMap } from "../parsers/pnpm-lock.js";
11
11
  import { buildYarnWorkspaceMap } from "../parsers/yarn-lock.js";
@@ -321,7 +321,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
321
321
  adjusted: false,
322
322
  adjustmentNote: null,
323
323
  reason: buildParentUpgradeReason(finding, coverage),
324
- command: finding.chainResolution.command,
324
+ command: buildPackageInstallCommand(packageManager, `${finding.chainResolution.directDep}@${finding.chainResolution.targetVersion}`),
325
325
  chainProof: finding.chainResolution.chain,
326
326
  chainSafeVersion: finding.chainResolution.safeVersion,
327
327
  chainVulnerablePackage: finding.pkg.name,
@@ -352,7 +352,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
352
352
  : "No confident automatic fix command could be generated for this issue.",
353
353
  });
354
354
  }
355
- const targets = [...targetsByKey.values()].sort((a, b) => {
355
+ const sortedTargets = [...targetsByKey.values()].sort((a, b) => {
356
356
  const sevDelta = severityOrder[b.severity] - severityOrder[a.severity];
357
357
  if (sevDelta !== 0)
358
358
  return sevDelta;
@@ -365,6 +365,7 @@ export function buildSuggestedFixCommandPlan(findings, scanInput, options) {
365
365
  return kindDelta;
366
366
  return a.package.localeCompare(b.package);
367
367
  });
368
+ const targets = withholdShellUnsafeTargets(sortedTargets, findings, skippedByKey, options?.subfolder);
368
369
  // Some install targets carry an explicit `command` built without workspace
369
370
  // context (e.g. a chain-resolution command). This raw field is exposed in JSON
370
371
  // and embedded in the HTML report, so scope it to the declaring member too.
@@ -483,6 +484,10 @@ export function commandPrefix(packageManager) {
483
484
  return "bun add";
484
485
  return "yarn add";
485
486
  }
487
+ /** Format a single install command with a shell-quoted package spec. */
488
+ export function buildPackageInstallCommand(packageManager, packageSpec, flag = "") {
489
+ return `${commandPrefix(packageManager)}${flag} ${shellQuote(packageSpec)}`;
490
+ }
486
491
  function devFlag(packageManager) {
487
492
  return packageManager === "bun" ? "--dev" : "-D";
488
493
  }
@@ -578,7 +583,7 @@ export function buildTargetCommand(target, packageManager) {
578
583
  if (target.command)
579
584
  return target.command;
580
585
  const flag = target.isDev ? ` ${devFlag(packageManager)}` : "";
581
- return `${commandPrefix(packageManager)}${flag} ${shellQuote(installPackageSpec(target))}`;
586
+ return buildPackageInstallCommand(packageManager, installPackageSpec(target), flag);
582
587
  }
583
588
  export function findSuggestedCommandForFinding(plan, finding) {
584
589
  const target = findFixTargetForFinding(plan, finding);
@@ -667,6 +672,52 @@ export function planVersionForFinding(plan, finding) {
667
672
  }
668
673
  return target.targetVersion;
669
674
  }
675
+ export const UNSAFE_PACKAGE_REASON = "The package or workspace name contains characters that are not safe to paste into every shell, so no command is offered. Check the name in your lockfile before running anything for it.";
676
+ export const UNSAFE_FOLDER_REASON = "The folder name contains characters that are not safe to paste into every shell, so no command is offered for this folder.";
677
+ // Every token a target's printed command is built from. A token that would
678
+ // still act in cmd.exe or PowerShell despite our quoting withholds the command.
679
+ function unsafeShellReason(target) {
680
+ const tokens = [
681
+ target.package,
682
+ target.registryName,
683
+ target.targetVersion,
684
+ target.childPackage,
685
+ target.childTargetVersion,
686
+ ...(target.workspaces ?? []),
687
+ ];
688
+ return tokens.every(token => token === undefined || isSafeInEveryShell(token)) ? null : UNSAFE_PACKAGE_REASON;
689
+ }
690
+ // Drops targets whose printed command could not be pasted safely into every
691
+ // shell, and records a skip for each finding that loses its command, under the
692
+ // finding's own package so a parent-update target named after its parent cannot
693
+ // hide the child it was refreshing.
694
+ function withholdShellUnsafeTargets(sortedTargets, findings, skippedByKey, subfolder) {
695
+ const unsafeFolder = !!subfolder && !isSafeInEveryShell(subfolder);
696
+ const kept = [];
697
+ const withheld = new Map();
698
+ for (const target of sortedTargets) {
699
+ const reason = unsafeFolder ? UNSAFE_FOLDER_REASON : unsafeShellReason(target);
700
+ if (reason)
701
+ withheld.set(target, reason);
702
+ else
703
+ kept.push(target);
704
+ }
705
+ if (withheld.size === 0)
706
+ return kept;
707
+ const withheldPlan = { targets: [...withheld.keys()] };
708
+ for (const finding of findings) {
709
+ const target = findFixTargetForFinding(withheldPlan, finding);
710
+ if (!target)
711
+ continue;
712
+ skippedByKey.set(`${finding.relationship}:${packageInstanceKey(finding.pkg)}`, {
713
+ package: finding.pkg.name,
714
+ version: finding.pkg.version,
715
+ relationship: finding.relationship,
716
+ reason: withheld.get(target),
717
+ });
718
+ }
719
+ return kept;
720
+ }
670
721
  function upsertTarget(targetsByKey, finding, next) {
671
722
  const key = targetKey(finding, next);
672
723
  const existing = targetsByKey.get(key);
@@ -1,4 +1,4 @@
1
- import { commandPrefix } from "./fix-commands.js";
1
+ import { buildPackageInstallCommand } from "./fix-commands.js";
2
2
  import { fetchPackument } from "./npm-registry.js";
3
3
  import { compareVersions, looksLikeVersion, isPreReleaseVersion, satisfiesRange } from "../utils/version.js";
4
4
  import { highestVersionSatisfyingRange } from "./npm-transitive-resolution.js";
@@ -42,7 +42,7 @@ export async function resolveChainFix(finding, installedVersions, packageManager
42
42
  targetVersion: candidateVersion,
43
43
  chain: traced.chain,
44
44
  safeVersion: traced.safeVersion,
45
- command: `${commandPrefix(packageManager)} ${directDepName}@${candidateVersion}`,
45
+ command: buildPackageInstallCommand(packageManager, `${directDepName}@${candidateVersion}`),
46
46
  coveredPaths: 1,
47
47
  totalPaths: finding.dependencyPaths.length,
48
48
  };
package/dist/scanner.js CHANGED
@@ -28,6 +28,7 @@ import { buildPnpmWorkspaceMap } from "./parsers/pnpm-lock.js";
28
28
  import { buildNpmWorkspaceMap } from "./parsers/package-lock.js";
29
29
  import { buildBunWorkspaceMap } from "./parsers/bun-lock.js";
30
30
  import { pluralize } from "./utils/string.js";
31
+ import { npmLsCommand, UNSAFE_LS_INSTRUCTION } from "./utils/shell-quote.js";
31
32
  import path from "node:path";
32
33
  import { resolveRegistryConfig } from "./utils/registry-config.js";
33
34
  import { extractErrorMessage } from "./utils/network.js";
@@ -589,7 +590,9 @@ export async function scanPackages(packages, batchSize, options, context, debugL
589
590
  continue;
590
591
  updateAnalysisProgress("resolving remediation for", `${finding.pkg.name}@${finding.pkg.version}`);
591
592
  if (aliasRemediationFindings.has(finding)) {
592
- const aliasNote = `Automatic parent remediation is unavailable for paths containing an npm alias. Run \`npm ls ${finding.pkg.name}\` to inspect the declaring dependency, then rescan after updating it.`;
593
+ const lsCommand = npmLsCommand(finding.pkg.name);
594
+ const lookup = lsCommand ? `Run \`${lsCommand}\`` : UNSAFE_LS_INSTRUCTION;
595
+ const aliasNote = `Automatic parent remediation is unavailable for paths containing an npm alias. ${lookup} to inspect the declaring dependency, then rescan after updating it.`;
593
596
  finding.fixVersionValidationNote = [finding.fixVersionValidationNote, aliasNote].filter(Boolean).join(" ");
594
597
  continue;
595
598
  }
@@ -58,6 +58,7 @@ function addDependencyNamesFromManifest(target, manifest, prodOnly) {
58
58
  const sections = [
59
59
  isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
60
60
  isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
61
+ isRecord(manifest.peerDependencies) ? manifest.peerDependencies : undefined,
61
62
  ];
62
63
  if (!prodOnly) {
63
64
  sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
@@ -5,8 +5,24 @@ export function shellQuote(token) {
5
5
  return token;
6
6
  return "'" + token.replace(/'/g, "'\\''") + "'";
7
7
  }
8
+ // shellQuote only protects POSIX shells. cmd.exe ignores single quotes, so
9
+ // & | < > ^ % ! and double quotes still act there, and PowerShell reads the
10
+ // POSIX escape for a quote inside a token differently, as it does a backtick.
11
+ // Spaces are left alone: in cmd.exe they only split an argument, they cannot
12
+ // run anything.
13
+ const UNSAFE_IN_SOME_SHELL = /[&|<>^%!"'`\u0000-\u001f\u007f]/;
14
+ /** True when a quoted token stays inert if pasted into any common shell, Windows included. */
15
+ export function isSafeInEveryShell(token) {
16
+ return !UNSAFE_IN_SOME_SHELL.test(token);
17
+ }
8
18
  export function quoteShellPath(directory) {
9
19
  // Preserve literal backslashes in POSIX names and keep ordinary Windows paths unquoted.
10
20
  const normalized = path.sep === "\\" ? directory.replace(/\\/g, "/") : directory;
11
21
  return shellQuote(normalized.startsWith("-") ? `./${normalized}` : normalized);
12
22
  }
23
+ /** Shown in place of an `npm ls` command when the package name is not safe to paste into every shell. */
24
+ export const UNSAFE_LS_INSTRUCTION = "Look it up with your package manager's ls command (no command is shown because the name is not safe to paste into every shell)";
25
+ /** `npm ls <name>` for a pasteable inspection hint, or null when the name is not safe in every shell. */
26
+ export function npmLsCommand(packageName) {
27
+ return isSafeInEveryShell(packageName) ? `npm ls ${shellQuote(packageName)}` : null;
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cve-lite-cli",
3
- "version": "1.41.1",
3
+ "version": "1.41.3",
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": {