vigievuln 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog — VigieVuln
2
2
 
3
+ ## [1.2.1] — 2026-11-04
4
+
5
+ - Report unreadable Maven manifests and native binaries as incomplete coverage, preserve other inventory entries, and bound binary hashing and PE metadata reads.
6
+ - Keep JSON source locations relative; preserve Excel workbooks with explicitly truncated oversized cells; report output failures clearly while continuing sibling exports.
7
+ - Recognize ignore-rule advisory aliases, warn about global ignores and mismatched baseline projects, reject future-dated snapshots, and compare npm prereleases correctly.
8
+ - Read certificate signature algorithms structurally and distinguish unknown private-key encryption; suppress only Node's known SQLite initialization notice while preserving other warnings.
9
+ - Require explicit, unambiguous product exemptions in VEX; preserve scoped triage in CSAF and SBOM exports.
10
+ - Fail CI when its baseline cannot be read or a requested report cannot be written; distinguish incomplete reassessment from resolved findings and exclude development dependencies from production-only diffs.
11
+ - Apply Go workspace replacements, preserve conditional Python and NuGet versions, and collect Python dependency groups with explicit coverage warnings.
12
+ - Suggest `vigievuln setup` during direct scans and refresh the committed report samples, terminal demo and screenshots.
13
+
3
14
  ## [1.2.0] — Unreleased
4
15
 
5
16
  - Match VigieVuln Maven/npm advisories through the configured official proxy and offline cache, including partial ranges and `VV:CVE-…` identifiers.
package/README.md CHANGED
@@ -17,7 +17,7 @@ It scans dependencies and **9 CMS/frameworks** in one pass without build tools,
17
17
 
