cve-lite-cli 1.37.0 → 1.38.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 (45) hide show
  1. package/README.md +20 -1
  2. package/dist/cli/args.js +120 -103
  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 +17 -2
  24. package/dist/overrides/detectors/index.js +2 -0
  25. package/dist/overrides/detectors/oa008-materialized.js +72 -13
  26. package/dist/overrides/detectors/oa009-stale-floor.js +12 -15
  27. package/dist/overrides/detectors/oa010-vulnerable-floor.js +5 -1
  28. package/dist/overrides/detectors/oa011-exceeds-range.js +128 -0
  29. package/dist/overrides/detectors/pd001-override-only-phantom.js +5 -4
  30. package/dist/overrides/detectors/pd002-transitive-only-phantom.js +5 -4
  31. package/dist/overrides/detectors/phantom-utils.js +29 -0
  32. package/dist/overrides/parsing/registry.js +79 -10
  33. package/dist/scan/multi-folder-scan.js +65 -51
  34. package/dist/scan/override-audit.js +49 -0
  35. package/dist/scan/single-scan.js +108 -33
  36. package/dist/scanner.js +8 -4
  37. package/dist/skills/content.js +4 -2
  38. package/dist/usage/scanner.js +219 -28
  39. package/dist/utils/contextual-signals.js +193 -0
  40. package/dist/utils/finding.js +5 -0
  41. package/dist/utils/package-json.js +66 -14
  42. package/dist/utils/severity.js +22 -0
  43. package/dist/utils/update-check.js +2 -1
  44. package/dist/utils/version.js +33 -19
  45. package/package.json +1 -1
@@ -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)
@@ -26,6 +26,25 @@ export function readDirectDependencyNames(projectPath, prodOnly) {
26
26
  return null;
27
27
  }
28
28
  }
