vigievuln 1.2.1 → 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 (107) hide show
  1. package/CHANGELOG.md +12 -2
  2. package/README.md +10 -4
  3. package/lib/airgap-project.js +35 -7
  4. package/lib/applicability-evidence.js +12 -0
  5. package/lib/artifacts/applications.js +54 -0
  6. package/lib/artifacts/cve-view.js +108 -0
  7. package/lib/artifacts/enrichment.js +86 -0
  8. package/lib/artifacts/go-main-identity.js +45 -0
  9. package/lib/artifacts/go-publisher-advisories.js +24 -0
  10. package/lib/artifacts/index.js +272 -0
  11. package/lib/artifacts/publisher-advisories.js +12 -0
  12. package/lib/artifacts/remediation-report.js +48 -0
  13. package/lib/artifacts/report-inventory.js +26 -0
  14. package/lib/artifacts/report.js +191 -0
  15. package/lib/artifacts/risk-report.js +120 -0
  16. package/lib/artifacts/sbom.js +68 -0
  17. package/lib/artifacts/scan.js +401 -0
  18. package/lib/cache-archive-sqlite.js +41 -25
  19. package/lib/charts.js +124 -32
  20. package/lib/cli-command-routing.js +20 -6
  21. package/lib/cli-groups.js +2 -1
  22. package/lib/cli-image.js +206 -0
  23. package/lib/codecs/binary/elf-metadata.js +42 -0
  24. package/lib/codecs/binary/go-buildinfo.js +37 -0
  25. package/lib/codecs/binary/metadata.js +7 -0
  26. package/lib/codecs/binary/scan.js +14 -13
  27. package/lib/codecs/binary/sniff.js +16 -15
  28. package/lib/codecs/binary.codec.js +22 -2
  29. package/lib/codecs/gradle/parse.js +63 -2
  30. package/lib/codecs/gradle/versionless.js +175 -0
  31. package/lib/codecs/gradle.codec.js +20 -3
  32. package/lib/codecs/index.js +2 -2
  33. package/lib/csaf-export.js +13 -6
  34. package/lib/cve-download.js +33 -29
  35. package/lib/cve-match.js +10 -0
  36. package/lib/cve-packages-proxy.js +19 -0
  37. package/lib/cve-report.js +273 -165
  38. package/lib/deps-descriptor.js +25 -3
  39. package/lib/diagnostics.js +12 -0
  40. package/lib/diff.js +0 -0
  41. package/lib/epss.js +6 -6
  42. package/lib/euvd.js +34 -4
  43. package/lib/finding-enrichment.js +165 -0
  44. package/lib/finding-summary.js +4 -3
  45. package/lib/i18n.js +34 -9
  46. package/lib/image-network.js +54 -0
  47. package/lib/image-references.js +203 -0
  48. package/lib/image-registry.js +385 -0
  49. package/lib/image-update.js +39 -0
  50. package/lib/json-export.js +50 -8
  51. package/lib/kev.js +6 -6
  52. package/lib/maven-bom.js +2 -1
  53. package/lib/merge-sources.js +3 -0
  54. package/lib/native-advisories.js +9 -7
  55. package/lib/native-cna-identities.js +12 -0
  56. package/lib/native-package-match.js +159 -0
  57. package/lib/native-source-prepare.js +60 -0
  58. package/lib/nvd.js +34 -23
  59. package/lib/osv.js +33 -14
  60. package/lib/project-descriptor.js +3 -2
  61. package/lib/provenance.js +8 -2
  62. package/lib/providers/alpine.js +8 -0
  63. package/lib/providers/common.js +11 -3
  64. package/lib/providers/debian.js +11 -0
  65. package/lib/providers/euvd.js +2 -1
  66. package/lib/providers/freexian.js +13 -0
  67. package/lib/providers/github.js +1 -0
  68. package/lib/providers/go.js +2 -1
  69. package/lib/providers/index.js +18 -14
  70. package/lib/providers/nginx.js +5 -0
  71. package/lib/providers/nvd.js +1 -1
  72. package/lib/providers/osv.js +1 -1
  73. package/lib/providers/osvdb.js +2 -2
  74. package/lib/proxy-throttle.js +89 -29
  75. package/lib/purl.js +10 -2
  76. package/lib/record-freshness.js +22 -0
  77. package/lib/report-notices.js +47 -0
  78. package/lib/report-time.js +45 -0
  79. package/lib/request-failure.js +22 -0
  80. package/lib/resource-cache/engine.js +130 -26
  81. package/lib/resource-cache/snapshot-projection.js +33 -0
  82. package/lib/resource-cache/validate.js +22 -5
  83. package/lib/risk-evidence.js +18 -0
  84. package/lib/sarif-export.js +17 -9
  85. package/lib/sbom-export.js +32 -12
  86. package/lib/source-health.js +25 -8
  87. package/lib/source-image-scan.js +57 -0
  88. package/lib/source-profile.js +6 -3
  89. package/lib/system-inventory/advisories.js +169 -0
  90. package/lib/system-inventory/alpine-tracker.js +47 -0
  91. package/lib/system-inventory/collect.js +118 -0
  92. package/lib/system-inventory/current-debian.js +99 -0
  93. package/lib/system-inventory/distribution-sources.js +132 -0
  94. package/lib/system-inventory/freexian-ela.js +32 -0
  95. package/lib/system-inventory/freexian-release-evidence.js +35 -0
  96. package/lib/system-inventory/freexian-tracker.js +72 -0
  97. package/lib/system-inventory/historical-debian.js +196 -0
  98. package/lib/system-inventory/index.js +2 -0
  99. package/lib/system-inventory/nginx-advisories.js +39 -0
  100. package/lib/system-inventory/rpm-storage.js +86 -0
  101. package/lib/system-inventory/targeted.js +70 -0
  102. package/lib/system-inventory/versions.js +59 -0
  103. package/lib/transitive.js +11 -2
  104. package/lib/ui.js +8 -5
  105. package/lib/unmanaged.js +1 -1
  106. package/package.json +12 -3
  107. package/vigievuln.js +204 -95
