vigievuln 1.2.0 → 1.3.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 (121) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +13 -7
  3. package/lib/advisory-freshness.js +2 -0
  4. package/lib/airgap-project.js +35 -7
  5. package/lib/applicability-evidence.js +12 -0
  6. package/lib/artifacts/applications.js +54 -0
  7. package/lib/artifacts/cve-view.js +108 -0
  8. package/lib/artifacts/enrichment.js +86 -0
  9. package/lib/artifacts/go-main-identity.js +45 -0
  10. package/lib/artifacts/go-publisher-advisories.js +24 -0
  11. package/lib/artifacts/index.js +272 -0
  12. package/lib/artifacts/publisher-advisories.js +12 -0
  13. package/lib/artifacts/remediation-report.js +48 -0
  14. package/lib/artifacts/report-inventory.js +26 -0
  15. package/lib/artifacts/report.js +191 -0
  16. package/lib/artifacts/risk-report.js +120 -0
  17. package/lib/artifacts/sbom.js +68 -0
  18. package/lib/artifacts/scan.js +401 -0
  19. package/lib/cache-archive-sqlite.js +41 -25
  20. package/lib/certs/analyze.js +49 -13
  21. package/lib/charts.js +124 -32
  22. package/lib/cli-command-routing.js +20 -6
  23. package/lib/cli-groups.js +2 -1
  24. package/lib/cli-image.js +206 -0
  25. package/lib/codecs/binary/elf-metadata.js +42 -0
  26. package/lib/codecs/binary/go-buildinfo.js +37 -0
  27. package/lib/codecs/binary/metadata.js +7 -0
  28. package/lib/codecs/binary/pe-metadata.js +27 -1
  29. package/lib/codecs/binary/scan.js +44 -26
  30. package/lib/codecs/binary/sniff.js +16 -15
  31. package/lib/codecs/binary.codec.js +27 -4
  32. package/lib/codecs/go/parse.js +10 -4
  33. package/lib/codecs/go.codec.js +23 -6
  34. package/lib/codecs/gradle/parse.js +63 -2
  35. package/lib/codecs/gradle/versionless.js +175 -0
  36. package/lib/codecs/gradle.codec.js +20 -3
  37. package/lib/codecs/index.js +2 -2
  38. package/lib/codecs/maven.codec.js +9 -4
  39. package/lib/codecs/npm/collect.js +6 -11
  40. package/lib/codecs/nuget/parse.js +16 -5
  41. package/lib/codecs/nuget.codec.js +2 -1
  42. package/lib/codecs/pypi/parse.js +56 -15
  43. package/lib/codecs/pypi.codec.js +2 -0
  44. package/lib/csaf-export.js +46 -11
  45. package/lib/cve-download.js +33 -29
  46. package/lib/cve-match.js +10 -0
  47. package/lib/cve-packages-proxy.js +19 -0
  48. package/lib/cve-report.js +273 -165
  49. package/lib/deps-descriptor.js +25 -3
  50. package/lib/diagnostics.js +12 -0
  51. package/lib/diff.js +0 -0
  52. package/lib/epss.js +6 -6
  53. package/lib/euvd.js +34 -4
  54. package/lib/finding-enrichment.js +165 -0
  55. package/lib/finding-summary.js +4 -3
  56. package/lib/i18n.js +35 -9
  57. package/lib/image-network.js +54 -0
  58. package/lib/image-references.js +203 -0
  59. package/lib/image-registry.js +385 -0
  60. package/lib/image-update.js +39 -0
  61. package/lib/json-export.js +100 -10
  62. package/lib/kev.js +6 -6
  63. package/lib/maven-bom.js +2 -1
  64. package/lib/merge-sources.js +3 -0
  65. package/lib/native-advisories.js +9 -7
  66. package/lib/native-cna-identities.js +12 -0
  67. package/lib/native-package-match.js +159 -0
  68. package/lib/native-source-prepare.js +60 -0
  69. package/lib/nvd.js +34 -23
  70. package/lib/osv.js +33 -14
  71. package/lib/project-descriptor.js +3 -2
  72. package/lib/provenance.js +8 -2
  73. package/lib/providers/alpine.js +8 -0
  74. package/lib/providers/common.js +11 -3
  75. package/lib/providers/debian.js +11 -0
  76. package/lib/providers/euvd.js +2 -1
  77. package/lib/providers/freexian.js +13 -0
  78. package/lib/providers/github.js +1 -0
  79. package/lib/providers/go.js +2 -1
  80. package/lib/providers/index.js +18 -14
  81. package/lib/providers/nginx.js +5 -0
  82. package/lib/providers/nvd.js +1 -1
  83. package/lib/providers/osv.js +1 -1
  84. package/lib/providers/osvdb.js +2 -2
  85. package/lib/proxy-throttle.js +89 -29
  86. package/lib/purl.js +10 -2
  87. package/lib/record-freshness.js +22 -0
  88. package/lib/report-notices.js +47 -0
  89. package/lib/report-time.js +45 -0
  90. package/lib/request-failure.js +22 -0
  91. package/lib/resource-cache/engine.js +130 -26
  92. package/lib/resource-cache/snapshot-projection.js +33 -0
  93. package/lib/resource-cache/validate.js +22 -5
  94. package/lib/risk-evidence.js +18 -0
  95. package/lib/sarif-export.js +17 -9
  96. package/lib/sbom-export.js +38 -12
  97. package/lib/source-health.js +25 -8
  98. package/lib/source-image-scan.js +57 -0
  99. package/lib/source-profile.js +6 -3
  100. package/lib/sqlite-driver.js +15 -1
  101. package/lib/suppress.js +34 -13
  102. package/lib/system-inventory/advisories.js +169 -0
  103. package/lib/system-inventory/alpine-tracker.js +47 -0
  104. package/lib/system-inventory/collect.js +118 -0
  105. package/lib/system-inventory/current-debian.js +99 -0
  106. package/lib/system-inventory/distribution-sources.js +132 -0
  107. package/lib/system-inventory/freexian-ela.js +32 -0
  108. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  109. package/lib/system-inventory/freexian-tracker.js +72 -0
  110. package/lib/system-inventory/historical-debian.js +196 -0
  111. package/lib/system-inventory/index.js +2 -0
  112. package/lib/system-inventory/nginx-advisories.js +39 -0
  113. package/lib/system-inventory/rpm-storage.js +86 -0
  114. package/lib/system-inventory/targeted.js +70 -0
  115. package/lib/system-inventory/versions.js +59 -0
  116. package/lib/transitive.js +11 -2
  117. package/lib/ui.js +8 -5
  118. package/lib/unmanaged.js +1 -1
  119. package/lib/xlsx-export.js +8 -2
  120. package/package.json +12 -3
  121. package/vigievuln.js +279 -127
