vigievuln 1.4.0 → 1.4.2

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,6 +1,20 @@
1
1
  # Release notes — VigieVuln
2
2
 
3
- ## Unreleased
3
+ ## [1.4.2] — 2026-12-02
4
+
5
+ - Export in a prepared archive (`cache prepare <descriptor|inventory>`) only what the preparation read or wrote: the advisories and CVE records of the packages it looked up, their NVD records, the Maven POMs, publisher advisories and registry answers it used. The archive carried the generic cache of every scan made on the machine (POMs, CMS plugin advisories, Composer package names, system trackers and registry lookups of other projects), the complete CVEProject corpus as soon as the descriptor held a CMS instance, a binary or an image, and the complete local cache for a system inventory or a descriptor without package coordinates. On a machine with a 2.9 GB cache, the archive of a 23-dependency project goes from 60 MB to 9 MB, that of a WordPress instance from 640 MB to 7 MB and that of an Alpine image inventory to 9 MB, with the same offline findings.
6
+ - Carry the retire.js signatures in every prepared project archive: a descriptor without an npm manifest left them out unless an earlier scan had cached them, while the offline scan looks for vendored JavaScript in any tree.
7
+ - Carry in the archive the CVE records named by the publisher advisories warmed for a CMS instance, with the NVD, EPSS, KEV, EUVD and CERT-FR data the cache holds for them.
8
+ - Stop consulting the advisory store for packages the scan does not hold while matching CVEProject records (5 767 lookups for a one-package project).
9
+ - Put the vulnerabilities of a host's interpreters, applications and services under their own collapsible heading, with their count of distinct advisories: the findings table followed the inventory table without a separation.
10
+
11
+ ## [1.4.1] — 2026-11-29
12
+
13
+ - Remove the `fad-checker` and `fad` command aliases from the package: the command is `vigievuln`. A script that still calls an alias must be updated. The `fad-checker.js` entry file stays in the package.
14
+ - Read a CERT-FR advisory again when its listing shows another title, and once a day the alerts revised in the last 30 days: CERT-FR edits a recent alert in place (a CVE added, "[MàJ]" before the title) without a new revision, so the index kept the first version and the CVE was never linked to the alert.
15
+ - Wrap long legend entries in the report charts: one entry naming several modules ("Shared: …") shrank the four charts of the summary row.
16
+
17
+ ## [1.4.0] — 2026-11-28
4
18
 
5
19
  - Close every HTML and Word report on a disclaimer, in the report language, and carry it in `findings.json` (`disclaimer`): an automated aid built from public data that may be incomplete or wrong, provided as is, without liability.
6
20
  - Scan only the container images a project declares with `vigievuln scan <path> --images-only`: the report goes to `./vigievuln-report-images`, apart from the dependency report of a scan without the option.
@@ -12,9 +26,6 @@
12
26
  - Count the reviewed VigieVuln advisories as a consulted source when OSV is disabled: a proxied scan run with `--no-osv` was cancelled as unassessed although they had answered.
13
27
  - Treat a consultation made during the run as current under `--advisory-query-ttl 0`: the reviewed advisories just fetched were reported stale and not counted.
14
28
  - Correct the `watch` help and the usage guide, which still named the removed `-s` option.
15
-
16
- ## [1.4.0] — 2026-11-28
17
-
18
29
  - Assess Wolfi and Chainguard OS systems from the security database of their package repositories.
19
30
  - Assess Red Hat Enterprise Linux and UBI, CentOS Linux, Oracle Linux, SUSE Linux Enterprise, openSUSE Leap and Tumbleweed, Azure Linux and CBL-Mariner, Mageia and openEuler systems from their `os-release` identity, without any advisory configuration. On a Red Hat UBI 8.6 image every fixed advisory reported by Trivy (567) and Grype (587) is found.
20
31
  - Report the vulnerabilities Red Hat states are present without a fix (affected, fix deferred, will not fix, out of support scope), from its OVAL data, for Red Hat Enterprise Linux 6 to 9 and the distributions rebuilt from it; one finding per source package names the packages concerned. Use Red Hat errata as a second source for AlmaLinux and Rocky Linux, whose own errata miss updates: on a Rocky Linux 8.6 image, 2 700 of the 2 705 fixed advisories reported by Grype are found (1 910 before) and 4 539 of its 4 593 unfixed ones.
