cve-lite-cli 1.37.0 → 1.39.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.
Files changed (47) hide show
  1. package/README.md +20 -1
  2. package/dist/cli/args.js +121 -104
  3. package/dist/cli/flags.js +39 -0
  4. package/dist/cli/help.js +6 -3
  5. package/dist/cli/overrides.js +25 -19
  6. package/dist/cli/validate.js +31 -9
  7. package/dist/index.js +6 -1
  8. package/dist/output/compact-truncation.js +35 -0
  9. package/dist/output/formatters.js +10 -2
  10. package/dist/output/html-reporter.js +24 -12
  11. package/dist/output/multi-folder-html-reporter.js +26 -7
  12. package/dist/output/override-findings-html.js +24 -3
  13. package/dist/output/override-findings-json.js +5 -2
  14. package/dist/output/override-findings-sarif.js +1 -0
  15. package/dist/output/override-findings-terminal.js +21 -1
  16. package/dist/output/printers.js +34 -21
  17. package/dist/output/sarif.js +54 -3
  18. package/dist/output/scan-json.js +74 -0
  19. package/dist/output/skipped-override-rules.js +41 -0
  20. package/dist/output/write-outputs.js +16 -28
  21. package/dist/overrides/admitted-scan.js +12 -1
  22. package/dist/overrides/api.js +75 -21
  23. package/dist/overrides/context-builder.js +49 -6
  24. package/dist/overrides/detectors/index.js +2 -0
  25. package/dist/overrides/detectors/oa005-nested-ineffective.js +50 -2
  26. package/dist/overrides/detectors/oa008-materialized.js +72 -13
  27. package/dist/overrides/detectors/oa009-stale-floor.js +12 -15
  28. package/dist/overrides/detectors/oa010-vulnerable-floor.js +5 -1
  29. package/dist/overrides/detectors/oa011-exceeds-range.js +128 -0
  30. package/dist/overrides/detectors/pd001-override-only-phantom.js +5 -4
  31. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +5 -4
  32. package/dist/overrides/detectors/phantom-utils.js +29 -0
  33. package/dist/overrides/parsing/registry.js +79 -10
  34. package/dist/scan/multi-folder-scan.js +65 -51
  35. package/dist/scan/override-audit.js +49 -0
  36. package/dist/scan/single-scan.js +109 -33
  37. package/dist/scanner.js +8 -4
  38. package/dist/skills/content.js +4 -2
  39. package/dist/usage/scanner.js +219 -28
  40. package/dist/utils/contextual-signals.js +193 -0
  41. package/dist/utils/finding.js +5 -0
  42. package/dist/utils/node-builtins.js +32 -0
  43. package/dist/utils/package-json.js +66 -14
  44. package/dist/utils/severity.js +22 -0
  45. package/dist/utils/update-check.js +2 -1
  46. package/dist/utils/version.js +37 -19
  47. package/package.json +1 -1
package/dist/scanner.js CHANGED
@@ -763,7 +763,7 @@ async function validateOneDirectFixTarget(finding, options) {
763
763
  };
764
764
  npmVersionCacheUpdated = true;
765
765
  };
