cve-lite-cli 1.26.0 → 1.27.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.
@@ -1,3 +1,4 @@
1
+ import { relative } from "node:path";
1
2
  import { SEVERITY_ORDER } from "../utils/severity.js";
2
3
  function esc(s) {
3
4
  return s
@@ -6,7 +7,7 @@ function esc(s) {
6
7
  .replace(/>/g, ">")
7
8
  .replace(/"/g, """);
8
9
  }
9
- export function renderOverrideFindingsHtml(findings) {
10
+ export function renderOverrideFindingsHtml(findings, projectPath) {
10
11
  // undefined = override hygiene was never requested -> render nothing, so a plain
11
12
  // `cve-lite .` report shows no Override hygiene panel at all. An empty array =
12
13
  // it ran and found nothing -> render the "no findings" reassurance.
@@ -36,8 +37,13 @@ export function renderOverrideFindingsHtml(findings) {
36
37
  const location = f.location.jsonPath
37
38
  ? `${esc(f.location.file)} › ${esc(f.location.jsonPath)}`
38
39
  : esc(f.location.file);
39
- const fixHtml = f.fix?.runnableCommand
40
- ? `<div class="fix-cmd-inline" style="margin-top:6px"><code>${esc(f.fix.runnableCommand)}</code><button class="copy-btn" data-cmd="${esc(f.fix.runnableCommand)}">Copy</button></div>`
40
+ const relPath = projectPath ? relative(process.cwd(), projectPath) : "";
41
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
42
+ const runnableCmd = f.fix?.runnableCommand && projectInfix
43
+ ? f.fix.runnableCommand.replace("cve-lite overrides", `cve-lite${projectInfix} overrides`)
44
+ : f.fix?.runnableCommand;
45
+ const fixHtml = runnableCmd
46
+ ? `<div class="fix-cmd-inline" style="margin-top:6px"><code>${esc(runnableCmd)}</code><button class="copy-btn" data-cmd="${esc(runnableCmd)}">Copy</button></div>`
41
47
  : "";
42
48
  rows.push(` <tr class="finding ${esc(f.severity)}">` +
43
49
  `<td>${esc(f.ruleId)}</td>` +
@@ -1,4 +1,6 @@
1
1
  import { getCliVersion } from "../utils/version-info.js";
2
+ import { severityToSarifLevel } from "../utils/severity.js";
3
+ import { sarifFingerprintHash } from "../utils/sarif.js";
2
4
  const OA_RULES = [
3
5
  { id: "OA001", name: "OrphanedTarget", shortDescription: "Override target not in resolved tree", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA001.md" },
4
6
  { id: "OA002", name: "FloatingTag", shortDescription: "Override pins to a moving tag", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA002.md" },
@@ -8,14 +10,11 @@ const OA_RULES = [
8
10
  { id: "OA006", name: "CoupledPlatformBinary", shortDescription: "Override fights exact-pinned parent", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA006.md" },
9
11
  { id: "OA007", name: "FrozenLatest", shortDescription: "\"latest\" tag has moved", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA007.md" },
10
12
  { id: "OA008", name: "MaterializedVulnerable", shortDescription: "Vulnerable copy still on disk", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA008.md" },
13
+ { id: "OA009", name: "StaleFloor", shortDescription: "Override floor already met by all parent declarations", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA009.md" },
14
+ { id: "PD001", name: "OverrideOnlyPhantom", shortDescription: "Package imported in source but only present via override pin - declare it as a dependency", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md" },
15
+ { id: "PD002", name: "TransitiveOnlyPhantom", shortDescription: "Package imported in source but only present as a transitive dependency - declare it explicitly", helpUri: "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md" },
11
16
  ];
12
- const SEVERITY_TO_LEVEL = {
13
- critical: "error",
14
- high: "error",
15
- medium: "warning",
16
- low: "note",
17
- info: "note",
18
- };
17
+ const OA_RULE_INDEX = new Map(OA_RULES.map((r, i) => [r.id, i]));
19
18
  export function buildOverrideSarifComponent() {
20
19
  return {
21
20
  name: "cve-lite-cli-overrides",
@@ -30,23 +29,34 @@ export function buildOverrideSarifComponent() {
30
29
  };
31
30
  }
32
31
  export function buildOverrideSarifResults(findings) {
33
- return findings.map((f) => ({
34
- ruleId: f.ruleId,
35
- rule: { id: f.ruleId, toolComponent: { index: 0 } },
36
- level: SEVERITY_TO_LEVEL[f.severity] ?? "warning",
37
- message: { text: f.message },
38
- locations: [
39
- {
40
- physicalLocation: {
41
- artifactLocation: { uri: f.location.file, uriBaseId: "%SRCROOT%" },
42
- region: { startLine: f.location.line ?? 1 },
32
+ return findings.map((f) => {
33
+ const ruleIndex = OA_RULE_INDEX.get(f.ruleId);
34
+ if (ruleIndex === undefined) {
35
+ throw new Error(`OA_RULE_INDEX: unknown ruleId "${f.ruleId}" - add it to OA_RULES`);
36
+ }
37
+ return {
38
+ ruleId: f.ruleId,
39
+ ruleIndex,
40
+ rule: { id: f.ruleId, toolComponent: { index: 0 } },
41
+ kind: "open",
42
+ level: severityToSarifLevel(f.severity),
43
+ message: { text: f.message },
44
+ locations: [
45
+ {
46
+ physicalLocation: {
47
+ artifactLocation: { uri: f.location.file, uriBaseId: "%SRCROOT%" },
48
+ region: { startLine: f.location.line ?? 1 },
49
+ },
43
50
  },
51
+ ],
52
+ partialFingerprints: {
53
+ primaryLocationLineHash: sarifFingerprintHash(`${f.ruleId}:${f.package.name}:${f.location.file}`),
44
54
  },
45
- ],
46
- properties: {
47
- package: f.package.name,
48
- jsonPath: f.location.jsonPath,
49
- severity: f.severity,
50
- },
51
- }));
55
+ properties: {
56
+ package: f.package.name,
57
+ jsonPath: f.location.jsonPath,
58
+ severity: f.severity,
59
+ },
60
+ };
61
+ });
52
62
  }
@@ -1,3 +1,4 @@
1
+ import { relative } from "node:path";
1
2
  import { chalk, stripAnsi } from "../utils/chalk.js";
2
3
  import { formatSeverityLabel, SEVERITY_ORDER } from "../utils/severity.js";
3
4
  import { pluralize } from "../utils/string.js";
@@ -6,7 +7,6 @@ const COL_PKG_MAX = 30;
6
7
  const COL_MSG_MAX = 50;
7
8
  export function renderOverrideFindings(findings, options) {
8
9
  const lines = [];
9
- lines.push("");
10
10
  if (options?.verbose) {
11
11
  lines.push(chalk.bold.cyan("🔍 Override Hygiene"));
12
12
  }
@@ -53,15 +53,32 @@ export function renderOverrideFindings(findings, options) {
53
53
  lines.push(hr("├", "┼", "┤"));
54
54
  }
55
55
  lines.push(hr("└", "┴", "┘"));
56
+ const relPath = options?.projectPath
57
+ ? relative(process.cwd(), options.projectPath)
58
+ : "";
59
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
56
60
  const seenRules = new Set();
57
61
  for (const f of sorted) {
58
62
  if (f.fix?.runnableCommand && !seenRules.has(f.ruleId)) {
59
63
  seenRules.add(f.ruleId);
60
- lines.push(chalk.bold.cyan(`> ${f.fix.runnableCommand}`));
64
+ const cmd = projectInfix
65
+ ? f.fix.runnableCommand.replace("cve-lite overrides", `cve-lite${projectInfix} overrides`)
66
+ : f.fix.runnableCommand;
67
+ lines.push(chalk.bold.cyan(`> ${cmd}`));
61
68
  }
62
69
  }
63
70
  lines.push("");
64
71
  }
72
+ const relPath = options?.projectPath
73
+ ? relative(process.cwd(), options.projectPath)
74
+ : "";
75
+ const projectInfix = relPath && relPath !== "." ? ` ${relPath}` : "";
76
+ const allFixableRules = new Set(findings.filter(f => f.fix?.runnableCommand).map(f => f.ruleId));
77
+ if (allFixableRules.size >= 2) {
78
+ const fixAllCmd = `cve-lite${projectInfix} overrides --fix`;
79
+ lines.push("💡 " + chalk.gray(`Tip: run ${fixAllCmd} to apply all auto-fixable fixes in one shot.`));
80
+ lines.push("");
81
+ }
65
82
  const worstSev = SEVERITY_ORDER.find(s => (grouped.get(s) ?? []).length > 0);
66
83
  const footerColor = worstSev === "critical" || worstSev === "high" ? chalk.redBright : chalk.yellow;
67
84
  lines.push(footerColor(`${findings.length} override hygiene ${pluralize(findings.length, "issue")} found.`));
@@ -3,7 +3,9 @@ import path from "node:path";
3
3
  import { getRecommendedAction } from "./formatters.js";
4
4
  import { getCliVersion } from "../utils/version-info.js";
5
5
  import { severityToSarifLevel } from "../utils/severity.js";
6
+ import { sarifFingerprintHash } from "../utils/sarif.js";
6
7
  import { buildOverrideSarifComponent, buildOverrideSarifResults } from "./override-findings-sarif.js";
8
+ const SARIF_SCHEMA = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json";
7
9
  const LOCKFILE_NAMES = {
8
10
  "package-lock": "package-lock.json",
9
11
  "npm-shrinkwrap": "npm-shrinkwrap.json",
@@ -75,6 +77,7 @@ export function deriveLockfileUri(scanInput) {
75
77
  }
76
78
  export function buildSarifOutput(findings, lockfileUri, version, _plan, overrideFindings) {
77
79
  const ruleMap = new Map();
80
+ const ruleIndexMap = new Map();
78
81
  const results = [];
79
82
  for (const finding of findings) {
80
83
  const level = severityToSarifLevel(finding.severity);
@@ -90,6 +93,8 @@ export function buildSarifOutput(findings, lockfileUri, version, _plan, override
90
93
  : finding.vulnerabilities.map(v => v.id);
91
94
  for (const ruleId of ruleIds) {
92
95
  if (!ruleMap.has(ruleId)) {
96
+ // ruleMap.size before insertion = 0-based index of the new entry
97
+ ruleIndexMap.set(ruleId, ruleMap.size);
93
98
  const vuln = findVulnForRuleId(ruleId, finding.vulnerabilities);
94
99
  const summary = vuln?.summary;
95
100
  const details = vuln?.details;
@@ -102,29 +107,32 @@ export function buildSarifOutput(findings, lockfileUri, version, _plan, override
102
107
  fullDescription: { text: details ?? summary ?? `Vulnerable dependency: ${ruleId}` },
103
108
  ...(help !== undefined ? { help } : {}),
104
109
  helpUri: `https://osv.dev/vulnerability/${ruleId}`,
105
- defaultConfiguration: { level },
106
110
  properties: { tags: ["security", "dependency"] },
107
111
  });
108
112
  }
109
113
  results.push({
110
114
  ruleId,
115
+ ruleIndex: ruleIndexMap.get(ruleId),
116
+ kind: "open",
111
117
  level,
112
118
  message: {
113
119
  text: `${finding.pkg.name}@${finding.pkg.version} is vulnerable (${finding.severity}). ${action}`,
114
120
  },
115
121
  locations: [location],
122
+ partialFingerprints: {
123
+ primaryLocationLineHash: sarifFingerprintHash(`${ruleId}:${finding.pkg.name}@${finding.pkg.version}`),
124
+ },
116
125
  });
117
126
  }
118
127
  }
119
- const extensions = overrideFindings && overrideFindings.length > 0
120
- ? [buildOverrideSarifComponent()]
121
- : undefined;
128
+ const hasOverrides = overrideFindings != null && overrideFindings.length > 0;
129
+ const extensions = hasOverrides ? [buildOverrideSarifComponent()] : undefined;
122
130
  const allResults = [
123
131
  ...results,
124
- ...(overrideFindings ? buildOverrideSarifResults(overrideFindings) : []),
132
+ ...(hasOverrides ? buildOverrideSarifResults(overrideFindings) : []),
125
133
  ];
126
134
  return {
127
- $schema: "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
135
+ $schema: SARIF_SCHEMA,
128
136
  version: "2.1.0",
129
137
  runs: [
130
138
  {
@@ -6,6 +6,7 @@ import { loadFromPackageLock } from "../parsers/package-lock.js";
6
6
  import { loadFromPnpmLock } from "../parsers/pnpm-lock.js";
7
7
  import { loadFromYarnLock } from "../parsers/yarn-lock.js";
8
8
  import { loadFromBunLock } from "../parsers/bun-lock.js";
9
+ import { scanAllImports } from "../usage/scanner.js";
9
10
  export function buildOverrideContext(projectPath, opts) {
10
11
  const pkgJsonPath = join(projectPath, "package.json");
11
12
  if (!existsSync(pkgJsonPath)) {
@@ -32,6 +33,7 @@ export function buildOverrideContext(projectPath, opts) {
32
33
  skipped.push({ ruleId: "OA004", reason: "node_modules missing" });
33
34
  skipped.push({ ruleId: "OA006", reason: "node_modules missing" });
34
35
  skipped.push({ ruleId: "OA008", reason: "node_modules missing" });
36
+ skipped.push({ ruleId: "OA009", reason: "node_modules missing" });
35
37
  }
36
38
  // installedVersions: top-level node_modules/<name>/package.json reads.
37
39
  const installedVersions = new Map();
@@ -52,8 +54,13 @@ export function buildOverrideContext(projectPath, opts) {
52
54
  const tree = nodeModulesExists
53
55
  ? walkInstalledTree(projectPath)
54
56
  : { installedCopies: new Map(), parentDeclarations: new Map() };
57
+ // Seed parentDeclarations with the root project's own dep fields so OA009 can
58
+ // detect stale floors when the root project is the sole consumer of a package.
59
+ // walkInstalledTree only reads node_modules manifests; it never sees the root.
60
+ seedRootDeclarations(parsed, tree.parentDeclarations);
55
61
  // OA007 registry: only when --check-network. Empty otherwise.
56
62
  const registryDistTags = new Map();
63
+ const importedPackageNames = scanAllImports(projectPath);
57
64
  return {
58
65
  projectPath,
59
66
  packageJson: parsed,
@@ -66,6 +73,7 @@ export function buildOverrideContext(projectPath, opts) {
66
73
  parentDeclarations: tree.parentDeclarations,
67
74
  registryDistTags,
68
75
  skippedDetectors: skipped,
76
+ importedPackageNames,
69
77
  auditLog: opts.auditLog,
70
78
  logger: opts.logger,
71
79
  };
@@ -136,6 +144,27 @@ function readLockfileNames(projectPath, pm) {
136
144
  }
137
145
  return { kind: "absent" };
138
146
  }
147
+ function seedRootDeclarations(pkg, parentDeclarations) {
148
+ const rootName = typeof pkg.name === "string" ? pkg.name : "<root>";
149
+ const rootVersion = typeof pkg.version === "string" ? pkg.version : "0.0.0";
150
+ const sections = [
151
+ { deps: pkg.dependencies, declaredIn: "dependencies" },
152
+ { deps: pkg.devDependencies, declaredIn: "dependencies" },
153
+ { deps: pkg.optionalDependencies, declaredIn: "optionalDependencies" },
154
+ { deps: pkg.peerDependencies, declaredIn: "peerDependencies" },
155
+ ];
156
+ for (const { deps, declaredIn } of sections) {
157
+ if (!deps || typeof deps !== "object" || Array.isArray(deps))
158
+ continue;
159
+ for (const [depName, declaredValue] of Object.entries(deps)) {
160
+ if (typeof declaredValue !== "string")
161
+ continue;
162
+ const list = parentDeclarations.get(depName) ?? [];
163
+ list.push({ parentName: rootName, parentVersion: rootVersion, declaredIn, declaredValue, exactVersion: false });
164
+ parentDeclarations.set(depName, list);
165
+ }
166
+ }
167
+ }
139
168
  function readInstalledVersionTopLevel(projectPath, name) {
140
169
  const p = join(projectPath, "node_modules", ...name.split("/"), "package.json");
141
170
  try {
@@ -6,6 +6,9 @@ import { detect as detectOA005 } from "./oa005-nested-ineffective.js";
6
6
  import { detect as detectOA006 } from "./oa006-coupled-platform-binary.js";
7
7
  import { detect as detectOA007 } from "./oa007-frozen-latest.js";
8
8
  import { detect as detectOA008 } from "./oa008-materialized.js";
9
+ import { detect as detectOA009 } from "./oa009-stale-floor.js";
10
+ import { detect as detectPD001 } from "./pd001-override-only-phantom.js";
11
+ import { detect as detectPD002 } from "./pd002-transitive-only-phantom.js";
9
12
  export const ALL_DETECTORS = [
10
13
  { ruleId: "OA001", detect: detectOA001 },
11
14
  { ruleId: "OA002", detect: detectOA002 },
@@ -15,6 +18,9 @@ export const ALL_DETECTORS = [
15
18
  { ruleId: "OA006", detect: detectOA006 },
16
19
  { ruleId: "OA007", detect: detectOA007 },
17
20
  { ruleId: "OA008", detect: detectOA008 },
21
+ { ruleId: "OA009", detect: detectOA009 },
22
+ { ruleId: "PD001", detect: detectPD001 },
23
+ { ruleId: "PD002", detect: detectPD002 },
18
24
  ];
19
25
  /** Verify subset - just OA001 and OA008 - for the post-fix verify path. */
20
26
  export const VERIFY_DETECTORS = [
@@ -0,0 +1,80 @@
1
+ import { jsonPointer } from "../parsing/json-pointer.js";
2
+ import { looksLikeVersion, coerceVersion, compareVersions } from "../../utils/version.js";
3
+ const RULE_ID = "OA009";
4
+ function majorOf(version) {
5
+ return parseInt(version.split(".")[0] ?? "0", 10);
6
+ }
7
+ function getDeclaredPackages(packageJson) {
8
+ const declared = new Set();
9
+ for (const section of ["dependencies", "devDependencies"]) {
10
+ const deps = packageJson[section];
11
+ if (deps && typeof deps === "object" && !Array.isArray(deps)) {
12
+ for (const name of Object.keys(deps)) {
13
+ declared.add(name);
14
+ }
15
+ }
16
+ }
17
+ return declared;
18
+ }
19
+ export function detect(ctx) {
20
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
21
+ return [];
22
+ const findings = [];
23
+ for (const entry of ctx.overrideEntries) {
24
+ if (typeof entry.value !== "string")
25
+ continue;
26
+ const pin = entry.value.trim();
27
+ if (looksLikeVersion(pin))
28
+ continue;
29
+ if (!pin.startsWith(">=") && !pin.startsWith("^"))
30
+ continue;
31
+ const floor = coerceVersion(pin);
32
+ if (!floor)
33
+ continue;
34
+ if (!ctx.installedVersions.has(entry.packageName))
35
+ continue;
36
+ const parents = ctx.parentDeclarations.get(entry.packageName) ?? [];
37
+ if (parents.length === 0)
38
+ continue;
39
+ const floorMajor = pin.startsWith("^") ? majorOf(floor) : -1;
40
+ const allParentsMeetFloor = parents.every((parent) => {
41
+ const parentFloor = coerceVersion(parent.declaredValue);
42
+ if (!parentFloor)
43
+ return false;
44
+ // For ^ ranges the allowed range is [floor, nextMajor). A parent in a
45
+ // different major cannot overlap, so the override is not redundant.
46
+ if (floorMajor >= 0 && majorOf(parentFloor) !== floorMajor)
47
+ return false;
48
+ return compareVersions(parentFloor, floor) >= 0;
49
+ });
50
+ if (!allParentsMeetFloor)
51
+ continue;
52
+ // Safety guard: if this package is imported in source but not declared in
53
+ // dependencies, the override is the only thing making it available. Removing
54
+ // it would create a phantom import (PD001). OA009 must not fire.
55
+ if (ctx.importedPackageNames.has(entry.packageName)) {
56
+ const declared = getDeclaredPackages(ctx.packageJson);
57
+ if (!declared.has(entry.packageName))
58
+ continue;
59
+ }
60
+ findings.push({
61
+ ruleId: RULE_ID,
62
+ severity: "low",
63
+ package: { name: entry.packageName },
64
+ location: { file: "package.json", jsonPath: jsonPointer(entry.path) },
65
+ message: "Override floor already met by all parent declarations",
66
+ details: `${entry.packageName} is floored to ${pin}, but every package that depends on it ` +
67
+ `already declares a minimum version that meets or exceeds the floor. ` +
68
+ `Removing the override is safe.`,
69
+ fix: {
70
+ type: "rfc6902",
71
+ patch: [{ op: "remove", path: jsonPointer(entry.path) }],
72
+ runnableCommand: `cve-lite overrides --fix --rule OA009`,
73
+ },
74
+ references: [
75
+ "https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/OA009.md",
76
+ ],
77
+ });
78
+ }
79
+ return findings;
80
+ }
@@ -0,0 +1,32 @@
1
+ import { getDeclaredPackages, installCmd } from "./phantom-utils.js";
2
+ const RULE_ID = "PD001";
3
+ export function detect(ctx) {
4
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
5
+ return [];
6
+ if (ctx.importedPackageNames.size === 0)
7
+ return [];
8
+ const declared = getDeclaredPackages(ctx.packageJson);
9
+ const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
+ const cmd = installCmd(ctx.packageManager);
11
+ const findings = [];
12
+ for (const [pkgName, files] of ctx.importedPackageNames) {
13
+ if (declared.has(pkgName))
14
+ continue;
15
+ if (!overrideNames.has(pkgName))
16
+ continue;
17
+ const shown = files.slice(0, 3);
18
+ const extra = files.length > 3 ? ` (+${files.length - 3} more)` : "";
19
+ findings.push({
20
+ ruleId: RULE_ID,
21
+ severity: "high",
22
+ package: { name: pkgName },
23
+ location: { file: "package.json" },
24
+ message: `${pkgName} is imported in source but only present via an override pin - declare it as a dependency`,
25
+ details: `Imported in: ${shown.join(", ")}${extra}. ` +
26
+ `In pnpm strict mode (default on Vercel), override-only packages are not importable and will cause a deploy failure. ` +
27
+ `Run: ${cmd} ${pkgName}`,
28
+ references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD001.md"],
29
+ });
30
+ }
31
+ return findings;
32
+ }
@@ -0,0 +1,34 @@
1
+ import { getDeclaredPackages, installCmd } from "./phantom-utils.js";
2
+ const RULE_ID = "PD002";
3
+ export function detect(ctx) {
4
+ if (ctx.skippedDetectors.some((s) => s.ruleId === RULE_ID))
5
+ return [];
6
+ if (ctx.importedPackageNames.size === 0)
7
+ return [];
8
+ const declared = getDeclaredPackages(ctx.packageJson);
9
+ const overrideNames = new Set(ctx.overrideEntries.map((e) => e.packageName));
10
+ const cmd = installCmd(ctx.packageManager);
11
+ const findings = [];
12
+ for (const [pkgName, files] of ctx.importedPackageNames) {
13
+ if (declared.has(pkgName))
14
+ continue;
15
+ if (overrideNames.has(pkgName))
16
+ continue; // PD001 owns this
17
+ if (!ctx.lockfilePackageNames.has(pkgName))
18
+ continue; // not in graph
19
+ const shown = files.slice(0, 3);
20
+ const extra = files.length > 3 ? ` (+${files.length - 3} more)` : "";
21
+ findings.push({
22
+ ruleId: RULE_ID,
23
+ severity: "medium",
24
+ package: { name: pkgName },
25
+ location: { file: "package.json" },
26
+ message: `${pkgName} is imported in source but only present as a transitive dependency - declare it explicitly`,
27
+ details: `Imported in: ${shown.join(", ")}${extra}. ` +
28
+ `If the parent package drops or changes this dependency, your code will break without warning. ` +
29
+ `Run: ${cmd} ${pkgName}`,
30
+ references: ["https://github.com/OWASP/cve-lite-cli/blob/main/docs/rules/PD002.md"],
31
+ });
32
+ }
33
+ return findings;
34
+ }
@@ -0,0 +1,21 @@
1
+ export function getDeclaredPackages(packageJson) {
2
+ const declared = new Set();
3
+ for (const section of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
4
+ const deps = packageJson[section];
5
+ if (deps && typeof deps === "object" && !Array.isArray(deps)) {
6
+ for (const name of Object.keys(deps)) {
7
+ declared.add(name);
8
+ }
9
+ }
10
+ }
11
+ return declared;
12
+ }
13
+ export function installCmd(pm) {
14
+ if (pm === "pnpm")
15
+ return "pnpm add";
16
+ if (pm === "yarn")
17
+ return "yarn add";
18
+ if (pm === "bun")
19
+ return "bun add";
20
+ return "npm install";
21
+ }
@@ -70,7 +70,7 @@ export function applyFix(opts) {
70
70
  }
71
71
  if (!dryRun && applied.length > 0) {
72
72
  const indent = detectIndent(original);
73
- writeFileSync(pkgPath, JSON.stringify(state, null, indent) + "\n");
73
+ writeFileSync(pkgPath, JSON.stringify(pruneEmptyOverrideContainers(state), null, indent) + "\n");
74
74
  }
75
75
  return {
76
76
  appliedAt: new Date().toISOString(),
@@ -79,6 +79,26 @@ export function applyFix(opts) {
79
79
  skipped,
80
80
  };
81
81
  }
82
+ function isEmpty(val) {
83
+ return !!val && typeof val === "object" && !Array.isArray(val) && Object.keys(val).length === 0;
84
+ }
85
+ function pruneEmptyOverrideContainers(doc) {
86
+ const result = { ...doc };
87
+ for (const key of ["overrides", "resolutions"]) {
88
+ if (isEmpty(result[key]))
89
+ delete result[key];
90
+ }
91
+ const pnpm = result.pnpm;
92
+ if (pnpm && typeof pnpm === "object" && !Array.isArray(pnpm)) {
93
+ const pnpmObj = { ...pnpm };
94
+ if (isEmpty(pnpmObj.overrides))
95
+ delete pnpmObj.overrides;
96
+ result.pnpm = Object.keys(pnpmObj).length === 0 ? undefined : pnpmObj;
97
+ if (result.pnpm === undefined)
98
+ delete result.pnpm;
99
+ }
100
+ return result;
101
+ }
82
102
  function detectIndent(raw) {
83
103
  const m = raw.match(/^\{\n([ \t]+)/);
84
104
  if (!m)
@@ -1,5 +1,6 @@
1
1
  import path from "node:path";
2
2
  import process from "node:process";
3
+ import { EXIT_OK, EXIT_FINDINGS, EXIT_ERROR } from "../types.js";
3
4
  import { loadMultiplePackages } from "../parsers/multi-package.js";
4
5
  import { scanPackages, buildCoverageNotes } from "../scanner.js";
5
6
  import { sortFindingsForOutput } from "../output/formatters.js";
@@ -67,18 +68,15 @@ export async function handleMultiFolderScan(params) {
67
68
  const results = await runMultiFolderScan(params);
68
69
  if (results.length === 0) {
69
70
  console.log(chalk.yellow("No scannable packages found in any subfolder."));
70
- process.exit(0);
71
- return;
71
+ return EXIT_OK;
72
72
  }
73
73
  if (params.options.fix) {
74
74
  console.error(chalk.yellow("--fix is not yet supported in multi-folder mode. Run cve-lite . from each subfolder individually."));
75
- process.exit(1);
76
- return;
75
+ return EXIT_ERROR;
77
76
  }
78
77
  if (params.options.sarif || params.options.cdx) {
79
78
  console.error(chalk.yellow("--sarif and --cdx are not yet supported in multi-folder mode."));
80
- process.exit(1);
81
- return;
79
+ return EXIT_ERROR;
82
80
  }
83
81
  if (params.options.json) {
84
82
  const { serializeFinding } = await import("../output/formatters.js");
@@ -101,7 +99,7 @@ export async function handleMultiFolderScan(params) {
101
99
  const { renderOverrideFindings } = await import("../output/override-findings-terminal.js");
102
100
  for (const r of results) {
103
101
  process.stdout.write(`\n${chalk.bold.cyan(`📁 ${r.subfolder}/`)} ${chalk.gray("override hygiene")}\n`);
104
- console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose }));
102
+ console.log(renderOverrideFindings(r.overrideFindings, { verbose: !!params.options.verbose, projectPath: path.join(params.projectRoot, r.subfolder) }));
105
103
  }
106
104
  }
107
105
  if (!params.options.checkOverrides && !params.options.ratchet) {
@@ -129,5 +127,5 @@ export async function handleMultiFolderScan(params) {
129
127
  const failLevel = normalizeSeverity(params.options.failOn);
130
128
  const allSorted = results.flatMap(r => r.sorted);
131
129
  const shouldFail = allSorted.some(f => severityOrder[f.severity] >= severityOrder[failLevel]);
132
- process.exit(shouldFail ? 1 : 0);
130
+ return shouldFail ? EXIT_FINDINGS : EXIT_OK;
133
131
  }
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  // Shared with lockfile scanning in utils/file.ts; additions affect both code paths.
4
4
  import { EXCLUDED_DIRS } from "../constants.js";
5
5
  const ALLOWED_EXTS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
6
+ const MAX_FILES_TO_SCAN = 5000;
6
7
  // Matches:
7
8
  // import { foo } from 'pkg'
8
9
  // import * as foo from "pkg"
@@ -30,7 +31,6 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
30
31
  return results;
31
32
  }
32
33
  // Cap at 5000 files to prevent performance issues on massive projects
33
- const MAX_FILES_TO_SCAN = 5000;
34
34
  let scannedCount = 0;
35
35
  function walk(dir) {
36
36
  if (scannedCount >= MAX_FILES_TO_SCAN)
@@ -98,3 +98,62 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
98
98
  walk(projectPath);
99
99
  return results;
100
100
  }
101
+ export function scanAllImports(projectPath) {
102
+ const results = new Map();
103
+ let scannedCount = 0;
104
+ function walk(dir) {
105
+ if (scannedCount >= MAX_FILES_TO_SCAN)
106
+ return;
107
+ let entries;
108
+ try {
109
+ entries = fs.readdirSync(dir, { withFileTypes: true });
110
+ }
111
+ catch {
112
+ return;
113
+ }
114
+ for (const entry of entries) {
115
+ if (scannedCount >= MAX_FILES_TO_SCAN)
116
+ return;
117
+ const fullPath = path.join(dir, entry.name);
118
+ if (entry.isDirectory()) {
119
+ if (!EXCLUDED_DIRS.has(entry.name) && !entry.name.startsWith(".")) {
120
+ walk(fullPath);
121
+ }
122
+ }
123
+ else if (entry.isFile()) {
124
+ const ext = path.extname(entry.name);
125
+ if (ALLOWED_EXTS.has(ext)) {
126
+ scanFile(fullPath);
127
+ scannedCount++;
128
+ }
129
+ }
130
+ }
131
+ }
132
+ function scanFile(filePath) {
133
+ let content;
134
+ try {
135
+ content = fs.readFileSync(filePath, "utf8");
136
+ }
137
+ catch {
138
+ return;
139
+ }
140
+ if (!content.includes("import") && !content.includes("require") && !content.includes("export"))
141
+ return;
142
+ const matches = content.matchAll(IMPORT_REQUIRE_REGEX);
143
+ const relPath = path.relative(projectPath, filePath);
144
+ for (const match of matches) {
145
+ const importPath = match[1] || match[2] || match[3] || match[4];
146
+ if (!importPath)
147
+ continue;
148
+ const bare = getBareModuleName(importPath);
149
+ if (!bare)
150
+ continue;
151
+ const existing = results.get(bare) ?? [];
152
+ if (!existing.includes(relPath))
153
+ existing.push(relPath);
154
+ results.set(bare, existing);
155
+ }
156
+ }
157
+ walk(projectPath);
158
+ return results;
159
+ }
@@ -140,3 +140,14 @@ export function isLikelyBlockedAdvisoryRequestError(message) {
140
140
  }
141
141
  return /^(401|403|407|408|451)\b/.test(finalCause);
142
142
  }
143
+ export function getNetworkErrorHint(error, errorMessage) {
144
+ if (isSslCertificateError(error))
145
+ return sslCertificateErrorHint();
146
+ if (isRateLimitError(errorMessage))
147
+ return rateLimitAdvisoryRequestHint();
148
+ if (isServerError(errorMessage))
149
+ return serverAdvisoryRequestHint();
150
+ if (isLikelyBlockedAdvisoryRequestError(errorMessage))
151
+ return blockedAdvisoryRequestHint();
152
+ return fetchErrorCaCertHint();
153
+ }
@@ -0,0 +1,4 @@
1
+ import { createHash } from "node:crypto";
2
+ export function sarifFingerprintHash(key) {
3
+ return createHash("sha256").update(key).digest("hex").slice(0, 16);
4
+ }