vigievuln 1.1.2 → 1.2.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 +25 -0
  2. package/README.md +51 -141
  3. package/completions/vigievuln.bash +1 -1
  4. package/completions/vigievuln.zsh +1 -0
  5. package/lib/account-client.js +21 -14
  6. package/lib/account-session.js +6 -2
  7. package/lib/advisory-compression.js +25 -0
  8. package/lib/advisory-fixes.js +21 -0
  9. package/lib/advisory-store-sqlite.js +156 -0
  10. package/lib/advisory-store.js +484 -0
  11. package/lib/airgap-project.js +117 -0
  12. package/lib/application-plugins/runner.js +22 -13
  13. package/lib/application-plugins/wordpress.js +4 -3
  14. package/lib/application-providers/live-snapshot.js +1 -12
  15. package/lib/application-providers/snapshot-cache.js +27 -0
  16. package/lib/application-providers/wordfence-client.js +3 -3
  17. package/lib/attribution.js +2 -2
  18. package/lib/cache-archive-sqlite.js +215 -0
  19. package/lib/cache-archive.js +357 -26
  20. package/lib/cache-db.js +142 -0
  21. package/lib/cache-directory.js +18 -74
  22. package/lib/cache-policy.js +25 -0
  23. package/lib/cache-repository.js +48 -0
  24. package/lib/cache-startup.js +54 -0
  25. package/lib/certfr.js +9 -9
  26. package/lib/cli-command-routing.js +29 -6
  27. package/lib/cli-groups.js +32 -3
  28. package/lib/cli-project-commands.js +47 -6
  29. package/lib/cli-setup.js +300 -0
  30. package/lib/codecs/binary/pe-metadata.js +79 -0
  31. package/lib/codecs/binary/scan.js +4 -3
  32. package/lib/codecs/binary.codec.js +4 -2
  33. package/lib/codecs/composer/registry.js +8 -6
  34. package/lib/codecs/go/parse.js +7 -9
  35. package/lib/codecs/go/registry.js +7 -5
  36. package/lib/codecs/go.codec.js +5 -0
  37. package/lib/codecs/maven.codec.js +73 -8
  38. package/lib/codecs/npm/collect.js +12 -5
  39. package/lib/codecs/npm/parse.js +12 -5
  40. package/lib/codecs/npm/registry.js +42 -12
  41. package/lib/codecs/nuget/registry.js +8 -6
  42. package/lib/codecs/pypi/registry.js +8 -6
  43. package/lib/codecs/ruby/registry.js +7 -5
  44. package/lib/compression-dictionary.js +5 -0
  45. package/lib/coverage-diagnostics.js +26 -0
  46. package/lib/cve-download.js +157 -41
  47. package/lib/cve-legacy-ranges.js +59 -0
  48. package/lib/cve-match.js +85 -17
  49. package/lib/cve-npm-proxy.js +29 -0
  50. package/lib/cve-report.js +145 -58
  51. package/lib/cve-version-verdict.js +77 -0
  52. package/lib/deps-descriptor.js +8 -3
  53. package/lib/epss.js +13 -8
  54. package/lib/euvd.js +32 -8
  55. package/lib/gcve-feed.js +103 -0
  56. package/lib/gcve-index.js +181 -0
  57. package/lib/gcve.js +1 -1
  58. package/lib/github-publisher-maven.js +40 -0
  59. package/lib/hash-id.js +5 -5
  60. package/lib/hosted-proxy.js +6 -1
  61. package/lib/i18n.js +31 -8
  62. package/lib/json-cache.js +18 -0
  63. package/lib/json-export.js +16 -2
  64. package/lib/kev.js +7 -8
  65. package/lib/line-stream.js +23 -0
  66. package/lib/maven-airgap.js +80 -0
  67. package/lib/maven-cache.js +21 -0
  68. package/lib/maven-license.js +2 -1
  69. package/lib/maven-presence.js +2 -2
  70. package/lib/maven-reactor.js +23 -14
  71. package/lib/maven-repo.js +11 -6
  72. package/lib/merge-sources.js +25 -18
  73. package/lib/native-advisories.js +268 -0
  74. package/lib/nvd-bulk.js +145 -0
  75. package/lib/nvd-package-ranges.js +109 -0
  76. package/lib/nvd.js +52 -24
  77. package/lib/osv-db.js +253 -59
  78. package/lib/osv-legacy.js +57 -0
  79. package/lib/osv.js +241 -168
  80. package/lib/outdated.js +11 -12
  81. package/lib/package-metadata.js +141 -0
  82. package/lib/package-versions.js +52 -0
  83. package/lib/packagist-audit.js +6 -6
  84. package/lib/provenance.js +73 -19
  85. package/lib/providers/common.js +11 -1
  86. package/lib/providers/gcve.js +17 -0
  87. package/lib/providers/github.js +1 -0
  88. package/lib/providers/index.js +49 -26
  89. package/lib/providers/vigievuln.js +7 -0
  90. package/lib/proxy-cache.js +1 -1
  91. package/lib/proxy-scope.js +59 -0
  92. package/lib/proxy-throttle.js +71 -0
  93. package/lib/resource-cache/engine.js +36 -9
  94. package/lib/resource-cache/sqlite-store.js +95 -0
  95. package/lib/resource-cache/validate.js +5 -0
  96. package/lib/retire.js +24 -24
  97. package/lib/ruby-version.js +36 -0
  98. package/lib/sarif-export.js +1 -1
  99. package/lib/sbom-export.js +11 -7
  100. package/lib/snyk.js +32 -20
  101. package/lib/source-profile.js +67 -0
  102. package/lib/sqlite-driver.js +46 -0
  103. package/lib/transitive.js +69 -34
  104. package/lib/unmanaged.js +2 -1
  105. package/lib/vigievuln-advisories.js +47 -0
  106. package/package.json +7 -6
  107. package/vigievuln.js +380 -107
package/lib/nvd.js CHANGED
@@ -9,7 +9,7 @@
9
9
  * API: https://services.nvd.nist.gov/rest/json/cves/2.0?cveId=CVE-YYYY-NNNN
10
10
  * Rate limit: 5 req / 30s unauthenticated, 50 req / 30s with NVD_API_KEY env var.
11
11
  *