package/README.md CHANGED
@@ -10,14 +10,14 @@
10
10
  [![CI](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml/badge.svg)](https://github.com/9pings/VigieVuln/actions/workflows/ci.yml)
11
11
 
12
12
 
13
- **VigieVuln 1.4.0** is a polyglot dependency auditor for code audits.
13
+ **VigieVuln** is a fully autonomous polyglot CVE scanner built for professional audits: audit them all, no build, backed by evidence.
14
14
 
15
15
  It scans dependencies of **10 ecosystems + 11 CMS/frameworks + systems/dockers images** in one pass without build tools, supports **air-gapped** workflows, detects private packages, binaries and certificates, and produces HTML, JSON and other reports.
16
16
 
17
17
 
18
18
  🌐 **[Project site & docs →](https://9pings.github.io/VigieVuln/)**
19
19
 
20
- *Terminal demo recorded with VigieVuln 1.2.1.*
20
+ *Terminal demo recorded with VigieVuln 1.4.0.*
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
 
@@ -158,7 +158,7 @@ VigieVuln inventories the **instance**: core, plugins, themes, bundles and frame
158
158
  | **PrestaShop** | core (`_PS_VERSION_`), modules, themes | the publisher's **GitHub security-advisories** feed |
159
159
  | **TYPO3** | core, extensions | the publisher's **GitHub security-advisories** feed |
160
160
  | **SPIP** | core (`$spip_version_branche` in `ecrire/inc_version.php`), dist plugins (`paquet.xml`), user plugins (`paquet.xml`/legacy `plugin.xml`) | **NVD product CVEs** (`cpe:2.3:a:spip:spip`) — the only machine-readable SPIP source; plugins stay honestly not-qualified |
161
- | **Joomla / Magento (Adobe Commerce)** | core, extensions/modules, themes | no machine-readable publisher feed exists; components locked as Composer packages read as covered by the **dependency lanes**, the rest stays honestly **not qualified**. A Magento source distribution reports its exact version from the root `composer.json` |
161
+ | **Joomla / Magento (Adobe Commerce)** | core, extensions/modules, themes | no publisher feed gives identifiers and version ranges a scanner can match (Joomla's JSON list of vulnerable extensions names them in free text); components locked as Composer packages read as covered by the **dependency lanes**, the rest stays honestly **not qualified**. A Magento source distribution reports its exact version from the root `composer.json` |
162
162
 
163
163
  Private/custom components are inventoried separately and never sent to any publisher. → **[the dedicated guide](docs/CMS-FRAMEWORKS.md)** · [application usage](docs/USAGE.md#application-inventory-experimental)
164
164
 
@@ -192,10 +192,11 @@ Review the descriptor before sharing and the report's coverage and freshness inf
192
192
 
193
193
  ### Interactive HTML samples
194
194
 
195
- - **[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.
196
- - **[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.
195
+ - **[Apache Dubbo 2.7.8 — open the report](https://9pings.github.io/VigieVuln/samples/dubbo.html)**: the project used for the report screenshot below; 105 Maven descriptors, 400 dependencies, direct/transitive CVEs, KEV matches, EOL and fix recommendations.
196
+ - **[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), every ecosystem assessed, with findings attributed to each instance.
197
+ - **[Traefik v2.11.0 image](https://9pings.github.io/VigieVuln/samples/traefik-image.html)** and **[NGINX 1.24.0 image](https://9pings.github.io/VigieVuln/samples/nginx-image.html)**: container images acquired from the registry and inventoried without being run (Alpine and Debian packages, Go modules of the binary).
197
198
 
198
- 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).
199
+ These are standalone reports from real scans, generated on **2026-11-29** with VigieVuln **1.4.0**, online against the public sources. Three of them are published marked incomplete, with each gap listed in chapter 0 (manifests without a lockfile, distributions out of support). [Sample scope, sources and reproduction commands](docs/samples/README.md).
199
200
 
200
201
  ### Resolution and coverage
201
202
 
@@ -37,4 +37,4 @@ _fad_check_complete() {
37
37
  return 0
38
38
  fi
39
39
  }
40
- complete -F _fad_check_complete vigievuln fad-checker fad
40
+ complete -F _fad_check_complete vigievuln
@@ -1,4 +1,4 @@
1
- #compdef vigievuln fad-checker fad
1
+ #compdef vigievuln
2
2
  # Zsh completion for vigievuln (VigieVuln — autonomous dependency auditor)
3
3
  _fad_check() {
4
4
  if (( CURRENT == 2 )); then
@@ -103,7 +103,8 @@ function loadRecords(store,sources){
103
103
  if(!store?.db?.prepare || typeof store.getRecord!=='function')return [];
104
104
  const sql=`SELECT source,id FROM advisory_records WHERE source IN (${sources.map(()=>'?').join(',')}) ORDER BY source,id`;
105
105
  const stmt=store.db.prepare(sql),rows=typeof stmt.iterate==='function'?stmt.iterate(...sources):stmt.all(...sources);
106
- return (function*(){for(const row of rows){const rec=store.getRecord(row.source,row.id);if(rec)yield rec;}})();
106
+ const read=typeof store.peekRecord==='function'?store.peekRecord.bind(store):store.getRecord.bind(store);
107
+ return (function*(){for(const row of rows){const rec=read(row.source,row.id);if(rec)yield rec;}})();
107
108
  }
108
109
  function matchNativePackages(deps,store,opts={}){
109
110
  const sources=(opts.sources||['cveproject','gcve']).filter(x=>['cveproject','gcve'].includes(x));
@@ -133,6 +134,8 @@ function matchNativePackages(deps,store,opts={}){
133
134
  for(const container of cs)for(const a of (Array.isArray(container.affected)?container.affected:[])){
134
135
  const p=explicitNativePackage(a,{source:rec.source,record:raw,container,cnaIdentities:opts.cnaIdentities});if(!p)continue;
135
136
  const candidates=wanted.get(JSON.stringify([p.ecosystem,packageName(p.ecosystem,p.name)]))||[];
137
+ // A package the scan does not hold has no verdict to give: do not consult the store for it.
138
+ if(!candidates.length)continue;
136
139
  const consultation=rec.source==='cveproject' && typeof store.getQuery==='function' ? store.getQuery({source:'cveproject',ecosystem:p.ecosystem,name:p.name,version:'*'},{ttlMs:Number.MAX_SAFE_INTEGER}) : null;
137
140
  if(consultation && consultation.provenance?.stale!==true && consultation.fetchedAt >= (rec.contentChangedAt||rec.fetchedAt) && !consultation.ids.includes(rec.id))continue;
138
141
  for(const dep of candidates){
@@ -14,7 +14,10 @@ class SqliteAdvisoryStore {
14
14
  constructor({cacheDir=require('../cache/directory').getCacheDir()}={}){
15
15
  this.cacheDir=cacheDir;
16
16
  this.db=openCacheDb({cacheDir});
17
+ // Packages and records this process looked up: a project archive exports them.
18
+ this.access=require('../cache/access-log').accessLog(cacheDir);
17
19
  }
20
+ _notePackage(ecosystem,packageKey,queryKey){require('../cache/access-log').note(this.access.packages,ecosystem,JSON.stringify([packageKey,queryKey]))}
18
21
  close(){this.db.close()}
19
22
  _rowRecord(source,id){return this.db.prepare('SELECT * FROM advisory_records WHERE source=? AND id=?').get(source,id)||null}
20
23
  _record(source,id){
@@ -86,10 +89,13 @@ class SqliteAdvisoryStore {
86
89
  this._commit(transaction);
87
90
  });
88
91
  }
89
- getRecord(source,id){return this._record(source,id)}
92
+ getRecord(source,id){require('../cache/access-log').note(this.access.records,source,id);return this._record(source,id)}
93
+ // Reads a record without listing it for a project archive: for a pass over the whole store.
94
+ peekRecord(source,id){return this._record(source,id)}
90
95
  getQuery(tuple,{now=Date.now(),ttlMs=DEFAULT_QUERY_TTL_MS}={}){
91
96
  if(!Number.isFinite(ttlMs)||ttlMs<0)throw Error('invalid advisory query TTL');
92
97
  const source=tuple.source||'osv',ecosystem=tuple.ecosystem,nameKey=ecosystem==='Maven'?tuple.name:packageName(ecosystem,tuple.name);
98
+ this._notePackage(ecosystem,packageName(ecosystem,tuple.name),nameKey);
93
99
  const row=this.db.prepare('SELECT * FROM advisory_queries WHERE source=? AND ecosystem=? AND name_key=? AND version=?').get(source,ecosystem,nameKey,tuple.version);
94
100
  if(!row)return null;
95
101
  const ids=this.db.prepare('SELECT id FROM advisory_query_ids WHERE source=? AND ecosystem=? AND name_key=? AND version=? ORDER BY ordinal').all(source,ecosystem,nameKey,tuple.version).map(x=>x.id);
@@ -119,6 +125,7 @@ class SqliteAdvisoryStore {
119
125
  }
120
126
  getPackageRecords(ecosystem,name,{source='osv',includeWithdrawn=false}={}){
121
127
  const pkgName=packageName(ecosystem,name);
128
+ this._notePackage(ecosystem,pkgName,ecosystem==='Maven'?name:pkgName);
122
129
  const rows=source==null
123
130
  ? this.db.prepare('SELECT source,id FROM advisory_packages WHERE ecosystem=? AND name_key=? ORDER BY source,id').all(ecosystem,pkgName)
124
131
  : this.db.prepare('SELECT source,id FROM advisory_packages WHERE ecosystem=? AND name_key=? AND source=? ORDER BY id').all(ecosystem,pkgName,source);
@@ -192,8 +192,11 @@ function buildSystemSections({projectInfo, matches, locale, systemIds, warnings,
192
192
  const intro = table([t('Host information','Informations sur l’hôte'),t('Value','Valeur')],metadata.map(([k,v])=>[esc(k),code(v)]));
193
193
  const hostGroup = (title,body) => minorSection(esc(title),body,{level:4});
194
194
  hostFindings.push(...runtime.findings,...hostDeps);
195
+ // The findings follow the inventory under their own collapsible heading, as the system dependencies do.
196
+ const runtimeFindings = runtime.findings.length ? minorSection(esc(t('Vulnerabilities of these components (direct)','Vulnérabilités de ces composants (directes)'))+
197
+ ' ('+advisories(runtime.findings)+' '+t('distinct advisories','avis distincts')+')',matchTable(runtime.findings,direct),{level:4}) : '';
195
198
  hosts.push(sub(intro+hostGroup(t('Interpreters, applications and services','Interpréteurs, applications et services'),
196
- inventoryTable(runtime.components,true)+matchTable(runtime.findings,direct) || '<p>'+t('None identified.','Aucun identifié.')+'</p>')+
199
+ inventoryTable(runtime.components,true)+runtimeFindings || '<p>'+t('None identified.','Aucun identifié.')+'</p>')+
197
200
  hostGroup(t('System dependencies (transitive)','Dépendances du système (transitives)'),matchTable(hostDeps,transitive) ||
198
201
  '<p>'+t('No vulnerability identified in host dependencies.','Aucune vulnérabilité identifiée dans les dépendances du système.')+'</p>')));
199
202
  const coverage = target.coverage || [];
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ // What this process read or wrote in a cache database: generic entries and snapshots,
4
+ // the keys used inside the shared registry maps, advisory packages and records, NVD records. A project archive exports these with the
5
+ // advisories of its packages and nothing else (airgap-project.js): what another scan
6
+ // left on the machine does not travel with it.
7
+ const path=require('node:path');
8
+
9
+ const logs=new Map();
10
+ function accessLog(cacheDir=require('./directory').getCacheDir()){
11
+ const root=path.resolve(cacheDir);
12
+ let log=logs.get(root);
13
+ if(!log){log={entries:new Map(),snapshots:new Set(),maps:new Map(),packages:new Map(),records:new Map(),cves:new Set()};logs.set(root,log)}
14
+ return log;
15
+ }
16
+ const note=(map,group,value)=>{let set=map.get(group);if(!set)map.set(group,set=new Set());set.add(String(value))};
17
+ const isEmpty=log=>!log.entries.size&&!log.snapshots.size&&!log.packages.size&&!log.records.size&&!log.cves.size;
18
+
19
+ module.exports={accessLog,note,isEmpty};
@@ -7,7 +7,7 @@ const {openCacheDb}=require('./db');
7
7
  const {packageName}=require('../advisories/store');
8
8
  const packageScope=(ecosystem,name)=>'project-package:'+JSON.stringify([ecosystem,ecosystem==='Maven'?name:packageName(ecosystem,name)]);
9
9
 
10
- function buildProjectScope(resolved,{applications=[],cves=[],imageReferences=[],images=true,preferSbom=false}={}){
10
+ function buildProjectScope(resolved,{cves=[],imageReferences=[],images=true,preferSbom=false}={}){
11
11
  const refs=require("../inventory/deps-descriptor").serializeImageReferences(imageReferences,{images});
12
12
  const {osvEcosystemFor,osvPkgName}=require('../providers/osv/query');
13
13
  const packages=new Map();
@@ -17,7 +17,7 @@ function buildProjectScope(resolved,{applications=[],cves=[],imageReferences=[],
17
17
  if(typeof name!=='string'||!name||name.includes('undefined'))continue;
18
18
  packages.set(JSON.stringify([ecosystem,name]),{ecosystem,name});
19
19
  }
20
- const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],imageReferences:refs,imagePreferSbom:!!preferSbom,retainAllNvd:refs.length>0||applications.length>0||[...resolved.values()].some(d=>d.provenance==='binary'||d.ecosystem==='binary')};
20
+ const project={schema:1,packages:[...packages.values()],cves:[...new Set(cves.filter(id=>/^CVE-\d{4}-\d{4,7}$/.test(id||'')))],imageReferences:refs,imagePreferSbom:!!preferSbom};
21
21
  return project;
22
22
  }
23
23
 
@@ -39,8 +39,8 @@ function validateImageSnapshotCompleteness(scope,repository){
39
39
  return {images:refs.length};
40
40
  }
41
41
 
42
- function buildProjectSnapshot(sourceDir,targetDir,project){
43
- if(project?.schema!==1||!Array.isArray(project.packages)||(!project.packages.length && !project.imageReferences?.length))throw Error('invalid or empty prepared project scope');
42
+ function buildProjectSnapshot(sourceDir,targetDir,project,accessed=require('./access-log').accessLog(sourceDir)){
43
+ if(project?.schema!==1||!Array.isArray(project.packages)||(!project.packages.length && !project.imageReferences?.length && require('./access-log').isEmpty(accessed)))throw Error('invalid or empty prepared project scope');
44
44
  const imageRefs=require('../inventory/deps-descriptor').serializeImageReferences(project.imageReferences);
45
45
  if(project.imageReferences?.length && imageRefs.length!==project.imageReferences.length)throw Error('invalid prepared image reference');
46
46
  if(imageRefs.length)validateImageSnapshotCompleteness(project,require('./repository').createCacheRepository(sourceDir));
@@ -51,14 +51,30 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
51
51
  // Pin one source snapshot while collecting identities and copying records.
52
52
  db.exec('BEGIN');
53
53
  db.exec('CREATE TEMP TABLE wanted_packages(ecosystem TEXT, package_key TEXT, query_key TEXT, PRIMARY KEY(ecosystem,query_key)) WITHOUT ROWID; CREATE TEMP TABLE wanted_advisories(source TEXT,id TEXT,PRIMARY KEY(source,id)) WITHOUT ROWID; CREATE TEMP TABLE wanted_cves(cve TEXT PRIMARY KEY) WITHOUT ROWID;');
54
+ // The cache holds what every scan of this machine fetched: POMs, publisher advisories,
55
+ // system trackers, CVE records. Beside the advisories of the project packages, only
56
+ // what the preparation read or wrote is exported. A namespace described by a snapshot
57
+ // is one dataset: it is exported whole, so the snapshot stays true.
58
+ db.exec(`CREATE TEMP TABLE wanted_entries(namespace TEXT,key TEXT,PRIMARY KEY(namespace,key)) WITHOUT ROWID; CREATE TEMP TABLE wanted_snapshots(namespace TEXT PRIMARY KEY) WITHOUT ROWID;`);
59
+ const addEntry=db.prepare('INSERT OR IGNORE INTO wanted_entries VALUES(?,?)'),addSnapshot=db.prepare('INSERT OR IGNORE INTO wanted_snapshots VALUES(?)');
60
+ for(const [namespace,keys] of accessed.entries)for(const key of keys)addEntry.run(namespace,key);
61
+ for(const namespace of accessed.snapshots)addSnapshot.run(namespace);
62
+ db.exec('INSERT OR IGNORE INTO wanted_entries SELECT e.namespace,e.key FROM source.cache_entries e JOIN wanted_snapshots s ON s.namespace=e.namespace');
63
+ // The GCVE index describes the GCVE records, which are exported whole.
64
+ addEntry.run('catalogue','gcve');
54
65
  const add=db.prepare('INSERT OR IGNORE INTO wanted_packages VALUES(?,?,?)');
55
66
  for(const p of project.packages){if(!p||typeof p.ecosystem!=='string'||typeof p.name!=='string'||!p.name)throw Error('invalid project package');add.run(p.ecosystem,packageName(p.ecosystem,p.name),p.ecosystem==='Maven'?p.name:packageName(p.ecosystem,p.name));}
67
+ // A package the preparation looked up without the descriptor listing it (a system
68
+ // package, the module of an identified binary, an artifact found in an image) is
69
+ // exported like a project package. Product names are looked up for Maven artifacts only.
70
+ for(const [ecosystem,keys] of accessed.packages)if(ecosystem!=='CVEProduct')for(const pair of keys){const [packageKey,queryKey]=JSON.parse(pair);add.run(ecosystem,packageKey,queryKey);}
56
71
  db.exec(`INSERT OR IGNORE INTO wanted_advisories SELECT source,id FROM source.advisory_records WHERE source NOT IN ('osv','vigievuln','cveproject','cveproject-legacy');
57
72
  INSERT OR IGNORE INTO wanted_advisories SELECT p.source,p.id FROM source.advisory_packages p JOIN wanted_packages w ON w.ecosystem=p.ecosystem AND w.package_key=p.name_key;
58
73
  INSERT OR IGNORE INTO wanted_advisories SELECT p.source,p.id FROM source.advisory_packages p JOIN wanted_packages w ON w.ecosystem='Maven' AND p.ecosystem='CVEProduct' AND p.name_key=lower(substr(w.package_key,instr(w.package_key,':')+1));
59
74
  INSERT OR IGNORE INTO wanted_advisories SELECT q.source,q.id FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
60
75
  INSERT OR IGNORE INTO wanted_cves SELECT DISTINCT l.cve FROM source.cve_lookup l JOIN wanted_packages w ON w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1))));`);
61
- if(project.retainAllNvd)db.exec("INSERT OR IGNORE INTO wanted_advisories SELECT source,id FROM source.advisory_records WHERE source IN ('cveproject','cveproject-legacy')");
76
+ const addRecord=db.prepare('INSERT OR IGNORE INTO wanted_advisories SELECT source,id FROM source.advisory_records WHERE source=? AND id=?');
77
+ for(const [source,ids] of accessed.records)for(const id of ids)addRecord.run(source,id);
62
78
  const {decompress}=require('./advisory-compression');
63
79
  const addCve=db.prepare('INSERT OR IGNORE INTO wanted_cves VALUES(?)');
64
80
  // Some findings (for example a vendored JS advisory) have no retained
@@ -67,6 +83,14 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
67
83
  for(const id of Array.isArray(project.cves)?project.cves:[]) {
68
84
  if(/^CVE-\d{4}-\d{4,7}$/.test(id||'')) addCve.run(id);
69
85
  }
86
+ for(const id of accessed.cves)if(/^CVE-\d{4}-\d{4,7}$/.test(id))addCve.run(id);
87
+ // A CMS instance is matched offline, against the real tree, from the publisher
88
+ // advisories warmed here: the records of the CVEs they name travel with them.
89
+ const zlib=require('node:zlib');
90
+ for(const row of db.prepare("SELECT e.encoding,e.payload FROM source.cache_entries e JOIN wanted_entries w ON w.namespace=e.namespace AND w.key=e.key WHERE e.namespace='application-snapshot'").all()){
91
+ const body=row.encoding.endsWith('+deflate')?zlib.inflateRawSync(Buffer.from(row.payload),{maxOutputLength:134217728}):Buffer.from(row.payload);
92
+ for(const id of body.toString('utf8').match(/CVE-\d{4}-\d{4,7}/g)||[])addCve.run(id);
93
+ }
70
94
  const rows=db.prepare('SELECT r.envelope_deflate,r.envelope_bytes FROM source.advisory_records r JOIN wanted_advisories w USING(source,id)');
71
95
  for(const row of rows.all()){
72
96
  const text=decompress(row.envelope_deflate,row.envelope_bytes).toString('utf8');
@@ -81,8 +105,8 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
81
105
  INSERT INTO advisory_queries SELECT q.* FROM source.advisory_queries q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
82
106
  INSERT INTO advisory_query_ids SELECT q.* FROM source.advisory_query_ids q JOIN wanted_packages w ON w.ecosystem=q.ecosystem AND w.query_key=q.name_key;
83
107
  INSERT INTO advisory_coverage SELECT * FROM source.advisory_coverage WHERE source<>'osv';
84
- INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace NOT IN ('airgap-project','airgap-cve-index','image-inventory') AND NOT (namespace='catalogue' AND (key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss') OR key GLOB 'image-tags-*'));
85
- INSERT INTO cache_snapshots SELECT * FROM source.cache_snapshots;
108
+ INSERT INTO cache_entries SELECT e.* FROM source.cache_entries e JOIN wanted_entries w ON w.namespace=e.namespace AND w.key=e.key WHERE e.namespace NOT IN ('airgap-project','airgap-cve-index','image-inventory','auxiliary') AND NOT (e.namespace='catalogue' AND (e.key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss') OR e.key GLOB 'image-tags-*'));
109
+ INSERT INTO cache_snapshots SELECT * FROM source.cache_snapshots WHERE namespace='cve_lookup' OR namespace IN (SELECT namespace FROM wanted_snapshots);
86
110
  INSERT INTO cve_lookup SELECT l.* FROM source.cve_lookup l WHERE EXISTS(SELECT 1 FROM wanted_packages w WHERE w.ecosystem='Maven' AND ((l.kind='package' AND l.lookup_key=lower(w.package_key)) OR (l.kind='product' AND l.lookup_key=lower(substr(w.package_key,instr(w.package_key,':')+1)))));
87
111
  INSERT INTO package_versions SELECT * FROM source.package_versions;
88
112
  INSERT INTO resource_bodies SELECT * FROM source.resource_bodies;
@@ -94,7 +118,7 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
94
118
  for(const item of imageRefs)for(const prefer of [false,true])for(const key of imageInventoryKeys(item,prefer))insertImage.run(key);
95
119
  const insertRegistry=db.prepare("INSERT OR IGNORE INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key=?");
96
120
  for(const item of imageRefs){const ref=require('../images/registry').parseReference(item.reference),key='image-tags-'+require('node:crypto').createHash('sha256').update(`${ref.registry}/${ref.repository}`).digest('hex');insertRegistry.run(key);}
97
- if(!project.retainAllNvd)db.exec("UPDATE advisory_coverage SET complete=0,entry_json=json_set(entry_json,'$.complete',json('false')) WHERE source IN ('cveproject','cveproject-legacy')");
121
+ db.exec("UPDATE advisory_coverage SET complete=0,entry_json=json_set(entry_json,'$.complete',json('false')) WHERE source IN ('cveproject','cveproject-legacy')");
98
122
  // A project index proves coverage only for its exported package buckets.
99
123
  // Preserve the source timestamp and never claim global index completeness.
100
124
  const indexSnapshot=db.prepare("SELECT * FROM source.cache_snapshots WHERE namespace='cve_lookup'").get();
@@ -103,8 +127,8 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
103
127
  db.prepare("UPDATE cache_snapshots SET complete=0,metadata_json=? WHERE namespace='cve_lookup'").run(JSON.stringify(indexMeta));
104
128
  const marker=db.prepare("INSERT OR REPLACE INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES('airgap-cve-index',?,?,NULL,?,'json',?,'{}')");
105
129
  const existing=db.prepare("SELECT fetched_at,stale FROM source.cache_entries WHERE namespace='airgap-cve-index' AND key=?");
106
- for(const p of project.packages.filter(p=>p.ecosystem==='Maven')){
107
- const coord=p.name.toLowerCase(),artifact=coord.slice(coord.indexOf(':')+1);
130
+ for(const p of db.prepare("SELECT query_key FROM wanted_packages WHERE ecosystem='Maven'").all()){
131
+ const coord=p.query_key.toLowerCase(),artifact=coord.slice(coord.indexOf(':')+1);
108
132
  const coverage=indexSnapshot.complete===1?indexSnapshot:existing.get(`p:${coord}`);
109
133
  if(coverage){
110
134
  marker.run(`p:${coord}`,coverage.fetched_at,coverage.stale,Buffer.from('{}'));
@@ -129,25 +153,44 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
129
153
  }
130
154
  }
131
155
  // These per-CVE enrichments may contain observations from other projects.
132
- // Keep only CVEs actually encountered while preparing this descriptor.
133
- const keep=new Set(Array.isArray(project.cves)?project.cves:[]),zlib=require('node:zlib');
156
+ // Keep only the CVEs of this descriptor: encountered while preparing it, or named
157
+ // by the advisories it exports.
158
+ const keep=new Set(db.prepare('SELECT cve FROM wanted_cves').all().map(row=>row.cve));
134
159
  const cached=db.prepare("SELECT * FROM source.cache_entries WHERE namespace='catalogue' AND key IN ('euvd-targeted','certfr-targeted','kev-targeted','epss')").all();
135
160
  const insertCache=db.prepare('INSERT INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json) VALUES(?,?,?,?,?,?,?,?)');
136
- for(const row of cached){
161
+ const decode=row=>{
137
162
  const raw=row.encoding==='json+deflate'?zlib.inflateRawSync(row.payload,{maxOutputLength:134217728}):row.encoding==='json'?row.payload:null;
138
- if(!raw)throw Error(`invalid ${row.key} cache encoding`);
139
- const value=JSON.parse(Buffer.from(raw).toString('utf8'));
140
- if(!value || !value.entries || typeof value.entries!=='object' || Array.isArray(value.entries))throw Error(`invalid ${row.key} cache`);
141
- value.entries=Object.fromEntries(Object.entries(value.entries).filter(([id])=>keep.has(id)));
163
+ return raw?JSON.parse(Buffer.from(raw).toString('utf8')):undefined;
164
+ };
165
+ const insertValue=(row,value)=>{
142
166
  const bytes=Buffer.from(JSON.stringify(value)),compressed=bytes.length>=4096,metadata=JSON.parse(row.metadata_json);
143
167
  delete metadata.uncompressedBytes;if(compressed)metadata.uncompressedBytes=bytes.length;
144
168
  insertCache.run(row.namespace,row.key,row.fetched_at,row.expires_at,row.stale,compressed?'json+deflate':'json',compressed?zlib.deflateRawSync(bytes,{level:1}):bytes,JSON.stringify(metadata));
169
+ };
170
+ const isMap=value=>!!value && !!value.entries && typeof value.entries==='object' && !Array.isArray(value.entries);
171
+ for(const row of cached){
172
+ const value=decode(row);
173
+ if(value===undefined)throw Error(`invalid ${row.key} cache encoding`);
174
+ if(!isMap(value))throw Error(`invalid ${row.key} cache`);
175
+ value.entries=Object.fromEntries(Object.entries(value.entries).filter(([id])=>keep.has(id)));
176
+ insertValue(row,value);
177
+ }
178
+ // A shared registry map (existence, latest versions, licences, end of life) holds
179
+ // the packages of every scan under one entry: keep the keys this preparation used.
180
+ const copyEntry=db.prepare('INSERT INTO cache_entries SELECT * FROM source.cache_entries WHERE namespace=? AND key=?');
181
+ for(const row of db.prepare("SELECT e.* FROM source.cache_entries e JOIN wanted_entries w ON w.namespace=e.namespace AND w.key=e.key WHERE e.namespace='auxiliary'").all()){
182
+ const value=decode(row);
183
+ if(!isMap(value)){copyEntry.run(row.namespace,row.key);continue;}
184
+ const used=accessed.maps.get(row.key)||new Set(),kept=object=>Object.fromEntries(Object.entries(object).filter(([name])=>used.has(name)));
185
+ value.entries=kept(value.entries);
186
+ if(value.fetchedAt && typeof value.fetchedAt==='object')value.fetchedAt=kept(value.fetchedAt);
187
+ insertValue(row,value);
145
188
  }
146
- db.exec(project.retainAllNvd?'INSERT INTO nvd_records SELECT * FROM source.nvd_records':'INSERT INTO nvd_records SELECT n.* FROM source.nvd_records n JOIN wanted_cves w USING(cve)');
189
+ db.exec('INSERT INTO nvd_records SELECT n.* FROM source.nvd_records n JOIN wanted_cves w USING(cve)');
147
190
  const global=db.prepare("SELECT slot,fetched_at,complete,stale,entry_json FROM source.advisory_coverage WHERE source='osv' AND ecosystem=?");
148
191
  const insert=db.prepare('INSERT OR REPLACE INTO advisory_coverage(source,ecosystem,slot,fetched_at,complete,stale,entry_json) VALUES(?,?,?,?,?,?,?)');
149
- for(const p of project.packages)for(const row of global.all(p.ecosystem)){
150
- const ecosystem=packageScope(p.ecosystem,p.name),entry=JSON.parse(row.entry_json);entry.ecosystem=ecosystem;
192
+ for(const p of db.prepare('SELECT ecosystem,query_key FROM wanted_packages').all())for(const row of global.all(p.ecosystem)){
193
+ const ecosystem=packageScope(p.ecosystem,p.query_key),entry=JSON.parse(row.entry_json);entry.ecosystem=ecosystem;
151
194
  insert.run('osv',ecosystem,row.slot,row.fetched_at,row.complete,row.stale,JSON.stringify(entry));
152
195
  }
153
196
  }
@@ -155,6 +198,6 @@ function buildProjectSnapshot(sourceDir,targetDir,project){
155
198
  db.exec('DETACH DATABASE source');
156
199
  db.exec('PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode=DELETE');
157
200
  }finally{db.close()}
158
- return {packages:project.packages.length,images:imageRefs.length,fullNvd:!!project.retainAllNvd};
201
+ return {packages:project.packages.length,images:imageRefs.length};
159
202
  }
160
203
  module.exports={buildProjectScope,buildProjectSnapshot,validateImageSnapshotCompleteness,imageInventoryKeys,packageScope};
package/lib/cache/json.js CHANGED
@@ -1,18 +1,51 @@
1
1
  'use strict';
2
2
 
3
3
  const {createCacheRepository} = require('./repository');
4
+ const {accessLog, note} = require('./access-log');
5
+
6
+ // A shared map ({entries: {key: value}}) holds the lookups of every scan of this machine
7
+ // under one cache entry. The keys this process reads or writes are noted, so a project
8
+ // archive keeps those and leaves the packages of other scans behind.
9
+ const watched = new WeakMap();
10
+
11
+ function track(cacheDir, key, entries) {
12
+ if (!entries || typeof entries !== 'object' || Array.isArray(entries) || watched.has(entries)) return entries;
13
+ const used = accessLog(cacheDir).maps;
14
+ const proxy = new Proxy(entries, {
15
+ get(target, name, receiver) { if (typeof name === 'string') note(used, key, name); return Reflect.get(target, name, receiver); },
16
+ set(target, name, item, receiver) { if (typeof name === 'string') note(used, key, name); return Reflect.set(target, name, item, receiver); },
17
+ });
18
+ watched.set(proxy, entries);
19
+ return proxy;
20
+ }
21
+
22
+ // The entries stay watched when the caller replaces them (a stale map is emptied, refilled
23
+ // by the scan, then completed with its previous entries).
24
+ function watch(cacheDir, key, value) {
25
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return value;
26
+ let entries = track(cacheDir, key, value.entries);
27
+ Object.defineProperty(value, 'entries', {enumerable: true, configurable: true, get: () => entries, set: next => { entries = track(cacheDir, key, next); }});
28
+ return value;
29
+ }
30
+
31
+ /** The plain entries of a loaded map, for a pass over all of them that uses none in particular. */
32
+ const allEntries = entries => watched.get(entries) || entries || {};
4
33
 
5
34
  function load(cacheDir, key, fallback) {
6
- try { return createCacheRepository(cacheDir).get('auxiliary', key)?.value ?? fallback; }
35
+ try { return watch(cacheDir, key, createCacheRepository(cacheDir).get('auxiliary', key)?.value ?? fallback); }
7
36
  catch { return fallback; }
8
37
  }
9
38
 
10
39
  function save(cacheDir, key, value) {
11
40
  try {
41
+ const entries = value?.entries, plain = watched.get(entries);
42
+ if (plain) value = {...value, entries: plain};
43
+ // A map rebuilt by this process holds only what it looked up.
44
+ else if (entries && typeof entries === 'object' && !Array.isArray(entries)) for (const name of Object.keys(entries)) note(accessLog(cacheDir).maps, key, name);
12
45
  createCacheRepository(cacheDir).put('auxiliary', key, value, {
13
46
  fetchedAt: Number.isSafeInteger(value?.meta?.fetchedAt) && value.meta.fetchedAt > 0 ? value.meta.fetchedAt : Date.now(),
14
47
  });
15
48
  } catch { /* Optional cache. */ }
16
49
  }
17
50
 
18
- module.exports = {load, save};
51
+ module.exports = {load, save, allEntries};
@@ -13,10 +13,13 @@ function fresh(fetchedAt, ttlMs = DEFAULT_TTL_MS, now = Date.now()) {
13
13
  function preserveEntries(cache, previous) {
14
14
  if (!previous?.entries) return cache;
15
15
  let retained=false;
16
- for (const [key,value] of Object.entries(previous.entries)) {
17
- const next=cache.entries[key];
18
- if (!Object.hasOwn(cache.entries,key) || (next?.error && !next.absent)) {
19
- cache.entries[key]=value;retained=true;
16
+ // Carrying the previous entries over uses none of them: a project archive keeps only
17
+ // the keys the scan looked up (cache/json.js).
18
+ const {allEntries}=require('./json'),current=allEntries(cache.entries);
19
+ for (const [key,value] of Object.entries(allEntries(previous.entries))) {
20
+ const next=current[key];
21
+ if (!Object.hasOwn(current,key) || (next?.error && !next.absent)) {
22
+ current[key]=value;retained=true;
20
23
  }
21
24
  }
22
25
  if(retained) cache.meta={...cache.meta,fetchedAt:Math.min(Number(cache.meta?.fetchedAt)||0,Number(previous.fetchedAt)||0)};
@@ -2,9 +2,11 @@
2
2
 
3
3
  const {getCacheDb}=require('./db');
4
4
  const zlib=require('node:zlib');
5
+ const {accessLog,note}=require('./access-log');
5
6
 
6
7
  function createCacheRepository(cacheDir){
7
- const db=getCacheDb(cacheDir);
8
+ const db=getCacheDb(cacheDir),log=accessLog(cacheDir);
9
+ const touch=(namespace,key)=>note(log.entries,namespace,key);
8
10
  const get=db.prepare('SELECT fetched_at,expires_at,stale,encoding,payload,metadata_json FROM cache_entries WHERE namespace=? AND key=?');
9
11
  const put=db.prepare(`INSERT INTO cache_entries(namespace,key,fetched_at,expires_at,stale,encoding,payload,metadata_json)
10
12
  VALUES (?,?,?,?,?,?,?,?) ON CONFLICT(namespace,key) DO UPDATE SET fetched_at=excluded.fetched_at,
@@ -14,6 +16,7 @@ function createCacheRepository(cacheDir){
14
16
  db,
15
17
  get(namespace,key){
16
18
  const row=get.get(namespace,key);if(!row)return null;
19
+ touch(namespace,key);
17
20
  const compressed=row.encoding.endsWith('+deflate');
18
21
  const body=compressed?zlib.inflateRawSync(Buffer.from(row.payload),{maxOutputLength:134217728}):Buffer.from(row.payload);
19
22
  const encoding=compressed?row.encoding.slice(0,-8):row.encoding;
@@ -24,6 +27,7 @@ function createCacheRepository(cacheDir){
24
27
  const encoding=Buffer.isBuffer(value)||value instanceof Uint8Array?'binary':typeof value==='string'?'text':'json';
25
28
  const bytes=encoding==='binary'?Buffer.from(value):Buffer.from(encoding==='text'?value:JSON.stringify(value));
26
29
  const compressed=bytes.length>=4096;
30
+ touch(namespace,key);
27
31
  put.run(namespace,key,fetchedAt,expiresAt,stale?1:0,compressed?encoding+'+deflate':encoding,
28
32
  compressed?zlib.deflateRawSync(bytes,{level:1}):bytes,JSON.stringify({...metadata,...(compressed?{uncompressedBytes:bytes.length}:{})}));
29
33
  },
@@ -36,8 +40,9 @@ function createCacheRepository(cacheDir){
36
40
  for(const row of rows){last=row.key;yield [row.key,this.get(namespace,row.key)]}
37
41
  }
38
42
  },
39
- getSnapshot(namespace){const row=db.prepare('SELECT * FROM cache_snapshots WHERE namespace=?').get(namespace);return row?{fetchedAt:row.fetched_at,complete:!!row.complete,stale:!!row.stale,recordCount:row.record_count,metadata:JSON.parse(row.metadata_json)}:null},
43
+ getSnapshot(namespace){log.snapshots.add(namespace);const row=db.prepare('SELECT * FROM cache_snapshots WHERE namespace=?').get(namespace);return row?{fetchedAt:row.fetched_at,complete:!!row.complete,stale:!!row.stale,recordCount:row.record_count,metadata:JSON.parse(row.metadata_json)}:null},
40
44
  putSnapshot(namespace,{fetchedAt=Date.now(),complete=false,stale=false,recordCount=0,metadata={}}={}){
45
+ log.snapshots.add(namespace);
41
46
  db.prepare(`INSERT INTO cache_snapshots(namespace,fetched_at,complete,stale,record_count,metadata_json) VALUES (?,?,?,?,?,?)
42
47
  ON CONFLICT(namespace) DO UPDATE SET fetched_at=excluded.fetched_at,complete=excluded.complete,
43
48
  stale=excluded.stale,record_count=excluded.record_count,metadata_json=excluded.metadata_json`).run(namespace,fetchedAt,complete?1:0,stale?1:0,recordCount,JSON.stringify(metadata));
package/lib/cli-image.js CHANGED
@@ -278,7 +278,9 @@ async function run(args, injected = {}, name = 'system scan') {
278
278
  if (opts.prepareCache) {
279
279
  const gaps = incompleteCapabilities(result, ['advisories', 'sources']);
280
280
  if (gaps.length) console.warn('⚠ Prepared cache has incomplete advisory or source coverage; review the scan notices.');
281
- const prepared = await require('./cache/archive').exportCache(opts.prepareCache, { sourceDir: cacheDir,
281
+ // The archive holds what this assessment consulted, not the cache of every scan made on this machine.
282
+ const project = require('./cache/airgap-project').buildProjectScope(result.resolvedDeps, { cves: result.cveMatches.map(m => m.cve?.id) });
283
+ const prepared = await require('./cache/archive').exportCache(opts.prepareCache, { sourceDir: cacheDir, project,
282
284
  proxyOrigin: options.proxyCache ? require('./cache/proxy-scope').proxyOrigin(options.proxyCache) : undefined });
283
285
  console.log(`Prepared cache: ${prepared.path}`);
284
286
  }
@@ -160,7 +160,7 @@ async function checkNpmRegistryDeps(resolvedDeps, opts = {}) {
160
160
  const cache = loadCache();
161
161
  const fresh = (offline || !require("../../providers").hasHostedProxy()) && cache.meta?.fetchedAt && require('../../cache/policy').fresh(cache.meta.fetchedAt, CACHE_MAX_AGE_MS);
162
162
  // Older versions saved transient HTTP/transport failures as ordinary entries.
163
- for (const [key, entry] of Object.entries(cache.entries || {})) {
163
+ for (const [key, entry] of Object.entries(require('../../cache/json').allEntries(cache.entries))) {
164
164
  if (entry?.error && !entry.absent && !offline) delete cache.entries[key];
165
165
  }
166
166
  const previous = !fresh && !offline ? {entries:cache.entries, fetchedAt:cache.meta?.fetchedAt} : null;
@@ -171,7 +171,7 @@ async function checkNpmRegistryDeps(resolvedDeps, opts = {}) {
171
171
  // just the version used for the probe. Preserve it across versions offline
172
172
  // unless another cached observation for that name found a packument.
173
173
  const offlineAbsent = new Map();
174
- if (offline) for (const [key, value] of Object.entries(cache.entries || {})) {
174
+ if (offline) for (const [key, value] of Object.entries(require('../../cache/json').allEntries(cache.entries))) {
175
175
  const split = key.lastIndexOf('@');
176
176
  if (split <= 0) continue;
177
177
  const name = key.slice(0, split), status = offlineAbsent.get(name) || { absent: false, present: false };
@@ -9,6 +9,11 @@
9
9
  * the handful published since. Hosted proxy mode instead sends matched CVE identifiers
10
10
  * to the proxy and receives only their stored advisory references.
11
11
  *
12
+ * CERT-FR also edits a recent alert in place — a CVE added, "[MàJ]" put before the title —
13
+ * without a new revision: the revision date alone misses it. So an advisory whose listing
14
+ * title differs from the indexed one is read again, and once a day the alerts revised in
15
+ * the last 30 days are read again whatever the listing says.
16
+ *
12
17
  * Cache: ~/.fad-checker/certfr-cache.json = { meta: { fetchedAt }, entries: { ref:
13
18
  * { kind, rev, title, cves } } } — the accumulating entry-map shape, so --import-cache
14
19
  * merges it key by key. The listings are re-read after 4h; offline uses what is there.
@@ -25,6 +30,9 @@ const CACHE_FILE = "certfr-cache.json";
25
30
  const CACHE_TTL_MS = 4 * 3600 * 1000;
26
31
  const KINDS = ["avis", "alerte"];
27
32
  const SAVE_EVERY = 500;
33
+ // Alerts revised within RECHECK_DAYS are read again every RECHECK_EVERY_MS.
34
+ const RECHECK_DAYS = 30;
35
+ const RECHECK_EVERY_MS = 24 * 3600 * 1000;
28
36
 
29
37
  const cachePath = dir => path.join(dir || DEFAULT_CACHE_DIR, CACHE_FILE);
30
38
 
@@ -58,11 +66,23 @@ function advisoryCves(json) {
58
66
  return [...out];
59
67
  }
60
68
 
61
- /** Pure: listing rows that are new or revised against the cached entries. */
62
- function staleAdvisories(listing, entries, kind) {
63
- return (Array.isArray(listing) ? listing : [])
64
- .filter(row => row?.reference && entries[row.reference]?.rev !== (row.last_revision_date || ""))
65
- .map(row => ({ kind, ref: row.reference, rev: row.last_revision_date || "", title: row.title || "" }));
69
+ /**
70
+ * Pure: listing rows to read against the indexed entries — new, revised, or shown under
71
+ * another title (edited in place). With `recheckSince` (ms), the alerts revised since then
72
+ * are added: `recheck` marks a row whose revision date is the indexed one, so its indexed
73
+ * copy must not be trusted and its content is compared after the read.
74
+ */
75
+ function staleAdvisories(listing, entries, kind, { recheckSince = null } = {}) {
76
+ const out = [];
77
+ for (const row of Array.isArray(listing) ? listing : []) {
78
+ if (!row?.reference) continue;
79
+ const e = entries[row.reference], rev = row.last_revision_date || "", title = row.title || "";
80
+ const sameRevision = !!e && e.rev === rev;
81
+ const retitled = sameRevision && typeof e.title === "string" && e.title !== title;
82
+ const recent = sameRevision && kind === "alerte" && recheckSince != null && Date.parse(String(rev).slice(0, 19) + "Z") >= recheckSince;
83
+ if (!sameRevision || retitled || recent) out.push({ kind, ref: row.reference, rev, title, recheck: sameRevision });
84
+ }
85
+ return out;
66
86
  }
67
87
 
68
88
  /** Pure: entries → { "CVE-…": [{ ref, kind, title }] }, newest advisory first. */
@@ -75,29 +95,35 @@ function indexByCve(entries) {
75
95
  return byCve;
76
96
  }
77
97
 
78
- async function refresh(data, { fetcher, verbose, cacheDir, concurrency, onProgress }) {
98
+ async function refresh(data, { fetcher, verbose, cacheDir, concurrency, onProgress, recheckSince = null }) {
79
99
  const { getResource } = require("..");
80
100
  const headers = { "User-Agent": "vigievuln-certfr" };
81
- const todo = [];
101
+ const todo = [], changed = [];
102
+ const sameCves = (a, b) => { const x = [...(a || [])].sort(), y = [...(b || [])].sort(); return x.length === y.length && x.every((c, i) => c === y[i]); };
82
103
  let oldestFetchedAt = Date.now();
83
104
  for (const kind of KINDS) {
84
105
  const r = await getResource("certfr", "index", { kind }, { fetcher, headers });
85
106
  if (!r.ok) throw new Error(`CERT-FR ${kind} listing HTTP ${r.status}`);
86
107
  oldestFetchedAt = Math.min(oldestFetchedAt, require('../common').responseFetchedAt(r));
87
- todo.push(...staleAdvisories(await r.json(), data.entries, kind));
108
+ todo.push(...staleAdvisories(await r.json(), data.entries, kind, { recheckSince }));
88
109
  }
89
110
  let done = 0, failed = 0, next = 0;
90
111
  const worker = async () => {
91
112
  while (next < todo.length) {
92
113
  const a = todo[next++];
93
114
  try {
94
- const r = await getResource("certfr", "advisory", { kind: a.kind, ref: a.ref, rev: a.rev }, { fetcher, headers });
115
+ // The copy kept under this revision is the one being doubted: a recheck asks the source.
116
+ const r = await getResource("certfr", "advisory", { kind: a.kind, ref: a.ref, rev: a.rev }, { fetcher, headers, ...(a.recheck ? { forceRefresh: true } : {}) });
95
117
  oldestFetchedAt = Math.min(oldestFetchedAt, require('../common').responseFetchedAt(r));
96
118
  // A 404/410 is an answer (a listed advisory without JSON): record it empty so it
97
119
  // is not re-requested every run. Anything else is retried next time.
98
- if (r.ok) data.entries[a.ref] = { kind: a.kind, rev: a.rev, title: a.title, cves: advisoryCves(await r.json()) };
99
- else if (r.status === 404 || r.status === 410) data.entries[a.ref] = { kind: a.kind, rev: a.rev, title: a.title, cves: [] };
100
- else failed++;
120
+ const before = data.entries[a.ref];
121
+ const cves = r.ok ? advisoryCves(await r.json()) : r.status === 404 || r.status === 410 ? [] : null;
122
+ if (cves === null) failed++;
123
+ // A recheck that finds the same title and CVEs — or no JSON this time — leaves the
124
+ // entry as it is: whoever keeps more in it (a description) does not lose it.
125
+ else if (a.recheck && (!r.ok || (before.title === a.title && sameCves(before.cves, cves)))) { /* unchanged */ }
126
+ else { data.entries[a.ref] = { kind: a.kind, rev: a.rev, title: a.title, cves }; changed.push(a.ref); }
101
127
  } catch { failed++; }
102
128
  done++;
103
129
  if (onProgress) onProgress(done, todo.length);
@@ -107,12 +133,15 @@ async function refresh(data, { fetcher, verbose, cacheDir, concurrency, onProgre
107
133
  await Promise.all(Array.from({ length: Math.max(1, concurrency) }, worker));
108
134
  // A run that could not read some advisories leaves the listing stamp unchanged, so the
109
135
  // next run retries them instead of waiting a day.
110
- if (!failed) data.meta = { fetchedAt: oldestFetchedAt };
136
+ if (!failed) data.meta = { fetchedAt: oldestFetchedAt, recheckedAt: recheckSince != null ? Date.now() : data.meta?.recheckedAt || 0 };
111
137
  writeCache(cacheDir, data);
112
- if (verbose) console.log(` CERT-FR: ${todo.length - failed} advisories indexed${failed ? `, ${failed} failed` : ""}`);
113
- return { changed: todo.filter(a => data.entries[a.ref]?.rev === a.rev).map(a => a.ref), failed };
138
+ if (verbose) console.log(` CERT-FR: ${todo.length - failed} advisories read, ${changed.length} indexed${failed ? `, ${failed} failed` : ""}`);
139
+ return { changed, failed, rechecked: recheckSince != null && !failed };
114
140
  }
115
141
 
142
+ /** The `recheckSince` of a run: the start of the recheck window when the last recheck is a day old, else null. */
143
+ const recheckDue = (recheckedAt, now = Date.now()) => now - (Number(recheckedAt) || 0) >= RECHECK_EVERY_MS ? now - RECHECK_DAYS * 86400000 : null;
144
+
116
145
  /**
117
146
  * Enrich matches in place: cve.certfr = [{ ref, kind, title }] for CVEs cited by a
118
147
  * CERT-FR advisory or alert. opts: { offline, verbose, fetcher, cacheDir, concurrency, onProgress }
@@ -137,7 +166,7 @@ async function enrichCertFr(matches, opts = {}) {
137
166
 
138
167
  const data = readCache(cacheDir);
139
168
  if (!offline && !require('../../cache/policy').fresh(data.meta?.fetchedAt || 0, CACHE_TTL_MS)) {
140
- try { await refresh(data, { fetcher, verbose, cacheDir, concurrency, onProgress }); }
169
+ try { await refresh(data, { fetcher, verbose, cacheDir, concurrency, onProgress, recheckSince: recheckDue(data.meta?.recheckedAt) }); }
141
170
  catch (err) { if (verbose) console.warn(` CERT-FR refresh failed: ${err.message} — using the cached index`); }
142
171
  }
143
172
  const byCve = indexByCve(data.entries);
@@ -151,7 +180,9 @@ async function enrichCertFr(matches, opts = {}) {
151
180
  /**
152
181
  * Bring an index { meta, entries } up to date in place (listings + new/revised advisories).
153
182
  * cacheDir: false = do not write the fad cache file (the caller persists the entries).
183
+ * recheckSince (ms): also read again the alerts revised since then (see `recheckDue`).
184
+ * → { changed: refs whose entry was written, failed, rechecked }
154
185
  */
155
186
  const refreshCertFrIndex = (data, opts = {}) => refresh(data, { concurrency: 8, ...opts });
156
187
 
157
- module.exports = { enrichCertFr, refreshCertFrIndex, advisoryCves, staleAdvisories, indexByCve, certfrUrl, CACHE_FILE };
188
+ module.exports = { enrichCertFr, refreshCertFrIndex, recheckDue, advisoryCves, staleAdvisories, indexByCve, certfrUrl, CACHE_FILE, RECHECK_DAYS, RECHECK_EVERY_MS };
@@ -32,7 +32,7 @@ function discardUnverifiedEntries(cache) {
32
32
  cache.entries = {};
33
33
  return true;
34
34
  }
35
- for (const [key, entry] of Object.entries(cache.entries)) {
35
+ for (const [key, entry] of Object.entries(require('../../cache/json').allEntries(cache.entries))) {
36
36
  if (entry === true || confirmedAbsence(entry)) continue;
37
37
  delete cache.entries[key];
38
38
  changed = true;
@@ -46,9 +46,15 @@ function cachePath(cveId) {
46
46
  return path.join(NVD_CACHE_DIR, `${cveId}.json`);
47
47
  }
48
48
 
49
+ // The NVD records this process consulted are the ones a project archive carries.
50
+ function recordsDb(cveId, cacheDir) {
51
+ require('../../cache/access-log').accessLog(cacheDir).cves.add(cveId);
52
+ return require('../../cache/db').getCacheDb(cacheDir);
53
+ }
54
+
49
55
  function readCache(cveId, offline = false, cacheDir = path.dirname(NVD_CACHE_DIR), options = {}) {
50
56
  try {
51
- const db=require('../../cache/db').getCacheDb(cacheDir);
57
+ const db=recordsDb(cveId,cacheDir);
52
58
  const row=db.prepare(`SELECT kind,fetched_at,body_deflate,body_bytes,metadata_json FROM nvd_records WHERE cve=?
53
59
  ${offline ? 'ORDER BY fetched_at DESC LIMIT 1' : "AND kind='live' LIMIT 1"}`).get(cveId);
54
60
  if(!row)return null;
@@ -73,7 +79,7 @@ function readCache(cveId, offline = false, cacheDir = path.dirname(NVD_CACHE_DIR
73
79
  }
74
80
 
75
81
  function writeCache(cveId, body, fetchedAt = Date.now(), cacheDir = path.dirname(NVD_CACHE_DIR), provenance = {}) {
76
- const db=require('../../cache/db').getCacheDb(cacheDir);
82
+ const db=recordsDb(cveId,cacheDir);
77
83
  const bytes=Buffer.from(JSON.stringify(body));
78
84
  db.prepare(`INSERT INTO nvd_records(cve,kind,fetched_at,revision_ms,body_deflate,body_bytes,metadata_json) VALUES (?,?,?,?,?,?,?)
79
85
  ON CONFLICT(cve,kind) DO UPDATE SET fetched_at=excluded.fetched_at,revision_ms=excluded.revision_ms,
@@ -94,7 +100,7 @@ function responseEvidence(response, status) {
94
100
  // cache entry. Keep the distinction when reporting offline coverage.
95
101
  function hasCachedAbsence(cveId, options = {}) {
96
102
  try {
97
- const db=require('../../cache/db').getCacheDb(options.cacheDir || path.dirname(NVD_CACHE_DIR));
103
+ const db=recordsDb(cveId,options.cacheDir || path.dirname(NVD_CACHE_DIR));
98
104
  const row=db.prepare('SELECT fetched_at,body_deflate,body_bytes FROM nvd_records WHERE cve=? ORDER BY fetched_at DESC LIMIT 1').get(cveId);
99
105
  return !!row && row.fetched_at > 1 && row.fetched_at <= Date.now() && (options.offline || Date.now()-row.fetched_at < NVD_CACHE_TTL_MS) && JSON.parse(require('../../cache/advisory-compression').decompress(row.body_deflate,row.body_bytes).toString('utf8')) === null;
100
106
  } catch { return false; }
@@ -104,7 +110,7 @@ function hasCachedAbsence(cveId, options = {}) {
104
110
  // changing whether that row is eligible for enrichment.
105
111
  function cachedEvidence(cveId, status, opts = {}) {
106
112
  try {
107
- const db = require('../../cache/db').getCacheDb(opts.cacheDir || path.dirname(NVD_CACHE_DIR));
113
+ const db = recordsDb(cveId, opts.cacheDir || path.dirname(NVD_CACHE_DIR));
108
114
  const row = db.prepare(`SELECT fetched_at,body_deflate,body_bytes,metadata_json FROM nvd_records WHERE cve=? ${opts.offline ? 'ORDER BY fetched_at DESC LIMIT 1' : "AND kind='live' LIMIT 1"}`).get(cveId);
109
115
  if (!row) return { status, stale: false };
110
116
  const metadata = JSON.parse(row.metadata_json);
@@ -374,12 +374,27 @@ const FONT = "font-family='-apple-system,Segoe UI,Roboto,sans-serif'";
374
374
  const legendStr = s => s.name ? `${s.label} · ${s.name} · ${s.value}` : `${s.label} · ${s.value}`;
375
375
  const LEGEND_CHARW = 4.15; // ~px per char at the 7.5px legend font
376
376
 
377
- // The viewBox width needed to fit the FULL legend text (no ellipsis). The caller
378
- // takes the MAX across all four charts and feeds it to every donut, so they share
379
- // one viewBox width → uniform donut size when each card is the same 25% slot.
377
+ // A legend entry keeps its full text (no ellipsis) but wraps past this length: the four
378
+ // donuts share one viewBox width, so a single long entry — "Shared: <seven modules>" —
379
+ // would otherwise shrink every chart of the row.
380
+ const LEGEND_MAX_CHARS = 72;
381
+ function legendLines(text) {
382
+ const lines = [];
383
+ let line = "";
384
+ for (const word of String(text).split(" ")) {
385
+ if (line && line.length + 1 + word.length > LEGEND_MAX_CHARS) { lines.push(line); line = ""; }
386
+ line += (line ? " " : "") + word;
387
+ }
388
+ if (line) lines.push(line);
389
+ return lines.flatMap(l => l.length > LEGEND_MAX_CHARS ? l.match(new RegExp(`.{1,${LEGEND_MAX_CHARS}}`, "g")) : [l]);
390
+ }
391
+
392
+ // The viewBox width needed to fit the legend lines. The caller takes the MAX across all
393
+ // four charts and feeds it to every donut, so they share one viewBox width → uniform
394
+ // donut size when each card is the same 25% slot.
380
395
  function legendBoxWidth(slices, note) {
381
396
  const items = (slices || []).filter(s => s.value > 0);
382
- return Math.ceil(Math.max(0, ...items.map(s => 13 + legendStr(s).length * LEGEND_CHARW), note ? note.length * 4 : 0)) + 8;
397
+ return Math.ceil(Math.max(0, ...items.flatMap(s => legendLines(legendStr(s)).map(l => 13 + l.length * LEGEND_CHARW)), note ? Math.min(note.length, LEGEND_MAX_CHARS) * 4 : 0)) + 8;
383
398
  }
384
399
 
385
400
  // A donut + a legend underneath. Category slices may carry per-severity `segments`;
@@ -448,9 +463,12 @@ function donutChart({ slices, width = 250, note, centerValue, t = EN_T }) {
448
463
  }
449
464
  ly += 12;
450
465
  }
451
- for (const s of items) { // full legend text — no ellipsis
466
+ for (const s of items) { // full legend text — no ellipsis, long entries wrap
452
467
  parts.push(`<rect x="0" y="${ly - 7}" width="8" height="8" rx="1" fill="${s.color}"/>`);
453
- parts.push(`<text x="11" y="${ly}" ${FONT} font-size="7.5" fill="#4b5563">${esc(legendTxt(s))}</text>`);
468
+ for (const [i, line] of legendLines(legendTxt(s)).entries()) {
469
+ if (i) ly += 9;
470
+ parts.push(`<text x="11" y="${ly}" ${FONT} font-size="7.5" fill="#4b5563">${esc(line)}</text>`);
471
+ }
454
472
  ly += 11;
455
473
  }
456
474
  if (note) {
package/package.json CHANGED
@@ -1,43 +1,60 @@
1
1
  {
2
2
  "name": "vigievuln",
3
- "version": "1.4.0",
4
- "description": "Polyglot dependency auditor for Maven, Gradle, JavaScript, Composer, PyPI, NuGet, Go, Ruby and 11 CMS/frameworks, with offline scans and audit reports.",
3
+ "version": "1.4.2",
4
+ "description": "Fully autonomous polyglot CVE scanner for professional audits, no build needed: Maven, Gradle, JavaScript, Composer, PyPI, NuGet, Go, Ruby, 11 CMS/frameworks, system and container images; offline scans and audit reports.",
5
5
  "keywords": [
6
+ "vigievuln",
6
7
  "sca",
7
8
  "software-composition-analysis",
8
9
  "dependency-scanner",
9
10
  "vulnerability-scanner",
11
+ "cve-scanner",
10
12
  "security",
13
+ "security-audit",
14
+ "code-audit",
15
+ "pentest",
16
+ "no-build",
17
+ "zero-build",
18
+ "offline",
19
+ "air-gapped",
11
20
  "cve",
12
21
  "osv",
13
22
  "nvd",
14
23
  "epss",
15
24
  "kev",
16
- "cyclonedx",
25
+ "euvd",
26
+ "cert-fr",
27
+ "eol",
28
+ "end-of-life",
29
+ "outdated",
30
+ "deprecated",
31
+ "malicious-packages",
32
+ "private-dependencies",
33
+ "license-compliance",
17
34
  "sbom",
35
+ "cyclonedx",
36
+ "spdx",
18
37
  "csaf",
19
38
  "vex",
20
39
  "sarif",
21
40
  "xlsx",
22
- "excel",
23
- "license-compliance",
24
- "eol",
25
- "end-of-life",
26
- "outdated",
27
- "deprecated",
28
41
  "audit",
29
42
  "devsecops",
30
43
  "appsec",
31
44
  "supply-chain",
32
- "offline",
33
- "air-gapped",
34
45
  "maven",
46
+ "gradle",
47
+ "java",
35
48
  "npm",
36
49
  "yarn",
37
50
  "pnpm",
51
+ "javascript",
38
52
  "composer",
53
+ "php",
39
54
  "pypi",
55
+ "python",
40
56
  "nuget",
57
+ "dotnet",
41
58
  "go",
42
59
  "golang",
43
60
  "ruby",
@@ -45,19 +62,26 @@
45
62
  "retirejs",
46
63
  "polyglot",
47
64
  "cli",
65
+ "docker",
66
+ "container-scanning",
67
+ "container-security",
68
+ "linux",
69
+ "debian",
70
+ "alpine",
71
+ "rhel",
48
72
  "cms",
49
73
  "framework",
50
74
  "wordpress",
51
75
  "drupal",
52
- "symfony",
53
- "laravel",
54
76
  "joomla",
55
77
  "prestashop",
56
- "typo3",
57
78
  "magento",
79
+ "typo3",
58
80
  "spip",
59
- "proxy-cache",
60
- "code-audit",
81
+ "ghost",
82
+ "redmine",
83
+ "symfony",
84
+ "laravel",
61
85
  "certificates",
62
86
  "binary-analysis"
63
87
  ],
@@ -76,9 +100,7 @@
76
100
  "pp9Ping <pp9Ping@gmail.com>"
77
101
  ],
78
102
  "bin": {
79
- "vigievuln": "vigievuln.js",
80
- "fad-checker": "vigievuln.js",
81
- "fad": "vigievuln.js"
103
+ "vigievuln": "vigievuln.js"
82
104
  },
83
105
  "exports": {
84
106
  ".": "./vigievuln.js",
package/vigievuln.js CHANGED
@@ -1190,8 +1190,9 @@ let preparedSource;
1190
1190
  const filled = backfillVersions(resolved, mgmt);
1191
1191
  if (filled) ui.ok(`backfilled ${chalk.bold(filled)} version(s) from ${externalParents.length} parent(s) + ${importBoms.length} BOM(s) in the descriptor`);
1192
1192
  }
1193
- // Warm retire signatures (online) so --export-cache carries them for offline JS scanning.
1194
- if (runNpm && !options.offline && options.retire !== false) {
1193
+ // Warm retire signatures (online) so the archive carries them: the offline scan looks
1194
+ // for vendored JavaScript in any tree, with or without an npm manifest in the descriptor.
1195
+ if (!options.offline && options.retire !== false) {
1195
1196
  const { warmRetireSignatures } = require("./lib/providers/retire/scan");
1196
1197
  await warmRetireSignatures({ verbose });
1197
1198
  }
@@ -1242,12 +1243,11 @@ let preparedSource;
1242
1243
  : [];
1243
1244
  const warmedReport = await runReportFlow(resolved, { activeIds, runMaven, runNpm, privateLibIds, mavenRepos, regMap, collectWarnings: [], walkOpts, mavenStore: reactor?.store, mavenPropsByPom: reactor?.propsByPom, imageReferences });
1244
1245
  if (options.prepareOffline && !process.exitCode) {
1245
- const scope=require('./lib/cache/airgap-project').buildProjectScope(resolved,{applications,cves:warmedReport?.cveIds || [],imageReferences:warmedReport?.imageReferences || [],images:options.images});
1246
+ const scope=require('./lib/cache/airgap-project').buildProjectScope(resolved,{cves:warmedReport?.cveIds || [],imageReferences:warmedReport?.imageReferences || [],images:options.images});
1246
1247
  const cacheDir=require('./lib/cache/directory').getCacheDir();
1247
1248
  const proxyOrigin=options.sourceProfile==='proxy' ? require('./lib/cache/proxy-scope').proxyOrigin(options.proxyCache) : null;
1248
- if(!scope.packages.length && !scope.imageReferences?.length) ui.warn('no package scope available; exporting the complete local cache');
1249
1249
  try {
1250
- const result=await require('./lib/cache/archive').exportCache(options.output,{sourceDir:cacheDir,proxyOrigin,project:(scope.packages.length || scope.imageReferences?.length)?scope:null});
1250
+ const result=await require('./lib/cache/archive').exportCache(options.output,{sourceDir:cacheDir,proxyOrigin,project:scope});
1251
1251
  ui.ok(`offline archive prepared: ${result.path} (${(result.size/1048576).toFixed(2)} MiB; ${scope.packages.length} packages)`);
1252
1252
  } catch(error) {console.error(chalk.red(`❌ could not prepare offline archive: ${error.message}`));process.exitCode=2;}
1253
1253
  }