18
18
  🌐 **[Project site & docs →](https://9pings.github.io/VigieVuln/)**
19
19
 
20
- *Terminal demo recorded with VigieVuln 1.0.1.*
20
+ *Terminal demo recorded with VigieVuln 1.2.1.*
21
21
 
22
22
  <p align="center"><img src="docs/assets/demo.gif" alt="vigievuln animated terminal demo: an offline Maven audit — dependencies absent from Maven Central flagged as private/internal, the compact single-line vulnerability-database progress, then findings coloured by severity" height="500"></p>
23
23
 
@@ -79,10 +79,10 @@ The proxy receives package coordinates and CVE identifiers, not source code. Cac
79
79
 
80
80
  ### Interactive HTML samples
81
81
 
82
- - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.1.3; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
82
+ - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below, rescanned with VigieVuln 1.2.1; 105 Maven descriptors, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
83
83
  - **[Multi-instance CMS & frameworks — open the report](https://9pings.github.io/VigieVuln/samples/multi-cms-frameworks.html)**: WordPress 6.4.2, Drupal 8.5.0, Symfony Demo (Symfony 7.1.1) and BookStack v24.10 (Laravel 10.48.22), with findings attributed to each instance.
84
84
 
85
- These are standalone reports from real source scans, generated on **2026-10-29** using the hosted proxy and local caches. The CMS sample focuses on PHP dependencies; WordPress advisory coverage is explicitly incomplete without a Wordfence feed. [Sample scope, sources and reproduction commands](docs/samples/README.md).
85
+ These are standalone reports from real source scans, generated on **2026-11-04** with VigieVuln **1.2.1**. Dubbo uses the hosted proxy; the CMS sample uses its local cache offline and focuses on PHP dependencies. Missing Wordfence/Drupal advisory and WordPress checksum inputs are explicitly marked incomplete. [Sample scope, sources and reproduction commands](docs/samples/README.md).
86
86
 
87
87
  > [!WARNING]
88
88
  > vigievuln is new and may still contain ( rare ) bugs. Treat its output as a strong first pass, **double-check anything critical**, and please [report issues](https://github.com/9pings/VigieVuln/issues); they get fixed fast.
@@ -27,6 +27,8 @@ function assertFresh(snapshot, label, maxAgeMs, nowMs = Date.now()) {
27
27
  if (!collectedAt) throw new Error(`${label} snapshot does not declare its collection date; `
28
28
  + `add _fadSnapshot.collectedAt (ISO 8601) or a top-level collectedAt/generatedAt to the snapshot file`);
29
29
  const ageMs = nowMs - collectedAt.getTime();
30
+ // Allow modest clock skew, consistently with the advisory cache validators.
31
+ if (ageMs < -5 * 60 * 1000) throw new Error(`${label} snapshot collection date ${collectedAt.toISOString()} is in the future; check the snapshot timestamp and system clock`);
30
32
  if (ageMs > maxAgeMs) throw new Error(`${label} snapshot collected at ${collectedAt.toISOString()} is stale: `
31
33
  + `age ${Math.round(ageMs / 3600000)}h exceeds --max-advisory-age ${Math.round(maxAgeMs / 3600000)}h`);
32
34
  return { collectedAt: collectedAt.toISOString() };
@@ -69,19 +69,28 @@ function parseOpensshPrivate(body) {
69
69
  const MAGIC = "openssh-key-v1\0";
70
70
  if (buf.subarray(0, MAGIC.length).toString("latin1") !== MAGIC) return null;
71
71
  let off = MAGIC.length;
72
- const readStr = () => { const len = buf.readUInt32BE(off); off += 4; const s = buf.subarray(off, off + len); off += len; return s; };
72
+ const readStr = () => {
73
+ if (off + 4 > buf.length) throw new Error("truncated SSH string");
74
+ const len = buf.readUInt32BE(off); off += 4;
75
+ if (len > buf.length - off) throw new Error("truncated SSH string");
76
+ const s = buf.subarray(off, off + len); off += len; return s;
77
+ };
73
78
  const cipher = readStr().toString("latin1");
74
- readStr(); // kdf name
79
+ const kdf = readStr().toString("latin1");
75
80
  readStr(); // kdf options
76
- off += 4; // numKeys (uint32)
81
+ if (!cipher || !kdf || (cipher === "none") !== (kdf === "none")) return null;
82
+ if (buf.readUInt32BE(off) !== 1) return null;
83
+ off += 4; // supported OpenSSH files contain one key
77
84
  const pub = readStr(); // first public-key blob
78
85
  const tlen = pub.readUInt32BE(0);
86
+ if (!tlen || tlen > pub.length - 4) return null;
79
87
  const keyType = pub.subarray(4, 4 + tlen).toString("latin1");
88
+ if (!readStr().length || off !== buf.length) return null; // private section
80
89
  return { algorithm: sshAlgo(keyType), encrypted: cipher !== "none" };
81
90
  } catch { return null; }
82
91
  }
83
92
 
84
- // ---- weak signature-algorithm detection (OID byte-scan over DER) ---------
93
+ // ---- weak signature-algorithm detection (X.509 AlgorithmIdentifier) -------
85
94
 
86
95
  // Signature-algorithm OIDs we consider weak, as their DER value bytes.
87
96
  const WEAK_SIG_OIDS = [
@@ -94,10 +103,36 @@ const WEAK_SIG_OIDS = [
94
103
 
95
104
  function detectWeakSig(raw) {
96
105
  if (!raw || !raw.length) return null;
97
- for (const oid of WEAK_SIG_OIDS) {
98
- if (raw.indexOf(Buffer.from(oid.bytes)) !== -1) return oid.name;
99
- }
100
- return null;
106
+ // Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signatureValue }.
107
+ // Never search extensions, names, public keys or signature bytes for an OID.
108
+ const tlv = (offset, limit) => {
109
+ if (offset + 2 > limit) throw new Error("truncated DER");
110
+ const tag = raw[offset++];
111
+ let length = raw[offset++];
112
+ if (length & 0x80) {
113
+ const octets = length & 0x7f;
114
+ if (!octets || octets > 4 || offset + octets > limit || raw[offset] === 0) throw new Error("invalid DER length");
115
+ length = 0;
116
+ for (let i = 0; i < octets; i++) length = length * 256 + raw[offset++];
117
+ if (length < 128) throw new Error("noncanonical DER length");
118
+ }
119
+ if (length > limit - offset) throw new Error("truncated DER value");
120
+ return { tag, start: offset, end: offset + length };
121
+ };
122
+ try {
123
+ const cert = tlv(0, raw.length);
124
+ if (cert.tag !== 0x30 || cert.end !== raw.length) return null;
125
+ const tbs = tlv(cert.start, cert.end);
126
+ if (tbs.tag !== 0x30) return null;
127
+ const algorithm = tlv(tbs.end, cert.end);
128
+ if (algorithm.tag !== 0x30) return null;
129
+ const signature = tlv(algorithm.end, cert.end);
130
+ if (signature.tag !== 0x03 || signature.end !== cert.end) return null;
131
+ const oid = tlv(algorithm.start, algorithm.end);
132
+ if (oid.tag !== 0x06) return null;
133
+ const value = raw.subarray(oid.start, oid.end);
134
+ return WEAK_SIG_OIDS.find(item => value.equals(Buffer.from(item.bytes)))?.name || null;
135
+ } catch { return null; }
101
136
  }
102
137
 
103
138
  // EC curves below the ~128-bit security floor (i.e. < 256-bit field).
@@ -166,14 +201,14 @@ function tryX509(buf) {
166
201
  // ---- key items -----------------------------------------------------------
167
202
 
168
203
  function privateKeyItem({ path, file, format, algorithm, encrypted }) {
169
- const enc = encrypted ? " (encrypted)" : " (UNENCRYPTED)";
204
+ const enc = encrypted === true ? " (encrypted)" : encrypted === false ? " (UNENCRYPTED)" : " (encryption unknown)";
170
205
  const issues = [{
171
206
  type: "private-key-committed", severity: "critical",
172
207
  message: `committed ${algorithm || ""} private key${enc} [${format}]`.replace(/\s+/g, " ").trim(),
173
208
  }];
174
209
  return {
175
210
  path, file, kind: "private-key", format, algorithm: algorithm || null,
176
- keyVisibility: "private", encrypted: !!encrypted,
211
+ keyVisibility: "private", encrypted: typeof encrypted === "boolean" ? encrypted : null,
177
212
  issues, severity: "critical",
178
213
  };
179
214
  }
@@ -194,7 +229,7 @@ function publicKeyItem({ path, file, format, algorithm, count }) {
194
229
  function pemPrivateInfo(block) {
195
230
  if (block.label === "OPENSSH PRIVATE KEY") {
196
231
  const r = parseOpensshPrivate(block.body);
197
- return { algorithm: r?.algorithm || null, encrypted: r ? r.encrypted : false, format: "openssh" };
232
+ return { algorithm: r?.algorithm || null, encrypted: r ? r.encrypted : null, format: "openssh" };
198
233
  }
199
234
  const encrypted = /ENCRYPTED/.test(block.label) || /Proc-Type:\s*4,ENCRYPTED/.test(block.body);
200
235
  let algorithm = null;
@@ -240,7 +275,7 @@ function analyzeBuffer({ name, path, buf, now = Date.now(), expiryDays = 90 } =
240
275
  const info = pemPrivateInfo(block);
241
276
  items.push(privateKeyItem({ path, file: name, ...info }));
242
277
  } else if (L === "PGP PRIVATE KEY BLOCK") {
243
- items.push(privateKeyItem({ path, file: name, format: "pgp", algorithm: "PGP", encrypted: true }));
278
+ items.push(privateKeyItem({ path, file: name, format: "pgp", algorithm: "PGP", encrypted: null }));
244
279
  } else if (/PUBLIC KEY$/.test(L)) {
245
280
  items.push(publicKeyItem({ path, file: name, format: "pem", algorithm: pemPublicAlgo(block) }));
246
281
  } else if (L === "PGP PUBLIC KEY BLOCK") {
@@ -253,7 +288,8 @@ function analyzeBuffer({ name, path, buf, now = Date.now(), expiryDays = 90 } =
253
288
  // 2. PuTTY private key (.ppk).
254
289
  if (/^PuTTY-User-Key-File-\d+:\s*(\S+)/m.test(text)) {
255
290
  const algo = /^PuTTY-User-Key-File-\d+:\s*(\S+)/m.exec(text)[1];
256
- const encrypted = !/^Encryption:\s*none/m.test(text);
291
+ const cipher = /^Encryption:\s*(\S+)/m.exec(text)?.[1];
292
+ const encrypted = cipher ? cipher !== "none" : null;
257
293
  items.push(privateKeyItem({ path, file: name, format: "putty", algorithm: sshAlgo(algo) || algo, encrypted }));
258
294
  return items;
259
295
  }
@@ -76,4 +76,30 @@ function extractPeMetadata(buf) {
76
76
  } catch { return null; }
77
77
  }
78
78
 
79
- module.exports = { extractPeMetadata };
79
+ // Adapt the bounded parser to a file descriptor. One 64 KiB cache serves the
80
+ // many small header/string reads; even a distant resource never loads the file.
81
+ function extractPeMetadataFile(fd, size) {
82
+ const fs = require("node:fs");
83
+ let start = -1, cache = Buffer.alloc(0);
84
+ const read = (offset, length) => {
85
+ if (!Number.isSafeInteger(offset) || offset < 0 || length < 0 || length > MAX_VERSION_INFO || offset + length > size) throw Error("bounds");
86
+ if (offset < start || offset + length > start + cache.length) {
87
+ start = offset;
88
+ cache = Buffer.alloc(Math.min(size - offset, Math.max(64 * 1024, length)));
89
+ let count = 0;
90
+ while (count < cache.length) {
91
+ const n = fs.readSync(fd, cache, count, cache.length - count, start + count);
92
+ if (!n) throw Error("unexpected EOF reading PE metadata");
93
+ count += n;
94
+ }
95
+ }
96
+ return cache.subarray(offset - start, offset - start + length);
97
+ };
98
+ return extractPeMetadata({ length: size,
99
+ readUInt16LE: offset => read(offset, 2).readUInt16LE(0),
100
+ readUInt32LE: offset => read(offset, 4).readUInt32LE(0),
101
+ toString: (encoding, begin, end) => read(begin, end - begin).toString(encoding),
102
+ });
103
+ }
104
+
105
+ module.exports = { extractPeMetadata, extractPeMetadataFile };
@@ -23,50 +23,67 @@ const SKIP = new Set([
23
23
 
24
24
  const MAGIC_BYTES = 8; // enough for every signature we sniff
25
25
 
26
- function hashFile(fp, kind) {
27
- const buf = fs.readFileSync(fp);
28
- return {
29
- size: buf.length,
30
- sha1: crypto.createHash("sha1").update(buf).digest("hex"),
31
- sha256: crypto.createHash("sha256").update(buf).digest("hex"),
32
- metadata: kind === "pe" ? require("./pe-metadata").extractPeMetadata(buf) : null,
33
- };
34
- }
26
+ // Bound both memory and work: large files are explicitly unassessed, never
27
+ // silently dropped or loaded into a multi-gigabyte Buffer.
28
+ const MAX_FILE_BYTES = 512 * 1024 * 1024;
29
+ const HASH_CHUNK_BYTES = 1024 * 1024;
35
30
 
36
- function readMagic(fp) {
31
+ function inspectFile(fp, kind, detectOnly) {
37
32
  let fd;
38
33
  try {
39
34
  fd = fs.openSync(fp, "r");
40
- const buf = Buffer.alloc(MAGIC_BYTES);
41
- const n = fs.readSync(fd, buf, 0, MAGIC_BYTES, 0);
42
- return buf.subarray(0, n);
43
- } catch { return Buffer.alloc(0); }
44
- finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* ignore */ } }
35
+ const before = fs.fstatSync(fd);
36
+ if (!before.isFile()) throw Error("not a regular file");
37
+ const magic = Buffer.alloc(MAGIC_BYTES);
38
+ const n = fs.readSync(fd, magic, 0, magic.length, 0);
39
+ if (sniffKind(magic.subarray(0, n)) !== kind) return null;
40
+ if (detectOnly) return {};
41
+ if (before.size > MAX_FILE_BYTES) throw Error(`file size ${before.size} exceeds binary scan limit ${MAX_FILE_BYTES} bytes`);
42
+ const sha1 = crypto.createHash("sha1"), sha256 = crypto.createHash("sha256");
43
+ const chunk = Buffer.alloc(Math.min(HASH_CHUNK_BYTES, before.size));
44
+ let offset = 0;
45
+ while (offset < before.size) {
46
+ const count = fs.readSync(fd, chunk, 0, Math.min(chunk.length, before.size - offset), offset);
47
+ if (!count) throw Error("file changed or unexpected EOF while hashing");
48
+ sha1.update(chunk.subarray(0, count)); sha256.update(chunk.subarray(0, count));
49
+ offset += count;
50
+ }
51
+ const metadata = kind === "pe" ? require("./pe-metadata").extractPeMetadataFile(fd, before.size) : null;
52
+ const after = fs.fstatSync(fd);
53
+ if (after.size !== before.size || after.mtimeMs !== before.mtimeMs || after.ctimeMs !== before.ctimeMs)
54
+ throw Error("file changed during binary scan");
55
+ return { size: offset, sha1: sha1.digest("hex"), sha256: sha256.digest("hex"), metadata };
56
+ } finally { if (fd !== undefined) fs.closeSync(fd); }
45
57
  }
46
58
 
47
59
  /** Walk `dir`, return [{ path, kind, size, sha1, sha256, declaredName }]. */
48
60
  function scanBinaries(dir, opts = {}) {
49
- const { onProgress } = opts;
61
+ const { onProgress, onWarning } = opts;
62
+ const warn = (fp, error) => onWarning?.({ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: fp,
63
+ message: `binary scan incomplete for ${fp}: ${error.message}` });
50
64
  const { makeDirFilter } = require("../../path-filter");
51
65
  const skipDir = makeDirFilter({ srcRoot: opts.srcRoot || dir, defaultSkip: SKIP, excludePath: opts.excludePath, useDefaults: opts.defaultExcludes !== false });
52
66
  const out = [];
53
67
  const stack = [dir];
54
68
  while (stack.length) {
55
69
  const cur = stack.pop();
56
- let entries; try { entries = fs.readdirSync(cur, { withFileTypes: true }); } catch { continue; }
70
+ let entries; try { entries = fs.readdirSync(cur, { withFileTypes: true }); } catch (error) { warn(cur, error); continue; }
57
71
  for (const e of entries) {
58
72
  const fp = path.join(cur, e.name);
59
73
  if (e.isDirectory()) { if (!skipDir(fp, e.name)) stack.push(fp); continue; }
60
74
  if (!e.isFile()) continue;
61
75
  const ext = extKind(e.name);
62
76
  if (!ext) continue; // not an allowlisted extension
63
- if (sniffKind(readMagic(fp)) !== ext) continue; // magic must confirm the extension
64
- if (onProgress) onProgress(fp);
65
- const h = hashFile(fp, ext);
66
- out.push({ path: fp, kind: ext, size: h.size, sha1: h.sha1, sha256: h.sha256, metadata: h.metadata, declaredName: e.name });
77
+ try {
78
+ if (onProgress) onProgress(fp);
79
+ const h = inspectFile(fp, ext, opts.detectOnly);
80
+ if (!h) continue;
81
+ out.push({ path: fp, kind: ext, ...h, declaredName: e.name });
82
+ if (opts.detectOnly) return out;
83
+ } catch (error) { warn(fp, error); }
67
84
  }
68
85
  }
69
86
  return out;
70
87
  }
71
88
 
72
- module.exports = { scanBinaries };
89
+ module.exports = { scanBinaries, MAX_FILE_BYTES };
@@ -20,7 +20,10 @@ module.exports = {
20
20
  manifestNames: ["*.dll", "*.exe", "*.so", "*.dylib"], // lets detectCodecs include us in auto mode
21
21
 
22
22
  detect(dir) {
23
- try { return scanBinaries(dir, { onProgress: null }).length > 0; }
23
+ try {
24
+ let incomplete = false;
25
+ return scanBinaries(dir, { detectOnly: true, onWarning: () => { incomplete = true; } }).length > 0 || incomplete;
26
+ }
24
27
  catch { return false; }
25
28
  },
26
29
 
@@ -28,8 +31,8 @@ module.exports = {
28
31
  const out = new Map();
29
32
  const warnings = [];
30
33
  let records;
31
- try { records = scanBinaries(dir, { onProgress: opts.onBinaryProgress, srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
32
- catch (e) { return { deps: out, warnings: [{ type: "scan-error", message: `binary scan failed: ${e.message}` }] }; }
34
+ try { records = scanBinaries(dir, { onProgress: opts.onBinaryProgress, onWarning: warning => warnings.push(warning), srcRoot: opts.srcRoot || dir, excludePath: opts.excludePath, defaultExcludes: opts.defaultExcludes }); }
35
+ catch (e) { return { deps: out, warnings: [{ type: "dependency-coverage", reason: "binary-scan-error", ecosystem: "binary", manifestPath: dir, message: `binary scan failed: ${e.message}` }] }; }
33
36
  for (const r of records) {
34
37
  const record = makeDepRecord({
35
38
  ecosystem: "binary",
@@ -29,7 +29,7 @@ function parseReplaceLine(s) {
29
29
  * Directory replaces have no scannable version — the dep is dropped and
30
30
  * surfaced in `dropped` so the codec can emit a chapter-0 warning.
31
31
  */
32
- function parseGoMod(text) {
32
+ function parseGoMod(text, { workspaceReplaces = [], replacementsOnly = false } = {}) {
33
33
  const out = { module: null, goVersion: null, deps: [], dropped: [] };
34
34
  const lines = String(text || "").split(/\r?\n/);
35
35
  let inRequire = false;
@@ -69,12 +69,18 @@ function parseGoMod(text) {
69
69
  if (rep) replaces.push(rep);
70
70
  else if (/^replace\b/.test(noComment)) uncertainSyntax = true;
71
71
  }
72
+ if (replacementsOnly) return replaces;
73
+ // Go checks exact versions before wildcard replacements within each file,
74
+ // and checks the workspace file before the module file (even a workspace
75
+ // wildcard overrides a module's exact-version replacement).
76
+ const replacement = (entries, dep) => entries.find(x => x.oldName === dep.name && x.oldVer === dep.version)
77
+ || entries.find(x => x.oldName === dep.name && !x.oldVer);
72
78
  // Apply replaces: versioned old matches that exact version only; versionless
73
79
  // old matches every version of the module.
74
- if (replaces.length) {
80
+ if (replaces.length || workspaceReplaces.length) {
75
81
  const kept = [];
76
82
  for (const dep of out.deps) {
77
- const r = replaces.find(x => x.oldName === dep.name && (!x.oldVer || x.oldVer === dep.version));
83
+ const r = replacement(workspaceReplaces, dep) || replacement(replaces, dep);
78
84
  if (!r) { kept.push(dep); continue; }
79
85
  if (r.newVer) kept.push({ ...dep, name: r.newName, version: r.newVer, replaced: true, managerRelations: ["unknown"] });
80
86
  else out.dropped.push({ name: dep.name, version: dep.version, path: r.newName });
@@ -123,7 +129,7 @@ function parseGoSum(text) {
123
129
  return { deps: [...byMod.entries()].map(([name, version]) => ({ name, version, scope: "transitive", isDev: false })) };
124
130
  }
125
131
 
126
- function parseGoModFile(fp) { return parseGoMod(fs.readFileSync(fp, "utf8")); }
132
+ function parseGoModFile(fp, opts) { return parseGoMod(fs.readFileSync(fp, "utf8"), opts); }
127
133
  function parseGoSumFile(fp) { return parseGoSum(fs.readFileSync(fp, "utf8")); }
128
134
 
129
135
  module.exports = { parseGoMod, parseGoSum, parseGoModFile, parseGoSumFile, stripV };
@@ -55,18 +55,35 @@ module.exports = {
55
55
  for (const g of findGoDirs(dir, dirFilter(dir, opts))) {
56
56
  let modHadDeps = false;
57
57
  const selectedHere = new Set();
58
- // Workspace overrides may change a selected version; do not claim root evidence there.
59
- let workspace = !!process.env.GOWORK && process.env.GOWORK !== "off";
60
- for (let cur = g.dir; ; cur = path.dirname(cur)) {
61
- if (fs.existsSync(path.join(cur, "go.work"))) workspace = true;
62
- if (path.dirname(cur) === cur) break;
58
+ // Honor the explicit workspace switch before looking for the nearest file.
59
+ let workspacePath = null;
60
+ if (process.env.GOWORK !== "off") {
61
+ if (process.env.GOWORK) workspacePath = path.resolve(process.env.GOWORK);
62
+ else for (let cur = g.dir; ; cur = path.dirname(cur)) {
63
+ const fp = path.join(cur, "go.work");
64
+ if (fs.existsSync(fp)) { workspacePath = fp; break; }
65
+ if (path.dirname(cur) === cur) break;
66
+ }
67
+ }
68
+ const workspace = !!workspacePath;
69
+ let workspaceReplaces = [];
70
+ if (workspace) {
71
+ try {
72
+ workspaceReplaces = G.parseGoModFile(workspacePath, { replacementsOnly: true });
73
+ if (!parsedManifests.includes(workspacePath)) parsedManifests.push(workspacePath);
74
+ } catch (error) {
75
+ warnings.push({ type: "parse-error", manifestPath: workspacePath, message: `go.work could not be read: ${error.message}` });
76
+ }
77
+ // Replaces alone cannot establish MVS across all workspace modules.
78
+ warnings.push({ type: "go-coverage", ecosystem: "go", reason: "workspace-graph-not-resolved", manifestPath: workspacePath,
79
+ message: "Go workspace graph was not resolved: recognized go.work replacements are applied, but workspace module selection and transitive versions remain uncertain. Inventory may be incomplete or include unselected versions." });
63
80
  }
64
81
  let goMinor = null;
65
82
  if (g.names.has("go.mod")) {
66
83
  const fp = path.join(g.dir, "go.mod");
67
84
  parsedManifests.push(fp);
68
85
  try {
69
- const r = G.parseGoModFile(fp);
86
+ const r = G.parseGoModFile(fp, { workspaceReplaces });
70
87
  const gm = /^1\.(\d+)/.exec(r.goVersion || "");
71
88
  goMinor = gm ? Number(gm[1]) : null;
72
89
  for (const d of r.dropped) {
@@ -129,14 +129,18 @@ module.exports = {
129
129
  const pomFiles = await core.findPomFilesAsync(dir, skipDir);
130
130
  const store = core.newMetadataStore();
131
131
  const propsByPom = {};
132
+ const warnings = [];
132
133
  for (const pom of pomFiles) {
133
- try { await core.parsePom(pom, store); } catch { /* logged by orchestrator */ }
134
+ try { await core.parsePom(pom, store); }
135
+ catch (error) { warnings.push({ type: "dependency-coverage", reason: "pom-parse-error", ecosystem: "maven", manifestPath: pom,
136
+ message: `pom.xml parse failed (${pom}): ${error.message}; dependency inventory is incomplete.` }); }
134
137
  }
135
138
  for (const pom of Object.keys(store.byPath)) {
136
- try { await core.getAllInheritedProps(pom, store, propsByPom); } catch { /* logged */ }
139
+ try { await core.getAllInheritedProps(pom, store, propsByPom); }
140
+ catch (error) { warnings.push({ type: "dependency-coverage", reason: "pom-inheritance-error", ecosystem: "maven", manifestPath: pom,
141
+ message: `pom.xml inheritance failed (${pom}): ${error.message}; dependency inventory is incomplete.` }); }
137
142
  }
138
143
  const deps = collectResolvedDeps(store, propsByPom, { ignoreTest: opts.ignoreTest, deps2Exclude: opts.deps2Exclude });
139
- const warnings = [];
140
144
  // Embedded binaries: discover Maven coordinates inside committed .jar/.war/.ear
141
145
  // archives (vendored libs, fat-jars). Keyed by physical location so they don't
142
146
  // merge with declared deps (they get their own report chapter). Default on;
@@ -149,7 +153,8 @@ module.exports = {
149
153
  warnings.push(...jarWarnings);
150
154
  } catch (e) { warnings.push({ type: "embedded-jar", message: `embedded-jar scan failed: ${e.message}` }); }
151
155
  }
152
- return { deps, warnings, parsedManifests: pomFiles.slice(), _maven: { store, propsByPom, pomFiles } };
156
+ const parsedPoms = pomFiles.filter(pom => Object.hasOwn(store.byPath, pom));
157
+ return { deps, warnings, parsedManifests: parsedPoms, _maven: { store, propsByPom, pomFiles: parsedPoms } };
153
158
  },
154
159
 
155
160
  coordKey(d) { return coordKeyFor("maven", d.namespace || d.groupId, d.name || d.artifactId); },
@@ -29,17 +29,12 @@ const SCOPE_RANK = { prod: 4, peer: 3, optional: 2, dev: 1, transitive: 0 };
29
29
  function rankScope(s) { return SCOPE_RANK[s] || 0; }
30
30
 
31
31
  function semverCompare(a, b) {
32
- // Lightweight semver compare — good enough for "keep highest"; not
33
- // canonical (doesn't fully implement build metadata ordering). For CVE
34
- // matching we'll defer to ecosystem-aware comparators when needed.
35
- const norm = v => String(v || "").replace(/^[v=]+/, "").split(/[-+]/)[0].split(".").map(n => parseInt(n, 10) || 0);
36
- const ax = norm(a), bx = norm(b);
37
- const n = Math.max(ax.length, bx.length);
38
- for (let i = 0; i < n; i++) {
39
- const d = (ax[i] || 0) - (bx[i] || 0);
40
- if (d !== 0) return d > 0 ? 1 : -1;
41
- }
42
- return 0;
32
+ // Use the same SemVer precedence as advisory matching: prereleases are below
33
+ // their release, numeric identifiers compare numerically, builds do not rank.
34
+ // Non-semver inputs are incomparable, never guessed as a newer release.
35
+ const left = String(a ?? ""), right = String(b ?? "");
36
+ if (left.length > 256 || right.length > 256) return null;
37
+ return require("../../osv-db").compareSemver(left, right);
43
38
  }
44
39
 
45
40
  function isResolvedVersion(v) {
@@ -74,13 +74,21 @@ async function parseDirectoryPackagesProps(filePath) {
74
74
  for (const ig of xml.Project?.ItemGroup || []) {
75
75
  for (const pv of ig.PackageVersion || []) {
76
76
  const id = pv.$?.Include; const v = pv.$?.Version;
77
- if (id && v) map[id.toLowerCase()] = v;
77
+ if (id && v) {
78
+ const key = id.toLowerCase(), previous = map[key];
79
+ // Conditions cannot be selected without evaluating MSBuild. Keep all
80
+ // alternatives (including a single conditional pin) and label them.
81
+ map[key] = previous !== undefined || pv.$?.Condition || ig.$?.Condition
82
+ ? [...new Set([...(previous === undefined ? [] : Array.isArray(previous) ? previous : [previous]), v])]
83
+ : v;
84
+ }
78
85
  }
79
86
  }
80
87
  return map;
81
88
  }
82
89
 
83
90
  async function parseCsproj(filePath, cpm = {}) {
91
+ const warnings = [];
84
92
  const xml = await xml2js.parseStringPromise(fs.readFileSync(filePath, "utf8"));
85
93
  const deps = [];
86
94
  let skipped = 0;
@@ -94,12 +102,15 @@ async function parseCsproj(filePath, cpm = {}) {
94
102
  || pr.$?.Version
95
103
  || (Array.isArray(pr.Version) ? pr.Version[0] : null)
96
104
  || cpm[name.toLowerCase()] || null;
97
- const version = concreteVersion(raw);
98
- if (version) deps.push({ name, version, scope: "prod", isDev: false });
99
- else skipped++;
105
+ if (Array.isArray(raw)) warnings.push({ type: "dependency-coverage", reason: "conditional-versions", message: `${name}: all central package version alternatives are scanned; MSBuild conditions were not evaluated.` });
106
+ for (const candidate of Array.isArray(raw) ? raw : [raw]) {
107
+ const version = concreteVersion(candidate);
108
+ if (version) deps.push({ name, version, scope: "prod", isDev: false });
109
+ else skipped++;
110
+ }
100
111
  }
101
112
  }
102
- return { manifestPath: filePath, manifestType: "csproj", deps, skipped };
113
+ return { manifestPath: filePath, manifestType: "csproj", deps, skipped, warnings };
103
114
  }
104
115
 
105
116
  async function parsePackagesConfig(filePath) {
@@ -100,7 +100,8 @@ module.exports = {
100
100
  const fp = path.join(g.dir, cs);
101
101
  parsedManifests.push(fp);
102
102
  try {
103
- const { deps, skipped: sk } = await N.parseCsproj(fp, cpm);
103
+ const { deps, skipped: sk, warnings: notices } = await N.parseCsproj(fp, cpm);
104
+ for (const warning of notices || []) warnings.push({ ...warning, manifestPath: fp });
104
105
  for (const d of deps) { add(d, fp); pinned++; }
105
106
  skipped += sk;
106
107
  } catch { /* ignore unparsable csproj */ }
@@ -78,12 +78,17 @@ function parsePyprojectToml(filePath) {
78
78
  const data = TOML.parse(fs.readFileSync(filePath, "utf8"));
79
79
  const deps = [];
80
80
  let skipped = 0;
81
+ const warnings = [];
81
82
  const seen = new Set();
82
83
  const push = (rawName, version, scope) => {
83
84
  const name = pep503(rawName);
84
85
  if (!name || name === "python") return;
85
86
  const k = `${name}@${version}`;
86
- if (seen.has(k)) return; seen.add(k);
87
+ if (seen.has(k)) {
88
+ if (scope !== "dev") { const prev = deps.find(d => d.name === name && d.version === version); prev.scope = scope; prev.isDev = false; }
89
+ return;
90
+ }
91
+ seen.add(k);
87
92
  deps.push({ name, version, scope, isDev: scope === "dev" });
88
93
  };
89
94
  // PEP 508 specs ("requests==2.31.0") — exact "==" pins only.
@@ -110,6 +115,32 @@ function parsePyprojectToml(filePath) {
110
115
  const isDev = /^(dev|test|tests|lint|docs|typing|type|check)$/i.test(group);
111
116
  for (const req of (Array.isArray(arr) ? arr : [])) addSpec(req, isDev ? "dev" : "prod");
112
117
  }
118
+ // PEP 735 groups may be the entire inventory of a scripts-only project.
119
+ // Resolve includes by normalized name; preserve all variants without selecting
120
+ // a local execution environment. Arbitrary group names are not proof of dev scope.
121
+ const groups = new Map();
122
+ for (const [name, entries] of Object.entries(data["dependency-groups"] || {})) {
123
+ const key = pep503(name);
124
+ if (groups.has(key)) warnings.push({ type: "parse-error", message: `duplicate dependency group: ${name}` });
125
+ groups.set(key, [...(groups.get(key) || []), ...(Array.isArray(entries) ? entries : [])]);
126
+ if (!Array.isArray(entries)) warnings.push({ type: "parse-error", message: `invalid dependency group: ${name}` });
127
+ }
128
+ const expanded = new Set();
129
+ const visit = (name, scope, trail = new Set()) => {
130
+ if (trail.has(name) || !groups.has(name)) {
131
+ warnings.push({ type: "parse-error", message: `cyclic or missing dependency group: ${name}` }); return;
132
+ }
133
+ const key = `${name}:${scope}`;
134
+ if (expanded.has(key)) return;
135
+ expanded.add(key);
136
+ const next = new Set([...trail, name]);
137
+ for (const entry of groups.get(name)) {
138
+ if (typeof entry === "string") addSpec(entry, scope);
139
+ else if (entry && Object.keys(entry).length === 1 && typeof entry["include-group"] === "string") visit(pep503(entry["include-group"]), scope, next);
140
+ else warnings.push({ type: "parse-error", message: `unsupported entry in dependency group: ${name}` });
141
+ }
142
+ };
143
+ for (const name of groups.keys()) visit(name, /^(dev|test|tests|lint|docs|typing|type|check)$/.test(name) ? "dev" : "prod");
113
144
  // Poetry [tool.poetry]
114
145
  const poetry = (data.tool && data.tool.poetry) || {};
115
146
  for (const [name, v] of Object.entries(poetry.dependencies || {})) addPoetry(name, v, "prod");
@@ -117,7 +148,7 @@ function parsePyprojectToml(filePath) {
117
148
  for (const grp of Object.values(poetry.group || {})) {
118
149
  for (const [name, v] of Object.entries((grp && grp.dependencies) || {})) addPoetry(name, v, "dev");
119
150
  }
120
- return { manifestPath: filePath, manifestType: "pyproject.toml", deps, skipped };
151
+ return { manifestPath: filePath, manifestType: "pyproject.toml", deps, skipped, warnings };
121
152
  }
122
153
 
123
154
  // Walk a requirements.txt graph, following -r/--requirement (deps) and
@@ -132,8 +163,9 @@ function collectReqGraph(filePath, seen, kind, acc, root) {
132
163
  if (relative === '..' || relative.startsWith('..' + path.sep) || path.isAbsolute(relative)) {
133
164
  acc.missing.push(`${real} (outside scan root; ignored)`); return;
134
165
  }
135
- if (seen.has(resolved)) return; // cycle / re-include guard
136
- seen.add(resolved);
166
+ const visitKey = `${kind}:${resolved}`;
167
+ if (seen.has(visitKey)) return; // same file may be both constraint and requirement
168
+ seen.add(visitKey);
137
169
  if (seen.size > 200) return; // sanity bound
138
170
  let lines;
139
171
  try { lines = fs.readFileSync(resolved, "utf8").split(/\r?\n/); }
@@ -156,29 +188,38 @@ function collectReqGraph(filePath, seen, kind, acc, root) {
156
188
  const { name, spec } = splitPep508(line.split(/\s+--/)[0].trim());
157
189
  if (!name) continue;
158
190
  const n = pep503(name);
159
- if (kind === "constraint") acc.constraints.set(n, spec);
191
+ if (kind === "constraint") {
192
+ if (!acc.constraints.has(n)) acc.constraints.set(n, []);
193
+ acc.constraints.get(n).push(spec);
194
+ if (line.includes(";")) acc.conditional.add(n);
195
+ }
160
196
  else acc.reqs.push({ name: n, spec });
161
197
  }
162
198
  }
163
199
 
164
200
  function parseRequirementsTxt(filePath, scanRoot = path.dirname(filePath)) {
165
- const acc = { reqs: [], constraints: new Map(), missing: [] };
201
+ const acc = { reqs: [], constraints: new Map(), missing: [], conditional: new Set() };
166
202
  collectReqGraph(filePath, new Set(), "req", acc, fs.realpathSync(scanRoot));
167
203
  const deps = [];
168
204
  let skipped = 0;
169
205
  const seen = new Set();
206
+ const warnings = [];
207
+ const warned = new Set();
170
208
  for (const r of acc.reqs) {
171
- let version = null;
172
- if (isPinned(r.spec)) version = stripOp(r.spec);
173
- else if (acc.constraints.has(r.name) && isPinned(acc.constraints.get(r.name))) {
174
- version = stripOp(acc.constraints.get(r.name)); // range pinned by -c constraint
209
+ const constraints = acc.constraints.get(r.name) || [];
210
+ const versions = isPinned(r.spec) ? [stripOp(r.spec)] : constraints.filter(isPinned).map(stripOp);
211
+ if (!versions.length) { skipped++; continue; }
212
+ if (!isPinned(r.spec) && (acc.conditional.has(r.name) || constraints.length > 1) && !warned.has(r.name)) {
213
+ warned.add(r.name);
214
+ warnings.push({ type: "dependency-coverage", reason: "conditional-versions", message: `${r.name}: all pinned constraint alternatives are scanned; environment markers and constraint intersection were not resolved.` });
215
+ }
216
+ for (const version of new Set(versions)) {
217
+ const k = `${r.name}@${version}`;
218
+ if (seen.has(k)) continue; seen.add(k);
219
+ deps.push({ name: r.name, version, scope: "prod", isDev: false });
175
220
  }
176
- if (!version) { skipped++; continue; }
177
- const k = `${r.name}@${version}`;
178
- if (seen.has(k)) continue; seen.add(k);
179
- deps.push({ name: r.name, version, scope: "prod", isDev: false });
180
221
  }
181
- return { manifestPath: filePath, manifestType: "requirements.txt", deps, skipped, missing: acc.missing };
222
+ return { manifestPath: filePath, manifestType: "requirements.txt", deps, skipped, missing: acc.missing, warnings };
182
223
  }
183
224
 
184
225
  module.exports = { pep503, isConcrete, splitPep508, parsePoetryLock, parseUvLock, parsePdmLock, parsePipfileLock, parsePyprojectToml, parseRequirementsTxt };
@@ -97,6 +97,7 @@ module.exports = {
97
97
  const r = P.parsePyprojectToml(fp);
98
98
  for (const d of r.deps) add(d, fp);
99
99
  skipped += r.skipped;
100
+ for (const warning of r.warnings || []) warnings.push({ ...warning, manifestPath: fp });
100
101
  if (r.deps.length || r.skipped) sources.push("pyproject.toml");
101
102
  } catch (e) { warnings.push({ type: "parse-error", manifestPath: fp, message: `pyproject.toml parse failed: ${e.message}` }); }
102
103
  }
@@ -108,6 +109,7 @@ module.exports = {
108
109
  const r = P.parseRequirementsTxt(fp, dir);
109
110
  for (const d of r.deps) add(devFile ? { ...d, isDev: true, scope: "dev" } : d, fp);
110
111
  skipped += r.skipped;
112
+ for (const warning of r.warnings || []) warnings.push({ ...warning, manifestPath: fp });
111
113
  sources.push(rf);
112
114
  for (const miss of (r.missing || [])) warnings.push({ type: "missing-include", manifestPath: fp, message: `referenced requirements file not found: ${miss}` });
113
115
  } catch (e) { warnings.push({ type: "parse-error", manifestPath: fp, message: `${rf} parse failed: ${e.message}` }); }
@@ -138,13 +138,41 @@ function buildCsaf(resolvedDeps, cveMatches, opts = {}) {
138
138
  if (!(v.ids || []).some(item => item.system_name === system_name && item.text === m.advisoryId))
139
139
  v.ids = [...(v.ids || []), { system_name, text: m.advisoryId }];
140
140
  }
141
- for (const pid of pids) if (pid && !v.product_status.known_affected.includes(pid)) {
142
- v.product_status.known_affected.push(pid);
143
- if (v.scores?.[0]) v.scores[0].products.push(pid);
144
- if (v.flags?.[0]) v.flags[0].product_ids.push(pid);
141
+ // Accepted risk remains affected. Only an explicit scoped VEX assertion
142
+ // may mark a product fixed/not affected.
143
+ const status = m.suppressed && ["fixed", "known_not_affected"].includes(m.suppressionStatus)
144
+ ? m.suppressionStatus : "known_affected";
145
+ if (m.suppressed) {
146
+ v.notes ||= [];
147
+ v.notes.push({ category: "other", title: "VigieVuln triage", text: JSON.stringify({
148
+ product_ids: pids, suppressed: true, reason: m.suppressedReason || "ignored", status,
149
+ }) });
150
+ }
151
+ v.product_status[status] ||= [];
152
+ for (const pid of pids) if (pid && !v.product_status[status].includes(pid)) {
153
+ v.product_status[status].push(pid);
154
+ if (v.scores?.[0] && !v.scores[0].products.includes(pid)) v.scores[0].products.push(pid);
155
+ if (v.flags?.[0] && !v.flags[0].product_ids.includes(pid)) v.flags[0].product_ids.push(pid);
145
156
  }
146
157
  }
147
158
 
159
+ for (const v of byCve.values()) {
160
+ const statuses = v.product_status;
161
+ const affected = new Set(statuses.known_affected || []);
162
+ // Contradictory assertions cannot clear a product; affected wins regardless
163
+ // of input order. Different clearance statuses are also contradictory.
164
+ for (const pid of statuses.fixed || [])
165
+ if ((statuses.known_not_affected || []).includes(pid)) affected.add(pid);
166
+ statuses.known_affected = [...affected];
167
+ for (const status of ["fixed", "known_not_affected"])
168
+ if (statuses[status]) statuses[status] = statuses[status].filter(pid => !affected.has(pid));
169
+ for (const status of Object.keys(statuses)) if (!statuses[status].length) delete statuses[status];
170
+ if (v.flags) {
171
+ v.flags = v.flags.map(flag => ({ ...flag, product_ids: flag.product_ids.filter(pid => affected.has(pid)) }))
172
+ .filter(flag => flag.product_ids.length);
173
+ if (!v.flags.length) delete v.flags;
174
+ }
175
+ }
148
176
  return {
149
177
  document: {
150
178
  category: "csaf_vex",
@@ -168,7 +196,7 @@ function buildCsaf(resolvedDeps, cveMatches, opts = {}) {
168
196
  product_tree: { full_product_names },
169
197
  // Drop any vulnerability that ended up with zero affected products (e.g. a
170
198
  // match with no usable dep) — an empty product_status is schema-invalid.
171
- vulnerabilities: [...byCve.values()].filter(v => v.product_status.known_affected.length > 0),
199
+ vulnerabilities: [...byCve.values()].filter(v => Object.keys(v.product_status).length > 0),
172
200
  };
173
201
  }
174
202
 
package/lib/diff.js CHANGED
Binary file
package/lib/i18n.js CHANGED
@@ -46,6 +46,7 @@ function normaliseLocale(raw) {
46
46
  // tool and flag names) are deliberately absent: they are names, not prose, and fall
47
47
  // through to English.
48
48
  const fr = {
49
+ "For faster scans with the VigieVuln DB or a seed → vigievuln setup": "Pour des scans plus rapides avec la DB VigieVuln ou un seed → vigievuln setup",
49
50
  // ---- Report header ----
50
51
  "VigieVuln Report": "Rapport VigieVuln",
51
52
  "Multi-ecosystem dependency security audit": "Audit de sécurité des dépendances, multi-écosystème",
@@ -10,10 +10,57 @@
10
10
  * @email: pp9ping@gmail.com
11
11
  */
12
12
  const fs = require("fs");
13
+ const path = require("node:path");
13
14
  const { purlFor } = require("./purl");
14
15
  const { summarizeFindings, uniqueFindings } = require("./finding-summary");
15
16
  const { europeanReferences, euvdExploited } = require("./eu-refs");
16
17
 
18
+ // Reports are shareable artifacts. Keep locations relative to the project,
19
+ // without rewriting advisory evidence, URLs, stable IDs or the input payload.
20
+ function portableLocations(doc, source) {
21
+ if (typeof source !== "string" || source.startsWith("(")) return doc;
22
+ const paths = path.win32.isAbsolute(source) && !path.posix.isAbsolute(source) ? path.win32 : path.posix;
23
+ if (!paths.isAbsolute(source)) return doc;
24
+ const normalized = paths.normalize(source);
25
+ const volumeRoot = paths.parse(normalized).root;
26
+ const root = normalized === volumeRoot ? volumeRoot : normalized.replace(/[\\/]+$/, "");
27
+ const locationKeys = new Set(["src", "path", "file", "root", "manifestPath", "manifestPaths", "pomPath", "pomPaths",
28
+ "archive", "dir", "location", "ignoreFile", "vexFile"]);
29
+ const relative = value => {
30
+ if (!paths.isAbsolute(value)) return value;
31
+ const rel = paths.relative(root, value);
32
+ return rel === ".." || rel.startsWith(`..${paths.sep}`) || paths.isAbsolute(rel)
33
+ ? `[external]/${paths.basename(value)}` : (rel || ".").split(paths.sep).join("/");
34
+ };
35
+ const walk = (value, key, warning = false) => {
36
+ if (typeof value === "string") {
37
+ if (locationKeys.has(key)) return relative(value);
38
+ if (warning && key === "message") {
39
+ const escape = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
40
+ const prefix = root.endsWith(paths.sep) ? root : root + paths.sep;
41
+ return value.split(/((?:https?:)?\/\/[^\s"'<>]+)/gi).map((part, index) => {
42
+ if (index % 2) return part; // keep whole URLs, including query paths
43
+ for (const p of new Set([prefix, prefix.replace(/\\/g, "/")])) {
44
+ // A filesystem path starts at a text boundary, never inside a URL.
45
+ // In particular source=/ must not strip slashes from https://...
46
+ // or from a protocol-relative //host/path reference.
47
+ part = part.replace(new RegExp(`(^|[\\s'"(=])${escape(p)}${p === "/" ? "(?!/)" : ""}(?=[^\\s'"),:;])`, "g"), "$1");
48
+ }
49
+ return part.replace(new RegExp(`(^|[\\s'"(=])${escape(root)}(?=$|[\\s'"),:;])`, "g"), "$1.");
50
+ }).join("");
51
+ }
52
+ return value;
53
+ }
54
+ if (Array.isArray(value)) return value.map(v => walk(v, key, warning));
55
+ if (value && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) return Object.fromEntries(Object.entries(value)
56
+ .map(([k, v]) => [k, walk(v, k, warning || k === "warnings")]));
57
+ return value;
58
+ };
59
+ const out = walk(doc);
60
+ out.project.src = paths.basename(root) || ".";
61
+ return out;
62
+ }
63
+
17
64
  function coordOf(dep) {
18
65
  const ns = dep.namespace || dep.groupId || "";
19
66
  const name = dep.name || dep.artifactId;
@@ -83,6 +130,7 @@ function cveFinding(m) {
83
130
  cpeFiltered: !!m.cpeFiltered,
84
131
  suppressed: !!m.suppressed,
85
132
  suppressedReason: m.suppressedReason || null,
133
+ suppressionStatus: m.suppressionStatus || null,
86
134
  dep: depBrief(m.dep),
87
135
  };
88
136
  }
@@ -115,7 +163,7 @@ function buildFindings(payload = {}) {
115
163
  const coverageWarningTypes = new Set(["source-unavailable", "source-stale", "dependency-coverage", "osv-coverage", "go-coverage", "unresolved-versions", "no-lockfile", "parse-error", "missing-include", "local-replace", "private-libs"]);
116
164
  const coverageWarnings = warnings.filter(w => coverageWarningTypes.has(w.type)).length;
117
165
 
118
- return {
166
+ return portableLocations({
119
167
  schema: "fad-findings/1",
120
168
  tool: { name: "VigieVuln", version: String(toolVersion) },
121
169
  generatedAt: projectInfo.generatedAt || null,
@@ -193,7 +241,7 @@ function buildFindings(payload = {}) {
193
241
  // Differential audit vs a --baseline document (summary + per-category deltas).
194
242
  // Null when no baseline was provided.
195
243
  diff: diff || null,
196
- };
244
+ }, projectInfo.src);
197
245
  }
198
246
 
199
247
  function writeFindings(payload, outputPath) {
@@ -146,6 +146,12 @@ function buildCycloneDx(resolvedDeps, cveMatches, opts = {}) {
146
146
  for (const source of String(m.source || 'cache').split('+').filter(Boolean))
147
147
  if (!v.properties.some(p => p.name === 'vigievuln:source' && p.value === source)) v.properties.push({ name: 'vigievuln:source', value: source });
148
148
  for (const ref of refs) if (ref && !v.affects.some(a => a.ref === ref)) v.affects.push({ ref });
149
+ // Triage is per affected component, not per CVE. A global analysis.state
150
+ // would incorrectly clear other products sharing the same advisory.
151
+ if (m.suppressed) v.properties.push({ name: "vigievuln:triage", value: JSON.stringify({
152
+ refs: refs.filter(Boolean), suppressed: true, reason: m.suppressedReason || "ignored",
153
+ ...(m.suppressionStatus ? { status: m.suppressionStatus } : {}),
154
+ }) });
149
155
  if (m.cpeFiltered) v.properties.push({ name: "fad:cpe-filtered", value: "true" });
150
156
  // One property per physical occurrence: consumers must be able to relate the SBOM
151
157
  // entry to the report's finding identity and its application relation.
@@ -3,11 +3,25 @@
3
3
  const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
 
6
+ function nodeDatabase() {
7
+ // Node emits this one-time notice synchronously while loading node:sqlite.
8
+ // Keep runtime, deprecation and application warnings intact; restore the
9
+ // original function before any database is opened or user code is called.
10
+ const emitWarning = process.emitWarning;
11
+ try {
12
+ process.emitWarning = function (warning, type, ...args) {
13
+ if (type === 'ExperimentalWarning' && warning === 'SQLite is an experimental feature and might change at any time') return;
14
+ return Reflect.apply(emitWarning, this, [warning, type, ...args]);
15
+ };
16
+ return require('node:sqlite').DatabaseSync;
17
+ } finally { process.emitWarning = emitWarning; }
18
+ }
19
+
6
20
  function openSqlite(file, {readonly = false} = {}) {
7
21
  if (file !== ':memory:') fs.mkdirSync(path.dirname(file), {recursive:true, mode:0o700});
8
22
  const db = typeof Bun !== 'undefined'
9
23
  ? new (require('bun:sqlite').Database)(file, {readonly, create:!readonly})
10
- : new (require('node:sqlite').DatabaseSync)(file, {readOnly:readonly});
24
+ : new (nodeDatabase())(file, {readOnly:readonly});
11
25
  db.exec('PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
12
26
  if (!readonly) db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;');
13
27
  const statements=new Map();
package/lib/suppress.js CHANGED
@@ -54,10 +54,10 @@ function parseVex(csaf) {
54
54
  const rules = [];
55
55
  if (!csaf || typeof csaf !== "object") return rules;
56
56
  // product_id → purl, to map suppressed products back to coordinates.
57
- const purlByPid = {};
57
+ const purlByPid = new Map();
58
58
  for (const p of csaf.product_tree?.full_product_names || []) {
59
59
  const purl = p.product_identification_helper?.purl;
60
- if (p.product_id && purl) purlByPid[p.product_id] = purl;
60
+ if (p.product_id && typeof purl === "string") purlByPid.set(p.product_id, purl);
61
61
  }
62
62
  for (const v of csaf.vulnerabilities || []) {
63
63
  const cve = v.cve;
@@ -66,35 +66,56 @@ function parseVex(csaf) {
66
66
  ...(v.product_status?.known_not_affected || []),
67
67
  ...(v.product_status?.fixed || []),
68
68
  ];
69
- if (!cleared.length) {
70
- // No product scope → suppress the CVE globally.
71
- rules.push({ cve, coord: null, coordRe: null, reason: "VEX: not affected / fixed" });
72
- continue;
73
- }
69
+ // No clearance means no exemption, including known_affected and
70
+ // under_investigation. Empty lists must never become global rules.
71
+ if (!cleared.length) continue;
74
72
  for (const pid of cleared) {
75
- const purl = purlByPid[pid];
73
+ if ((v.product_status?.known_affected || []).includes(pid) ||
74
+ (v.product_status?.under_investigation || []).includes(pid)) continue;
75
+ const purl = purlByPid.get(pid);
76
76
  // A product we can't map back to a coord must NOT become a coordRe:null
77
77
  // rule — that would suppress this CVE for EVERY dependency (a security
78
78
  // false-negative). Skip it: a product-scoped clearance only ever narrows.
79
79
  if (!purl) continue;
80
- rules.push({ cve, coord: purl, coordRe: globToRe(purl), reason: "VEX: not affected / fixed" });
80
+ const status = (v.product_status?.fixed || []).includes(pid) ? "fixed" : "known_not_affected";
81
+ // PURLs do not distinguish physical occurrences. A clearance for one
82
+ // product cannot clear an affected/unknown sibling with that same PURL.
83
+ const siblings = [...purlByPid].filter(([, value]) => value === purl).map(([id]) => id);
84
+ if (siblings.some(id => !(v.product_status?.[status] || []).includes(id))) continue;
85
+ if ((csaf.vulnerabilities || []).some(other => other.cve === cve &&
86
+ [...(other.product_status?.known_affected || []), ...(other.product_status?.under_investigation || [])]
87
+ .some(id => purlByPid.get(id) === purl))) continue;
88
+ // Imported identities are exact PURLs, never user-authored ignore globs.
89
+ rules.push({ cve, coord: purl, purl, reason: `VEX: ${status}`, status });
81
90
  }
82
91
  }
83
92
  return rules;
84
93
  }
85
94
 
95
+ /** Explicit ignore rules can use any identifier of the merged finding.
96
+ * VEX remains primary-id exact: alias expansion would also need conflict analysis
97
+ * across all VEX entries, not merely an alias lookup on a clearance. */
86
98
  function ruleMatches(rule, m) {
87
- if (rule.cve && rule.cve !== "*" && rule.cve !== m.cve?.id) return false;
99
+ const ids = rule.purl ? [m.cve?.id] : [m.cve?.id, m.cve?.ghsa,
100
+ ...(Array.isArray(m.cve?.aliases) ? m.cve.aliases : [])].filter(id => typeof id === "string");
101
+ if (rule.cve && rule.cve !== "*" && !ids.includes(rule.cve)) return false;
102
+ if (rule.purl) return rule.purl === purlFor(m.dep);
88
103
  if (!rule.coordRe) return true;
89
104
  const coord = coordOf(m.dep);
90
105
  const purl = purlFor(m.dep) || "";
91
106
  return rule.coordRe.test(coord) || rule.coordRe.test(purl) || rule.coordRe.test(m.dep.name || "");
92
107
  }
93
108
 
109
+ /** Signal an explicit global wildcard without rejecting the user's triage policy. */
110
+ function hasGlobalIgnoreRule(rules) {
111
+ return (rules || []).some(rule => rule.cve === "*" && !rule.purl &&
112
+ (!rule.coord || /^\*+$/.test(rule.coord)));
113
+ }
114
+
94
115
  /** Build a matcher from a flat rule list. */
95
116
  function buildSuppressor(rules) {
96
117
  return (m) => {
97
- for (const r of rules || []) if (ruleMatches(r, m)) return { suppressed: true, reason: r.reason };
118
+ for (const r of rules || []) if (ruleMatches(r, m)) return { suppressed: true, reason: r.reason, ...(r.status ? { status: r.status } : {}) };
98
119
  return null;
99
120
  };
100
121
  }
@@ -105,9 +126,9 @@ function applySuppressions(matches, rules) {
105
126
  let n = 0;
106
127
  for (const m of matches || []) {
107
128
  const hit = suppressor(m);
108
- if (hit) { m.suppressed = true; m.suppressedReason = hit.reason; n++; }
129
+ if (hit) { m.suppressed = true; m.suppressedReason = hit.reason; if (hit.status) m.suppressionStatus = hit.status; n++; }
109
130
  }
110
131
  return n;
111
132
  }
112
133
 
113
- module.exports = { parseIgnoreFile, parseVex, buildSuppressor, applySuppressions, globToRe };
134
+ module.exports = { parseIgnoreFile, parseVex, buildSuppressor, applySuppressions, globToRe, hasGlobalIgnoreRule };
@@ -10,6 +10,7 @@ const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships
10
10
  const PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
11
11
  const MAX_ROWS = 1048576;
12
12
  const MAX_CELL = 32767;
13
+ const TRUNCATION_MARKER = "\n… [TRUNCATED: Excel cell limit; export JSON for the full value]";
13
14
 
14
15
  function xml(value) {
15
16
  return String(value ?? "").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "")
@@ -30,8 +31,13 @@ function valueCell(value, address, header = false) {
30
31
  if (typeof value === "boolean") return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
31
32
  // Inline strings are never formulas, even for source-controlled text beginning
32
33
  // with =, +, -, or @. This is essential for an audit export opened in Excel.
33
- const raw = (typeof value === "object" ? JSON.stringify(value) : String(value)) ?? "";
34
- if (raw.length > MAX_CELL) throw new Error(`Excel cell ${address} exceeds ${MAX_CELL} characters`);
34
+ let raw = ((typeof value === "object" ? JSON.stringify(value) : String(value)) ?? "").toWellFormed();
35
+ if (raw.length > MAX_CELL) {
36
+ let end = MAX_CELL - TRUNCATION_MARKER.length;
37
+ // Keep supplementary Unicode characters intact at the cut boundary.
38
+ if (/[\uD800-\uDBFF]/.test(raw[end - 1])) end--;
39
+ raw = raw.slice(0, end) + TRUNCATION_MARKER;
40
+ }
35
41
  return `<c r="${address}"${style} t="inlineStr"><is><t xml:space="preserve">${xml(raw)}</t></is></c>`;
36
42
  }
37
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vigievuln",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "Polyglot dependency auditor for Maven, Gradle, JavaScript, Composer, PyPI, NuGet, Go, Ruby and 9 CMS/frameworks, with offline scans and audit reports.",
5
5
  "keywords": [
6
6
  "sca",
package/vigievuln.js CHANGED
@@ -298,7 +298,7 @@ if (process.argv.includes("--export-cache") || process.argv.includes("--import-c
298
298
  // Standalone differential audit between two findings JSON exports. Mirrors the other
299
299
  // pre-parse intercepts so it never collides with the main option set (which requires -s).
300
300
  if (process.argv[2] === "diff") {
301
- const { diffFindings, summarizeDiff, newProductionCveCount } = require("./lib/diff");
301
+ const { diffFindings, summarizeDiff, newProductionCveCount, isProductionCve, validateFindingsDocument, baselineProjectWarning } = require("./lib/diff");
302
302
  const rest = process.argv.slice(3);
303
303
  const positionals = rest.filter(a => !a.startsWith("-"));
304
304
  const [basePath, curPath] = positionals;
@@ -310,10 +310,12 @@ if (process.argv[2] === "diff") {
310
310
  process.exit(2);
311
311
  }
312
312
  let baseDoc, curDoc;
313
- try { baseDoc = JSON.parse(fs.readFileSync(basePath, "utf8")); }
313
+ try { baseDoc = validateFindingsDocument(JSON.parse(fs.readFileSync(basePath, "utf8"))); }
314
314
  catch (e) { console.error(chalk.red(`❌ cannot read baseline ${basePath}: ${e.message}`)); process.exit(2); }
315
- try { curDoc = JSON.parse(fs.readFileSync(curPath, "utf8")); }
315
+ try { curDoc = validateFindingsDocument(JSON.parse(fs.readFileSync(curPath, "utf8"))); }
316
316
  catch (e) { console.error(chalk.red(`❌ cannot read current ${curPath}: ${e.message}`)); process.exit(2); }
317
+ const baselineWarning = baselineProjectWarning(baseDoc, curDoc);
318
+ if (baselineWarning) console.error(chalk.yellow(`⚠ ${baselineWarning.message}`));
317
319
  const d = diffFindings(baseDoc, curDoc);
318
320
  const s = summarizeDiff(d);
319
321
  const newProd = newProductionCveCount(d);
@@ -323,13 +325,19 @@ if (process.argv[2] === "diff") {
323
325
  console.log();
324
326
  const sev = Object.entries(s.cve.addedBySeverity).filter(([, n]) => n).map(([k, n]) => `${n} ${k.toLowerCase()}`).join(", ") || "none";
325
327
  console.log(` ${chalk.bold("New production CVE findings:")} ${newProd ? chalk.red.bold(newProd) : chalk.green("0")} ${chalk.dim(`(${sev})`)}`);
326
- const newCves = (d.cve.added || []).filter(f => !f.suppressed && !f.cpeFiltered);
328
+ const newCves = (d.cve.added || []).filter(isProductionCve);
327
329
  for (const f of newCves.slice(0, 25)) console.log(` ${chalk.red("•")} ${f.id} ${chalk.dim((f.severity || "") + " · " + ((f.dep && f.dep.coord) || "") + "@" + ((f.dep && f.dep.version) || ""))}`);
328
330
  if (newCves.length > 25) console.log(chalk.dim(` …and ${newCves.length - 25} more`));
329
331
  if (jsonOut) {
330
- const out = { tool: "vigievuln", kind: "fad-diff/1", baseline: basePath, current: curPath, summary: s, diff: d };
331
- try { fs.mkdirSync(path.dirname(path.resolve(jsonOut)), { recursive: true }); } catch { /* ignore */ }
332
- fs.writeFileSync(jsonOut, JSON.stringify(out, null, 2) + "\n");
332
+ const out = { tool: "vigievuln", kind: "fad-diff/1", baseline: basePath, current: curPath, summary: s, diff: d,
333
+ warnings: baselineWarning ? [baselineWarning] : [] };
334
+ try {
335
+ fs.mkdirSync(path.dirname(path.resolve(jsonOut)), { recursive: true });
336
+ fs.writeFileSync(jsonOut, JSON.stringify(out, null, 2) + "\n");
337
+ } catch (err) {
338
+ console.error(chalk.red(`❌ cannot write diff report to ${jsonOut}: ${err.message}`));
339
+ process.exit(2);
340
+ }
333
341
  console.log(chalk.green(`\n✅ diff written → ${jsonOut}`));
334
342
  }
335
343
  console.log();
@@ -812,6 +820,19 @@ if (options.failOn) {
812
820
  }
813
821
  options.failOn = lvl;
814
822
  }
823
+ let baselineDoc = null;
824
+ if (options.failOnNew && !options.baseline) {
825
+ console.error(chalk.red("❌ --fail-on-new requires --baseline <findings.json>"));
826
+ process.exit(2);
827
+ }
828
+ if (options.baseline) {
829
+ try {
830
+ baselineDoc = require("./lib/diff").validateFindingsDocument(JSON.parse(fs.readFileSync(options.baseline, "utf8")));
831
+ } catch (err) {
832
+ console.error(chalk.red(`❌ cannot read baseline ${options.baseline}: ${err.message}`));
833
+ process.exit(2);
834
+ }
835
+ }
815
836
  // Read-only when no target is given. No need for an explicit --test flag.
816
837
  const readOnly = !options.target;
817
838
  // -t is an EXTRACTION step (walk + link the reactor + cleaned tree + POM analysis),
@@ -1450,9 +1471,17 @@ async function timedPhase(label, fn) {
1450
1471
  ui.info(`run Snyk on the cleaned tree:`);
1451
1472
  console.log(" " + chalk.white(`cd ${options.target} && snyk test --json --all-projects | snyk-to-html -o ../snyk-deps-check.html`));
1452
1473
  }
1453
- })();
1474
+ })().catch(err => {
1475
+ console.error(chalk.red(`❌ scan failed: ${err.message || String(err)}`));
1476
+ if (verbose && err.stack) console.error(err.stack);
1477
+ process.exitCode = 2;
1478
+ });
1454
1479
 
1455
1480
  async function runReportFlow(resolved, ecoFlags = {}) {
1481
+ if (!options.proxyCache && !options.importAnonymized) {
1482
+ const t = require("./lib/i18n").makeT(options.lang);
1483
+ console.error("\n " + chalk.yellow("⚠") + " " + chalk.yellow(t("For faster scans with the VigieVuln DB or a seed → vigievuln setup")));
1484
+ }
1456
1485
  const { activeIds = [], runMaven = true, runGradle = false, runNpm = false, privateLibIds = [], mavenRepos = [], regMap = {}, collectWarnings = [], mavenPropsByPom = null, mavenStore = null, gradlePlatformBoms = [], parsedManifests = [], composerPlatforms = [], walkOpts = {} } = ecoFlags;
1457
1486
  const { excludePath = [], defaultExcludes = true } = walkOpts;
1458
1487
  const registriesFor = eco => regMap[eco] || [];
@@ -2285,12 +2314,18 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2285
2314
  // Marked in place; kept in the machine exports (flagged) but dropped from the
2286
2315
  // human report's active chapters and from CI gating.
2287
2316
  let suppressedCount = 0;
2317
+ const triageWarnings = [];
2288
2318
  if (options.ignore || options.vex) {
2289
2319
  try {
2290
- const { parseIgnoreFile, parseVex, applySuppressions } = require("./lib/suppress");
2320
+ const { parseIgnoreFile, parseVex, applySuppressions, hasGlobalIgnoreRule } = require("./lib/suppress");
2291
2321
  const rules = [];
2292
2322
  if (options.ignore) rules.push(...parseIgnoreFile(fs.readFileSync(options.ignore, "utf8")));
2293
2323
  if (options.vex) rules.push(...parseVex(JSON.parse(fs.readFileSync(options.vex, "utf8"))));
2324
+ if (hasGlobalIgnoreRule(rules)) {
2325
+ const warning = { type: "global-ignore", message: "The --ignore file contains a global wildcard: all CVE findings are suppressed, including CI gates. Use an advisory ID or package scope to narrow it." };
2326
+ triageWarnings.push(warning);
2327
+ ui.warn(warning.message);
2328
+ }
2294
2329
  suppressedCount = applySuppressions(cveMatches, rules);
2295
2330
  const via = [options.ignore && "--ignore", options.vex && "--vex"].filter(Boolean).join(" + ");
2296
2331
  if (suppressedCount) ui.info(chalk.dim(`triage: ${suppressedCount} finding(s) suppressed by ${via}`));
@@ -2494,6 +2529,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2494
2529
  }
2495
2530
 
2496
2531
  const reportWarnings = [
2532
+ ...triageWarnings,
2497
2533
  ...sourceHealth.degraded().map(s => ({type:"source-unavailable",count:1,
2498
2534
  message:`${s.id}: source unavailable (${s.codes.join(", ") || "no response"}); coverage may be incomplete.`})),
2499
2535
  ...sourceHealth.stale().map(s => ({ type:"source-stale", count:1,
@@ -2583,39 +2619,46 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2583
2619
 
2584
2620
  // Differential audit vs --baseline: build the current findings doc once, diff it
2585
2621
  // against the prior export → a `diff` block for the report + JSON export, and a
2586
- // `--fail-on-new` gate signal. Best-effort: a missing/unreadable baseline warns.
2622
+ // `--fail-on-new` gate signal. The baseline is validated before scanning.
2587
2623
  let diff = null, jsonDiff = null;
2588
2624
  if (options.baseline) {
2589
2625
  try {
2590
- const baseDoc = JSON.parse(fs.readFileSync(options.baseline, "utf8"));
2626
+ const baseDoc = baselineDoc;
2591
2627
  const { buildFindings } = require("./lib/json-export");
2592
2628
  const curDoc = buildFindings({ cveMatches, retireMatches, vendoredJsInventory, eolResults, obsoleteResults, outdatedResults, licenseResults,
2593
2629
  excludedDirs, resolvedDeps: resolved, projectInfo, toolVersion: pkg.version, typosquats,
2594
2630
  applications: appState.applications, applicationInventory: appState.inventory,
2595
2631
  applicationRelations, coverage: appState.coverage, warnings: reportWarnings });
2596
- const { diffFindings, summarizeDiff } = require("./lib/diff");
2632
+ const { diffFindings, summarizeDiff, baselineProjectWarning } = require("./lib/diff");
2633
+ const warning = baselineProjectWarning(baseDoc, curDoc);
2634
+ if (warning) { reportWarnings.push(warning); ui.warn(warning.message); }
2597
2635
  const dd = diffFindings(baseDoc, curDoc);
2598
2636
  diff = { ...dd, summary: summarizeDiff(dd) };
2599
2637
  jsonDiff = { summary: diff.summary, cve: { added: dd.cve.added, removed: dd.cve.removed, unassessed: dd.cve.unassessed } };
2600
- } catch (err) { ui.warn(`baseline diff skipped (${options.baseline}): ${err.message}`); }
2638
+ } catch (err) { throw new Error(`baseline diff failed (${options.baseline}): ${err.message}`); }
2601
2639
  }
2602
2640
 
2603
2641
  const wrote = [];
2604
- let xlsxFailed = false;
2642
+ let exportFailed = false;
2605
2643
  // Announce coverage gaps for every output combination, including JSON-only.
2606
2644
  warnIfDegraded();
2607
- if (out.html || out.doc) {
2608
- await ensureDir(out.html); await ensureDir(out.doc);
2609
- // Include collection/registry outages even when they preceded step progress.
2610
- const { htmlPath, docPath } = await writeReports({
2611
- cveMatches: prodMatches, devCveMatches: devMatches, embeddedMatches, retireMatches, vendoredJsInventory, certFindings,
2612
- eolResults, obsoleteResults, outdatedResults, licenseResults, excludedDirs,
2613
- resolvedDeps: resolved, projectInfo, warnings: reportWarnings, parsedManifests, diff, locale: options.lang,
2614
- applications: appState.applications, applicationInventory: appState.inventory, applicationRelations, coverage: appState.coverage,
2615
- htmlPath: out.html, docPath: out.doc,
2616
- });
2617
- if (htmlPath) wrote.push(["HTML report", htmlPath]);
2618
- if (docPath) wrote.push(["Word .doc", docPath]);
2645
+ for (const [format, label] of [["html", "HTML report"], ["doc", "Word .doc"]]) {
2646
+ if (!out[format]) continue;
2647
+ try {
2648
+ // Write formats independently: a failed destination must not prevent
2649
+ // the remaining requested artifacts or the gate summary from running.
2650
+ await writeReports({
2651
+ cveMatches: prodMatches, devCveMatches: devMatches, embeddedMatches, retireMatches, vendoredJsInventory, certFindings,
2652
+ eolResults, obsoleteResults, outdatedResults, licenseResults, excludedDirs,
2653
+ resolvedDeps: resolved, projectInfo, warnings: reportWarnings, parsedManifests, diff, locale: options.lang,
2654
+ applications: appState.applications, applicationInventory: appState.inventory, applicationRelations, coverage: appState.coverage,
2655
+ htmlPath: format === "html" ? out.html : null, docPath: format === "doc" ? out.doc : null,
2656
+ });
2657
+ wrote.push([label, out[format]]);
2658
+ } catch (err) {
2659
+ exportFailed = true;
2660
+ ui.warn(`${label} export failed (${out[format]}): ${err.message}`);
2661
+ }
2619
2662
  }
2620
2663
 
2621
2664
  // Machine-readable exports. Use the full match set (prod + dev + cpe-filtered) so
@@ -2626,7 +2669,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2626
2669
  await ensureDir(out.sbom);
2627
2670
  writeCycloneDx(resolved, cveMatches, out.sbom, { projectInfo, toolVersion: pkg.version, timestamp: projectInfo.generatedAt, licenseResults });
2628
2671
  wrote.push(["CycloneDX SBOM", out.sbom]);
2629
- } catch (err) { ui.warn(`SBOM export failed: ${err.message}`); }
2672
+ } catch (err) { exportFailed = true; ui.warn(`SBOM export failed: ${err.message}`); }
2630
2673
  }
2631
2674
  if (out.csaf) {
2632
2675
  try {
@@ -2634,7 +2677,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2634
2677
  await ensureDir(out.csaf);
2635
2678
  writeCsaf(resolved, cveMatches, out.csaf, { projectInfo, toolVersion: pkg.version, timestamp: projectInfo.generatedAt });
2636
2679
  wrote.push(["CSAF 2.0 VEX", out.csaf]);
2637
- } catch (err) { ui.warn(`CSAF export failed: ${err.message}`); }
2680
+ } catch (err) { exportFailed = true; ui.warn(`CSAF export failed: ${err.message}`); }
2638
2681
  }
2639
2682
  if (out.json) {
2640
2683
  try {
@@ -2645,7 +2688,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2645
2688
  typosquats, diff: jsonDiff, applications: appState.applications, applicationInventory: appState.inventory,
2646
2689
  applicationRelations, coverage: appState.coverage, warnings: reportWarnings }, out.json);
2647
2690
  wrote.push(["Findings JSON", out.json]);
2648
- } catch (err) { ui.warn(`JSON export failed: ${err.message}`); }
2691
+ } catch (err) { exportFailed = true; ui.warn(`JSON export failed: ${err.message}`); }
2649
2692
  }
2650
2693
  if (out.xlsx) {
2651
2694
  try {
@@ -2656,7 +2699,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2656
2699
  typosquats, diff: jsonDiff, applications: appState.applications, applicationInventory: appState.inventory,
2657
2700
  applicationRelations, coverage: appState.coverage, warnings: reportWarnings }, out.xlsx);
2658
2701
  wrote.push(["Excel workbook", out.xlsx]);
2659
- } catch (err) { xlsxFailed = true; ui.warn(`XLSX export failed: ${err.message}`); }
2702
+ } catch (err) { exportFailed = true; ui.warn(`XLSX export failed: ${err.message}`); }
2660
2703
  }
2661
2704
  if (out.sarif) {
2662
2705
  try {
@@ -2664,7 +2707,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2664
2707
  await ensureDir(out.sarif);
2665
2708
  writeSarif(cveMatches.filter(m => !m.suppressed), out.sarif, { projectInfo, toolVersion: pkg.version, certFindings });
2666
2709
  wrote.push(["SARIF", out.sarif]);
2667
- } catch (err) { ui.warn(`SARIF export failed: ${err.message}`); }
2710
+ } catch (err) { exportFailed = true; ui.warn(`SARIF export failed: ${err.message}`); }
2668
2711
  }
2669
2712
 
2670
2713
  // Integrity manifest: a standard SHA256SUMS over every artifact written this run,
@@ -2737,7 +2780,7 @@ async function runReportFlow(resolved, ecoFlags = {}) {
2737
2780
  process.exitCode = 2;
2738
2781
  }
2739
2782
  }
2740
- if (xlsxFailed) process.exitCode = 2;
2783
+ if (exportFailed) process.exitCode = 2;
2741
2784
  return {cveIds:[...new Set(cveMatches.map(m=>m.cve?.id).filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))]};
2742
2785
  }
2743
2786