12
- * Cache: ~/.fad-checker/nvd-cache/<cve-id>.json, 7-day TTL.
12
+ * Cache: ~/.fad-checker/nvd-cache/<cve-id>.json, 4-hour TTL.
13
13
  *
14
14
  * @author: N.BRAUN
15
15
  * @email: pp9ping@gmail.com
@@ -20,11 +20,12 @@ const os = require("os");
20
20
  const { getNvdApiKey } = require("./config");
21
21
 
22
22
  const NVD_CACHE_DIR = path.join(require("./cache-directory").getCacheDir(), "nvd-cache");
23
- const NVD_CACHE_TTL_MS = 7 * 24 * 3600 * 1000;
23
+ const NVD_CACHE_TTL_MS = 4 * 3600 * 1000;
24
24
  // Bump whenever `extractFromNvdRecord` adds a new field — pre-bump cache
25
25
  // entries are treated as cache-miss so we re-fetch and pick up the new field.
26
26
  // 2: added `cwes` (Common Weakness Enumeration list).
27
- const NVD_CACHE_SCHEMA = 2;
27
+ // 3: retain the structured CNA/ADP affected data delivered by NVD.
28
+ const NVD_CACHE_SCHEMA = 3;
28
29
  const NVD_BASE = "https://services.nvd.nist.gov/rest/json/cves/2.0";
29
30
 
