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
@@ -0,0 +1,196 @@
1
+ 'use strict';
2
+ // Debian tracker computes release status from unqualified source notes, then
3
+ // replaces them with release-specific notes; DSA/DLA provide release fixes.
4
+ const fs = require('node:fs');
5
+ const crypto = require('node:crypto');
6
+ const {createCacheRepository} = require('../cache-repository');
7
+ const {getCacheDir} = require('../cache-directory');
8
+ const {debian:compare} = require('./versions');
9
+
10
+ const SOURCE = 'debian-security-tracker-history';
11
+ const PARSER_VERSION = 2;
12
+ const SALSA = 'https://salsa.debian.org/security-tracker-team/security-tracker';
13
+ const NAMESPACE = distribution => `system-debian-history:${distribution.versionId}:${distribution.codename}`;
14
+ const CVE = /^CVE-\d{4}-\d{4,}$/;
15
+ function validDate(value){if(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value))return false;const n=Date.parse(value+'T00:00:00Z');return Number.isFinite(n)&&new Date(n).toISOString().slice(0,10)===value;}
16
+ function checkDistribution(d) {
17
+ if (String(d?.id||'').toLowerCase()!=='debian' || !/^\d+(?:\.\d+)*$/.test(String(d.versionId||'')) || !/^[a-z][a-z0-9-]{0,30}$/.test(String(d.codename||''))) throw Error('Debian release version and codename are required');
18
+ return {id:'debian',versionId:String(d.versionId).split('.')[0],codename:String(d.codename)};
19
+ }
20
+ function repository(opts){return opts.repository || createCacheRepository(opts.cacheDir || getCacheDir());}
21
+ const originKey = (name,version) => JSON.stringify([name,version]);
22
+ async function syncDebianPackageOrigins(packages,opts={}) {
23
+ if(opts.offline)throw Error('cannot check Debian package origin offline');
24
+ if(!Array.isArray(packages) || packages.length>(opts.maxOriginQueries??1000))throw Error('invalid Debian package origin query');
25
+ const cache=repository(opts),out=[];
26
+ for(const p of packages){
27
+ if(!/^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p?.name||'') || typeof p.version!=='string' || compare(p.version,p.version)!==0)throw Error('invalid Debian package origin identity');
28
+ const sourceURL=`https://sources.debian.org/api/src/${encodeURIComponent(p.name)}/${encodeURIComponent(p.version)}/`;
29
+ let observation;
30
+ try{
31
+ const response=opts.fetchResource?await opts.fetchResource('source-version',{name:p.name,version:p.version}):await require('../providers').getResource('debian','source-version',{name:p.name,version:p.version},{fetcher:opts.fetcher,signal:opts.signal});
32
+ const payload=JSON.parse((await bounded(response,opts.maxMetadataBytes??4*1024*1024)).toString());
33
+ const stamp=Date.parse(response.headers?.get?.('x-fad-proxy-fetched-at')||''),fetchedAt=Number.isFinite(stamp)&&stamp<=Date.now()?stamp:Date.now();
34
+ observation={status:payload && !payload.error && payload.package===p.name && payload.version===p.version?'corroborated':'unknown',suites:Array.isArray(payload?.pkg_infos?.suites)?payload.pkg_infos.suites.filter(x=>typeof x==='string'):[],sourceURL,fetchedAt};
35
+ }catch{observation={status:'unknown',sourceURL,fetchedAt:Date.now()};}
36
+ cache.put('system-debian-origin',originKey(p.name,p.version),observation,{fetchedAt:observation.fetchedAt});out.push({name:p.name,version:p.version,...observation});
37
+ }
38
+ return out;
39
+ }
40
+ function normalizeList(input,limit,allowEmpty=false){const bytes=Buffer.isBuffer(input)?input:Buffer.from(String(input));if((!allowEmpty&&!bytes.length)||bytes.length>limit)throw Error('Debian tracker list exceeds size limit or is empty');return bytes.toString('utf8');}
41
+ // Preserve whole upstream blocks, including cross references and every release
42
+ // line, so server-side package projection cannot alter a record's meaning.
43
+ function projectDebianList(input,{list,packages,maxListBytes=128*1024*1024}={}) {
44
+ if(!['CVE','DSA','DLA'].includes(list)||!Array.isArray(packages)||packages.length>5000 || packages.some(p=>typeof p!=='string'||!/^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p)))throw Error('invalid Debian tracker projection');
45
+ const wanted=new Set(packages),text=normalizeList(input,maxListBytes),out=[];let block=[],keep=false;
46
+ const flush=()=>{if(keep)out.push(block.join('\n'));block=[];keep=false;};
47
+ for(const line of text.split(/\r?\n/)){
48
+ if(line && !/^\s/.test(line)){flush();block=[line];continue;}
49
+ if(!block.length)continue;block.push(line);
50
+ const m=line.match(/^\s+(?:\[[^\]]+\]\s+)?-\s+([a-z0-9][a-z0-9+.-]*)\s+/);
51
+ if(m&&wanted.has(m[1]))keep=true;
52
+ }
53
+ flush();return out.length?out.join('\n')+'\n':'';
54
+ }
55
+ function parseHistoricalDebian(lists, distribution, options={}) {
56
+ const d=checkDistribution(distribution),limit=options.maxListBytes??128*1024*1024;
57
+ const partial=Array.isArray(options.packages),cves=normalizeList(lists.CVE,limit,partial), notices=['DSA','DLA'].map(k=>[k,normalizeList(lists[k],limit,partial)]);
58
+ const grouped=new Map(),rejected=new Set(); let id=null,description='',releaseLines=0,headers=0;
59
+ const add=(pkg,record)=>{if(!grouped.has(pkg))grouped.set(pkg,new Map());const by=grouped.get(pkg);if(!by.has(record.id))by.set(record.id,{id:record.id,description:record.description||'',statuses:[],fixes:[],globalNotes:[],contextNotes:[]});const r=by.get(record.id);if(record.description&&!r.description)r.description=record.description;if(record.status)r.statuses.push(record.status);if(record.fix)r.fixes.push(record.fix);if(record.globalNote)r.globalNotes.push(record.globalNote);if(record.contextNote)r.contextNotes.push(record.contextNote);};
60
+ for(const line of cves.split(/\r?\n/)) {
61
+ if(!/^\s/.test(line)){const m=line.match(/^(CVE-\d{4}-\d{4,})\b\s*(.*)$/);id=m?.[1]||null;description=m?.[2]||'';if(id)headers++;continue;}
62
+ if(!id)continue;
63
+ if(/^\s+REJECTED\s*$/.test(line)){rejected.add(id);continue;}
64
+ const m=line.match(/^\s+(?:\[([^\]]+)\]\s+)?-\s+([a-z0-9][a-z0-9+.-]*)\s+(\S+)(.*)$/);
65
+ if(!m)continue;
66
+ const token=m[3],tag=token.match(/^<([^>]+)>$/);
67
+ if(m[1]&&!m[1].split(/[,\s]+/).includes(d.codename)){
68
+ if(options.includeContextReleases)add(m[2],{id,description,contextNote:{releases:m[1].split(/[,\s]+/).filter(Boolean),kind:tag?tag[1]:'fixed',version:tag?null:token,note:m[4].trim(),source:'CVE/list'}});
69
+ continue;
70
+ }
71
+ if(!m[1]){add(m[2],{id,description,globalNote:{kind:tag?tag[1]:'fixed',version:tag?null:token,note:m[4].trim(),source:'CVE/list'}});continue;}
72
+ releaseLines++;
73
+ if(tag)add(m[2],{id,description,status:{kind:tag[1],note:m[4].trim(),source:'CVE/list'}});
74
+ else add(m[2],{id,description,fix:{version:token,source:'CVE/list',note:m[4].trim()}});
75
+ }
76
+ if(!partial && (!headers || !releaseLines))throw Error('Debian tracker snapshot lacks release-scoped records');
77
+ for(const [kind,text] of notices){let notice=null,ids=[],entries=[];const flush=()=>{if(!notice)return;for(const entry of entries)for(const cve of ids)if(CVE.test(cve))add(entry.pkg,{id:cve,fix:{version:entry.version,source:`${kind}/list`,advisory:notice}});};
78
+ for(const line of text.split(/\r?\n/)){
79
+ if(!/^\s/.test(line)){flush();const m=line.match(/^\[[^\]]+\]\s+((?:DSA|DLA)-\d+-\d+)\b/);notice=m?.[1]||null;ids=[];entries=[];continue;}
80
+ if(!notice)continue;const m=line.match(/^\s+\{([^}]+)\}/);if(m)ids.push(...m[1].split(/\s+/));
81
+ const r=line.match(/^\s+\[([^\]]+)\]\s+-\s+([a-z0-9][a-z0-9+.-]*)\s+(\S+)/);
82
+ if(r&&r[1].split(/[,\s]+/).includes(d.codename) && !r[3].startsWith('<'))entries.push({pkg:r[2],version:r[3]});
83
+ }flush();
84
+ }
85
+ for(const records of grouped.values())for(const cve of records.keys())if(rejected.has(cve))records.delete(cve);
86
+ return {distribution:d,packages:new Map([...grouped].filter(([,v])=>v.size).map(([k,v])=>[k,[...v.values()]])),releaseLines};
87
+ }
88
+ async function importHistoricalDebian(lists,opts={}) {
89
+ const distribution=checkDistribution(opts.distribution),commit=String(opts.commit||'');
90
+ if(!/^[a-f0-9]{40}$/.test(commit))throw Error('immutable Debian tracker commit is required');
91
+ if(!validDate(opts.cutoff))throw Error('historical cutoff date is required');
92
+ if(Date.parse(opts.cutoff+'T23:59:59Z')>Date.now())throw Error('Explicit historical Debian cutoff is in the future');
93
+ if(opts.commitTimestamp && (!Number.isFinite(Date.parse(opts.commitTimestamp)) || Date.parse(opts.commitTimestamp)>Date.parse(opts.cutoff+'T23:59:59Z')))throw Error('Debian tracker commit is outside the historical cutoff');
94
+ const normalized={};for(const k of ['CVE','DSA','DLA']){const v=lists[k];normalized[k]=typeof v==='string'&&fs.existsSync(v)?fs.readFileSync(v):v;if(normalized[k]==null)throw Error('all Debian tracker lists are required');}
95
+ if(opts.packages && (!Array.isArray(opts.packages)||opts.packages.some(p=>typeof p!=='string'||!/^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p))))throw Error('invalid Debian tracker package scope');
96
+ const parsed=parseHistoricalDebian(normalized,distribution,opts),cache=repository(opts),ns=NAMESPACE(distribution),now=Number.isFinite(opts.fetchedAt)?opts.fetchedAt:Date.now(),previous=cache.getSnapshot(ns),partial=Array.isArray(opts.packages);
97
+ if(partial){const permitted=new Set(opts.packages);for(const name of parsed.packages.keys())if(!permitted.has(name))parsed.packages.delete(name);}
98
+ const hashes=Object.fromEntries(Object.entries(normalized).map(([k,v])=>[k,crypto.createHash('sha256').update(v).digest('hex')]));
99
+ const write=()=>{
100
+ if(!partial || previous?.metadata?.commit!==commit || previous?.metadata?.parserVersion!==PARSER_VERSION){for(const [key] of cache.entries(ns))cache.delete(ns,key);}
101
+ else if(previous.complete)throw Error('partial Debian tracker snapshot cannot replace a complete snapshot');
102
+ if(partial)for(const name of opts.packages)cache.delete(ns,name);
103
+ for(const [name,records] of parsed.packages)cache.put(ns,name,records,{fetchedAt:now});
104
+ const queriedPackages=partial?[...new Set([...(previous?.metadata?.commit===commit&&previous.metadata.parserVersion===PARSER_VERSION?previous.metadata.queriedPackages||[]:[]),...opts.packages])].sort():null;
105
+ cache.putSnapshot(ns,{fetchedAt:now,complete:!partial,recordCount:[...parsed.packages.values()].reduce((n,x)=>n+x.length,0),metadata:{distribution,commit,parserVersion:PARSER_VERSION,commitTimestamp:opts.commitTimestamp||null,cutoff:opts.cutoff,hashes,source:SALSA,acquisition:opts.acquisition||'import',sourceFetchedAt:opts.sourceFetchedAt||null,sourceHashes:opts.sourceHashes||null,releaseLines:parsed.releaseLines,queriedPackages}});
106
+ };
107
+ if(cache.db?.transaction)cache.db.transaction(write);else write();
108
+ return {distribution,commit,cutoff:opts.cutoff,packageCount:parsed.packages.size,releaseLines:parsed.releaseLines,hashes,fetchedAt:now};
109
+ }
110
+ async function bounded(response,max) {if(!response?.ok)throw Error(`Debian historical source HTTP ${response?.status||'failure'}`);const chunks=[];let n=0;for await(const part of response.body||[]){n+=part.length;if(n>max)throw Error('Debian historical source exceeds download limit');chunks.push(Buffer.from(part));}return Buffer.concat(chunks,n);}
111
+ async function syncHistoricalDebian(distribution,opts={}) {
112
+ const d=checkDistribution(distribution);if(opts.offline)throw Error('cannot sync Debian history offline');
113
+ if(opts.packages!==undefined&&!Array.isArray(opts.packages))throw Error('invalid Debian tracker package scope');
114
+ const packages=opts.packages===undefined?null:[...new Set(opts.packages)];
115
+ if(packages && (packages.length>(opts.maxPackages??100000) || packages.some(p=>typeof p!=='string'||!/^[a-z0-9][a-z0-9+.-]{0,199}$/.test(p))))throw Error('invalid Debian tracker package scope');
116
+ if(packages && !packages.length)return {notApplicable:true,reason:'no-source-packages'};
117
+ const transport=opts.fetchResource || ((kind,p)=>kind==='lifecycle' ? require('../providers').getResource('eol','product',{product:p.distribution},{fetcher:opts.fetcher,signal:opts.signal}) : require('../providers').getResource('debian',kind,p,{streaming:true,fetcher:opts.fetcher,signal:opts.signal}));
118
+ const sourceFetchedAt={},sourceHashes={};
119
+ const get=async(kind,params,key,max)=>{const res=await transport(kind,params);const stamp=Date.parse(res.headers?.get?.('x-fad-proxy-fetched-at')||'');sourceFetchedAt[key]=Number.isFinite(stamp)&&stamp<=Date.now()?stamp:Date.now();const hash=res.headers?.get?.('x-vigievuln-source-sha256');if(/^[a-f0-9]{64}$/.test(hash||''))sourceHashes[key]=hash;return bounded(res,max);};
120
+ let cutoff=opts.cutoff;
121
+ if(!cutoff){const cycles=JSON.parse((await get('lifecycle',{distribution:'debian'},'lifecycle',opts.maxMetadataBytes??4*1024*1024)).toString());const cycle=Array.isArray(cycles)&&cycles.find(x=>String(x.cycle)===d.versionId && String(x.codename||'').toLowerCase()===d.codename);cutoff=cycle?.eol;}
122
+ if(!validDate(cutoff))throw Error('No valid historical Debian release cutoff is available');
123
+ if(Date.parse(cutoff+'T23:59:59Z')>Date.now()){
124
+ if(opts.cutoff)throw Error('Explicit historical Debian cutoff is in the future');
125
+ return {notApplicable:true,reason:'release-not-historical'};
126
+ }
127
+ const until=cutoff+'T23:59:59Z',history=JSON.parse((await get('history',{until},'history',opts.maxMetadataBytes??4*1024*1024)).toString());
128
+ const commit=Array.isArray(history)&&history[0]?.id,at=history?.[0]?.committed_date;
129
+ if(!/^[a-f0-9]{40}$/.test(commit||'')||!Number.isFinite(Date.parse(at))||Date.parse(at)>Date.parse(until))throw Error('Invalid Debian tracker historical commit');
130
+ const lists={};
131
+ // The relay projects at most 1000 package names per request. The direct
132
+ // source returns the whole list irrespective of params, so download it once.
133
+ if(!packages && !opts.fetchResource)throw Error('Debian history sync requires source package names');
134
+ const chunks=packages?Array.from({length:Math.ceil(packages.length/1000)},(_,i)=>packages.slice(i*1000,i*1000+1000)):[null];
135
+ const direct=!opts.fetchResource&&!require('../providers').hasProxyRoute();
136
+ for(const name of ['CVE','DSA','DLA']){
137
+ const parts=[];for(let i=0;i<(direct?1:chunks.length);i++){
138
+ const bytes=await get('list',{commit,list:name,...(chunks[i]?{packages:chunks[i]}:{})},i?`${name}:${i}`:name,opts.maxDownloadBytes??128*1024*1024);
139
+ if(i && sourceHashes[name] && sourceHashes[`${name}:${i}`] && sourceHashes[name]!==sourceHashes[`${name}:${i}`])throw Error('Debian tracker projection source changed between pages');
140
+ parts.push(bytes);
141
+ }lists[name]=Buffer.concat(parts.flatMap((part,i)=>i?[Buffer.from('\n'),part]:[part]));
142
+ }
143
+ return importHistoricalDebian(lists,{...opts,packages,distribution:d,commit,commitTimestamp:at,cutoff,acquisition:'network',sourceFetchedAt,sourceHashes,fetchedAt:Math.min(...Object.values(sourceFetchedAt))});
144
+ }
145
+ function evaluateTrackerRecord(rec,version) {
146
+ const statuses=rec.statuses||[],fixes=rec.fixes||[],globalNotes=rec.globalNotes||[];
147
+ const tags=new Set(statuses.map(s=>s.kind)),fixed=fixes.map(f=>f.version).filter(v=>compare(v,v)===0).sort(compare);
148
+ const annotations=statuses.filter(s=>['no-dsa','ignored','postponed'].includes(s.kind));
149
+ const unsupported=[...tags].some(t=>!['not-affected','unfixed','removed','no-dsa','ignored','postponed'].includes(t));
150
+ let threshold=null,releaseFix=null,affected=null,scope='release-specific';
151
+ if(!version || compare(version,version)!==0 || unsupported || fixes.some(f=>compare(f.version,f.version)!==0)) affected=null;
152
+ else if(tags.has('unfixed') || tags.has('removed')) affected=true;
153
+ else if(fixed.length){releaseFix=fixed[fixed.length-1];threshold=releaseFix;affected=compare(version,threshold)<0;}
154
+ else if(tags.has('not-affected')) affected=false;
155
+ else {
156
+ scope='inherited-source-note';
157
+ const globalKinds=new Set(globalNotes.map(n=>n.kind)),globalFixed=globalNotes.filter(n=>n.kind==='fixed').map(n=>n.version);
158
+ if(globalNotes.some(n=>n.kind==='fixed' && compare(n.version,n.version)!==0) || [...globalKinds].some(k=>!['fixed','unfixed','removed','not-affected'].includes(k))) affected=null;
159
+ else if(globalKinds.has('unfixed') || globalKinds.has('removed')) affected=true;
160
+ else if(globalFixed.length){globalFixed.sort(compare);threshold=globalFixed[globalFixed.length-1];affected=compare(version,threshold)<0;}
161
+ else if(globalKinds.has('not-affected')) affected=false;
162
+ }
163
+ const effectiveNotes=scope==='inherited-source-note' ? globalNotes : [...statuses.filter(s=>s.kind==='unfixed'||s.kind==='removed'),...fixes.filter(f=>f.version===releaseFix)];
164
+ const trackerUrgency=effectiveNotes.some(n=>/\(unimportant(?:\s*[;)]|$)/i.test(n.note||''))?'unimportant':null;
165
+ return {affected,threshold,releaseFix,scope,annotations,trackerUrgency,statuses,fixes,globalNotes};
166
+ }
167
+ function assessHistoricalDebian(inventory,opts={}) {
168
+ let d;try{d=checkDistribution(inventory?.distribution);}catch{return {matches:[],coverage:[{source:SOURCE,status:'unknown',result:'indeterminate',reason:'missing exact Debian distribution identity'}],warnings:[]};}
169
+ const cache=repository(opts),ns=NAMESPACE(d),snapshot=cache.getSnapshot(ns),matches=[],observations=[],warnings=[],coverage=[];
170
+ if(!snapshot)return {matches,observations,coverage:[{source:SOURCE,status:'missing',result:'indeterminate'}],warnings:['No historical Debian release snapshot is cached']};
171
+ let unknown=0,examined=0;
172
+ for(const dep of inventory.packages||[]){if(!dep.sourceName || !dep.sourceVersion || (!snapshot.complete && !snapshot.metadata?.queriedPackages?.includes(dep.sourceName))){unknown++;continue;}const version=dep.sourceVersion;if(compare(version,version)!==0){unknown++;continue;}
173
+ const entry=cache.get(ns,dep.sourceName);if(!entry)continue;
174
+ for(const rec of entry.value){
175
+ examined++;
176
+ const {affected,threshold,releaseFix,scope,annotations,trackerUrgency,statuses,fixes,globalNotes}=evaluateTrackerRecord(rec,version);
177
+ if(affected===null){unknown++;observations.push({dep,cveId:rec.id,status:'unknown',reason:'no usable tracker package/version verdict',evidence:{statuses,fixes,globalNotes}});continue;}
178
+ if(!affected)continue;
179
+ {
180
+ const evidence={distribution:d,commit:snapshot.metadata.commit,commitTimestamp:snapshot.metadata.commitTimestamp||null,cutoff:snapshot.metadata.cutoff,fixes,globalNotes,annotations,scope,comparisonThreshold:threshold,trackerUrgency};
181
+ // Identity is conditional on the installed package metadata, like the OSV
182
+ // adapter. Archive corroboration is separate from authenticating its bytes.
183
+ const declared=typeof dep.packageMetadata?.origin==='string' ? dep.packageMetadata.origin.trim() : '';
184
+ const declaredOrigin=declared && declared.toLowerCase()!=='debian' ? {status:'third-party',source:'dpkg-origin',declared} : null;
185
+ const origin=(typeof opts.packageOrigin==='function'?opts.packageOrigin(dep,d):dep.packageOrigin) || declaredOrigin || cache.get('system-debian-origin',originKey(dep.sourceName,version))?.value || {status:'distribution-context'};
186
+ if(['third-party','ambiguous'].includes(origin.status)){unknown++;observations.push({dep,cveId:rec.id,status:'possible',reason:'package vendor provenance does not establish Debian origin',evidence:{...evidence,origin}});continue;}
187
+ const originStatus=origin.status==='corroborated' && (!Array.isArray(origin.suites) || origin.suites.includes(d.codename))?'corroborated':'distribution-context';
188
+ matches.push({dep,source:SOURCE,advisoryId:rec.id,cve:{id:rec.id,summary:rec.description,description:rec.description,severity:'UNKNOWN',fixVersion:releaseFix,advisorySource:`https://security-tracker.debian.org/tracker/${rec.id}`,historicalEvidence:{...evidence,originStatus,origin}}});
189
+ }
190
+ }
191
+ }
192
+ const meta=snapshot.metadata||{},legacy=meta.parserVersion!==PARSER_VERSION;
193
+ coverage.push({source:SOURCE,status:legacy?'incomplete':'complete',execution:legacy?'partial':'completed',result:'indeterminate',complete:!legacy,completeness:'historical-only',scope:'historical-release-evidence',parserVersion:meta.parserVersion||1,queriedPackages:meta.queriedPackages||null,historicalCutoff:meta.cutoff,commit:meta.commit,commitTimestamp:meta.commitTimestamp||null,fetchedAt:snapshot.fetchedAt,sourceFetchedAt:meta.sourceFetchedAt,examined,unknown,reason:legacy?'Historical cache predates inherited source notes; refresh for complete historical assessment.':'Historical release evidence ends at the snapshot; later vulnerabilities remain unassessed.'});
194
+ return {matches,observations,coverage,warnings};
195
+ }
196
+ module.exports={SOURCE,PARSER_VERSION,namespace:NAMESPACE,checkDistribution,projectDebianList,parseHistoricalDebian,evaluateTrackerRecord,importHistoricalDebian,syncHistoricalDebian,syncDebianPackageOrigins,assessHistoricalDebian};
@@ -0,0 +1,2 @@
1
+ 'use strict';
2
+ module.exports={...require('./collect'),...require('./advisories'),...require('./targeted'),versions:require('./versions')};
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ // Official nginx.org advisory XML; upstream version ranges apply only to
3
+ // packages with an explicitly declared vendor identity, never generic distro builds.
4
+ const crypto=require('node:crypto');
5
+ const {createCacheRepository}=require('../cache-repository');
6
+ const {getCacheDir}=require('../cache-directory');
7
+ const SOURCE='nginx-vendor-advisories',URL='https://raw.githubusercontent.com/nginx/nginx.org/master/xml/en/security_advisories.xml',PAGE='https://nginx.org/en/security_advisories.html';
8
+ function ver(s){const m=/^(\d+)\.(\d+)\.(\d+)$/.exec(String(s));return m?m.slice(1).map(Number):null;}
9
+ function cmp(a,b){for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]-b[i];return 0;}
10
+ function inRange(version,text){const v=ver(version);if(!v)return null;const pieces=String(text||'').split(',').map(s=>s.trim());let unknown=false;for(const piece of pieces){if(piece==='all')return true;const m=/^(\d+\.\d+\.\d+)(?:-(\d+\.\d+\.\d+))?$/.exec(piece);if(!m){unknown=true;continue;}const low=ver(m[1]),high=ver(m[2]||m[1]);if(cmp(v,low)>=0&&cmp(v,high)<=0)return true;}return unknown?null:false;}
11
+ function vendor(p,domains){const meta=p.packageMetadata||{},origin=String(meta.origin||'').trim().toLowerCase(),maintainer=String(meta.maintainer||'');const email=/<[^<>@\s]+@([^<>\s]+)>\s*$/.exec(maintainer)?.[1]?.toLowerCase();const declared=origin==='nginx'||origin==='nginx, inc.'||!!email&&domains.includes(email);return declared?{status:'third-party',source:origin.startsWith('nginx')?'dpkg-origin':'dpkg-maintainer',declared:origin.startsWith('nginx')?meta.origin:meta.maintainer,signatureVerified:false}:null;}
12
+ async function parseNginxAdvisories(input,{maxBytes=4*1024*1024}={}){
13
+ const bytes=Buffer.isBuffer(input)?input:Buffer.from(String(input));if(!bytes.length||bytes.length>maxBytes)throw Error('NGINX advisory XML exceeds size limit or is empty');let text=bytes.toString('utf8');
14
+ if(/<!ENTITY\b/i.test(text)||/<!DOCTYPE\s+[^>]*\[/i.test(text))throw Error('NGINX advisory XML contains entity declarations');
15
+ text=text.replace(/<!DOCTYPE\s+article\s+SYSTEM\s+["']\.\.\/\.\.\/dtd\/article\.dtd["']\s*>/i,'');if(/<!DOCTYPE\b/i.test(text))throw Error('unsupported NGINX XML doctype');
16
+ const doc=await require('xml2js').parseStringPromise(text,{strict:true}),sections=doc?.article?.section;if(!Array.isArray(sections))throw Error('invalid NGINX advisory XML');
17
+ const items=sections.flatMap(s=>s.security||[]).flatMap(s=>s.item||[]);if(!items.length)throw Error('NGINX advisory XML has no records');
18
+ const records=[];for(const item of items){const a=item.$||{},id=/^\d{4}-\d{4,}$/.test(a.cve||'')?`CVE-${a.cve}`:null;if(!id)continue;if(typeof a.name!=='string'||typeof a.vulnerable!=='string')throw Error('invalid NGINX advisory record');records.push({id,title:a.name,severity:a.severity||null,vulnerable:a.vulnerable,good:a.good||null,sourceDetails:{attributes:a,content:Object.fromEntries(Object.entries(item).filter(([key])=>key!=='$'))},advisory:typeof a.advisory==='string'&&/^https:\/\//.test(a.advisory)?a.advisory:PAGE});}
19
+ if(!records.length)throw Error('NGINX advisory XML has no identified records');return {records,sha256:crypto.createHash('sha256').update(bytes).digest('hex')};
20
+ }
21
+ async function syncNginxAdvisories(options={}){
22
+ if(options.offline)throw Error('cannot refresh NGINX advisories offline');const timeout=AbortSignal.timeout(options.timeoutMs??30000),signal=options.signal?AbortSignal.any([options.signal,timeout]):timeout;const res=await require('../providers').getResource('nginx','advisories',{}, {fetcher:options.fetcher,signal,streaming:true,noStore:true});if(!res.ok){await res.body?.cancel();throw Error(`NGINX advisory HTTP ${res.status}`);}let size=0,chunks=[];for await(const chunk of res.body){size+=chunk.length;if(size>(options.maxBytes??4*1024*1024))throw Error('NGINX advisory XML exceeds size limit');chunks.push(Buffer.from(chunk));}const parsed=await parseNginxAdvisories(Buffer.concat(chunks),options),now=Date.now(),stamp=Date.parse(res.headers.get('x-fad-proxy-fetched-at')||''),proxy=require('../providers').hasProxyRoute(),valid=Number.isFinite(stamp)&&stamp>0&&stamp<=now;
23
+ const snapshot={...parsed,sourceURL:URL,observedAt:proxy&&valid?stamp:now,stale:proxy&&(!valid||res.headers.get('x-fad-proxy')==='stale')};(options.cacheRepository||createCacheRepository(options.cacheDir||getCacheDir())).put('catalogue','nginx-advisories',snapshot);return snapshot;
24
+ }
25
+ async function assessNginxAdvisories(packages,options={}){
26
+ const matches=[],observations=[],warnings=[],repo=options.cacheRepository||createCacheRepository(options.cacheDir||getCacheDir()),domains=options.allowedMaintainerDomains||['nginx.org','nginx.com','f5.com'];if(!Array.isArray(domains)||domains.some(d=>typeof d!=='string'||!/^[a-z0-9.-]+$/.test(d)))throw Error('invalid NGINX maintainer domains');
27
+ const candidates=(packages||[]).filter(p=>p.manager==='dpkg'&&p.sourceName==='nginx'),cached=repo.get('catalogue','nginx-advisories')?.value,ttl=options.ttlMs??86400000;if(!Number.isSafeInteger(ttl)||ttl<=0)throw Error('invalid NGINX advisory TTL');let snapshot=Array.isArray(cached?.records)&&/^[a-f0-9]{64}$/.test(cached.sha256||'')&&Number.isFinite(cached.observedAt)?cached:null;
28
+ if(!candidates.length)return {matches,observations,coverage:[{source:SOURCE,execution:'not-applicable',result:'not-applicable'}],warnings};
29
+ if(!options.offline&&(!snapshot||snapshot.stale||Date.now()-snapshot.observedAt>=ttl||Date.now()<snapshot.observedAt)){try{snapshot=await syncNginxAdvisories(options);}catch(error){warnings.push({type:'source-unavailable',source:SOURCE,message:`NGINX advisories: ${error.message}`});}}
30
+ if(!snapshot){if(options.offline)warnings.push({type:'source-unavailable',source:SOURCE,message:'NGINX vendor advisory snapshot is not cached.'});return {matches,observations,coverage:[{source:SOURCE,execution:'partial',result:'indeterminate',reason:'NGINX vendor advisory snapshot unavailable.'}],warnings};}
31
+ for(const p of candidates){const identity=p.packageOrigin?.status==='ambiguous'?null:vendor(p,domains),upstream=/^(\d+\.\d+\.\d+)(?:-[A-Za-z0-9.+~]+)?$/.exec(p.sourceVersion||'')?.[1];for(const record of snapshot.records){const affected=inRange(upstream,record.vulnerable);if(affected===false)continue;const evidence={sourceURL:URL,sha256:snapshot.sha256,observedAt:snapshot.observedAt,advisoryURL:record.advisory,upstreamVersion:upstream||null,versionRange:record.vulnerable,vendorSeverity:record.severity,packageOrigin:identity,signatureVerified:false,configurationApplicability:'unknown',sourceDetails:record.sourceDetails||null};
32
+ if(!identity||affected===null){observations.push({dep:p,cveId:record.id,status:'unknown',reason:!identity?'Vendor package origin is not established.':'Upstream version range cannot be evaluated.',evidence});continue;}
33
+ const current=ver(upstream),fix=(record.good||'').split(',').map(s=>s.trim()).map(s=>/^(\d+\.\d+\.\d+)\+$/.exec(s)?.[1]).filter(Boolean).filter(s=>{const v=ver(s);return v[0]===current[0]&&v[1]===current[1]&&cmp(v,current)>0;}).sort((a,b)=>cmp(ver(a),ver(b)))[0]||null;
34
+ matches.push({dep:{...p,packageOrigin:identity},source:SOURCE,advisoryId:record.id,cve:{id:record.id,summary:record.title,description:record.title,severity:'UNKNOWN',fixVersion:fix,advisorySource:record.advisory,vendorEvidence:evidence}});
35
+ }}
36
+ return {matches,observations,coverage:[{source:SOURCE,execution:snapshot.stale||warnings.length?'partial':'completed',result:'consulted',scope:'upstream-nginx-version',fetchedAt:snapshot.observedAt,sha256:snapshot.sha256,reason:'Version applicability is assessed from vendor declarations; runtime configuration and package signature remain unverified.'}],warnings};
37
+ }
38
+ function nginxPackageOrigin(pkg,options={}){if(pkg?.manager!=='dpkg'||pkg.sourceName!=='nginx')return null;return vendor(pkg,options.allowedMaintainerDomains||['nginx.org','nginx.com','f5.com']);}
39
+ module.exports={SOURCE,URL,nginxPackageOrigin,parseNginxAdvisories,syncNginxAdvisories,assessNginxAdvisories};
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+ // Read-only RPM database storage adapters. On-disk structures are based on
3
+ // rpm/lib/backend/ndb/rpmpkg.c and Berkeley DB dbinc/db_page.h.
4
+ const fs = require('node:fs');
5
+ const DEFAULT_LIMITS = Object.freeze({ maxDatabaseBytes: 8 * 1024 ** 3, maxHeaderBytes: 64 * 1024 ** 2, maxPackages: 1000000, maxPages: 2000000 });
6
+ const DIRS = ['/usr/lib/sysimage/rpm', '/var/lib/rpm'];
7
+ function adler32(buffer) { let a=1,b=0; for(let i=0;i<buffer.length;i++) {a=(a+buffer[i])%65521;b=(b+a)%65521;} return ((b<<16)|a)>>>0; }
8
+ function read(fd, start, length, size) {
9
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(length) || start < 0 || length < 0 || start+length > size) throw Error('truncated RPM database');
10
+ const b=Buffer.alloc(length);let at=0;while(at<length){const n=fs.readSync(fd,b,at,length-at,start+at);if(!n)throw Error('truncated RPM database');at+=n;}return b;
11
+ }
12
+ function readNdb(file, { limits, onBlob }) {
13
+ const fd=fs.openSync(file,'r'); try {
14
+ const size=fs.fstatSync(fd).size;if(size>limits.maxDatabaseBytes || size%16)throw Error('invalid or oversized RPM NDB');
15
+ const head=read(fd,0,32,size);if(head.toString('ascii',0,4)!=='RpmP' || head.readUInt32LE(4)!==0)throw Error('unsupported RPM NDB header');
16
+ const pages=head.readUInt32LE(12);if(!pages || pages>limits.maxPages || pages*4096>size)throw Error('invalid RPM NDB slot pages');
17
+ const slots=[],ids=new Set();
18
+ for(let page=0;page<pages;page++) {
19
+ const b=read(fd,page*4096,4096,size);
20
+ for(let off=page===0?32:0;off<4096;off+=16) {
21
+ if(b.toString('ascii',off,off+4)!=='Slot')throw Error('invalid RPM NDB slot');
22
+ const id=b.readUInt32LE(off+4),start=b.readUInt32LE(off+8),count=b.readUInt32LE(off+12);if(!start)continue;
23
+ if(!id||!count||start<pages*256||(start+count)*16>size||ids.has(id))throw Error('invalid RPM NDB slot bounds');
24
+ ids.add(id);slots.push({id,start,count});if(slots.length>limits.maxPackages)throw Error('RPM package count limit exceeded');
25
+ }
26
+ }
27
+ const ordered=[...slots].sort((a,b)=>a.start-b.start);for(let i=1;i<ordered.length;i++)if(ordered[i].start<ordered[i-1].start+ordered[i-1].count)throw Error('overlapping RPM NDB blobs');
28
+ for(const slot of slots) {
29
+ const len=slot.count*16;if(len>limits.maxHeaderBytes+32)throw Error('RPM header exceeds configured limit');
30
+ const b=read(fd,slot.start*16,len,size),bodySize=b.readUInt32LE(12),tail=len-12;
31
+ if(b.toString('ascii',0,4)!=='BlbS'||b.readUInt32LE(4)!==slot.id||Math.ceil((16+bodySize+12)/16)!==slot.count||b.toString('ascii',tail+8,tail+12)!=='BlbE'||b.readUInt32LE(tail+4)!==bodySize||b.readUInt32LE(tail)!==adler32(b.subarray(0,tail)))throw Error('invalid RPM NDB blob or checksum');
32
+ onBlob(b.subarray(16,16+bodySize));
33
+ }
34
+ } finally {fs.closeSync(fd);}
35
+ }
36
+ function readBdb(file, { limits, onBlob }) {
37
+ const fd=fs.openSync(file,'r');try {
38
+ const size=fs.fstatSync(fd).size;if(size>limits.maxDatabaseBytes)throw Error('RPM Berkeley DB exceeds configured limit');
39
+ const meta=read(fd,0,512,size);let le;
40
+ if(meta.readUInt32LE(12)===0x00061561)le=true;else if(meta.readUInt32BE(12)===0x00061561)le=false;else throw Error('unsupported RPM Berkeley DB format');
41
+ const u32=(b,o)=>le?b.readUInt32LE(o):b.readUInt32BE(o),u16=(b,o)=>le?b.readUInt16LE(o):b.readUInt16BE(o);
42
+ const version=u32(meta,16),pageSize=u32(meta,20),last=u32(meta,32);
43
+ if(meta[24] || meta[25]!==8 || version<7 || version>9 || pageSize<512 || pageSize>65536 || (pageSize&(pageSize-1)) || last>=limits.maxPages || (last+1)*pageSize>size)throw Error('unsupported or invalid RPM Berkeley DB metadata');
44
+ const page=n=>{if(n>last)throw Error('RPM Berkeley DB page out of bounds');return read(fd,n*pageSize,pageSize,size);};
45
+ let seen=0;
46
+ for(let n=1;n<=last;n++) {
47
+ const b=page(n),type=b[25];if(type!==2 && type!==13)continue;
48
+ const count=u16(b,20);if(count%2 || 26+count*2>pageSize)throw Error('invalid RPM Berkeley DB hash page');
49
+ const offsets=[];for(let i=0;i<count;i++){const o=u16(b,26+i*2);if(o<26+count*2||o>=pageSize)throw Error('invalid RPM Berkeley DB item offset');offsets.push(o);}
50
+ for(let i=1;i<count;i+=2){
51
+ // RPM reserves integer key zero for its next-header-number counter.
52
+ const key=offsets[i-1];
53
+ if(b[key]===1 && key+5<=pageSize && u32(b,key+1)===0) continue;
54
+ const off=offsets[i],kind=b[off];let data;
55
+ if(kind===3){
56
+ if(off+12>pageSize)throw Error('invalid RPM Berkeley DB overflow item');let next=u32(b,off+4);const length=u32(b,off+8),parts=[];let actual=0;const visited=new Set();
57
+ if(length>limits.maxHeaderBytes)throw Error('RPM header exceeds configured limit');
58
+ while(next){if(visited.has(next)||visited.size>=limits.maxPages)throw Error('RPM Berkeley DB overflow cycle');visited.add(next);const part=page(next);if(part[25]!==7)throw Error('invalid RPM Berkeley DB overflow page');const nextPage=u32(part,16),available=nextPage?pageSize-26:u16(part,22);if(available>pageSize-26 || actual+available>length)throw Error('invalid RPM Berkeley DB overflow length');parts.push(part.subarray(26,26+available));actual+=available;next=nextPage;}
59
+ if(actual!==length)throw Error('truncated RPM Berkeley DB overflow item');data=Buffer.concat(parts,actual);
60
+ } else if(kind===1){
61
+ const end=Math.min(pageSize,...offsets.filter(x=>x>off));data=b.subarray(off+1,end);if(data.length>limits.maxHeaderBytes)throw Error('RPM header exceeds configured limit');
62
+ } else throw Error(`unsupported RPM Berkeley DB item type ${kind}`);
63
+ if(++seen>limits.maxPackages)throw Error('RPM package count limit exceeded');onBlob(data);
64
+ }
65
+ }
66
+ }finally{fs.closeSync(fd);}
67
+ }
68
+ const adapters = [
69
+ {id:'sqlite', filename:'rpmdb.sqlite', read(file,ctx,onBlob) {if(fs.statSync(file).size>ctx.limits.maxDatabaseBytes)throw Error('RPM SQLite exceeds configured limit');const db=ctx.openSqlite(file,{readonly:true});try{const stmt=db.prepare(`SELECT blob FROM Packages LIMIT ${ctx.limits.maxPackages + 1}`), rows=typeof stmt.iterate==='function'?stmt.iterate():stmt.all();let n=0;for(const row of rows){if(++n>ctx.limits.maxPackages||row.blob.length>ctx.limits.maxHeaderBytes)throw Error('RPM SQLite resource limit exceeded');onBlob(row.blob);}}finally{db.close();}}},
70
+ {id:'ndb', filename:'Packages.db', read(file,ctx,onBlob) {readNdb(file,{limits:ctx.limits,onBlob});}},
71
+ {id:'bdb', filename:'Packages', read(file,ctx,onBlob) {readBdb(file,{limits:ctx.limits,onBlob});}},
72
+ ];
73
+ async function readRpmStorage(root, options) {
74
+ const limits={...DEFAULT_LIMITS,...options.limits};for(const [k,v] of Object.entries(limits))if(!Number.isSafeInteger(v)||v<1)throw Error(`invalid RPM storage limit ${k}`);
75
+ const ctx={...options,limits}, available=options.rpmStorageAdapters || adapters, ids=new Set();
76
+ for(const a of available){if(!a||!a.id||ids.has(a.id)||typeof a.read!=='function'||(!a.filename&&typeof a.probe!=='function'))throw Error('invalid RPM storage adapter');ids.add(a.id);}
77
+ for(const dir of DIRS)for(const adapter of available){
78
+ const manifestPath=adapter.filename ? `${dir}/${adapter.filename}` : null;
79
+ const file=adapter.probe ? await adapter.probe(root,ctx,dir) : options.safeFile(root,manifestPath);if(!file)continue;
80
+ const packages=[],warnings=[];let reason;
81
+ try {await adapter.read(file,ctx,blob=>{try{const header=options.rpmHeader(blob);packages.push({...header,manifestPath});if(header.ownershipIncomplete)warnings.push(`RPM ${adapter.id}: package file ownership incomplete`);}catch(e){warnings.push(`RPM header: ${e.message}`);}});}catch(e){reason=e.message;warnings.push(`RPM ${adapter.id}: ${e.message}`);}
82
+ return {packages,coverage:{collector:'rpm',backend:adapter.id,status:reason||warnings.length?'incomplete':'complete',count:packages.length,...(reason?{reason}: {})},warnings};
83
+ }
84
+ return null;
85
+ }
86
+ module.exports={readRpmStorage,readNdb,readBdb,adapters,DEFAULT_LIMITS};
@@ -0,0 +1,70 @@
1
+ 'use strict';
2
+ // Targeted consultations preserve an observation per exact distro/name/version;
3
+ // they never claim the whole distribution corpus was imported.
4
+ const crypto=require('node:crypto');
5
+ const {scope,assessSystemInventory}=require('./advisories');
6
+ const {createCacheRepository}=require('../cache-repository');
7
+ const {getResource}=require('../providers');
8
+ const idOk=id=>typeof id==='string' && /^[A-Za-z0-9][A-Za-z0-9._:+-]{0,255}$/.test(id);
9
+ const key=q=>crypto.createHash('sha256').update(JSON.stringify(q)).digest('hex');
10
+ const observed=response=>{
11
+ const stamp=Date.parse(response.headers?.get?.('x-fad-proxy-fetched-at')||'');
12
+ const proxy=require('../providers').hasProxyRoute();
13
+ return {fetchedAt:Number.isFinite(stamp)&&stamp>0&&stamp<=Date.now()+300000?stamp:proxy?1:Date.now(),stale:response.headers?.get?.('x-fad-proxy')==='stale' || (proxy&&!Number.isFinite(stamp))};
14
+ };
15
+ async function assessTargetedSystemInventory(inventory,opts={}){
16
+ const s=scope(inventory.distribution,opts),matches=[],warnings=[];
17
+ if(!s)return {matches,coverage:[{source:'system-osv-targeted',status:'unknown',reason:'unsupported or missing distribution identity'}],warnings};
18
+ const repo=opts.repository || createCacheRepository(opts.cacheDir),ns='system-osv-query:'+s.ecosystem,items=[],unique=new Map();let unknown=0;
19
+ for(const dep of inventory.packages||[]){
20
+ const source=dep.manager==='dpkg'||dep.manager==='apk';
21
+ const name=source?dep.sourceName:dep.name,version=source?dep.sourceVersion:dep.version;
22
+ if(!name||!version||s.compare(version,version)!==0){unknown++;continue;}
23
+ const query={ecosystem:s.ecosystem,name,version},k=key(query);items.push({dep,query,k});if(!unique.has(k))unique.set(k,query);
24
+ }
25
+ const pending=[...unique].filter(([k])=>{const entry=repo.get(ns,k);return !opts.offline && (!entry || entry.stale || Date.now()-entry.fetchedAt>=require('../cache-policy').DEFAULT_TTL_MS || opts.refresh);});
26
+ let error=null;
27
+ if(pending.length){
28
+ try{
29
+ for(let start=0;start<pending.length;start+=500){
30
+ const batch=pending.slice(start,start+500),states=batch.map(([k,query])=>({k,query,ids:[],seen:new Set(),fetchedAt:Date.now(),stale:false}));let active=states;
31
+ while(active.length){
32
+ const response=await getResource('osv','packages',{queries:active.map(x=>({...x.query,...(x.page?{page_token:x.page}:{})}))},{fetcher:opts.fetcher,forceRefresh:true,signal:opts.signal});
33
+ if(!response.ok)throw Error(`OSV query HTTP ${response.status}`);
34
+ const stamp=observed(response),body=await response.json();if(!Array.isArray(body?.results)||body.results.length!==active.length)throw Error('OSV query result incomplete');
35
+ const next=[];
36
+ for(let i=0;i<active.length;i++){
37
+ const state=active[i],row=body.results[i];state.fetchedAt=Math.min(state.fetchedAt,stamp.fetchedAt);state.stale ||= stamp.stale;
38
+ if(!row||typeof row!=='object'||Array.isArray(row)||row.error||(row.vulns!==undefined&&(!Array.isArray(row.vulns)||!row.vulns.every(v=>idOk(v?.id)))))throw Error('OSV query result invalid');
39
+ state.ids.push(...(row.vulns||[]).map(v=>v.id));
40
+ if(row.next_page_token!==undefined && typeof row.next_page_token!=='string')throw Error('OSV pagination invalid');
41
+ if(row.next_page_token){if(state.seen.has(row.next_page_token)||state.seen.size>=1000)throw Error('OSV pagination invalid');state.seen.add(row.next_page_token);state.page=row.next_page_token;next.push(state);}
42
+ }
43
+ active=next;
44
+ }
45
+ const ids=[...new Set(states.flatMap(x=>x.ids))],docs=new Map();
46
+ for(let i=0;i<ids.length;i+=10)await Promise.all(ids.slice(i,i+10).map(async id=>{
47
+ const response=await getResource('osv','vuln',{id},{fetcher:opts.fetcher,forceRefresh:true,signal:opts.signal});if(!response.ok)throw Error(`OSV advisory HTTP ${response.status}`);
48
+ const doc=await response.json();if(doc?.id!==id || !Array.isArray(doc.affected))throw Error('OSV advisory detail invalid');docs.set(id,{doc,...observed(response)});
49
+ }));
50
+ for(const state of states){
51
+ const selected=[...new Set(state.ids)].map(id=>docs.get(id));
52
+ if(selected.some(x=>!x.doc.affected.some(a=>a?.package?.ecosystem===state.query.ecosystem && a?.package?.name===state.query.name)))throw Error('OSV detail does not match consulted package');
53
+ const fetchedAt=Math.min(state.fetchedAt,...selected.map(x=>x.fetchedAt));const stale=state.stale||selected.some(x=>x.stale);
54
+ repo.put(ns,state.k,{query:state.query,records:selected.map(x=>x.doc),complete:true},{fetchedAt,stale});
55
+ }
56
+ }
57
+ }catch(e){error=e.message;warnings.push(`System OSV targeted consultation failed: ${error}`);}
58
+ }
59
+ for(const item of items){
60
+ const entry=repo.get(ns,item.k);
61
+ if(!entry || !entry.value?.complete || JSON.stringify(entry.value.query)!==JSON.stringify(item.query)){unknown++;continue;}
62
+ if(entry.stale || (!opts.offline && Date.now()-entry.fetchedAt>require('../cache-policy').DEFAULT_TTL_MS))warnings.push('System OSV targeted consultation is stale');
63
+ const queryDep={...item.dep,version:item.query.version};
64
+ const result=await assessSystemInventory({distribution:inventory.distribution,packages:[queryDep]},{...opts,records:entry.value.records,complete:true});
65
+ matches.push(...result.matches.map(match=>({...match,dep:item.dep})));unknown+=result.coverage[0]?.unknown||0;
66
+ }
67
+ const incomplete=unknown>0 || !!error || warnings.length>0;
68
+ return {matches,coverage:[{source:'system-osv-targeted',ecosystem:s.ecosystem,status:incomplete?'incomplete':'complete',result:incomplete?'indeterminate':matches.length?'affected':'no-match',scope:'consulted-package-versions',consulted:items.length,unknown}],warnings:[...new Set(warnings)]};
69
+ }
70
+ module.exports={assessTargetedSystemInventory};
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+ const sign = n => n < 0 ? -1 : n > 0 ? 1 : 0;
3
+ function number(a,b) {a=(a||'0').replace(/^0+/,'')||'0';b=(b||'0').replace(/^0+/,'')||'0';return sign(a.length-b.length)||sign(a.localeCompare(b,'en'));}
4
+ function debPart(a,b) {
5
+ let i=0,j=0;
6
+ const ord=c=>!c ? 0 : c==='~' ? -1 : /[A-Za-z]/.test(c) ? c.charCodeAt(0) : c.charCodeAt(0)+256;
7
+ while(i<a.length || j<b.length) {
8
+ while((i<a.length&&!/\d/.test(a[i])) || (j<b.length&&!/\d/.test(b[j]))) {
9
+ const x=i<a.length&&!/\d/.test(a[i])?a[i]:'';const y=j<b.length&&!/\d/.test(b[j])?b[j]:'';
10
+ const c=sign(ord(x)-ord(y));if(c)return c;if(x)i++;if(y)j++;
11
+ }
12
+ const x=(a.slice(i).match(/^\d+/)||[''])[0],y=(b.slice(j).match(/^\d+/)||[''])[0];
13
+ const c=number(x,y);if(c)return c;i+=x.length;j+=y.length;
14
+ }
15
+ return 0;
16
+ }
17
+ function splitDeb(v){const m=String(v).match(/^(?:(\d+):)?([A-Za-z0-9.+:~\-]+?)(?:-([A-Za-z0-9+.~]+))?$/);return m&&[m[1]||'0',m[2],m[3]||'0'];}
18
+ function debian(a,b) {a=splitDeb(a);b=splitDeb(b);return a&&b ? number(a[0],b[0])||debPart(a[1],b[1])||debPart(a[2],b[2]) : null;}
19
+ function rpmPart(a,b) {
20
+ let i=0,j=0;
21
+ while(i<a.length || j<b.length) {
22
+ while(i<a.length && !/[A-Za-z0-9~^]/.test(a[i]))i++;
23
+ while(j<b.length && !/[A-Za-z0-9~^]/.test(b[j]))j++;
24
+ if(a[i]==='~'||b[j]==='~'){if(a[i]!=='~')return 1;if(b[j]!=='~')return -1;i++;j++;continue;}
25
+ if(a[i]==='^'||b[j]==='^'){if(i>=a.length)return -1;if(j>=b.length)return 1;if(a[i]!=='^')return 1;if(b[j]!=='^')return -1;i++;j++;continue;}
26
+ if(i>=a.length || j>=b.length)break;
27
+ const dig=/\d/.test(a[i]), x=(a.slice(i).match(dig?/^\d+/:/^[A-Za-z]+/)||[''])[0],y=(b.slice(j).match(dig?/^\d+/:/^[A-Za-z]+/)||[''])[0];
28
+ if(!y)return dig?1:-1;
29
+ const c=dig?number(x,y):sign(x<y?-1:x>y?1:0);if(c)return c;i+=x.length;j+=y.length;
30
+ }
31
+ return sign((i<a.length?1:0)-(j<b.length?1:0));
32
+ }
33
+ function rpm(a,b) {
34
+ const parse=v=>String(v).match(/^(?:(\d+):)?([A-Za-z0-9._+~^]+)(?:-([A-Za-z0-9._+~^]+))?$/);
35
+ a=parse(a);b=parse(b);return a&&b ? number(a[1],b[1])||rpmPart(a[2],b[2])||rpmPart(a[3]||'',b[3]||'') : null;
36
+ }
37
+ function apk(a,b) {
38
+ const parse=v=>{
39
+ const m=String(v).match(/^(\d+(?:\.\d+)*)([a-z]?)((?:_(?:alpha|beta|pre|rc|cvs|svn|git|hg|p)\d*)*)(?:-r(\d+))?$/);
40
+ if(!m)return null;
41
+ const tokens=m[1].split('.').map((value,i)=>({type:i?1:0,value}));
42
+ if(m[2])tokens.push({type:2,value:m[2]});
43
+ for(const sm of m[3].matchAll(/_(alpha|beta|pre|rc|cvs|svn|git|hg|p)(\d*)/g)){tokens.push({type:3,value:sm[1]});if(sm[2])tokens.push({type:4,value:sm[2]});}
44
+ if(m[4]!==undefined)tokens.push({type:6,value:m[4]});
45
+ tokens.push({type:7,value:''});return tokens;
46
+ };
47
+ a=parse(a);b=parse(b);if(!a||!b)return null;
48
+ const rank={alpha:-4,beta:-3,pre:-2,rc:-1,cvs:1,svn:2,git:3,hg:4,p:5};let i=0;
49
+ while(a[i].type===b[i].type && a[i].type!==7){const x=a[i],y=b[i];let c;
50
+ if(x.type===3)c=sign(rank[x.value]-rank[y.value]);
51
+ else if(x.type===2 || (x.type===1 && (x.value[0]==='0'||y.value[0]==='0')))c=sign(x.value<y.value?-1:x.value>y.value?1:0);
52
+ else c=number(x.value,y.value);
53
+ if(c)return c;i++;
54
+ }
55
+ const x=a[i],y=b[i];if(x.type===y.type)return 0;
56
+ if(x.type===3 && rank[x.value]<0)return -1;if(y.type===3 && rank[y.value]<0)return 1;
57
+ return x.type>y.type?-1:1;
58
+ }
59
+ module.exports={debian,rpm,apk};
package/lib/transitive.js CHANGED
@@ -214,7 +214,7 @@ async function effectivePom(g, a, v, opts = {}, seen = new Set()) {
214
214
  const ovKeys = opts.propertyOverrides ? Object.keys(opts.propertyOverrides) : [];
215
215
  const ovSuffix = ovKeys.length ? "|ov:" + ovKeys.sort().map(k => `${k}=${opts.propertyOverrides[k]}`).join(",") : "";
216
216
  const key = `${g}:${a}:${v}${ovSuffix}`;
217
- if (seen.has(key)) return null;
217
+ if (seen.has(key)) { opts.onPomCycle?.({ groupId: g, artifactId: a, version: v }); return null; }
218
218
  // Opt-in cross-call memo (used by the per-module overlay, which resolves the
219
219
  // same shared parents/BOMs once per module). Immutable POMs → the effective
220
220
  // result for a g:a:v is stable, so caching the finished object is safe; callers
@@ -419,7 +419,7 @@ async function resolveTransitiveDeps(directDeps, opts = {}) {
419
419
  repos, // optional repo list (lib/maven-repo). Falls back to repo1.maven.org alone.
420
420
  effCache,
421
421
  } = opts;
422
- const fetchOpts = { verbose, offline, fetcher, cacheDir, repos, ...(effCache ? { effCache } : {}), ...(opts.onMissingPom ? { onMissingPom: opts.onMissingPom } : {}) };
422
+ const fetchOpts = { verbose, offline, fetcher, cacheDir, repos, ...(effCache ? { effCache } : {}), ...(opts.onMissingPom ? { onMissingPom: opts.onMissingPom } : {}), ...(opts.onPomCycle ? { onPomCycle: opts.onPomCycle } : {}) };
423
423
 
424
424
  // A managed entry is `{ version, exclusions? }` (global pass) or a bare version string
425
425
  // (per-module management). Reading `.version` off a string gave
@@ -452,6 +452,7 @@ async function resolveTransitiveDeps(directDeps, opts = {}) {
452
452
  const v = await concrete(dep.groupId, dep.artifactId, dep.version);
453
453
  if (!v) continue;
454
454
  noteVariant(dep);
455
+ opts.onGraphRequest?.({ key: `${dep.groupId}:${dep.artifactId}`, version: v });
455
456
  level.push({
456
457
  groupId: dep.groupId, artifactId: dep.artifactId, version: v,
457
458
  scope: dep.scope || "compile", depth: 0, via: [],
@@ -494,6 +495,7 @@ async function resolveTransitiveDeps(directDeps, opts = {}) {
494
495
  // not on, with a CRITICAL.
495
496
  const own = mgmt.get(managedKey(dep));
496
497
  const depScope = dep.scopeDeclared === false && own?.scope && own.scope !== "import" ? own.scope : (dep.scope || "compile");
498
+ if (opts.runtimeDependencies === false && depScope === "runtime") continue;
497
499
  const depExclusions = (dep.exclusions && dep.exclusions.length) ? dep.exclusions : (own?.exclusions || []);
498
500
 
499
501
  const propagated = SCOPE_MATRIX[node.scope]?.[depScope];
@@ -501,6 +503,13 @@ async function resolveTransitiveDeps(directDeps, opts = {}) {
501
503
  noteVariant(dep);
502
504
 
503
505
  const via = [...node.via, nodeKey];
506
+ opts.onGraphRequest?.({ key: childKey, version: dep.version || own?.version || null });
507
+ // Optional evidence for Gradle's versionless declarations. Observe every
508
+ // requested version, including losing paths, without changing Maven mediation.
509
+ if (opts.versionRequestKeys?.has(childKey) && opts.onVersionRequest) {
510
+ const requested = dep.version || own?.version;
511
+ if (requested) opts.onVersionRequest({ key: childKey, version: /^\d[\w.\-]*$/.test(requested) ? requested : null, via });
512
+ }
504
513
  if (visited.has(childKey)) {
505
514
  // Already mediated (nearer, or same depth and declared earlier): the winner
506
515
  // keeps its version. Record the alternate chain; widen the scope if needed.
package/lib/ui.js CHANGED
@@ -62,13 +62,16 @@ function kv(label, value, { pad = 10 } = {}) {
62
62
  * so clear it first; its next tick redraws itself below. Used for retry notices, which must
63
63
  * survive in a CI log rather than flicker past inside the spinner's live suffix.
64
64
  */
65
- function interject(msg) {
66
- if (isTTY) process.stdout.write("\r\x1b[K");
67
- console.log(msg);
65
+ function interject(msg, {stream = process.stdout} = {}) {
66
+ if (isTTY) process.stdout.write("\r\x1b[2K");
67
+ stream.write(String(msg) + "\n");
68
+ if (isTTY) process.stdout.write("\r\x1b[2K");
68
69
  }
69
70
 
71
+ function networkNotice(msg) { interject(msg, {stream:process.stderr}); }
72
+
70
73
  function ok(msg) { console.log(" " + chalk.green("✓") + " " + msg); }
71
- function warn(msg) { console.log(" " + chalk.yellow("⚠") + " " + msg); }
74
+ function warn(msg) { interject(" " + chalk.yellow("⚠") + " " + msg); }
72
75
  function info(msg) { console.log(" " + chalk.dim("·") + " " + msg); }
73
76
 
74
77
  function sevColor(sev) {
@@ -148,4 +151,4 @@ class Progress {
148
151
  }
149
152
  }
150
153
 
151
- module.exports = { banner, section, kv, ok, warn, info, interject, sevColor, Progress, shouldBeat, HEARTBEAT_MS, isTTY, TITLE_A, TITLE_B };
154
+ module.exports = { banner, section, kv, ok, warn, info, interject, networkNotice, sevColor, Progress, shouldBeat, HEARTBEAT_MS, isTTY, TITLE_A, TITLE_B };
package/lib/unmanaged.js CHANGED
@@ -60,7 +60,7 @@ function nameMatches(declared, identityName) {
60
60
  function buildInventory(resolved) {
61
61
  const out = [];
62
62
  for (const d of resolved.values()) {
63
- if (!d.hashes || !(d.provenance === "binary" || d.provenance === "embedded")) continue;
63
+ if (!d.hashes || !(d.provenance === "binary" || d.provenance === "embedded") || (d.artifactTargetId && d.osPackageOwners?.length)) continue;
64
64
  const identity = d.identity || null;
65
65
  out.push({
66
66
  path: d.manifestPaths?.[0] || d.declaredName || null,
@@ -10,6 +10,7 @@ const REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships
10
10
  const PKG_REL = "http://schemas.openxmlformats.org/package/2006/relationships";
11
11
  const MAX_ROWS = 1048576;
12
12
  const MAX_CELL = 32767;
13
+ const TRUNCATION_MARKER = "\n… [TRUNCATED: Excel cell limit; export JSON for the full value]";
13
14
 
14
15
  function xml(value) {
15
16
  return String(value ?? "").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g, "")
@@ -30,8 +31,13 @@ function valueCell(value, address, header = false) {
30
31
  if (typeof value === "boolean") return `<c r="${address}"${style} t="b"><v>${value ? 1 : 0}</v></c>`;
31
32
  // Inline strings are never formulas, even for source-controlled text beginning
32
33
  // with =, +, -, or @. This is essential for an audit export opened in Excel.
33
- const raw = (typeof value === "object" ? JSON.stringify(value) : String(value)) ?? "";
34
- if (raw.length > MAX_CELL) throw new Error(`Excel cell ${address} exceeds ${MAX_CELL} characters`);
34
+ let raw = ((typeof value === "object" ? JSON.stringify(value) : String(value)) ?? "").toWellFormed();
35
+ if (raw.length > MAX_CELL) {
36
+ let end = MAX_CELL - TRUNCATION_MARKER.length;
37
+ // Keep supplementary Unicode characters intact at the cut boundary.
38
+ if (/[\uD800-\uDBFF]/.test(raw[end - 1])) end--;
39
+ raw = raw.slice(0, end) + TRUNCATION_MARKER;
40
+ }
35
41
  return `<c r="${address}"${style} t="inlineStr"><is><t xml:space="preserve">${xml(raw)}</t></is></c>`;
36
42
  }
37
43