766
- if (lowestKnownResolution.resolvedVersion) {
766
+ if (lowestKnownResolution.resolvedVersion && lowestKnownResolution.verified) {
767
767
  finding.validatedFirstFixedVersion = lowestKnownResolution.resolvedVersion;
768
768
  finding.validatedTargetScannedVersions = lowestKnownResolution.candidatesChecked;
769
769
  finding.validatedTargetKnownVulnerableVersions = lowestKnownResolution.candidatesKnownVulnerable;
@@ -798,11 +798,15 @@ async function validateOneDirectFixTarget(finding, options) {
798
798
  return npmVersionCacheUpdated;
799
799
  }
800
800
  const resolution = await resolvePublishedFixVersion(finding.pkg.name, fixedVersionHint);
801
- finding.validatedFirstFixedVersion = resolution.resolvedVersion;
802
- finding.fixVersionValidationNote = resolution.note ?? lowestKnownResolution.note;
801
+ // Publication confirms availability, not that every advisory is fixed.
802
+ finding.validatedFirstFixedVersion = null;
803
+ finding.fixVersionValidationNote = [
804
+ lowestKnownResolution.note ?? `A non-vulnerable version could not be confirmed for ${finding.pkg.name}.`,
805
+ resolution.note,
806
+ ].filter(Boolean).join(" ");
803
807
  finding.validatedTargetScannedVersions = null;
804
808
  finding.validatedTargetKnownVulnerableVersions = null;
805
- setPublishedDate(resolution);
809
+ finding.fixVersionPublishedAt = null;
806
810
  logFixValidation();
807
811
  return npmVersionCacheUpdated;
808
812
  }
@@ -12,7 +12,8 @@ Key fields in each finding:
12
12
  - \`recommendedAction\` — human-readable fix guidance
13
13
  - \`cves\` — CVE IDs
14
14
  - \`dependencyPaths\` — chains showing how the package is pulled in
15
- - \`usage.imported\` — whether the package is actually imported in source files
15
+ - \`usage.imported\` — whether the package is imported in source files; \`null\` when the usage scan hit its file cap (import status unknown), and \`usage\` itself is \`null\` when \`--usage\` was not run
16
+ - \`contextualSignals\` — heuristic prioritization hints (\`usage\`, \`reachabilityHint\`, \`exposure\`). Not exploitability verdicts; \`not_imported\` / \`not_indicated\` does not mean safe or unreachable
16
17
 
17
18
  Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
18
19
 
@@ -22,10 +23,11 @@ Top-level \`suggestedFixCommands\` contains grouped, copy-ready fix commands.
22
23
  2. Direct dependencies before transitive
23
24
  3. If \`usage.imported === false\`, flag as lower practical risk but do not dismiss
24
25
  4. If \`runnableFixCommand\` is present, that is the exact command to run — prefer it over manual guidance
26
+ 5. Treat \`contextualSignals\` as triage context only — never as exploitability or runtime reachability
25
27
 
26
28
  ### Codebase analysis
27
29
 
28
- - Cross-reference vulnerable packages against source file imports to confirm reachability
30
+ - Cross-reference vulnerable packages against source file imports as a heuristic only; an import match is not proof of runtime reachability
29
31
  - Check \`package.json\` version constraints for direct dependency findings
30
32
  - Use \`dependencyPaths\` to trace transitive chains and identify which parent package to upgrade
31
33
  - Look for patterns: a single parent responsible for multiple transitive findings (fixing the parent clears all of them)
@@ -2,7 +2,21 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { EXCLUDED_DIRS } from "../constants.js";
4
4
  const ALLOWED_EXTS = new Set([".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs"]);
5
- const MAX_FILES_TO_SCAN = 5000;
5
+ export const MAX_FILES_TO_SCAN = 5000;
6
+ /**
7
+ * Single source of truth for the cap disclosure, so the three call sites cannot
8
+ * drift. When `onlyUsed` is set the message states the actionable consequence:
9
+ * the filter was skipped, which is why a package with no import found is still
10
+ * reported. Otherwise it only warns that coverage is incomplete.
11
+ */
12
+ export function usageScanTruncationWarning(opts) {
13
+ const scope = opts?.subfolder ? ` in ${opts.subfolder}/` : "";
14
+ const head = `Usage scan stopped at ${MAX_FILES_TO_SCAN} files${scope}`;
15
+ if (opts?.onlyUsed) {
16
+ return `${head}; --only-used filtering was skipped so packages imported only in unscanned files are not dropped.`;
17
+ }
18
+ return `${head}; packages imported only in unscanned files may not be detected.`;
19
+ }
6
20
  const ALL_IMPORTS_EXCLUDED_DIRS = new Set([
7
21
  ...EXCLUDED_DIRS,
8
22
  "__fixtures__",
@@ -22,6 +36,181 @@ const ALL_IMPORTS_EXCLUDED_DIRS = new Set([
22
36
  // require('pkg')
23
37
  // await import('pkg')
24
38
  const IMPORT_REQUIRE_REGEX = /(?:(?:import|export)\s+[\w\s{},*]+\s+from\s+['"]([^'"]+)['"]|import\s+['"]([^'"]+)['"]|require\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s*\(\s*['"]([^'"]+)['"]\s*\))/g;
39
+ // A `/` opens a regex literal only where an expression may begin. After a value
40
+ // - an identifier, a number, `)`, `]` or a closing backtick - it is division.
41
+ // These keywords are the cases where a `/` directly after a word is still a
42
+ // regex, as in `return /x/.test(s)`.
43
+ const REGEX_AFTER_KEYWORDS = new Set([
44
+ "return", "typeof", "case", "in", "of", "new", "delete", "void", "do", "else",
45
+ "yield", "await", "instanceof",
46
+ ]);
47
+ function regexCanStartAfter(prev, prevWord) {
48
+ if (prev === "")
49
+ return true;
50
+ if (REGEX_AFTER_KEYWORDS.has(prevWord))
51
+ return true;
52
+ // `}` is ambiguous without a parser (block end versus object literal end).
53
+ // Treated as expression position, which is the commoner case, and a
54
+ // misjudgement here costs at most one line because a regex literal cannot
55
+ // span a newline.
56
+ return !/[\w$)\]`]/.test(prev);
57
+ }
58
+ // Blank out `//` and `/* */` comments so the import regex never matches text
59
+ // that is not code. The motivating case is a JSDoc annotation such as
60
+ // `/** @type {import('postcss-load-config').Config} */`: nothing loads that
61
+ // package at runtime, but a raw-text regex sees `import('...')` and counts it
62
+ // as a dynamic import. String literals are tracked so a `//` inside
63
+ // 'https://...' is not mistaken for a line comment. Comment bodies are
64
+ // replaced with spaces (newlines kept) so nothing else shifts position.
65
+ //
66
+ // Regex literals are tracked for the same reason, and the cost of not doing so
67
+ // is severe rather than cosmetic: in `const sep = /[/*]/;` the `/` inside the
68
+ // character class would otherwise read as the start of a block comment, which
69
+ // then runs to the next `*/` or to end of file, blanking every import after it.
70
+ // stripComments runs these for nearly every character of every scanned file,
71
+ // so they are integer comparisons rather than `/\s/` and `/[\w$]/` tests. On a
72
+ // 2.2 MB corpus that difference is about 20ms per pass. Code points above ASCII
73
+ // fall back to the original regexes, so the semantics are exactly those of `\s`
74
+ // and `[\w$]` rather than an approximation that happens to hold for our files.
75
+ const FIRST_NON_ASCII = 0x80;
76
+ function isWhitespaceChar(code, ch) {
77
+ if (code >= FIRST_NON_ASCII)
78
+ return /\s/.test(ch);
79
+ // ASCII `\s` is space plus the 0x09 to 0x0d run (tab, LF, VT, FF, CR).
80
+ return code === 0x20 || (code >= 0x09 && code <= 0x0d);
81
+ }
82
+ function isWordChar(code, ch) {
83
+ if (code >= FIRST_NON_ASCII)
84
+ return /[\w$]/.test(ch);
85
+ return ((code >= 0x61 && code <= 0x7a) || // a-z
86
+ (code >= 0x41 && code <= 0x5a) || // A-Z
87
+ (code >= 0x30 && code <= 0x39) || // 0-9
88
+ code === 0x5f || // _
89
+ code === 0x24 // $
90
+ );
91
+ }
92
+ export function stripComments(source) {
93
+ let out = "";
94
+ let i = 0;
95
+ const n = source.length;
96
+ // Last non-whitespace character of emitted code, and the identifier run
97
+ // ending at it. Both ignore comment and string bodies.
98
+ let prev = "";
99
+ let prevWord = "";
100
+ while (i < n) {
101
+ const ch = source[i];
102
+ const next = source[i + 1];
103
+ if (ch === "/" && next === "/") {
104
+ while (i < n && source[i] !== "\n")
105
+ i++;
106
+ out += " ";
107
+ continue;
108
+ }
109
+ if (ch === "/" && next === "*") {
110
+ i += 2;
111
+ while (i < n && !(source[i] === "*" && source[i + 1] === "/")) {
112
+ out += source[i] === "\n" ? "\n" : " ";
113
+ i++;
114
+ }
115
+ i += 2;
116
+ out += " ";
117
+ continue;
118
+ }
119
+ if (ch === "'" || ch === '"' || ch === "`") {
120
+ const quote = ch;
121
+ prev = quote;
122
+ prevWord = "";
123
+ out += ch;
124
+ i++;
125
+ while (i < n) {
126
+ const c = source[i];
127
+ out += c;
128
+ i++;
129
+ if (c === "\\" && i < n) {
130
+ out += source[i];
131
+ i++;
132
+ continue;
133
+ }
134
+ if (c === quote)
135
+ break;
136
+ // An unterminated ' or " string ends at the line break; template
137
+ // literals may span lines.
138
+ if (c === "\n" && quote !== "`")
139
+ break;
140
+ }
141
+ continue;
142
+ }
143
+ if (ch === "/" && regexCanStartAfter(prev, prevWord)) {
144
+ out += ch;
145
+ i++;
146
+ let inCharClass = false;
147
+ while (i < n) {
148
+ const c = source[i];
149
+ // A regex literal cannot contain an unescaped newline. Bailing here
150
+ // bounds the damage of a misjudged division to a single line.
151
+ if (c === "\n")
152
+ break;
153
+ out += c;
154
+ i++;
155
+ if (c === "\\") {
156
+ if (i < n && source[i] !== "\n") {
157
+ out += source[i];
158
+ i++;
159
+ }
160
+ continue;
161
+ }
162
+ if (c === "[")
163
+ inCharClass = true;
164
+ else if (c === "]")
165
+ inCharClass = false;
166
+ else if (c === "/" && !inCharClass)
167
+ break;
168
+ }
169
+ prev = "/";
170
+ prevWord = "";
171
+ continue;
172
+ }
173
+ const code = source.charCodeAt(i);
174
+ if (!isWhitespaceChar(code, ch)) {
175
+ prev = ch;
176
+ prevWord = isWordChar(code, ch) ? prevWord + ch : "";
177
+ }
178
+ out += ch;
179
+ i++;
180
+ }
181
+ return out;
182
+ }
183
+ // `import type { X } from 'pkg'`, `export type { X } from 'pkg'`, and
184
+ // `import { type A, type B } from 'pkg'` are erased by the TypeScript compiler
185
+ // and never load `pkg` at runtime. A default import that happens to be named
186
+ // `type` (`import type from 'pkg'`) or a mixed list (`import { type A, b }`)
187
+ // still loads the module and is kept.
188
+ export function isTypeOnlyImportStatement(statement) {
189
+ const clause = /^(?:import|export)\s+([\s\S]*?)\s+from\s/.exec(statement)?.[1]?.trim();
190
+ if (!clause)
191
+ return false;
192
+ if (/^type\s+[\w{*]/.test(clause))
193
+ return true;
194
+ const braced = /^\{([\s\S]*)\}$/.exec(clause);
195
+ if (!braced)
196
+ return false;
197
+ const specifiers = braced[1].split(",").map(s => s.trim()).filter(Boolean);
198
+ return specifiers.length > 0 && specifiers.every(s => /^type\s+\S/.test(s));
199
+ }
200
+ // Every module specifier that `content` would actually load at runtime:
201
+ // static imports and re-exports, side-effect imports, `require()` and dynamic
202
+ // `import()`, minus anything inside a comment or in a type-only import.
203
+ function collectRuntimeImportPaths(content) {
204
+ const paths = [];
205
+ for (const match of stripComments(content).matchAll(IMPORT_REQUIRE_REGEX)) {
206
+ if (match[1] && isTypeOnlyImportStatement(match[0]))
207
+ continue;
208
+ const importPath = match[1] || match[2] || match[3] || match[4];
209
+ if (importPath)
210
+ paths.push(importPath);
211
+ }
212
+ return paths;
213
+ }
25
214
  function getBareModuleName(importPath) {
26
215
  if (importPath.startsWith(".") || importPath.startsWith("/")) {
27
216
  return "";
@@ -33,17 +222,17 @@ function getBareModuleName(importPath) {
33
222
  return importPath.split("/")[0];
34
223
  }
35
224
  export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
36
- const results = {};
225
+ const usage = {};
37
226
  for (const pkg of packagesToLookFor) {
38
- results[pkg] = [];
227
+ usage[pkg] = [];
39
228
  }
40
229
  if (packagesToLookFor.size === 0) {
41
- return results;
230
+ return { usage, truncated: false, scannedFiles: 0 };
42
231
  }
43
- // Cap at 5000 files to prevent performance issues on massive projects
44
232
  let scannedCount = 0;
233
+ let truncated = false;
45
234
  function walk(dir) {
46
- if (scannedCount >= MAX_FILES_TO_SCAN)
235
+ if (truncated)
47
236
  return;
48
237
  let entries;
49
238
  try {
@@ -53,7 +242,7 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
53
242
  return;
54
243
  }
55
244
  for (const entry of entries) {
56
- if (scannedCount >= MAX_FILES_TO_SCAN)
245
+ if (truncated)
57
246
  return;
58
247
  const fullPath = path.join(dir, entry.name);
59
248
  if (entry.isDirectory()) {
@@ -64,6 +253,11 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
64
253
  else if (entry.isFile()) {
65
254
  const ext = path.extname(entry.name);
66
255
  if (ALLOWED_EXTS.has(ext)) {
256
+ // Cap at 5000 files to prevent performance issues on massive projects
257
+ if (scannedCount >= MAX_FILES_TO_SCAN) {
258
+ truncated = true;
259
+ return;
260
+ }
67
261
  scanFile(fullPath);
68
262
  scannedCount++;
69
263
  }
@@ -88,31 +282,28 @@ export function scanProjectForPackageUsage(projectPath, packagesToLookFor) {
88
282
  }
89
283
  if (!hasPotentialMatch)
90
284
  return;
91
- const matches = content.matchAll(IMPORT_REQUIRE_REGEX);
92
285
  const foundPackages = new Set();
93
- for (const match of matches) {
94
- const importPath = match[1] || match[2] || match[3] || match[4];
95
- if (importPath) {
96
- const bare = getBareModuleName(importPath);
97
- if (bare && packagesToLookFor.has(bare)) {
98
- foundPackages.add(bare);
99
- }
286
+ for (const importPath of collectRuntimeImportPaths(content)) {
287
+ const bare = getBareModuleName(importPath);
288
+ if (bare && packagesToLookFor.has(bare)) {
289
+ foundPackages.add(bare);
100
290
  }
101
291
  }
102
292
  for (const pkg of foundPackages) {
103
293
  // Store relative path for cleaner output
104
294
  const relPath = path.relative(projectPath, filePath);
105
- results[pkg].push(relPath);
295
+ usage[pkg].push(relPath);
106
296
  }
107
297
  }
108
298
  walk(projectPath);
109
- return results;
299
+ return { usage, truncated, scannedFiles: scannedCount };
110
300
  }
111
301
  export function scanAllImports(projectPath) {
112
- const results = new Map();
302
+ const imports = new Map();
113
303
  let scannedCount = 0;
304
+ let truncated = false;
114
305
  function walk(dir) {
115
- if (scannedCount >= MAX_FILES_TO_SCAN)
306
+ if (truncated)
116
307
  return;
117
308
  let entries;
118
309
  try {
@@ -122,7 +313,7 @@ export function scanAllImports(projectPath) {
122
313
  return;
123
314
  }
124
315
  for (const entry of entries) {
125
- if (scannedCount >= MAX_FILES_TO_SCAN)
316
+ if (truncated)
126
317
  return;
127
318
  const fullPath = path.join(dir, entry.name);
128
319
  if (entry.isDirectory()) {
@@ -133,6 +324,10 @@ export function scanAllImports(projectPath) {
133
324
  else if (entry.isFile()) {
134
325
  const ext = path.extname(entry.name);
135
326
  if (ALLOWED_EXTS.has(ext)) {
327
+ if (scannedCount >= MAX_FILES_TO_SCAN) {
328
+ truncated = true;
329
+ return;
330
+ }
136
331
  scanFile(fullPath);
137
332
  scannedCount++;
138
333
  }
@@ -149,21 +344,17 @@ export function scanAllImports(projectPath) {
149
344
  }
150
345
  if (!content.includes("import") && !content.includes("require") && !content.includes("export"))
151
346
  return;
152
- const matches = content.matchAll(IMPORT_REQUIRE_REGEX);
153
347
  const relPath = path.relative(projectPath, filePath);
154
- for (const match of matches) {
155
- const importPath = match[1] || match[2] || match[3] || match[4];
156
- if (!importPath)
157
- continue;
348
+ for (const importPath of collectRuntimeImportPaths(content)) {
158
349
  const bare = getBareModuleName(importPath);
159
350
  if (!bare)
160
351
  continue;
161
- const existing = results.get(bare) ?? [];
352
+ const existing = imports.get(bare) ?? [];
162
353
  if (!existing.includes(relPath))
163
354
  existing.push(relPath);
164
- results.set(bare, existing);
355
+ imports.set(bare, existing);
165
356
  }
166
357
  }
167
358
  walk(projectPath);
168
- return results;
359
+ return { imports, truncated, scannedFiles: scannedCount };
169
360
  }
@@ -0,0 +1,193 @@
1
+ /**
2
+ * Heuristic package-name markers for server / request-facing stacks.
3
+ *
4
+ * Matching is path-name only (lockfile chains + the finding package). It is not
5
+ * a network probe, a runtime check, or an exploitability verdict.
6
+ *
7
+ * Short/generic names (`http`, `next`, `router`, …) match the exact package or
8
+ * a scoped prefix such as `@next/` — never hyphenated lookalikes. Distinctive
9
+ * stacks (`express`, `fastify`, `@nestjs/`, …) still allow hyphen/token forms.
10
+ */
11
+ export const REQUEST_FACING_MARKERS = [
12
+ "express",
13
+ "fastify",
14
+ "koa-router",
15
+ "koa",
16
+ "hapi",
17
+ "@hapi/",
18
+ "nestjs",
19
+ "@nestjs/",
20
+ "apollo-server",
21
+ "@apollo/server",
22
+ "graphql",
23
+ "restify",
24
+ "connect",
25
+ "polka",
26
+ "hono",
27
+ "next",
28
+ "@remix-run",
29
+ "astro",
30
+ "http",
31
+ "https",
32
+ "router",
33
+ ];
34
+ /** Short/generic markers: no hyphen token matching (`next-tick`, `https-proxy-agent`). */
35
+ const EXACT_OR_SCOPED_MARKERS = new Set([
36
+ "http",
37
+ "https",
38
+ "next",
39
+ "router",
40
+ "connect",
41
+ "koa",
42
+ "hapi",
43
+ "graphql",
44
+ "astro",
45
+ ]);
46
+ /** Subset that must not use an `@<name>/` scoped prefix either. */
47
+ const EXACT_NAME_ONLY_MARKERS = new Set(["http", "https", "router"]);
48
+ function signal(value, basis) {
49
+ return { value, basis, heuristic: true };
50
+ }
51
+ function shortestLockfileHops(paths) {
52
+ if (!paths || paths.length === 0)
53
+ return null;
54
+ let min = null;
55
+ for (const path of paths) {
56
+ if (path.length === 0)
57
+ continue;
58
+ const hops = path.length - 1;
59
+ if (min === null || hops < min)
60
+ min = hops;
61
+ }
62
+ return min;
63
+ }
64
+ /**
65
+ * Package names to inspect for exposure markers: the finding itself, plus every
66
+ * lockfile path entry except the first (project root) when the path is longer
67
+ * than one hop.
68
+ */
69
+ export function collectPathPackageNames(finding) {
70
+ const names = new Set();
71
+ if (finding.pkg?.name)
72
+ names.add(finding.pkg.name);
73
+ for (const path of finding.dependencyPaths ?? []) {
74
+ const start = path.length > 1 ? 1 : 0;
75
+ for (let i = start; i < path.length; i++) {
76
+ const name = path[i];
77
+ if (name)
78
+ names.add(name);
79
+ }
80
+ }
81
+ return [...names];
82
+ }
83
+ /**
84
+ * True when `pkgName` looks like the marker as a package identity, not an
85
+ * accidental substring (so `http` does not match `https-proxy-agent`).
86
+ */
87
+ export function packageNameMatchesExposureMarker(pkgName, marker) {
88
+ const name = pkgName.toLowerCase();
89
+ const m = marker.toLowerCase();
90
+ if (m.endsWith("/")) {
91
+ return name === m.slice(0, -1) || name.startsWith(m);
92
+ }
93
+ if (name === m)
94
+ return true;
95
+ if (EXACT_OR_SCOPED_MARKERS.has(m)) {
96
+ if (EXACT_NAME_ONLY_MARKERS.has(m))
97
+ return false;
98
+ return name.startsWith(`@${m}/`);
99
+ }
100
+ if (name.startsWith(`${m}/`) || name.startsWith(`${m}-`))
101
+ return true;
102
+ if (name.endsWith(`-${m}`) || name.includes(`-${m}-`))
103
+ return true;
104
+ if (!m.startsWith("@") && name.startsWith(`@${m}/`))
105
+ return true;
106
+ return false;
107
+ }
108
+ export function matchRequestFacingMarkers(packageNames) {
109
+ const matched = new Set();
110
+ for (const pkgName of packageNames) {
111
+ for (const marker of REQUEST_FACING_MARKERS) {
112
+ if (packageNameMatchesExposureMarker(pkgName, marker)) {
113
+ matched.add(marker);
114
+ }
115
+ }
116
+ }
117
+ return [...matched].sort((a, b) => b.length - a.length || a.localeCompare(b));
118
+ }
119
+ function computeUsageSignal(finding) {
120
+ // undefined usage = --usage was never run (no signal); null imported = the
121
+ // scan ran but stopped at the file cap, so import status is genuinely unknown.
122
+ if (!finding.usage)
123
+ return null;
124
+ if (finding.usage.imported === null) {
125
+ return signal("unknown", "heuristic prioritization signal: usage scan stopped at the file cap, so import status could not be determined; not a claim of non-exploitability");
126
+ }
127
+ if (finding.usage.imported) {
128
+ const count = finding.usage.files.length;
129
+ const files = count === 1 ? "1 file" : `${count} files`;
130
+ return signal("imported", `heuristic prioritization signal: package name matched in the project import/require scan (${files}); not an exploitability verdict`);
131
+ }
132
+ return signal("not_imported", "heuristic prioritization signal: import/require scan found no references; this is not proof of non-exploitability");
133
+ }
134
+ function computeReachabilityHint(finding) {
135
+ const hops = shortestLockfileHops(finding.dependencyPaths);
136
+ if (finding.relationship === "direct") {
137
+ return signal("direct_dependency", "heuristic prioritization hint: lockfile lists this as a direct dependency; not a runtime reachability proof");
138
+ }
139
+ if (finding.relationship === "transitive") {
140
+ // Per-root import data is not attached to a finding. When the usage scan
141
+ // ran and this transitive package itself appears in imports, that is a
142
+ // source-reference heuristic - not a claim that a lockfile root is imported.
143
+ if (finding.usage?.imported) {
144
+ const depth = hops === null ? "unknown depth" : `shortest path ${hops} hop${hops === 1 ? "" : "s"} from the project root`;
145
+ return signal("transitive_imported", `heuristic prioritization hint: transitive lockfile path (${depth}); the vulnerable package appeared in the import/require scan (heuristic, not a runtime reachability proof)`);
146
+ }
147
+ // Prefer path depth over restating relationship=transitive from the findings table.
148
+ if (hops === null) {
149
+ return null;
150
+ }
151
+ return signal(`path_depth_${hops}`, `heuristic prioritization hint: lockfile path depth ${hops} from the project root; not a runtime reachability proof`);
152
+ }
153
+ if (finding.relationship === "unknown") {
154
+ return signal("unknown", "heuristic prioritization hint: dependency relationship could not be classified; not a runtime reachability proof");
155
+ }
156
+ return null;
157
+ }
158
+ function computeExposureSignal(finding) {
159
+ const names = collectPathPackageNames(finding);
160
+ if (names.length === 0)
161
+ return null;
162
+ const markers = matchRequestFacingMarkers(names);
163
+ if (markers.length > 0) {
164
+ return signal("request_facing_path", `heuristic path-name indicator only: dependency-path package name(s) matched request-facing marker(s) (${markers.join(", ")}); not a network exposure or exploitability verdict`);
165
+ }
166
+ return signal("not_indicated", "heuristic path-name indicator only: no request-facing package-name markers found; this does not mean the package is not exposed");
167
+ }
168
+ /**
169
+ * Pure, serialize-time heuristics from fields already on a finding.
170
+ * Does not change vulnerability matching.
171
+ */
172
+ export function computeContextualSignals(finding) {
173
+ return {
174
+ usage: computeUsageSignal(finding),
175
+ reachabilityHint: computeReachabilityHint(finding),
176
+ exposure: computeExposureSignal(finding),
177
+ };
178
+ }
179
+ /** Compact machine values for terminal lines. Omits signals with no data (e.g. usage without `--usage`). */
180
+ export function formatContextualSignalValues(signals) {
181
+ const parts = [];
182
+ if (signals.usage)
183
+ parts.push(`usage=${signals.usage.value}`);
184
+ if (signals.reachabilityHint)
185
+ parts.push(`reachability=${signals.reachabilityHint.value}`);
186
+ if (signals.exposure)
187
+ parts.push(`exposure=${signals.exposure.value}`);
188
+ return parts.join("; ");
189
+ }
190
+ /** Single labeled line for verbose / compact finding output. */
191
+ export function formatContextualSignalsLine(signals) {
192
+ return `Prioritization signals (heuristic): ${formatContextualSignalValues(signals)}`;
193
+ }
@@ -1,3 +1,8 @@
1
+ export function isUnconfirmedFix(finding) {
2
+ return finding.relationship === "direct"
3
+ && finding.validatedFirstFixedVersion === null
4
+ && Boolean(finding.fixVersionValidationNote);
5
+ }
1
6
  export function getPrimaryParent(finding) {
2
7
  const firstPath = finding.dependencyPaths?.[0];
3
8
  if (!firstPath || firstPath.length < 3)
@@ -0,0 +1,32 @@
1
+ import { builtinModules } from "node:module";
2
+ /**
3
+ * Identifies import specifiers that resolve to a Node built-in module rather
4
+ * than to an npm package.
5
+ *
6
+ * Phantom-dependency rules compare imported names against declared
7
+ * dependencies, so a built-in has to be excluded before that comparison: it
8
+ * needs no declaration, and telling someone to install it points them at an
9
+ * unrelated npm shim.
10
+ */
11
+ const NODE_PREFIX = "node:";
12
+ const BUILTIN_NAMES = new Set(builtinModules);
13
+ /**
14
+ * True when the specifier is a Node built-in.
15
+ *
16
+ * Two cases, and both are needed. `builtinModules` lists the bare names
17
+ * (`events`, `string_decoder`), but it deliberately omits the modules that
18
+ * exist only behind the prefix, so `test`, `sea` and `sqlite` are absent from
19
+ * it. Node also rejects any unknown `node:` specifier rather than falling back
20
+ * to the registry, so the prefix alone is proof of intent and nothing on npm
21
+ * can claim it.
22
+ *
23
+ * Subpaths resolve on their first segment, so `node:fs/promises` and
24
+ * `stream/web` are both recognised. A scoped package is unaffected, since
25
+ * `@scope` is never a built-in name.
26
+ */
27
+ export function isNodeBuiltinSpecifier(specifier) {
28
+ if (specifier.startsWith(NODE_PREFIX))
29
+ return true;
30
+ const firstSegment = specifier.split("/")[0];
31
+ return BUILTIN_NAMES.has(firstSegment);
32
+ }