30
31
  function getRateDelay() {
@@ -46,27 +47,43 @@ function cachePath(cveId) {
46
47
  }
47
48
 
48
49
  function readCache(cveId, offline = false) {
49
- const p = cachePath(cveId);
50
- if (!fs.existsSync(p)) return null;
51
50
  try {
52
- const data = JSON.parse(fs.readFileSync(p, "utf8"));
51
+ const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
52
+ const row=db.prepare(`SELECT kind,fetched_at,body_deflate,body_bytes,metadata_json FROM nvd_records WHERE cve=?
53
+ ${offline ? 'ORDER BY fetched_at DESC LIMIT 1' : "AND kind='live' LIMIT 1"}`).get(cveId);
54
+ if(!row)return null;
55
+ const bytes=require('./advisory-compression').decompress(row.body_deflate,row.body_bytes);
56
+ const body=JSON.parse(bytes.toString('utf8')),metadata=JSON.parse(row.metadata_json);
53
57
  // Offline (air-gapped): the warmed cache is the ONLY source — never reject it
54
58
  // for age or an older schema. Dropping it would silently lose ALL NVD
55
59
  // enrichment (CWEs, CVSS vector, references, CPE configs) for that CVE, which
56
60
  // is exactly the "offline missed some CWE titles" regression. A stale/older
57
61
  // body just means a field may be missing — strictly better than nothing.
58
62
  // (Online still enforces schema + TTL so we re-fetch and upgrade.)
59
- if (offline) return data.body ?? null;
63
+ if (offline) return body;
60
64
  // Schema mismatch → force re-fetch so newly-added fields (e.g. cwes) get populated.
61
- if ((data._schema || 1) < NVD_CACHE_SCHEMA) return null;
62
- if (Date.now() - data._fetchedAt < NVD_CACHE_TTL_MS) return data.body;
65
+ if ((metadata.schema || 1) < NVD_CACHE_SCHEMA) return null;
66
+ if (require('./cache-policy').fresh(row.fetched_at,NVD_CACHE_TTL_MS)) return body;
63
67
  } catch { /* ignore */ }
64
68
  return null;
65
69
  }
66
70
 
67
- function writeCache(cveId, body) {
68
- fs.mkdirSync(NVD_CACHE_DIR, { recursive: true });
69
- fs.writeFileSync(cachePath(cveId), JSON.stringify({ _schema: NVD_CACHE_SCHEMA, _fetchedAt: Date.now(), body }));
71
+ function writeCache(cveId, body, fetchedAt = Date.now()) {
72
+ const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
73
+ const bytes=Buffer.from(JSON.stringify(body));
74
+ db.prepare(`INSERT INTO nvd_records(cve,kind,fetched_at,revision_ms,body_deflate,body_bytes,metadata_json) VALUES (?,?,?,?,?,?,?)
75
+ ON CONFLICT(cve,kind) DO UPDATE SET fetched_at=excluded.fetched_at,revision_ms=excluded.revision_ms,
76
+ body_deflate=excluded.body_deflate,body_bytes=excluded.body_bytes,metadata_json=excluded.metadata_json`).run(cveId,'live',fetchedAt,null,require('./advisory-compression').compress(bytes),bytes.length,JSON.stringify({schema:NVD_CACHE_SCHEMA}));
77
+ }
78
+
79
+ // A cached JSON null is an answered lookup with no NVD record, not a missing
80
+ // cache entry. Keep the distinction when reporting offline coverage.
81
+ function hasCachedAbsence(cveId) {
82
+ try {
83
+ const db=require('./cache-db').getCacheDb(path.dirname(NVD_CACHE_DIR));
84
+ const row=db.prepare('SELECT fetched_at,body_deflate,body_bytes FROM nvd_records WHERE cve=? ORDER BY fetched_at DESC LIMIT 1').get(cveId);
85
+ return !!row && row.fetched_at <= Date.now() && Date.now()-row.fetched_at < NVD_CACHE_TTL_MS && JSON.parse(require('./advisory-compression').decompress(row.body_deflate,row.body_bytes).toString('utf8')) === null;
86
+ } catch { return false; }
70
87
  }
71
88
 
72
89
  function bestMetric(metrics) {
@@ -138,6 +155,12 @@ function extractFromNvdRecord(record) {
138
155
  }
139
156
  return {
140
157
  id: record.id,
158
+ sourceIdentifier: record.sourceIdentifier || null,
159
+ vulnStatus: record.vulnStatus || null,
160
+ // Keep provider boundaries and the complete native entries: packageName,
161
+ // modules, platforms, defaultStatus, versionType, bounds and changes all
162
+ // contribute to identity/applicability. CPE configurations are independent.
163
+ affected: Array.isArray(record.affected) ? structuredClone(record.affected) : [],
141
164
  description: desc,
142
165
  severity: metric?.severity || "UNKNOWN",
143
166
  score: metric?.score ?? null,
@@ -183,15 +206,16 @@ const MIRROR_CONCURRENCY = 16;
183
206
  async function fetchFromMirror(cveId, opts = {}) {
184
207
  const { fetcher = globalThis.fetch } = opts;
185
208
  try {
186
- const m = await require("./providers").getResource("nvd", "cve-mirror", { id: cveId },
187
- { fetcher, headers: { "User-Agent": "vigievuln-nvd-enrich" }, signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) });
209
+ const providers = require("./providers");
210
+ const m = await providers.getResource("nvd", "cve-mirror", { id: cveId },
211
+ { fetcher, headers: { "User-Agent": "vigievuln-nvd-enrich" }, ...(providers.hasHostedProxy() ? {requestTimeoutMs:MIRROR_TIMEOUT_MS, retryProxyDenied:false, noSourceRetry:true} : {signal:AbortSignal.timeout(MIRROR_TIMEOUT_MS)}) });
188
212
  if (m.status === 404) return { absent: true };
189
213
  if (!m.ok) return { failed: true };
190
214
  const raw = await m.json();
191
215
  const extracted = extractFromNvdRecord(raw && raw.id ? raw : raw?.vulnerabilities?.[0]?.cve);
192
216
  if (!extracted) return { failed: true };
193
217
  extracted.via = MIRROR_NAME;
194
- writeCache(cveId, extracted);
218
+ writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(m));
195
219
  return { record: extracted };
196
220
  } catch { return { failed: true }; }
197
221
  }
@@ -223,16 +247,16 @@ async function fetchOne(cveId, opts = {}) {
223
247
  const url = `${NVD_BASE}?cveId=${encodeURIComponent(cveId)}`;
224
248
  const providers = require("./providers");
225
249
  const health = require("./source-health");
226
- const deadline = () => (mirror ? { signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) } : {});
250
+ const deadline = () => providers.hasHostedProxy() ? {requestTimeoutMs:MIRROR_TIMEOUT_MS} : (mirror ? { signal: AbortSignal.timeout(MIRROR_TIMEOUT_MS) } : {});
227
251
 
228
252
  let nvdReason;
229
253
  try {
230
- const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, ...deadline() });
231
- if (r.status === 404) { writeCache(cveId, null); return null; }
254
+ const r = await providers.getResource("nvd", "cve", { id: cveId }, { fetcher, headers, ...deadline(), ...(providers.hasHostedProxy() && mirror ? {retryProxyDenied:false,noSourceRetry:true} : {}) });
255
+ if (r.status === 404) { writeCache(cveId, null, require('./providers/common').responseFetchedAt(r)); return null; }
232
256
  if (r.ok) {
233
257
  const data = await r.json();
234
258
  const extracted = extractFromNvdRecord(data.vulnerabilities?.[0]?.cve);
235
- writeCache(cveId, extracted);
259
+ writeCache(cveId, extracted, require('./providers/common').responseFetchedAt(r));
236
260
  return extracted;
237
261
  }
238
262
  nvdReason = `HTTP ${r.status}`;
@@ -270,7 +294,8 @@ async function enrichMatches(matches, opts = {}) {
270
294
  for (const m of matches) if (m.cve?.id?.startsWith("CVE-")) uniqueCves.add(m.cve.id);
271
295
  // `opts.hasKey` lets a test pin the key/no-key branch whatever ~/.fad-checker holds.
272
296
  const hasKey = opts.hasKey ?? !!getNvdApiKey();
273
- const burst = getBurstSize();
297
+ const hosted = !offline && require("./providers").hasHostedProxy();
298
+ const burst = hosted ? 10 : getBurstSize();
274
299
 
275
300
  // Partition cached vs live up-front so the progress display reflects the
276
301
  // actual work to do (the user's "stuck at OSV" complaint was caused by
@@ -319,10 +344,10 @@ async function enrichMatches(matches, opts = {}) {
319
344
 
320
345
  if (liveIds.length && !onProgress) {
321
346
  const etaSec = Math.ceil((liveIds.length / burst) * (NVD_WINDOW_MS / 1000));
322
- const keyHint = hasKey ? "with API key (50/30s)" : "no API key — throttled to 5/30s, run `vigievuln --set-nvd-key <KEY>` (free, instant) to be 10× faster";
347
+ const keyHint = hosted ? "via hosted proxy" : hasKey ? "with API key (50/30s)" : "no API key — throttled to 5/30s, run `vigievuln --set-nvd-key <KEY>` (free, instant) to be 10× faster";
323
348
  const cachedCount = byId.size;
324
349
  const cachedHint = cachedCount ? `, ${cachedCount} cached` : "";
325
- console.log(`🔍 NVD: enriching ${liveIds.length} CVEs${cachedHint} — ${keyHint}. ETA ~${etaSec}s.`);
350
+ console.log(`🔍 NVD: enriching ${liveIds.length} CVEs${cachedHint} — ${keyHint}.${hosted ? '' : ` ETA ~${etaSec}s.`}`);
326
351
  } else if (uniqueCves.size && !onProgress) {
327
352
  console.log(`🔍 NVD: ${uniqueCves.size} CVEs (all cached).`);
328
353
  }
@@ -352,7 +377,7 @@ async function enrichMatches(matches, opts = {}) {
352
377
  printProgress();
353
378
 
354
379
  // Respect the rolling 30s window before starting the next burst.
355
- if (i + burst < liveIds.length) {
380
+ if (!hosted && i + burst < liveIds.length) {
356
381
  const since = Date.now() - windowStart;
357
382
  if (since < NVD_WINDOW_MS) await sleep(NVD_WINDOW_MS - since);
358
383
  }
@@ -383,9 +408,11 @@ async function enrichMatches(matches, opts = {}) {
383
408
  m.cve.cpes = data.cpes || [];
384
409
  m.cve.cwes = data.cwes || [];
385
410
  m.cve.configurations = data.configurations || [];
411
+ m.cve.nvdAffected = data.affected || [];
412
+ m.cve.nvdVulnStatus = data.vulnStatus || null;
386
413
  if (!m.cve.published && data.published) m.cve.published = data.published;
387
414
  if (!m.cve.modified && data.modified) m.cve.modified = data.modified;
388
- // Tag NVD as a contributing source so the report shows fad+nvd / osv+nvd.
415
+ // Tag NVD as a contributing source without losing the original source.
389
416
  const sources = new Set((m.source || "").split("+").filter(Boolean));
390
417
  sources.add("nvd");
391
418
  m.source = [...sources].sort().join("+");
@@ -399,6 +426,7 @@ module.exports = {
399
426
  extractFromNvdRecord,
400
427
  readCache,
401
428
  writeCache,
429
+ hasCachedAbsence,
402
430
  NVD_CACHE_DIR,
403
431
  NVD_CACHE_SCHEMA,
404
432
  NVD_CACHE_TTL_MS,
package/lib/osv-db.js CHANGED
@@ -1,23 +1,9 @@
1
1
  /**
2
- * lib/osv-db.js — offline-COMPLETE OSV matching from a locally imported OSV database
3
- * (the per-ecosystem `all.zip` exports OSV.dev publishes on its public GCS bucket).
4
- *
5
- * Why this exists alongside lib/osv.js: the latter queries the OSV.dev API *per
6
- * dependency* and caches each response (12 h TTL). Offline, that only covers the deps
7
- * that happened to be queried online before — a cold dep has NO OSV data. This module
8
- * imports the FULL OSV database once while online (Maven = 9 MB zip, ~6.6 k advisories)
9
- * and matches EVERY dep against it offline, deterministically, regardless of the per-dep
10
- * cache. That is exactly the model OSV-Scanner uses for air-gapped scans
11
- * (`--download-offline-databases`), and it makes fad's offline Maven recall complete and
12
- * cache-independent for an air-gapped engagement.
13
- *
14
- * Maven only for now: range matching needs the ecosystem's version ordering, and fad has
15
- * a robust Maven comparator (lib/maven-version). npm/PyPI/etc. are a documented follow-up
16
- * (they need semver/PEP-440 ordering). The OSV records are full OSV-schema vuln objects —
17
- * identical to the API — so lib/osv.js#vulnToMatch is reused verbatim.
18
- *
19
- * Online (download+index) + cached (~/.fad-checker/osv-db, 24 h) + offline-aware (loads a
20
- * present index, never blocks). The index travels in the cache archive automatically.
2
+ * Offline OSV matching from imported ecosystem snapshots. Unlike per-version API
3
+ * caches, these retain advisory ranges and can evaluate previously unseen versions.
4
+ * Unsupported range semantics remain indeterminate and are reported to callers.
5
+ * Maven's legacy index may also be downloaded explicitly; multi-ecosystem JSONL
6
+ * snapshots are streamed from a cache bundle and checked for corruption before use.
21
7
  */
22
8
  const fs = require("fs");
23
9
  const path = require("path");
@@ -28,10 +14,40 @@ const { vulnToMatch } = require("./osv");
28
14
 
29
15
  const OSV_DB_DIR = path.join(require("./cache-directory").getCacheDir(), "osv-db");
30
16
  const BUCKET = "https://osv-vulnerabilities.storage.googleapis.com";
31
- const TTL_MS = 24 * 3600 * 1000;
17
+ const TTL_MS = 4 * 3600 * 1000;
32
18
  // OSV ecosystem export name per fad codec id. Maven only for now (version ordering).
33
- const ECO = { maven: "Maven" };
19
+ const ECO = { maven: "Maven", npm: "npm", pypi: "PyPI", composer: "Packagist", nuget: "NuGet", go: "Go", ruby: "RubyGems" };
34
20
  const indexPath = eco => path.join(OSV_DB_DIR, `${eco}-index.json`);
21
+ const recordsPath = eco => path.join(OSV_DB_DIR, 'records', eco);
22
+
23
+ // OSV identities have ecosystem-specific casing rules. Go module paths and
24
+ // Ruby names must never be folded into another package's identity.
25
+ function packageKey(name, eco) {
26
+ const n = String(name || "");
27
+ if (eco === "PyPI") return n.toLowerCase().replace(/[-_.]+/g, "-");
28
+ return ["Maven", "npm", "NuGet", "Packagist"].includes(eco) ? n.toLowerCase() : n;
29
+ }
30
+
31
+ function newOsvIndex(ecosystemName, builtAt = Date.now()) {
32
+ return { _schema: 2, _builtAt: builtAt, ecosystem: ecosystemName, count: 0, packages: 0, byPackage: Object.create(null) };
33
+ }
34
+
35
+ function addOsvRecord(index, vuln) {
36
+ if (!vuln || typeof vuln.id !== 'string' || !vuln.id) throw new Error('invalid OSV advisory');
37
+ if (vuln.withdrawn) return;
38
+ const byPkg = new Map();
39
+ for (const a of (Array.isArray(vuln.affected) ? vuln.affected : [])) {
40
+ if (a.package?.ecosystem !== index.ecosystem || typeof a.package?.name !== 'string' || !a.package.name) continue;
41
+ const key = packageKey(a.package.name, index.ecosystem);
42
+ if (!byPkg.has(key)) byPkg.set(key, []);
43
+ byPkg.get(key).push(a);
44
+ }
45
+ for (const [key, affs] of byPkg) {
46
+ if (!Object.hasOwn(index.byPackage, key)) { index.byPackage[key] = []; index.packages++; }
47
+ index.byPackage[key].push(trimVuln(vuln, affs));
48
+ index.count++;
49
+ }
50
+ }
35
51
 
36
52
  /** Keep only what vulnToMatch + matching need, so the cached index stays compact. */
37
53
  function trimVuln(vuln, affForPkg) {
@@ -52,29 +68,13 @@ function trimVuln(vuln, affForPkg) {
52
68
  /** Build { byPackage: { "g:a"(lower): [trimmedVuln] }, … } from an all.zip buffer. */
53
69
  function buildIndexFromZip(buf, ecosystemName) {
54
70
  const files = unzipSync(new Uint8Array(buf));
55
- const dec = new TextDecoder();
56
- const byPackage = {};
57
- let count = 0;
71
+ const dec = new TextDecoder('utf-8', { fatal: true });
72
+ const index = newOsvIndex(ecosystemName);
58
73
  for (const name of Object.keys(files)) {
59
- let vuln;
60
- try { vuln = JSON.parse(dec.decode(files[name])); } catch { continue; }
61
- if (!vuln || vuln.withdrawn) continue;
62
- // A vuln can list several packages; index it under each (with that package's affected slice).
63
- const byPkg = new Map();
64
- for (const a of (vuln.affected || [])) {
65
- if (a.package?.ecosystem !== ecosystemName) continue;
66
- const nm = a.package?.name;
67
- if (!nm) continue;
68
- if (!byPkg.has(nm)) byPkg.set(nm, []);
69
- byPkg.get(nm).push(a);
70
- }
71
- for (const [nm, affs] of byPkg) {
72
- const key = nm.toLowerCase();
73
- (byPackage[key] = byPackage[key] || []).push(trimVuln(vuln, affs));
74
- count++;
75
- }
74
+ if (!name.endsWith('.json')) continue;
75
+ addOsvRecord(index, JSON.parse(dec.decode(files[name])));
76
76
  }
77
- return { _builtAt: Date.now(), ecosystem: ecosystemName, count, packages: Object.keys(byPackage).length, byPackage };
77
+ return index;
78
78
  }
79
79
 
80
80
  /**
@@ -86,21 +86,38 @@ async function ensureOsvDb(opts = {}) {
86
86
  const ecoName = ECO[ecosystem];
87
87
  if (!ecoName) return null;
88
88
  const ip = indexPath(ecosystem);
89
- const loadAny = () => { try { return JSON.parse(fs.readFileSync(ip, "utf8")); } catch { return null; } };
90
- const loadFresh = () => { const j = loadAny(); return j && (Date.now() - (j._builtAt || 0) < TTL_MS) ? j : null; };
89
+ const loadRecords = () => { try {
90
+ const dir = recordsPath(ecosystem), meta = JSON.parse(fs.readFileSync(path.join(dir, 'meta.json'), 'utf8'));
91
+ if (meta._schema !== 1 || meta.ecosystem !== ecoName || typeof meta.complete !== 'boolean' || !Number.isSafeInteger(meta._builtAt) || meta._builtAt <= 0 || meta._builtAt > Date.now() + 300000 ||
92
+ !Number.isSafeInteger(meta.recordCount) || meta.recordCount < 0 || !/^[a-f0-9]{64}$/.test(meta.sha256) || !fs.statSync(path.join(dir, 'records.jsonl')).isFile()) return null;
93
+ return {...meta, recordsFile:path.join(dir, 'records.jsonl')};
94
+ } catch { return null; } };
95
+ const loadAny = () => { try {
96
+ const index = JSON.parse(fs.readFileSync(ip, "utf8"));
97
+ return index && index.ecosystem === ecoName && index.byPackage && typeof index.byPackage === 'object' && !Array.isArray(index.byPackage) && Number.isFinite(index._builtAt) && index._builtAt > 0 && index._builtAt <= Date.now() + 300000 ? index : null;
98
+ } catch { return null; } };
99
+ const loadBest = () => { const a = loadRecords(), b = loadAny(); return a && (!b || a._builtAt >= b._builtAt) ? a : b; };
100
+ const loadFresh = () => { const j = loadBest(); return j && require('./cache-policy').fresh(j._builtAt || 0, TTL_MS) ? j : null; };
91
101
 
92
- if (offline) return loadAny();
102
+ if (offline) return loadBest();
93
103
  if (!refresh) { const f = loadFresh(); if (f) return f; }
94
104
  try {
105
+ // Large ZIP64 upstream exports need the server's streaming validator.
106
+ if (ecosystem !== 'maven') throw new Error(`direct OSV ${ecoName} import is not supported; import a verified seed`);
95
107
  const res = await require("./providers").getResource("osvdb", "ecosystem-archive", { ecosystem: ecoName },
96
108
  { fetcher, headers: { "User-Agent": "vigievuln-osv-db" } });
97
- if (!res || !res.ok) { if (verbose) console.warn(`osv-db: HTTP ${res?.status}`); return loadAny(); }
109
+ if (!res || !res.ok) { if (verbose) console.warn(`osv-db: HTTP ${res?.status}`); return loadBest(); }
98
110
  const buf = Buffer.from(await res.arrayBuffer());
111
+ // The in-process ZIP decoder does not support large ZIP64 archives. Never
112
+ // silently use a truncated database: prebuilt indexes come from the server.
99
113
  const index = buildIndexFromZip(buf, ecoName);
114
+ if (!index.count) throw new Error('empty OSV index');
100
115
  fs.mkdirSync(OSV_DB_DIR, { recursive: true });
101
- fs.writeFileSync(ip, JSON.stringify(index));
116
+ const tmp = `${ip}.${process.pid}.${require('crypto').randomBytes(6).toString('hex')}.tmp`;
117
+ try { fs.writeFileSync(tmp, JSON.stringify(index), { flag: 'wx' }); fs.renameSync(tmp, ip); }
118
+ finally { try { fs.unlinkSync(tmp); } catch {} }
102
119
  return index;
103
- } catch (e) { if (verbose) console.warn(`osv-db: ${e.message}`); return loadAny(); }
120
+ } catch (e) { if (verbose) console.warn(`osv-db: ${e.message}`); return loadBest(); }
104
121
  }
105
122
 
106
123
  // ---- OSV range evaluation over Maven version ordering ----
@@ -147,34 +164,211 @@ function vulnAffectsVersion(version, trimmedVuln) {
147
164
  return false;
148
165
  }
149
166
 
167
+ const SEMVER = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+([0-9A-Za-z.-]+))?$/;
168
+ // The Maven comparator uses JavaScript Numbers internally. Avoid precision loss.
169
+ function safeMavenCompare(a,b) {
170
+ if (/\d{16}/.test(String(a)) || /\d{16}/.test(String(b))) return null;
171
+ return compareMavenVersions(a,b);
172
+ }
173
+ function compareSemver(a, b) {
174
+ const x = SEMVER.exec(String(a)), y = SEMVER.exec(String(b));
175
+ const valid = m => m && m.slice(1, 4).every(n => n === '0' || !n.startsWith('0')) &&
176
+ (!m[4] || m[4].split('.').every(n => n && (!/^\d+$/.test(n) || n === '0' || !n.startsWith('0')))) &&
177
+ (!m[5] || m[5].split('.').every(Boolean));
178
+ if (!valid(x) || !valid(y)) return null;
179
+ for (let i = 1; i <= 3; i++) { const l = BigInt(x[i]), r = BigInt(y[i]); if (l !== r) return l < r ? -1 : 1; }
180
+ if (!x[4] || !y[4]) return x[4] === y[4] ? 0 : x[4] ? -1 : 1;
181
+ const p = x[4].split('.'), q = y[4].split('.');
182
+ for (let i = 0; i < Math.max(p.length, q.length); i++) {
183
+ if (p[i] === undefined) return -1;
184
+ if (q[i] === undefined) return 1;
185
+ const pn = /^\d+$/.test(p[i]), qn = /^\d+$/.test(q[i]);
186
+ if (pn && qn) { const l = BigInt(p[i]), r = BigInt(q[i]); if (l !== r) return l < r ? -1 : 1; }
187
+ else if (pn !== qn) return pn ? -1 : 1;
188
+ else if (p[i] !== q[i]) return p[i] < q[i] ? -1 : 1;
189
+ }
190
+ return 0;
191
+ }
192
+
193
+ // Three-valued evaluator: unsupported semantics and malformed versions are
194
+ // unknown, not clean. GIT ranges need a commit graph and are never guessed.
195
+ function rangeVerdict(version, range, ecosystem) {
196
+ if (!range || !['SEMVER', 'ECOSYSTEM'].includes(range.type) || !Array.isArray(range.events) || !range.events.length) return null;
197
+ let cmp;
198
+ if (range.type === 'SEMVER' || ['npm', 'Go'].includes(ecosystem)) cmp = compareSemver;
199
+ else if (ecosystem === 'Maven') cmp = safeMavenCompare;
200
+ else if (ecosystem === 'RubyGems') cmp = require('./ruby-version').compareRubyVersions;
201
+ else return null;
202
+ const v = String(version);
203
+ // Validate version itself even for an open range introduced at 0.
204
+ try { if (cmp(v, v) !== 0) return null; } catch { return null; }
205
+ const compare = (a, b) => a === '0' || b === '0' ? (a === b ? 0 : a === '0' ? -1 : 1) : cmp(a, b);
206
+ const events = [], limits = [];
207
+ for (const item of range.events) {
208
+ if (!item || typeof item !== 'object' || Array.isArray(item) || Object.keys(item).length !== 1) return null;
209
+ const [kind, at] = Object.entries(item)[0];
210
+ if (!['introduced', 'fixed', 'last_affected', 'limit'].includes(kind) || typeof at !== 'string' || !at) return null;
211
+ if (kind === 'limit') limits.push(at); else events.push({ kind, at });
212
+ }
213
+ if (!events.some(e => e.kind === 'introduced')) return null;
214
+ try {
215
+ for (const e of events) if (compare(v, e.at) == null) return null;
216
+ for (const l of limits) if (l !== '*' && compare(v, l) == null) return null;
217
+ if (limits.length && !limits.some(l => l === '*' || compare(v, l) < 0)) return false;
218
+ events.sort((a, b) => compare(a.at, b.at) || (EVENT_RANK[a.kind] - EVENT_RANK[b.kind]));
219
+ let affected = false;
220
+ for (const e of events) {
221
+ const c = compare(v, e.at);
222
+ if (e.kind === 'introduced' && c >= 0) affected = true;
223
+ else if (e.kind === 'fixed' && c >= 0) affected = false;
224
+ else if (e.kind === 'last_affected' && c > 0) affected = false;
225
+ }
226
+ return affected;
227
+ } catch { return null; }
228
+ }
229
+
230
+ function vulnVerdict(version, vuln, ecosystem, opts = {}) {
231
+ let unknown = false;
232
+ for (const a of (vuln.affected || [])) {
233
+ const versions = Array.isArray(a.versions) ? a.versions : [];
234
+ // Our reviewed evidence can establish individual positive and negative
235
+ // releases without establishing the complete affected history. Interpret
236
+ // this extension only when the caller identifies our own advisory store;
237
+ // external OSV documents cannot change OSV's version-list semantics.
238
+ const partial = opts.source === 'vigievuln' && a.database_specific?.vigievuln_partial_versions === true;
239
+ if (partial) {
240
+ const tested = vulnVerdict(version, {affected:[{versions, ranges:a.ranges || []}]}, ecosystem);
241
+ const knownSafe = Array.isArray(a.database_specific.unaffected_versions)
242
+ ? vulnVerdict(version, {affected:[{versions:a.database_specific.unaffected_versions}]}, ecosystem)
243
+ : false;
244
+ if (tested === true && knownSafe === true) { unknown = true; continue; }
245
+ if (tested === true) return true;
246
+ if (knownSafe !== true || tested === null) unknown = true;
247
+ continue;
248
+ }
249
+ if (versions.includes(String(version))) return true;
250
+ // Composer removes the VCS tag's optional v prefix. Match only identical
251
+ // numeric release spellings here; this does not infer range ordering, pad
252
+ // components, or interpret development branches and prerelease suffixes.
253
+ // https://getcomposer.org/doc/articles/versions.md#tags
254
+ if (ecosystem === 'Packagist' && /^[vV]?\d{1,5}(?:\.\d+){0,3}$/.test(String(version)) &&
255
+ versions.some(candidate => typeof candidate === 'string' && /^[vV]?\d{1,5}(?:\.\d+){0,3}$/.test(candidate) &&
256
+ candidate.replace(/^[vV]/, '') === String(version).replace(/^[vV]/, ''))) return true;
257
+ for (const candidate of versions) {
258
+ let comparison = null;
259
+ try {
260
+ if (ecosystem === 'Maven') comparison = safeMavenCompare(String(version), String(candidate));
261
+ else if (['npm', 'Go'].includes(ecosystem)) comparison = compareSemver(version, candidate);
262
+ else if (ecosystem === 'RubyGems') comparison = require('./ruby-version').compareRubyVersions(version, candidate);
263
+ } catch { /* unknown */ }
264
+ if (comparison === 0) return true;
265
+ if (comparison == null) unknown = true;
266
+ }
267
+ for (const r of (Array.isArray(a.ranges) ? a.ranges : [])) {
268
+ const verdict = rangeVerdict(version, r, ecosystem);
269
+ if (verdict === true) return true;
270
+ if (verdict === null) unknown = true;
271
+ }
272
+ // Version spellings outside understood ecosystems can be equivalent even
273
+ // when the literal strings differ (e.g. PEP 440 1.0 and 1.0.0).
274
+ if (!(a.ranges || []).length && versions.length && !['Maven', 'npm', 'Go', 'RubyGems'].includes(ecosystem)) unknown = true;
275
+ if (!(a.ranges || []).length && !versions.length) unknown = true;
276
+ }
277
+ return unknown ? null : false;
278
+ }
279
+
150
280
  /**
151
281
  * Match resolved Maven deps against a local OSV DB index. Returns vulnToMatch-shaped
152
282
  * matches (source 'osv'), one per (coord, version, vuln). Scans every distinct version.
153
283
  */
154
- function matchOsvDbDeps(resolvedDeps, index) {
284
+ function matchOsvDbDeps(resolvedDeps, index, { onUnknown } = {}) {
155
285
  if (!index || !index.byPackage) return [];
156
286
  const out = [];
157
287
  const seen = new Set();
288
+ const ecoName = index.ecosystem || 'Maven'; // legacy Maven index has no schema
289
+ const { osvEcosystemFor, osvPkgName } = require('./osv');
158
290
  for (const dep of resolvedDeps.values()) {
159
- if (dep.ecosystem !== "maven") continue;
160
- if (dep.provenance === "embedded" || dep.provenance === "binary") continue;
161
- const recs = index.byPackage[`${dep.groupId}:${dep.artifactId}`.toLowerCase()];
291
+ if (!Object.hasOwn(ECO, dep.ecosystem === 'yarn' ? 'npm' : dep.ecosystem) || osvEcosystemFor(dep) !== ecoName) continue;
292
+ if (dep.provenance === "binary") continue;
293
+ const name = osvPkgName(dep), pkgKey = packageKey(name, ecoName);
294
+ const recs = Object.hasOwn(index.byPackage, pkgKey) ? index.byPackage[pkgKey] : null;
162
295
  if (!recs || !recs.length) continue;
163
296
  const versions = (dep.versions && dep.versions.length) ? dep.versions : [dep.version];
164
297
  for (const ver of versions) {
165
298
  if (!ver || /\$\{/.test(String(ver))) continue;
166
299
  for (const rec of recs) {
167
- if (!vulnAffectsVersion(ver, rec)) continue;
168
- const key = `${dep.groupId}:${dep.artifactId}:${ver}|${rec.id}`;
300
+ // The legacy lookup key folds case. Confirm the original Maven
301
+ // coordinate before using its affected versions or ranges.
302
+ const affected = ecoName === 'Maven' ? (rec.affected || []).filter(a => a?.package?.ecosystem === 'Maven' && a.package.name === name) : rec.affected;
303
+ if (ecoName === 'Maven' && !affected.length) {
304
+ if ((rec.affected || []).some(a => !a?.package?.name)) onUnknown?.({ecosystem:ecoName,name,version:ver,advisory:rec.id});
305
+ continue;
306
+ }
307
+ const verdict = vulnVerdict(ver, { ...rec, affected }, ecoName);
308
+ if (verdict === null) { if (onUnknown) onUnknown({ecosystem:ecoName, name, version:ver, advisory:rec.id}); continue; }
309
+ if (!verdict) continue;
310
+ const key = `${dep.coordKey || pkgKey}:${ver}|${rec.id}`;
169
311
  if (seen.has(key)) continue;
170
312
  seen.add(key);
171
- out.push(vulnToMatch(ver === dep.version ? dep : { ...dep, version: ver }, rec));
313
+ const match = vulnToMatch(ver === dep.version ? dep : { ...dep, version: ver }, rec);
314
+ out.push(match);
172
315
  }
173
316
  }
174
317
  }
175
318
  return out;
176
319
  }
177
320
 
321
+ /** Stream seed records; do not publish partial matches if integrity fails. */
322
+ async function matchOsvDbRecords(resolvedDeps, index, { onUnknown } = {}) {
323
+ if (!index?.recordsFile || !ECO || !Object.values(ECO).includes(index.ecosystem)) throw new Error('invalid OSV seed');
324
+ const { osvEcosystemFor, osvPkgName } = require('./osv');
325
+ const targets = new Map();
326
+ for (const dep of resolvedDeps.values()) {
327
+ if (!dep || !Object.hasOwn(ECO, dep.ecosystem === 'yarn' ? 'npm' : dep.ecosystem) || osvEcosystemFor(dep) !== index.ecosystem || dep.provenance === 'binary') continue;
328
+ const name = osvPkgName(dep); if (!name) continue;
329
+ const key = packageKey(name, index.ecosystem);
330
+ if (!targets.has(key)) targets.set(key, []);
331
+ targets.get(key).push(dep);
332
+ }
333
+ const stream = fs.createReadStream(index.recordsFile), hash = require('crypto').createHash('sha256');
334
+ stream.on('data', chunk => hash.update(chunk));
335
+ const lines = require('./line-stream').readTextLines(stream);
336
+ const out = [], seen = new Set(), unknown = [], unknownKeys = new Set(); let count = 0;
337
+ try {
338
+ for await (const line of lines) {
339
+ if (!line) throw new Error('empty OSV seed record');
340
+ const vuln = JSON.parse(line); count++;
341
+ if (!vuln || typeof vuln.id !== 'string' || !Array.isArray(vuln.affected)) throw new Error('invalid OSV seed record');
342
+ if (vuln.withdrawn) continue;
343
+ const relevant = new Map();
344
+ for (const a of vuln.affected) {
345
+ if (a?.package?.ecosystem !== index.ecosystem || typeof a.package.name !== 'string') continue;
346
+ const key = packageKey(a.package.name, index.ecosystem);
347
+ if (!targets.has(key)) continue;
348
+ if (!relevant.has(key)) relevant.set(key, []);
349
+ relevant.get(key).push(a);
350
+ }
351
+ for (const [key, affected] of relevant) for (const dep of targets.get(key)) {
352
+ const exactAffected = index.ecosystem === 'Maven' ? affected.filter(a => a.package.name === osvPkgName(dep)) : affected;
353
+ if (!exactAffected.length) continue;
354
+ const record = { ...vuln, affected: exactAffected };
355
+ for (const ver of (dep.versions?.length ? dep.versions : [dep.version])) {
356
+ if (!ver || /\$\{/.test(String(ver))) continue;
357
+ const id = `${dep.coordKey || key}:${ver}|${vuln.id}`;
358
+ const verdict = vulnVerdict(ver, record, index.ecosystem);
359
+ if (verdict === null && !unknownKeys.has(id)) { unknownKeys.add(id); unknown.push({ecosystem:index.ecosystem,name:osvPkgName(dep),version:ver,advisory:vuln.id}); }
360
+ if (verdict !== true || seen.has(id)) continue;
361
+ seen.add(id); const match = vulnToMatch(ver === dep.version ? dep : {...dep,version:ver}, record);
362
+ out.push(match);
363
+ }
364
+ }
365
+ }
366
+ } finally { stream.destroy(); }
367
+ if (count !== index.recordCount || hash.digest('hex') !== index.sha256) throw new Error('OSV seed checksum or count mismatch');
368
+ if (onUnknown) for (const item of unknown) onUnknown(item);
369
+ return out;
370
+ }
371
+
178
372
  /**
179
373
  * Decide whether this run uses the local OSV database.
180
374
  *
@@ -198,13 +392,13 @@ function autoEnableOsvDb(options = {}, eco = {}) {
198
392
  if (options.osvDb === false) return false; // --no-osv-db
199
393
  if (options.vigievulnProxy && !options.offline) return false; // do not silently merge an old local snapshot
200
394
  if (options.osv === false) return false; // --no-osv means no OSV data at all
201
- if (!(eco.runMaven || eco.runGradle)) return false;
202
- return !!eco.hasIndex; // present = free to use; absent = do not download behind their back
395
+ if (!(eco.runMaven || eco.runGradle || eco.hasOtherIndex)) return false;
396
+ return !!(eco.hasIndex || eco.hasOtherIndex); // do not download behind their back
203
397
  }
204
398
 
205
399
  /** Cheap "is the index already on disk" probe, so the decision above stays pure. */
206
400
  function hasOsvDbIndex(ecosystem = "maven") {
207
- try { return fs.existsSync(indexPath(ecosystem)); } catch { return false; }
401
+ try { return fs.existsSync(indexPath(ecosystem)) || (fs.existsSync(path.join(recordsPath(ecosystem), 'meta.json')) && fs.existsSync(path.join(recordsPath(ecosystem), 'records.jsonl'))); } catch { return false; }
208
402
  }
209
403
 
210
- module.exports = { ensureOsvDb, buildIndexFromZip, matchOsvDbDeps, rangeAffects, vulnAffectsVersion, autoEnableOsvDb, hasOsvDbIndex, OSV_DB_DIR };
404
+ module.exports = { ensureOsvDb, buildIndexFromZip, newOsvIndex, addOsvRecord, packageKey, ECO, matchOsvDbDeps, matchOsvDbRecords, rangeAffects, rangeVerdict, vulnVerdict, compareSemver, vulnAffectsVersion, autoEnableOsvDb, hasOsvDbIndex, OSV_DB_DIR };
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ // Published 1.1.x cached full advisory details independently from lossy tuple
3
+ // filenames. Only those native documents are reusable; filenames never prove
4
+ // that a package/version was checked, and negative query lists are not migrated.
5
+ const fs = require('node:fs');
6
+ const path = require('node:path');
7
+ const crypto = require('node:crypto');
8
+ const { validateRecord } = require('./advisory-store');
9
+
10
+ function importLegacyOsvDetails(store, { cacheDir, legacyDir = path.join(cacheDir, 'osv-cache'), force = false } = {}) {
11
+ const marker = path.join(store.directory, 'legacy-details-import.json');
12
+ let directoryMtime;
13
+ try { directoryMtime = fs.statSync(legacyDir).mtimeMs; }
14
+ catch (error) { if (error.code === 'ENOENT') return { imported: 0, skipped: 0 }; throw error; }
15
+ try {
16
+ const previous = JSON.parse(fs.readFileSync(marker, 'utf8'));
17
+ if (!force && previous.schema === 1 && previous.directory === path.resolve(legacyDir) && previous.directoryMtime === directoryMtime) return { ...previous, previouslyImported: true };
18
+ } catch {}
19
+ let entries;
20
+ try { entries = fs.readdirSync(legacyDir, { withFileTypes: true }); }
21
+ catch (error) { if (error.code === 'ENOENT') return { imported: 0, skipped: 0 }; throw error; }
22
+ fs.mkdirSync(store.directory, { recursive: true });
23
+ const temporary = path.join(store.directory, `.legacy-${process.pid}-${crypto.randomBytes(8).toString('hex')}.jsonl`);
24
+ const fd = fs.openSync(temporary, 'wx', 0o600); let imported = 0, skipped = 0, batch = [];
25
+ const flush = () => {
26
+ if (!batch.length) return;
27
+ fs.writeFileSync(fd, JSON.stringify({ schema: 1, records: batch, queries: [], coverages: [] }) + '\n'); batch = [];
28
+ };
29
+ try {
30
+ try {
31
+ for (const entry of entries) {
32
+ if (!/^vuln_.+\.json$/.test(entry.name)) continue;
33
+ if (!entry.isFile()) { skipped++; continue; }
34
+ let record;
35
+ try {
36
+ const file = path.join(legacyDir, entry.name), stat = fs.lstatSync(file);
37
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 16 * 1024 * 1024) throw new Error('invalid legacy advisory file');
38
+ const cached = JSON.parse(fs.readFileSync(file, 'utf8')), document = cached.body;
39
+ record = { source: 'osv', document, fetchedAt: cached._fetchedAt, provenance: { transport: 'legacy-cache', format: '1.1.x-detail' } };
40
+ validateRecord(record);
41
+ if (!document.withdrawn && !document.affected?.some(affected => affected.package?.ecosystem && affected.package?.name)) throw new Error('legacy advisory has no package identity');
42
+ } catch { skipped++; continue; }
43
+ // A large but valid document gets its own bounded transaction.
44
+ if (Buffer.byteLength(JSON.stringify(record)) > 512 * 1024) { flush(); batch.push(record); flush(); }
45
+ else { batch.push(record); if (batch.length >= 25) flush(); }
46
+ imported++;
47
+ }
48
+ flush();
49
+ } finally { fs.closeSync(fd); }
50
+ if (imported) store.mergeJournal(temporary);
51
+ const result = { schema: 1, directory: path.resolve(legacyDir), directoryMtime, imported, skipped, importedAt: Date.now() };
52
+ fs.writeFileSync(marker, JSON.stringify(result), { mode: 0o600 });
53
+ return result;
54
+ } finally { fs.rmSync(temporary, { force: true }); }
55
+ }
56
+
57
+ module.exports = { importLegacyOsvDetails };