@@ -5,33 +5,48 @@ const path=require('node:path');
5
5
  const os=require('node:os');
6
6
  const crypto=require('node:crypto');
7
7
  const zlib=require('node:zlib');
8
- const {execFile}=require('node:child_process');
9
- const {promisify}=require('node:util');
10
- const run=promisify(execFile);
8
+ const tar=require('tar-stream');
9
+ const {pipeline}=require('node:stream/promises');
10
+ const {Transform}=require('node:stream');
11
11
  const {openCacheDb,closeCacheDbs,SCHEMA_VERSION}=require('./cache-db');
12
12
  const {proxyOrigin:canonicalOrigin}=require('./proxy-scope');
13
13
  const FORMAT='vigievuln-sqlite-cache';
14
14
  const ALLOWED=new Set(['.vigie-vuln/','.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json','.vigievuln-archive-origin.json']);
15
15
  const sha256=file=>new Promise((resolve,reject)=>{const hash=crypto.createHash('sha256'),stream=fs.createReadStream(file);stream.on('data',part=>hash.update(part));stream.on('error',reject);stream.on('end',()=>resolve(hash.digest('hex')))});
16
- async function inspectArchive(file){
17
- let names,details;
16
+ async function extractArchive(file,stage){
17
+ const seen=new Set(),extract=tar.extract();let failure,total=0;
18
+ extract.on('entry',(header,stream,next)=>{
19
+ (async()=>{
20
+ const name=header.name;
21
+ if(!ALLOWED.has(name)||seen.has(name)||seen.size>=4)throw Error('unsupported cache bundle: missing, duplicate or unexpected archive entries');
22
+ seen.add(name);
23
+ if(name==='.vigie-vuln/'){
24
+ if(header.type!=='directory')throw Error('cache bundle contains links or special files');
25
+ for await(const _ of stream){};next();return;
26
+ }
27
+ if(header.type!=='file' && header.type!=='contiguous-file')throw Error('cache bundle contains links or special files');
28
+ const limit=name==='.vigie-vuln/cache.sqlite'?64*1024**3:1024**2;
29
+ if(!Number.isSafeInteger(header.size)||header.size<0||header.size>limit||(total+=header.size)>64*1024**3+2*1024**2)throw Error('cache bundle exceeds size limit');
30
+ const destination=path.join(stage,...name.split('/'));
31
+ await fs.promises.mkdir(path.dirname(destination),{recursive:true,mode:0o700});
32
+ await pipeline(stream,fs.createWriteStream(destination,{flags:'wx',mode:0o600}));next();
33
+ })().catch(error=>{failure=error;stream.destroy();extract.destroy(error);});
34
+ });
35
+ let expanded=0;const counter=new Transform({transform(chunk,encoding,callback){expanded+=chunk.length;if(expanded>64*1024**3+16*1024**2)callback(Error('cache bundle exceeds size limit'));else callback(null,chunk);}});
36
+ try{await pipeline(fs.createReadStream(file),zlib.createGunzip(),counter,extract);}
37
+ catch(error){if(failure)throw failure;if(error.message==='cache bundle exceeds size limit')throw error;throw Error('unsupported cache bundle: invalid gzip or tar data');}
38
+ if(!seen.has('.vigie-vuln/cache.sqlite')||!seen.has('.vigie-vuln/cli-bundle-meta.json'))throw Error('unsupported cache bundle: missing or unexpected archive entries');
39
+ }
40
+ async function createArchive(file,stage,names){
41
+ const pack=tar.pack();const output=pipeline(pack,zlib.createGzip(),fs.createWriteStream(file,{flags:'wx',mode:0o600}));
18
42
  try{
19
- ({stdout:names}=await run('tar',['-tzf',file],{maxBuffer:64*1024}));
20
- ({stdout:details}=await run('tar',['-tvzf',file],{maxBuffer:128*1024}));
21
- }catch(error){
22
- // Distinguish a malformed archive from an unavailable or resource-starved
23
- // tar process. Do not include stderr or command arguments: both can contain
24
- // private local paths and attacker-controlled member names.
25
- const code=error?.code;
26
- if(typeof code==='string' && /^[A-Z][A-Z0-9_]{0,31}$/.test(code))throw Error(`cannot inspect cache bundle: tar process failed (${code})`);
27
- if(typeof code==='number')throw Error(`unsupported cache bundle: tar exited with status ${code}`);
28
- if(typeof error?.signal==='string' && /^SIG[A-Z0-9]+$/.test(error.signal))throw Error(`cannot inspect cache bundle: tar terminated (${error.signal})`);
29
- throw Error('cannot inspect cache bundle: tar failed');
30
- }
31
- const listed=names.trim().split(/\r?\n/).filter(Boolean);
32
- if(!listed.length||listed.length>4||!listed.includes('.vigie-vuln/cache.sqlite')||!listed.includes('.vigie-vuln/cli-bundle-meta.json')||listed.some(name=>!ALLOWED.has(name)))throw Error('unsupported cache bundle: missing or unexpected archive entries');
33
- const types=details.trim().split(/\r?\n/);
34
- if(types.length!==listed.length||types.some(line=>!['-','d'].includes(line[0])))throw Error('cache bundle contains links or special files');
43
+ for(const name of names){
44
+ const source=path.join(stage,...name.split('/')),stat=await fs.promises.stat(source);
45
+ const entry=pack.entry({name,size:stat.size,mode:0o600,type:'file'});
46
+ await pipeline(fs.createReadStream(source),entry);
47
+ }
48
+ pack.finalize();await output;
49
+ }catch(error){pack.destroy(error);await output.catch(()=>{});throw error;}
35
50
  }