29
+ // Every workspace member declared by the root manifest's `workspaces` field or
30
+ // by pnpm-workspace.yaml, with its parsed package.json. Empty for a
31
+ // single-package project. Best-effort: unreadable members are skipped.
32
+ export function readWorkspaceMemberManifests(projectPath) {
33
+ const rootManifest = readPackageJsonObject(path.join(projectPath, "package.json"));
34
+ if (!rootManifest)
35
+ return [];
36
+ const members = [];
37
+ for (const packageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, readWorkspacePatterns(rootManifest, projectPath))) {
38
+ const manifest = readPackageJsonObject(packageJsonPath);
39
+ if (!manifest)
40
+ continue;
41
+ const dir = path.relative(projectPath, path.dirname(packageJsonPath)).split(path.sep).join("/");
42
+ if (!dir || dir === ".")
43
+ continue;
44
+ members.push({ dir, manifest });
45
+ }
46
+ return members;
47
+ }
29
48
  function readPackageJsonObject(filePath) {
30
49
  try {
31
50
  const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
@@ -89,26 +108,59 @@ function resolveWorkspacePackageJsonPaths(projectPath, patterns) {
89
108
  }
90
109
  return [...matches];
91
110
  }
111
+ /**
112
+ * Directory names directly under `relativePath`, skipping `node_modules` and dot-directories.
113
+ * A workspace member never lives inside `node_modules`, and descending into it during a `**`
114
+ * walk is both wrong and ruinously slow on a real monorepo.
115
+ */
116
+ function childDirectoryNames(projectPath, relativePath) {
117
+ const baseDir = relativePath ? path.join(projectPath, relativePath) : projectPath;
118
+ try {
119
+ return fs
120
+ .readdirSync(baseDir, { withFileTypes: true })
121
+ // isDirectory() is false for a symlink, so a link pointing back up cannot loop the walk.
122
+ .filter(entry => entry.isDirectory())
123
+ .map(entry => entry.name)
124
+ .filter(name => name !== "node_modules" && !name.startsWith("."));
125
+ }
126
+ catch {
127
+ return [];
128
+ }
129
+ }
130
+ /**
131
+ * Compiles one path segment containing `*` into an anchored matcher. `*` matches any run of
132
+ * characters within a single segment, so `pkg-*` and `*-app` both work. Everything else is
133
+ * escaped, so a literal dot in a directory name is not treated as a regex wildcard.
134
+ */
135
+ function segmentMatcher(segment) {
136
+ const escaped = segment.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
137
+ return new RegExp(`^${escaped}$`);
138
+ }
92
139
  function expandWorkspacePattern(projectPath, segments, currentRelativePath) {
93
140
  if (segments.length === 0) {
94
141
  return currentRelativePath ? [currentRelativePath] : [];
95
142
  }
96
143
  const [segment, ...rest] = segments;
97
- if (segment === "*") {
98
- const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
99
- let entries = [];
100
- try {
101
- entries = fs.readdirSync(baseDir, { withFileTypes: true });
102
- }
103
- catch {
104
- return [];
144
+ // `**` matches zero or more directory levels, so it expands both to "the rest of the
145
+ // pattern applied here" and to the same pattern applied one level deeper.
146
+ if (segment === "**") {
147
+ const results = new Set(expandWorkspacePattern(projectPath, rest, currentRelativePath));
148
+ for (const name of childDirectoryNames(projectPath, currentRelativePath)) {
149
+ const next = currentRelativePath ? path.join(currentRelativePath, name) : name;
150
+ for (const found of expandWorkspacePattern(projectPath, segments, next)) {
151
+ results.add(found);
152
+ }
105
153
  }
106
- return entries
107
- .filter(entry => entry.isDirectory())
108
- .flatMap(entry => {
109
- const nextRelativePath = currentRelativePath
110
- ? path.join(currentRelativePath, entry.name)
111
- : entry.name;
154
+ return [...results];
155
+ }
156
+ // Any segment containing `*` is matched against the directory entries. A whole-segment `*`
157
+ // is the degenerate case of this and needs no separate branch.
158
+ if (segment.includes("*")) {
159
+ const matcher = segmentMatcher(segment);
160
+ return childDirectoryNames(projectPath, currentRelativePath)
161
+ .filter(name => matcher.test(name))
162
+ .flatMap(name => {
163
+ const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, name) : name;
112
164
  return expandWorkspacePattern(projectPath, rest, nextRelativePath);
113
165
  });
114
166
  }
@@ -8,6 +8,28 @@ export function reachesFailOn(findings, failOn) {
8
8
  const failLevel = normalizeSeverity(failOn);
9
9
  return findings.some((f) => severityOrder[f.severity] >= severityOrder[failLevel]);
10
10
  }
11
+ // One line that names what tripped the --fail-on gate, so a red CI job says why
12
+ // it is red. The gate ORs three finding classes (CVE, override hygiene,
13
+ // maintenance risk) and none of the rendered output mentioned the gate before,
14
+ // which read as a broken exit code. Returns null when the gate would not fire,
15
+ // so callers derive the exit decision from it (gateLine !== null) and the two
16
+ // cannot disagree. The parenthetical echoes the raw flag value: --fail-on is not
17
+ // validated and normalizeSeverity falls back to critical, so echoing the
18
+ // normalized level would show the user a value they never typed.
19
+ export function failingGateSummary(classes, failOn) {
20
+ if (!failOn)
21
+ return null;
22
+ const failLevel = normalizeSeverity(failOn);
23
+ const parts = [];
24
+ for (const { label, findings } of classes) {
25
+ const count = findings.filter((f) => severityOrder[f.severity] >= severityOrder[failLevel]).length;
26
+ if (count > 0)
27
+ parts.push(`${count} ${label} ${count === 1 ? "finding" : "findings"}`);
28
+ }
29
+ if (parts.length === 0)
30
+ return null;
31
+ return `Failing: ${parts.join(", ")} at or above ${failLevel} (--fail-on ${failOn}).`;
32
+ }
11
33
  export function formatSeverityLabel(severity) {
12
34
  const lower = severity.toLowerCase();
13
35
  if (lower === "critical")