@@ -0,0 +1,203 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const crypto = require('node:crypto');
6
+ const yaml = require('js-yaml');
7
+ const { makeDirFilter } = require('./path-filter');
8
+
9
+ function resolveVariables(value, variables) {
10
+ const unresolved = new Set();
11
+ const resolved = String(value).replace(/\$\$|\$\{([A-Za-z_][\w]*)(?:(:-|-)([^}]*))?\}|\$([A-Za-z_][\w]*)/g,
12
+ (whole, brace, operator, fallback, bare) => {
13
+ if (whole === '$$') return '$';
14
+ const name = brace || bare, present = Object.hasOwn(variables, name), current = variables[name];
15
+ if (present && !(operator === ':-' && current === '')) return String(current);
16
+ if (operator) return fallback;
17
+ unresolved.add(name); return whole;
18
+ });
19
+ return { reference: resolved, unresolved: [...unresolved] };
20
+ }
21
+
22
+ function classifyImageReference(item) {
23
+ if (item.localBuild) return {...item, classification:'local-build',scanEligible:false,blockReason:'local-build'};
24
+ if (item.unresolved?.length || /\$[{A-Za-z_]/.test(item.reference || '')) return {...item,classification:'unresolved',scanEligible:false,blockReason:'unresolved-variables'};
25
+ if (item.platformInvalid || (item.platform != null && !/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*(?:\/[A-Za-z0-9][A-Za-z0-9._-]*)?$/.test(item.platform))) return {...item,classification:'non-scannable',scanEligible:false,blockReason:'invalid-platform'};
26
+ if (!item.reference || item.reason) return {...item,classification:'non-scannable',scanEligible:false,blockReason:item.reason||'missing-reference'};
27
+ try { require('./image-registry').parseReference(item.reference); return {...item,classification:'registry',scanEligible:true,blockReason:null}; }
28
+ catch { return {...item,classification:'non-scannable',scanEligible:false,blockReason:'invalid-reference'}; }
29
+ }
30
+
31
+ function scalarVariables(value) {
32
+ const out={};if(!value || typeof value!=='object' || Array.isArray(value))return out;
33
+ for(const [name,raw] of Object.entries(value)){const v=raw && typeof raw==='object' && !Array.isArray(raw)?raw.value:raw;if(typeof v==='string'||typeof v==='number'||typeof v==='boolean')out[name]=String(v);}
34
+ return out;
35
+ }
36
+ function resolveExpanded(value, variables) {
37
+ let reference=String(value);for(let i=0;i<16;i++){const next=resolveVariables(reference,variables);if(next.reference===reference)return next;reference=next.reference;}
38
+ const result=resolveVariables(reference,variables);if(result.reference!==reference)return {reference,unresolved:['recursive-variable']};return result;
39
+ }
40
+
41
+ function dockerfileReferences(text, context = {}) {
42
+ const out = [], variables = { ...(context.variables || {}) }, stages = new Set();
43
+ let stage = -1, pending = '', start = 0, escaped = '\\', heredocs = [];
44
+ const lines = text.split(/\r?\n/);
45
+ for (let i = 0; i < lines.length; i++) {
46
+ const line = lines[i];
47
+ if (heredocs.length) {
48
+ const current = heredocs[0], candidate = current.stripTabs ? line.replace(/^\t+/, '') : line;
49
+ if (candidate === current.delimiter) heredocs.shift();
50
+ continue;
51
+ }
52
+ const directive = /^\s*#\s*escape\s*=\s*([`\\])\s*$/i.exec(line);
53
+ if (directive && stage < 0 && !pending) { escaped = directive[1]; continue; }
54
+ if (/^\s*#/.test(line)) continue;
55
+ if (!pending) start = i + 1;
56
+ const trimmed = line.trimEnd(), continued = trimmed.endsWith(escaped);
57
+ pending += (continued ? trimmed.slice(0, -1) : line) + ' ';
58
+ if (continued) continue;
59
+ const instruction = /^\s*(\w+)\s+([\s\S]*?)\s*$/.exec(pending); pending = '';
60
+ if (!instruction) continue;
61
+ const command = instruction[1].toUpperCase(), body = instruction[2];
62
+ if (['RUN', 'COPY', 'ADD'].includes(command)) {
63
+ for (const match of body.matchAll(/<<(-?)\s*(['"]?)([A-Za-z_][\w.-]*)\2/g)) heredocs.push({ delimiter: match[3], stripTabs: !!match[1] });
64
+ }
65
+ if (command === 'ARG' && stage < 0) {
66
+ const arg = /^([A-Za-z_]\w*)(?:=(.*))?$/.exec(body);
67
+ if (arg && !Object.hasOwn(variables, arg[1]) && arg[2] !== undefined) variables[arg[1]] = arg[2].replace(/^(['"])(.*)\1$/, '$2');
68
+ }
69
+ if (command !== 'FROM') continue;
70
+ const from = /^(?:--platform=(\S+)\s+)?(\S+)(?:\s+AS\s+(\S+))?\s*$/i.exec(body);
71
+ if (!from) { out.push(classifyImageReference({ role: 'base', line: start, declared: body, reference: null, unresolved: [], reason: 'unparsed-from' })); continue; }
72
+ stage++;
73
+ const resolved = resolveExpanded(from[2], variables), localStage = stages.has(resolved.reference.toLowerCase());
74
+ const platform = from[1] ? resolveExpanded(from[1], variables) : null;
75
+ if (!localStage && resolved.reference.toLowerCase() !== 'scratch') out.push(classifyImageReference({ ...resolved, declared: from[2], line: start,
76
+ platform: platform?.reference || null, unresolved: [...new Set([...resolved.unresolved, ...(platform?.unresolved || [])])],
77
+ stage, stageName: from[3] || null, role: 'base', finalStage: false }));
78
+ stages.add(String(stage));
79
+ if (from[3]) stages.add(from[3].toLowerCase());
80
+ }
81
+ if (heredocs.length) throw Error('unterminated Dockerfile heredoc');
82
+ for (const item of out) item.finalStage = item.stage === stage;
83
+ return out;
84
+ }
85
+
86
+ function yamlReferences(text, context = {}) {
87
+ const documents = yaml.loadAll(text, undefined, { schema: yaml.JSON_SCHEMA, json: false });
88
+ const out = [], visited = new WeakSet();
89
+ const maxNodes = context.maxNodes ?? 100000;
90
+ let nodes = 0;
91
+ const file=String(context.filePath||'').replace(/\\/g,'/');
92
+ const ci=context.ci === true || /(^|\/)\.gitlab-ci\.ya?ml$/i.test(file) || /(^|\/)\.gitlab\/.*\.ya?ml$/i.test(file) || /(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i.test(file);
93
+ function walk(value, parts, variables, localImages) {
94
+ if (!value || typeof value !== 'object' || visited.has(value)) return;
95
+ if (++nodes > maxNodes || parts.length > 128) throw Error('YAML image discovery exceeds configured traversal limits');
96
+ visited.add(value);
97
+ const scoped=ci && value.variables ? {...variables,...scalarVariables(value.variables),...(context.variables||{})}:variables;
98
+ for (const [key, child] of Object.entries(value)) {
99
+ if(ci && key==='services' && Array.isArray(child)){
100
+ for(let i=0;i<child.length;i++)if(typeof child[i]==='string'){const declared=child[i],resolved=resolveExpanded(declared,scoped);out.push(classifyImageReference({...resolved,declared,location:[...parts,key,String(i)].join('.'),role:'ci',line:null}));}else walk(child[i],[...parts,key,String(i)],scoped,localImages);
101
+ continue;
102
+ }
103
+ const serviceName=ci && key==='name' && parts.includes('services') && typeof child==='string';
104
+ const declared=key==='image'?(typeof child==='string'?child:ci&&child&&typeof child.name==='string'?child.name:null):serviceName?child:null;
105
+ if (declared!==null) {
106
+ const resolved = resolveExpanded(declared, scoped);
107
+ const localBuild=(!ci && Object.hasOwn(value,'build')) || localImages.has(resolved.reference);
108
+ const hasPlatform=!ci && Object.hasOwn(value,'platform'),platform=hasPlatform && typeof value.platform==='string'?resolveExpanded(value.platform,scoped):null;
109
+ out.push(classifyImageReference({ ...resolved, ...(hasPlatform?{platform:platform?.reference ?? null,platformInvalid:!platform,unresolved:[...new Set([...resolved.unresolved,...(platform?.unresolved||[])])]}:{}), declared, location: [...parts, key].join('.'), role: ci?'ci':'deployment', line: null, ...(localBuild?{localBuild:true}:{}) }));
110
+ } else if(key!=='variables') walk(child, [...parts, key],scoped,localImages);
111
+ }
112
+ }
113
+ documents.forEach((doc, index) => {
114
+ const variables={...scalarVariables(ci?doc?.variables:null),...(context.variables||{})},localImages=new Set();
115
+ if(!ci && doc?.services && typeof doc.services==='object')for(const service of Object.values(doc.services))if(service && typeof service==='object' && Object.hasOwn(service,'build') && typeof service.image==='string'){const r=resolveExpanded(service.image,variables);if(!r.unresolved.length)localImages.add(r.reference);}
116
+ walk(doc, [String(index)],variables,localImages);
117
+ });
118
+ return out;
119
+ }
120
+
121
+ const DEFAULT_EXTRACTORS = Object.freeze([
122
+ { id: 'dockerfile', accepts: name => /^(?:dockerfile|containerfile)(?:\..+)?$/i.test(name) || /\.(?:dockerfile|containerfile)$/i.test(name), extract: dockerfileReferences },
123
+ { id: 'yaml-image', accepts: name => /\.ya?ml$/i.test(name), extract: yamlReferences },
124
+ ]);
125
+
126
+ function discoverImageReferences(root, options = {}) {
127
+ const extractors = options.extractors || DEFAULT_EXTRACTORS;
128
+ const ids = new Set();
129
+ for (const extractor of extractors) {
130
+ if (!extractor?.id || ids.has(extractor.id) || typeof extractor.accepts !== 'function' || typeof extractor.extract !== 'function') throw Error('invalid or duplicate image reference extractor');
131
+ ids.add(extractor.id);
132
+ }
133
+ const references = [], warnings = [], stack = [path.resolve(root)];
134
+ const skip = makeDirFilter({ srcRoot: root, defaultSkip: new Set(['.git', 'node_modules', '.venv', 'vendor']),
135
+ excludePath: options.excludePath, useDefaults: options.defaultExcludes !== false });
136
+ while (stack.length) {
137
+ const dir = stack.pop();
138
+ let entries;
139
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
140
+ catch (error) { warnings.push({ type: 'dependency-coverage', reason: 'image-reference-read-error', message: `Cannot inspect image declarations: ${error.message}` }); continue; }
141
+ for (const entry of entries) {
142
+ const file = path.join(dir, entry.name), relative = path.relative(root, file).split(path.sep).join('/');
143
+ if (entry.isDirectory()) { if (!skip(file, entry.name)) stack.push(file); continue; }
144
+ if (!entry.isFile()) continue;
145
+ for (const extractor of extractors) {
146
+ if (!extractor.accepts(entry.name, relative)) continue;
147
+ try {
148
+ if (fs.statSync(file).size > (options.maxFileBytes ?? 8 * 1024 * 1024)) throw Error('declaration exceeds configured size limit');
149
+ const items = extractor.extract(fs.readFileSync(file, 'utf8'), {...options,filePath:relative});
150
+ for (const item of items) {
151
+ const id = 'image-reference:' + crypto.createHash('sha256').update(JSON.stringify([relative, extractor.id, item.line, item.location, item.declared])).digest('hex');
152
+ references.push({ ...classifyImageReference(item), id, path: relative, extractor: extractor.id, evidence: 'reference-only', contentVerified: false });
153
+ }
154
+ } catch (error) {
155
+ warnings.push({ type: 'dependency-coverage', reason: 'image-reference-parse-error', manifestPath: relative,
156
+ message: `Image references could not be fully parsed in ${relative}: ${error.message}` });
157
+ }
158
+ }
159
+ }
160
+ }
161
+ return { references: references.sort((a, b) => a.path.localeCompare(b.path) || (a.line || 0) - (b.line || 0)), warnings };
162
+ }
163
+
164
+ // A mutable tag or a matching file name is not evidence of which image was
165
+ // scanned. Explicit digest references may bind to a selected manifest or its
166
+ // acquired index; keep Dockerfile base-stage role intact.
167
+ function bindImageDefinitions(targets, references) {
168
+ const declarations = references.map(ref => ({ ...ref, boundArtifactIds: [] }));
169
+ for (const target of targets) {
170
+ target.metadata ||= {};
171
+ const previous = Array.isArray(target.metadata.definitions) ? target.metadata.definitions : [];
172
+ const definitions = [...previous];
173
+ const digest = target.metadata.digest;
174
+ const indexDigest = target.metadata.registryEvidence?.digest;
175
+ for (const ref of declarations) {
176
+ if (ref.unresolved?.length || typeof ref.reference !== 'string') continue;
177
+ const match = /@([a-z][a-z0-9]*:[a-f0-9]+)$/.exec(ref.reference);
178
+ if (!match) continue;
179
+ const exact = match[1], binding = exact === digest ? 'manifest-digest' : exact === indexDigest ? 'index-digest' : null;
180
+ if (!binding) continue;
181
+ ref.boundArtifactIds.push(target.id);
182
+ if (!definitions.some(item => item.id === ref.id && item.digest === exact)) definitions.push({
183
+ id: ref.id, path: ref.path, line: ref.line ?? null, location: ref.location ?? null,
184
+ declared: ref.declared, reference: ref.reference, role: ref.role,
185
+ stage: ref.stage ?? null, stageName: ref.stageName ?? null, finalStage: ref.finalStage ?? null,
186
+ digest: exact, binding,
187
+ });
188
+ }
189
+ target.metadata.definitions = definitions;
190
+ }
191
+ for (const target of targets) target.metadata.declarations = declarations.map(ref => ({ ...ref, boundArtifactIds: [...ref.boundArtifactIds] }));
192
+ return declarations;
193
+ }
194
+
195
+ function referenceWarnings(references) {
196
+ return references.map(reference => ({ type: 'dependency-coverage', reason: 'image-content-unverified', severity: 'info',
197
+ capability: 'inventory', artifactId: reference.id, manifestPath: reference.path,
198
+ message: `${reference.path}${reference.line ? ':' + reference.line : ''}: image ${reference.declared} — reference only; image content not verified.` +
199
+ (reference.unresolved?.length ? ` Unresolved variables: ${reference.unresolved.join(', ')}.` : '') +
200
+ (reference.role === 'base' ? ' A Dockerfile base is not evidence of the final built image.' : '') }));
201
+ }
202
+
203
+ module.exports = { discoverImageReferences, referenceWarnings, bindImageDefinitions, dockerfileReferences, yamlReferences, resolveVariables, classifyImageReference, DEFAULT_EXTRACTORS };
@@ -0,0 +1,385 @@
1
+ 'use strict';
2
+
3
+ // OCI transport only: no image execution, Docker client or credential helper.
4
+ const fs = require('node:fs');
5
+ const path = require('node:path');
6
+ const os = require('node:os');
7
+ const crypto = require('node:crypto');
8
+ const { Readable, Transform } = require('node:stream');
9
+ const { pipeline } = require('node:stream/promises');
10
+
11
+ const ACCEPT = [
12
+ 'application/vnd.oci.image.index.v1+json', 'application/vnd.oci.image.manifest.v1+json',
13
+ 'application/vnd.docker.distribution.manifest.list.v2+json', 'application/vnd.docker.distribution.manifest.v2+json',
14
+ ].join(', ');
15
+ const DEFAULT_LIMITS = Object.freeze({ metadataBytes: 16 * 1024 * 1024, blobBytes: 8 * 1024 ** 3,
16
+ totalBytes: 32 * 1024 ** 3, descriptors: 100000, depth: 16, timeoutMs: 120000, redirects: 5 });
17
+
18
+ function parseReference(value) {
19
+ const input = String(value || '').replace(/^docker:\/\//, '');
20
+ if (!input || /[\s?#\\]/.test(input) || input.includes('://')) throw Error('invalid image reference');
21
+ const at = input.indexOf('@');
22
+ let name = at < 0 ? input : input.slice(0, at);
23
+ let reference = at < 0 ? null : input.slice(at + 1);
24
+ if (at >= 0 && !reference) throw Error('invalid image digest');
25
+ if (reference) { if (!/^[a-z0-9]+:[a-f0-9]+$/.test(reference)) throw Error('invalid image digest'); digestParts(reference); }
26
+ const colon = name.lastIndexOf(':');
27
+ if (colon > name.lastIndexOf('/')) {
28
+ const tag = name.slice(colon + 1);
29
+ if (!/^[\w][\w.-]{0,127}$/.test(tag)) throw Error('invalid image tag');
30
+ if (!reference) reference = tag;
31
+ name = name.slice(0, colon);
32
+ }
33
+ const parts = name.split('/');
34
+ const explicitRegistry = parts.length > 1 && (/[.:]/.test(parts[0]) || parts[0] === 'localhost');
35
+ let registry = explicitRegistry ? parts.shift() : 'registry-1.docker.io';
36
+ if (registry === 'docker.io' || registry === 'index.docker.io') registry = 'registry-1.docker.io';
37
+ if (registry === 'registry-1.docker.io' && parts.length === 1) parts.unshift('library');
38
+ if (!parts.length || parts.some(p => !/^[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*$/.test(p))) throw Error('invalid image repository');
39
+ const host = new URL(`https://${registry}`);
40
+ if (host.username || host.password || host.pathname !== '/' || !host.hostname) throw Error('invalid registry host');
41
+ return { registry, repository: parts.join('/'), reference: reference || 'latest', original: input };
42
+ }
43
+
44
+ function digestParts(digest) {
45
+ const match = /^([a-z0-9]+):([a-f0-9]+)$/.exec(String(digest));
46
+ if (!match || match[1] !== 'sha256') throw Error('unsupported image digest algorithm');
47
+ const size = crypto.createHash(match[1]).digest().length * 2;
48
+ if (match[2].length !== size) throw Error('invalid image digest length');
49
+ return { algorithm: match[1], hex: match[2] };
50
+ }
51
+
52
+ async function readBounded(response, limit) {
53
+ const chunks = []; let size = 0;
54
+ if (!response.body) throw Error('empty registry response');
55
+ for await (const chunk of response.body) {
56
+ size += chunk.length;
57
+ if (size > limit) throw Error('registry metadata exceeds configured limit');
58
+ chunks.push(Buffer.from(chunk));
59
+ }
60
+ return Buffer.concat(chunks);
61
+ }
62
+
63
+ function bearerChallenge(header) {
64
+ if (!/^Bearer\s/i.test(header || '')) return null;
65
+ const fields = {};
66
+ for (const match of header.matchAll(/([\w]+)="((?:[^"\\]|\\.)*)"/g)) fields[match[1].toLowerCase()] = match[2].replace(/\\(.)/g, '$1');
67
+ if (!fields.realm) throw Error('registry Bearer challenge has no realm');
68
+ return fields;
69
+ }
70
+
71
+ function createRegistryTransport(ref, options, limits) {
72
+ const origin = `${options.insecure ? 'http' : 'https'}://${ref.registry}`;
73
+ const base = `${origin}/v2/${ref.repository}`;
74
+ const fetcher = options.fetcher || globalThis.fetch;
75
+ let authorization = options.credentials?.token ? `Bearer ${options.credentials.token}` : null;
76
+ const basic = options.credentials?.username !== undefined
77
+ ? 'Basic ' + Buffer.from(`${options.credentials.username}:${options.credentials.password || ''}`).toString('base64') : null;
78
+ async function request(url, headers = {}) {
79
+ let current = new URL(url), requestHeaders = { ...headers };
80
+ for (let count = 0; count <= limits.redirects; count++) {
81
+ let response;
82
+ try { response = await fetcher(current.href, { headers: requestHeaders, redirect: 'manual', signal: AbortSignal.timeout(limits.timeoutMs) }); }
83
+ catch { throw Error('registry network request failed'); }
84
+ if (![301, 302, 303, 307, 308].includes(response.status)) return response;
85
+ const location = response.headers.get('location');
86
+ await response.body?.cancel();
87
+ if (!location) throw Error('registry redirect has no location');
88
+ const next = new URL(location, current);
89
+ if (!['https:', 'http:'].includes(next.protocol) || next.username || next.password || (next.protocol === 'http:' && !options.insecure)) throw Error('unsafe registry redirect');
90
+ if (next.origin !== current.origin) delete requestHeaders.Authorization;
91
+ current = next;
92
+ }
93
+ throw Error('too many registry redirects');
94
+ }
95
+ async function registryGet(url, accept, allow404 = false) {
96
+ const headers = { ...(accept ? { Accept: accept } : {}), ...(authorization ? { Authorization: authorization } : {}) };
97
+ let response = await request(url, headers);
98
+ if (response.status === 401) {
99
+ const header = response.headers.get('www-authenticate');
100
+ await response.body?.cancel();
101
+ const challenge = bearerChallenge(header);
102
+ if (challenge) {
103
+ const realm = new URL(challenge.realm);
104
+ if (!['https:', 'http:'].includes(realm.protocol) || realm.username || realm.password || (realm.protocol !== 'https:' && !options.insecure)) throw Error('unsafe registry authentication realm');
105
+ if (challenge.service) realm.searchParams.set('service', challenge.service);
106
+ realm.searchParams.set('scope', `repository:${ref.repository}:pull`);
107
+ const trusted = realm.origin === origin || (options.authOrigins || []).includes(realm.origin);
108
+ if (basic && !trusted) throw Error('cross-origin registry authentication requires an explicitly trusted auth origin');
109
+ const tokenResponse = await request(realm.href, basic ? { Authorization: basic } : {});
110
+ if (!tokenResponse.ok) { await tokenResponse.body?.cancel(); throw Error(`registry authentication failed (HTTP ${tokenResponse.status})`); }
111
+ let token;
112
+ try { token = JSON.parse((await readBounded(tokenResponse, limits.metadataBytes)).toString('utf8')); }
113
+ catch { throw Error('invalid registry authentication response'); }
114
+ if (typeof (token.token || token.access_token) !== 'string') throw Error('registry authentication returned no token');
115
+ authorization = `Bearer ${token.token || token.access_token}`;
116
+ } else if (/^Basic\b/i.test(header || '') && basic) authorization = basic;
117
+ else throw Error('registry requires credentials or an unsupported authentication scheme');
118
+ response = await request(url, { ...headers, Authorization: authorization });
119
+ }
120
+ if (!response.ok && !(allow404 && response.status === 404)) { await response.body?.cancel(); throw Error(`registry request failed (HTTP ${response.status})`); }
121
+ return response;
122
+ }
123
+ return { registryGet, base };
124
+ }
125
+
126
+ // Resolve only the top-level manifest/index. Its content digest covers all
127
+ // selected platforms and layers, so an unchanged digest can reuse an inventory.
128
+ async function fetchRegistryDigest(reference, options = {}) {
129
+ if (options.offline) throw Error('registry resolution is unavailable in offline mode');
130
+ const ref = parseReference(reference), limits = {...DEFAULT_LIMITS, ...options.limits};
131
+ for (const [key, value] of Object.entries(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw Error(`invalid registry limit: ${key}`);
132
+ const {registryGet, base} = createRegistryTransport(ref, options, limits);
133
+ const response = await registryGet(`${base}/manifests/${encodeURIComponent(ref.reference)}`, ACCEPT);
134
+ const buffer = await readBounded(response, limits.metadataBytes);
135
+ const digest = `sha256:${crypto.createHash('sha256').update(buffer).digest('hex')}`;
136
+ const expected = ref.reference.includes(':') ? ref.reference : response.headers.get('docker-content-digest');
137
+ if (expected && digest !== expected) throw Error('image manifest digest mismatch');
138
+ const document = JSON.parse(buffer.toString('utf8'));
139
+ if (document.schemaVersion !== 2 || (!Array.isArray(document.manifests) && !Array.isArray(document.layers))) throw Error('invalid image manifest');
140
+ return digest;
141
+ }
142
+
143
+ async function fetchRegistryImage(reference, options = {}) {
144
+ if (options.offline) throw Error('registry image acquisition is unavailable in offline mode; supply an archive or inventory');
145
+ const ref = parseReference(reference);
146
+ const limits = { ...DEFAULT_LIMITS, ...options.limits };
147
+ for (const [key, value] of Object.entries(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw Error(`invalid registry limit: ${key}`);
148
+ const { registryGet, base } = createRegistryTransport(ref, options, limits);
149
+ const root = await fs.promises.mkdtemp(path.join(options.tmpDir || os.tmpdir(), 'vv-registry-'));
150
+ const cleanup = () => fs.promises.rm(root, { recursive: true, force: true });
151
+ let bytes = 0, descriptors = 0;
152
+ const diagnostics = [];
153
+ const blobs = new Map();
154
+ const blobPath = digest => { const { algorithm, hex } = digestParts(digest); return path.join(root, 'blobs', algorithm, hex); };
155
+ async function saveBuffer(buffer, expected) {
156
+ const digest = expected || `sha256:${crypto.createHash('sha256').update(buffer).digest('hex')}`;
157
+ const { algorithm, hex } = digestParts(digest);
158
+ if (crypto.createHash(algorithm).update(buffer).digest('hex') !== hex) throw Error('image manifest digest mismatch');
159
+ if (!blobs.has(digest)) {
160
+ bytes += buffer.length;
161
+ if (bytes > limits.totalBytes) throw Error('registry download exceeds configured total limit');
162
+ const file = blobPath(digest);
163
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
164
+ await fs.promises.writeFile(file, buffer, { flag: 'wx', mode: 0o600 });
165
+ blobs.set(digest, buffer.length);
166
+ }
167
+ return digest;
168
+ }
169
+ async function downloadBlob(descriptor) {
170
+ if (++descriptors > limits.descriptors) throw Error('too many image descriptors');
171
+ if (!Number.isSafeInteger(descriptor.size) || descriptor.size < 0 || descriptor.size > limits.blobBytes) throw Error('invalid or oversized image blob');
172
+ if (blobs.has(descriptor.digest)) {
173
+ if (blobs.get(descriptor.digest) !== descriptor.size) throw Error('conflicting image blob size');
174
+ return;
175
+ }
176
+ const { algorithm, hex } = digestParts(descriptor.digest), file = blobPath(descriptor.digest);
177
+ const response = await registryGet(`${base}/blobs/${descriptor.digest}`);
178
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
179
+ let size = 0;
180
+ const hash = crypto.createHash(algorithm);
181
+ const limiter = new Transform({ transform(chunk, _encoding, callback) {
182
+ size += chunk.length; bytes += chunk.length;
183
+ if (size > descriptor.size || bytes > limits.totalBytes) return callback(Error('image blob exceeds declared size or configured total limit'));
184
+ hash.update(chunk); callback(null, chunk);
185
+ } });
186
+ await pipeline(Readable.fromWeb(response.body), limiter, fs.createWriteStream(file, { flags: 'wx', mode: 0o600 }));
187
+ if (size !== descriptor.size || hash.digest('hex') !== hex) throw Error('image blob size/digest mismatch');
188
+ blobs.set(descriptor.digest, size);
189
+ }
190
+ function platformMatches(platform) {
191
+ if (!options.platform || !platform) return true;
192
+ const requested = options.platform.split('/');
193
+ if (requested.length < 2 || requested.length > 3 || requested.some(x => !x)) throw Error('invalid requested platform');
194
+ return requested[0] === platform.os && requested[1] === platform.architecture && (requested.length < 3 || requested[2] === platform.variant);
195
+ }
196
+ async function manifest(id, depth = 0, expectedSize) {
197
+ if (++descriptors > limits.descriptors || depth > limits.depth) throw Error('image index exceeds configured limits');
198
+ const response = await registryGet(`${base}/manifests/${encodeURIComponent(id)}`, ACCEPT);
199
+ const buffer = await readBounded(response, limits.metadataBytes);
200
+ if (expectedSize !== undefined && expectedSize !== buffer.length) throw Error('image manifest size mismatch');
201
+ const expected = id.includes(':') ? id : response.headers.get('docker-content-digest');
202
+ const digest = await saveBuffer(buffer, expected);
203
+ const document = JSON.parse(buffer.toString('utf8'));
204
+ if (document.schemaVersion !== 2) throw Error('unsupported image manifest schema');
205
+ const type = document.mediaType || response.headers.get('content-type')?.split(';')[0];
206
+ if (Array.isArray(document.manifests)) {
207
+ const children = document.manifests.filter(d => {
208
+ const attestation = d.artifactType || d.annotations?.['vnd.docker.reference.type'] === 'attestation-manifest' || (d.platform?.os === 'unknown' && d.platform?.architecture === 'unknown');
209
+ if (attestation) { diagnostics.push({ kind: 'non-image-artifact', digest: d.digest, artifactType: d.artifactType || d.annotations?.['vnd.docker.reference.type'] || 'unknown-platform' }); return false; }
210
+ return platformMatches(d.platform);
211
+ });
212
+ const manifests = [];
213
+ for (const child of children) {
214
+ const descriptor = await manifest(child.digest, depth + 1, child.size);
215
+ if (!descriptor) continue;
216
+ manifests.push({ ...descriptor, ...(child.platform ? { platform: child.platform } : {}), ...(child.annotations ? { annotations: child.annotations } : {}) });
217
+ }
218
+ // A selected-platform layout has its own index; original registry digest remains evidence.
219
+ return { mediaType: type, digest, size: buffer.length, children: manifests };
220
+ }
221
+ if (document.artifactType || document.subject || (document.config?.mediaType && !['application/vnd.oci.image.config.v1+json', 'application/vnd.docker.container.image.v1+json'].includes(document.config.mediaType))) {
222
+ diagnostics.push({ kind: 'non-image-artifact', digest, artifactType: document.artifactType || document.config?.mediaType || 'subject' });
223
+ return null;
224
+ }
225
+ if (!document.config || !Array.isArray(document.layers)) throw Error('invalid image manifest');
226
+ if (document.config.size > limits.metadataBytes) throw Error('image config exceeds metadata limit');
227
+ await downloadBlob(document.config);
228
+ const config = JSON.parse(await fs.promises.readFile(blobPath(document.config.digest), 'utf8'));
229
+ if (!platformMatches(config)) throw Error('requested platform differs from image configuration');
230
+ for (const layer of document.layers) await downloadBlob(layer);
231
+ return { mediaType: type, digest, size: buffer.length, platform: { os: config.os, architecture: config.architecture, ...(config.variant ? { variant: config.variant } : {}) } };
232
+ }
233
+ try {
234
+ const descriptor = await manifest(ref.reference);
235
+ const flatten = item => !item ? [] : item.children ? item.children.flatMap(flatten) : [item];
236
+ const leaves = flatten(descriptor);
237
+ if (!leaves.length) throw Error(options.platform ? 'requested platform is absent from image index' : 'image index contains no runnable images');
238
+ await fs.promises.writeFile(path.join(root, 'oci-layout'), JSON.stringify({ imageLayoutVersion: '1.0.0' }));
239
+ await fs.promises.writeFile(path.join(root, 'index.json'), JSON.stringify({ schemaVersion: 2, mediaType: 'application/vnd.oci.image.index.v1+json', manifests: leaves }));
240
+ return { path: root, metadata: { reference: ref.original, registry: ref.registry, repository: ref.repository,
241
+ digest: descriptor?.digest || null, diagnostics, resolvedAt: new Date().toISOString(), platforms: leaves.map(d => d.platform), acquisition: 'registry' }, cleanup };
242
+ } catch (error) { await cleanup(); throw error; }
243
+ }
244
+
245
+ // Publisher-provided inventories are assertions, not verified signatures or a
246
+ // guarantee that the inventory is complete. Every fetched descriptor is hashed.
247
+ async function fetchRegistrySboms(reference, options = {}) {
248
+ if (options.offline) throw Error('registry SBOM acquisition is unavailable in offline mode');
249
+ const ref = parseReference(reference), limits = { ...DEFAULT_LIMITS, ...options.limits };
250
+ for (const [key, value] of Object.entries(limits)) if (!Number.isSafeInteger(value) || value <= 0) throw Error(`invalid registry limit: ${key}`);
251
+ const { registryGet, base } = createRegistryTransport(ref, options, limits);
252
+ const diagnostics = [], documents = [], leaves = [], attached = [], visited = new Set();
253
+ let count = 0, total = 0;
254
+ const fail = (kind, detail) => diagnostics.push({ kind, ...detail });
255
+ function account(buffer) { total += buffer.length; if (total > limits.totalBytes) throw Error('registry download exceeds configured total limit'); }
256
+ async function data(url, descriptor, accept, optional = false) {
257
+ if (++count > limits.descriptors) throw Error('too many image descriptors');
258
+ if (descriptor && (!Number.isSafeInteger(descriptor.size) || descriptor.size < 0 || descriptor.size > limits.metadataBytes)) throw Error('invalid or oversized registry metadata descriptor');
259
+ const response = await registryGet(url, accept, optional);
260
+ if (response.status === 404) { await response.body?.cancel(); return null; }
261
+ const body = await readBounded(response, limits.metadataBytes); account(body);
262
+ const claimed = descriptor?.digest || response.headers.get('docker-content-digest');
263
+ if (descriptor && descriptor.size !== body.length) throw Error('registry metadata size mismatch');
264
+ const hash = 'sha256:' + crypto.createHash('sha256').update(body).digest('hex');
265
+ if (claimed && (digestParts(claimed), claimed !== hash)) throw Error('registry metadata digest mismatch');
266
+ return { body, digest: hash, response };
267
+ }
268
+ const parse = (buffer) => { try { return JSON.parse(buffer.toString('utf8')); } catch { throw Error('invalid registry JSON metadata'); } };
269
+ const manifest = (id, descriptor) => data(`${base}/manifests/${encodeURIComponent(id)}`, descriptor, ACCEPT);
270
+ const blob = desc => data(`${base}/blobs/${encodeURIComponent(desc.digest)}`, desc);
271
+ function matches(platform) {
272
+ if (!options.platform) return true;
273
+ const p = options.platform.split('/'); if (p.length < 2 || p.length > 3 || p.some(x => !x)) throw Error('invalid requested platform');
274
+ return p[0] === platform?.os && p[1] === platform?.architecture && (p.length < 3 || p[2] === platform?.variant);
275
+ }
276
+ async function walk(id, descriptor, platform, depth) {
277
+ if (depth > limits.depth) throw Error('image index exceeds configured depth');
278
+ const fetched = await manifest(id, descriptor);
279
+ if (id.includes(':') && id !== fetched.digest) throw Error('image manifest digest mismatch');
280
+ if (visited.has(fetched.digest)) return; visited.add(fetched.digest);
281
+ const doc = parse(fetched.body);
282
+ if (doc.schemaVersion !== 2) throw Error('unsupported image manifest schema');
283
+ if (Array.isArray(doc.manifests)) {
284
+ for (const child of doc.manifests) {
285
+ const annotation = child.annotations || {};
286
+ if (annotation['vnd.docker.reference.type'] === 'attestation-manifest') { attached.push(child); continue; }
287
+ if (child.artifactType || (child.platform?.os === 'unknown' && child.platform?.architecture === 'unknown')) { fail('unclassified-index-artifact', { digest: child.digest }); continue; }
288
+ if (child.platform && !matches(child.platform)) continue;
289
+ await walk(child.digest, child, child.platform || platform, depth + 1);
290
+ }
291
+ return fetched.digest;
292
+ }
293
+ if (doc.artifactType || doc.subject || !doc.config || !Array.isArray(doc.layers)) { fail('not-image-manifest', { digest: fetched.digest }); return fetched.digest; }
294
+ const config = parse((await blob(doc.config)).body);
295
+ const actual = { os: config.os, architecture: config.architecture, ...(config.variant ? { variant: config.variant } : {}) };
296
+ if (platform && (platform.os !== actual.os || platform.architecture !== actual.architecture || (platform.variant && platform.variant !== actual.variant))) throw Error('image platform descriptor/config mismatch');
297
+ if (matches(actual)) leaves.push({ digest: fetched.digest, platform: actual });
298
+ return fetched.digest;
299
+ }
300
+ const digest = await walk(ref.reference, null, null, 0);
301
+ if (!leaves.length) throw Error(options.platform ? 'requested platform is absent from image index' : 'image index contains no runnable images');
302
+ async function scanArtifact(descriptor, leaf, source) {
303
+ const fetched = await manifest(descriptor.digest, descriptor), artifact = parse(fetched.body);
304
+ if (artifact.subject && artifact.subject.digest !== leaf.digest) { fail('artifact-subject-mismatch', { digest: descriptor.digest }); return; }
305
+ if (source === 'oci-referrers' && !artifact.subject) { fail('artifact-subject-missing', { digest: descriptor.digest }); return; }
306
+ if (!Array.isArray(artifact.layers)) { fail('unsupported-artifact', { digest: descriptor.digest }); return; }
307
+ for (const layer of artifact.layers) {
308
+ const media = layer.mediaType || '';
309
+ if (!/json/i.test(media)) { fail('unsupported-sbom-media-type', { digest: layer.digest, mediaType: media }); continue; }
310
+ const fetchedLayer = await blob(layer); let value;
311
+ try { value = parse(fetchedLayer.body); } catch { fail('invalid-sbom-json', { digest: layer.digest }); continue; }
312
+ let document = value;
313
+ if (value._type && value.predicate) {
314
+ if (!Array.isArray(value.subject) || !value.subject.some(item => item.digest?.sha256 === leaf.digest.slice(7))) { fail('attestation-subject-mismatch', { digest: layer.digest }); continue; }
315
+ document = value.predicate;
316
+ }
317
+ if (!(document?.spdxVersion || document?.bomFormat === 'CycloneDX')) { fail('unsupported-sbom-format', { digest: layer.digest }); continue; }
318
+ documents.push({ document: value._type && value.predicate ? value : document, expectedDigest: leaf.digest, platform: leaf.platform, source: { kind: source, reference: ref.original, manifestDigest: descriptor.digest, blobDigest: layer.digest, binding: { kind: artifact.subject ? 'oci-subject' : 'buildkit-index', digest: leaf.digest }, signatureVerified: false } });
319
+ }
320
+ }
321
+ for (const leaf of leaves) {
322
+ for (const descriptor of attached) if (descriptor.annotations?.['vnd.docker.reference.digest'] === leaf.digest) await scanArtifact(descriptor, leaf, 'buildkit-index');
323
+ let url = `${base}/referrers/${leaf.digest}`, pages = 0;
324
+ while (url) {
325
+ if (++pages > limits.depth) throw Error('registry referrers pagination exceeds configured limit');
326
+ const result = await data(url, null, 'application/vnd.oci.image.index.v1+json', true);
327
+ if (!result) { fail('referrers-unavailable', { digest: leaf.digest }); break; }
328
+ const index = parse(result.body); if (!Array.isArray(index.manifests)) throw Error('invalid referrers response');
329
+ for (const descriptor of index.manifests) await scanArtifact(descriptor, leaf, 'oci-referrers');
330
+ const link = result.response.headers.get('link'), match = link && /<([^>]+)>\s*;\s*rel="?next"?/i.exec(link);
331
+ if (!match) { url = null; continue; }
332
+ const next = new URL(match[1], url); if (next.origin !== new URL(base).origin || !next.pathname.startsWith(new URL(base).pathname + '/referrers/')) throw Error('unsafe referrers pagination URL'); url = next.href;
333
+ }
334
+ }
335
+ return { documents, metadata: { reference: ref.original, digest, platforms: leaves.map(x => x.platform), resolvedAt: new Date().toISOString(), signatureVerified: false }, diagnostics };
336
+ }
337
+
338
+ async function fetchRegistryTags(reference, options = {}) {
339
+ if (options.offline) throw Error('registry tags are unavailable offline');
340
+ const ref=parseReference(reference),limits={...DEFAULT_LIMITS,...options.limits};
341
+ const maxPages=limits.maxTagPages??100,maxTags=limits.maxTags??100000;
342
+ if(!Number.isSafeInteger(maxPages)||maxPages<=0||!Number.isSafeInteger(maxTags)||maxTags<=0)throw Error('invalid registry tag limits');
343
+ const {registryGet,base}=createRegistryTransport(ref,options,limits),endpoint=new URL(`${base}/tags/list`),tags=new Set(),seen=new Set();
344
+ let next=endpoint.href;
345
+ for(let page=0;next;page++){
346
+ if(page>=maxPages || seen.has(next))throw Error('registry tag pagination exceeds limits or repeats');seen.add(next);
347
+ const res=await registryGet(next,'application/json');let body;
348
+ try{body=JSON.parse((await readBounded(res,limits.metadataBytes)).toString('utf8'));}catch{throw Error('invalid registry tag response');}
349
+ if(!Array.isArray(body.tags) || body.tags.some(t=>typeof t!=='string'||!/^\w[\w.-]{0,127}$/.test(t)))throw Error('invalid registry tag response');
350
+ for(const tag of body.tags){tags.add(tag);if(tags.size>maxTags)throw Error('registry tag count exceeds limit');}
351
+ const link=res.headers.get('link');if(!link){next=null;continue;}
352
+ const match=/<([^>]+)>\s*;\s*rel="?next"?/i.exec(link);if(!match)throw Error('invalid registry pagination link');
353
+ const url=new URL(match[1],next);if(url.origin!==endpoint.origin || url.pathname!==endpoint.pathname || url.username || url.password)throw Error('unsafe registry pagination link');next=url.href;
354
+ }
355
+ return {tags:[...tags],registry:ref.registry,repository:ref.repository};
356
+ }
357
+ async function fetchRegistryTagPlatform(reference,platform,options={}) {
358
+ if(options.offline)throw Error('registry manifest is unavailable offline');
359
+ if(!platform?.os||!platform?.architecture)throw Error('image platform is unavailable');
360
+ const ref=parseReference(reference),limits={...DEFAULT_LIMITS,...options.limits},{registryGet,base}=createRegistryTransport(ref,options,limits);
361
+ const matches=p=>p?.os===platform.os&&p?.architecture===platform.architecture&&(!platform.variant||p.variant===platform.variant);
362
+ async function readManifest(id,depth=0,expectedSize,declaredPlatform){
363
+ if(depth>limits.depth)throw Error('image index exceeds configured depth');
364
+ const res=await registryGet(`${base}/manifests/${encodeURIComponent(id)}`,ACCEPT),buffer=await readBounded(res,limits.metadataBytes);
365
+ if(expectedSize!==undefined&&expectedSize!==buffer.length)throw Error('image manifest size mismatch');
366
+ const digest=`sha256:${crypto.createHash('sha256').update(buffer).digest('hex')}`,expected=id.includes(':')?id:res.headers.get('docker-content-digest');
367
+ if(expected&&expected!==digest)throw Error('image manifest digest mismatch');const doc=JSON.parse(buffer.toString('utf8'));
368
+ if(doc.schemaVersion!==2)throw Error('unsupported image manifest schema');
369
+ if(Array.isArray(doc.manifests)){
370
+ for(const d of doc.manifests){if(d.artifactType||d.annotations?.['vnd.docker.reference.type']==='attestation-manifest'||(d.platform&&!matches(d.platform)))continue;
371
+ const child=await readManifest(d.digest,depth+1,d.size,d.platform||declaredPlatform);if(child)return {digest,platformDigest:child.platformDigest};}
372
+ return null;
373
+ }
374
+ if(doc.artifactType||doc.subject||!doc.config||!Array.isArray(doc.layers))return null;
375
+ const descriptor=doc.config;digestParts(descriptor.digest);if(!Number.isSafeInteger(descriptor.size)||descriptor.size<0||descriptor.size>limits.metadataBytes)throw Error('invalid image config size');
376
+ const resConfig=await registryGet(`${base}/blobs/${descriptor.digest}`),bytes=await readBounded(resConfig,limits.metadataBytes);
377
+ if(bytes.length!==descriptor.size||`sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}`!==descriptor.digest)throw Error('image config digest/size mismatch');
378
+ const config=JSON.parse(bytes.toString('utf8'));
379
+ if(declaredPlatform && (config.os!==declaredPlatform.os || config.architecture!==declaredPlatform.architecture || (config.variant && declaredPlatform.variant && config.variant!==declaredPlatform.variant)))throw Error('image index and config platform mismatch');
380
+ const effective={...declaredPlatform,...config,variant:config.variant||declaredPlatform?.variant};
381
+ return matches(effective)?{digest,platformDigest:digest}:null;
382
+ }
383
+ return readManifest(ref.reference);
384
+ }
385
+ module.exports = { fetchRegistryImage, fetchRegistryDigest, fetchRegistrySboms, fetchRegistryTags, fetchRegistryTagPlatform, parseReference, bearerChallenge, DEFAULT_LIMITS };
@@ -0,0 +1,39 @@
1
+ 'use strict';
2
+ const crypto=require('node:crypto');
3
+ const {createCacheRepository}=require('./cache-repository');
4
+ const {getCacheDir}=require('./cache-directory');
5
+ const {parseReference,fetchRegistryTags,fetchRegistryTagPlatform}=require('./image-registry');
6
+
7
+ // Only patch releases with an exact major.minor branch and suffix are ordered.
8
+ // A suffix is treated as an opaque variant, never as a guessed version.
9
+ function numericTag(tag){const m=/^(v?)(0|[1-9]\d*)\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?(-[A-Za-z][A-Za-z0-9._-]*)?$/.exec(tag||'');return m?{prefix:m[1],major:m[2],minor:m[3],patch:m[4]===undefined?null:BigInt(m[4]),suffix:m[5]||''}:null;}
10
+ async function resolveImageUpdate(metadata,options={}){
11
+ const binding=metadata?.registryReference,scannedDigest=metadata?.digest||metadata?.acquisition?.resolvedDigest||null;
12
+ const bound=binding && typeof binding.reference==='string' && /^sha256:[a-f0-9]{64}$/.test(binding.platformDigest||'') && binding.platformDigest===scannedDigest;
13
+ const reference=metadata?.acquisition?.kind==='registry'?metadata.acquisition.reference:bound?binding.reference:null;
14
+ const fallback=(reason,reasonCode='unavailable')=>({status:'unknown',reference:reference||null,currentTag:null,targetReference:null,targetTag:null,branch:null,observedAt:null,source:null,reason,reasonCode,verifiedFix:false});
15
+ if(!reference)return fallback('No registry image reference is available; update the image or its affected package or binary.','no-reference');
16
+ let ref;try{ref=parseReference(reference);}catch{return fallback('The image reference cannot be parsed; update the image or affected package or binary.');}
17
+ const name=String(reference).replace(/^docker:\/\//,'').split('@')[0],at=name.lastIndexOf(':'),slash=name.lastIndexOf('/'),currentTag=at>slash?name.slice(at+1):ref.reference;
18
+ const parsed=numericTag(currentTag);if(!parsed)return {...fallback('The image tag does not identify a comparable patch-release branch; update the image or affected package or binary.','unsupported-tag'),currentTag};
19
+ const base={reference,currentTag,branch:`${parsed.prefix}${parsed.major}.${parsed.minor}${parsed.suffix}`,source:'registry-tags',verifiedFix:false};
20
+ const platform=metadata.platform;if(!platform?.os||!platform?.architecture)return {...fallback('The image platform is unavailable; update the image or affected package or binary.','platform-unknown'),...base,status:'unknown'};
21
+ const key='image-tags-'+crypto.createHash('sha256').update(`${ref.registry}/${ref.repository}`).digest('hex'),repo=createCacheRepository(options.cacheDir||getCacheDir());let observation=repo.get('catalogue',key)?.value;
22
+ const transport={...options,fetcher:options.registryFetcher||options.fetcher,limits:options.registryLimits},ttl=options.imageUpdateTtlMs??4*3600000;
23
+ if(!Number.isSafeInteger(ttl)||ttl<=0)throw Error('invalid image update cache TTL');
24
+ const age=Date.now()-Date.parse(observation?.observedAt);
25
+ if(!options.offline && (!observation || !Number.isFinite(age) || age<0 || age>=ttl)){try{const found=await fetchRegistryTags(reference,transport);observation={tags:found.tags,registry:found.registry,repository:found.repository,observedAt:new Date().toISOString(),platforms:{}};repo.put('catalogue',key,observation);}catch(error){return {...fallback(`Registry tag lookup failed: ${error.message}`,'registry-error'),...base,status:'unknown'};}}
26
+ if(options.offline && (!Number.isFinite(age)||age<0))return {...fallback('Registry observation has an invalid collection date.','cache-miss'),...base,status:'unknown'};
27
+ if(!observation || !Array.isArray(observation.tags))return {...fallback('No registry tag observation is available offline; update the image or affected package or binary.','cache-miss'),...base,status:'unknown'};
28
+ const repository=at>slash?name.slice(0,at):name,candidates=[];
29
+ for(const tag of observation.tags){const version=numericTag(tag);if(version&&version.patch!==null&&version.prefix===parsed.prefix&&version.major===parsed.major&&version.minor===parsed.minor&&version.suffix===parsed.suffix&&(parsed.patch===null||version.patch>=parsed.patch))candidates.push({tag,version});}
30
+ candidates.sort((a,b)=>a.version.patch>b.version.patch?-1:a.version.patch<b.version.patch?1:0);
31
+ observation.platforms ||= {};const platformKey=JSON.stringify([platform.os,platform.architecture,platform.variant||'']);
32
+ for(const candidate of candidates){const candidateKey=JSON.stringify([candidate.tag,platformKey]);let proof=observation.platforms[candidateKey];
33
+ if(proof===undefined&&!options.offline){try{proof=await fetchRegistryTagPlatform(`${repository}:${candidate.tag}`,platform,transport);observation.platforms[candidateKey]=proof;repo.put('catalogue',key,observation);}catch(error){return {...fallback(`Registry manifest lookup failed: ${error.message}`,'registry-error'),...base,observedAt:observation.observedAt,status:'unknown'};}}
34
+ if(proof){const rebuilt=parsed.patch!==null&&candidate.version.patch===parsed.patch&&!!scannedDigest&&proof.platformDigest!==scannedDigest;return {...base,status:parsed.patch===null||candidate.version.patch>parsed.patch||rebuilt?'available':'current',...(rebuilt?{reasonCode:'rebuilt-tag'}:{}),targetTag:candidate.tag,targetReference:`${repository}:${candidate.tag}`,targetDigest:proof.digest,platformDigest:proof.platformDigest,observedAt:observation.observedAt,reason:'Registry tag ordering does not establish that any vulnerability is fixed.'};}
35
+ if(proof===undefined && options.offline)break;
36
+ }
37
+ return {...fallback('No comparable tag with verified image platform is available in the registry observation.','platform-mismatch'),...base,observedAt:observation.observedAt,status:'unknown'};
38
+ }
39
+ module.exports={resolveImageUpdate,numericTag};