36
51
  function verifyDb(file){
37
52
  const db=openCacheDb({cacheDir:path.dirname(file),readonly:true});
@@ -158,11 +173,12 @@ function mergeDatabase(targetFile,incomingFile){
158
173
  }
159
174
  async function importCache(source,{targetDir=require('./cache-directory').getCacheDir(),proxyOrigin,replace=false,force=false,onProgress,requireUsableSeed=false}={}){
160
175
  const abs=path.resolve(source);if(!fs.statSync(abs).isFile())throw Error('cache bundle is not a file');
161
- onProgress?.({phase:'validating'});await inspectArchive(abs);
176
+ onProgress?.({phase:'validating'});
177
+ fs.mkdirSync(path.dirname(targetDir),{recursive:true,mode:0o700});
162
178
  const stage=fs.mkdtempSync(path.join(path.dirname(targetDir),'vigievuln-sqlite-import-'));
163
179
  try{
164
180
  onProgress?.({phase:'extracting'});
165
- await run('tar',['-xzf',abs,'--no-same-owner','-C',stage],{maxBuffer:64*1024});
181
+ await extractArchive(abs,stage);
166
182
  const root=path.join(stage,'.vigie-vuln'),file=path.join(root,'cache.sqlite'),manifestPath=path.join(root,'cli-bundle-meta.json');
167
183
  for(const item of [root,file,manifestPath]){const st=fs.lstatSync(item);if(st.isSymbolicLink()||st.nlink!==1&&st.isFile()||!(st.isFile()||st.isDirectory()))throw Error('unsafe cache bundle entry')}
168
184
  const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));
@@ -204,8 +220,8 @@ async function exportCache(destination,{sourceDir=require('./cache-directory').g
204
220
  try {
205
221
  // Enumerate exactly the files accepted by the reader. SQLite may create
206
222
  // sidecars in a temporary directory; never include them implicitly.
207
- const args=['-czf',temporary,'-C',stage,'.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json'];if(proxyOrigin)args.push('.vigievuln-archive-origin.json');
208
- await run('tar',args,{maxBuffer:64*1024});
223
+ const names=['.vigie-vuln/cache.sqlite','.vigie-vuln/cli-bundle-meta.json'];if(proxyOrigin)names.push('.vigievuln-archive-origin.json');
224
+ await createArchive(temporary,stage,names);
209
225
  verifyStandaloneSnapshot(file);
210
226
  fs.renameSync(temporary,abs);
211
227
  } finally {fs.rmSync(temporary,{force:true})}
@@ -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
  }
package/lib/charts.js CHANGED
@@ -13,8 +13,8 @@
13
13
  * a CSS class — a class would not survive the canvas rasterisation (the document
14
14
  * stylesheet is not applied to the serialised SVG).
15
15
  *
16
- * Charts: (1) CWE of direct vulns, (2) vulnerable indirect deps by introducing
17
- * component, (3) exposed applications or modules, and (4) fix-priority bands.
16
+ * Charts: (1) CWE distribution, (2) findings by component, (3) exposure or
17
+ * severity breakdown, and (4) fix-priority bands.
18
18
  * All four cards use donuts, including application reports. The legends show counts;
19
19
  * application categories and exposed instances may overlap.
20
20
  *
@@ -67,7 +67,6 @@ const sevKey = m => {
67
67
  return s in SEV_RANK ? s : "unknown";
68
68
  };
69
69
  const emptySeg = () => ({ critical: 0, high: 0, medium: 0, low: 0, unknown: 0 });
70
- const coordKeyOf = dep => dep.coordKey || `${dep.ecosystem === "npm" ? "npm:" : (dep.groupId || "") + ":"}${dep.artifactId}`;
71
70
 
72
71
  // Keep the top-N rows; fold the remainder into a single "+K more" aggregate row
73
72
  // (a chart must never silently drop categories).
@@ -90,10 +89,10 @@ function capRows(rows, topN, { stacked = false, t = EN_T } = {}) {
90
89
  // ---------------------------------------------------------------- aggregators
91
90
 
92
91
  /** Chart 1 — CWE distribution of DIRECT production vulns, with per-severity counts. */
93
- function cweByCriticality(prodMatches, { topN = 7, t = EN_T, cweTitle = cweName } = {}) {
92
+ function cweByCriticality(prodMatches, { topN = 7, t = EN_T, cweTitle = cweName, includeTransitive = false } = {}) {
94
93
  const map = new Map();
95
94
  for (const m of prodMatches || []) {
96
- if (m.dep && m.dep.scope === "transitive") continue; // direct (declared) only
95
+ if (!includeTransitive && m.dep && m.dep.scope === "transitive") continue; // source direct findings by default
97
96
  const cwes = Array.isArray(m.cve && m.cve.cwes) ? m.cve.cwes : [];
98
97
  if (!cwes.length) continue; // a "by CWE" chart only counts categorised findings
99
98
  const sev = sevKey(m);
@@ -123,6 +122,74 @@ function readableDepLabel(coordKey) {
123
122
  return tail || s;
124
123
  }
125
124
 
125
+ /** Findings grouped by actual image identity, with per-severity counts. */
126
+ function findingsByImage(matches, artifacts = [], { topN = 7, t = EN_T } = {}) {
127
+ const by = new Map(), targets = new Map((artifacts || []).map(a => [a.id, a]));
128
+ for (const match of matches || []) {
129
+ const id = match.dep?.artifactTargetId; if (!id) continue;
130
+ if (!by.has(id)) by.set(id, { segments: emptySeg(), total: 0 });
131
+ const group = by.get(id); group.segments[sevKey(match)]++; group.total++;
132
+ }
133
+ const rows = [...by].map(([id, group]) => {
134
+ const m = targets.get(id)?.metadata || {};
135
+ const source = m.acquisition?.reference || m.registryEvidence?.reference || m.tags?.[0] || m.source || id;
136
+ const platform = m.platform && typeof m.platform === 'object' ? [m.platform.os, m.platform.architecture, m.platform.variant].filter(Boolean).join('/') : m.platform;
137
+ return { key: id, label: platform ? `${source} (${platform})` : source, segments: group.segments, total: group.total };
138
+ }).sort((a, b) => b.total - a.total || String(a.label).localeCompare(String(b.label)));
139
+ return capRows(rows, topN, { stacked: true, t });
140
+ }
141
+
142
+ /** Group each finding by image, application or module; show shared owners
143
+ * together and retain unknown ownership in an unattributed group. */
144
+ function findingsByComponent(matches, { artifacts = [], applications = [], moduleNames = new Map(), topN = 7, t = EN_T } = {}) {
145
+ const images = new Map(artifacts.map(a => [a.id, a]));
146
+ const apps = new Map(applications.map(a => [a.id, a]));
147
+ const groups = new Map(), occurrences = [], indexed = new Map();
148
+ for (const m of matches || []) {
149
+ const identity = m.findingId ? JSON.stringify([m.dep?.artifactTargetId || null, m.findingId]) : null;
150
+ const prior = identity && indexed.get(identity);
151
+ if (!prior) {
152
+ const copy = { ...m, dep: { ...m.dep, manifestPaths: [...(m.dep?.manifestPaths || [])] }, applicationIds: [...(m.applicationIds || [])] };
153
+ occurrences.push(copy); if (identity) indexed.set(identity, copy);
154
+ } else {
155
+ prior.applicationIds.push(...(m.applicationIds || []));
156
+ prior.dep.manifestPaths.push(...(m.dep?.manifestPaths || []));
157
+ if (SEV_RANK[sevKey(m)] > SEV_RANK[sevKey(prior)]) prior.cve = m.cve;
158
+ }
159
+ }
160
+ for (const m of occurrences) {
161
+ const artifact = m.dep?.artifactTargetId;
162
+ let key, label;
163
+ if (artifact) {
164
+ const meta = images.get(artifact)?.metadata || {};
165
+ const source = meta.acquisition?.reference || meta.registryReference?.reference || meta.tags?.[0] || meta.source || artifact;
166
+ const platform = meta.platform && typeof meta.platform === 'object' ? [meta.platform.os, meta.platform.architecture, meta.platform.variant].filter(Boolean).join('/') : meta.platform;
167
+ key = `image:${artifact}`; label = platform ? `${source} (${platform})` : source;
168
+ } else {
169
+ const appIds = [...new Set((m.applicationIds || []).filter(Boolean))];
170
+ // When parsed descriptors are available, they are the authoritative
171
+ // module inventory. A dependency's own metadata path is not a project module.
172
+ const paths = [...new Set((m.dep?.manifestPaths || []).filter(path => path && (!moduleNames.size || moduleNames.has(path))))];
173
+ if (appIds.length === 1) {
174
+ const app = apps.get(appIds[0]); key = `application:${appIds[0]}`;
175
+ label = `${app?.type || t('Application')} · ${app?.root || appIds[0]}`;
176
+ } else if (appIds.length > 1) {
177
+ appIds.sort(); key = `shared-applications:${JSON.stringify(appIds)}`;
178
+ label = `${t('Shared')}: ${appIds.map(id => apps.get(id)?.root || id).join(', ')}`;
179
+ } else if (!appIds.length && paths.length === 1) {
180
+ key = `module:${paths[0]}`; label = moduleNames.get(paths[0]) || paths[0];
181
+ } else if (paths.length > 1) {
182
+ paths.sort(); key = `shared-modules:${JSON.stringify(paths)}`;
183
+ label = `${t('Shared')}: ${paths.map(path => moduleNames.get(path) || path).join(', ')}`;
184
+ } else { key = '__unattributed__'; label = t('Unattributed'); }
185
+ }
186
+ if (!groups.has(key)) groups.set(key, { key, label, segments: emptySeg(), total: 0 });
187
+ const group = groups.get(key); group.segments[sevKey(m)]++; group.total++;
188
+ }
189
+ const rows = [...groups.values()].sort((a,b) => b.total - a.total || String(a.label).localeCompare(String(b.label)));
190
+ return capRows(rows, topN, { stacked: true, t });
191
+ }
192
+
126
193
  /** Chart 2 — sub-dep CVEs grouped by their ROOT (direct) dep, by severity.
127
194
  * Counts CVEs (a sub-dep with 3 CVEs contributes 3), each in its own bucket. */
128
195
  function vulnSubdepsByDep(prodMatches, { topN = 7, t = EN_T } = {}) {
@@ -214,12 +281,16 @@ const MAJOR_SEVERITIES = new Set(["critical", "high"]);
214
281
  * @param {Map<string,string>} moduleNames absolute descriptor path → label (lib/module-names.js)
215
282
  */
216
283
  function mostVulnerableComponents(prodMatches, moduleNames, { topN = 7, t = EN_T } = {}) {
217
- const by = new Map();
284
+ const by = new Map(), seen = new Map();
218
285
  for (const m of prodMatches || []) {
219
286
  const sev = sevKey(m);
220
287
  if (!MAJOR_SEVERITIES.has(sev)) continue;
221
288
  for (const file of (m.dep && m.dep.manifestPaths) || []) {
222
289
  if (!file) continue;
290
+ if (!seen.has(file)) seen.set(file, new Set());
291
+ const identity = m.findingId || m;
292
+ if (seen.get(file).has(identity)) continue;
293
+ seen.get(file).add(identity);
223
294
  let e = by.get(file);
224
295
  if (!e) { e = { segments: emptySeg(), total: 0 }; by.set(file, e); }
225
296
  e.segments[sev]++; e.total++;
@@ -249,11 +320,16 @@ function mostVulnerableComponents(prodMatches, moduleNames, { topN = 7, t = EN_T
249
320
  function mostVulnerableApplications(prodMatches, applications = [], coverage = [], { topN = 7, t = EN_T } = {}) {
250
321
  const by = new Map();
251
322
  const unique = new Set();
323
+ const seen = new Map();
252
324
  for (const m of prodMatches || []) {
253
325
  const sev = sevKey(m);
254
326
  if (!MAJOR_SEVERITIES.has(sev)) continue;
255
327
  for (const appId of m.applicationIds || []) {
256
- unique.add(m.findingId || `${m.cve && m.cve.id}|${coordKeyOf(m.dep || {})}|${m.dep && m.dep.version}`);
328
+ const identity = m.findingId || m;
329
+ unique.add(identity);
330
+ if (!seen.has(appId)) seen.set(appId, new Set());
331
+ if (seen.get(appId).has(identity)) continue;
332
+ seen.get(appId).add(identity);
257
333
  let e = by.get(appId);
258
334
  if (!e) { e = { segments: emptySeg(), total: 0 }; by.set(appId, e); }
259
335
  e.segments[sev]++; e.total++;
@@ -374,7 +450,18 @@ function donutChart({ slices, width = 250, note, centerValue, t = EN_T }) {
374
450
  parts.push(`<text x="11" y="${ly}" ${FONT} font-size="7.5" fill="#4b5563">${esc(legendTxt(s))}</text>`);
375
451
  ly += 11;
376
452
  }
377
- if (note) { parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(note)}</text>`); ly += 11; }
453
+ if (note) {
454
+ const limit = Math.max(16, Math.floor(width / 4));
455
+ let line = '';
456
+ for (const word of String(note).split(/\s+/)) {
457
+ if (line && `${line} ${word}`.length > limit) {
458
+ parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(line)}</text>`);
459
+ ly += 11; line = '';
460
+ }
461
+ line += (line ? ' ' : '') + word;
462
+ }
463
+ if (line) { parts.push(`<text x="0" y="${ly}" ${FONT} font-size="7" font-style="italic" fill="#9ca3af">${esc(line)}</text>`); ly += 11; }
464
+ }
378
465
  return { body: parts.join(""), width, height: ly + 2 };
379
466
  }
380
467
 
@@ -402,36 +489,39 @@ function renderCharts(payload = {}, opts = {}) {
402
489
  // by default, which keeps every existing caller and test rendering English.
403
490
  const t = typeof opts.t === "function" ? opts.t : EN_T;
404
491
  const prod = payload.prodMatches || [];
492
+ const imageMatches = prod.filter(m => !!m.dep?.artifactTargetId);
493
+ const sourceMatches = prod.filter(m => !m.dep?.artifactTargetId);
494
+ const hasImages = imageMatches.length > 0 || (payload.artifacts || []).length > 0;
495
+ const imageOnly = hasImages && !sourceMatches.length;
405
496
  const cweTitle = typeof opts.cweName === "function" ? opts.cweName : cweName;
406
- // Application scans announce their own axis (plan §6.3): chart 1 carries the CWEs of
407
- // the DIRECT application findings (core/framework/components/extensions), chart 2 the
408
- // indirect CVEs grouped by their introducing component. Package-manager scope and
409
- // non-application findings are never silently mixed into these lanes.
497
+ // Include direct application and source findings, plus image findings, in the
498
+ // CWE distribution; the component chart includes all production findings.
410
499
  const applications = payload.applications || [];
411
500
  const appScan = applications.length > 0;
412
- const cwe = appScan
413
- ? cweByCriticality(prod.filter(m => m.applicationRelation === "direct"), { t, cweTitle })
414
- : cweByCriticality(prod, { t, cweTitle });
415
- const origins = appScan ? vulnByApplicationOrigin(prod, payload.applicationInventory || [], { t }) : null;
416
- const subs = appScan ? origins.rows : vulnSubdepsByDep(prod, { t });
417
- const unattr = appScan ? origins.unknown : unattributedSubdeps(prod);
418
- const scope = directVsTransitive(prod, t);
501
+ const cweInput = appScan ? sourceMatches.filter(m => m.applicationRelation === "direct" || (!m.applicationIds?.length && m.dep?.scope !== 'transitive')).concat(imageMatches)
502
+ : sourceMatches.filter(m => m.dep?.scope !== 'transitive').concat(imageMatches);
503
+ const cwe = cweByCriticality(cweInput, { t, cweTitle, includeTransitive: hasImages });
504
+ const subs = findingsByComponent(prod, { artifacts: payload.artifacts || [], applications, moduleNames: payload.moduleNames instanceof Map ? payload.moduleNames : new Map(), t });
505
+ const unattr = 0;
506
+ const scope = directVsTransitive(sourceMatches, t);
419
507
  const prio = fixPriority(prod, t);
420
508
  // On a multi-module tree, "which of my modules is worst" is actionable; the direct vs
421
509
  // transitive split is not module-specific and keeps its slot on a single-descriptor scan,
422
510
  // where ranking one component against itself would say nothing.
423
511
  const moduleNames = payload.moduleNames instanceof Map ? payload.moduleNames : new Map();
424
512
  const multiModule = (Number(payload.descriptorCount) || 0) > 1;
425
- const components = multiModule ? mostVulnerableComponents(prod, moduleNames, { t }) : [];
513
+ const components = multiModule ? mostVulnerableComponents(sourceMatches, moduleNames, { t }) : [];
426
514
  // Application scans rank exposed instances instead of modules (plan §6.4): plugins,
427
515
  // themes and extensions count as the direct lane, their dependencies as indirect.
428
- const appChart = appScan ? mostVulnerableApplications(prod, applications, payload.coverage || [], { t }) : null;
516
+ const appChart = appScan ? mostVulnerableApplications(sourceMatches, applications, payload.coverage || [], { t }) : null;
429
517
 
430
518
  if (!(cwe.length || subs.length || scope.length || prio.length || unattr || components.length || (appChart && appChart.rows.length))) return "";
431
519
 
432
520
  const interactive = opts.interactive !== false; // copy button only in the interactive HTML
433
521
 
434
- const cweSlices = colorizeCategories(cwe.map(r => ({ key: r.key, label: r.key, name: r.name,
522
+ const imageSeverity = SEV_SERIES.map(s => ({ ...s, label:t(s.label), value:imageMatches.filter(m => sevKey(m) === s.key).length })).filter(s => s.value);
523
+ const moduleUnique = new Set(sourceMatches.filter(m => MAJOR_SEVERITIES.has(sevKey(m)) && (m.dep?.manifestPaths || []).some(Boolean)).map(m => m.findingId || m)).size;
524
+ const cweSlices = colorizeCategories(cwe.map(r => ({ key: r.key, label: r.more ? r.label : r.key, name: r.name,
435
525
  value: r.total, segments: r.segments, more: r.more })));
436
526
  const subSlices = colorizeCategories(subs.map(r => ({ key: r.key, label: r.label,
437
527
  value: r.total, segments: r.segments, more: r.more })));
@@ -442,22 +532,22 @@ function renderCharts(payload = {}, opts = {}) {
442
532
 
443
533
  // Share one viewBox width so the four donuts remain aligned.
444
534
  const W = Math.max(250, legendBoxWidth(cweSlices), legendBoxWidth(subSlices, note2),
445
- legendBoxWidth(appChart ? appChart.rows : multiModule ? components : scope), legendBoxWidth(prio));
535
+ legendBoxWidth(imageOnly ? imageSeverity : appChart ? appChart.rows : multiModule ? components : scope), legendBoxWidth(prio));
446
536
 
447
- const card1 = cwe.length
448
- ? chartCard({ t, id: "chart-cwe", title: t("CWE — direct vulns (by criticality)"), interactive,
537
+ const cweHeading = hasImages ? t("CWE — findings (by severity)") : t("CWE — direct vulns (by criticality)");
538
+ const card1 = cwe.length
539
+ ? chartCard({ t, id: "chart-cwe", title: cweHeading, interactive,
449
540
  ...donutChart({ slices: cweSlices, width: W, t }) })
450
- : emptyCard("chart-cwe", t("CWE — direct vulns (by criticality)"), t("No categorised direct CVE."));
541
+ : emptyCard("chart-cwe", cweHeading, hasImages ? t("No categorised finding.") : t("No categorised direct CVE."));
451
542
 
452
543
  const card2 = (subs.length || unattr)
453
544
  ? chartCard({ t, id: "chart-subdeps",
454
- title: appScan ? t("Indirect CVEs per direct dependency") : t("Sub-dep CVEs per dependency"),
545
+ title: t("Findings per component"),
455
546
  interactive, ...donutChart({ slices: subSlices, width: W, note: note2, t }) })
456
547
  : emptyCard("chart-subdeps",
457
- appScan ? t("Indirect CVEs per direct dependency") : t("Sub-dep CVEs per dependency"),
458
- appScan ? t("No indirect application CVE.") : t("No vulnerable transitive deps."));
548
+ t("Findings per component"), t("No production CVE."));
459
549
 
460
- const card3 = appChart
550
+ const card3 = imageOnly ? (imageSeverity.length ? chartCard({ t, id: 'chart-image-severity', title:t('Findings by severity'), interactive, ...donutChart({slices:imageSeverity,width:W,t}) }) : emptyCard('chart-image-severity',t('Findings by severity'),t('No production CVE.'))) : appChart
461
551
  ? (appChart.rows.length
462
552
  ? chartCard({ t, id: "chart-instances", title: t("Most vulnerable instances"), interactive,
463
553
  ...donutChart({ slices: appChart.rows, width: W, centerValue: appChart.unique, t,
@@ -466,8 +556,8 @@ function renderCharts(payload = {}, opts = {}) {
466
556
  : emptyCard("chart-instances", t("Most vulnerable instances"), t("No critical or high application CVE.")))
467
557
  : multiModule
468
558
  ? (components.length
469
- ? chartCard({ t, id: "chart-components", title: t("Most vulnerable components"), interactive, ...donutChart({ slices: components, width: W, t }) })
470
- : emptyCard("chart-components", t("Most vulnerable components"), t("No critical or high production CVE.")))
559
+ ? chartCard({ t, id: "chart-components", title: t("Most vulnerable components"), interactive, ...donutChart({ slices: components, width: W, centerValue: moduleUnique, note:t('Shared findings count once per affected module.'), t }) })
560
+ : emptyCard("chart-components", t("Most vulnerable components"), t("No critical or high production findings attributed to a project descriptor.")))
471
561
  : (scope.length
472
562
  ? chartCard({ t, id: "chart-scope", title: t("Direct vs transitive (by severity)"), interactive, ...donutChart({ slices: scope, width: W, t }) })
473
563
  : emptyCard("chart-scope", t("Direct vs transitive (by severity)"), t("No production CVE.")));
@@ -481,6 +571,8 @@ function renderCharts(payload = {}, opts = {}) {
481
571
 
482
572
  module.exports = {
483
573
  cweByCriticality,
574
+ findingsByImage,
575
+ findingsByComponent,
484
576
  vulnSubdepsByDep,
485
577
  unattributedSubdeps,
486
578
  directVsTransitive,
@@ -3,15 +3,14 @@
3
3
  const COMMAND_HELP = `
4
4
  Commands:
5
5
  scan <dir> [options] scan a source tree (alias of -s <dir>)
6
+ image <archive|rootfs> [options] scan an image natively; image --help
6
7
  setup configure sources and proxy
7
- watch <dir> --name <name> collect and upload a project
8
- watch <dir> --id <id> update an explicitly selected project
8
+ watch <dir> --name <name>|--id <id> collect and upload a project
9
9
  watch <dir> --export <file> export descriptor locally
10
10
  login | logout | whoami aliases of auth login | logout | status
11
11
  config show show masked configuration
12
12
  cache export|import <file> transfer the complete local cache
13
- cache prepare <descriptor> --output <file> prepare a project archive online
14
-
13
+ cache prepare <descriptor|inventory> --output <file> prepare an offline archive online
15
14
  watch --help: privacy, safe updates; free account: 1 project,
16
15
  100 distinct direct coordinates (versions count once). Legacy commands remain supported.`;
17
16
 
@@ -37,11 +36,26 @@ function routeArguments(input) {
37
36
  }
38
37
  if (command === 'cache') {
39
38
  if (args.length === 1 || args.some(a => a === '--help' || a === '-h'))
40
- return { help: 'Usage: vigievuln cache prepare <descriptor.json> --output <archive.tar.gz> [source options]\n vigievuln cache export <file> [--verbose] [source options]\n vigievuln cache import <file> [--replace] [--force] [--verbose] [source options]\nPrepare warms the descriptor and writes a project archive in one invocation. Export copies the complete local cache.' };
39
+ return { help: 'Usage: vigievuln cache prepare <descriptor-or-inventory.json> --output <archive.tar.gz> [source options]\n vigievuln cache export <file> [--verbose] [source options]\n vigievuln cache import <file> [--replace] [--force] [--verbose] [source options]\nPrepare warms the source descriptor or artifact inventory and writes an offline archive. Export copies the complete local cache.' };
41
40
  const [, operation, file, ...rest] = args;
42
41
  if (operation === 'prepare') {
43
42
  if (!file || file.startsWith('-')) throw new Error('usage: vigievuln cache prepare <descriptor.json> --output <archive.tar.gz>');
44
43
  if (rest.some(a=>/^--(?:export-cache|import-cache|prepare-offline|import-anonymized)(?:=|$)/.test(a))) throw new Error('cache prepare cannot be combined with another cache or descriptor command');
44
+ let artifact=false;
45
+ try {
46
+ const fs=require('node:fs'),stat=fs.statSync(file);
47
+ if(stat.isFile() && stat.size<=128*1024*1024)artifact=JSON.parse(fs.readFileSync(file,'utf8'))?.schema==='vigievuln-artifact-inventory/1';
48
+ } catch { /* Descriptor parsing reports invalid inputs in the regular path. */ }
49
+ if(artifact){
50
+ const args=[],outputs=[];
51
+ for(let i=0;i<rest.length;i++){
52
+ if(rest[i]==='--output'){if(!rest[i+1]||rest[i+1].startsWith('-'))throw Error('--output requires a value');outputs.push(rest[++i]);}
53
+ else if(rest[i].startsWith('--output='))outputs.push(rest[i].slice('--output='.length));
54
+ else args.push(rest[i]);
55
+ }
56
+ if(outputs.length!==1 || !outputs[0])throw Error('cache prepare requires exactly one --output');
57
+ return {args:['image','--inventory',file,'--no-report','--prepare-cache',outputs[0],...args]};
58
+ }
45
59
  return {args:['--prepare-offline',file,...rest]};
46
60
  }
47
61
  if (!['export', 'import'].includes(operation) || !file || file.startsWith('-'))
@@ -50,7 +64,7 @@ function routeArguments(input) {
50
64
  for (let i = 0; i < rest.length; i++) {
51
65
  const arg = rest[i];
52
66
  if (allowed.includes(arg)) continue;
53
- const match = /^(--config|--source-profile|--proxy-cache)(?:=(.*))?$/.exec(arg);
67
+ const match = /^(--config|--source-profile|--proxy-cache|--cache-dir)(?:=(.*))?$/.exec(arg);
54
68
  if (match) {
55
69
  const value = match[2] === undefined ? rest[++i] : match[2];
56
70
  if (!value || value.startsWith('-')) throw new Error(`${match[1]} requires a value`);
package/lib/cli-groups.js CHANGED
@@ -22,12 +22,13 @@ const DISABLE = {
22
22
  retire: "retire", "vendored-js-inventory": "vendoredJsInventory",
23
23
  maven: "maven", gradle: "gradle", npm: "npm", yarn: "yarn", nuget: "nuget",
24
24
  composer: "composer", pypi: "pypi", go: "go", ruby: "ruby",
25
- binaries: "binaries", jars: "jars", certs: "certs", js: "js",
25
+ binaries: "binaries", jars: "jars", certs: "certs", js: "js", images: "images",
26
26
  "default-excludes": "defaultExcludes",
27
27
  };
28
28
 
29
29
  /** Token → option key, for things that are OFF unless asked for. */
30
30
  const ACTIVATE = {
31
+ images: "images",
31
32
  licenses: "licenses", "eol-support": "eolSupport", typosquat: "typosquat", snyk: "snyk",
32
33
  "osv-db": "osvDb", "nvd-cpe-match": "nvdCpeMatch", "cve-refresh": "cveRefresh",
33
34
  "osv-db-refresh": "osvDbRefresh", "retire-refresh": "retireRefresh", "cve-offline": "cveOffline", "gcve-offline": "gcveOffline",